body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
d7e1ac9340803b625c3617750588889c09883bfc53b20ad7e94dc1220579a4bd
def manage_stocks(request): 'Представление: управление складами.' from catalog.models import Stock if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')): stocks = Stock.objects.all().order_by('alias') return render(request, 'catalog/manage_stocks.html', locals())
Представление: управление складами.
views.py
manage_stocks
anodos-ru/catalog
2
python
def manage_stocks(request): from catalog.models import Stock if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')): stocks = Stock.objects.all().order_by('alias') return render(request, 'catalog/manage_stocks.html', locals())
def manage_stocks(request): from catalog.models import Stock if (request.user.has_perm('catalog.add_stock') or request.user.has_perm('catalog.change_stock') or request.user.has_perm('catalog.delete_stock')): stocks = Stock.objects.all().order_by('alias') return render(request, 'catalog/manage_stocks.html', locals())<|docstring|>Представление: управление складами.<|endoftext|>
1147f6fe5b40b296c3e821efffa46228cb3d8b60ae98f22680cf02ae94b76fcd
def manage_vendors(request): 'Представление: список производителей.' from catalog.models import Vendor vendors = Vendor.objects.all().order_by('name') return render(request, 'catalog/manage_vendors.html', locals())
Представление: список производителей.
views.py
manage_vendors
anodos-ru/catalog
2
python
def manage_vendors(request): from catalog.models import Vendor vendors = Vendor.objects.all().order_by('name') return render(request, 'catalog/manage_vendors.html', locals())
def manage_vendors(request): from catalog.models import Vendor vendors = Vendor.objects.all().order_by('name') return render(request, 'catalog/manage_vendors.html', locals())<|docstring|>Представление: список производителей.<|endoftext|>
649fbaffb74221ef1a8d7711f9b046224ef2d00d6bb23b0d890ed16e01220757
def manage_categories(request): 'Представление: управление категорями.' from catalog.models import Category categories = [] categories = Category.objects.get_category_tree(categories) for category in categories: category.name = (('— ' * category.level) + category.name) return render(request, 'catalog/manage_categories.html', locals())
Представление: управление категорями.
views.py
manage_categories
anodos-ru/catalog
2
python
def manage_categories(request): from catalog.models import Category categories = [] categories = Category.objects.get_category_tree(categories) for category in categories: category.name = (('— ' * category.level) + category.name) return render(request, 'catalog/manage_categories.html', locals())
def manage_categories(request): from catalog.models import Category categories = [] categories = Category.objects.get_category_tree(categories) for category in categories: category.name = (('— ' * category.level) + category.name) return render(request, 'catalog/manage_categories.html', locals())<|docstring|>Представление: управление категорями.<|endoftext|>
f8994b03af6c35b9f24c293c3e8896a9a727f6e3273671f75159c85519b9c793
def manage_products(request, **kwargs): 'Представление: управление продуктами' from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/manage/products/' for parameter in kwargs.get('string', '').split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = '' if name: parameters_[name] = values if (name != 'page'): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) parameters['category'] = fix_parameter_category(parameters_.get('category', '')) categories = Category.objects.get_category_tree([], state=True) parameters['vendor'] = fix_parameter_vendor(parameters_.get('vendor', '')) vendors = Vendor.objects.filter(state=True, double=None) parameters['search'] = fix_parameter_search(parameters_.get('search', '')) filters_ = {'double': Q(double=None), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['category'] or parameters['vendor'] or parameters['search']): if parameters['category']: filters['category'] = Q(category=parameters['category']) if parameters['vendor']: filters['vendor'] = Q(vendor=parameters['vendor']) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) return render(request, 'catalog/manage_products.html', locals())
Представление: управление продуктами
views.py
manage_products
anodos-ru/catalog
2
python
def manage_products(request, **kwargs): from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/manage/products/' for parameter in kwargs.get('string', ).split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = if name: parameters_[name] = values if (name != 'page'): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) parameters['category'] = fix_parameter_category(parameters_.get('category', )) categories = Category.objects.get_category_tree([], state=True) parameters['vendor'] = fix_parameter_vendor(parameters_.get('vendor', )) vendors = Vendor.objects.filter(state=True, double=None) parameters['search'] = fix_parameter_search(parameters_.get('search', )) filters_ = {'double': Q(double=None), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['category'] or parameters['vendor'] or parameters['search']): if parameters['category']: filters['category'] = Q(category=parameters['category']) if parameters['vendor']: filters['vendor'] = Q(vendor=parameters['vendor']) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) return render(request, 'catalog/manage_products.html', locals())
def manage_products(request, **kwargs): from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/manage/products/' for parameter in kwargs.get('string', ).split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = if name: parameters_[name] = values if (name != 'page'): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) parameters['category'] = fix_parameter_category(parameters_.get('category', )) categories = Category.objects.get_category_tree([], state=True) parameters['vendor'] = fix_parameter_vendor(parameters_.get('vendor', )) vendors = Vendor.objects.filter(state=True, double=None) parameters['search'] = fix_parameter_search(parameters_.get('search', )) filters_ = {'double': Q(double=None), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['category'] or parameters['vendor'] or parameters['search']): if parameters['category']: filters['category'] = Q(category=parameters['category']) if parameters['vendor']: filters['vendor'] = Q(vendor=parameters['vendor']) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) return render(request, 'catalog/manage_products.html', locals())<|docstring|>Представление: управление продуктами<|endoftext|>
5b62ee829c412a77da69e613f58b33a969cef3d90374d01188499b5657917ffd
def units(request): 'Представление: список единиц измерения.' from catalog.models import Unit units = Unit.objects.all() return render(request, 'catalog/units.html', locals())
Представление: список единиц измерения.
views.py
units
anodos-ru/catalog
2
python
def units(request): from catalog.models import Unit units = Unit.objects.all() return render(request, 'catalog/units.html', locals())
def units(request): from catalog.models import Unit units = Unit.objects.all() return render(request, 'catalog/units.html', locals())<|docstring|>Представление: список единиц измерения.<|endoftext|>
0ee32a6ed3ea658a22909ea37883172d9974e29445a9d68570faa8a2529ad025
def pricetypes(request): 'Представление: список типов цен.' from catalog.models import PriceType if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')): pricetypes = PriceType.objects.all().order_by('name') return render(request, 'catalog/pricetypes.html', locals())
Представление: список типов цен.
views.py
pricetypes
anodos-ru/catalog
2
python
def pricetypes(request): from catalog.models import PriceType if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')): pricetypes = PriceType.objects.all().order_by('name') return render(request, 'catalog/pricetypes.html', locals())
def pricetypes(request): from catalog.models import PriceType if (request.user.has_perm('catalog.add_pricetype') or request.user.has_perm('catalog.change_pricetype') or request.user.has_perm('catalog.delete_pricetype')): pricetypes = PriceType.objects.all().order_by('name') return render(request, 'catalog/pricetypes.html', locals())<|docstring|>Представление: список типов цен.<|endoftext|>
ab07b2eea2d2630a47bd9ee431d00040ad203d79437bf8a9d28583b774d84edf
def currencies(request): 'Представление: список валют.' from catalog.models import Currency currencies = Currency.objects.all() return render(request, 'catalog/currencies.html', locals())
Представление: список валют.
views.py
currencies
anodos-ru/catalog
2
python
def currencies(request): from catalog.models import Currency currencies = Currency.objects.all() return render(request, 'catalog/currencies.html', locals())
def currencies(request): from catalog.models import Currency currencies = Currency.objects.all() return render(request, 'catalog/currencies.html', locals())<|docstring|>Представление: список валют.<|endoftext|>
fd3d8f4be0dd3bcef0ab62e52152b43710aecec6c13d55a3837b9d64e4bc8bc1
def products(request, **kwargs): 'Представление: список продуктов.' import unidecode from lxml import etree from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/products/' for parameter in kwargs.get('string', '').split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = '' if name: parameters_[name] = values if ((name != 'page') and name): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) categories = Category.objects.get_category_tree([], state=True) root = etree.Element('div') Category.objects.get_category_tree_html(root, parent=None, first=True, state=True) categories_tree = etree.tostring(root) parameters_['categories'] = parameters_.get('categories', '').split(',') parameters['categories'] = [] for category in categories: for id_ in parameters_['categories']: if (id_ == None): parameters['categories'].append(None) else: try: if (category.id == int(id_)): parameters['categories'].append(category) except Exception: pass vendors = Vendor.objects.filter(state=True) parameters_['vendors'] = parameters_.get('vendors', '').split(',') parameters['vendors'] = [] for vendor in vendors: for alias_ in parameters_['vendors']: if (vendor.alias == str(alias_)): parameters['vendors'].append(vendor) parameters_['search'] = str(parameters_.get('search', '')) if parameters_['search']: translation_map = {ord('&'): 'and', ord("'"): '', ord('('): ' ', ord(')'): ' ', ord('['): ' ', ord(']'): ' ', ord('.'): ' ', ord(','): ' ', ord('+'): ' ', ord('/'): ' '} parameters_['search'] = parameters_['search'].translate(translation_map) parameters_['search'] = parameters_['search'].strip().lower() parameters['search'] = [] for word in parameters_['search'].split(' '): if word: parameters['search'].append(word) parameters_['search'] = str(parameters_.get('search', '')) filters_ = {'state': Q(state=True), 'double': Q(double=None), 'vendor_state': Q(vendor__state=True), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['categories'] or parameters['vendors'] or parameters['search']): if parameters['categories']: filters['categories'] = Q() for category in parameters['categories']: filters['categories'] = (filters['categories'] | Q(category=category)) if parameters['vendors']: filters['vendors'] = Q() for vendor in parameters['vendors']: filters['vendors'] = (filters['vendors'] | Q(vendor=vendor)) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) if len(filters): products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) if (not count): from anodos.models import Log if request.user.id: user_name = '{} {}'.format(request.user.first_name, request.user.last_name) else: user_name = 'AnonymousUser' Log.objects.add(subject='catalog.views.products', channel='info', title='Not found', description='{}: {}'.format(user_name, parameters_['search'])) else: products = [] return render(request, 'catalog/products.html', locals())
Представление: список продуктов.
views.py
products
anodos-ru/catalog
2
python
def products(request, **kwargs): import unidecode from lxml import etree from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/products/' for parameter in kwargs.get('string', ).split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = if name: parameters_[name] = values if ((name != 'page') and name): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) categories = Category.objects.get_category_tree([], state=True) root = etree.Element('div') Category.objects.get_category_tree_html(root, parent=None, first=True, state=True) categories_tree = etree.tostring(root) parameters_['categories'] = parameters_.get('categories', ).split(',') parameters['categories'] = [] for category in categories: for id_ in parameters_['categories']: if (id_ == None): parameters['categories'].append(None) else: try: if (category.id == int(id_)): parameters['categories'].append(category) except Exception: pass vendors = Vendor.objects.filter(state=True) parameters_['vendors'] = parameters_.get('vendors', ).split(',') parameters['vendors'] = [] for vendor in vendors: for alias_ in parameters_['vendors']: if (vendor.alias == str(alias_)): parameters['vendors'].append(vendor) parameters_['search'] = str(parameters_.get('search', )) if parameters_['search']: translation_map = {ord('&'): 'and', ord("'"): , ord('('): ' ', ord(')'): ' ', ord('['): ' ', ord(']'): ' ', ord('.'): ' ', ord(','): ' ', ord('+'): ' ', ord('/'): ' '} parameters_['search'] = parameters_['search'].translate(translation_map) parameters_['search'] = parameters_['search'].strip().lower() parameters['search'] = [] for word in parameters_['search'].split(' '): if word: parameters['search'].append(word) parameters_['search'] = str(parameters_.get('search', )) filters_ = {'state': Q(state=True), 'double': Q(double=None), 'vendor_state': Q(vendor__state=True), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['categories'] or parameters['vendors'] or parameters['search']): if parameters['categories']: filters['categories'] = Q() for category in parameters['categories']: filters['categories'] = (filters['categories'] | Q(category=category)) if parameters['vendors']: filters['vendors'] = Q() for vendor in parameters['vendors']: filters['vendors'] = (filters['vendors'] | Q(vendor=vendor)) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) if len(filters): products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) if (not count): from anodos.models import Log if request.user.id: user_name = '{} {}'.format(request.user.first_name, request.user.last_name) else: user_name = 'AnonymousUser' Log.objects.add(subject='catalog.views.products', channel='info', title='Not found', description='{}: {}'.format(user_name, parameters_['search'])) else: products = [] return render(request, 'catalog/products.html', locals())
def products(request, **kwargs): import unidecode from lxml import etree from django.db.models import Q from catalog.models import Product, Category, Vendor parameters_ = {} url = '/catalog/products/' for parameter in kwargs.get('string', ).split('/'): name = parameter.split('=')[0] try: values = parameter.split('=')[1] except IndexError: values = if name: parameters_[name] = values if ((name != 'page') and name): url = '{}{}/'.format(url, parameter) parameters = {} try: parameters['items'] = int(parameters_.get('items')) except Exception: parameters['items'] = 100 if (parameters['items'] < 1): parameters['items'] = 100 parameters['page'] = fix_parameter_page(parameters_.get('page')) categories = Category.objects.get_category_tree([], state=True) root = etree.Element('div') Category.objects.get_category_tree_html(root, parent=None, first=True, state=True) categories_tree = etree.tostring(root) parameters_['categories'] = parameters_.get('categories', ).split(',') parameters['categories'] = [] for category in categories: for id_ in parameters_['categories']: if (id_ == None): parameters['categories'].append(None) else: try: if (category.id == int(id_)): parameters['categories'].append(category) except Exception: pass vendors = Vendor.objects.filter(state=True) parameters_['vendors'] = parameters_.get('vendors', ).split(',') parameters['vendors'] = [] for vendor in vendors: for alias_ in parameters_['vendors']: if (vendor.alias == str(alias_)): parameters['vendors'].append(vendor) parameters_['search'] = str(parameters_.get('search', )) if parameters_['search']: translation_map = {ord('&'): 'and', ord("'"): , ord('('): ' ', ord(')'): ' ', ord('['): ' ', ord(']'): ' ', ord('.'): ' ', ord(','): ' ', ord('+'): ' ', ord('/'): ' '} parameters_['search'] = parameters_['search'].translate(translation_map) parameters_['search'] = parameters_['search'].strip().lower() parameters['search'] = [] for word in parameters_['search'].split(' '): if word: parameters['search'].append(word) parameters_['search'] = str(parameters_.get('search', )) filters_ = {'state': Q(state=True), 'double': Q(double=None), 'vendor_state': Q(vendor__state=True), 'vendor_double': Q(vendor__double=None)} filters = {} if (parameters['categories'] or parameters['vendors'] or parameters['search']): if parameters['categories']: filters['categories'] = Q() for category in parameters['categories']: filters['categories'] = (filters['categories'] | Q(category=category)) if parameters['vendors']: filters['vendors'] = Q() for vendor in parameters['vendors']: filters['vendors'] = (filters['vendors'] | Q(vendor=vendor)) if parameters['search']: translation_map = {ord('o'): '0', ord('е'): 'e', ord('т'): 't', ord('у'): 'y', ord('о'): 'o', ord('р'): 'p', ord('а'): 'a', ord('н'): 'h', ord('к'): 'k', ord('l'): 'i', ord('х'): 'x', ord('c'): 'c', ord('в'): 'b', ord('м'): 'm'} filters['search'] = Q() for search in parameters['search']: search_ = search.translate(translation_map) filters['search'] = (filters['search'] & (Q(alias__icontains=search) | Q(alias__icontains=search_))) if len(filters): products = Product.objects.all() for key in filters_: products = products.filter(filters_[key]) for key in filters: products = products.filter(filters[key]) count = products.count() page_max = (count // parameters['items']) if (count % parameters['items']): page_max += 1 if (page_max > 1): pages = [] dispersion = 3 prev = False for n in range(1, (page_max + 1)): if ((((parameters['page'] - n) < dispersion) and ((n - parameters['page']) < dispersion)) or (((page_max - n) < dispersion) and ((n - page_max) < dispersion)) or (((1 - n) < dispersion) and ((n - 1) < dispersion))): pages.append(n) prev = True elif prev: pages.append(0) prev = False first = ((parameters['page'] - 1) * parameters['items']) last = (parameters['page'] * parameters['items']) if (parameters['page'] > 1): page_prev = (parameters['page'] - 1) if (parameters['page'] < page_max): page_next = (parameters['page'] + 1) products = products[first:last] else: first = 0 last = count for n in range(len(products)): products[n].n = ((n + first) + 1) if (not count): from anodos.models import Log if request.user.id: user_name = '{} {}'.format(request.user.first_name, request.user.last_name) else: user_name = 'AnonymousUser' Log.objects.add(subject='catalog.views.products', channel='info', title='Not found', description='{}: {}'.format(user_name, parameters_['search'])) else: products = [] return render(request, 'catalog/products.html', locals())<|docstring|>Представление: список продуктов.<|endoftext|>
4b62c40b8e0f5d6ad42b95433c138899788c66b93850502daf1a7893d1762c42
def product(request, id=None, vendor=None, article=None): 'Представление: продукт.' from catalog.models import Vendor, Product, ProductPhoto if id: product = Product.objects.get(id=id) elif (vendor and article): vendor = Vendor.objects.get(alias=vendor) product = Product.objects.get(vendor=vendor, article=article) photos = ProductPhoto.objects.filter(product=product) return render(request, 'catalog/product.html', locals())
Представление: продукт.
views.py
product
anodos-ru/catalog
2
python
def product(request, id=None, vendor=None, article=None): from catalog.models import Vendor, Product, ProductPhoto if id: product = Product.objects.get(id=id) elif (vendor and article): vendor = Vendor.objects.get(alias=vendor) product = Product.objects.get(vendor=vendor, article=article) photos = ProductPhoto.objects.filter(product=product) return render(request, 'catalog/product.html', locals())
def product(request, id=None, vendor=None, article=None): from catalog.models import Vendor, Product, ProductPhoto if id: product = Product.objects.get(id=id) elif (vendor and article): vendor = Vendor.objects.get(alias=vendor) product = Product.objects.get(vendor=vendor, article=article) photos = ProductPhoto.objects.filter(product=product) return render(request, 'catalog/product.html', locals())<|docstring|>Представление: продукт.<|endoftext|>
f6124b0b69498f30eab05d9304b54d9d462cb4d50f4bb8a15ac6cef53a033c79
def ajax_get(request, *args, **kwargs): 'AJAX-представление: Get Object.' import json import catalog.models model_name = kwargs.get('model_name', '') model = catalog.models.models[model_name] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) open_models = ['product', 'vendor', 'category'] if (not (model_name in open_models)): if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) try: m = model.objects.get(id=request.POST.get('id')) result = {'status': 'success', kwargs['model_name']: m.get_dicted()} except model.DoesNotExist: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Get Object.
views.py
ajax_get
anodos-ru/catalog
2
python
def ajax_get(request, *args, **kwargs): import json import catalog.models model_name = kwargs.get('model_name', ) model = catalog.models.models[model_name] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) open_models = ['product', 'vendor', 'category'] if (not (model_name in open_models)): if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) try: m = model.objects.get(id=request.POST.get('id')) result = {'status': 'success', kwargs['model_name']: m.get_dicted()} except model.DoesNotExist: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_get(request, *args, **kwargs): import json import catalog.models model_name = kwargs.get('model_name', ) model = catalog.models.models[model_name] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) open_models = ['product', 'vendor', 'category'] if (not (model_name in open_models)): if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) try: m = model.objects.get(id=request.POST.get('id')) result = {'status': 'success', kwargs['model_name']: m.get_dicted()} except model.DoesNotExist: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Get Object.<|endoftext|>
8b87ef05dc7d74407d1f8435da5a145a0bd781b098ec3dcf1903f29c3cd42a15
def ajax_save(request, *args, **kwargs): 'AJAX-представление: Save Object.' import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] result = {'status': 'success', 'reload': False} if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) try: o = model.objects.get(id=request.POST.get('id')) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) except model.DoesNotExist: o = model() result['reload'] = True if (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) o.created = timezone.now() for key in request.POST: if (key == 'name'): if request.POST.get('name', '').strip(): o.name = request.POST.get('name').strip() else: break if request.POST.get('alias', '').strip(): o.alias = fix_alias(request.POST.get('alias'), model_name=kwargs['model_name']) else: o.alias = fix_alias(request.POST.get(key)) if request.POST.get('name_search', '').strip(): o.name_search = request.POST.get('name_search')[:512] else: o.name_search = request.POST.get(key)[:512] if request.POST.get('full_name', '').strip(): o.full_name = request.POST.get('full_name').strip() else: o.name = request.POST.get(key)[:512] if request.POST.get('name_short', '').strip(): o.name_short = request.POST.get('name_short')[:100] else: o.name_short = request.POST.get(key)[:100] if request.POST.get('name_short_xml', '').strip(): o.name_short_xml = request.POST.get('name_short_xml')[:100] else: o.name_short_xml = request.POST.get(key)[:100] elif (key == 'article'): o.article = request.POST.get('article', '').strip()[:100] elif (key == 'description'): o.description = request.POST.get(key, '').strip() elif (key == 'login'): o.login = request.POST.get(key, '').strip() elif (key == 'password'): o.password = request.POST.get(key, '').strip() elif (key == 'state'): if ('true' == request.POST.get(key, 'true')): o.state = True else: o.state = False elif (key == 'delivery_time_min'): try: o.delivery_time_min = int(request.POST.get(key, 0)) except Exception: o.delivery_time_min = 0 elif (key == 'delivery_time_max'): try: o.delivery_time_max = int(request.POST.get(key, 0)) except Exception: o.delivery_time_max = 0 elif (key == 'order'): try: o.order = int(request.POST.get(key, 0)) except Exception: o.order = 0 elif (key == 'rate'): try: o.rate = float(request.POST.get(key).strip().replace(',', '.').replace(' ', '')) except Exception: o.rate = 1.0 elif ((key == 'quantity') and (kwargs['model_name'] == 'currency')): try: o.quantity = float(request.POST.get(key).strip().replace(',', '.').replace(' ', '')) except Exception: o.quantity = 1.0 elif (key == 'multiplier'): try: o.multiplier = float(request.POST.get(key).strip().replace(',', '.').replace(' ', '')) except Exception: o.multiplier = 1.0 elif (key == 'updater_id'): try: m = catalog.models.models['updater'] o.updater = m.objects.get(id=request.POST.get(key, '')) except Exception: o.updater = None elif (key == 'unit_id'): try: m = catalog.models.models['unit'] o.unit = m.objects.get(id=request.POST.get(key, '')) except Exception: o.unit = None elif (key == 'distributor_id'): try: m = catalog.models.models['distributor'] o.distributor = m.objects.get(id=request.POST.get(key, '')) except Exception: o.distributor = None elif (key == 'vendor_id'): try: m = catalog.models.models['vendor'] o.vendor = m.objects.get(id=request.POST.get(key, '')) except Exception: o.vendor = None elif (key == 'category_id'): old_category = o.category try: m = catalog.models.models['category'] o.category = m.objects.get(id=request.POST.get(key, '')) except Exception: o.category = None if (o.category != old_category): result['reload'] = True elif ((key == 'parent_id') and (kwargs['model_name'] == 'category')): from django.db.models import Max old_parent = o.parent try: m = catalog.models.models[kwargs['model_name']] o.parent = m.objects.get(id=request.POST.get(key, '')) except Exception: o.parent = None o.level = 0 else: childs = [] childs = m.objects.getCategoryTree(childs, o) if (o.parent in childs): o.parent = None o.level = 0 else: o.level = (o.parent.level + 1) if (o.parent != old_parent): result['reload'] = True o.order = m.objects.filter(parent=o.parent).aggregate(Max('order'))['order__max'] if (o.order is None): o.order = 0 else: o.order += 1 if o.parent: o.path = '{}{}/'.format(o.parent.path, o.id) else: o.path = '/{}/'.format(o.id) elif ((key == 'duble_id') and (kwargs['model_name'] == 'product')): try: m = catalog.models.models[kwargs['model_name']] o.duble = m.objects.get(id=request.POST.get(key, '')) except Exception: o.duble = None elif (key == 'parametertype_id'): result['parametertype_id'] = request.POST.get(key, '') try: m = catalog.models.models['parametertype'] o.parametertype = m.objects.get(id=request.POST.get(key, '')) except Exception: o.parametertype = None elif (key == 'parameter_id'): try: m = catalog.models.models['parameter'] o.parameter = m.objects.get(id=request.POST.get(key, '')) except Exception: o.parameter = None elif (key == 'parametervalue_id'): try: m = catalog.models.models['parametervalue'] o.parametervalue = m.objects.get(id=request.POST.get(key, '')) except Exception: o.parametervalue = None o.modified = timezone.now() o.save() result[kwargs['model_name']] = o.get_dicted() return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Save Object.
views.py
ajax_save
anodos-ru/catalog
2
python
def ajax_save(request, *args, **kwargs): import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] result = {'status': 'success', 'reload': False} if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) try: o = model.objects.get(id=request.POST.get('id')) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) except model.DoesNotExist: o = model() result['reload'] = True if (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) o.created = timezone.now() for key in request.POST: if (key == 'name'): if request.POST.get('name', ).strip(): o.name = request.POST.get('name').strip() else: break if request.POST.get('alias', ).strip(): o.alias = fix_alias(request.POST.get('alias'), model_name=kwargs['model_name']) else: o.alias = fix_alias(request.POST.get(key)) if request.POST.get('name_search', ).strip(): o.name_search = request.POST.get('name_search')[:512] else: o.name_search = request.POST.get(key)[:512] if request.POST.get('full_name', ).strip(): o.full_name = request.POST.get('full_name').strip() else: o.name = request.POST.get(key)[:512] if request.POST.get('name_short', ).strip(): o.name_short = request.POST.get('name_short')[:100] else: o.name_short = request.POST.get(key)[:100] if request.POST.get('name_short_xml', ).strip(): o.name_short_xml = request.POST.get('name_short_xml')[:100] else: o.name_short_xml = request.POST.get(key)[:100] elif (key == 'article'): o.article = request.POST.get('article', ).strip()[:100] elif (key == 'description'): o.description = request.POST.get(key, ).strip() elif (key == 'login'): o.login = request.POST.get(key, ).strip() elif (key == 'password'): o.password = request.POST.get(key, ).strip() elif (key == 'state'): if ('true' == request.POST.get(key, 'true')): o.state = True else: o.state = False elif (key == 'delivery_time_min'): try: o.delivery_time_min = int(request.POST.get(key, 0)) except Exception: o.delivery_time_min = 0 elif (key == 'delivery_time_max'): try: o.delivery_time_max = int(request.POST.get(key, 0)) except Exception: o.delivery_time_max = 0 elif (key == 'order'): try: o.order = int(request.POST.get(key, 0)) except Exception: o.order = 0 elif (key == 'rate'): try: o.rate = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.rate = 1.0 elif ((key == 'quantity') and (kwargs['model_name'] == 'currency')): try: o.quantity = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.quantity = 1.0 elif (key == 'multiplier'): try: o.multiplier = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.multiplier = 1.0 elif (key == 'updater_id'): try: m = catalog.models.models['updater'] o.updater = m.objects.get(id=request.POST.get(key, )) except Exception: o.updater = None elif (key == 'unit_id'): try: m = catalog.models.models['unit'] o.unit = m.objects.get(id=request.POST.get(key, )) except Exception: o.unit = None elif (key == 'distributor_id'): try: m = catalog.models.models['distributor'] o.distributor = m.objects.get(id=request.POST.get(key, )) except Exception: o.distributor = None elif (key == 'vendor_id'): try: m = catalog.models.models['vendor'] o.vendor = m.objects.get(id=request.POST.get(key, )) except Exception: o.vendor = None elif (key == 'category_id'): old_category = o.category try: m = catalog.models.models['category'] o.category = m.objects.get(id=request.POST.get(key, )) except Exception: o.category = None if (o.category != old_category): result['reload'] = True elif ((key == 'parent_id') and (kwargs['model_name'] == 'category')): from django.db.models import Max old_parent = o.parent try: m = catalog.models.models[kwargs['model_name']] o.parent = m.objects.get(id=request.POST.get(key, )) except Exception: o.parent = None o.level = 0 else: childs = [] childs = m.objects.getCategoryTree(childs, o) if (o.parent in childs): o.parent = None o.level = 0 else: o.level = (o.parent.level + 1) if (o.parent != old_parent): result['reload'] = True o.order = m.objects.filter(parent=o.parent).aggregate(Max('order'))['order__max'] if (o.order is None): o.order = 0 else: o.order += 1 if o.parent: o.path = '{}{}/'.format(o.parent.path, o.id) else: o.path = '/{}/'.format(o.id) elif ((key == 'duble_id') and (kwargs['model_name'] == 'product')): try: m = catalog.models.models[kwargs['model_name']] o.duble = m.objects.get(id=request.POST.get(key, )) except Exception: o.duble = None elif (key == 'parametertype_id'): result['parametertype_id'] = request.POST.get(key, ) try: m = catalog.models.models['parametertype'] o.parametertype = m.objects.get(id=request.POST.get(key, )) except Exception: o.parametertype = None elif (key == 'parameter_id'): try: m = catalog.models.models['parameter'] o.parameter = m.objects.get(id=request.POST.get(key, )) except Exception: o.parameter = None elif (key == 'parametervalue_id'): try: m = catalog.models.models['parametervalue'] o.parametervalue = m.objects.get(id=request.POST.get(key, )) except Exception: o.parametervalue = None o.modified = timezone.now() o.save() result[kwargs['model_name']] = o.get_dicted() return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_save(request, *args, **kwargs): import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] result = {'status': 'success', 'reload': False} if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) try: o = model.objects.get(id=request.POST.get('id')) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) except model.DoesNotExist: o = model() result['reload'] = True if (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) o.created = timezone.now() for key in request.POST: if (key == 'name'): if request.POST.get('name', ).strip(): o.name = request.POST.get('name').strip() else: break if request.POST.get('alias', ).strip(): o.alias = fix_alias(request.POST.get('alias'), model_name=kwargs['model_name']) else: o.alias = fix_alias(request.POST.get(key)) if request.POST.get('name_search', ).strip(): o.name_search = request.POST.get('name_search')[:512] else: o.name_search = request.POST.get(key)[:512] if request.POST.get('full_name', ).strip(): o.full_name = request.POST.get('full_name').strip() else: o.name = request.POST.get(key)[:512] if request.POST.get('name_short', ).strip(): o.name_short = request.POST.get('name_short')[:100] else: o.name_short = request.POST.get(key)[:100] if request.POST.get('name_short_xml', ).strip(): o.name_short_xml = request.POST.get('name_short_xml')[:100] else: o.name_short_xml = request.POST.get(key)[:100] elif (key == 'article'): o.article = request.POST.get('article', ).strip()[:100] elif (key == 'description'): o.description = request.POST.get(key, ).strip() elif (key == 'login'): o.login = request.POST.get(key, ).strip() elif (key == 'password'): o.password = request.POST.get(key, ).strip() elif (key == 'state'): if ('true' == request.POST.get(key, 'true')): o.state = True else: o.state = False elif (key == 'delivery_time_min'): try: o.delivery_time_min = int(request.POST.get(key, 0)) except Exception: o.delivery_time_min = 0 elif (key == 'delivery_time_max'): try: o.delivery_time_max = int(request.POST.get(key, 0)) except Exception: o.delivery_time_max = 0 elif (key == 'order'): try: o.order = int(request.POST.get(key, 0)) except Exception: o.order = 0 elif (key == 'rate'): try: o.rate = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.rate = 1.0 elif ((key == 'quantity') and (kwargs['model_name'] == 'currency')): try: o.quantity = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.quantity = 1.0 elif (key == 'multiplier'): try: o.multiplier = float(request.POST.get(key).strip().replace(',', '.').replace(' ', )) except Exception: o.multiplier = 1.0 elif (key == 'updater_id'): try: m = catalog.models.models['updater'] o.updater = m.objects.get(id=request.POST.get(key, )) except Exception: o.updater = None elif (key == 'unit_id'): try: m = catalog.models.models['unit'] o.unit = m.objects.get(id=request.POST.get(key, )) except Exception: o.unit = None elif (key == 'distributor_id'): try: m = catalog.models.models['distributor'] o.distributor = m.objects.get(id=request.POST.get(key, )) except Exception: o.distributor = None elif (key == 'vendor_id'): try: m = catalog.models.models['vendor'] o.vendor = m.objects.get(id=request.POST.get(key, )) except Exception: o.vendor = None elif (key == 'category_id'): old_category = o.category try: m = catalog.models.models['category'] o.category = m.objects.get(id=request.POST.get(key, )) except Exception: o.category = None if (o.category != old_category): result['reload'] = True elif ((key == 'parent_id') and (kwargs['model_name'] == 'category')): from django.db.models import Max old_parent = o.parent try: m = catalog.models.models[kwargs['model_name']] o.parent = m.objects.get(id=request.POST.get(key, )) except Exception: o.parent = None o.level = 0 else: childs = [] childs = m.objects.getCategoryTree(childs, o) if (o.parent in childs): o.parent = None o.level = 0 else: o.level = (o.parent.level + 1) if (o.parent != old_parent): result['reload'] = True o.order = m.objects.filter(parent=o.parent).aggregate(Max('order'))['order__max'] if (o.order is None): o.order = 0 else: o.order += 1 if o.parent: o.path = '{}{}/'.format(o.parent.path, o.id) else: o.path = '/{}/'.format(o.id) elif ((key == 'duble_id') and (kwargs['model_name'] == 'product')): try: m = catalog.models.models[kwargs['model_name']] o.duble = m.objects.get(id=request.POST.get(key, )) except Exception: o.duble = None elif (key == 'parametertype_id'): result['parametertype_id'] = request.POST.get(key, ) try: m = catalog.models.models['parametertype'] o.parametertype = m.objects.get(id=request.POST.get(key, )) except Exception: o.parametertype = None elif (key == 'parameter_id'): try: m = catalog.models.models['parameter'] o.parameter = m.objects.get(id=request.POST.get(key, )) except Exception: o.parameter = None elif (key == 'parametervalue_id'): try: m = catalog.models.models['parametervalue'] o.parametervalue = m.objects.get(id=request.POST.get(key, )) except Exception: o.parametervalue = None o.modified = timezone.now() o.save() result[kwargs['model_name']] = o.get_dicted() return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Save Object.<|endoftext|>
9636a11b9c356b9e8cb96ca490333b308734e77bb0ef9d6b92048132db68988b
def ajax_switch_state(request, *args, **kwargs): 'AJAX-представление: Switch State.' import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Объект с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} return HttpResponse(json.dumps(result), 'application/javascript') else: if ('true' == request.POST.get('state')): o.state = True else: o.state = False o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Switch State.
views.py
ajax_switch_state
anodos-ru/catalog
2
python
def ajax_switch_state(request, *args, **kwargs): import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Объект с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} return HttpResponse(json.dumps(result), 'application/javascript') else: if ('true' == request.POST.get('state')): o.state = True else: o.state = False o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_switch_state(request, *args, **kwargs): import json from django.utils import timezone import catalog.models model = catalog.models.models[kwargs['model_name']] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Объект с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} return HttpResponse(json.dumps(result), 'application/javascript') else: if ('true' == request.POST.get('state')): o.state = True else: o.state = False o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Switch State.<|endoftext|>
6759321fe6cc767edc332964b7d3762488e8d4431be574ba81e62d979b68dfbf
def ajax_delete(request, *args, **kwargs): 'AJAX-представление: Delete Object.' import json import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: m = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} else: m.delete() result = {'status': 'success', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Delete Object.
views.py
ajax_delete
anodos-ru/catalog
2
python
def ajax_delete(request, *args, **kwargs): import json import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: m = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} else: m.delete() result = {'status': 'success', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_delete(request, *args, **kwargs): import json import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if (not request.user.has_perm('catalog.delete_{}'.format(kwargs['model_name']))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: m = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.', 'id': request.POST.get('id')} else: m.delete() result = {'status': 'success', 'id': request.POST.get('id')} return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Delete Object.<|endoftext|>
ac9a8c8375c52de702b674f190295edac1df34482b138aa7e4284c8e9ad298ea
def ajax_link(request, *args, **kwargs): 'AJAX-представление: Link Model.' import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = request.POST.get('name', '') double = model.objects.take(name, get_doubles=False) if (o.id == double.id): o.double = None o.state = True o.name = name o.save() else: o.double = double o.state = False o.save() double.name = name double.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Link Model.
views.py
ajax_link
anodos-ru/catalog
2
python
def ajax_link(request, *args, **kwargs): import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = request.POST.get('name', ) double = model.objects.take(name, get_doubles=False) if (o.id == double.id): o.double = None o.state = True o.name = name o.save() else: o.double = double o.state = False o.save() double.name = name double.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_link(request, *args, **kwargs): import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = request.POST.get('name', ) double = model.objects.take(name, get_doubles=False) if (o.id == double.id): o.double = None o.state = True o.name = name o.save() else: o.double = double o.state = False o.save() double.name = name double.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Link Model.<|endoftext|>
b0d415f1c98c3edc82f685ad99a7078e03945ee296eb28169302f891c094d93b
def ajax_link_same_foreign(request, *args, **kwargs): 'AJAX-представление: Link Model to Same Foreign.' import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] foreign = catalog.models.models[kwargs['foreign_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = o.name alias = fix_alias(name) try: f = foreign.objects.get(alias=alias) except Exception: f = foreign() f.name = name f.alias = alias f.created = timezone.now() f.modified = timezone.now() if (kwargs['foreign_name'] == 'parametervalue'): f.order = 0 f.parameter = o.parameter f.save() if (kwargs['foreign_name'] == 'vendor'): o.vendor = f elif (kwargs['foreign_name'] == 'parameter'): o.parameter = f elif (kwargs['foreign_name'] == 'parametervalue'): o.parametervalue = f o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted(), kwargs['foreign_name']: foreign.objects.get_all_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
AJAX-представление: Link Model to Same Foreign.
views.py
ajax_link_same_foreign
anodos-ru/catalog
2
python
def ajax_link_same_foreign(request, *args, **kwargs): import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] foreign = catalog.models.models[kwargs['foreign_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = o.name alias = fix_alias(name) try: f = foreign.objects.get(alias=alias) except Exception: f = foreign() f.name = name f.alias = alias f.created = timezone.now() f.modified = timezone.now() if (kwargs['foreign_name'] == 'parametervalue'): f.order = 0 f.parameter = o.parameter f.save() if (kwargs['foreign_name'] == 'vendor'): o.vendor = f elif (kwargs['foreign_name'] == 'parameter'): o.parameter = f elif (kwargs['foreign_name'] == 'parametervalue'): o.parametervalue = f o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted(), kwargs['foreign_name']: foreign.objects.get_all_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')
def ajax_link_same_foreign(request, *args, **kwargs): import json from django.utils import timezone import catalog.models if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if ((not request.user.has_perm('catalog.change_{}'.format(kwargs['model_name']))) or (not request.user.has_perm('catalog.add_{}'.format(kwargs['model_name'])))): return HttpResponse(status=403) model = catalog.models.models[kwargs['model_name']] foreign = catalog.models.models[kwargs['foreign_name']] try: o = model.objects.get(id=request.POST.get('id')) except Exception: result = {'status': 'alert', 'message': 'Ошибка: объект отсутствует в базе.'} return HttpResponse(json.dumps(result), 'application/javascript') name = o.name alias = fix_alias(name) try: f = foreign.objects.get(alias=alias) except Exception: f = foreign() f.name = name f.alias = alias f.created = timezone.now() f.modified = timezone.now() if (kwargs['foreign_name'] == 'parametervalue'): f.order = 0 f.parameter = o.parameter f.save() if (kwargs['foreign_name'] == 'vendor'): o.vendor = f elif (kwargs['foreign_name'] == 'parameter'): o.parameter = f elif (kwargs['foreign_name'] == 'parametervalue'): o.parametervalue = f o.modified = timezone.now() o.save() result = {'status': 'success', kwargs['model_name']: o.get_dicted(), kwargs['foreign_name']: foreign.objects.get_all_dicted()} return HttpResponse(json.dumps(result), 'application/javascript')<|docstring|>AJAX-представление: Link Model to Same Foreign.<|endoftext|>
bc64410c88dd0fe4d6e8957cd5f3829583ed387ba8dff52957b80902a94b4e32
def ajax_get_parties(request): 'AJAX-представление: Get Parties.' import json from catalog.models import Product, Party items = [] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if request.POST.get('product_id'): try: product = Product.objects.get(id=request.POST.get('product_id')) parties = Party.objects.filter(product=product) if request.user.id: access = True for party in parties: item = {} item['id'] = str(party.id) item['stock'] = str(party.stock.name) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price'] = str(party.price_str) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) else: access = False for party in parties: item = {} item['id'] = str(party.id) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) item = {} item['product_id'] = product.id item['product_article'] = product.article item['product_name'] = product.name item['vendor_name'] = product.vendor.name result = {'status': 'success', 'message': 'Данные партий получены. Количество партий {}'.format(len(parties)), 'len': len(parties), 'items': items, 'product': item, 'access': access} except Product.DoesNotExist: result = {'status': 'alert', 'message': 'Продукт с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} result = json.dumps(result) return HttpResponse(result, 'application/javascript')
AJAX-представление: Get Parties.
views.py
ajax_get_parties
anodos-ru/catalog
2
python
def ajax_get_parties(request): import json from catalog.models import Product, Party items = [] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if request.POST.get('product_id'): try: product = Product.objects.get(id=request.POST.get('product_id')) parties = Party.objects.filter(product=product) if request.user.id: access = True for party in parties: item = {} item['id'] = str(party.id) item['stock'] = str(party.stock.name) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price'] = str(party.price_str) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) else: access = False for party in parties: item = {} item['id'] = str(party.id) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) item = {} item['product_id'] = product.id item['product_article'] = product.article item['product_name'] = product.name item['vendor_name'] = product.vendor.name result = {'status': 'success', 'message': 'Данные партий получены. Количество партий {}'.format(len(parties)), 'len': len(parties), 'items': items, 'product': item, 'access': access} except Product.DoesNotExist: result = {'status': 'alert', 'message': 'Продукт с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} result = json.dumps(result) return HttpResponse(result, 'application/javascript')
def ajax_get_parties(request): import json from catalog.models import Product, Party items = [] if ((not request.is_ajax()) or (request.method != 'POST')): return HttpResponse(status=400) if request.POST.get('product_id'): try: product = Product.objects.get(id=request.POST.get('product_id')) parties = Party.objects.filter(product=product) if request.user.id: access = True for party in parties: item = {} item['id'] = str(party.id) item['stock'] = str(party.stock.name) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price'] = str(party.price_str) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) else: access = False for party in parties: item = {} item['id'] = str(party.id) item['delivery_time_min'] = str(party.stock.delivery_time_min) item['delivery_time_max'] = str(party.stock.delivery_time_max) item['price_out'] = str(party.price_out_str) if ((- 1) == party.quantity): item['quantity'] = 'неограничено' elif (0 == party.quantity): item['quantity'] = '0' elif (party.quantity is None): item['quantity'] = 'неизвестно' else: item['quantity'] = '{}&nbsp;{}'.format(party.quantity, party.unit.name_short_xml) items.append(item) item = {} item['product_id'] = product.id item['product_article'] = product.article item['product_name'] = product.name item['vendor_name'] = product.vendor.name result = {'status': 'success', 'message': 'Данные партий получены. Количество партий {}'.format(len(parties)), 'len': len(parties), 'items': items, 'product': item, 'access': access} except Product.DoesNotExist: result = {'status': 'alert', 'message': 'Продукт с идентификатором {} отсутствует в базе.'.format(request.POST.get('id'))} result = json.dumps(result) return HttpResponse(result, 'application/javascript')<|docstring|>AJAX-представление: Get Parties.<|endoftext|>
5256303914371b40916521dd5ba37dafe035955f6c88c3c619b4af9429083a15
@transaction.atomic() def _process_row(self, row, cleaned_data): 'Save the data from a single row' if row['closing']: return 0 chain = None if (row['zentrale'] != NULL): (chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale']) address = Address.objects.create(street=row['strasse'], street_number=row['hausnr'], postal_code=row['plz'], suburb=row['stadtteil'], town=row['ort'], district=row['kreis'], state=row['bundesland'], latitude=row['y'].replace(',', '.'), longitude=row['x'].replace(',', '.')) name = (row['markttyp'] if (row['markttyp'] not in [NULL, OTHER]) else row['inhaber']) supermarket = Supermarket(chain=chain, name=name, proprietor=row['inhaber'], phone_number=row['fon'], fax_number=row['fax'], email_address=row['email'], website=row['url'], address=address, people_per_slot=cleaned_data['default_people_per_slot'], minutes_per_slot=cleaned_data['default_minutes_per_slot']) supermarket.clean() supermarket.save() for weekday in cleaned_data['default_working_days']: OpeningHours.objects.create(supermarket=supermarket, weekday=weekday, opening_time=cleaned_data['default_opening_time'], closing_time=cleaned_data['default_closing_time']) return 1
Save the data from a single row
marktzeit/supermarkets/views.py
_process_row
firstdayofjune/marktzeit
0
python
@transaction.atomic() def _process_row(self, row, cleaned_data): if row['closing']: return 0 chain = None if (row['zentrale'] != NULL): (chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale']) address = Address.objects.create(street=row['strasse'], street_number=row['hausnr'], postal_code=row['plz'], suburb=row['stadtteil'], town=row['ort'], district=row['kreis'], state=row['bundesland'], latitude=row['y'].replace(',', '.'), longitude=row['x'].replace(',', '.')) name = (row['markttyp'] if (row['markttyp'] not in [NULL, OTHER]) else row['inhaber']) supermarket = Supermarket(chain=chain, name=name, proprietor=row['inhaber'], phone_number=row['fon'], fax_number=row['fax'], email_address=row['email'], website=row['url'], address=address, people_per_slot=cleaned_data['default_people_per_slot'], minutes_per_slot=cleaned_data['default_minutes_per_slot']) supermarket.clean() supermarket.save() for weekday in cleaned_data['default_working_days']: OpeningHours.objects.create(supermarket=supermarket, weekday=weekday, opening_time=cleaned_data['default_opening_time'], closing_time=cleaned_data['default_closing_time']) return 1
@transaction.atomic() def _process_row(self, row, cleaned_data): if row['closing']: return 0 chain = None if (row['zentrale'] != NULL): (chain, __) = SupermarketChain.objects.get_or_create(name=row['zentrale']) address = Address.objects.create(street=row['strasse'], street_number=row['hausnr'], postal_code=row['plz'], suburb=row['stadtteil'], town=row['ort'], district=row['kreis'], state=row['bundesland'], latitude=row['y'].replace(',', '.'), longitude=row['x'].replace(',', '.')) name = (row['markttyp'] if (row['markttyp'] not in [NULL, OTHER]) else row['inhaber']) supermarket = Supermarket(chain=chain, name=name, proprietor=row['inhaber'], phone_number=row['fon'], fax_number=row['fax'], email_address=row['email'], website=row['url'], address=address, people_per_slot=cleaned_data['default_people_per_slot'], minutes_per_slot=cleaned_data['default_minutes_per_slot']) supermarket.clean() supermarket.save() for weekday in cleaned_data['default_working_days']: OpeningHours.objects.create(supermarket=supermarket, weekday=weekday, opening_time=cleaned_data['default_opening_time'], closing_time=cleaned_data['default_closing_time']) return 1<|docstring|>Save the data from a single row<|endoftext|>
6f5a10a53193f6f670b6a61b9a4d13bad2e1030ac8ea1637842705b7db9f4a19
def create_supermarkets(self, reader, cleaned_data): 'Create the supermarkets from the uploaded data' created = 0 for (idx, row) in enumerate(reader): try: created += self._process_row(row, cleaned_data) except Exception as e: messages.add_message(self.request, messages.ERROR, _('Error occurred on row {}: {!r}. Row content: {}').format((idx + 1), e, row)) break return created
Create the supermarkets from the uploaded data
marktzeit/supermarkets/views.py
create_supermarkets
firstdayofjune/marktzeit
0
python
def create_supermarkets(self, reader, cleaned_data): created = 0 for (idx, row) in enumerate(reader): try: created += self._process_row(row, cleaned_data) except Exception as e: messages.add_message(self.request, messages.ERROR, _('Error occurred on row {}: {!r}. Row content: {}').format((idx + 1), e, row)) break return created
def create_supermarkets(self, reader, cleaned_data): created = 0 for (idx, row) in enumerate(reader): try: created += self._process_row(row, cleaned_data) except Exception as e: messages.add_message(self.request, messages.ERROR, _('Error occurred on row {}: {!r}. Row content: {}').format((idx + 1), e, row)) break return created<|docstring|>Create the supermarkets from the uploaded data<|endoftext|>
4db4b8f76f81c5ae74bcd1a574b78366db830746983ba857d71da9844f667d7c
@pytest.mark.asyncio async def test_task_catches_cancel(): 'A nasty task catches all exceptions' async def nasty(): while True: try: (await asyncio.sleep(1)) print('loop') except asyncio.CancelledError: pass before = time.time() with pytest.raises(OSError): async with Scope(timeout=0.1) as n: n.spawn(nasty(), cancel_timeout=0.5) after = time.time() assert (0.4 < (after - before) < 1)
A nasty task catches all exceptions
tests/test_cancel.py
test_task_catches_cancel
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_task_catches_cancel(): async def nasty(): while True: try: (await asyncio.sleep(1)) print('loop') except asyncio.CancelledError: pass before = time.time() with pytest.raises(OSError): async with Scope(timeout=0.1) as n: n.spawn(nasty(), cancel_timeout=0.5) after = time.time() assert (0.4 < (after - before) < 1)
@pytest.mark.asyncio async def test_task_catches_cancel(): async def nasty(): while True: try: (await asyncio.sleep(1)) print('loop') except asyncio.CancelledError: pass before = time.time() with pytest.raises(OSError): async with Scope(timeout=0.1) as n: n.spawn(nasty(), cancel_timeout=0.5) after = time.time() assert (0.4 < (after - before) < 1)<|docstring|>A nasty task catches all exceptions<|endoftext|>
97c7c78b90c2810f3af9389962ce4d64975a6a4f45f8c2db7f623947e4a6ebff
@pytest.mark.asyncio async def test_external_cancel(): 'Raise an external cancellation' async def run_me(): n = Scope() async with n: n.spawn(run10()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(asyncio.shield(task), 0.1)) except asyncio.TimeoutError: task.cancel() with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')
Raise an external cancellation
tests/test_cancel.py
test_external_cancel
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_external_cancel(): async def run_me(): n = Scope() async with n: n.spawn(run10()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(asyncio.shield(task), 0.1)) except asyncio.TimeoutError: task.cancel() with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')
@pytest.mark.asyncio async def test_external_cancel(): async def run_me(): n = Scope() async with n: n.spawn(run10()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(asyncio.shield(task), 0.1)) except asyncio.TimeoutError: task.cancel() with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')<|docstring|>Raise an external cancellation<|endoftext|>
563d3dae259d7e672d24e5417820ad2da6abf289f8f07f69c286851647f22d35
@pytest.mark.asyncio async def test_external_cancel_nasty(): 'Raise an external cancellation with task which fails cancelling' async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') async def run_me(): n = Scope() async with n: n.spawn(nasty()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(task, 0.1)) except asyncio.TimeoutError: with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')
Raise an external cancellation with task which fails cancelling
tests/test_cancel.py
test_external_cancel_nasty
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_external_cancel_nasty(): async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') async def run_me(): n = Scope() async with n: n.spawn(nasty()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(task, 0.1)) except asyncio.TimeoutError: with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')
@pytest.mark.asyncio async def test_external_cancel_nasty(): async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') async def run_me(): n = Scope() async with n: n.spawn(nasty()) assert n.cancelled() task = asyncio.ensure_future(run_me()) try: (await asyncio.wait_for(task, 0.1)) except asyncio.TimeoutError: with pytest.raises(asyncio.CancelledError): (await task) else: raise Exception('should have raised')<|docstring|>Raise an external cancellation with task which fails cancelling<|endoftext|>
972d0a6f053fc0d4eea8f89cae5113e45e224095b702061e71c1cb0af2202805
@pytest.mark.asyncio async def test_internal_cancel(): 'Test an internal cancellation' before = time.time() async with Scope() as n: n.spawn(run10()) (await asyncio.sleep(0.2)) n.cancel() after = time.time() assert ((after - before) < 0.5)
Test an internal cancellation
tests/test_cancel.py
test_internal_cancel
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_internal_cancel(): before = time.time() async with Scope() as n: n.spawn(run10()) (await asyncio.sleep(0.2)) n.cancel() after = time.time() assert ((after - before) < 0.5)
@pytest.mark.asyncio async def test_internal_cancel(): before = time.time() async with Scope() as n: n.spawn(run10()) (await asyncio.sleep(0.2)) n.cancel() after = time.time() assert ((after - before) < 0.5)<|docstring|>Test an internal cancellation<|endoftext|>
d13232f8220fd3cebd8788495e79bb84409174dde790edfeb49318b2baf45287
@pytest.mark.asyncio async def test_cancelling_going_bad(): 'Test cancelling a pending task, but things go wrong...' async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') with pytest.raises(TimeoutError): async with Scope(timeout=0.5) as n: n.spawn(nasty()) (await asyncio.sleep(0.1))
Test cancelling a pending task, but things go wrong...
tests/test_cancel.py
test_cancelling_going_bad
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancelling_going_bad(): async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') with pytest.raises(TimeoutError): async with Scope(timeout=0.5) as n: n.spawn(nasty()) (await asyncio.sleep(0.1))
@pytest.mark.asyncio async def test_cancelling_going_bad(): async def nasty(): try: (await asyncio.sleep(10)) except asyncio.CancelledError: raise ValueError('boom') with pytest.raises(TimeoutError): async with Scope(timeout=0.5) as n: n.spawn(nasty()) (await asyncio.sleep(0.1))<|docstring|>Test cancelling a pending task, but things go wrong...<|endoftext|>
98073373456853662c57b669964d1e4e9bf1cc7e30d2e65e322e5d6dd83b7d05
@pytest.mark.asyncio async def test_cancel_not_joined_yet(): "\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n " async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() (await asyncio.sleep(10)) before = time.time() async with Scope() as s: (s << cleaner()) (await asyncio.sleep(1)) raise Exception('never called') after = time.time() assert ((after - before) < 0.4), 'for now...'
When we cancel the nursery, it hasn't been joined yet. This should cancel it anyway.
tests/test_cancel.py
test_cancel_not_joined_yet
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_not_joined_yet(): "\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n " async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() (await asyncio.sleep(10)) before = time.time() async with Scope() as s: (s << cleaner()) (await asyncio.sleep(1)) raise Exception('never called') after = time.time() assert ((after - before) < 0.4), 'for now...'
@pytest.mark.asyncio async def test_cancel_not_joined_yet(): "\n When we cancel the nursery, it hasn't been joined yet.\n This should cancel it anyway.\n " async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() (await asyncio.sleep(10)) before = time.time() async with Scope() as s: (s << cleaner()) (await asyncio.sleep(1)) raise Exception('never called') after = time.time() assert ((after - before) < 0.4), 'for now...'<|docstring|>When we cancel the nursery, it hasn't been joined yet. This should cancel it anyway.<|endoftext|>
9d9900f2bbbf49e0a02cd8ac79887a6c68db845792ec3d68dab0321100f3775a
@pytest.mark.asyncio async def test_cancel_double(): '\n Cancelled externally, twice\n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel() scope.cancel() scope = Scope() task = asyncio.ensure_future(cleaner(scope)) async with scope: (scope << run10()) (await task) assert (scope.done() and (scope.exception() is None))
Cancelled externally, twice
tests/test_cancel.py
test_cancel_double
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_double(): '\n \n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel() scope.cancel() scope = Scope() task = asyncio.ensure_future(cleaner(scope)) async with scope: (scope << run10()) (await task) assert (scope.done() and (scope.exception() is None))
@pytest.mark.asyncio async def test_cancel_double(): '\n \n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel() scope.cancel() scope = Scope() task = asyncio.ensure_future(cleaner(scope)) async with scope: (scope << run10()) (await task) assert (scope.done() and (scope.exception() is None))<|docstring|>Cancelled externally, twice<|endoftext|>
b1ca58292b6478f6752b6235fd3898195465acd84aa079cfddfc80df6cd68eed
@pytest.mark.asyncio async def test_cancel_double_exception(): '\n Cancelled externally, twice, with exception\n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel(ValueError('boom')) scope.cancel(ValueError('boom')) scope = Scope() task = asyncio.ensure_future(cleaner(scope)) with pytest.raises(ValueError): async with scope: (scope << run10()) (await task) assert (scope.done() and isinstance(scope.exception(), ValueError))
Cancelled externally, twice, with exception
tests/test_cancel.py
test_cancel_double_exception
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_double_exception(): '\n \n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel(ValueError('boom')) scope.cancel(ValueError('boom')) scope = Scope() task = asyncio.ensure_future(cleaner(scope)) with pytest.raises(ValueError): async with scope: (scope << run10()) (await task) assert (scope.done() and isinstance(scope.exception(), ValueError))
@pytest.mark.asyncio async def test_cancel_double_exception(): '\n \n ' async def cleaner(scope): (await asyncio.sleep(0.2)) scope.cancel(ValueError('boom')) scope.cancel(ValueError('boom')) scope = Scope() task = asyncio.ensure_future(cleaner(scope)) with pytest.raises(ValueError): async with scope: (scope << run10()) (await task) assert (scope.done() and isinstance(scope.exception(), ValueError))<|docstring|>Cancelled externally, twice, with exception<|endoftext|>
68ba9d90edb684c89244772be373b11c64e6df8c521e28d529a358d4a72ae857
@pytest.mark.asyncio async def test_cancel_double_internal(): '\n Cancelled internally, twice\n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() Scope.get_current().cancel() async with Scope() as scope: (scope << cleaner())
Cancelled internally, twice
tests/test_cancel.py
test_cancel_double_internal
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_double_internal(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() Scope.get_current().cancel() async with Scope() as scope: (scope << cleaner())
@pytest.mark.asyncio async def test_cancel_double_internal(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel() Scope.get_current().cancel() async with Scope() as scope: (scope << cleaner())<|docstring|>Cancelled internally, twice<|endoftext|>
e6cedeaeda19daecca7478fc2b3ab435af6601759525e82118e69b82e8b76b67
@pytest.mark.asyncio async def test_cancel_double_internal_exception(): '\n Cancelled internally, twice, with exception\n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel(ValueError('boom')) Scope.get_current().cancel(ValueError('boom')) with pytest.raises(ValueError): async with Scope() as scope: (scope << cleaner())
Cancelled internally, twice, with exception
tests/test_cancel.py
test_cancel_double_internal_exception
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_double_internal_exception(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel(ValueError('boom')) Scope.get_current().cancel(ValueError('boom')) with pytest.raises(ValueError): async with Scope() as scope: (scope << cleaner())
@pytest.mark.asyncio async def test_cancel_double_internal_exception(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) Scope.get_current().cancel(ValueError('boom')) Scope.get_current().cancel(ValueError('boom')) with pytest.raises(ValueError): async with Scope() as scope: (scope << cleaner())<|docstring|>Cancelled internally, twice, with exception<|endoftext|>
3a93e3d45e9bd5ef6a2ca6b461441aa77158f5769330412ef9d01295975b29eb
@pytest.mark.asyncio async def test_cancel_finally_cancel(): '\n Cancelled internally, twice\n ' async def cleaner(): (await asyncio.sleep(0.2)) raise ValueError('boom') scope = Scope() with pytest.raises(ValueError): try: async with scope: (scope << cleaner()) finally: scope.cancel()
Cancelled internally, twice
tests/test_cancel.py
test_cancel_finally_cancel
RouquinBlanc/traio
3
python
@pytest.mark.asyncio async def test_cancel_finally_cancel(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) raise ValueError('boom') scope = Scope() with pytest.raises(ValueError): try: async with scope: (scope << cleaner()) finally: scope.cancel()
@pytest.mark.asyncio async def test_cancel_finally_cancel(): '\n \n ' async def cleaner(): (await asyncio.sleep(0.2)) raise ValueError('boom') scope = Scope() with pytest.raises(ValueError): try: async with scope: (scope << cleaner()) finally: scope.cancel()<|docstring|>Cancelled internally, twice<|endoftext|>
45cd9d31ee59a958813992915bfcfa183ed75afd2c68ded05fc3598432db122f
def validate_email_config(self) -> None: 'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeError\n ' smtp = self._login() smtp.close()
Validates SMTP server configuration. Returns: None Raises: smtplib.SMTPHeloError smtplib.SMTPAuthenticationError smtplib.SMTPNotSupportedError smtplib.SMTPException RuntimeError
package/cloudshell/email/email_service.py
validate_email_config
QualiSystemsLab/cloudshell-email
0
python
def validate_email_config(self) -> None: 'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeError\n ' smtp = self._login() smtp.close()
def validate_email_config(self) -> None: 'Validates SMTP server configuration.\n\n Returns:\n None\n Raises:\n smtplib.SMTPHeloError\n smtplib.SMTPAuthenticationError\n smtplib.SMTPNotSupportedError\n smtplib.SMTPException\n RuntimeError\n ' smtp = self._login() smtp.close()<|docstring|>Validates SMTP server configuration. Returns: None Raises: smtplib.SMTPHeloError smtplib.SMTPAuthenticationError smtplib.SMTPNotSupportedError smtplib.SMTPException RuntimeError<|endoftext|>
5822e73f6b3020b36b287fe39bbcf1f3596cbdc4dd528cd56a9e9bf9feeba98a
def rotate_crop(image, angle): 'Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace.' (h, w) = image.shape[:2] (cX, cY) = ((w // 2), (h // 2)) M = cv.getRotationMatrix2D((cX, cY), angle, 1.0) cos = np.abs(M[(0, 0)]) sin = np.abs(M[(0, 1)]) nW = int((((h * sin) + (w * cos)) - (2 * min((h * sin), (w * cos))))) nH = int((((h * cos) + (w * sin)) - (2 * min((w * sin), (h * cos))))) diag = int(min((w * cos), (h * sin))) if ((nW < diag) or (nH < diag)): nW = nH = diag M[(0, 2)] += ((nW / 2) - cX) M[(1, 2)] += ((nH / 2) - cY) return cv.warpAffine(image, M, (nW, nH))
Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace.
im_tools.py
rotate_crop
wwilliamcook/floop
0
python
def rotate_crop(image, angle): (h, w) = image.shape[:2] (cX, cY) = ((w // 2), (h // 2)) M = cv.getRotationMatrix2D((cX, cY), angle, 1.0) cos = np.abs(M[(0, 0)]) sin = np.abs(M[(0, 1)]) nW = int((((h * sin) + (w * cos)) - (2 * min((h * sin), (w * cos))))) nH = int((((h * cos) + (w * sin)) - (2 * min((w * sin), (h * cos))))) diag = int(min((w * cos), (h * sin))) if ((nW < diag) or (nH < diag)): nW = nH = diag M[(0, 2)] += ((nW / 2) - cX) M[(1, 2)] += ((nH / 2) - cY) return cv.warpAffine(image, M, (nW, nH))
def rotate_crop(image, angle): (h, w) = image.shape[:2] (cX, cY) = ((w // 2), (h // 2)) M = cv.getRotationMatrix2D((cX, cY), angle, 1.0) cos = np.abs(M[(0, 0)]) sin = np.abs(M[(0, 1)]) nW = int((((h * sin) + (w * cos)) - (2 * min((h * sin), (w * cos))))) nH = int((((h * cos) + (w * sin)) - (2 * min((w * sin), (h * cos))))) diag = int(min((w * cos), (h * sin))) if ((nW < diag) or (nH < diag)): nW = nH = diag M[(0, 2)] += ((nW / 2) - cX) M[(1, 2)] += ((nH / 2) - cY) return cv.warpAffine(image, M, (nW, nH))<|docstring|>Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace.<|endoftext|>
fdf8bcf712eb4884fd47db047d01da4966c72ca5878b58a47811c8ad15c6fc8b
def openPDF(name, page_index=None): 'Open a page of the given PDF as an OpenCV image.' name = str(name) if os.path.exists(name): doc = fitz.open(name) if (page_index is None): page = doc.loadPage(np.random.randint(0, doc.pageCount)) else: page = doc.loadPage(page_index) pix = page.getPixmap() nparr = np.frombuffer(pix.getImageData('jpg'), np.uint8) doc.close() return cv.imdecode(nparr, cv.IMREAD_COLOR) else: raise FileNotFoundError(('Unable to locate "%s"' % name))
Open a page of the given PDF as an OpenCV image.
im_tools.py
openPDF
wwilliamcook/floop
0
python
def openPDF(name, page_index=None): name = str(name) if os.path.exists(name): doc = fitz.open(name) if (page_index is None): page = doc.loadPage(np.random.randint(0, doc.pageCount)) else: page = doc.loadPage(page_index) pix = page.getPixmap() nparr = np.frombuffer(pix.getImageData('jpg'), np.uint8) doc.close() return cv.imdecode(nparr, cv.IMREAD_COLOR) else: raise FileNotFoundError(('Unable to locate "%s"' % name))
def openPDF(name, page_index=None): name = str(name) if os.path.exists(name): doc = fitz.open(name) if (page_index is None): page = doc.loadPage(np.random.randint(0, doc.pageCount)) else: page = doc.loadPage(page_index) pix = page.getPixmap() nparr = np.frombuffer(pix.getImageData('jpg'), np.uint8) doc.close() return cv.imdecode(nparr, cv.IMREAD_COLOR) else: raise FileNotFoundError(('Unable to locate "%s"' % name))<|docstring|>Open a page of the given PDF as an OpenCV image.<|endoftext|>
7f4efc33772b23936a51bf2197b2898310bb8ded84d6ced589d16264fdd6bce2
def generate_sample(image, output_res, min_src_res=(150, 150)): 'Generate an image/label pair from the given image' angle = (np.random.random() * 360) image = rotate_crop(image, angle) w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1]) h = np.random.randint(min(min_src_res[1], image.shape[0]), image.shape[0]) x = np.random.randint(0, (image.shape[1] - w)) y = np.random.randint(0, (image.shape[0] - h)) image = image[(y:(y + h), x:(x + w))] image = cv.resize(image, output_res, interpolation=cv.INTER_CUBIC) return (image, angle)
Generate an image/label pair from the given image
im_tools.py
generate_sample
wwilliamcook/floop
0
python
def generate_sample(image, output_res, min_src_res=(150, 150)): angle = (np.random.random() * 360) image = rotate_crop(image, angle) w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1]) h = np.random.randint(min(min_src_res[1], image.shape[0]), image.shape[0]) x = np.random.randint(0, (image.shape[1] - w)) y = np.random.randint(0, (image.shape[0] - h)) image = image[(y:(y + h), x:(x + w))] image = cv.resize(image, output_res, interpolation=cv.INTER_CUBIC) return (image, angle)
def generate_sample(image, output_res, min_src_res=(150, 150)): angle = (np.random.random() * 360) image = rotate_crop(image, angle) w = np.random.randint(min(min_src_res[0], image.shape[1]), image.shape[1]) h = np.random.randint(min(min_src_res[1], image.shape[0]), image.shape[0]) x = np.random.randint(0, (image.shape[1] - w)) y = np.random.randint(0, (image.shape[0] - h)) image = image[(y:(y + h), x:(x + w))] image = cv.resize(image, output_res, interpolation=cv.INTER_CUBIC) return (image, angle)<|docstring|>Generate an image/label pair from the given image<|endoftext|>
f83cbcaa4d0a8e7c09b2661b03b94f4ab19e318c0a3b97b557778da261847617
def rotatePDF(name, relative_orientation): 'Permanently rotate the given PDF by the specified angle (multiple of 90).' doc = fitz.open(name) for i in range(doc.pageCount): page = doc.loadPage(i) page.setRotation((page.rotation + relative_orientation)) doc.saveIncr() doc.close()
Permanently rotate the given PDF by the specified angle (multiple of 90).
im_tools.py
rotatePDF
wwilliamcook/floop
0
python
def rotatePDF(name, relative_orientation): doc = fitz.open(name) for i in range(doc.pageCount): page = doc.loadPage(i) page.setRotation((page.rotation + relative_orientation)) doc.saveIncr() doc.close()
def rotatePDF(name, relative_orientation): doc = fitz.open(name) for i in range(doc.pageCount): page = doc.loadPage(i) page.setRotation((page.rotation + relative_orientation)) doc.saveIncr() doc.close()<|docstring|>Permanently rotate the given PDF by the specified angle (multiple of 90).<|endoftext|>
982d567a33b877936860deb9e3246b029c363fe3a26baeadc8cdf0c29937be6f
def spin(img): "animates rotating 'img' using 'rotate_crop'" a = 0 while True: cv.imshow('spin', rotate_clip(img, a)) k = cv.waitKey(1) if (k == 27): break a = ((a + 0.01) % 360) cv.destroyAllWindows()
animates rotating 'img' using 'rotate_crop'
im_tools.py
spin
wwilliamcook/floop
0
python
def spin(img): a = 0 while True: cv.imshow('spin', rotate_clip(img, a)) k = cv.waitKey(1) if (k == 27): break a = ((a + 0.01) % 360) cv.destroyAllWindows()
def spin(img): a = 0 while True: cv.imshow('spin', rotate_clip(img, a)) k = cv.waitKey(1) if (k == 27): break a = ((a + 0.01) % 360) cv.destroyAllWindows()<|docstring|>animates rotating 'img' using 'rotate_crop'<|endoftext|>
6c56e68d0bf4a624e0d1ea35ece03af3af470270bc3274304a50497300bc71d9
def AttachEOLMarker(self): "Attach an EOL marker '$' to the pattern." self.pattern += '$' self._regex = re.compile(self.pattern)
Attach an EOL marker '$' to the pattern.
ashierlib/reactive.py
AttachEOLMarker
google/ashier
26
python
def AttachEOLMarker(self): self.pattern += '$' self._regex = re.compile(self.pattern)
def AttachEOLMarker(self): self.pattern += '$' self._regex = re.compile(self.pattern)<|docstring|>Attach an EOL marker '$' to the pattern.<|endoftext|>
19b00fdd52414d019a9278abfc3eb346ed525b26ddfbcd6f3a7ca9f032059371
def Match(self, text, bindings): 'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A Boolean value that indicates match success.\n ' matches = self._regex.match(text) if matches: for (index, name) in enumerate(self.bound_names): if name: bindings[name] = matches.group((index + 1)) return True return False
Match a string to a pattern. Check if the string argument matches the pattern and, if so, extact substrings into the bindings dictionary. Args: text: the string to match. bindings: dictionary to store extracted substrings. Returns: A Boolean value that indicates match success.
ashierlib/reactive.py
Match
google/ashier
26
python
def Match(self, text, bindings): 'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A Boolean value that indicates match success.\n ' matches = self._regex.match(text) if matches: for (index, name) in enumerate(self.bound_names): if name: bindings[name] = matches.group((index + 1)) return True return False
def Match(self, text, bindings): 'Match a string to a pattern.\n\n Check if the string argument matches the pattern and, if so,\n extact substrings into the bindings dictionary.\n\n Args:\n text: the string to match.\n bindings: dictionary to store extracted substrings.\n\n Returns:\n A Boolean value that indicates match success.\n ' matches = self._regex.match(text) if matches: for (index, name) in enumerate(self.bound_names): if name: bindings[name] = matches.group((index + 1)) return True return False<|docstring|>Match a string to a pattern. Check if the string argument matches the pattern and, if so, extact substrings into the bindings dictionary. Args: text: the string to match. bindings: dictionary to store extracted substrings. Returns: A Boolean value that indicates match success.<|endoftext|>
ca05fb3497e70f1e07ba42ab9d5ddc79c01f67f79fe082a89a50a5d0c20964df
def PatternSize(self): 'Return pattern length (in lines).' return len(self._patterns)
Return pattern length (in lines).
ashierlib/reactive.py
PatternSize
google/ashier
26
python
def PatternSize(self): return len(self._patterns)
def PatternSize(self): return len(self._patterns)<|docstring|>Return pattern length (in lines).<|endoftext|>
2e2409a740c1e97b873507feb17b1eef21b5b78c779691a2e04984db107ed69c
def React(self, nesting, buf, bound, channels): 'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains the terminal output to match.\n bound: integer index matching upper limit (non-inclusive).\n channels: dictionary that maps channel names (which are strings)\n to the corresponding writable file descriptors.\n\n Returns:\n An integer indicating the how the matching baseline should be\n adjusted. If non-negative, the value indicates what the\n baseline *can* be raised to. If negative, its absolute value\n indicates what the baseline *must* be raised to.\n ' self_indentation = self._nesting[(- 1)][0] def LowerIndentation(nest): return (nest[0] < self_indentation) if (filter(LowerIndentation, nesting) != self._nesting[:(- 1)]): return buf.GetBound() start = (bound - len(self._patterns)) if (start < buf.baseline): return buf.baseline bindings = dict() for index in xrange(start, bound): pattern = self._patterns[(index - start)] if (not pattern.Match(buf.GetLine(index), bindings)): definite_mismatch = (index < (buf.GetBound() - 1)) return ((start + 1) if definite_mismatch else start) for send in self._actions: send.Send(channels, bindings) nesting[:] = self._nesting if (not self._patterns[(- 1)].pattern): return (1 - bound) return (- bound)
React if there is a match from line buffer. Args: nesting: persistent state to support nested matching. Initialize with a fresh empty mutable list and reuse the same list for subsequent calls. buf: a Buffer object that contains the terminal output to match. bound: integer index matching upper limit (non-inclusive). channels: dictionary that maps channel names (which are strings) to the corresponding writable file descriptors. Returns: An integer indicating the how the matching baseline should be adjusted. If non-negative, the value indicates what the baseline *can* be raised to. If negative, its absolute value indicates what the baseline *must* be raised to.
ashierlib/reactive.py
React
google/ashier
26
python
def React(self, nesting, buf, bound, channels): 'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains the terminal output to match.\n bound: integer index matching upper limit (non-inclusive).\n channels: dictionary that maps channel names (which are strings)\n to the corresponding writable file descriptors.\n\n Returns:\n An integer indicating the how the matching baseline should be\n adjusted. If non-negative, the value indicates what the\n baseline *can* be raised to. If negative, its absolute value\n indicates what the baseline *must* be raised to.\n ' self_indentation = self._nesting[(- 1)][0] def LowerIndentation(nest): return (nest[0] < self_indentation) if (filter(LowerIndentation, nesting) != self._nesting[:(- 1)]): return buf.GetBound() start = (bound - len(self._patterns)) if (start < buf.baseline): return buf.baseline bindings = dict() for index in xrange(start, bound): pattern = self._patterns[(index - start)] if (not pattern.Match(buf.GetLine(index), bindings)): definite_mismatch = (index < (buf.GetBound() - 1)) return ((start + 1) if definite_mismatch else start) for send in self._actions: send.Send(channels, bindings) nesting[:] = self._nesting if (not self._patterns[(- 1)].pattern): return (1 - bound) return (- bound)
def React(self, nesting, buf, bound, channels): 'React if there is a match from line buffer.\n\n Args:\n nesting: persistent state to support nested matching.\n Initialize with a fresh empty mutable list and reuse the same\n list for subsequent calls.\n buf: a Buffer object that contains the terminal output to match.\n bound: integer index matching upper limit (non-inclusive).\n channels: dictionary that maps channel names (which are strings)\n to the corresponding writable file descriptors.\n\n Returns:\n An integer indicating the how the matching baseline should be\n adjusted. If non-negative, the value indicates what the\n baseline *can* be raised to. If negative, its absolute value\n indicates what the baseline *must* be raised to.\n ' self_indentation = self._nesting[(- 1)][0] def LowerIndentation(nest): return (nest[0] < self_indentation) if (filter(LowerIndentation, nesting) != self._nesting[:(- 1)]): return buf.GetBound() start = (bound - len(self._patterns)) if (start < buf.baseline): return buf.baseline bindings = dict() for index in xrange(start, bound): pattern = self._patterns[(index - start)] if (not pattern.Match(buf.GetLine(index), bindings)): definite_mismatch = (index < (buf.GetBound() - 1)) return ((start + 1) if definite_mismatch else start) for send in self._actions: send.Send(channels, bindings) nesting[:] = self._nesting if (not self._patterns[(- 1)].pattern): return (1 - bound) return (- bound)<|docstring|>React if there is a match from line buffer. Args: nesting: persistent state to support nested matching. Initialize with a fresh empty mutable list and reuse the same list for subsequent calls. buf: a Buffer object that contains the terminal output to match. bound: integer index matching upper limit (non-inclusive). channels: dictionary that maps channel names (which are strings) to the corresponding writable file descriptors. Returns: An integer indicating the how the matching baseline should be adjusted. If non-negative, the value indicates what the baseline *can* be raised to. If negative, its absolute value indicates what the baseline *must* be raised to.<|endoftext|>
62ee2f15010a9c521663618af474d69854c76e2456f4a3f220249c04a4ae36e4
def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]: '\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdirectories should be recursed.\n\t' all_py_files: List[pathlib.Path] = [] for filename in files_and_dirs: if (filename.suffix.startswith('.py') and filename.is_file()): all_py_files.append(filename) elif filename.is_dir(): if recursive: all_py_files += list(filename.rglob('*.py*')) else: all_py_files += list(filename.rglob('*.py*')) for filename in all_py_files: if (not filename.is_file()): continue if (not filename.suffix.startswith('.py')): continue if (filename.suffix in {'.pyd', '.pyc', '.pyo'}): continue filename = filename.absolute() if any(((exclude_dir in str(filename.parent)) for exclude_dir in {'.mypy_cache', '.pytest_cache', 'venv', '.tox', '__pycache__'})): continue (yield filename)
Iterate over all ``.py`` files in the given directories. TODO: Wildcards in filename/directory :param files_and_dirs: An iterable of filenames and directories :param recursive: Whether subdirectories should be recursed.
pyupgrade_directories/__init__.py
iter_py_files
domdfcoding/pyupgrade-directories
8
python
def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]: '\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdirectories should be recursed.\n\t' all_py_files: List[pathlib.Path] = [] for filename in files_and_dirs: if (filename.suffix.startswith('.py') and filename.is_file()): all_py_files.append(filename) elif filename.is_dir(): if recursive: all_py_files += list(filename.rglob('*.py*')) else: all_py_files += list(filename.rglob('*.py*')) for filename in all_py_files: if (not filename.is_file()): continue if (not filename.suffix.startswith('.py')): continue if (filename.suffix in {'.pyd', '.pyc', '.pyo'}): continue filename = filename.absolute() if any(((exclude_dir in str(filename.parent)) for exclude_dir in {'.mypy_cache', '.pytest_cache', 'venv', '.tox', '__pycache__'})): continue (yield filename)
def iter_py_files(files_and_dirs: Iterable[pathlib.Path], recursive: bool=False) -> Iterable[pathlib.Path]: '\n\tIterate over all ``.py`` files in the given directories.\n\n\tTODO: Wildcards in filename/directory\n\n\t:param files_and_dirs: An iterable of filenames and directories\n\t:param recursive: Whether subdirectories should be recursed.\n\t' all_py_files: List[pathlib.Path] = [] for filename in files_and_dirs: if (filename.suffix.startswith('.py') and filename.is_file()): all_py_files.append(filename) elif filename.is_dir(): if recursive: all_py_files += list(filename.rglob('*.py*')) else: all_py_files += list(filename.rglob('*.py*')) for filename in all_py_files: if (not filename.is_file()): continue if (not filename.suffix.startswith('.py')): continue if (filename.suffix in {'.pyd', '.pyc', '.pyo'}): continue filename = filename.absolute() if any(((exclude_dir in str(filename.parent)) for exclude_dir in {'.mypy_cache', '.pytest_cache', 'venv', '.tox', '__pycache__'})): continue (yield filename)<|docstring|>Iterate over all ``.py`` files in the given directories. TODO: Wildcards in filename/directory :param files_and_dirs: An iterable of filenames and directories :param recursive: Whether subdirectories should be recursed.<|endoftext|>
7642a72d5bd0285a7a02c69ced4d37d879d624ee4c5d405036f47986d076d670
@course_bp.route('', methods=['POST', 'GET']) def retrieve_courses(): 'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.' if (request.method == 'POST'): data = request.get_json(force=True) try: new_course = Course(**data) db.session.add(new_course) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, str(ex)) return Response(headers={'Location': url_for('courses.course_detail', id=new_course.id)}, status=201) if (request.method == 'GET'): page = request.args.get('page', 1, type=int) start = (PAGE_SIZE * (page - 1)) end = (start + PAGE_SIZE) courses = Course.query.all() formatted_courses = [course.format() for course in courses[start:end]] return (jsonify(formatted_courses), 200)
Endpoint for courses, GET will return all courses in db by default, POST allows user to add a course to the database.
flask_app/course_views.py
retrieve_courses
kentblock/golf-api
0
python
@course_bp.route(, methods=['POST', 'GET']) def retrieve_courses(): 'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.' if (request.method == 'POST'): data = request.get_json(force=True) try: new_course = Course(**data) db.session.add(new_course) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, str(ex)) return Response(headers={'Location': url_for('courses.course_detail', id=new_course.id)}, status=201) if (request.method == 'GET'): page = request.args.get('page', 1, type=int) start = (PAGE_SIZE * (page - 1)) end = (start + PAGE_SIZE) courses = Course.query.all() formatted_courses = [course.format() for course in courses[start:end]] return (jsonify(formatted_courses), 200)
@course_bp.route(, methods=['POST', 'GET']) def retrieve_courses(): 'Endpoint for courses, GET will return all courses in db by default,\n POST allows user to add a course to the database.' if (request.method == 'POST'): data = request.get_json(force=True) try: new_course = Course(**data) db.session.add(new_course) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, str(ex)) return Response(headers={'Location': url_for('courses.course_detail', id=new_course.id)}, status=201) if (request.method == 'GET'): page = request.args.get('page', 1, type=int) start = (PAGE_SIZE * (page - 1)) end = (start + PAGE_SIZE) courses = Course.query.all() formatted_courses = [course.format() for course in courses[start:end]] return (jsonify(formatted_courses), 200)<|docstring|>Endpoint for courses, GET will return all courses in db by default, POST allows user to add a course to the database.<|endoftext|>
00fff9c1e768129254c7f98ebfa54f025c3f936935161ec95ab67711bd1d27c9
@course_bp.route('/<int:id>', methods=['GET', 'PATCH']) def course_detail(id): 'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH' if (request.method == 'GET'): course = Course.query.get(id) if course: return (jsonify(course.detail_format()), 200) abort(404, f'Course with id: {id} does not exist.') if (request.method == 'PATCH'): pass
Course detail endpoint, retrieve data for course with GET, update course with PATCH
flask_app/course_views.py
course_detail
kentblock/golf-api
0
python
@course_bp.route('/<int:id>', methods=['GET', 'PATCH']) def course_detail(id): 'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH' if (request.method == 'GET'): course = Course.query.get(id) if course: return (jsonify(course.detail_format()), 200) abort(404, f'Course with id: {id} does not exist.') if (request.method == 'PATCH'): pass
@course_bp.route('/<int:id>', methods=['GET', 'PATCH']) def course_detail(id): 'Course detail endpoint, retrieve data for course with GET, update \n course with PATCH' if (request.method == 'GET'): course = Course.query.get(id) if course: return (jsonify(course.detail_format()), 200) abort(404, f'Course with id: {id} does not exist.') if (request.method == 'PATCH'): pass<|docstring|>Course detail endpoint, retrieve data for course with GET, update course with PATCH<|endoftext|>
f7c898f93eefc8913a5787192917286c5987b67fea856310018dfb80f0c549af
@course_bp.route('/<int:id>/holes', methods=['GET', 'POST']) def retrieve_holes(id): 'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.' course = Course.query.get(id) if (not course): return abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'GET'): if (not course.holes): abort(404, 'No holes for this course currently in the database') formatted_holes = [hole.format() for hole in course.holes] return (jsonify(formatted_holes), 200) if (request.method == 'POST'): data = request.get_json(force=True) for hole_item in data: try: tees_list = [] if ('tees' in hole_item.keys()): tees_list = hole_item.pop('tees') hole = Hole(course=course, **hole_item) db.session.add(hole) for tee_item in tees_list: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() yardage = Yardage(hole=hole, tee=tee, yardage=tee_item['yardage']) db.session.add(yardage) except DBAPIError as ex: db.session.rollback() abort(400, f'''The following exception was raise while attempting to add holes to the database. {str(ex)}''') try: db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'''The following exception was raise while attempting to add holes to the database. {str(ex)}''') return Response(headers={'Location': url_for('courses.retrieve_holes', id=id)}, status=201)
Retrieves holes for course with given id, you can also add holes for a course with a POST request, one at a time, or in bulk.
flask_app/course_views.py
retrieve_holes
kentblock/golf-api
0
python
@course_bp.route('/<int:id>/holes', methods=['GET', 'POST']) def retrieve_holes(id): 'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.' course = Course.query.get(id) if (not course): return abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'GET'): if (not course.holes): abort(404, 'No holes for this course currently in the database') formatted_holes = [hole.format() for hole in course.holes] return (jsonify(formatted_holes), 200) if (request.method == 'POST'): data = request.get_json(force=True) for hole_item in data: try: tees_list = [] if ('tees' in hole_item.keys()): tees_list = hole_item.pop('tees') hole = Hole(course=course, **hole_item) db.session.add(hole) for tee_item in tees_list: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() yardage = Yardage(hole=hole, tee=tee, yardage=tee_item['yardage']) db.session.add(yardage) except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception was raise while attempting to add holes to the database. {str(ex)}') try: db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception was raise while attempting to add holes to the database. {str(ex)}') return Response(headers={'Location': url_for('courses.retrieve_holes', id=id)}, status=201)
@course_bp.route('/<int:id>/holes', methods=['GET', 'POST']) def retrieve_holes(id): 'Retrieves holes for course with given id, you can also add holes\n for a course with a POST request, one at a time, or in bulk.' course = Course.query.get(id) if (not course): return abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'GET'): if (not course.holes): abort(404, 'No holes for this course currently in the database') formatted_holes = [hole.format() for hole in course.holes] return (jsonify(formatted_holes), 200) if (request.method == 'POST'): data = request.get_json(force=True) for hole_item in data: try: tees_list = [] if ('tees' in hole_item.keys()): tees_list = hole_item.pop('tees') hole = Hole(course=course, **hole_item) db.session.add(hole) for tee_item in tees_list: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() yardage = Yardage(hole=hole, tee=tee, yardage=tee_item['yardage']) db.session.add(yardage) except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception was raise while attempting to add holes to the database. {str(ex)}') try: db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception was raise while attempting to add holes to the database. {str(ex)}') return Response(headers={'Location': url_for('courses.retrieve_holes', id=id)}, status=201)<|docstring|>Retrieves holes for course with given id, you can also add holes for a course with a POST request, one at a time, or in bulk.<|endoftext|>
302eedcc8f452579eb9fc149f122a7fbcf883fbce97cbd7a26a3460aa42a62d1
@course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH']) def hole_detail(id, hole_id): 'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.' course = Course.query.get(id) if (not course): abort(404, f'Cource with id: {id} was not found.') hole = Hole.query.get(hole_id) if (not hole): abort(404, f'Hole with id: {hole_id} was not found.') if (request.method == 'GET'): return (jsonify(hole.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) tee_items = data.pop('tees', None) if tee_items: for tee_item in tee_items: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() if (not tee): abort(400, 'Bad request tee does not exist') yardage = Yardage.query.get((hole.id, tee.id)) try: if (not yardage): yardage = Yardage(tee=tee, hole=hole, yardage=0) yardage.yardage = tee_item['yardage'] db.session.add(yardage) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'''The following exception occurred when attempting to update the hole record in the database. {str(ex)}''') try: for key in data.keys(): setattr(hole, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'''The following exception occurred when attempting to update the hole object: {ex}''') return (jsonify({}), 201)
Endpoint for hole detail, update a hole record with a PATCH request, retrieve course data with a GET request.
flask_app/course_views.py
hole_detail
kentblock/golf-api
0
python
@course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH']) def hole_detail(id, hole_id): 'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.' course = Course.query.get(id) if (not course): abort(404, f'Cource with id: {id} was not found.') hole = Hole.query.get(hole_id) if (not hole): abort(404, f'Hole with id: {hole_id} was not found.') if (request.method == 'GET'): return (jsonify(hole.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) tee_items = data.pop('tees', None) if tee_items: for tee_item in tee_items: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() if (not tee): abort(400, 'Bad request tee does not exist') yardage = Yardage.query.get((hole.id, tee.id)) try: if (not yardage): yardage = Yardage(tee=tee, hole=hole, yardage=0) yardage.yardage = tee_item['yardage'] db.session.add(yardage) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the hole record in the database. {str(ex)}') try: for key in data.keys(): setattr(hole, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the hole object: {ex}') return (jsonify({}), 201)
@course_bp.route('/<int:id>/holes/<int:hole_id>', methods=['GET', 'PATCH']) def hole_detail(id, hole_id): 'Endpoint for hole detail, update a hole record with a PATCH request, \n retrieve course data with a GET request.' course = Course.query.get(id) if (not course): abort(404, f'Cource with id: {id} was not found.') hole = Hole.query.get(hole_id) if (not hole): abort(404, f'Hole with id: {hole_id} was not found.') if (request.method == 'GET'): return (jsonify(hole.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) tee_items = data.pop('tees', None) if tee_items: for tee_item in tee_items: tee = Tee.query.filter_by(course=course, colour=tee_item['colour']).first() if (not tee): abort(400, 'Bad request tee does not exist') yardage = Yardage.query.get((hole.id, tee.id)) try: if (not yardage): yardage = Yardage(tee=tee, hole=hole, yardage=0) yardage.yardage = tee_item['yardage'] db.session.add(yardage) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the hole record in the database. {str(ex)}') try: for key in data.keys(): setattr(hole, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the hole object: {ex}') return (jsonify({}), 201)<|docstring|>Endpoint for hole detail, update a hole record with a PATCH request, retrieve course data with a GET request.<|endoftext|>
4a3f2b852e0e027d9782a36133e91dfbb0e5057827c760274130eddb81ecd7fe
@course_bp.route('/<int:id>/tees', methods=['GET', 'POST']) def retrieve_tees(id): 'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST' course = Course.query.get(id) if (not course): abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'POST'): data = request.get_json(force=True) try: tee = Tee(course=course, **data) db.session.add(tee) db.session.commit() tee_id = tee.id except DBAPIError as ex: db.session.rollback() abort(400, f'''The following error occurred when attempting to add the scorecard to the database. {str(ex)}''') return Response(headers={'Location': url_for('courses.tee_detail', id=course.id, tee_id=tee_id)}, status=201) if (request.method == 'GET'): print(f'course.tees {course.tees}') formatted_tees = [tee.format() for tee in course.tees] if (not formatted_tees): abort(404, f'No tees exist for course with id: {id}.') return (jsonify(formatted_tees), 200)
Endpoint for the tees of a course, retrieve all tees with a GET, add a new tee to the course with a POST
flask_app/course_views.py
retrieve_tees
kentblock/golf-api
0
python
@course_bp.route('/<int:id>/tees', methods=['GET', 'POST']) def retrieve_tees(id): 'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST' course = Course.query.get(id) if (not course): abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'POST'): data = request.get_json(force=True) try: tee = Tee(course=course, **data) db.session.add(tee) db.session.commit() tee_id = tee.id except DBAPIError as ex: db.session.rollback() abort(400, f'The following error occurred when attempting to add the scorecard to the database. {str(ex)}') return Response(headers={'Location': url_for('courses.tee_detail', id=course.id, tee_id=tee_id)}, status=201) if (request.method == 'GET'): print(f'course.tees {course.tees}') formatted_tees = [tee.format() for tee in course.tees] if (not formatted_tees): abort(404, f'No tees exist for course with id: {id}.') return (jsonify(formatted_tees), 200)
@course_bp.route('/<int:id>/tees', methods=['GET', 'POST']) def retrieve_tees(id): 'Endpoint for the tees of a course, retrieve all tees with a GET, \n add a new tee to the course with a POST' course = Course.query.get(id) if (not course): abort(404, f'Course with id: {id}, does not exist.') if (request.method == 'POST'): data = request.get_json(force=True) try: tee = Tee(course=course, **data) db.session.add(tee) db.session.commit() tee_id = tee.id except DBAPIError as ex: db.session.rollback() abort(400, f'The following error occurred when attempting to add the scorecard to the database. {str(ex)}') return Response(headers={'Location': url_for('courses.tee_detail', id=course.id, tee_id=tee_id)}, status=201) if (request.method == 'GET'): print(f'course.tees {course.tees}') formatted_tees = [tee.format() for tee in course.tees] if (not formatted_tees): abort(404, f'No tees exist for course with id: {id}.') return (jsonify(formatted_tees), 200)<|docstring|>Endpoint for the tees of a course, retrieve all tees with a GET, add a new tee to the course with a POST<|endoftext|>
c99f31cdc7dbaa21e122758109b78f842c47bd1723c84e60e569227850961141
@course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH']) def tee_detail(id, tee_id): 'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH' course = Course.query.get(id) tee = Tee.query.get(tee_id) if ((not course) or (not tee)): abort(404, 'Tee does not exist') if (request.method == 'GET'): return (jsonify(tee.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) if ('colour' in data.keys()): abort(400, "Error, you cannot change a tee's colour.") try: for key in data.keys(): setattr(tee, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'''The following exception occurred when attempting to update the tee object: {ex}''') return (jsonify({}), 201)
Endpoint for tee detail, retrieve detailed tee data with a GET, update tee detail with a PATCH
flask_app/course_views.py
tee_detail
kentblock/golf-api
0
python
@course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH']) def tee_detail(id, tee_id): 'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH' course = Course.query.get(id) tee = Tee.query.get(tee_id) if ((not course) or (not tee)): abort(404, 'Tee does not exist') if (request.method == 'GET'): return (jsonify(tee.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) if ('colour' in data.keys()): abort(400, "Error, you cannot change a tee's colour.") try: for key in data.keys(): setattr(tee, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the tee object: {ex}') return (jsonify({}), 201)
@course_bp.route('<id>/tees/<tee_id>', methods=['GET', 'PATCH']) def tee_detail(id, tee_id): 'Endpoint for tee detail, retrieve detailed tee data with a GET, \n update tee detail with a PATCH' course = Course.query.get(id) tee = Tee.query.get(tee_id) if ((not course) or (not tee)): abort(404, 'Tee does not exist') if (request.method == 'GET'): return (jsonify(tee.detail_format()), 200) if (request.method == 'PATCH'): data = request.get_json(force=True) if ('colour' in data.keys()): abort(400, "Error, you cannot change a tee's colour.") try: for key in data.keys(): setattr(tee, key, data[key]) db.session.commit() except DBAPIError as ex: db.session.rollback() abort(400, f'The following exception occurred when attempting to update the tee object: {ex}') return (jsonify({}), 201)<|docstring|>Endpoint for tee detail, retrieve detailed tee data with a GET, update tee detail with a PATCH<|endoftext|>
9791826c6f930b21d685eda574f2613146cd503a6c44342350cb66f8dd8d0cb5
def testV1NonResourceRule(self): '\n Test V1NonResourceRule\n ' pass
Test V1NonResourceRule
kubernetes/test/test_v1_non_resource_rule.py
testV1NonResourceRule
zq-david-wang/python
1
python
def testV1NonResourceRule(self): '\n \n ' pass
def testV1NonResourceRule(self): '\n \n ' pass<|docstring|>Test V1NonResourceRule<|endoftext|>
15896c441b8fe6e1467186e86e54cdfc271a361532e210c3ec6555dc8a5d693f
@register.inclusion_tag('analytics/tracker.html') def show_tracker(secure=False): '\n Output the analytics tracker code.\n ' google = getattr(settings, 'ANALYTICS', {}) if google: analytics_code = google.get('ANALYTICS_CODE') if analytics_code: return {'analytics_code': analytics_code} return {}
Output the analytics tracker code.
apps/sso/accounts/templatetags/analytics.py
show_tracker
g10f/sso
3
python
@register.inclusion_tag('analytics/tracker.html') def show_tracker(secure=False): '\n \n ' google = getattr(settings, 'ANALYTICS', {}) if google: analytics_code = google.get('ANALYTICS_CODE') if analytics_code: return {'analytics_code': analytics_code} return {}
@register.inclusion_tag('analytics/tracker.html') def show_tracker(secure=False): '\n \n ' google = getattr(settings, 'ANALYTICS', {}) if google: analytics_code = google.get('ANALYTICS_CODE') if analytics_code: return {'analytics_code': analytics_code} return {}<|docstring|>Output the analytics tracker code.<|endoftext|>
b8930fdb949b4267f8b530cd2f50327fd4abc4b2e7cd3cebcf3c421b01ac9ebb
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5): '\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n ' if isinstance(factors[0], tuple): factors = [f[0] for f in factors] if (len(factors) == 1): return factors[0] points = {x: v} symbols = (dom.symbols if hasattr(dom, 'symbols') else []) t = QQ(1, 10) for n in range((bound ** len(symbols))): prec1 = 10 n_temp = n for s in symbols: points[s] = (n_temp % bound) n_temp = (n_temp // bound) while True: candidates = [] eps = (t ** (prec1 // 2)) for f in factors: if (abs(f.as_expr().evalf(prec1, points)) < eps): candidates.append(f) if candidates: factors = candidates if (len(factors) == 1): return factors[0] if (prec1 > prec): break prec1 *= 2 raise NotImplementedError(('multiple candidates for the minimal polynomial of %s' % v))
Return a factor having root ``v`` It is assumed that one of the factors has root ``v``.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_choose_factor
RivtLib/replit01
603
python
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5): '\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n ' if isinstance(factors[0], tuple): factors = [f[0] for f in factors] if (len(factors) == 1): return factors[0] points = {x: v} symbols = (dom.symbols if hasattr(dom, 'symbols') else []) t = QQ(1, 10) for n in range((bound ** len(symbols))): prec1 = 10 n_temp = n for s in symbols: points[s] = (n_temp % bound) n_temp = (n_temp // bound) while True: candidates = [] eps = (t ** (prec1 // 2)) for f in factors: if (abs(f.as_expr().evalf(prec1, points)) < eps): candidates.append(f) if candidates: factors = candidates if (len(factors) == 1): return factors[0] if (prec1 > prec): break prec1 *= 2 raise NotImplementedError(('multiple candidates for the minimal polynomial of %s' % v))
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5): '\n Return a factor having root ``v``\n It is assumed that one of the factors has root ``v``.\n ' if isinstance(factors[0], tuple): factors = [f[0] for f in factors] if (len(factors) == 1): return factors[0] points = {x: v} symbols = (dom.symbols if hasattr(dom, 'symbols') else []) t = QQ(1, 10) for n in range((bound ** len(symbols))): prec1 = 10 n_temp = n for s in symbols: points[s] = (n_temp % bound) n_temp = (n_temp // bound) while True: candidates = [] eps = (t ** (prec1 // 2)) for f in factors: if (abs(f.as_expr().evalf(prec1, points)) < eps): candidates.append(f) if candidates: factors = candidates if (len(factors) == 1): return factors[0] if (prec1 > prec): break prec1 *= 2 raise NotImplementedError(('multiple candidates for the minimal polynomial of %s' % v))<|docstring|>Return a factor having root ``v`` It is assumed that one of the factors has root ``v``.<|endoftext|>
54a832c48d80061ff3b1adee1eb320faa203fddb63987d2b02f25ae8a9c38854
def _separate_sq(p): '\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to eliminate ``sqrt(g)``\n\n See simplify.simplify.split_surds and polytools.sqf_norm.\n\n Examples\n ========\n\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> from sympy.polys.numberfields import _separate_sq\n >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)\n >>> p = _separate_sq(p); p\n -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8\n >>> p = _separate_sq(p); p\n -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20\n >>> p = _separate_sq(p); p\n -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400\n\n ' from sympy.utilities.iterables import sift def is_sqrt(expr): return (expr.is_Pow and (expr.exp is S.Half)) a = [] for y in p.args: if (not y.is_Mul): if is_sqrt(y): a.append((S.One, (y ** 2))) elif y.is_Atom: a.append((y, S.One)) elif (y.is_Pow and y.exp.is_integer): a.append((y, S.One)) else: raise NotImplementedError continue (T, F) = sift(y.args, is_sqrt, binary=True) a.append((Mul(*F), (Mul(*T) ** 2))) a.sort(key=(lambda z: z[1])) if (a[(- 1)][1] is S.One): return p surds = [z for (y, z) in a] for i in range(len(surds)): if (surds[i] != 1): break (g, b1, b2) = _split_gcd(*surds[i:]) a1 = [] a2 = [] for (y, z) in a: if (z in b1): a1.append((y * (z ** S.Half))) else: a2.append((y * (z ** S.Half))) p1 = Add(*a1) p2 = Add(*a2) p = (_mexpand((p1 ** 2)) - _mexpand((p2 ** 2))) return p
helper function for ``_minimal_polynomial_sq`` It selects a rational ``g`` such that the polynomial ``p`` consists of a sum of terms whose surds squared have gcd equal to ``g`` and a sum of terms with surds squared prime with ``g``; then it takes the field norm to eliminate ``sqrt(g)`` See simplify.simplify.split_surds and polytools.sqf_norm. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x >>> from sympy.polys.numberfields import _separate_sq >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7) >>> p = _separate_sq(p); p -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8 >>> p = _separate_sq(p); p -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20 >>> p = _separate_sq(p); p -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_separate_sq
RivtLib/replit01
603
python
def _separate_sq(p): '\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to eliminate ``sqrt(g)``\n\n See simplify.simplify.split_surds and polytools.sqf_norm.\n\n Examples\n ========\n\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> from sympy.polys.numberfields import _separate_sq\n >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)\n >>> p = _separate_sq(p); p\n -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8\n >>> p = _separate_sq(p); p\n -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20\n >>> p = _separate_sq(p); p\n -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400\n\n ' from sympy.utilities.iterables import sift def is_sqrt(expr): return (expr.is_Pow and (expr.exp is S.Half)) a = [] for y in p.args: if (not y.is_Mul): if is_sqrt(y): a.append((S.One, (y ** 2))) elif y.is_Atom: a.append((y, S.One)) elif (y.is_Pow and y.exp.is_integer): a.append((y, S.One)) else: raise NotImplementedError continue (T, F) = sift(y.args, is_sqrt, binary=True) a.append((Mul(*F), (Mul(*T) ** 2))) a.sort(key=(lambda z: z[1])) if (a[(- 1)][1] is S.One): return p surds = [z for (y, z) in a] for i in range(len(surds)): if (surds[i] != 1): break (g, b1, b2) = _split_gcd(*surds[i:]) a1 = [] a2 = [] for (y, z) in a: if (z in b1): a1.append((y * (z ** S.Half))) else: a2.append((y * (z ** S.Half))) p1 = Add(*a1) p2 = Add(*a2) p = (_mexpand((p1 ** 2)) - _mexpand((p2 ** 2))) return p
def _separate_sq(p): '\n helper function for ``_minimal_polynomial_sq``\n\n It selects a rational ``g`` such that the polynomial ``p``\n consists of a sum of terms whose surds squared have gcd equal to ``g``\n and a sum of terms with surds squared prime with ``g``;\n then it takes the field norm to eliminate ``sqrt(g)``\n\n See simplify.simplify.split_surds and polytools.sqf_norm.\n\n Examples\n ========\n\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> from sympy.polys.numberfields import _separate_sq\n >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)\n >>> p = _separate_sq(p); p\n -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8\n >>> p = _separate_sq(p); p\n -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20\n >>> p = _separate_sq(p); p\n -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400\n\n ' from sympy.utilities.iterables import sift def is_sqrt(expr): return (expr.is_Pow and (expr.exp is S.Half)) a = [] for y in p.args: if (not y.is_Mul): if is_sqrt(y): a.append((S.One, (y ** 2))) elif y.is_Atom: a.append((y, S.One)) elif (y.is_Pow and y.exp.is_integer): a.append((y, S.One)) else: raise NotImplementedError continue (T, F) = sift(y.args, is_sqrt, binary=True) a.append((Mul(*F), (Mul(*T) ** 2))) a.sort(key=(lambda z: z[1])) if (a[(- 1)][1] is S.One): return p surds = [z for (y, z) in a] for i in range(len(surds)): if (surds[i] != 1): break (g, b1, b2) = _split_gcd(*surds[i:]) a1 = [] a2 = [] for (y, z) in a: if (z in b1): a1.append((y * (z ** S.Half))) else: a2.append((y * (z ** S.Half))) p1 = Add(*a1) p2 = Add(*a2) p = (_mexpand((p1 ** 2)) - _mexpand((p2 ** 2))) return p<|docstring|>helper function for ``_minimal_polynomial_sq`` It selects a rational ``g`` such that the polynomial ``p`` consists of a sum of terms whose surds squared have gcd equal to ``g`` and a sum of terms with surds squared prime with ``g``; then it takes the field norm to eliminate ``sqrt(g)`` See simplify.simplify.split_surds and polytools.sqf_norm. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x >>> from sympy.polys.numberfields import _separate_sq >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7) >>> p = _separate_sq(p); p -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8 >>> p = _separate_sq(p); p -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20 >>> p = _separate_sq(p); p -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400<|endoftext|>
2b6b0726943a4499275b166a375f9a7570c10bc8113b080cdfc7bf6ebb1b33e4
def _minimal_polynomial_sq(p, n, x): '\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> from sympy.polys.numberfields import _minimal_polynomial_sq\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> q = 1 + sqrt(2) + sqrt(3)\n >>> _minimal_polynomial_sq(q, 3, x)\n x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8\n\n ' from sympy.simplify.simplify import _is_sum_surds p = sympify(p) n = sympify(n) if ((not n.is_Integer) or (not (n > 0)) or (not _is_sum_surds(p))): return None pn = (p ** Rational(1, n)) p -= x while 1: p1 = _separate_sq(p) if (p1 is p): p = p1.subs({x: (x ** n)}) break else: p = p1 if (n == 1): p1 = Poly(p) if (p.coeff((x ** p1.degree(x))) < 0): p = (- p) p = p.primitive()[1] return p factors = factor_list(p)[1] result = _choose_factor(factors, x, pn) return result
Returns the minimal polynomial for the ``nth-root`` of a sum of surds or ``None`` if it fails. Parameters ========== p : sum of surds n : positive integer x : variable of the returned polynomial Examples ======== >>> from sympy.polys.numberfields import _minimal_polynomial_sq >>> from sympy import sqrt >>> from sympy.abc import x >>> q = 1 + sqrt(2) + sqrt(3) >>> _minimal_polynomial_sq(q, 3, x) x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minimal_polynomial_sq
RivtLib/replit01
603
python
def _minimal_polynomial_sq(p, n, x): '\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> from sympy.polys.numberfields import _minimal_polynomial_sq\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> q = 1 + sqrt(2) + sqrt(3)\n >>> _minimal_polynomial_sq(q, 3, x)\n x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8\n\n ' from sympy.simplify.simplify import _is_sum_surds p = sympify(p) n = sympify(n) if ((not n.is_Integer) or (not (n > 0)) or (not _is_sum_surds(p))): return None pn = (p ** Rational(1, n)) p -= x while 1: p1 = _separate_sq(p) if (p1 is p): p = p1.subs({x: (x ** n)}) break else: p = p1 if (n == 1): p1 = Poly(p) if (p.coeff((x ** p1.degree(x))) < 0): p = (- p) p = p.primitive()[1] return p factors = factor_list(p)[1] result = _choose_factor(factors, x, pn) return result
def _minimal_polynomial_sq(p, n, x): '\n Returns the minimal polynomial for the ``nth-root`` of a sum of surds\n or ``None`` if it fails.\n\n Parameters\n ==========\n\n p : sum of surds\n n : positive integer\n x : variable of the returned polynomial\n\n Examples\n ========\n\n >>> from sympy.polys.numberfields import _minimal_polynomial_sq\n >>> from sympy import sqrt\n >>> from sympy.abc import x\n >>> q = 1 + sqrt(2) + sqrt(3)\n >>> _minimal_polynomial_sq(q, 3, x)\n x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8\n\n ' from sympy.simplify.simplify import _is_sum_surds p = sympify(p) n = sympify(n) if ((not n.is_Integer) or (not (n > 0)) or (not _is_sum_surds(p))): return None pn = (p ** Rational(1, n)) p -= x while 1: p1 = _separate_sq(p) if (p1 is p): p = p1.subs({x: (x ** n)}) break else: p = p1 if (n == 1): p1 = Poly(p) if (p.coeff((x ** p1.degree(x))) < 0): p = (- p) p = p.primitive()[1] return p factors = factor_list(p)[1] result = _choose_factor(factors, x, pn) return result<|docstring|>Returns the minimal polynomial for the ``nth-root`` of a sum of surds or ``None`` if it fails. Parameters ========== p : sum of surds n : positive integer x : variable of the returned polynomial Examples ======== >>> from sympy.polys.numberfields import _minimal_polynomial_sq >>> from sympy import sqrt >>> from sympy.abc import x >>> q = 1 + sqrt(2) + sqrt(3) >>> _minimal_polynomial_sq(q, 3, x) x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8<|endoftext|>
0ee1ac210be56e4e5b733b4de3d27cd8116376def6e17ec8b73ab7cdb7efef11
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None): '\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom: ground domain\n mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None\n\n Examples\n ========\n\n >>> from sympy import sqrt, Add, Mul, QQ\n >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element\n >>> from sympy.abc import x, y\n >>> p1 = sqrt(sqrt(2) + 1)\n >>> p2 = sqrt(sqrt(2) - 1)\n >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)\n x - 1\n >>> q1 = sqrt(y)\n >>> q2 = 1 / y\n >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))\n x**2*y**2 - 2*x*y - y**3 + 1\n\n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Resultant\n .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638\n "Degrees of sums in a separable field extension".\n\n ' y = Dummy(str(x)) if (mp1 is None): mp1 = _minpoly_compose(ex1, x, dom) if (mp2 is None): mp2 = _minpoly_compose(ex2, y, dom) else: mp2 = mp2.subs({x: y}) if (op is Add): if (dom == QQ): (R, X) = ring('X', QQ) p1 = R(dict_from_expr(mp1)[0]) p2 = R(dict_from_expr(mp2)[0]) else: ((p1, p2), _) = parallel_poly_from_expr((mp1, (x - y)), x, y) r = p1.compose(p2) mp1a = r.as_expr() elif (op is Mul): mp1a = _muly(mp1, x, y) else: raise NotImplementedError('option not available') if ((op is Mul) or (dom != QQ)): r = resultant(mp1a, mp2, gens=[y, x]) else: r = rs_compose_add(p1, p2) r = expr_from_dict(r.as_expr_dict(), x) deg1 = degree(mp1, x) deg2 = degree(mp2, y) if (((op is Mul) and (deg1 == 1)) or (deg2 == 1)): return r r = Poly(r, x, domain=dom) (_, factors) = r.factor_list() res = _choose_factor(factors, x, op(ex1, ex2), dom) return res.as_expr()
return the minimal polynomial for ``op(ex1, ex2)`` Parameters ========== op : operation ``Add`` or ``Mul`` ex1, ex2 : expressions for the algebraic elements x : indeterminate of the polynomials dom: ground domain mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None Examples ======== >>> from sympy import sqrt, Add, Mul, QQ >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element >>> from sympy.abc import x, y >>> p1 = sqrt(sqrt(2) + 1) >>> p2 = sqrt(sqrt(2) - 1) >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ) x - 1 >>> q1 = sqrt(y) >>> q2 = 1 / y >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y)) x**2*y**2 - 2*x*y - y**3 + 1 References ========== .. [1] https://en.wikipedia.org/wiki/Resultant .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638 "Degrees of sums in a separable field extension".
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_op_algebraic_element
RivtLib/replit01
603
python
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None): '\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom: ground domain\n mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None\n\n Examples\n ========\n\n >>> from sympy import sqrt, Add, Mul, QQ\n >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element\n >>> from sympy.abc import x, y\n >>> p1 = sqrt(sqrt(2) + 1)\n >>> p2 = sqrt(sqrt(2) - 1)\n >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)\n x - 1\n >>> q1 = sqrt(y)\n >>> q2 = 1 / y\n >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))\n x**2*y**2 - 2*x*y - y**3 + 1\n\n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Resultant\n .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638\n "Degrees of sums in a separable field extension".\n\n ' y = Dummy(str(x)) if (mp1 is None): mp1 = _minpoly_compose(ex1, x, dom) if (mp2 is None): mp2 = _minpoly_compose(ex2, y, dom) else: mp2 = mp2.subs({x: y}) if (op is Add): if (dom == QQ): (R, X) = ring('X', QQ) p1 = R(dict_from_expr(mp1)[0]) p2 = R(dict_from_expr(mp2)[0]) else: ((p1, p2), _) = parallel_poly_from_expr((mp1, (x - y)), x, y) r = p1.compose(p2) mp1a = r.as_expr() elif (op is Mul): mp1a = _muly(mp1, x, y) else: raise NotImplementedError('option not available') if ((op is Mul) or (dom != QQ)): r = resultant(mp1a, mp2, gens=[y, x]) else: r = rs_compose_add(p1, p2) r = expr_from_dict(r.as_expr_dict(), x) deg1 = degree(mp1, x) deg2 = degree(mp2, y) if (((op is Mul) and (deg1 == 1)) or (deg2 == 1)): return r r = Poly(r, x, domain=dom) (_, factors) = r.factor_list() res = _choose_factor(factors, x, op(ex1, ex2), dom) return res.as_expr()
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None): '\n return the minimal polynomial for ``op(ex1, ex2)``\n\n Parameters\n ==========\n\n op : operation ``Add`` or ``Mul``\n ex1, ex2 : expressions for the algebraic elements\n x : indeterminate of the polynomials\n dom: ground domain\n mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None\n\n Examples\n ========\n\n >>> from sympy import sqrt, Add, Mul, QQ\n >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element\n >>> from sympy.abc import x, y\n >>> p1 = sqrt(sqrt(2) + 1)\n >>> p2 = sqrt(sqrt(2) - 1)\n >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)\n x - 1\n >>> q1 = sqrt(y)\n >>> q2 = 1 / y\n >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))\n x**2*y**2 - 2*x*y - y**3 + 1\n\n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Resultant\n .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638\n "Degrees of sums in a separable field extension".\n\n ' y = Dummy(str(x)) if (mp1 is None): mp1 = _minpoly_compose(ex1, x, dom) if (mp2 is None): mp2 = _minpoly_compose(ex2, y, dom) else: mp2 = mp2.subs({x: y}) if (op is Add): if (dom == QQ): (R, X) = ring('X', QQ) p1 = R(dict_from_expr(mp1)[0]) p2 = R(dict_from_expr(mp2)[0]) else: ((p1, p2), _) = parallel_poly_from_expr((mp1, (x - y)), x, y) r = p1.compose(p2) mp1a = r.as_expr() elif (op is Mul): mp1a = _muly(mp1, x, y) else: raise NotImplementedError('option not available') if ((op is Mul) or (dom != QQ)): r = resultant(mp1a, mp2, gens=[y, x]) else: r = rs_compose_add(p1, p2) r = expr_from_dict(r.as_expr_dict(), x) deg1 = degree(mp1, x) deg2 = degree(mp2, y) if (((op is Mul) and (deg1 == 1)) or (deg2 == 1)): return r r = Poly(r, x, domain=dom) (_, factors) = r.factor_list() res = _choose_factor(factors, x, op(ex1, ex2), dom) return res.as_expr()<|docstring|>return the minimal polynomial for ``op(ex1, ex2)`` Parameters ========== op : operation ``Add`` or ``Mul`` ex1, ex2 : expressions for the algebraic elements x : indeterminate of the polynomials dom: ground domain mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None Examples ======== >>> from sympy import sqrt, Add, Mul, QQ >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element >>> from sympy.abc import x, y >>> p1 = sqrt(sqrt(2) + 1) >>> p2 = sqrt(sqrt(2) - 1) >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ) x - 1 >>> q1 = sqrt(y) >>> q2 = 1 / y >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y)) x**2*y**2 - 2*x*y - y**3 + 1 References ========== .. [1] https://en.wikipedia.org/wiki/Resultant .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638 "Degrees of sums in a separable field extension".<|endoftext|>
aecbdc2f93ace1fc02954b0694bc9cc9ed7cc62579e50cb4a9843e6d7900c3d4
def _invertx(p, x): '\n Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``\n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)
Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_invertx
RivtLib/replit01
603
python
def _invertx(p, x): '\n \n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)
def _invertx(p, x): '\n \n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [(c * (x ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)<|docstring|>Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``<|endoftext|>
baca23eea9540fd31e8e3d028e160bcb5642f5530e5cf80ee6106406a28aac11
def _muly(p, x, y): '\n Returns ``_mexpand(y**deg*p.subs({x:x / y}))``\n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)
Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_muly
RivtLib/replit01
603
python
def _muly(p, x, y): '\n \n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)
def _muly(p, x, y): '\n \n ' p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [((c * (x ** i)) * (y ** (n - i))) for ((i,), c) in p1.terms()] return Add(*a)<|docstring|>Returns ``_mexpand(y**deg*p.subs({x:x / y}))``<|endoftext|>
d5d3c39472349ad531a7733fc5efe8c4fa4fd4dfc72004b31f2b26ee8d6a59a7
def _minpoly_pow(ex, pw, x, dom, mp=None): '\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> from sympy import sqrt, QQ, Rational\n >>> from sympy.polys.numberfields import _minpoly_pow, minpoly\n >>> from sympy.abc import x, y\n >>> p = sqrt(1 + sqrt(2))\n >>> _minpoly_pow(p, 2, x, QQ)\n x**2 - 2*x - 1\n >>> minpoly(p**2, x)\n x**2 - 2*x - 1\n >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))\n x**3 - y\n >>> minpoly(y**Rational(1, 3), x)\n x**3 - y\n\n ' pw = sympify(pw) if (not mp): mp = _minpoly_compose(ex, x, dom) if (not pw.is_rational): raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) if (pw < 0): if (mp == x): raise ZeroDivisionError(('%s is zero' % ex)) mp = _invertx(mp, x) if (pw == (- 1)): return mp pw = (- pw) ex = (1 / ex) y = Dummy(str(x)) mp = mp.subs({x: y}) (n, d) = pw.as_numer_denom() res = Poly(resultant(mp, ((x ** d) - (y ** n)), gens=[y]), x, domain=dom) (_, factors) = res.factor_list() res = _choose_factor(factors, x, (ex ** pw), dom) return res.as_expr()
Returns ``minpoly(ex**pw, x)`` Parameters ========== ex : algebraic element pw : rational number x : indeterminate of the polynomial dom: ground domain mp : minimal polynomial of ``p`` Examples ======== >>> from sympy import sqrt, QQ, Rational >>> from sympy.polys.numberfields import _minpoly_pow, minpoly >>> from sympy.abc import x, y >>> p = sqrt(1 + sqrt(2)) >>> _minpoly_pow(p, 2, x, QQ) x**2 - 2*x - 1 >>> minpoly(p**2, x) x**2 - 2*x - 1 >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y)) x**3 - y >>> minpoly(y**Rational(1, 3), x) x**3 - y
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_pow
RivtLib/replit01
603
python
def _minpoly_pow(ex, pw, x, dom, mp=None): '\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> from sympy import sqrt, QQ, Rational\n >>> from sympy.polys.numberfields import _minpoly_pow, minpoly\n >>> from sympy.abc import x, y\n >>> p = sqrt(1 + sqrt(2))\n >>> _minpoly_pow(p, 2, x, QQ)\n x**2 - 2*x - 1\n >>> minpoly(p**2, x)\n x**2 - 2*x - 1\n >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))\n x**3 - y\n >>> minpoly(y**Rational(1, 3), x)\n x**3 - y\n\n ' pw = sympify(pw) if (not mp): mp = _minpoly_compose(ex, x, dom) if (not pw.is_rational): raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) if (pw < 0): if (mp == x): raise ZeroDivisionError(('%s is zero' % ex)) mp = _invertx(mp, x) if (pw == (- 1)): return mp pw = (- pw) ex = (1 / ex) y = Dummy(str(x)) mp = mp.subs({x: y}) (n, d) = pw.as_numer_denom() res = Poly(resultant(mp, ((x ** d) - (y ** n)), gens=[y]), x, domain=dom) (_, factors) = res.factor_list() res = _choose_factor(factors, x, (ex ** pw), dom) return res.as_expr()
def _minpoly_pow(ex, pw, x, dom, mp=None): '\n Returns ``minpoly(ex**pw, x)``\n\n Parameters\n ==========\n\n ex : algebraic element\n pw : rational number\n x : indeterminate of the polynomial\n dom: ground domain\n mp : minimal polynomial of ``p``\n\n Examples\n ========\n\n >>> from sympy import sqrt, QQ, Rational\n >>> from sympy.polys.numberfields import _minpoly_pow, minpoly\n >>> from sympy.abc import x, y\n >>> p = sqrt(1 + sqrt(2))\n >>> _minpoly_pow(p, 2, x, QQ)\n x**2 - 2*x - 1\n >>> minpoly(p**2, x)\n x**2 - 2*x - 1\n >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))\n x**3 - y\n >>> minpoly(y**Rational(1, 3), x)\n x**3 - y\n\n ' pw = sympify(pw) if (not mp): mp = _minpoly_compose(ex, x, dom) if (not pw.is_rational): raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) if (pw < 0): if (mp == x): raise ZeroDivisionError(('%s is zero' % ex)) mp = _invertx(mp, x) if (pw == (- 1)): return mp pw = (- pw) ex = (1 / ex) y = Dummy(str(x)) mp = mp.subs({x: y}) (n, d) = pw.as_numer_denom() res = Poly(resultant(mp, ((x ** d) - (y ** n)), gens=[y]), x, domain=dom) (_, factors) = res.factor_list() res = _choose_factor(factors, x, (ex ** pw), dom) return res.as_expr()<|docstring|>Returns ``minpoly(ex**pw, x)`` Parameters ========== ex : algebraic element pw : rational number x : indeterminate of the polynomial dom: ground domain mp : minimal polynomial of ``p`` Examples ======== >>> from sympy import sqrt, QQ, Rational >>> from sympy.polys.numberfields import _minpoly_pow, minpoly >>> from sympy.abc import x, y >>> p = sqrt(1 + sqrt(2)) >>> _minpoly_pow(p, 2, x, QQ) x**2 - 2*x - 1 >>> minpoly(p**2, x) x**2 - 2*x - 1 >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y)) x**3 - y >>> minpoly(y**Rational(1, 3), x) x**3 - y<|endoftext|>
1660cd1aad49f767601b417579b199c95f10ec3e8071d675342d90ff3df617ab
def _minpoly_add(x, dom, *a): '\n returns ``minpoly(Add(*a), dom, x)``\n ' mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom) p = (a[0] + a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp) p = (p + px) return mp
returns ``minpoly(Add(*a), dom, x)``
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_add
RivtLib/replit01
603
python
def _minpoly_add(x, dom, *a): '\n \n ' mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom) p = (a[0] + a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp) p = (p + px) return mp
def _minpoly_add(x, dom, *a): '\n \n ' mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom) p = (a[0] + a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp) p = (p + px) return mp<|docstring|>returns ``minpoly(Add(*a), dom, x)``<|endoftext|>
262558677b3fd698d9ed4eeab5b117da7d4941a3737bee7efc281c504dc5b94c
def _minpoly_mul(x, dom, *a): '\n returns ``minpoly(Mul(*a), dom, x)``\n ' mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom) p = (a[0] * a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp) p = (p * px) return mp
returns ``minpoly(Mul(*a), dom, x)``
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_mul
RivtLib/replit01
603
python
def _minpoly_mul(x, dom, *a): '\n \n ' mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom) p = (a[0] * a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp) p = (p * px) return mp
def _minpoly_mul(x, dom, *a): '\n \n ' mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom) p = (a[0] * a[1]) for px in a[2:]: mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp) p = (p * px) return mp<|docstring|>returns ``minpoly(Mul(*a), dom, x)``<|endoftext|>
557737f853744626e4b00301b6b92ddfe1c3dd47093b1a897826c4451600d96c
def _minpoly_sin(ex, x): '\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: n = c.q q = sympify(n) if q.is_prime: a = dup_chebyshevt(n, ZZ) return Add(*[((x ** ((n - i) - 1)) * a[i]) for i in range(n)]) if (c.p == 1): if (q == 9): return ((((64 * (x ** 6)) - (96 * (x ** 4))) + (36 * (x ** 2))) - 3) if ((n % 2) == 1): a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = Add(*a) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res expr = (((1 - cos(((2 * c) * pi))) / 2) ** S.Half) res = _minpoly_compose(expr, x, QQ) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
Returns the minimal polynomial of ``sin(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_sin
RivtLib/replit01
603
python
def _minpoly_sin(ex, x): '\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: n = c.q q = sympify(n) if q.is_prime: a = dup_chebyshevt(n, ZZ) return Add(*[((x ** ((n - i) - 1)) * a[i]) for i in range(n)]) if (c.p == 1): if (q == 9): return ((((64 * (x ** 6)) - (96 * (x ** 4))) + (36 * (x ** 2))) - 3) if ((n % 2) == 1): a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = Add(*a) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res expr = (((1 - cos(((2 * c) * pi))) / 2) ** S.Half) res = _minpoly_compose(expr, x, QQ) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
def _minpoly_sin(ex, x): '\n Returns the minimal polynomial of ``sin(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: n = c.q q = sympify(n) if q.is_prime: a = dup_chebyshevt(n, ZZ) return Add(*[((x ** ((n - i) - 1)) * a[i]) for i in range(n)]) if (c.p == 1): if (q == 9): return ((((64 * (x ** 6)) - (96 * (x ** 4))) + (36 * (x ** 2))) - 3) if ((n % 2) == 1): a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = Add(*a) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res expr = (((1 - cos(((2 * c) * pi))) / 2) ** S.Half) res = _minpoly_compose(expr, x, QQ) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))<|docstring|>Returns the minimal polynomial of ``sin(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html<|endoftext|>
07d77096d0f44f92e6283744a15335467629a0d5d827b7980f7dd002ee03b4df
def _minpoly_cos(ex, x): '\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' from sympy import sqrt (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: if (c.p == 1): if (c.q == 7): return ((((8 * (x ** 3)) - (4 * (x ** 2))) - (4 * x)) + 1) if (c.q == 9): return (((8 * (x ** 3)) - (6 * x)) + 1) elif (c.p == 2): q = sympify(c.q) if q.is_prime: s = _minpoly_sin(ex, x) return _mexpand(s.subs({x: sqrt(((1 - x) / 2))})) n = int(c.q) a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = (Add(*a) - ((- 1) ** c.p)) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
Returns the minimal polynomial of ``cos(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_cos
RivtLib/replit01
603
python
def _minpoly_cos(ex, x): '\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' from sympy import sqrt (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: if (c.p == 1): if (c.q == 7): return ((((8 * (x ** 3)) - (4 * (x ** 2))) - (4 * x)) + 1) if (c.q == 9): return (((8 * (x ** 3)) - (6 * x)) + 1) elif (c.p == 2): q = sympify(c.q) if q.is_prime: s = _minpoly_sin(ex, x) return _mexpand(s.subs({x: sqrt(((1 - x) / 2))})) n = int(c.q) a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = (Add(*a) - ((- 1) ** c.p)) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
def _minpoly_cos(ex, x): '\n Returns the minimal polynomial of ``cos(ex)``\n see http://mathworld.wolfram.com/TrigonometryAngles.html\n ' from sympy import sqrt (c, a) = ex.args[0].as_coeff_Mul() if (a is pi): if c.is_rational: if (c.p == 1): if (c.q == 7): return ((((8 * (x ** 3)) - (4 * (x ** 2))) - (4 * x)) + 1) if (c.q == 9): return (((8 * (x ** 3)) - (6 * x)) + 1) elif (c.p == 2): q = sympify(c.q) if q.is_prime: s = _minpoly_sin(ex, x) return _mexpand(s.subs({x: sqrt(((1 - x) / 2))})) n = int(c.q) a = dup_chebyshevt(n, ZZ) a = [((x ** (n - i)) * a[i]) for i in range((n + 1))] r = (Add(*a) - ((- 1) ** c.p)) (_, factors) = factor_list(r) res = _choose_factor(factors, x, ex) return res raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))<|docstring|>Returns the minimal polynomial of ``cos(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html<|endoftext|>
f235692a6405e26abdeb4845d72d607ffb92badd0f1d46352d2867209b3db3b5
def _minpoly_exp(ex, x): '\n Returns the minimal polynomial of ``exp(ex)``\n ' (c, a) = ex.args[0].as_coeff_Mul() q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (- 1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) if (q == 6): return (((x ** 4) - (x ** 2)) + 1) if (q == 8): return ((x ** 8) + 1) if (q == 9): return (((x ** 6) - (x ** 3)) + 1) if (q == 10): return (((((x ** 8) - (x ** 6)) + (x ** 4)) - (x ** 2)) + 1) if q.is_prime: s = 0 for i in range(q): s += ((- x) ** i) return s factors = [cyclotomic_poly(i, x) for i in divisors((2 * q))] mp = _choose_factor(factors, x, ex) return mp else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
Returns the minimal polynomial of ``exp(ex)``
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_exp
RivtLib/replit01
603
python
def _minpoly_exp(ex, x): '\n \n ' (c, a) = ex.args[0].as_coeff_Mul() q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (- 1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) if (q == 6): return (((x ** 4) - (x ** 2)) + 1) if (q == 8): return ((x ** 8) + 1) if (q == 9): return (((x ** 6) - (x ** 3)) + 1) if (q == 10): return (((((x ** 8) - (x ** 6)) + (x ** 4)) - (x ** 2)) + 1) if q.is_prime: s = 0 for i in range(q): s += ((- x) ** i) return s factors = [cyclotomic_poly(i, x) for i in divisors((2 * q))] mp = _choose_factor(factors, x, ex) return mp else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))
def _minpoly_exp(ex, x): '\n \n ' (c, a) = ex.args[0].as_coeff_Mul() q = sympify(c.q) if (a == (I * pi)): if c.is_rational: if ((c.p == 1) or (c.p == (- 1))): if (q == 3): return (((x ** 2) - x) + 1) if (q == 4): return ((x ** 4) + 1) if (q == 6): return (((x ** 4) - (x ** 2)) + 1) if (q == 8): return ((x ** 8) + 1) if (q == 9): return (((x ** 6) - (x ** 3)) + 1) if (q == 10): return (((((x ** 8) - (x ** 6)) + (x ** 4)) - (x ** 2)) + 1) if q.is_prime: s = 0 for i in range(q): s += ((- x) ** i) return s factors = [cyclotomic_poly(i, x) for i in divisors((2 * q))] mp = _choose_factor(factors, x, ex) return mp else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex))<|docstring|>Returns the minimal polynomial of ``exp(ex)``<|endoftext|>
21a74cd718233e266b9379a1bbf8f44cf9fab17d46535c6519cfe4803bde5e68
def _minpoly_rootof(ex, x): '\n Returns the minimal polynomial of a ``CRootOf`` object.\n ' p = ex.expr p = p.subs({ex.poly.gens[0]: x}) (_, factors) = factor_list(p, x) result = _choose_factor(factors, x, ex) return result
Returns the minimal polynomial of a ``CRootOf`` object.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_rootof
RivtLib/replit01
603
python
def _minpoly_rootof(ex, x): '\n \n ' p = ex.expr p = p.subs({ex.poly.gens[0]: x}) (_, factors) = factor_list(p, x) result = _choose_factor(factors, x, ex) return result
def _minpoly_rootof(ex, x): '\n \n ' p = ex.expr p = p.subs({ex.poly.gens[0]: x}) (_, factors) = factor_list(p, x) result = _choose_factor(factors, x, ex) return result<|docstring|>Returns the minimal polynomial of a ``CRootOf`` object.<|endoftext|>
08f3351ee554cf0bff9af0e7c3caabec17497d0141d44820f0b2fd512a5a1c1b
def _minpoly_compose(ex, x, dom): '\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)\n x**2 - 2*x - 1\n >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)\n x**2*y**2 - 2*x*y - y**3 + 1\n\n ' if ex.is_Rational: return ((ex.q * x) - ex.p) if (ex is I): (_, factors) = factor_list(((x ** 2) + 1), x, domain=dom) return (((x ** 2) + 1) if (len(factors) == 1) else (x - I)) if (ex is GoldenRatio): (_, factors) = factor_list((((x ** 2) - x) - 1), x, domain=dom) if (len(factors) == 1): return (((x ** 2) - x) - 1) else: return _choose_factor(factors, x, ((1 + sqrt(5)) / 2), dom=dom) if (ex is TribonacciConstant): (_, factors) = factor_list(((((x ** 3) - (x ** 2)) - x) - 1), x, domain=dom) if (len(factors) == 1): return ((((x ** 3) - (x ** 2)) - x) - 1) else: fac = (((1 + cbrt((19 - (3 * sqrt(33))))) + cbrt((19 + (3 * sqrt(33))))) / 3) return _choose_factor(factors, x, fac, dom=dom) if (hasattr(dom, 'symbols') and (ex in dom.symbols)): return (x - ex) if (dom.is_QQ and _is_sum_surds(ex)): ex -= x while 1: ex1 = _separate_sq(ex) if (ex1 is ex): return ex else: ex = ex1 if ex.is_Add: res = _minpoly_add(x, dom, *ex.args) elif ex.is_Mul: f = Factors(ex).factors r = sift(f.items(), (lambda itx: (itx[0].is_Rational and itx[1].is_Rational))) if (r[True] and (dom == QQ)): ex1 = Mul(*[(bx ** ex) for (bx, ex) in (r[False] + r[None])]) r1 = dict(r[True]) dens = [y.q for y in r1.values()] lcmdens = reduce(lcm, dens, 1) neg1 = S.NegativeOne expn1 = r1.pop(neg1, S.Zero) nums = [(base ** ((y.p * lcmdens) // y.q)) for (base, y) in r1.items()] ex2 = Mul(*nums) mp1 = minimal_polynomial(ex1, x) mp2 = ((ex2.q * (x ** lcmdens)) - (ex2.p * (neg1 ** (expn1 * lcmdens)))) ex2 = ((neg1 ** expn1) * (ex2 ** Rational(1, lcmdens))) res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2) else: res = _minpoly_mul(x, dom, *ex.args) elif ex.is_Pow: res = _minpoly_pow(ex.base, ex.exp, x, dom) elif (ex.__class__ is sin): res = _minpoly_sin(ex, x) elif (ex.__class__ is cos): res = _minpoly_cos(ex, x) elif (ex.__class__ is exp): res = _minpoly_exp(ex, x) elif (ex.__class__ is CRootOf): res = _minpoly_rootof(ex, x) else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) return res
Computes the minimal polynomial of an algebraic element using operations on minimal polynomials Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True) x**2 - 2*x - 1 >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True) x**2*y**2 - 2*x*y - y**3 + 1
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_compose
RivtLib/replit01
603
python
def _minpoly_compose(ex, x, dom): '\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)\n x**2 - 2*x - 1\n >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)\n x**2*y**2 - 2*x*y - y**3 + 1\n\n ' if ex.is_Rational: return ((ex.q * x) - ex.p) if (ex is I): (_, factors) = factor_list(((x ** 2) + 1), x, domain=dom) return (((x ** 2) + 1) if (len(factors) == 1) else (x - I)) if (ex is GoldenRatio): (_, factors) = factor_list((((x ** 2) - x) - 1), x, domain=dom) if (len(factors) == 1): return (((x ** 2) - x) - 1) else: return _choose_factor(factors, x, ((1 + sqrt(5)) / 2), dom=dom) if (ex is TribonacciConstant): (_, factors) = factor_list(((((x ** 3) - (x ** 2)) - x) - 1), x, domain=dom) if (len(factors) == 1): return ((((x ** 3) - (x ** 2)) - x) - 1) else: fac = (((1 + cbrt((19 - (3 * sqrt(33))))) + cbrt((19 + (3 * sqrt(33))))) / 3) return _choose_factor(factors, x, fac, dom=dom) if (hasattr(dom, 'symbols') and (ex in dom.symbols)): return (x - ex) if (dom.is_QQ and _is_sum_surds(ex)): ex -= x while 1: ex1 = _separate_sq(ex) if (ex1 is ex): return ex else: ex = ex1 if ex.is_Add: res = _minpoly_add(x, dom, *ex.args) elif ex.is_Mul: f = Factors(ex).factors r = sift(f.items(), (lambda itx: (itx[0].is_Rational and itx[1].is_Rational))) if (r[True] and (dom == QQ)): ex1 = Mul(*[(bx ** ex) for (bx, ex) in (r[False] + r[None])]) r1 = dict(r[True]) dens = [y.q for y in r1.values()] lcmdens = reduce(lcm, dens, 1) neg1 = S.NegativeOne expn1 = r1.pop(neg1, S.Zero) nums = [(base ** ((y.p * lcmdens) // y.q)) for (base, y) in r1.items()] ex2 = Mul(*nums) mp1 = minimal_polynomial(ex1, x) mp2 = ((ex2.q * (x ** lcmdens)) - (ex2.p * (neg1 ** (expn1 * lcmdens)))) ex2 = ((neg1 ** expn1) * (ex2 ** Rational(1, lcmdens))) res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2) else: res = _minpoly_mul(x, dom, *ex.args) elif ex.is_Pow: res = _minpoly_pow(ex.base, ex.exp, x, dom) elif (ex.__class__ is sin): res = _minpoly_sin(ex, x) elif (ex.__class__ is cos): res = _minpoly_cos(ex, x) elif (ex.__class__ is exp): res = _minpoly_exp(ex, x) elif (ex.__class__ is CRootOf): res = _minpoly_rootof(ex, x) else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) return res
def _minpoly_compose(ex, x, dom): '\n Computes the minimal polynomial of an algebraic element\n using operations on minimal polynomials\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x, y\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)\n x**2 - 2*x - 1\n >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)\n x**2*y**2 - 2*x*y - y**3 + 1\n\n ' if ex.is_Rational: return ((ex.q * x) - ex.p) if (ex is I): (_, factors) = factor_list(((x ** 2) + 1), x, domain=dom) return (((x ** 2) + 1) if (len(factors) == 1) else (x - I)) if (ex is GoldenRatio): (_, factors) = factor_list((((x ** 2) - x) - 1), x, domain=dom) if (len(factors) == 1): return (((x ** 2) - x) - 1) else: return _choose_factor(factors, x, ((1 + sqrt(5)) / 2), dom=dom) if (ex is TribonacciConstant): (_, factors) = factor_list(((((x ** 3) - (x ** 2)) - x) - 1), x, domain=dom) if (len(factors) == 1): return ((((x ** 3) - (x ** 2)) - x) - 1) else: fac = (((1 + cbrt((19 - (3 * sqrt(33))))) + cbrt((19 + (3 * sqrt(33))))) / 3) return _choose_factor(factors, x, fac, dom=dom) if (hasattr(dom, 'symbols') and (ex in dom.symbols)): return (x - ex) if (dom.is_QQ and _is_sum_surds(ex)): ex -= x while 1: ex1 = _separate_sq(ex) if (ex1 is ex): return ex else: ex = ex1 if ex.is_Add: res = _minpoly_add(x, dom, *ex.args) elif ex.is_Mul: f = Factors(ex).factors r = sift(f.items(), (lambda itx: (itx[0].is_Rational and itx[1].is_Rational))) if (r[True] and (dom == QQ)): ex1 = Mul(*[(bx ** ex) for (bx, ex) in (r[False] + r[None])]) r1 = dict(r[True]) dens = [y.q for y in r1.values()] lcmdens = reduce(lcm, dens, 1) neg1 = S.NegativeOne expn1 = r1.pop(neg1, S.Zero) nums = [(base ** ((y.p * lcmdens) // y.q)) for (base, y) in r1.items()] ex2 = Mul(*nums) mp1 = minimal_polynomial(ex1, x) mp2 = ((ex2.q * (x ** lcmdens)) - (ex2.p * (neg1 ** (expn1 * lcmdens)))) ex2 = ((neg1 ** expn1) * (ex2 ** Rational(1, lcmdens))) res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2) else: res = _minpoly_mul(x, dom, *ex.args) elif ex.is_Pow: res = _minpoly_pow(ex.base, ex.exp, x, dom) elif (ex.__class__ is sin): res = _minpoly_sin(ex, x) elif (ex.__class__ is cos): res = _minpoly_cos(ex, x) elif (ex.__class__ is exp): res = _minpoly_exp(ex, x) elif (ex.__class__ is CRootOf): res = _minpoly_rootof(ex, x) else: raise NotAlgebraic(("%s doesn't seem to be an algebraic element" % ex)) return res<|docstring|>Computes the minimal polynomial of an algebraic element using operations on minimal polynomials Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True) x**2 - 2*x - 1 >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True) x**2*y**2 - 2*x*y - y**3 + 1<|endoftext|>
6b1cca3133e517e9e4ff2ead81e2104faf0bd86637978876ad160f6790b741b0
@public def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None): '\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Independent variable of the minimal polynomial\n\n compose : boolean, optional (default=True)\n Method to use for computing minimal polynomial. If ``compose=True``\n (default) then ``_minpoly_compose`` is used, if ``compose=False`` then\n groebner bases are used.\n\n polys : boolean, optional (default=False)\n If ``True`` returns a ``Poly`` object else an ``Expr`` object.\n\n domain : Domain, optional\n Ground domain\n\n Notes\n =====\n\n By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``\n are computed, then the arithmetic operations on them are performed using the resultant\n and factorization.\n If ``compose=False``, a bottom-up algorithm is used with ``groebner``.\n The default algorithm stalls less frequently.\n\n If no ground domain is given, it will be generated automatically from the expression.\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, solve, QQ\n >>> from sympy.abc import x, y\n\n >>> minimal_polynomial(sqrt(2), x)\n x**2 - 2\n >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))\n x - sqrt(2)\n >>> minimal_polynomial(sqrt(2) + sqrt(3), x)\n x**4 - 10*x**2 + 1\n >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)\n x**3 + x + 3\n >>> minimal_polynomial(sqrt(y), x)\n x**2 - y\n\n ' from sympy.polys.polytools import degree from sympy.polys.domains import FractionField from sympy.core.basic import preorder_traversal ex = sympify(ex) if ex.is_number: ex = _mexpand(ex, recursive=True) for expr in preorder_traversal(ex): if expr.is_AlgebraicNumber: compose = False break if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not domain): if ex.free_symbols: domain = FractionField(QQ, list(ex.free_symbols)) else: domain = QQ if (hasattr(domain, 'symbols') and (x in domain.symbols)): raise GeneratorsError(('the variable %s is an element of the ground domain %s' % (x, domain))) if compose: result = _minpoly_compose(ex, x, domain) result = result.primitive()[1] c = result.coeff((x ** degree(result, x))) if c.is_negative: result = expand_mul((- result)) return (cls(result, x, field=True) if polys else result.collect(x)) if (not domain.is_QQ): raise NotImplementedError('groebner method only works for QQ') result = _minpoly_groebner(ex, x, cls) return (cls(result, x, field=True) if polys else result.collect(x))
Computes the minimal polynomial of an algebraic element. Parameters ========== ex : Expr Element or expression whose minimal polynomial is to be calculated. x : Symbol, optional Independent variable of the minimal polynomial compose : boolean, optional (default=True) Method to use for computing minimal polynomial. If ``compose=True`` (default) then ``_minpoly_compose`` is used, if ``compose=False`` then groebner bases are used. polys : boolean, optional (default=False) If ``True`` returns a ``Poly`` object else an ``Expr`` object. domain : Domain, optional Ground domain Notes ===== By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex`` are computed, then the arithmetic operations on them are performed using the resultant and factorization. If ``compose=False``, a bottom-up algorithm is used with ``groebner``. The default algorithm stalls less frequently. If no ground domain is given, it will be generated automatically from the expression. Examples ======== >>> from sympy import minimal_polynomial, sqrt, solve, QQ >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2), x) x**2 - 2 >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) x - sqrt(2) >>> minimal_polynomial(sqrt(2) + sqrt(3), x) x**4 - 10*x**2 + 1 >>> minimal_polynomial(solve(x**3 + x + 3)[0], x) x**3 + x + 3 >>> minimal_polynomial(sqrt(y), x) x**2 - y
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
minimal_polynomial
RivtLib/replit01
603
python
@public def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None): '\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Independent variable of the minimal polynomial\n\n compose : boolean, optional (default=True)\n Method to use for computing minimal polynomial. If ``compose=True``\n (default) then ``_minpoly_compose`` is used, if ``compose=False`` then\n groebner bases are used.\n\n polys : boolean, optional (default=False)\n If ``True`` returns a ``Poly`` object else an ``Expr`` object.\n\n domain : Domain, optional\n Ground domain\n\n Notes\n =====\n\n By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``\n are computed, then the arithmetic operations on them are performed using the resultant\n and factorization.\n If ``compose=False``, a bottom-up algorithm is used with ``groebner``.\n The default algorithm stalls less frequently.\n\n If no ground domain is given, it will be generated automatically from the expression.\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, solve, QQ\n >>> from sympy.abc import x, y\n\n >>> minimal_polynomial(sqrt(2), x)\n x**2 - 2\n >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))\n x - sqrt(2)\n >>> minimal_polynomial(sqrt(2) + sqrt(3), x)\n x**4 - 10*x**2 + 1\n >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)\n x**3 + x + 3\n >>> minimal_polynomial(sqrt(y), x)\n x**2 - y\n\n ' from sympy.polys.polytools import degree from sympy.polys.domains import FractionField from sympy.core.basic import preorder_traversal ex = sympify(ex) if ex.is_number: ex = _mexpand(ex, recursive=True) for expr in preorder_traversal(ex): if expr.is_AlgebraicNumber: compose = False break if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not domain): if ex.free_symbols: domain = FractionField(QQ, list(ex.free_symbols)) else: domain = QQ if (hasattr(domain, 'symbols') and (x in domain.symbols)): raise GeneratorsError(('the variable %s is an element of the ground domain %s' % (x, domain))) if compose: result = _minpoly_compose(ex, x, domain) result = result.primitive()[1] c = result.coeff((x ** degree(result, x))) if c.is_negative: result = expand_mul((- result)) return (cls(result, x, field=True) if polys else result.collect(x)) if (not domain.is_QQ): raise NotImplementedError('groebner method only works for QQ') result = _minpoly_groebner(ex, x, cls) return (cls(result, x, field=True) if polys else result.collect(x))
@public def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None): '\n Computes the minimal polynomial of an algebraic element.\n\n Parameters\n ==========\n\n ex : Expr\n Element or expression whose minimal polynomial is to be calculated.\n\n x : Symbol, optional\n Independent variable of the minimal polynomial\n\n compose : boolean, optional (default=True)\n Method to use for computing minimal polynomial. If ``compose=True``\n (default) then ``_minpoly_compose`` is used, if ``compose=False`` then\n groebner bases are used.\n\n polys : boolean, optional (default=False)\n If ``True`` returns a ``Poly`` object else an ``Expr`` object.\n\n domain : Domain, optional\n Ground domain\n\n Notes\n =====\n\n By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``\n are computed, then the arithmetic operations on them are performed using the resultant\n and factorization.\n If ``compose=False``, a bottom-up algorithm is used with ``groebner``.\n The default algorithm stalls less frequently.\n\n If no ground domain is given, it will be generated automatically from the expression.\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, solve, QQ\n >>> from sympy.abc import x, y\n\n >>> minimal_polynomial(sqrt(2), x)\n x**2 - 2\n >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))\n x - sqrt(2)\n >>> minimal_polynomial(sqrt(2) + sqrt(3), x)\n x**4 - 10*x**2 + 1\n >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)\n x**3 + x + 3\n >>> minimal_polynomial(sqrt(y), x)\n x**2 - y\n\n ' from sympy.polys.polytools import degree from sympy.polys.domains import FractionField from sympy.core.basic import preorder_traversal ex = sympify(ex) if ex.is_number: ex = _mexpand(ex, recursive=True) for expr in preorder_traversal(ex): if expr.is_AlgebraicNumber: compose = False break if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not domain): if ex.free_symbols: domain = FractionField(QQ, list(ex.free_symbols)) else: domain = QQ if (hasattr(domain, 'symbols') and (x in domain.symbols)): raise GeneratorsError(('the variable %s is an element of the ground domain %s' % (x, domain))) if compose: result = _minpoly_compose(ex, x, domain) result = result.primitive()[1] c = result.coeff((x ** degree(result, x))) if c.is_negative: result = expand_mul((- result)) return (cls(result, x, field=True) if polys else result.collect(x)) if (not domain.is_QQ): raise NotImplementedError('groebner method only works for QQ') result = _minpoly_groebner(ex, x, cls) return (cls(result, x, field=True) if polys else result.collect(x))<|docstring|>Computes the minimal polynomial of an algebraic element. Parameters ========== ex : Expr Element or expression whose minimal polynomial is to be calculated. x : Symbol, optional Independent variable of the minimal polynomial compose : boolean, optional (default=True) Method to use for computing minimal polynomial. If ``compose=True`` (default) then ``_minpoly_compose`` is used, if ``compose=False`` then groebner bases are used. polys : boolean, optional (default=False) If ``True`` returns a ``Poly`` object else an ``Expr`` object. domain : Domain, optional Ground domain Notes ===== By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex`` are computed, then the arithmetic operations on them are performed using the resultant and factorization. If ``compose=False``, a bottom-up algorithm is used with ``groebner``. The default algorithm stalls less frequently. If no ground domain is given, it will be generated automatically from the expression. Examples ======== >>> from sympy import minimal_polynomial, sqrt, solve, QQ >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2), x) x**2 - 2 >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) x - sqrt(2) >>> minimal_polynomial(sqrt(2) + sqrt(3), x) x**4 - 10*x**2 + 1 >>> minimal_polynomial(solve(x**3 + x + 3)[0], x) x**3 + x + 3 >>> minimal_polynomial(sqrt(y), x) x**2 - y<|endoftext|>
039b63a672bf0ba93e36060661887fc84230849dbda5ff81cfc0235405498750
def _minpoly_groebner(ex, x, cls): '\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)\n x**2 - 2*x - 1\n\n ' from sympy.polys.polytools import degree from sympy.core.function import expand_multinomial generator = numbered_symbols('a', cls=Dummy) (mapping, symbols) = ({}, {}) def update_mapping(ex, exp, base=None): a = next(generator) symbols[ex] = a if (base is not None): mapping[ex] = ((a ** exp) + base) else: mapping[ex] = exp.as_expr(a) return a def bottom_up_scan(ex): if ex.is_Atom: if (ex is S.ImaginaryUnit): if (ex not in mapping): return update_mapping(ex, 2, 1) else: return symbols[ex] elif ex.is_Rational: return ex elif ex.is_Add: return Add(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Mul: return Mul(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Pow: if ex.exp.is_Rational: if (ex.exp < 0): minpoly_base = _minpoly_groebner(ex.base, x, cls) inverse = invert(x, minpoly_base).as_expr() base_inv = inverse.subs(x, ex.base).expand() if (ex.exp == (- 1)): return bottom_up_scan(base_inv) else: ex = (base_inv ** (- ex.exp)) if (not ex.exp.is_Integer): (base, exp) = ((ex.base ** ex.exp.p).expand(), Rational(1, ex.exp.q)) else: (base, exp) = (ex.base, ex.exp) base = bottom_up_scan(base) expr = (base ** exp) if (expr not in mapping): return update_mapping(expr, (1 / exp), (- base)) else: return symbols[expr] elif ex.is_AlgebraicNumber: if (ex.root not in mapping): return update_mapping(ex.root, ex.minpoly) else: return symbols[ex.root] raise NotAlgebraic(("%s doesn't seem to be an algebraic number" % ex)) def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False inverted = False ex = expand_multinomial(ex) if ex.is_AlgebraicNumber: return ex.minpoly.as_expr(x) elif ex.is_Rational: result = ((ex.q * x) - ex.p) else: inverted = simpler_inverse(ex) if inverted: ex = (ex ** (- 1)) res = None if (ex.is_Pow and (1 / ex.exp).is_Integer): n = (1 / ex.exp) res = _minimal_polynomial_sq(ex.base, n, x) elif _is_sum_surds(ex): res = _minimal_polynomial_sq(ex, S.One, x) if (res is not None): result = res if (res is None): bus = bottom_up_scan(ex) F = ([(x - bus)] + list(mapping.values())) G = groebner(F, (list(symbols.values()) + [x]), order='lex') (_, factors) = factor_list(G[(- 1)]) result = _choose_factor(factors, x, ex) if inverted: result = _invertx(result, x) if (result.coeff((x ** degree(result, x))) < 0): result = expand_mul((- result)) return result
Computes the minimal polynomial of an algebraic number using Groebner bases Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False) x**2 - 2*x - 1
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
_minpoly_groebner
RivtLib/replit01
603
python
def _minpoly_groebner(ex, x, cls): '\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)\n x**2 - 2*x - 1\n\n ' from sympy.polys.polytools import degree from sympy.core.function import expand_multinomial generator = numbered_symbols('a', cls=Dummy) (mapping, symbols) = ({}, {}) def update_mapping(ex, exp, base=None): a = next(generator) symbols[ex] = a if (base is not None): mapping[ex] = ((a ** exp) + base) else: mapping[ex] = exp.as_expr(a) return a def bottom_up_scan(ex): if ex.is_Atom: if (ex is S.ImaginaryUnit): if (ex not in mapping): return update_mapping(ex, 2, 1) else: return symbols[ex] elif ex.is_Rational: return ex elif ex.is_Add: return Add(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Mul: return Mul(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Pow: if ex.exp.is_Rational: if (ex.exp < 0): minpoly_base = _minpoly_groebner(ex.base, x, cls) inverse = invert(x, minpoly_base).as_expr() base_inv = inverse.subs(x, ex.base).expand() if (ex.exp == (- 1)): return bottom_up_scan(base_inv) else: ex = (base_inv ** (- ex.exp)) if (not ex.exp.is_Integer): (base, exp) = ((ex.base ** ex.exp.p).expand(), Rational(1, ex.exp.q)) else: (base, exp) = (ex.base, ex.exp) base = bottom_up_scan(base) expr = (base ** exp) if (expr not in mapping): return update_mapping(expr, (1 / exp), (- base)) else: return symbols[expr] elif ex.is_AlgebraicNumber: if (ex.root not in mapping): return update_mapping(ex.root, ex.minpoly) else: return symbols[ex.root] raise NotAlgebraic(("%s doesn't seem to be an algebraic number" % ex)) def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False inverted = False ex = expand_multinomial(ex) if ex.is_AlgebraicNumber: return ex.minpoly.as_expr(x) elif ex.is_Rational: result = ((ex.q * x) - ex.p) else: inverted = simpler_inverse(ex) if inverted: ex = (ex ** (- 1)) res = None if (ex.is_Pow and (1 / ex.exp).is_Integer): n = (1 / ex.exp) res = _minimal_polynomial_sq(ex.base, n, x) elif _is_sum_surds(ex): res = _minimal_polynomial_sq(ex, S.One, x) if (res is not None): result = res if (res is None): bus = bottom_up_scan(ex) F = ([(x - bus)] + list(mapping.values())) G = groebner(F, (list(symbols.values()) + [x]), order='lex') (_, factors) = factor_list(G[(- 1)]) result = _choose_factor(factors, x, ex) if inverted: result = _invertx(result, x) if (result.coeff((x ** degree(result, x))) < 0): result = expand_mul((- result)) return result
def _minpoly_groebner(ex, x, cls): '\n Computes the minimal polynomial of an algebraic number\n using Groebner bases\n\n Examples\n ========\n\n >>> from sympy import minimal_polynomial, sqrt, Rational\n >>> from sympy.abc import x\n >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)\n x**2 - 2*x - 1\n\n ' from sympy.polys.polytools import degree from sympy.core.function import expand_multinomial generator = numbered_symbols('a', cls=Dummy) (mapping, symbols) = ({}, {}) def update_mapping(ex, exp, base=None): a = next(generator) symbols[ex] = a if (base is not None): mapping[ex] = ((a ** exp) + base) else: mapping[ex] = exp.as_expr(a) return a def bottom_up_scan(ex): if ex.is_Atom: if (ex is S.ImaginaryUnit): if (ex not in mapping): return update_mapping(ex, 2, 1) else: return symbols[ex] elif ex.is_Rational: return ex elif ex.is_Add: return Add(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Mul: return Mul(*[bottom_up_scan(g) for g in ex.args]) elif ex.is_Pow: if ex.exp.is_Rational: if (ex.exp < 0): minpoly_base = _minpoly_groebner(ex.base, x, cls) inverse = invert(x, minpoly_base).as_expr() base_inv = inverse.subs(x, ex.base).expand() if (ex.exp == (- 1)): return bottom_up_scan(base_inv) else: ex = (base_inv ** (- ex.exp)) if (not ex.exp.is_Integer): (base, exp) = ((ex.base ** ex.exp.p).expand(), Rational(1, ex.exp.q)) else: (base, exp) = (ex.base, ex.exp) base = bottom_up_scan(base) expr = (base ** exp) if (expr not in mapping): return update_mapping(expr, (1 / exp), (- base)) else: return symbols[expr] elif ex.is_AlgebraicNumber: if (ex.root not in mapping): return update_mapping(ex.root, ex.minpoly) else: return symbols[ex.root] raise NotAlgebraic(("%s doesn't seem to be an algebraic number" % ex)) def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False inverted = False ex = expand_multinomial(ex) if ex.is_AlgebraicNumber: return ex.minpoly.as_expr(x) elif ex.is_Rational: result = ((ex.q * x) - ex.p) else: inverted = simpler_inverse(ex) if inverted: ex = (ex ** (- 1)) res = None if (ex.is_Pow and (1 / ex.exp).is_Integer): n = (1 / ex.exp) res = _minimal_polynomial_sq(ex.base, n, x) elif _is_sum_surds(ex): res = _minimal_polynomial_sq(ex, S.One, x) if (res is not None): result = res if (res is None): bus = bottom_up_scan(ex) F = ([(x - bus)] + list(mapping.values())) G = groebner(F, (list(symbols.values()) + [x]), order='lex') (_, factors) = factor_list(G[(- 1)]) result = _choose_factor(factors, x, ex) if inverted: result = _invertx(result, x) if (result.coeff((x ** degree(result, x))) < 0): result = expand_mul((- result)) return result<|docstring|>Computes the minimal polynomial of an algebraic number using Groebner bases Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False) x**2 - 2*x - 1<|endoftext|>
0c6e5c96a5b98850c5efd74afa6d0500c4674b903baf5e8b91de01528f237e0d
@public def primitive_element(extension, x=None, *, ex=False, polys=False): 'Construct a common number field for all extensions. ' if (not extension): raise ValueError("can't compute primitive element for empty extension") if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not ex): (gen, coeffs) = (extension[0], [1]) g = minimal_polynomial(gen, x, polys=True) for ext in extension[1:]: (_, factors) = factor_list(g, extension=ext) g = _choose_factor(factors, x, gen) (s, _, g) = g.sqf_norm() gen += (s * ext) coeffs.append(s) if (not polys): return (g.as_expr(), coeffs) else: return (cls(g), coeffs) (gen, coeffs) = (extension[0], [1]) f = minimal_polynomial(gen, x, polys=True) K = QQ.algebraic_field((f, gen)) reps = [K.unit] for ext in extension[1:]: p = minimal_polynomial(ext, x, polys=True) L = QQ.algebraic_field((p, ext)) (_, factors) = factor_list(f, domain=L) f = _choose_factor(factors, x, gen) (s, g, f) = f.sqf_norm() gen += (s * ext) coeffs.append(s) K = QQ.algebraic_field((f, gen)) h = _switch_domain(g, K) erep = _linsolve(h.gcd(p)) ogen = (K.unit - (s * erep)) reps = ([dup_eval(_.rep, ogen, K) for _ in reps] + [erep]) H = [_.rep for _ in reps] if (not polys): return (f.as_expr(), coeffs, H) else: return (f, coeffs, H)
Construct a common number field for all extensions.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
primitive_element
RivtLib/replit01
603
python
@public def primitive_element(extension, x=None, *, ex=False, polys=False): ' ' if (not extension): raise ValueError("can't compute primitive element for empty extension") if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not ex): (gen, coeffs) = (extension[0], [1]) g = minimal_polynomial(gen, x, polys=True) for ext in extension[1:]: (_, factors) = factor_list(g, extension=ext) g = _choose_factor(factors, x, gen) (s, _, g) = g.sqf_norm() gen += (s * ext) coeffs.append(s) if (not polys): return (g.as_expr(), coeffs) else: return (cls(g), coeffs) (gen, coeffs) = (extension[0], [1]) f = minimal_polynomial(gen, x, polys=True) K = QQ.algebraic_field((f, gen)) reps = [K.unit] for ext in extension[1:]: p = minimal_polynomial(ext, x, polys=True) L = QQ.algebraic_field((p, ext)) (_, factors) = factor_list(f, domain=L) f = _choose_factor(factors, x, gen) (s, g, f) = f.sqf_norm() gen += (s * ext) coeffs.append(s) K = QQ.algebraic_field((f, gen)) h = _switch_domain(g, K) erep = _linsolve(h.gcd(p)) ogen = (K.unit - (s * erep)) reps = ([dup_eval(_.rep, ogen, K) for _ in reps] + [erep]) H = [_.rep for _ in reps] if (not polys): return (f.as_expr(), coeffs, H) else: return (f, coeffs, H)
@public def primitive_element(extension, x=None, *, ex=False, polys=False): ' ' if (not extension): raise ValueError("can't compute primitive element for empty extension") if (x is not None): (x, cls) = (sympify(x), Poly) else: (x, cls) = (Dummy('x'), PurePoly) if (not ex): (gen, coeffs) = (extension[0], [1]) g = minimal_polynomial(gen, x, polys=True) for ext in extension[1:]: (_, factors) = factor_list(g, extension=ext) g = _choose_factor(factors, x, gen) (s, _, g) = g.sqf_norm() gen += (s * ext) coeffs.append(s) if (not polys): return (g.as_expr(), coeffs) else: return (cls(g), coeffs) (gen, coeffs) = (extension[0], [1]) f = minimal_polynomial(gen, x, polys=True) K = QQ.algebraic_field((f, gen)) reps = [K.unit] for ext in extension[1:]: p = minimal_polynomial(ext, x, polys=True) L = QQ.algebraic_field((p, ext)) (_, factors) = factor_list(f, domain=L) f = _choose_factor(factors, x, gen) (s, g, f) = f.sqf_norm() gen += (s * ext) coeffs.append(s) K = QQ.algebraic_field((f, gen)) h = _switch_domain(g, K) erep = _linsolve(h.gcd(p)) ogen = (K.unit - (s * erep)) reps = ([dup_eval(_.rep, ogen, K) for _ in reps] + [erep]) H = [_.rep for _ in reps] if (not polys): return (f.as_expr(), coeffs, H) else: return (f, coeffs, H)<|docstring|>Construct a common number field for all extensions.<|endoftext|>
778926c2eb2ce4870eb5eda995434d3f7c75fe62063b0f844ec6448f3a0758d9
def is_isomorphism_possible(a, b): 'Returns `True` if there is a chance for isomorphism. ' n = a.minpoly.degree() m = b.minpoly.degree() if ((m % n) != 0): return False if (n == m): return True da = a.minpoly.discriminant() db = b.minpoly.discriminant() (i, k, half) = (1, (m // n), (db // 2)) while True: p = sieve[i] P = (p ** k) if (P > half): break if (((da % p) % 2) and (not (db % P))): return False i += 1 return True
Returns `True` if there is a chance for isomorphism.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
is_isomorphism_possible
RivtLib/replit01
603
python
def is_isomorphism_possible(a, b): ' ' n = a.minpoly.degree() m = b.minpoly.degree() if ((m % n) != 0): return False if (n == m): return True da = a.minpoly.discriminant() db = b.minpoly.discriminant() (i, k, half) = (1, (m // n), (db // 2)) while True: p = sieve[i] P = (p ** k) if (P > half): break if (((da % p) % 2) and (not (db % P))): return False i += 1 return True
def is_isomorphism_possible(a, b): ' ' n = a.minpoly.degree() m = b.minpoly.degree() if ((m % n) != 0): return False if (n == m): return True da = a.minpoly.discriminant() db = b.minpoly.discriminant() (i, k, half) = (1, (m // n), (db // 2)) while True: p = sieve[i] P = (p ** k) if (P > half): break if (((da % p) % 2) and (not (db % P))): return False i += 1 return True<|docstring|>Returns `True` if there is a chance for isomorphism.<|endoftext|>
150fe6e62ebf7d5d9d86ad1e714c73cb3fa8a4e06001d337ba92b426af170f6c
def field_isomorphism_pslq(a, b): 'Construct field isomorphism using PSLQ algorithm. ' if ((not a.root.is_real) or (not b.root.is_real)): raise NotImplementedError("PSLQ doesn't support complex coefficients") f = a.minpoly g = b.minpoly.replace(f.gen) (n, m, prev) = (100, b.minpoly.degree(), None) for i in range(1, 5): A = a.root.evalf(n) B = b.root.evalf(n) basis = (([1, B] + [(B ** i) for i in range(2, m)]) + [A]) (dps, mp.dps) = (mp.dps, n) coeffs = pslq(basis, maxcoeff=int(10000000000.0), maxsteps=1000) mp.dps = dps if (coeffs is None): break if (coeffs != prev): prev = coeffs else: break coeffs = [(S(c) / coeffs[(- 1)]) for c in coeffs[:(- 1)]] while (not coeffs[(- 1)]): coeffs.pop() coeffs = list(reversed(coeffs)) h = Poly(coeffs, f.gen, domain='QQ') if f.compose(h).rem(g).is_zero: (d, approx) = ((len(coeffs) - 1), 0) for (i, coeff) in enumerate(coeffs): approx += (coeff * (B ** (d - i))) if ((A * approx) < 0): return [(- c) for c in coeffs] else: return coeffs elif f.compose((- h)).rem(g).is_zero: return [(- c) for c in coeffs] else: n *= 2 return None
Construct field isomorphism using PSLQ algorithm.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
field_isomorphism_pslq
RivtLib/replit01
603
python
def field_isomorphism_pslq(a, b): ' ' if ((not a.root.is_real) or (not b.root.is_real)): raise NotImplementedError("PSLQ doesn't support complex coefficients") f = a.minpoly g = b.minpoly.replace(f.gen) (n, m, prev) = (100, b.minpoly.degree(), None) for i in range(1, 5): A = a.root.evalf(n) B = b.root.evalf(n) basis = (([1, B] + [(B ** i) for i in range(2, m)]) + [A]) (dps, mp.dps) = (mp.dps, n) coeffs = pslq(basis, maxcoeff=int(10000000000.0), maxsteps=1000) mp.dps = dps if (coeffs is None): break if (coeffs != prev): prev = coeffs else: break coeffs = [(S(c) / coeffs[(- 1)]) for c in coeffs[:(- 1)]] while (not coeffs[(- 1)]): coeffs.pop() coeffs = list(reversed(coeffs)) h = Poly(coeffs, f.gen, domain='QQ') if f.compose(h).rem(g).is_zero: (d, approx) = ((len(coeffs) - 1), 0) for (i, coeff) in enumerate(coeffs): approx += (coeff * (B ** (d - i))) if ((A * approx) < 0): return [(- c) for c in coeffs] else: return coeffs elif f.compose((- h)).rem(g).is_zero: return [(- c) for c in coeffs] else: n *= 2 return None
def field_isomorphism_pslq(a, b): ' ' if ((not a.root.is_real) or (not b.root.is_real)): raise NotImplementedError("PSLQ doesn't support complex coefficients") f = a.minpoly g = b.minpoly.replace(f.gen) (n, m, prev) = (100, b.minpoly.degree(), None) for i in range(1, 5): A = a.root.evalf(n) B = b.root.evalf(n) basis = (([1, B] + [(B ** i) for i in range(2, m)]) + [A]) (dps, mp.dps) = (mp.dps, n) coeffs = pslq(basis, maxcoeff=int(10000000000.0), maxsteps=1000) mp.dps = dps if (coeffs is None): break if (coeffs != prev): prev = coeffs else: break coeffs = [(S(c) / coeffs[(- 1)]) for c in coeffs[:(- 1)]] while (not coeffs[(- 1)]): coeffs.pop() coeffs = list(reversed(coeffs)) h = Poly(coeffs, f.gen, domain='QQ') if f.compose(h).rem(g).is_zero: (d, approx) = ((len(coeffs) - 1), 0) for (i, coeff) in enumerate(coeffs): approx += (coeff * (B ** (d - i))) if ((A * approx) < 0): return [(- c) for c in coeffs] else: return coeffs elif f.compose((- h)).rem(g).is_zero: return [(- c) for c in coeffs] else: n *= 2 return None<|docstring|>Construct field isomorphism using PSLQ algorithm.<|endoftext|>
02107afe918d47bb7b8c761a9aba102558b027e496d2be4a3a2c5e3f81f99e91
def field_isomorphism_factor(a, b): 'Construct field isomorphism via factorization. ' (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((coeff * (b.root ** (d - i)))) root = Add(*terms) if ((a.root - root).evalf(chop=True) == 0): return coeffs if ((a.root + root).evalf(chop=True) == 0): return [(- c) for c in coeffs] return None
Construct field isomorphism via factorization.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
field_isomorphism_factor
RivtLib/replit01
603
python
def field_isomorphism_factor(a, b): ' ' (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((coeff * (b.root ** (d - i)))) root = Add(*terms) if ((a.root - root).evalf(chop=True) == 0): return coeffs if ((a.root + root).evalf(chop=True) == 0): return [(- c) for c in coeffs] return None
def field_isomorphism_factor(a, b): ' ' (_, factors) = factor_list(a.minpoly, extension=b) for (f, _) in factors: if (f.degree() == 1): coeffs = f.rep.TC().to_sympy_list() (d, terms) = ((len(coeffs) - 1), []) for (i, coeff) in enumerate(coeffs): terms.append((coeff * (b.root ** (d - i)))) root = Add(*terms) if ((a.root - root).evalf(chop=True) == 0): return coeffs if ((a.root + root).evalf(chop=True) == 0): return [(- c) for c in coeffs] return None<|docstring|>Construct field isomorphism via factorization.<|endoftext|>
76e9d1b2692c537e7be92214b2d7090d2a3b2520c1ed6eb198a09f466a773321
@public def field_isomorphism(a, b, *, fast=True): 'Construct an isomorphism between two number fields. ' (a, b) = (sympify(a), sympify(b)) if (not a.is_AlgebraicNumber): a = AlgebraicNumber(a) if (not b.is_AlgebraicNumber): b = AlgebraicNumber(b) if (a == b): return a.coeffs() n = a.minpoly.degree() m = b.minpoly.degree() if (n == 1): return [a.root] if ((m % n) != 0): return None if fast: try: result = field_isomorphism_pslq(a, b) if (result is not None): return result except NotImplementedError: pass return field_isomorphism_factor(a, b)
Construct an isomorphism between two number fields.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
field_isomorphism
RivtLib/replit01
603
python
@public def field_isomorphism(a, b, *, fast=True): ' ' (a, b) = (sympify(a), sympify(b)) if (not a.is_AlgebraicNumber): a = AlgebraicNumber(a) if (not b.is_AlgebraicNumber): b = AlgebraicNumber(b) if (a == b): return a.coeffs() n = a.minpoly.degree() m = b.minpoly.degree() if (n == 1): return [a.root] if ((m % n) != 0): return None if fast: try: result = field_isomorphism_pslq(a, b) if (result is not None): return result except NotImplementedError: pass return field_isomorphism_factor(a, b)
@public def field_isomorphism(a, b, *, fast=True): ' ' (a, b) = (sympify(a), sympify(b)) if (not a.is_AlgebraicNumber): a = AlgebraicNumber(a) if (not b.is_AlgebraicNumber): b = AlgebraicNumber(b) if (a == b): return a.coeffs() n = a.minpoly.degree() m = b.minpoly.degree() if (n == 1): return [a.root] if ((m % n) != 0): return None if fast: try: result = field_isomorphism_pslq(a, b) if (result is not None): return result except NotImplementedError: pass return field_isomorphism_factor(a, b)<|docstring|>Construct an isomorphism between two number fields.<|endoftext|>
9df13d1fd803ce61ca9f0ffe7bd4eec5504126ef27c52d1ee3eb0e9c56642106
@public def to_number_field(extension, theta=None, *, gen=None): 'Express `extension` in the field generated by `theta`. ' if hasattr(extension, '__iter__'): extension = list(extension) else: extension = [extension] if ((len(extension) == 1) and (type(extension[0]) is tuple)): return AlgebraicNumber(extension[0]) (minpoly, coeffs) = primitive_element(extension, gen, polys=True) root = sum([(coeff * ext) for (coeff, ext) in zip(coeffs, extension)]) if (theta is None): return AlgebraicNumber((minpoly, root)) else: theta = sympify(theta) if (not theta.is_AlgebraicNumber): theta = AlgebraicNumber(theta, gen=gen) coeffs = field_isomorphism(root, theta) if (coeffs is not None): return AlgebraicNumber(theta, coeffs) else: raise IsomorphismFailed(('%s is not in a subfield of %s' % (root, theta.root)))
Express `extension` in the field generated by `theta`.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
to_number_field
RivtLib/replit01
603
python
@public def to_number_field(extension, theta=None, *, gen=None): ' ' if hasattr(extension, '__iter__'): extension = list(extension) else: extension = [extension] if ((len(extension) == 1) and (type(extension[0]) is tuple)): return AlgebraicNumber(extension[0]) (minpoly, coeffs) = primitive_element(extension, gen, polys=True) root = sum([(coeff * ext) for (coeff, ext) in zip(coeffs, extension)]) if (theta is None): return AlgebraicNumber((minpoly, root)) else: theta = sympify(theta) if (not theta.is_AlgebraicNumber): theta = AlgebraicNumber(theta, gen=gen) coeffs = field_isomorphism(root, theta) if (coeffs is not None): return AlgebraicNumber(theta, coeffs) else: raise IsomorphismFailed(('%s is not in a subfield of %s' % (root, theta.root)))
@public def to_number_field(extension, theta=None, *, gen=None): ' ' if hasattr(extension, '__iter__'): extension = list(extension) else: extension = [extension] if ((len(extension) == 1) and (type(extension[0]) is tuple)): return AlgebraicNumber(extension[0]) (minpoly, coeffs) = primitive_element(extension, gen, polys=True) root = sum([(coeff * ext) for (coeff, ext) in zip(coeffs, extension)]) if (theta is None): return AlgebraicNumber((minpoly, root)) else: theta = sympify(theta) if (not theta.is_AlgebraicNumber): theta = AlgebraicNumber(theta, gen=gen) coeffs = field_isomorphism(root, theta) if (coeffs is not None): return AlgebraicNumber(theta, coeffs) else: raise IsomorphismFailed(('%s is not in a subfield of %s' % (root, theta.root)))<|docstring|>Express `extension` in the field generated by `theta`.<|endoftext|>
9be35c67f3fddb8fb9e5b23ed0032ab90cfed0c4caf81b918a010ddece4dea03
@public def isolate(alg, eps=None, fast=False): 'Give a rational isolating interval for an algebraic number. ' alg = sympify(alg) if alg.is_Rational: return (alg, alg) elif (not alg.is_real): raise NotImplementedError('complex algebraic numbers are not supported') func = lambdify((), alg, modules='mpmath', printer=IntervalPrinter()) poly = minpoly(alg, polys=True) intervals = poly.intervals(sqf=True) (dps, done) = (mp.dps, False) try: while (not done): alg = func() for (a, b) in intervals: if ((a <= alg.a) and (alg.b <= b)): done = True break else: mp.dps *= 2 finally: mp.dps = dps if (eps is not None): (a, b) = poly.refine_root(a, b, eps=eps, fast=fast) return (a, b)
Give a rational isolating interval for an algebraic number.
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
isolate
RivtLib/replit01
603
python
@public def isolate(alg, eps=None, fast=False): ' ' alg = sympify(alg) if alg.is_Rational: return (alg, alg) elif (not alg.is_real): raise NotImplementedError('complex algebraic numbers are not supported') func = lambdify((), alg, modules='mpmath', printer=IntervalPrinter()) poly = minpoly(alg, polys=True) intervals = poly.intervals(sqf=True) (dps, done) = (mp.dps, False) try: while (not done): alg = func() for (a, b) in intervals: if ((a <= alg.a) and (alg.b <= b)): done = True break else: mp.dps *= 2 finally: mp.dps = dps if (eps is not None): (a, b) = poly.refine_root(a, b, eps=eps, fast=fast) return (a, b)
@public def isolate(alg, eps=None, fast=False): ' ' alg = sympify(alg) if alg.is_Rational: return (alg, alg) elif (not alg.is_real): raise NotImplementedError('complex algebraic numbers are not supported') func = lambdify((), alg, modules='mpmath', printer=IntervalPrinter()) poly = minpoly(alg, polys=True) intervals = poly.intervals(sqf=True) (dps, done) = (mp.dps, False) try: while (not done): alg = func() for (a, b) in intervals: if ((a <= alg.a) and (alg.b <= b)): done = True break else: mp.dps *= 2 finally: mp.dps = dps if (eps is not None): (a, b) = poly.refine_root(a, b, eps=eps, fast=fast) return (a, b)<|docstring|>Give a rational isolating interval for an algebraic number.<|endoftext|>
2a30b9002327df8ab7e6f732da67dd6d74c1c426c0300591df00b6ac080562f5
def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False
Returns True if it is more likely that the minimal polynomial algorithm works better with the inverse
.venv/lib/python3.8/site-packages/sympy/polys/numberfields.py
simpler_inverse
RivtLib/replit01
603
python
def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False
def simpler_inverse(ex): '\n Returns True if it is more likely that the minimal polynomial\n algorithm works better with the inverse\n ' if ex.is_Pow: if ((1 / ex.exp).is_integer and (ex.exp < 0)): if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if (p.base.is_Add and (p.exp > 0)): return False if hit: return True return False<|docstring|>Returns True if it is more likely that the minimal polynomial algorithm works better with the inverse<|endoftext|>
0ce59989e387908231b502caf13a399f5dc3bfc7088374bd89714f127fe65821
def make_accessors(strategy='strategy', storage='storage'): '\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n ' def make_getter(attr): def getter(self): return getattr(self, attr) return getter def make_setter(attr): def setter(self, val): setattr(self, attr, val) return setter classdef = sys._getframe(1).f_locals classdef['_get_strategy'] = make_getter(strategy) classdef['_set_strategy'] = make_setter(strategy) classdef['_get_storage'] = make_getter(storage) classdef['_set_storage'] = make_setter(storage)
Instead of using this generator, the methods can be implemented manually. A third way is to overwrite the getter/setter methods in StrategyFactory.
rpython/rlib/rstrategies/rstrategies.py
make_accessors
yxzoro/pypy
381
python
def make_accessors(strategy='strategy', storage='storage'): '\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n ' def make_getter(attr): def getter(self): return getattr(self, attr) return getter def make_setter(attr): def setter(self, val): setattr(self, attr, val) return setter classdef = sys._getframe(1).f_locals classdef['_get_strategy'] = make_getter(strategy) classdef['_set_strategy'] = make_setter(strategy) classdef['_get_storage'] = make_getter(storage) classdef['_set_storage'] = make_setter(storage)
def make_accessors(strategy='strategy', storage='storage'): '\n Instead of using this generator, the methods can be implemented manually.\n A third way is to overwrite the getter/setter methods in StrategyFactory.\n ' def make_getter(attr): def getter(self): return getattr(self, attr) return getter def make_setter(attr): def setter(self, val): setattr(self, attr, val) return setter classdef = sys._getframe(1).f_locals classdef['_get_strategy'] = make_getter(strategy) classdef['_set_strategy'] = make_setter(strategy) classdef['_get_storage'] = make_getter(storage) classdef['_set_storage'] = make_setter(storage)<|docstring|>Instead of using this generator, the methods can be implemented manually. A third way is to overwrite the getter/setter methods in StrategyFactory.<|endoftext|>
f5b44397b082c68b7224b9fc7f97754692862b7758b9155ced093ef489099074
def strategy(generalize=None, singleton=True): '\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing the singleton object.\n ' def decorator(strategy_class): if generalize: @jit.unroll_safe def generalized_strategy_for(self, value): for strategy in generalize: if self.strategy_factory().strategy_singleton_instance(strategy)._check_can_handle(value): return strategy raise Exception(('Could not find generalized strategy for %s coming from %s' % (value, self))) strategy_class.generalized_strategy_for = generalized_strategy_for for generalized in generalize: generalized._specializations.append(strategy_class) strategy_class._is_strategy = True strategy_class._generalizations = generalize strategy_class._is_singleton = singleton return strategy_class return decorator
Strategy classes must be decorated with this. generalize is a list of other strategies, that can be switched to from the decorated strategy. If the singleton flag is set to False, new strategy instances will be created, instead of always reusing the singleton object.
rpython/rlib/rstrategies/rstrategies.py
strategy
yxzoro/pypy
381
python
def strategy(generalize=None, singleton=True): '\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing the singleton object.\n ' def decorator(strategy_class): if generalize: @jit.unroll_safe def generalized_strategy_for(self, value): for strategy in generalize: if self.strategy_factory().strategy_singleton_instance(strategy)._check_can_handle(value): return strategy raise Exception(('Could not find generalized strategy for %s coming from %s' % (value, self))) strategy_class.generalized_strategy_for = generalized_strategy_for for generalized in generalize: generalized._specializations.append(strategy_class) strategy_class._is_strategy = True strategy_class._generalizations = generalize strategy_class._is_singleton = singleton return strategy_class return decorator
def strategy(generalize=None, singleton=True): '\n Strategy classes must be decorated with this.\n generalize is a list of other strategies, that can be switched to from the decorated strategy.\n If the singleton flag is set to False, new strategy instances will be created,\n instead of always reusing the singleton object.\n ' def decorator(strategy_class): if generalize: @jit.unroll_safe def generalized_strategy_for(self, value): for strategy in generalize: if self.strategy_factory().strategy_singleton_instance(strategy)._check_can_handle(value): return strategy raise Exception(('Could not find generalized strategy for %s coming from %s' % (value, self))) strategy_class.generalized_strategy_for = generalized_strategy_for for generalized in generalize: generalized._specializations.append(strategy_class) strategy_class._is_strategy = True strategy_class._generalizations = generalize strategy_class._is_singleton = singleton return strategy_class return decorator<|docstring|>Strategy classes must be decorated with this. generalize is a list of other strategies, that can be switched to from the decorated strategy. If the singleton flag is set to False, new strategy instances will be created, instead of always reusing the singleton object.<|endoftext|>
720737c06cc64ac37635b6d4f0f6d6291ae6c3e438a77d45d2bac3eda90f84b2
def switch_strategy(self, w_self, new_strategy_type, new_element=None): '\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n ' old_strategy = self.get_strategy(w_self) if new_strategy_type._is_singleton: new_strategy = self.strategy_singleton_instance(new_strategy_type) else: size = old_strategy.size(w_self) new_strategy = self.instantiate_strategy(new_strategy_type, w_self, size) self.set_strategy(w_self, new_strategy) old_strategy._convert_storage_to(w_self, new_strategy) new_strategy.strategy_switched(w_self) self.log(w_self, new_strategy, old_strategy, new_element) return new_strategy
Switch the strategy of w_self to the new type. new_element can be given as as hint, purely for logging purposes. It should be the object that was added to w_self, causing the strategy switch.
rpython/rlib/rstrategies/rstrategies.py
switch_strategy
yxzoro/pypy
381
python
def switch_strategy(self, w_self, new_strategy_type, new_element=None): '\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n ' old_strategy = self.get_strategy(w_self) if new_strategy_type._is_singleton: new_strategy = self.strategy_singleton_instance(new_strategy_type) else: size = old_strategy.size(w_self) new_strategy = self.instantiate_strategy(new_strategy_type, w_self, size) self.set_strategy(w_self, new_strategy) old_strategy._convert_storage_to(w_self, new_strategy) new_strategy.strategy_switched(w_self) self.log(w_self, new_strategy, old_strategy, new_element) return new_strategy
def switch_strategy(self, w_self, new_strategy_type, new_element=None): '\n Switch the strategy of w_self to the new type.\n new_element can be given as as hint, purely for logging purposes.\n It should be the object that was added to w_self, causing the strategy switch.\n ' old_strategy = self.get_strategy(w_self) if new_strategy_type._is_singleton: new_strategy = self.strategy_singleton_instance(new_strategy_type) else: size = old_strategy.size(w_self) new_strategy = self.instantiate_strategy(new_strategy_type, w_self, size) self.set_strategy(w_self, new_strategy) old_strategy._convert_storage_to(w_self, new_strategy) new_strategy.strategy_switched(w_self) self.log(w_self, new_strategy, old_strategy, new_element) return new_strategy<|docstring|>Switch the strategy of w_self to the new type. new_element can be given as as hint, purely for logging purposes. It should be the object that was added to w_self, causing the strategy switch.<|endoftext|>
37f61ea697596c68bdb7964fc83123cf25c8de87f3fb5aa9797652e83d573bfd
def set_initial_strategy(self, w_self, strategy_type, size, elements=None): '\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If given, then len(elements) == size must hold.\n ' assert (self.get_strategy(w_self) is None), 'Strategy should not be initialized yet!' if strategy_type._is_singleton: strategy = self.strategy_singleton_instance(strategy_type) else: strategy = self.instantiate_strategy(strategy_type, w_self, size) self.set_strategy(w_self, strategy) strategy._initialize_storage(w_self, size) element = None if elements: strategy.store_all(w_self, elements) if (len(elements) > 0): element = elements[0] strategy.strategy_switched(w_self) self.log(w_self, strategy, None, element) return strategy
Initialize the strategy and storage fields of w_self. This must be called before switch_strategy or any strategy method can be used. elements is an optional list of values initially stored in w_self. If given, then len(elements) == size must hold.
rpython/rlib/rstrategies/rstrategies.py
set_initial_strategy
yxzoro/pypy
381
python
def set_initial_strategy(self, w_self, strategy_type, size, elements=None): '\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If given, then len(elements) == size must hold.\n ' assert (self.get_strategy(w_self) is None), 'Strategy should not be initialized yet!' if strategy_type._is_singleton: strategy = self.strategy_singleton_instance(strategy_type) else: strategy = self.instantiate_strategy(strategy_type, w_self, size) self.set_strategy(w_self, strategy) strategy._initialize_storage(w_self, size) element = None if elements: strategy.store_all(w_self, elements) if (len(elements) > 0): element = elements[0] strategy.strategy_switched(w_self) self.log(w_self, strategy, None, element) return strategy
def set_initial_strategy(self, w_self, strategy_type, size, elements=None): '\n Initialize the strategy and storage fields of w_self.\n This must be called before switch_strategy or any strategy method can be used.\n elements is an optional list of values initially stored in w_self.\n If given, then len(elements) == size must hold.\n ' assert (self.get_strategy(w_self) is None), 'Strategy should not be initialized yet!' if strategy_type._is_singleton: strategy = self.strategy_singleton_instance(strategy_type) else: strategy = self.instantiate_strategy(strategy_type, w_self, size) self.set_strategy(w_self, strategy) strategy._initialize_storage(w_self, size) element = None if elements: strategy.store_all(w_self, elements) if (len(elements) > 0): element = elements[0] strategy.strategy_switched(w_self) self.log(w_self, strategy, None, element) return strategy<|docstring|>Initialize the strategy and storage fields of w_self. This must be called before switch_strategy or any strategy method can be used. elements is an optional list of values initially stored in w_self. If given, then len(elements) == size must hold.<|endoftext|>
35a1b26dada01ff3639b39e51308b9a3144aa6e0f5a9b17babbfa86289a5c6eb
@jit.unroll_safe def strategy_type_for(self, objects): '\n Return the best-fitting strategy to hold all given objects.\n ' specialized_strategies = len(self.strategies) can_handle = ([True] * specialized_strategies) for obj in objects: if (specialized_strategies <= 1): break for (i, strategy) in enumerate(self.strategies): if (can_handle[i] and (not self.strategy_singleton_instance(strategy)._check_can_handle(obj))): can_handle[i] = False specialized_strategies -= 1 for (i, strategy_type) in enumerate(self.strategies): if can_handle[i]: return strategy_type raise ValueError(('Could not find strategy to handle: %s' % objects))
Return the best-fitting strategy to hold all given objects.
rpython/rlib/rstrategies/rstrategies.py
strategy_type_for
yxzoro/pypy
381
python
@jit.unroll_safe def strategy_type_for(self, objects): '\n \n ' specialized_strategies = len(self.strategies) can_handle = ([True] * specialized_strategies) for obj in objects: if (specialized_strategies <= 1): break for (i, strategy) in enumerate(self.strategies): if (can_handle[i] and (not self.strategy_singleton_instance(strategy)._check_can_handle(obj))): can_handle[i] = False specialized_strategies -= 1 for (i, strategy_type) in enumerate(self.strategies): if can_handle[i]: return strategy_type raise ValueError(('Could not find strategy to handle: %s' % objects))
@jit.unroll_safe def strategy_type_for(self, objects): '\n \n ' specialized_strategies = len(self.strategies) can_handle = ([True] * specialized_strategies) for obj in objects: if (specialized_strategies <= 1): break for (i, strategy) in enumerate(self.strategies): if (can_handle[i] and (not self.strategy_singleton_instance(strategy)._check_can_handle(obj))): can_handle[i] = False specialized_strategies -= 1 for (i, strategy_type) in enumerate(self.strategies): if can_handle[i]: return strategy_type raise ValueError(('Could not find strategy to handle: %s' % objects))<|docstring|>Return the best-fitting strategy to hold all given objects.<|endoftext|>
c7dc4ebc8a6e6fd49044caf51196b1e5c827ead390c33b0402792578fe6d3453
@not_rpython def decorate_strategies(self, transitions): "\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'generalize' list parameter (see @strategy decorator).\n " for (strategy_class, generalized) in transitions.items(): strategy(generalized)(strategy_class)
As an alternative to decorating all strategies with @strategy, invoke this in the constructor of your StrategyFactory subclass, before calling __init__. transitions is a dict mapping all strategy classes to their 'generalize' list parameter (see @strategy decorator).
rpython/rlib/rstrategies/rstrategies.py
decorate_strategies
yxzoro/pypy
381
python
@not_rpython def decorate_strategies(self, transitions): "\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'generalize' list parameter (see @strategy decorator).\n " for (strategy_class, generalized) in transitions.items(): strategy(generalized)(strategy_class)
@not_rpython def decorate_strategies(self, transitions): "\n As an alternative to decorating all strategies with @strategy,\n invoke this in the constructor of your StrategyFactory subclass, before\n calling __init__. transitions is a dict mapping all strategy classes to\n their 'generalize' list parameter (see @strategy decorator).\n " for (strategy_class, generalized) in transitions.items(): strategy(generalized)(strategy_class)<|docstring|>As an alternative to decorating all strategies with @strategy, invoke this in the constructor of your StrategyFactory subclass, before calling __init__. transitions is a dict mapping all strategy classes to their 'generalize' list parameter (see @strategy decorator).<|endoftext|>
edd1fc2ed97b9ea9e5e55b496a84ff771085328605319d2d858bd9296988bd65
def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0): '\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n ' return strategy_type()
Return a functional instance of strategy_type. Overwrite this if you need a non-default constructor. The two additional parameters should be ignored for singleton-strategies.
rpython/rlib/rstrategies/rstrategies.py
instantiate_strategy
yxzoro/pypy
381
python
def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0): '\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n ' return strategy_type()
def instantiate_strategy(self, strategy_type, w_self=None, initial_size=0): '\n Return a functional instance of strategy_type.\n Overwrite this if you need a non-default constructor.\n The two additional parameters should be ignored for singleton-strategies.\n ' return strategy_type()<|docstring|>Return a functional instance of strategy_type. Overwrite this if you need a non-default constructor. The two additional parameters should be ignored for singleton-strategies.<|endoftext|>
983c94a78382ecfcfc991f282356f6d6f0e2e438cf303c42e81784a8a6cfc6db
def log(self, w_self, new_strategy, old_strategy=None, new_element=None): '\n This can be overwritten into a more appropriate call to self.logger.log\n ' if (not self.logger.active): return new_strategy_str = self.log_string_for_object(new_strategy) old_strategy_str = self.log_string_for_object(old_strategy) element_typename = self.log_string_for_object(new_element) size = new_strategy.size(w_self) typename = '' cause = ('Switched' if old_strategy else 'Created') self.logger.log(new_strategy_str, size, cause, old_strategy_str, typename, element_typename)
This can be overwritten into a more appropriate call to self.logger.log
rpython/rlib/rstrategies/rstrategies.py
log
yxzoro/pypy
381
python
def log(self, w_self, new_strategy, old_strategy=None, new_element=None): '\n \n ' if (not self.logger.active): return new_strategy_str = self.log_string_for_object(new_strategy) old_strategy_str = self.log_string_for_object(old_strategy) element_typename = self.log_string_for_object(new_element) size = new_strategy.size(w_self) typename = cause = ('Switched' if old_strategy else 'Created') self.logger.log(new_strategy_str, size, cause, old_strategy_str, typename, element_typename)
def log(self, w_self, new_strategy, old_strategy=None, new_element=None): '\n \n ' if (not self.logger.active): return new_strategy_str = self.log_string_for_object(new_strategy) old_strategy_str = self.log_string_for_object(old_strategy) element_typename = self.log_string_for_object(new_element) size = new_strategy.size(w_self) typename = cause = ('Switched' if old_strategy else 'Created') self.logger.log(new_strategy_str, size, cause, old_strategy_str, typename, element_typename)<|docstring|>This can be overwritten into a more appropriate call to self.logger.log<|endoftext|>
a5e394966654b880479b065bbcd725b0e90e20eb7e56c80620697a8f8f6c11bd
@specialize.call_location() def log_string_for_object(self, obj): '\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n ' return (obj.__class__.__name__ if obj else '')
This can be overwritten instead of the entire log() method. Keep the specialize-annotation in order to handle different kinds of objects here.
rpython/rlib/rstrategies/rstrategies.py
log_string_for_object
yxzoro/pypy
381
python
@specialize.call_location() def log_string_for_object(self, obj): '\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n ' return (obj.__class__.__name__ if obj else )
@specialize.call_location() def log_string_for_object(self, obj): '\n This can be overwritten instead of the entire log() method.\n Keep the specialize-annotation in order to handle different kinds of objects here.\n ' return (obj.__class__.__name__ if obj else )<|docstring|>This can be overwritten instead of the entire log() method. Keep the specialize-annotation in order to handle different kinds of objects here.<|endoftext|>
3b6e17a11b37626c2f186aa2f81e9af0697e69f5d07c967b493ce1b7ab2337a7
def force_unicode(value): '\n Forces a bytestring to become a Unicode string.\n ' if IS_PY3: if isinstance(value, bytes): value = value.decode('utf-8', errors='replace') elif (not isinstance(value, str)): value = str(value) elif isinstance(value, str): value = value.decode('utf-8', 'replace') elif (not isinstance(value, basestring)): value = unicode(value) return value
Forces a bytestring to become a Unicode string.
pysolr.py
force_unicode
sxalexander/pysolr
0
python
def force_unicode(value): '\n \n ' if IS_PY3: if isinstance(value, bytes): value = value.decode('utf-8', errors='replace') elif (not isinstance(value, str)): value = str(value) elif isinstance(value, str): value = value.decode('utf-8', 'replace') elif (not isinstance(value, basestring)): value = unicode(value) return value
def force_unicode(value): '\n \n ' if IS_PY3: if isinstance(value, bytes): value = value.decode('utf-8', errors='replace') elif (not isinstance(value, str)): value = str(value) elif isinstance(value, str): value = value.decode('utf-8', 'replace') elif (not isinstance(value, basestring)): value = unicode(value) return value<|docstring|>Forces a bytestring to become a Unicode string.<|endoftext|>
b7d1e464fa61401108dda128682cb8ffbe6970b5ac44ffd16ff50d309a2a2392
def force_bytes(value): '\n Forces a Unicode string to become a bytestring.\n ' if IS_PY3: if isinstance(value, str): value = value.encode('utf-8') elif isinstance(value, unicode): value = value.encode('utf-8') return value
Forces a Unicode string to become a bytestring.
pysolr.py
force_bytes
sxalexander/pysolr
0
python
def force_bytes(value): '\n \n ' if IS_PY3: if isinstance(value, str): value = value.encode('utf-8') elif isinstance(value, unicode): value = value.encode('utf-8') return value
def force_bytes(value): '\n \n ' if IS_PY3: if isinstance(value, str): value = value.encode('utf-8') elif isinstance(value, unicode): value = value.encode('utf-8') return value<|docstring|>Forces a Unicode string to become a bytestring.<|endoftext|>
b8abd55ec3e727d7ba2b759e49817a9d8d70aaf939b0302a444cb8dbde019153
def unescape_html(text): '\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n ' def fixup(m): text = m.group(0) if (text[:2] == '&#'): try: if (text[:3] == '&#x'): return unicode_char(int(text[3:(- 1)], 16)) else: return unicode_char(int(text[2:(- 1)])) except ValueError: pass else: try: text = unicode_char(htmlentities.name2codepoint[text[1:(- 1)]]) except KeyError: pass return text return re.sub('&#?\\w+;', fixup, text)
Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. Source: http://effbot.org/zone/re-sub.htm#unescape-html
pysolr.py
unescape_html
sxalexander/pysolr
0
python
def unescape_html(text): '\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n ' def fixup(m): text = m.group(0) if (text[:2] == '&#'): try: if (text[:3] == '&#x'): return unicode_char(int(text[3:(- 1)], 16)) else: return unicode_char(int(text[2:(- 1)])) except ValueError: pass else: try: text = unicode_char(htmlentities.name2codepoint[text[1:(- 1)]]) except KeyError: pass return text return re.sub('&#?\\w+;', fixup, text)
def unescape_html(text): '\n Removes HTML or XML character references and entities from a text string.\n\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n\n Source: http://effbot.org/zone/re-sub.htm#unescape-html\n ' def fixup(m): text = m.group(0) if (text[:2] == '&#'): try: if (text[:3] == '&#x'): return unicode_char(int(text[3:(- 1)], 16)) else: return unicode_char(int(text[2:(- 1)])) except ValueError: pass else: try: text = unicode_char(htmlentities.name2codepoint[text[1:(- 1)]]) except KeyError: pass return text return re.sub('&#?\\w+;', fixup, text)<|docstring|>Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. Source: http://effbot.org/zone/re-sub.htm#unescape-html<|endoftext|>
bf80685693d9c5be2eab106428729c9abc8172f822ddb278150cf1bbff9ea8df
def safe_urlencode(params, doseq=0): "\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n " if IS_PY3: return urlencode(params, doseq) if hasattr(params, 'items'): params = params.items() new_params = list() for (k, v) in params: k = k.encode('utf-8') if isinstance(v, (list, tuple)): new_params.append((k, [force_bytes(i) for i in v])) elif isinstance(v, bool): new_params.append((k, force_bytes(str(v).lower()))) else: new_params.append((k, force_bytes(v))) return urlencode(new_params, doseq)
UTF-8-safe version of safe_urlencode The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values which can't fail down to ascii.
pysolr.py
safe_urlencode
sxalexander/pysolr
0
python
def safe_urlencode(params, doseq=0): "\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n " if IS_PY3: return urlencode(params, doseq) if hasattr(params, 'items'): params = params.items() new_params = list() for (k, v) in params: k = k.encode('utf-8') if isinstance(v, (list, tuple)): new_params.append((k, [force_bytes(i) for i in v])) elif isinstance(v, bool): new_params.append((k, force_bytes(str(v).lower()))) else: new_params.append((k, force_bytes(v))) return urlencode(new_params, doseq)
def safe_urlencode(params, doseq=0): "\n UTF-8-safe version of safe_urlencode\n\n The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n which can't fail down to ascii.\n " if IS_PY3: return urlencode(params, doseq) if hasattr(params, 'items'): params = params.items() new_params = list() for (k, v) in params: k = k.encode('utf-8') if isinstance(v, (list, tuple)): new_params.append((k, [force_bytes(i) for i in v])) elif isinstance(v, bool): new_params.append((k, force_bytes(str(v).lower()))) else: new_params.append((k, force_bytes(v))) return urlencode(new_params, doseq)<|docstring|>UTF-8-safe version of safe_urlencode The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values which can't fail down to ascii.<|endoftext|>
6a5792bdc6a3854a197a58f998694d0671d6c5d6e914fe99efc1951a8a5927c1
def _extract_error(self, resp): '\n Extract the actual error message from a solr response.\n ' reason = resp.headers.get('reason', None) full_html = None if (reason is None): (reason, full_html) = self._scrape_response(resp.headers, resp.content) msg = ('[Reason: %s]' % reason) if (reason is None): msg += ('\n%s' % unescape_html(full_html)) return msg
Extract the actual error message from a solr response.
pysolr.py
_extract_error
sxalexander/pysolr
0
python
def _extract_error(self, resp): '\n \n ' reason = resp.headers.get('reason', None) full_html = None if (reason is None): (reason, full_html) = self._scrape_response(resp.headers, resp.content) msg = ('[Reason: %s]' % reason) if (reason is None): msg += ('\n%s' % unescape_html(full_html)) return msg
def _extract_error(self, resp): '\n \n ' reason = resp.headers.get('reason', None) full_html = None if (reason is None): (reason, full_html) = self._scrape_response(resp.headers, resp.content) msg = ('[Reason: %s]' % reason) if (reason is None): msg += ('\n%s' % unescape_html(full_html)) return msg<|docstring|>Extract the actual error message from a solr response.<|endoftext|>
19736f67eb930385f2a2c8dbebca60eacc0ec8cd377cbc536035d897dd520d90
def _scrape_response(self, headers, response): '\n Scrape the html response.\n ' server_type = None server_string = headers.get('server', '') if (server_string and ('jetty' in server_string.lower())): server_type = 'jetty' if (server_string and ('coyote' in server_string.lower())): import lxml.html server_type = 'tomcat' reason = None full_html = '' dom_tree = None if (server_type == 'tomcat'): soup = lxml.html.fromstring(response) body_node = soup.find('body') p_nodes = body_node.cssselect('p') for p_node in p_nodes: children = p_node.getchildren() if ((len(children) >= 2) and ('message' in children[0].text.lower())): reason = children[1].text if (reason is None): from lxml.html.clean import clean_html full_html = clean_html(response) else: try: dom_tree = ET.fromstring(response) reason_node = None if (server_type == 'jetty'): reason_node = dom_tree.find('body/pre') else: reason_node = dom_tree.find('head/title') if (reason_node is not None): reason = reason_node.text if (reason is None): full_html = ET.tostring(dom_tree) except SyntaxError as err: full_html = ('%s' % response) full_html = full_html.replace('\n', '') full_html = full_html.replace('\r', '') full_html = full_html.replace('<br/>', '') full_html = full_html.replace('<br />', '') full_html = full_html.strip() return (reason, full_html)
Scrape the html response.
pysolr.py
_scrape_response
sxalexander/pysolr
0
python
def _scrape_response(self, headers, response): '\n \n ' server_type = None server_string = headers.get('server', ) if (server_string and ('jetty' in server_string.lower())): server_type = 'jetty' if (server_string and ('coyote' in server_string.lower())): import lxml.html server_type = 'tomcat' reason = None full_html = dom_tree = None if (server_type == 'tomcat'): soup = lxml.html.fromstring(response) body_node = soup.find('body') p_nodes = body_node.cssselect('p') for p_node in p_nodes: children = p_node.getchildren() if ((len(children) >= 2) and ('message' in children[0].text.lower())): reason = children[1].text if (reason is None): from lxml.html.clean import clean_html full_html = clean_html(response) else: try: dom_tree = ET.fromstring(response) reason_node = None if (server_type == 'jetty'): reason_node = dom_tree.find('body/pre') else: reason_node = dom_tree.find('head/title') if (reason_node is not None): reason = reason_node.text if (reason is None): full_html = ET.tostring(dom_tree) except SyntaxError as err: full_html = ('%s' % response) full_html = full_html.replace('\n', ) full_html = full_html.replace('\r', ) full_html = full_html.replace('<br/>', ) full_html = full_html.replace('<br />', ) full_html = full_html.strip() return (reason, full_html)
def _scrape_response(self, headers, response): '\n \n ' server_type = None server_string = headers.get('server', ) if (server_string and ('jetty' in server_string.lower())): server_type = 'jetty' if (server_string and ('coyote' in server_string.lower())): import lxml.html server_type = 'tomcat' reason = None full_html = dom_tree = None if (server_type == 'tomcat'): soup = lxml.html.fromstring(response) body_node = soup.find('body') p_nodes = body_node.cssselect('p') for p_node in p_nodes: children = p_node.getchildren() if ((len(children) >= 2) and ('message' in children[0].text.lower())): reason = children[1].text if (reason is None): from lxml.html.clean import clean_html full_html = clean_html(response) else: try: dom_tree = ET.fromstring(response) reason_node = None if (server_type == 'jetty'): reason_node = dom_tree.find('body/pre') else: reason_node = dom_tree.find('head/title') if (reason_node is not None): reason = reason_node.text if (reason is None): full_html = ET.tostring(dom_tree) except SyntaxError as err: full_html = ('%s' % response) full_html = full_html.replace('\n', ) full_html = full_html.replace('\r', ) full_html = full_html.replace('<br/>', ) full_html = full_html.replace('<br />', ) full_html = full_html.strip() return (reason, full_html)<|docstring|>Scrape the html response.<|endoftext|>
a46b632856636043bb0fa9f20c1752faa8765888a0c7d0043e53ff9c72494149
def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None): "\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (default True). This is done by default because\n these characters would cause Solr to fail to parse the XML. Only pass\n False if you're positive your data is clean.\n " path = 'update/' query_vars = [] if (commit is not None): query_vars.append(('commit=%s' % str(bool(commit)).lower())) if (waitFlush is not None): query_vars.append(('waitFlush=%s' % str(bool(waitFlush)).lower())) if (waitSearcher is not None): query_vars.append(('waitSearcher=%s' % str(bool(waitSearcher)).lower())) if query_vars: path = ('%s?%s' % (path, '&'.join(query_vars))) if clean_ctrl_chars: message = sanitize(message) return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
Posts the given xml message to http://<self.url>/update and returns the result. Passing `sanitize` as False will prevent the message from being cleaned of control characters (default True). This is done by default because these characters would cause Solr to fail to parse the XML. Only pass False if you're positive your data is clean.
pysolr.py
_update
sxalexander/pysolr
0
python
def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None): "\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (default True). This is done by default because\n these characters would cause Solr to fail to parse the XML. Only pass\n False if you're positive your data is clean.\n " path = 'update/' query_vars = [] if (commit is not None): query_vars.append(('commit=%s' % str(bool(commit)).lower())) if (waitFlush is not None): query_vars.append(('waitFlush=%s' % str(bool(waitFlush)).lower())) if (waitSearcher is not None): query_vars.append(('waitSearcher=%s' % str(bool(waitSearcher)).lower())) if query_vars: path = ('%s?%s' % (path, '&'.join(query_vars))) if clean_ctrl_chars: message = sanitize(message) return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None): "\n Posts the given xml message to http://<self.url>/update and\n returns the result.\n\n Passing `sanitize` as False will prevent the message from being cleaned\n of control characters (default True). This is done by default because\n these characters would cause Solr to fail to parse the XML. Only pass\n False if you're positive your data is clean.\n " path = 'update/' query_vars = [] if (commit is not None): query_vars.append(('commit=%s' % str(bool(commit)).lower())) if (waitFlush is not None): query_vars.append(('waitFlush=%s' % str(bool(waitFlush)).lower())) if (waitSearcher is not None): query_vars.append(('waitSearcher=%s' % str(bool(waitSearcher)).lower())) if query_vars: path = ('%s?%s' % (path, '&'.join(query_vars))) if clean_ctrl_chars: message = sanitize(message) return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})<|docstring|>Posts the given xml message to http://<self.url>/update and returns the result. Passing `sanitize` as False will prevent the message from being cleaned of control characters (default True). This is done by default because these characters would cause Solr to fail to parse the XML. Only pass False if you're positive your data is clean.<|endoftext|>
abd0dfb427e59bbaa7cd1b3bc3b3aabfdcb4a2d1d72febb39ce208e2b383e977
def _from_python(self, value): '\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n ' if hasattr(value, 'strftime'): if hasattr(value, 'hour'): value = ('%sZ' % value.isoformat()) else: value = ('%sT00:00:00Z' % value.isoformat()) elif isinstance(value, bool): if value: value = 'true' else: value = 'false' else: if IS_PY3: if isinstance(value, bytes): value = str(value, errors='replace') elif isinstance(value, str): value = unicode(value, errors='replace') value = '{0}'.format(value) return value
Converts python values to a form suitable for insertion into the xml we send to solr.
pysolr.py
_from_python
sxalexander/pysolr
0
python
def _from_python(self, value): '\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n ' if hasattr(value, 'strftime'): if hasattr(value, 'hour'): value = ('%sZ' % value.isoformat()) else: value = ('%sT00:00:00Z' % value.isoformat()) elif isinstance(value, bool): if value: value = 'true' else: value = 'false' else: if IS_PY3: if isinstance(value, bytes): value = str(value, errors='replace') elif isinstance(value, str): value = unicode(value, errors='replace') value = '{0}'.format(value) return value
def _from_python(self, value): '\n Converts python values to a form suitable for insertion into the xml\n we send to solr.\n ' if hasattr(value, 'strftime'): if hasattr(value, 'hour'): value = ('%sZ' % value.isoformat()) else: value = ('%sT00:00:00Z' % value.isoformat()) elif isinstance(value, bool): if value: value = 'true' else: value = 'false' else: if IS_PY3: if isinstance(value, bytes): value = str(value, errors='replace') elif isinstance(value, str): value = unicode(value, errors='replace') value = '{0}'.format(value) return value<|docstring|>Converts python values to a form suitable for insertion into the xml we send to solr.<|endoftext|>
87917024ec14a09d2b772ec644a6cf4038ee87c64b152394e406d0117d445461
def _to_python(self, value): '\n Converts values from Solr to native Python values.\n ' if isinstance(value, (int, float, long, complex)): return value if isinstance(value, (list, tuple)): value = value[0] if (value == 'true'): return True elif (value == 'false'): return False is_string = False if IS_PY3: if isinstance(value, bytes): value = force_unicode(value) if isinstance(value, str): is_string = True else: if isinstance(value, str): value = force_unicode(value) if isinstance(value, basestring): is_string = True if (is_string == True): possible_datetime = DATETIME_REGEX.search(value) if possible_datetime: date_values = possible_datetime.groupdict() for (dk, dv) in date_values.items(): date_values[dk] = int(dv) return datetime.datetime(date_values['year'], date_values['month'], date_values['day'], date_values['hour'], date_values['minute'], date_values['second']) try: converted_value = eval(value) if isinstance(converted_value, (list, tuple, set, dict, int, float, long, complex)): return converted_value except: pass return value
Converts values from Solr to native Python values.
pysolr.py
_to_python
sxalexander/pysolr
0
python
def _to_python(self, value): '\n \n ' if isinstance(value, (int, float, long, complex)): return value if isinstance(value, (list, tuple)): value = value[0] if (value == 'true'): return True elif (value == 'false'): return False is_string = False if IS_PY3: if isinstance(value, bytes): value = force_unicode(value) if isinstance(value, str): is_string = True else: if isinstance(value, str): value = force_unicode(value) if isinstance(value, basestring): is_string = True if (is_string == True): possible_datetime = DATETIME_REGEX.search(value) if possible_datetime: date_values = possible_datetime.groupdict() for (dk, dv) in date_values.items(): date_values[dk] = int(dv) return datetime.datetime(date_values['year'], date_values['month'], date_values['day'], date_values['hour'], date_values['minute'], date_values['second']) try: converted_value = eval(value) if isinstance(converted_value, (list, tuple, set, dict, int, float, long, complex)): return converted_value except: pass return value
def _to_python(self, value): '\n \n ' if isinstance(value, (int, float, long, complex)): return value if isinstance(value, (list, tuple)): value = value[0] if (value == 'true'): return True elif (value == 'false'): return False is_string = False if IS_PY3: if isinstance(value, bytes): value = force_unicode(value) if isinstance(value, str): is_string = True else: if isinstance(value, str): value = force_unicode(value) if isinstance(value, basestring): is_string = True if (is_string == True): possible_datetime = DATETIME_REGEX.search(value) if possible_datetime: date_values = possible_datetime.groupdict() for (dk, dv) in date_values.items(): date_values[dk] = int(dv) return datetime.datetime(date_values['year'], date_values['month'], date_values['day'], date_values['hour'], date_values['minute'], date_values['second']) try: converted_value = eval(value) if isinstance(converted_value, (list, tuple, set, dict, int, float, long, complex)): return converted_value except: pass return value<|docstring|>Converts values from Solr to native Python values.<|endoftext|>
e176a45cc2ac3088daf00445526bc119285c0ad422af430583157d919b0ec181
def _is_null_value(self, value): "\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n " if (value is None): return True if IS_PY3: if (isinstance(value, str) and (len(value) == 0)): return True elif (isinstance(value, basestring) and (len(value) == 0)): return True return False
Check if a given value is ``null``. Criteria for this is based on values that shouldn't be included in the Solr ``add`` request at all.
pysolr.py
_is_null_value
sxalexander/pysolr
0
python
def _is_null_value(self, value): "\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n " if (value is None): return True if IS_PY3: if (isinstance(value, str) and (len(value) == 0)): return True elif (isinstance(value, basestring) and (len(value) == 0)): return True return False
def _is_null_value(self, value): "\n Check if a given value is ``null``.\n\n Criteria for this is based on values that shouldn't be included\n in the Solr ``add`` request at all.\n " if (value is None): return True if IS_PY3: if (isinstance(value, str) and (len(value) == 0)): return True elif (isinstance(value, basestring) and (len(value) == 0)): return True return False<|docstring|>Check if a given value is ``null``. Criteria for this is based on values that shouldn't be included in the Solr ``add`` request at all.<|endoftext|>
6ca32e6850954a7332c1c6df4e092a36435983dec7a081fcd56c0d9f466d272c
def search(self, q, **kwargs): "\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n results = solr.search('*:*')\n\n # Search with highlighting.\n results = solr.search('ponies', **{\n 'hl': 'true',\n 'hl.fragsize': 10,\n })\n\n " params = {'q': q} params.update(kwargs) response = self._select(params) result = self.decoder.decode(response) result_kwargs = {} if result.get('debug'): result_kwargs['debug'] = result['debug'] if result.get('highlighting'): result_kwargs['highlighting'] = result['highlighting'] if result.get('facet_counts'): result_kwargs['facets'] = result['facet_counts'] if result.get('spellcheck'): result_kwargs['spellcheck'] = result['spellcheck'] if result.get('stats'): result_kwargs['stats'] = result['stats'] if ('QTime' in result.get('responseHeader', {})): result_kwargs['qtime'] = result['responseHeader']['QTime'] if result.get('grouped'): result_kwargs['grouped'] = result['grouped'] response = (result.get('response') or {}) numFound = response.get('numFound', 0) self.log.debug("Found '%s' search results.", numFound) return Results(response.get('docs', ()), numFound, **result_kwargs)
Performs a search and returns the results. Requires a ``q`` for a string version of the query to run. Optionally accepts ``**kwargs`` for additional options to be passed through the Solr URL. Usage:: # All docs. results = solr.search('*:*') # Search with highlighting. results = solr.search('ponies', **{ 'hl': 'true', 'hl.fragsize': 10, })
pysolr.py
search
sxalexander/pysolr
0
python
def search(self, q, **kwargs): "\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n results = solr.search('*:*')\n\n # Search with highlighting.\n results = solr.search('ponies', **{\n 'hl': 'true',\n 'hl.fragsize': 10,\n })\n\n " params = {'q': q} params.update(kwargs) response = self._select(params) result = self.decoder.decode(response) result_kwargs = {} if result.get('debug'): result_kwargs['debug'] = result['debug'] if result.get('highlighting'): result_kwargs['highlighting'] = result['highlighting'] if result.get('facet_counts'): result_kwargs['facets'] = result['facet_counts'] if result.get('spellcheck'): result_kwargs['spellcheck'] = result['spellcheck'] if result.get('stats'): result_kwargs['stats'] = result['stats'] if ('QTime' in result.get('responseHeader', {})): result_kwargs['qtime'] = result['responseHeader']['QTime'] if result.get('grouped'): result_kwargs['grouped'] = result['grouped'] response = (result.get('response') or {}) numFound = response.get('numFound', 0) self.log.debug("Found '%s' search results.", numFound) return Results(response.get('docs', ()), numFound, **result_kwargs)
def search(self, q, **kwargs): "\n Performs a search and returns the results.\n\n Requires a ``q`` for a string version of the query to run.\n\n Optionally accepts ``**kwargs`` for additional options to be passed\n through the Solr URL.\n\n Usage::\n\n # All docs.\n results = solr.search('*:*')\n\n # Search with highlighting.\n results = solr.search('ponies', **{\n 'hl': 'true',\n 'hl.fragsize': 10,\n })\n\n " params = {'q': q} params.update(kwargs) response = self._select(params) result = self.decoder.decode(response) result_kwargs = {} if result.get('debug'): result_kwargs['debug'] = result['debug'] if result.get('highlighting'): result_kwargs['highlighting'] = result['highlighting'] if result.get('facet_counts'): result_kwargs['facets'] = result['facet_counts'] if result.get('spellcheck'): result_kwargs['spellcheck'] = result['spellcheck'] if result.get('stats'): result_kwargs['stats'] = result['stats'] if ('QTime' in result.get('responseHeader', {})): result_kwargs['qtime'] = result['responseHeader']['QTime'] if result.get('grouped'): result_kwargs['grouped'] = result['grouped'] response = (result.get('response') or {}) numFound = response.get('numFound', 0) self.log.debug("Found '%s' search results.", numFound) return Results(response.get('docs', ()), numFound, **result_kwargs)<|docstring|>Performs a search and returns the results. Requires a ``q`` for a string version of the query to run. Optionally accepts ``**kwargs`` for additional options to be passed through the Solr URL. Usage:: # All docs. results = solr.search('*:*') # Search with highlighting. results = solr.search('ponies', **{ 'hl': 'true', 'hl.fragsize': 10, })<|endoftext|>
19580121e9eeb78f51e26d0e031020eee3a782bf4ea00cb206de454e1114122c
def more_like_this(self, q, mltfl, **kwargs): "\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n " params = {'q': q, 'mlt.fl': mltfl} params.update(kwargs) response = self._mlt(params) result = self.decoder.decode(response) if (result['response'] is None): result['response'] = {'docs': [], 'numFound': 0} self.log.debug("Found '%s' MLT results.", result['response']['numFound']) return Results(result['response']['docs'], result['response']['numFound'])
Finds and returns results similar to the provided query. Requires Solr 1.3+. Usage:: similar = solr.more_like_this('id:doc_234', 'text')
pysolr.py
more_like_this
sxalexander/pysolr
0
python
def more_like_this(self, q, mltfl, **kwargs): "\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n " params = {'q': q, 'mlt.fl': mltfl} params.update(kwargs) response = self._mlt(params) result = self.decoder.decode(response) if (result['response'] is None): result['response'] = {'docs': [], 'numFound': 0} self.log.debug("Found '%s' MLT results.", result['response']['numFound']) return Results(result['response']['docs'], result['response']['numFound'])
def more_like_this(self, q, mltfl, **kwargs): "\n Finds and returns results similar to the provided query.\n\n Requires Solr 1.3+.\n\n Usage::\n\n similar = solr.more_like_this('id:doc_234', 'text')\n\n " params = {'q': q, 'mlt.fl': mltfl} params.update(kwargs) response = self._mlt(params) result = self.decoder.decode(response) if (result['response'] is None): result['response'] = {'docs': [], 'numFound': 0} self.log.debug("Found '%s' MLT results.", result['response']['numFound']) return Results(result['response']['docs'], result['response']['numFound'])<|docstring|>Finds and returns results similar to the provided query. Requires Solr 1.3+. Usage:: similar = solr.more_like_this('id:doc_234', 'text')<|endoftext|>
2ca098c6c46917db2c1a8c3a39b6271cea47ad551b33b7fcbddf37429536c5ad
def suggest_terms(self, fields, prefix, **kwargs): '\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n ' params = {'terms.fl': fields, 'terms.prefix': prefix} params.update(kwargs) response = self._suggest_terms(params) result = self.decoder.decode(response) terms = result.get('terms', {}) res = {} if isinstance(terms, (list, tuple)): terms = dict(zip(terms[0::2], terms[1::2])) for (field, values) in terms.items(): tmp = list() while values: tmp.append((values.pop(0), values.pop(0))) res[field] = tmp self.log.debug("Found '%d' Term suggestions results.", sum((len(j) for (i, j) in res.items()))) return res
Accepts a list of field names and a prefix Returns a dictionary keyed on field name containing a list of ``(term, count)`` pairs Requires Solr 1.4+.
pysolr.py
suggest_terms
sxalexander/pysolr
0
python
def suggest_terms(self, fields, prefix, **kwargs): '\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n ' params = {'terms.fl': fields, 'terms.prefix': prefix} params.update(kwargs) response = self._suggest_terms(params) result = self.decoder.decode(response) terms = result.get('terms', {}) res = {} if isinstance(terms, (list, tuple)): terms = dict(zip(terms[0::2], terms[1::2])) for (field, values) in terms.items(): tmp = list() while values: tmp.append((values.pop(0), values.pop(0))) res[field] = tmp self.log.debug("Found '%d' Term suggestions results.", sum((len(j) for (i, j) in res.items()))) return res
def suggest_terms(self, fields, prefix, **kwargs): '\n Accepts a list of field names and a prefix\n\n Returns a dictionary keyed on field name containing a list of\n ``(term, count)`` pairs\n\n Requires Solr 1.4+.\n ' params = {'terms.fl': fields, 'terms.prefix': prefix} params.update(kwargs) response = self._suggest_terms(params) result = self.decoder.decode(response) terms = result.get('terms', {}) res = {} if isinstance(terms, (list, tuple)): terms = dict(zip(terms[0::2], terms[1::2])) for (field, values) in terms.items(): tmp = list() while values: tmp.append((values.pop(0), values.pop(0))) res[field] = tmp self.log.debug("Found '%d' Term suggestions results.", sum((len(j) for (i, j) in res.items()))) return res<|docstring|>Accepts a list of field names and a prefix Returns a dictionary keyed on field name containing a list of ``(term, count)`` pairs Requires Solr 1.4+.<|endoftext|>
0f2f8a1850db521077d209ef3b0c07fe65a30dfc574ab10466c11a89de2507cb
def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None): '\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``boost``. Default is ``None``.\n\n Optionally accepts ``commitWithin``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.add([\n {\n "id": "doc_1",\n "title": "A test document",\n },\n {\n "id": "doc_2",\n "title": "The Banana: Tasty or Dangerous?",\n },\n ])\n ' start_time = time.time() self.log.debug('Starting to build add request...') message = ET.Element('add') if commitWithin: message.set('commitWithin', commitWithin) for doc in docs: message.append(self._build_doc(doc, boost=boost)) m = ET.tostring(message, encoding='utf-8') m = force_unicode(m) end_time = time.time() self.log.debug('Built add request of %s docs in %0.2f seconds.', len(docs), (end_time - start_time)) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field name and each value is the value to index. Optionally accepts ``commit``. Default is ``True``. Optionally accepts ``boost``. Default is ``None``. Optionally accepts ``commitWithin``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.add([ { "id": "doc_1", "title": "A test document", }, { "id": "doc_2", "title": "The Banana: Tasty or Dangerous?", }, ])
pysolr.py
add
sxalexander/pysolr
0
python
def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None): '\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``boost``. Default is ``None``.\n\n Optionally accepts ``commitWithin``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.add([\n {\n "id": "doc_1",\n "title": "A test document",\n },\n {\n "id": "doc_2",\n "title": "The Banana: Tasty or Dangerous?",\n },\n ])\n ' start_time = time.time() self.log.debug('Starting to build add request...') message = ET.Element('add') if commitWithin: message.set('commitWithin', commitWithin) for doc in docs: message.append(self._build_doc(doc, boost=boost)) m = ET.tostring(message, encoding='utf-8') m = force_unicode(m) end_time = time.time() self.log.debug('Built add request of %s docs in %0.2f seconds.', len(docs), (end_time - start_time)) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
def add(self, docs, commit=True, boost=None, commitWithin=None, waitFlush=None, waitSearcher=None): '\n Adds or updates documents.\n\n Requires ``docs``, which is a list of dictionaries. Each key is the\n field name and each value is the value to index.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``boost``. Default is ``None``.\n\n Optionally accepts ``commitWithin``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.add([\n {\n "id": "doc_1",\n "title": "A test document",\n },\n {\n "id": "doc_2",\n "title": "The Banana: Tasty or Dangerous?",\n },\n ])\n ' start_time = time.time() self.log.debug('Starting to build add request...') message = ET.Element('add') if commitWithin: message.set('commitWithin', commitWithin) for doc in docs: message.append(self._build_doc(doc, boost=boost)) m = ET.tostring(message, encoding='utf-8') m = force_unicode(m) end_time = time.time() self.log.debug('Built add request of %s docs in %0.2f seconds.', len(docs), (end_time - start_time)) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)<|docstring|>Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field name and each value is the value to index. Optionally accepts ``commit``. Default is ``True``. Optionally accepts ``boost``. Default is ``None``. Optionally accepts ``commitWithin``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.add([ { "id": "doc_1", "title": "A test document", }, { "id": "doc_2", "title": "The Banana: Tasty or Dangerous?", }, ])<|endoftext|>
75289f38ff47d9392d33529450f8108f98a298646e114f9c4f1a99d644f8b20b
def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None): "\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to delete.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.delete(id='doc_12')\n solr.delete(q='*:*')\n\n " if ((id is None) and (q is None)): raise ValueError('You must specify "id" or "q".') elif ((id is not None) and (q is not None)): raise ValueError('You many only specify "id" OR "q", not both.') elif (id is not None): m = ('<delete><id>%s</id></delete>' % id) elif (q is not None): m = ('<delete><query>%s</query></delete>' % q) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
Deletes documents. Requires *either* ``id`` or ``query``. ``id`` is if you know the specific document id to remove. ``query`` is a Lucene-style query indicating a collection of documents to delete. Optionally accepts ``commit``. Default is ``True``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.delete(id='doc_12') solr.delete(q='*:*')
pysolr.py
delete
sxalexander/pysolr
0
python
def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None): "\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to delete.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.delete(id='doc_12')\n solr.delete(q='*:*')\n\n " if ((id is None) and (q is None)): raise ValueError('You must specify "id" or "q".') elif ((id is not None) and (q is not None)): raise ValueError('You many only specify "id" OR "q", not both.') elif (id is not None): m = ('<delete><id>%s</id></delete>' % id) elif (q is not None): m = ('<delete><query>%s</query></delete>' % q) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None): "\n Deletes documents.\n\n Requires *either* ``id`` or ``query``. ``id`` is if you know the\n specific document id to remove. ``query`` is a Lucene-style query\n indicating a collection of documents to delete.\n\n Optionally accepts ``commit``. Default is ``True``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.delete(id='doc_12')\n solr.delete(q='*:*')\n\n " if ((id is None) and (q is None)): raise ValueError('You must specify "id" or "q".') elif ((id is not None) and (q is not None)): raise ValueError('You many only specify "id" OR "q", not both.') elif (id is not None): m = ('<delete><id>%s</id></delete>' % id) elif (q is not None): m = ('<delete><query>%s</query></delete>' % q) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)<|docstring|>Deletes documents. Requires *either* ``id`` or ``query``. ``id`` is if you know the specific document id to remove. ``query`` is a Lucene-style query indicating a collection of documents to delete. Optionally accepts ``commit``. Default is ``True``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.delete(id='doc_12') solr.delete(q='*:*')<|endoftext|>
8a659b9c0b01fc28a9da2ad37f0d4a249b22146595ef871b5116cf2e28162985
def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None): '\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.commit()\n\n ' if (expungeDeletes is not None): msg = ('<commit expungeDeletes="%s" />' % str(bool(expungeDeletes)).lower()) else: msg = '<commit />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)
Forces Solr to write the index data to disk. Optionally accepts ``expungeDeletes``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.commit()
pysolr.py
commit
sxalexander/pysolr
0
python
def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None): '\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.commit()\n\n ' if (expungeDeletes is not None): msg = ('<commit expungeDeletes="%s" />' % str(bool(expungeDeletes)).lower()) else: msg = '<commit />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)
def commit(self, waitFlush=None, waitSearcher=None, expungeDeletes=None): '\n Forces Solr to write the index data to disk.\n\n Optionally accepts ``expungeDeletes``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.commit()\n\n ' if (expungeDeletes is not None): msg = ('<commit expungeDeletes="%s" />' % str(bool(expungeDeletes)).lower()) else: msg = '<commit />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)<|docstring|>Forces Solr to write the index data to disk. Optionally accepts ``expungeDeletes``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.commit()<|endoftext|>
e845101921b8a12e4470e8992191e1857574eecd4679374646d91d1434bfdd2a
def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None): '\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.optimize()\n\n ' if maxSegments: msg = ('<optimize maxSegments="%d" />' % maxSegments) else: msg = '<optimize />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)
Tells Solr to streamline the number of segments used, essentially a defragmentation operation. Optionally accepts ``maxSegments``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.optimize()
pysolr.py
optimize
sxalexander/pysolr
0
python
def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None): '\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.optimize()\n\n ' if maxSegments: msg = ('<optimize maxSegments="%d" />' % maxSegments) else: msg = '<optimize />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)
def optimize(self, waitFlush=None, waitSearcher=None, maxSegments=None): '\n Tells Solr to streamline the number of segments used, essentially a\n defragmentation operation.\n\n Optionally accepts ``maxSegments``. Default is ``None``.\n\n Optionally accepts ``waitFlush``. Default is ``None``.\n\n Optionally accepts ``waitSearcher``. Default is ``None``.\n\n Usage::\n\n solr.optimize()\n\n ' if maxSegments: msg = ('<optimize maxSegments="%d" />' % maxSegments) else: msg = '<optimize />' return self._update(msg, waitFlush=waitFlush, waitSearcher=waitSearcher)<|docstring|>Tells Solr to streamline the number of segments used, essentially a defragmentation operation. Optionally accepts ``maxSegments``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: solr.optimize()<|endoftext|>
8ded1cebf5a05532b511a7db6307d5e911ca423dbaee42b26fa151c4a42c9666
def extract(self, file_obj, extractOnly=True, **kwargs): "\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandler has a very simply model: it extracts\n contents and metadata from the uploaded file and inserts it directly\n into the index. This is rarely useful as it allows no way to store\n additional data or otherwise customize the record. Instead, by default\n we'll use the extract-only mode to extract the data without indexing it\n so the caller has the opportunity to process it as appropriate; call\n with ``extractOnly=False`` if you want to insert with no additional\n processing.\n\n Returns None if metadata cannot be extracted; otherwise returns a\n dictionary containing at least two keys:\n\n :contents:\n Extracted full-text content, if applicable\n :metadata:\n key:value pairs of text strings\n " if (not hasattr(file_obj, 'name')): raise ValueError('extract() requires file-like objects which have a defined name property') params = {'extractOnly': ('true' if extractOnly else 'false'), 'lowernames': 'true', 'wt': 'json'} params.update(kwargs) try: resp = self._send_request('post', 'update/extract', body=params, files={'file': (file_obj.name, file_obj)}) except (IOError, SolrError) as err: self.log.error('Failed to extract document metadata: %s', err, exc_info=True) raise try: data = json.loads(resp) except ValueError as err: self.log.error('Failed to load JSON response: %s', err, exc_info=True) raise data['contents'] = data.pop(file_obj.name, None) data['metadata'] = metadata = {} raw_metadata = data.pop(('%s_metadata' % file_obj.name), None) if raw_metadata: while raw_metadata: metadata[raw_metadata.pop()] = raw_metadata.pop() return data
POSTs a file to the Solr ExtractingRequestHandler so rich content can be processed using Apache Tika. See the Solr wiki for details: http://wiki.apache.org/solr/ExtractingRequestHandler The ExtractingRequestHandler has a very simply model: it extracts contents and metadata from the uploaded file and inserts it directly into the index. This is rarely useful as it allows no way to store additional data or otherwise customize the record. Instead, by default we'll use the extract-only mode to extract the data without indexing it so the caller has the opportunity to process it as appropriate; call with ``extractOnly=False`` if you want to insert with no additional processing. Returns None if metadata cannot be extracted; otherwise returns a dictionary containing at least two keys: :contents: Extracted full-text content, if applicable :metadata: key:value pairs of text strings
pysolr.py
extract
sxalexander/pysolr
0
python
def extract(self, file_obj, extractOnly=True, **kwargs): "\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandler has a very simply model: it extracts\n contents and metadata from the uploaded file and inserts it directly\n into the index. This is rarely useful as it allows no way to store\n additional data or otherwise customize the record. Instead, by default\n we'll use the extract-only mode to extract the data without indexing it\n so the caller has the opportunity to process it as appropriate; call\n with ``extractOnly=False`` if you want to insert with no additional\n processing.\n\n Returns None if metadata cannot be extracted; otherwise returns a\n dictionary containing at least two keys:\n\n :contents:\n Extracted full-text content, if applicable\n :metadata:\n key:value pairs of text strings\n " if (not hasattr(file_obj, 'name')): raise ValueError('extract() requires file-like objects which have a defined name property') params = {'extractOnly': ('true' if extractOnly else 'false'), 'lowernames': 'true', 'wt': 'json'} params.update(kwargs) try: resp = self._send_request('post', 'update/extract', body=params, files={'file': (file_obj.name, file_obj)}) except (IOError, SolrError) as err: self.log.error('Failed to extract document metadata: %s', err, exc_info=True) raise try: data = json.loads(resp) except ValueError as err: self.log.error('Failed to load JSON response: %s', err, exc_info=True) raise data['contents'] = data.pop(file_obj.name, None) data['metadata'] = metadata = {} raw_metadata = data.pop(('%s_metadata' % file_obj.name), None) if raw_metadata: while raw_metadata: metadata[raw_metadata.pop()] = raw_metadata.pop() return data
def extract(self, file_obj, extractOnly=True, **kwargs): "\n POSTs a file to the Solr ExtractingRequestHandler so rich content can\n be processed using Apache Tika. See the Solr wiki for details:\n\n http://wiki.apache.org/solr/ExtractingRequestHandler\n\n The ExtractingRequestHandler has a very simply model: it extracts\n contents and metadata from the uploaded file and inserts it directly\n into the index. This is rarely useful as it allows no way to store\n additional data or otherwise customize the record. Instead, by default\n we'll use the extract-only mode to extract the data without indexing it\n so the caller has the opportunity to process it as appropriate; call\n with ``extractOnly=False`` if you want to insert with no additional\n processing.\n\n Returns None if metadata cannot be extracted; otherwise returns a\n dictionary containing at least two keys:\n\n :contents:\n Extracted full-text content, if applicable\n :metadata:\n key:value pairs of text strings\n " if (not hasattr(file_obj, 'name')): raise ValueError('extract() requires file-like objects which have a defined name property') params = {'extractOnly': ('true' if extractOnly else 'false'), 'lowernames': 'true', 'wt': 'json'} params.update(kwargs) try: resp = self._send_request('post', 'update/extract', body=params, files={'file': (file_obj.name, file_obj)}) except (IOError, SolrError) as err: self.log.error('Failed to extract document metadata: %s', err, exc_info=True) raise try: data = json.loads(resp) except ValueError as err: self.log.error('Failed to load JSON response: %s', err, exc_info=True) raise data['contents'] = data.pop(file_obj.name, None) data['metadata'] = metadata = {} raw_metadata = data.pop(('%s_metadata' % file_obj.name), None) if raw_metadata: while raw_metadata: metadata[raw_metadata.pop()] = raw_metadata.pop() return data<|docstring|>POSTs a file to the Solr ExtractingRequestHandler so rich content can be processed using Apache Tika. See the Solr wiki for details: http://wiki.apache.org/solr/ExtractingRequestHandler The ExtractingRequestHandler has a very simply model: it extracts contents and metadata from the uploaded file and inserts it directly into the index. This is rarely useful as it allows no way to store additional data or otherwise customize the record. Instead, by default we'll use the extract-only mode to extract the data without indexing it so the caller has the opportunity to process it as appropriate; call with ``extractOnly=False`` if you want to insert with no additional processing. Returns None if metadata cannot be extracted; otherwise returns a dictionary containing at least two keys: :contents: Extracted full-text content, if applicable :metadata: key:value pairs of text strings<|endoftext|>
fd9be8845f84bcb40b78aec56dd24ebf9115c9e03ac46a9b225d434e93f5454d
def status(self, core=None): 'http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953' params = {'action': 'STATUS'} if (core is not None): params.update(core=core) return self._get_url(params=params)
http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953
pysolr.py
status
sxalexander/pysolr
0
python
def status(self, core=None): params = {'action': 'STATUS'} if (core is not None): params.update(core=core) return self._get_url(params=params)
def status(self, core=None): params = {'action': 'STATUS'} if (core is not None): params.update(core=core) return self._get_url(params=params)<|docstring|>http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953<|endoftext|>