repo_name
stringlengths
7
94
repo_path
stringlengths
4
237
repo_head_hexsha
stringlengths
40
40
content
stringlengths
10
680k
apis
stringlengths
2
680k
MTES-MCT/sparte
public_data/serializers.py
3b8ae6d21da81ca761d64ae9dfe2c8f54487211c
from rest_framework_gis import serializers from rest_framework import serializers as s from .models import ( Artificialisee2015to2018, Artificielle2018, CommunesSybarval, CouvertureSol, EnveloppeUrbaine2018, Ocsge, Renaturee2018to2015, Sybarval, Voirie2018, ZonesBaties2018, UsageSol, ) def get_label(code="", label=""): if code is None: code = "-" if label is None: label = "inconnu" return f"{code} {label[:30]}" class Artificialisee2015to2018Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Artificialisee2015to2018 class Artificielle2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "surface", "couverture", ) geo_field = "mpoly" model = Artificielle2018 class CommunesSybarvalSerializer(serializers.GeoFeatureModelSerializer): """Marker GeoJSON serializer.""" class Meta: """Marker serializer meta class.""" fields = ( "nom", "code_insee", "surface", ) geo_field = "mpoly" model = CommunesSybarval class EnveloppeUrbaine2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "couverture", "surface", ) geo_field = "mpoly" model = EnveloppeUrbaine2018 class OcsgeSerializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "millesime", "map_color", "year", ) geo_field = "mpoly" model = Ocsge class Renaturee2018to2015Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Renaturee2018to2015 class SybarvalSerializer(serializers.GeoFeatureModelSerializer): class Meta: fields = ( "id", "surface", ) geo_field = "mpoly" model = Sybarval class Voirie2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "surface", "couverture", "usage", ) geo_field = "mpoly" model = Voirie2018 class ZonesBaties2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "surface", ) geo_field = "mpoly" model = ZonesBaties2018 class CouvertureSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", "is_artificial", ) model = CouvertureSol class UsageSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", ) model = UsageSol
[((590, 615), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (613, 615), True, 'from rest_framework import serializers as s\n'), ((633, 658), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (656, 658), True, 'from rest_framework import serializers as s\n'), ((681, 706), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (704, 706), True, 'from rest_framework import serializers as s\n'), ((729, 754), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (752, 754), True, 'from rest_framework import serializers as s\n'), ((1543, 1568), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (1566, 1568), True, 'from rest_framework import serializers as s\n'), ((2281, 2306), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (2304, 2306), True, 'from rest_framework import serializers as s\n'), ((2676, 2701), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (2699, 2701), True, 'from rest_framework import serializers as s\n'), ((2714, 2739), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (2737, 2739), True, 'from rest_framework import serializers as s\n'), ((3271, 3296), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (3294, 3296), True, 'from rest_framework import serializers as s\n'), ((3314, 3339), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (3337, 3339), True, 'from rest_framework import serializers as s\n'), ((3362, 3387), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (3385, 3387), True, 'from rest_framework import serializers as s\n'), ((3410, 3435), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (3433, 3435), True, 'from rest_framework import serializers as s\n'), ((4419, 4444), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (4442, 4444), True, 'from rest_framework import serializers as s\n'), ((4457, 4482), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (4480, 4482), True, 'from rest_framework import serializers as s\n'), ((4968, 4993), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (4991, 4993), True, 'from rest_framework import serializers as s\n'), ((5006, 5031), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ([], {}), '()\n', (5029, 5031), True, 'from rest_framework import serializers as s\n')]
naman1901/django-quick-search
quick_search/admin.py
7b93554ed9fa4721e52372f9fd1a395d94cc04a7
from django.contrib import admin from .models import SearchResult # Register your models here. class SearchResultAdmin(admin.ModelAdmin): fields = ["query", "heading", "url", "text"] admin.site.register(SearchResult, SearchResultAdmin)
[((189, 241), 'django.contrib.admin.site.register', 'admin.site.register', (['SearchResult', 'SearchResultAdmin'], {}), '(SearchResult, SearchResultAdmin)\n', (208, 241), False, 'from django.contrib import admin\n')]
Amirali-Shirkh/rasa-for-botfront
rasa/train.py
36aa24ad31241c5d1a180bbe34e1c8c50da40ff7
import asyncio import os import tempfile from contextlib import ExitStack from typing import Text, Optional, List, Union, Dict from rasa.importers.importer import TrainingDataImporter from rasa import model from rasa.model import FingerprintComparisonResult from rasa.core.domain import Domain from rasa.utils.common import TempDirectoryPath from rasa.cli.utils import ( print_success, print_warning, print_error, bcolors, print_color, ) from rasa.constants import DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME def train( domain: Text, config: Text, training_files: Union[Text, List[Text]], output: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None, ) -> Optional[Text]: if loop is None: try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete( train_async( domain=domain, config=config, training_files=training_files, output_path=output, force_training=force_training, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) ) async def train_async( domain: Union[Domain, Text], config: Dict[Text, Text], training_files: Optional[Union[Text, List[Text]]], output_path: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Args: domain: Path to the domain file. config: Dict of paths to the config for Core and NLU. Keys are language codes training_files: Paths to the training data for Core and NLU. output_path: Output path. force_training: If `True` retrain model even if data has not changed. fixed_model_name: Name of model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ # file_importer = TrainingDataImporter.load_from_config( # config, domain, training_files # ) with ExitStack() as stack: train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod from rasa_addons.importers import BotfrontFileImporter file_importer = BotfrontFileImporter(config, domain, training_files) # domain = await file_importer.get_domain() # if domain.is_empty(): # return await handle_domain_if_not_exists( # file_importer, output_path, fixed_model_name # ) # /bf mod return await _train_async_internal( file_importer, train_path, output_path, force_training, fixed_model_name, persist_nlu_training_data, additional_arguments, ) async def handle_domain_if_not_exists( file_importer: TrainingDataImporter, output_path, fixed_model_name ): nlu_model_only = await _train_nlu_with_validated_data( file_importer, output=output_path, fixed_model_name=fixed_model_name ) print_warning( "Core training was skipped because no valid domain file was found. Only an nlu-model was created." "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return nlu_model_only async def _train_async_internal( file_importer: TrainingDataImporter, train_path: Text, output_path: Text, force_training: bool, fixed_model_name: Optional[Text], persist_nlu_training_data: bool, additional_arguments: Optional[Dict], ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Use only from `train_async`. Args: file_importer: `TrainingDataImporter` which supplies the training data. train_path: Directory in which to train the model. output_path: Output path. force_training: If `True` retrain model even if data has not changed. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. fixed_model_name: Name of model to be stored. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ stories, nlu_data = await asyncio.gather( file_importer.get_stories(), file_importer.get_nlu_data() ) # if stories.is_empty() and nlu_data.is_empty(): # print_error( # "No training data given. Please provide stories and NLU data in " # "order to train a Rasa model using the '--data' argument." # ) # return # if nlu_data.is_empty(): # print_warning("No NLU data present. Just a Rasa Core model will be trained.") # return await _train_core_with_validated_data( # file_importer, # output=output_path, # fixed_model_name=fixed_model_name, # additional_arguments=additional_arguments, # ) new_fingerprint = await model.model_fingerprint(file_importer) old_model = model.get_latest_model(output_path) fingerprint_comparison = FingerprintComparisonResult(force_training=force_training) if not force_training: fingerprint_comparison = model.should_retrain( new_fingerprint, old_model, train_path ) # bf mod > if fingerprint_comparison.nlu == True: # replace True with list of all langs fingerprint_comparison.nlu = list(new_fingerprint.get("nlu-config", {}).keys()) domain = await file_importer.get_domain() core_untrainable = domain.is_empty() or stories.is_empty() nlu_untrainable = [l for l, d in nlu_data.items() if d.is_empty()] fingerprint_comparison.core = fingerprint_comparison.core and not core_untrainable fingerprint_comparison.nlu = [l for l in fingerprint_comparison.nlu if l not in nlu_untrainable] if core_untrainable: print_color("Skipping Core training since domain or stories are empty.", color=bcolors.OKBLUE) for lang in nlu_untrainable: print_color("No NLU data found for language <{}>, skipping training...".format(lang), color=bcolors.OKBLUE) # </ bf mod if fingerprint_comparison.is_training_required(): await _do_training( file_importer, output_path=output_path, train_path=train_path, fingerprint_comparison_result=fingerprint_comparison, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) return model.package_model( fingerprint=new_fingerprint, output_directory=output_path, train_path=train_path, fixed_model_name=fixed_model_name, ) print_success( "Nothing changed. You can use the old model stored at '{}'." "".format(os.path.abspath(old_model)) ) return old_model async def _do_training( file_importer: TrainingDataImporter, output_path: Text, train_path: Text, fingerprint_comparison_result: Optional[FingerprintComparisonResult] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ): if not fingerprint_comparison_result: fingerprint_comparison_result = FingerprintComparisonResult() if fingerprint_comparison_result.should_retrain_core(): await _train_core_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) elif fingerprint_comparison_result.should_retrain_nlg(): print_color( "Core stories/configuration did not change. " "Only the templates section has been changed. A new model with " "the updated templates will be created.", color=bcolors.OKBLUE, ) await model.update_model_with_new_domain(file_importer, train_path) else: print_color( "Core stories/configuration did not change. No need to retrain Core model.", color=bcolors.OKBLUE, ) if fingerprint_comparison_result.should_retrain_nlu(): await _train_nlu_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, retrain_nlu=fingerprint_comparison_result.nlu, persist_nlu_training_data=persist_nlu_training_data, ) else: print_color( "NLU data/configuration did not change. No need to retrain NLU model.", color=bcolors.OKBLUE, ) def train_core( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: loop = asyncio.get_event_loop() return loop.run_until_complete( train_core_async( domain=domain, config=config, stories=stories, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) ) async def train_core_async( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Core model. Args: domain: Path to the domain file. config: Path to the config file for Core. stories: Path to the Core training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of model to be stored. uncompress: If `True` the model will not be compressed. additional_arguments: Additional training parameters. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ file_importer = TrainingDataImporter.load_core_importer_from_config( config, domain, [stories] ) domain = await file_importer.get_domain() if domain.is_empty(): print_error( "Core training was skipped because no valid domain file was found. " "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return None if not await file_importer.get_stories(): print_error( "No stories given. Please provide stories in order to " "train a Rasa Core model using the '--stories' argument." ) return return await _train_core_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) async def _train_core_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Train Core with validated training and config data.""" import rasa.core.train with ExitStack() as stack: if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # normal (not compare) training print_color("Training Core model...", color=bcolors.OKBLUE) domain, config = await asyncio.gather( file_importer.get_domain(), file_importer.get_config() ) await rasa.core.train( domain_file=domain, training_resource=file_importer, output_path=os.path.join(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME), policy_config=config, additional_arguments=additional_arguments, ) print_color("Core model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only Core was trained. new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="core-", ) return _train_path def train_nlu( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ) -> Optional[Text]: """Trains an NLU model. Args: config: Path to the config file for NLU. nlu_data: Path to the NLU training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of the model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ loop = asyncio.get_event_loop() return loop.run_until_complete( _train_nlu_async( config, nlu_data, output, train_path, fixed_model_name, persist_nlu_training_data, ) ) async def _train_nlu_async( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ): if not nlu_data: print_error( "No NLU data given. Please provide NLU data in order to train " "a Rasa NLU model using the '--nlu' argument." ) return # training NLU only hence the training files still have to be selected file_importer = TrainingDataImporter.load_nlu_importer_from_config( config, training_data_paths=[nlu_data] ) training_datas = await file_importer.get_nlu_data() if training_datas.is_empty(): print_error( f"Path '{nlu_data}' doesn't contain valid NLU data in it. " "Please verify the data format. " "The NLU model training will be skipped now." ) return return await _train_nlu_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, ) async def _train_nlu_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, retrain_nlu: Union[bool, List[Text]] = True ) -> Optional[Text]: """Train NLU with validated training and config data.""" import rasa.nlu.train with ExitStack() as stack: models = {} from rasa.nlu import config as cfg_loader if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod config = await file_importer.get_nlu_config(retrain_nlu) for lang in config: if config[lang]: print_color("Start training {} NLU model ...".format(lang), color=bcolors.OKBLUE) _, models[lang], _ = await rasa.nlu.train( config[lang], file_importer, _train_path, fixed_model_name="nlu-{}".format(lang), persist_nlu_training_data=persist_nlu_training_data, ) else: print_color("NLU data for language <{}> didn't change, skipping training...".format(lang), color=bcolors.OKBLUE) # /bf mod print_color("NLU model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only NLU was trained new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="nlu-", ) return _train_path
[((3729, 3952), 'rasa.cli.utils.print_warning', 'print_warning', (['"""Core training was skipped because no valid domain file was found. Only an nlu-model was created.Please specify a valid domain using \'--domain\' argument or check if the provided domain file exists."""'], {}), '(\n "Core training was skipped because no valid domain file was found. Only an nlu-model was created.Please specify a valid domain using \'--domain\' argument or check if the provided domain file exists."\n )\n', (3742, 3952), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((5750, 5785), 'rasa.model.get_latest_model', 'model.get_latest_model', (['output_path'], {}), '(output_path)\n', (5772, 5785), False, 'from rasa import model\n'), ((5815, 5873), 'rasa.model.FingerprintComparisonResult', 'FingerprintComparisonResult', ([], {'force_training': 'force_training'}), '(force_training=force_training)\n', (5842, 5873), False, 'from rasa.model import FingerprintComparisonResult\n'), ((9790, 9814), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (9812, 9814), False, 'import asyncio\n'), ((11124, 11202), 'rasa.importers.importer.TrainingDataImporter.load_core_importer_from_config', 'TrainingDataImporter.load_core_importer_from_config', (['config', 'domain', '[stories]'], {}), '(config, domain, [stories])\n', (11175, 11202), False, 'from rasa.importers.importer import TrainingDataImporter\n'), ((14616, 14640), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (14638, 14640), False, 'import asyncio\n'), ((15390, 15484), 'rasa.importers.importer.TrainingDataImporter.load_nlu_importer_from_config', 'TrainingDataImporter.load_nlu_importer_from_config', (['config'], {'training_data_paths': '[nlu_data]'}), '(config,\n training_data_paths=[nlu_data])\n', (15440, 15484), False, 'from rasa.importers.importer import TrainingDataImporter\n'), ((2709, 2720), 'contextlib.ExitStack', 'ExitStack', ([], {}), '()\n', (2718, 2720), False, 'from contextlib import ExitStack\n'), ((2916, 2968), 'rasa_addons.importers.BotfrontFileImporter', 'BotfrontFileImporter', (['config', 'domain', 'training_files'], {}), '(config, domain, training_files)\n', (2936, 2968), False, 'from rasa_addons.importers import BotfrontFileImporter\n'), ((5695, 5733), 'rasa.model.model_fingerprint', 'model.model_fingerprint', (['file_importer'], {}), '(file_importer)\n', (5718, 5733), False, 'from rasa import model\n'), ((5934, 5994), 'rasa.model.should_retrain', 'model.should_retrain', (['new_fingerprint', 'old_model', 'train_path'], {}), '(new_fingerprint, old_model, train_path)\n', (5954, 5994), False, 'from rasa import model\n'), ((6604, 6702), 'rasa.cli.utils.print_color', 'print_color', (['"""Skipping Core training since domain or stories are empty."""'], {'color': 'bcolors.OKBLUE'}), "('Skipping Core training since domain or stories are empty.',\n color=bcolors.OKBLUE)\n", (6615, 6702), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((7305, 7446), 'rasa.model.package_model', 'model.package_model', ([], {'fingerprint': 'new_fingerprint', 'output_directory': 'output_path', 'train_path': 'train_path', 'fixed_model_name': 'fixed_model_name'}), '(fingerprint=new_fingerprint, output_directory=\n output_path, train_path=train_path, fixed_model_name=fixed_model_name)\n', (7324, 7446), False, 'from rasa import model\n'), ((8080, 8109), 'rasa.model.FingerprintComparisonResult', 'FingerprintComparisonResult', ([], {}), '()\n', (8107, 8109), False, 'from rasa.model import FingerprintComparisonResult\n'), ((9378, 9492), 'rasa.cli.utils.print_color', 'print_color', (['"""NLU data/configuration did not change. No need to retrain NLU model."""'], {'color': 'bcolors.OKBLUE'}), "(\n 'NLU data/configuration did not change. No need to retrain NLU model.',\n color=bcolors.OKBLUE)\n", (9389, 9492), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((11297, 11488), 'rasa.cli.utils.print_error', 'print_error', (['"""Core training was skipped because no valid domain file was found. Please specify a valid domain using \'--domain\' argument or check if the provided domain file exists."""'], {}), '(\n "Core training was skipped because no valid domain file was found. Please specify a valid domain using \'--domain\' argument or check if the provided domain file exists."\n )\n', (11308, 11488), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((11591, 11724), 'rasa.cli.utils.print_error', 'print_error', (['"""No stories given. Please provide stories in order to train a Rasa Core model using the \'--stories\' argument."""'], {}), '(\n "No stories given. Please provide stories in order to train a Rasa Core model using the \'--stories\' argument."\n )\n', (11602, 11724), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((12353, 12364), 'contextlib.ExitStack', 'ExitStack', ([], {}), '()\n', (12362, 12364), False, 'from contextlib import ExitStack\n'), ((12724, 12783), 'rasa.cli.utils.print_color', 'print_color', (['"""Training Core model..."""'], {'color': 'bcolors.OKBLUE'}), "('Training Core model...', color=bcolors.OKBLUE)\n", (12735, 12783), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((13206, 13273), 'rasa.cli.utils.print_color', 'print_color', (['"""Core model training completed."""'], {'color': 'bcolors.OKBLUE'}), "('Core model training completed.', color=bcolors.OKBLUE)\n", (13217, 13273), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((15121, 15251), 'rasa.cli.utils.print_error', 'print_error', (['"""No NLU data given. Please provide NLU data in order to train a Rasa NLU model using the \'--nlu\' argument."""'], {}), '(\n "No NLU data given. Please provide NLU data in order to train a Rasa NLU model using the \'--nlu\' argument."\n )\n', (15132, 15251), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((15594, 15750), 'rasa.cli.utils.print_error', 'print_error', (['f"""Path \'{nlu_data}\' doesn\'t contain valid NLU data in it. Please verify the data format. The NLU model training will be skipped now."""'], {}), '(\n f"Path \'{nlu_data}\' doesn\'t contain valid NLU data in it. Please verify the data format. The NLU model training will be skipped now."\n )\n', (15605, 15750), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((16444, 16455), 'contextlib.ExitStack', 'ExitStack', ([], {}), '()\n', (16453, 16455), False, 'from contextlib import ExitStack\n'), ((17559, 17625), 'rasa.cli.utils.print_color', 'print_color', (['"""NLU model training completed."""'], {'color': 'bcolors.OKBLUE'}), "('NLU model training completed.', color=bcolors.OKBLUE)\n", (17570, 17625), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((974, 998), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (996, 998), False, 'import asyncio\n'), ((7608, 7634), 'os.path.abspath', 'os.path.abspath', (['old_model'], {}), '(old_model)\n', (7623, 7634), False, 'import os\n'), ((8493, 8683), 'rasa.cli.utils.print_color', 'print_color', (['"""Core stories/configuration did not change. Only the templates section has been changed. A new model with the updated templates will be created."""'], {'color': 'bcolors.OKBLUE'}), "(\n 'Core stories/configuration did not change. Only the templates section has been changed. A new model with the updated templates will be created.'\n , color=bcolors.OKBLUE)\n", (8504, 8683), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((8833, 8953), 'rasa.cli.utils.print_color', 'print_color', (['"""Core stories/configuration did not change. No need to retrain Core model."""'], {'color': 'bcolors.OKBLUE'}), "(\n 'Core stories/configuration did not change. No need to retrain Core model.'\n , color=bcolors.OKBLUE)\n", (8844, 8953), False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((13437, 13600), 'rasa.model.package_model', 'model.package_model', ([], {'fingerprint': 'new_fingerprint', 'output_directory': 'output', 'train_path': '_train_path', 'fixed_model_name': 'fixed_model_name', 'model_prefix': '"""core-"""'}), "(fingerprint=new_fingerprint, output_directory=output,\n train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix\n ='core-')\n", (13456, 13600), False, 'from rasa import model\n'), ((17788, 17950), 'rasa.model.package_model', 'model.package_model', ([], {'fingerprint': 'new_fingerprint', 'output_directory': 'output', 'train_path': '_train_path', 'fixed_model_name': 'fixed_model_name', 'model_prefix': '"""nlu-"""'}), "(fingerprint=new_fingerprint, output_directory=output,\n train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix\n ='nlu-')\n", (17807, 17950), False, 'from rasa import model\n'), ((1047, 1071), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (1069, 1071), False, 'import asyncio\n'), ((1084, 1112), 'asyncio.set_event_loop', 'asyncio.set_event_loop', (['loop'], {}), '(loop)\n', (1106, 1112), False, 'import asyncio\n'), ((2790, 2808), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (2806, 2808), False, 'import tempfile\n'), ((8753, 8814), 'rasa.model.update_model_with_new_domain', 'model.update_model_with_new_domain', (['file_importer', 'train_path'], {}), '(file_importer, train_path)\n', (8787, 8814), False, 'from rasa import model\n'), ((13379, 13417), 'rasa.model.model_fingerprint', 'model.model_fingerprint', (['file_importer'], {}), '(file_importer)\n', (13402, 13417), False, 'from rasa import model\n'), ((17729, 17767), 'rasa.model.model_fingerprint', 'model.model_fingerprint', (['file_importer'], {}), '(file_importer)\n', (17752, 17767), False, 'from rasa import model\n'), ((12654, 12672), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (12670, 12672), False, 'import tempfile\n'), ((13040, 13097), 'os.path.join', 'os.path.join', (['_train_path', 'DEFAULT_CORE_SUBDIRECTORY_NAME'], {}), '(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME)\n', (13052, 13097), False, 'import os\n'), ((16816, 16834), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (16832, 16834), False, 'import tempfile\n')]
Jahidul007/Python-Bootcamp
coding_intereview/1475. Final Prices With a Special Discount in a Shop.py
3c870587465ff66c2c1871c8d3c4eea72463abda
class Solution: def finalPrices(self, prices: List[int]) -> List[int]: res = [] for i in range(len(prices)): for j in range(i+1,len(prices)): if prices[j]<=prices[i]: res.append(prices[i]-prices[j]) break if j==len(prices)-1: res.append(prices[i]) res.append(prices[-1]) return res
[]
timgates42/denite.nvim
rplugin/python3/denite/ui/default.py
12a9b5456f5a4600afeb0ba284ce1098bd35e501
# ============================================================================ # FILE: default.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ import re import typing from denite.util import echo, error, clearmatch, regex_convert_py_vim from denite.util import Nvim, UserContext, Candidates, Candidate from denite.parent import SyncParent class Default(object): @property def is_async(self) -> bool: return self._is_async def __init__(self, vim: Nvim) -> None: self._vim = vim self._denite: typing.Optional[SyncParent] = None self._selected_candidates: typing.List[int] = [] self._candidates: Candidates = [] self._cursor = 0 self._entire_len = 0 self._result: typing.List[typing.Any] = [] self._context: UserContext = {} self._bufnr = -1 self._winid = -1 self._winrestcmd = '' self._initialized = False self._winheight = 0 self._winwidth = 0 self._winminheight = -1 self._is_multi = False self._is_async = False self._matched_pattern = '' self._displayed_texts: typing.List[str] = [] self._statusline_sources = '' self._titlestring = '' self._ruler = False self._prev_action = '' self._prev_status: typing.Dict[str, typing.Any] = {} self._prev_curpos: typing.List[typing.Any] = [] self._save_window_options: typing.Dict[str, typing.Any] = {} self._sources_history: typing.List[typing.Any] = [] self._previous_text = '' self._floating = False self._filter_floating = False self._updated = False self._timers: typing.Dict[str, int] = {} self._matched_range_id = -1 self._matched_char_id = -1 self._check_matchdelete = bool(self._vim.call( 'denite#util#check_matchdelete')) def start(self, sources: typing.List[typing.Any], context: UserContext) -> typing.List[typing.Any]: if not self._denite: # if hasattr(self._vim, 'run_coroutine'): # self._denite = ASyncParent(self._vim) # else: self._denite = SyncParent(self._vim) self._result = [] context['sources_queue'] = [sources] self._start_sources_queue(context) return self._result def do_action(self, action_name: str, command: str = '', is_manual: bool = False) -> None: if is_manual: candidates = self._get_selected_candidates() elif self._get_cursor_candidate(): candidates = [self._get_cursor_candidate()] else: candidates = [] if not self._denite or not candidates or not action_name: return self._prev_action = action_name action = self._denite.get_action( self._context, action_name, candidates) if not action: return post_action = self._context['post_action'] is_quit = action['is_quit'] or post_action == 'quit' if is_quit: self.quit() self._denite.do_action(self._context, action_name, candidates) self._result = candidates if command != '': self._vim.command(command) if is_quit and post_action == 'open': # Re-open denite buffer prev_cursor = self._cursor cursor_candidate = self._get_cursor_candidate() self._init_buffer() self.redraw(False) if cursor_candidate == self._get_candidate(prev_cursor): # Restore the cursor self._move_to_pos(prev_cursor) # Disable quit flag is_quit = False if not is_quit and is_manual: self._selected_candidates = [] self.redraw(action['is_redraw']) if is_manual and self._context['sources_queue']: self._context['input'] = '' self._context['quick_move'] = '' self._start_sources_queue(self._context) return def redraw(self, is_force: bool = True) -> None: self._context['is_redraw'] = is_force if is_force: self._gather_candidates() if self._update_candidates(): self._update_buffer() else: self._update_status() self._context['is_redraw'] = False def quit(self) -> None: if self._denite: self._denite.on_close(self._context) self._quit_buffer() self._result = [] return def _restart(self) -> None: self._context['input'] = '' self._quit_buffer() self._init_denite() self._gather_candidates() self._init_buffer() self._update_candidates() self._update_buffer() def _start_sources_queue(self, context: UserContext) -> None: if not context['sources_queue']: return self._sources_history.append({ 'sources': context['sources_queue'][0], 'path': context['path'], }) self._start(context['sources_queue'][0], context) if context['sources_queue']: context['sources_queue'].pop(0) context['path'] = self._context['path'] def _start(self, sources: typing.List[typing.Any], context: UserContext) -> None: from denite.ui.map import do_map self._vim.command('silent! autocmd! denite') if re.search(r'\[Command Line\]$', self._vim.current.buffer.name): # Ignore command line window. return resume = self._initialized and context['resume'] if resume: # Skip the initialization update = ('immediately', 'immediately_1', 'cursor_pos', 'prev_winid', 'start_filter', 'quick_move') for key in update: self._context[key] = context[key] self._check_move_option() if self._check_do_option(): return self._init_buffer() if context['refresh']: self.redraw() self._move_to_pos(self._cursor) else: if self._context != context: self._context.clear() self._context.update(context) self._context['sources'] = sources self._context['is_redraw'] = False self._is_multi = len(sources) > 1 if not sources: # Ignore empty sources. error(self._vim, 'Empty sources') return self._init_denite() self._gather_candidates() self._update_candidates() self._init_cursor() self._check_move_option() if self._check_do_option(): return self._init_buffer() self._update_displayed_texts() self._update_buffer() self._move_to_pos(self._cursor) if self._context['quick_move'] and do_map(self, 'quick_move', []): return if self._context['start_filter']: do_map(self, 'open_filter_buffer', []) def _init_buffer(self) -> None: self._prev_status = dict() self._displayed_texts = [] self._prev_bufnr = self._vim.current.buffer.number self._prev_curpos = self._vim.call('getcurpos') self._prev_wininfo = self._get_wininfo() self._prev_winid = self._context['prev_winid'] self._winrestcmd = self._vim.call('winrestcmd') self._ruler = self._vim.options['ruler'] self._switch_buffer() self._bufnr = self._vim.current.buffer.number self._winid = self._vim.call('win_getid') self._resize_buffer(True) self._winheight = self._vim.current.window.height self._winwidth = self._vim.current.window.width self._bufvars = self._vim.current.buffer.vars self._bufvars['denite'] = { 'buffer_name': self._context['buffer_name'], } self._bufvars['denite_statusline'] = {} self._vim.vars['denite#_previewed_buffers'] = {} self._save_window_options = {} window_options = { 'colorcolumn', 'concealcursor', 'conceallevel', 'cursorcolumn', 'cursorline', 'foldcolumn', 'foldenable', 'list', 'number', 'relativenumber', 'signcolumn', 'spell', 'winfixheight', 'wrap', } for k in window_options: self._save_window_options[k] = self._vim.current.window.options[k] # Note: Have to use setlocal instead of "current.window.options" # "current.window.options" changes global value instead of local in # neovim. self._vim.command('setlocal colorcolumn=') self._vim.command('setlocal conceallevel=3') self._vim.command('setlocal concealcursor=inv') self._vim.command('setlocal nocursorcolumn') self._vim.command('setlocal nofoldenable') self._vim.command('setlocal foldcolumn=0') self._vim.command('setlocal nolist') self._vim.command('setlocal nonumber') self._vim.command('setlocal norelativenumber') self._vim.command('setlocal nospell') self._vim.command('setlocal winfixheight') self._vim.command('setlocal nowrap') if self._context['prompt']: self._vim.command('setlocal signcolumn=yes') else: self._vim.command('setlocal signcolumn=auto') if self._context['cursorline']: self._vim.command('setlocal cursorline') options = self._vim.current.buffer.options if self._floating: # Disable ruler self._vim.options['ruler'] = False options['buftype'] = 'nofile' options['bufhidden'] = 'delete' options['swapfile'] = False options['buflisted'] = False options['modeline'] = False options['modifiable'] = False options['filetype'] = 'denite' if self._vim.call('exists', '#WinEnter'): self._vim.command('doautocmd WinEnter') if self._vim.call('exists', '#BufWinEnter'): self._vim.command('doautocmd BufWinEnter') if not self._vim.call('has', 'nvim'): # In Vim8, FileType autocmd is not fired after set filetype option. self._vim.command('silent doautocmd FileType denite') if self._context['auto_action']: self._vim.command('autocmd denite ' 'CursorMoved <buffer> ' 'call denite#call_map("auto_action")') self._init_syntax() def _switch_buffer(self) -> None: split = self._context['split'] if (split != 'no' and self._winid > 0 and self._vim.call('win_gotoid', self._winid)): if split != 'vertical' and not self._floating: # Move the window to bottom self._vim.command('wincmd J') self._winrestcmd = '' return self._floating = split in [ 'floating', 'floating_relative_cursor', 'floating_relative_window', ] self._filter_floating = False if self._vim.current.buffer.options['filetype'] != 'denite': self._titlestring = self._vim.options['titlestring'] command = 'edit' if split == 'tab': self._vim.command('tabnew') elif self._floating: self._split_floating(split) elif self._context['filter_split_direction'] == 'floating': self._filter_floating = True elif split != 'no': command = self._get_direction() command += ' vsplit' if split == 'vertical' else ' split' bufname = '[denite]-' + self._context['buffer_name'] if self._vim.call('exists', '*bufadd'): bufnr = self._vim.call('bufadd', bufname) vertical = 'vertical' if split == 'vertical' else '' command = ( 'buffer' if split in ['no', 'tab', 'floating', 'floating_relative_window', 'floating_relative_cursor'] else 'sbuffer') self._vim.command( 'silent keepalt %s %s %s %s' % ( self._get_direction(), vertical, command, bufnr, ) ) else: self._vim.call( 'denite#util#execute_path', f'silent keepalt {command}', bufname) def _get_direction(self) -> str: direction = str(self._context['direction']) if direction == 'dynamictop' or direction == 'dynamicbottom': self._update_displayed_texts() winwidth = self._vim.call('winwidth', 0) is_fit = not [x for x in self._displayed_texts if self._vim.call('strwidth', x) > winwidth] if direction == 'dynamictop': direction = 'aboveleft' if is_fit else 'topleft' else: direction = 'belowright' if is_fit else 'botright' return direction def _get_wininfo(self) -> typing.List[typing.Any]: return [ self._vim.options['columns'], self._vim.options['lines'], self._vim.call('win_getid'), self._vim.call('tabpagebuflist') ] def _switch_prev_buffer(self) -> None: if (self._prev_bufnr == self._bufnr or self._vim.buffers[self._prev_bufnr].name == ''): self._vim.command('enew') else: self._vim.command('buffer ' + str(self._prev_bufnr)) def _init_syntax(self) -> None: self._vim.command('syntax case ignore') self._vim.command('highlight default link deniteInput ModeMsg') self._vim.command('highlight link deniteMatchedRange ' + self._context['highlight_matched_range']) self._vim.command('highlight link deniteMatchedChar ' + self._context['highlight_matched_char']) self._vim.command('highlight default link ' + 'deniteStatusLinePath Comment') self._vim.command('highlight default link ' + 'deniteStatusLineNumber LineNR') self._vim.command('highlight default link ' + 'deniteSelectedLine Statement') if self._floating: self._vim.current.window.options['winhighlight'] = ( 'Normal:' + self._context['highlight_window_background'] ) self._vim.command(('syntax match deniteSelectedLine /^[%s].*/' + ' contains=deniteConcealedMark') % ( self._context['selected_icon'])) self._vim.command(('syntax match deniteConcealedMark /^[ %s]/' + ' conceal contained') % ( self._context['selected_icon'])) if self._denite: self._denite.init_syntax(self._context, self._is_multi) def _update_candidates(self) -> bool: if not self._denite: return False [self._is_async, pattern, statuses, self._entire_len, self._candidates] = self._denite.filter_candidates(self._context) prev_displayed_texts = self._displayed_texts self._update_displayed_texts() prev_matched_pattern = self._matched_pattern self._matched_pattern = pattern prev_statusline_sources = self._statusline_sources self._statusline_sources = ' '.join(statuses) if self._is_async: self._start_timer('update_candidates') else: self._stop_timer('update_candidates') updated = (self._displayed_texts != prev_displayed_texts or self._matched_pattern != prev_matched_pattern or self._statusline_sources != prev_statusline_sources) if updated: self._updated = True self._start_timer('update_buffer') if self._context['search'] and self._context['input']: self._vim.call('setreg', '/', self._context['input']) return self._updated def _update_displayed_texts(self) -> None: candidates_len = len(self._candidates) if not self._is_async and self._context['auto_resize']: winminheight = self._context['winminheight'] max_height = min(self._context['winheight'], self._get_max_height()) if (winminheight != -1 and candidates_len < winminheight): self._winheight = winminheight elif candidates_len > max_height: self._winheight = max_height elif candidates_len != self._winheight: self._winheight = candidates_len max_source_name_len = 0 if self._candidates: max_source_name_len = max([ len(self._get_display_source_name(x['source_name'])) for x in self._candidates]) self._context['max_source_name_len'] = max_source_name_len self._context['max_source_name_format'] = ( '{:<' + str(self._context['max_source_name_len']) + '}') self._displayed_texts = [ self._get_candidate_display_text(i) for i in range(0, candidates_len) ] def _update_buffer(self) -> None: is_current_buffer = self._bufnr == self._vim.current.buffer.number self._update_status() if self._check_matchdelete and self._context['match_highlight']: matches = [x['id'] for x in self._vim.call('getmatches', self._winid)] if self._matched_range_id in matches: self._vim.call('matchdelete', self._matched_range_id, self._winid) self._matched_range_id = -1 if self._matched_char_id in matches: self._vim.call('matchdelete', self._matched_char_id, self._winid) self._matched_char_id = -1 if self._matched_pattern != '': self._matched_range_id = self._vim.call( 'matchadd', 'deniteMatchedRange', r'\c' + regex_convert_py_vim(self._matched_pattern), 10, -1, {'window': self._winid}) matched_char_pattern = '[{}]'.format(re.sub( r'([\[\]\\^-])', r'\\\1', self._context['input'].replace(' ', '') )) self._matched_char_id = self._vim.call( 'matchadd', 'deniteMatchedChar', matched_char_pattern, 10, -1, {'window': self._winid}) prev_linenr = self._vim.call('line', '.') prev_candidate = self._get_cursor_candidate() buffer = self._vim.buffers[self._bufnr] buffer.options['modifiable'] = True self._vim.vars['denite#_candidates'] = [ x['word'] for x in self._candidates] buffer[:] = self._displayed_texts buffer.options['modifiable'] = False self._previous_text = self._context['input'] self._resize_buffer(is_current_buffer) is_changed = (self._context['reversed'] or (is_current_buffer and self._previous_text != self._context['input'])) if self._updated and is_changed: if not is_current_buffer: save_winid = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) self._init_cursor() self._move_to_pos(self._cursor) if not is_current_buffer: self._vim.call('win_gotoid', save_winid) elif is_current_buffer: self._vim.call('cursor', [prev_linenr, 0]) if is_current_buffer: if (self._context['auto_action'] and prev_candidate != self._get_cursor_candidate()): self.do_action(self._context['auto_action']) self._updated = False self._stop_timer('update_buffer') def _update_status(self) -> None: inpt = '' if self._context['input']: inpt = self._context['input'] + ' ' if self._context['error_messages']: inpt = '[ERROR] ' + inpt path = '[' + self._context['path'] + ']' status = { 'input': inpt, 'sources': self._statusline_sources, 'path': path, # Extra 'buffer_name': self._context['buffer_name'], 'line_total': len(self._candidates), } if status == self._prev_status: return self._bufvars['denite_statusline'] = status self._prev_status = status linenr = "printf('%'.(len(line('$'))+2).'d/%d',line('.'),line('$'))" if self._context['statusline']: if self._floating or self._filter_floating: self._vim.options['titlestring'] = ( "%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} " + " %{denite#get_status('path')}%*" + "%{" + linenr + "}%*") else: winnr = self._vim.call('win_id2win', self._winid) self._vim.call('setwinvar', winnr, '&statusline', ( "%#deniteInput#%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} %=" + "%#deniteStatusLinePath# %{denite#get_status('path')}%*" + "%#deniteStatusLineNumber#%{" + linenr + "}%*")) def _get_display_source_name(self, name: str) -> str: source_names = self._context['source_names'] if not self._is_multi or source_names == 'hide': source_name = '' else: short_name = (re.sub(r'([a-zA-Z])[a-zA-Z]+', r'\1', name) if re.search(r'[^a-zA-Z]', name) else name[:2]) source_name = short_name if source_names == 'short' else name return source_name def _get_candidate_display_text(self, index: int) -> str: source_names = self._context['source_names'] candidate = self._candidates[index] terms = [] if self._is_multi and source_names != 'hide': terms.append(self._context['max_source_name_format'].format( self._get_display_source_name(candidate['source_name']))) encoding = self._context['encoding'] abbr = candidate.get('abbr', candidate['word']).encode( encoding, errors='replace').decode(encoding, errors='replace') terms.append(abbr[:int(self._context['max_candidate_width'])]) return (str(self._context['selected_icon']) if index in self._selected_candidates else ' ') + ' '.join(terms).replace('\n', '') def _get_max_height(self) -> int: return int(self._vim.options['lines']) if not self._floating else ( int(self._vim.options['lines']) - int(self._context['winrow']) - int(self._vim.options['cmdheight'])) def _resize_buffer(self, is_current_buffer: bool) -> None: split = self._context['split'] if (split == 'no' or split == 'tab' or self._vim.call('winnr', '$') == 1): return winheight = max(self._winheight, 1) winwidth = max(self._winwidth, 1) is_vertical = split == 'vertical' if not is_current_buffer: restore = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) if not is_vertical and self._vim.current.window.height != winheight: if self._floating: wincol = self._context['winrow'] row = wincol if split == 'floating': if self._context['auto_resize'] and row > 1: row += self._context['winheight'] row -= self._winheight self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'editor', 'row': row, 'col': self._context['wincol'], 'width': winwidth, 'height': winheight, }) filter_row = 0 if wincol == 1 else row + winheight filter_col = self._context['wincol'] else: init_pos = self._vim.call('nvim_win_get_config', self._winid) self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'win', 'win': init_pos['win'], 'row': init_pos['row'], 'col': init_pos['col'], 'width': winwidth, 'height': winheight, }) filter_col = init_pos['col'] if init_pos['anchor'] == 'NW': winpos = self._vim.call('nvim_win_get_position', self._winid) filter_row = winpos[0] + winheight filter_winid = self._vim.vars['denite#_filter_winid'] self._context['filter_winrow'] = row if self._vim.call('win_id2win', filter_winid) > 0: self._vim.call('nvim_win_set_config', filter_winid, { 'relative': 'editor', 'row': filter_row, 'col': filter_col, }) self._vim.command('resize ' + str(winheight)) if self._context['reversed']: self._vim.command('normal! zb') elif is_vertical and self._vim.current.window.width != winwidth: self._vim.command('vertical resize ' + str(winwidth)) if not is_current_buffer: self._vim.call('win_gotoid', restore) def _check_do_option(self) -> bool: if self._context['do'] != '': self._do_command(self._context['do']) return True elif (self._candidates and self._context['immediately'] or len(self._candidates) == 1 and self._context['immediately_1']): self._do_immediately() return True return not (self._context['empty'] or self._is_async or self._candidates) def _check_move_option(self) -> None: if self._context['cursor_pos'].isnumeric(): self._cursor = int(self._context['cursor_pos']) + 1 elif re.match(r'\+\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_next_line() elif re.match(r'-\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_prev_line() elif self._context['cursor_pos'] == '$': self._move_to_last_line() def _do_immediately(self) -> None: goto = self._winid > 0 and self._vim.call( 'win_gotoid', self._winid) if goto: # Jump to denite window self._init_buffer() self.do_action('default') candidate = self._get_cursor_candidate() if not candidate: return echo(self._vim, 'Normal', '[{}/{}] {}'.format( self._cursor, len(self._candidates), candidate.get('abbr', candidate['word']))) if goto: # Move to the previous window self._vim.command('wincmd p') def _do_command(self, command: str) -> None: self._init_cursor() cursor = 1 while cursor < len(self._candidates): self.do_action('default', command) self._move_to_next_line() self._quit_buffer() def _cleanup(self) -> None: self._stop_timer('update_candidates') self._stop_timer('update_buffer') if self._vim.current.buffer.number == self._bufnr: self._cursor = self._vim.call('line', '.') # Note: Close filter window before preview window self._vim.call('denite#filter#_close_filter_window') if not self._context['has_preview_window']: self._vim.command('pclose!') # Clear previewed buffers for bufnr in self._vim.vars['denite#_previewed_buffers'].keys(): if not self._vim.call('win_findbuf', bufnr): self._vim.command('silent bdelete ' + str(bufnr)) self._vim.vars['denite#_previewed_buffers'] = {} self._vim.command('highlight! link CursorLine CursorLine') if self._floating or self._filter_floating: self._vim.options['titlestring'] = self._titlestring self._vim.options['ruler'] = self._ruler def _close_current_window(self) -> None: if self._vim.call('winnr', '$') == 1: self._vim.command('buffer #') else: self._vim.command('close!') def _quit_buffer(self) -> None: self._cleanup() if self._vim.call('bufwinnr', self._bufnr) < 0: # Denite buffer is already closed return winids = self._vim.call('win_findbuf', self._vim.vars['denite#_filter_bufnr']) if winids: # Quit filter buffer self._vim.call('win_gotoid', winids[0]) self._close_current_window() # Move to denite window self._vim.call('win_gotoid', self._winid) # Restore the window if self._context['split'] == 'no': self._switch_prev_buffer() for k, v in self._save_window_options.items(): self._vim.current.window.options[k] = v else: if self._context['split'] == 'tab': self._vim.command('tabclose!') if self._context['split'] != 'tab': self._close_current_window() self._vim.call('win_gotoid', self._prev_winid) # Restore the position self._vim.call('setpos', '.', self._prev_curpos) if self._get_wininfo() and self._get_wininfo() == self._prev_wininfo: # Note: execute restcmd twice to restore layout properly self._vim.command(self._winrestcmd) self._vim.command(self._winrestcmd) clearmatch(self._vim) def _get_cursor_candidate(self) -> Candidate: return self._get_candidate(self._cursor) def _get_candidate(self, pos: int) -> Candidate: if not self._candidates or pos > len(self._candidates): return {} return self._candidates[pos - 1] def _get_selected_candidates(self) -> Candidates: if not self._selected_candidates: return [self._get_cursor_candidate() ] if self._get_cursor_candidate() else [] return [self._candidates[x] for x in self._selected_candidates] def _init_denite(self) -> None: if self._denite: self._denite.start(self._context) self._denite.on_init(self._context) self._initialized = True self._winheight = self._context['winheight'] self._winwidth = self._context['winwidth'] def _gather_candidates(self) -> None: self._selected_candidates = [] if self._denite: self._denite.gather_candidates(self._context) def _init_cursor(self) -> None: if self._context['reversed']: self._move_to_last_line() else: self._move_to_first_line() def _move_to_pos(self, pos: int) -> None: self._vim.call('cursor', pos, 0) self._cursor = pos if self._context['reversed']: self._vim.command('normal! zb') def _move_to_next_line(self) -> None: if self._cursor < len(self._candidates): self._cursor += 1 def _move_to_prev_line(self) -> None: if self._cursor >= 1: self._cursor -= 1 def _move_to_first_line(self) -> None: self._cursor = 1 def _move_to_last_line(self) -> None: self._cursor = len(self._candidates) def _start_timer(self, key: str) -> None: if key in self._timers: return if key == 'update_candidates': self._timers[key] = self._vim.call( 'denite#helper#_start_update_candidates_timer', self._bufnr) elif key == 'update_buffer': self._timers[key] = self._vim.call( 'denite#helper#_start_update_buffer_timer', self._bufnr) def _stop_timer(self, key: str) -> None: if key not in self._timers: return self._vim.call('timer_stop', self._timers[key]) # Note: After timer_stop is called, self._timers may be removed if key in self._timers: self._timers.pop(key) def _split_floating(self, split: str) -> None: # Use floating window if split == 'floating': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'editor', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], }) elif split == 'floating_relative_cursor': opened_pos = (self._vim.call('nvim_win_get_position', 0)[0] + self._vim.call('winline') - 1) if self._context['auto_resize']: height = max(self._winheight, 1) width = max(self._winwidth, 1) else: width = self._context['winwidth'] height = self._context['winheight'] if opened_pos + height + 3 > self._vim.options['lines']: anchor = 'SW' row = 0 self._context['filter_winrow'] = row + opened_pos else: anchor = 'NW' row = 1 self._context['filter_winrow'] = row + height + opened_pos self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'cursor', 'row': row, 'col': 0, 'width': width, 'height': height, 'anchor': anchor, }) elif split == 'floating_relative_window': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'win', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], })
[((5612, 5675), 're.search', 're.search', (['"""\\\\[Command Line\\\\]$"""', 'self._vim.current.buffer.name'], {}), "('\\\\[Command Line\\\\]$', self._vim.current.buffer.name)\n", (5621, 5675), False, 'import re\n'), ((31002, 31023), 'denite.util.clearmatch', 'clearmatch', (['self._vim'], {}), '(self._vim)\n', (31012, 31023), False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n'), ((2307, 2328), 'denite.parent.SyncParent', 'SyncParent', (['self._vim'], {}), '(self._vim)\n', (2317, 2328), False, 'from denite.parent import SyncParent\n'), ((7185, 7215), 'denite.ui.map.do_map', 'do_map', (['self', '"""quick_move"""', '[]'], {}), "(self, 'quick_move', [])\n", (7191, 7215), False, 'from denite.ui.map import do_map\n'), ((7291, 7329), 'denite.ui.map.do_map', 'do_map', (['self', '"""open_filter_buffer"""', '[]'], {}), "(self, 'open_filter_buffer', [])\n", (7297, 7329), False, 'from denite.ui.map import do_map\n'), ((27199, 27247), 're.match', 're.match', (['"""\\\\+\\\\d+"""', "self._context['cursor_pos']"], {}), "('\\\\+\\\\d+', self._context['cursor_pos'])\n", (27207, 27247), False, 'import re\n'), ((6698, 6731), 'denite.util.error', 'error', (['self._vim', '"""Empty sources"""'], {}), "(self._vim, 'Empty sources')\n", (6703, 6731), False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n'), ((22421, 22449), 're.search', 're.search', (['"""[^a-zA-Z]"""', 'name'], {}), "('[^a-zA-Z]', name)\n", (22430, 22449), False, 'import re\n'), ((22348, 22390), 're.sub', 're.sub', (['"""([a-zA-Z])[a-zA-Z]+"""', '"""\\\\1"""', 'name'], {}), "('([a-zA-Z])[a-zA-Z]+', '\\\\1', name)\n", (22354, 22390), False, 'import re\n'), ((27369, 27415), 're.match', 're.match', (['"""-\\\\d+"""', "self._context['cursor_pos']"], {}), "('-\\\\d+', self._context['cursor_pos'])\n", (27377, 27415), False, 'import re\n'), ((18668, 18711), 'denite.util.regex_convert_py_vim', 'regex_convert_py_vim', (['self._matched_pattern'], {}), '(self._matched_pattern)\n', (18688, 18711), False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n')]
yuanz271/PyDSTool
PyDSTool/core/context_managers.py
886c143cdd192aea204285f3a1cb4968c763c646
# -*- coding: utf-8 -*- """Context managers implemented for (mostly) internal use""" import contextlib import functools from io import UnsupportedOperation import os import sys __all__ = ["RedirectStdout", "RedirectStderr"] @contextlib.contextmanager def _stdchannel_redirected(stdchannel, dest_filename, mode="w"): """ A context manager to temporarily redirect stdout or stderr Originally by Marc Abramowitz, 2013 (http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/) """ oldstdchannel = None dest_file = None try: if stdchannel is None: yield iter([None]) else: oldstdchannel = os.dup(stdchannel.fileno()) dest_file = open(dest_filename, mode) os.dup2(dest_file.fileno(), stdchannel.fileno()) yield except (UnsupportedOperation, AttributeError): yield iter([None]) finally: if oldstdchannel is not None: os.dup2(oldstdchannel, stdchannel.fileno()) if dest_file is not None: dest_file.close() RedirectStdout = functools.partial(_stdchannel_redirected, sys.stdout) RedirectStderr = functools.partial(_stdchannel_redirected, sys.stderr) RedirectNoOp = functools.partial(_stdchannel_redirected, None, "")
[((1137, 1190), 'functools.partial', 'functools.partial', (['_stdchannel_redirected', 'sys.stdout'], {}), '(_stdchannel_redirected, sys.stdout)\n', (1154, 1190), False, 'import functools\n'), ((1208, 1261), 'functools.partial', 'functools.partial', (['_stdchannel_redirected', 'sys.stderr'], {}), '(_stdchannel_redirected, sys.stderr)\n', (1225, 1261), False, 'import functools\n'), ((1277, 1328), 'functools.partial', 'functools.partial', (['_stdchannel_redirected', 'None', '""""""'], {}), "(_stdchannel_redirected, None, '')\n", (1294, 1328), False, 'import functools\n')]
Muzzy73/pos_kiosk
pos_kiosk/hooks.py
1ed42cfaeb15f009293b76d05dd85bd322b42f03
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import __version__ as app_version app_name = "pos_kiosk" app_title = "Pos Kiosk" app_publisher = "9t9it" app_description = "Kiosk App" app_icon = "octicon octicon-file-directory" app_color = "grey" app_email = "info@9t9it.com" app_license = "MIT" # Includes in <head> # ------------------ # include js, css files in header of desk.html # app_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # app_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js, css files in header of web template # web_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # web_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js in page # page_js = {"page" : "public/js/file.js"} # page_js = { # "kiosk": ["public/js/pos_page_js.js", "public/js/includes/number_to_words.js"] # } # include js in doctype views # doctype_js = {"doctype" : "public/js/doctype.js"} # doctype_list_js = {"doctype" : "public/js/doctype_list.js"} # doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} # doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"} fixtures = [ { "doctype": "Custom Field", "filters": [ [ "name", "in", [ "Sales Invoice Item-pos_kiosk", "Mode of Payment-logo" ] ] ] } ] # Home Pages # ---------- # application home page (will override Website Settings) # home_page = "login" # website user home page (by Role) # role_home_page = { # "Role": "home_page" # } # Website user home page (by function) # get_website_user_home_page = "pos_kiosk.utils.get_home_page" # Generators # ---------- # automatically create page for each record of this doctype # website_generators = ["Web Page"] # Installation # ------------ # before_install = "pos_kiosk.install.before_install" # after_install = "pos_kiosk.install.after_install" # Desk Notifications # ------------------ # See frappe.core.notifications.get_notification_config # notification_config = "pos_kiosk.notifications.get_notification_config" # Permissions # ----------- # Permissions evaluated in scripted ways # permission_query_conditions = { # "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions", # } # # has_permission = { # "Event": "frappe.desk.doctype.event.event.has_permission", # } # Document Events # --------------- # Hook on document methods and events # doc_events = { # "*": { # "on_update": "method", # "on_cancel": "method", # "on_trash": "method" # } # } # Scheduled Tasks # --------------- # scheduler_events = { # "all": [ # "pos_kiosk.tasks.all" # ], # "daily": [ # "pos_kiosk.tasks.daily" # ], # "hourly": [ # "pos_kiosk.tasks.hourly" # ], # "weekly": [ # "pos_kiosk.tasks.weekly" # ] # "monthly": [ # "pos_kiosk.tasks.monthly" # ] # } # Testing # ------- # before_tests = "pos_kiosk.install.before_tests" # Overriding Whitelisted Methods # ------------------------------ # # override_whitelisted_methods = { # "pos_bahrain.api.get_item_details.get_item_details": "pos_kiosk.api.item.get_item_details" # noqa # }
[]
gcouti/pypagAI
pypagai/models/model_lstm.py
d08fac95361dcc036d890a88cb86ce090322a612
from keras import Model, Input from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten from keras.optimizers import Adam from pypagai.models.base import KerasModel class SimpleLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') conc = concatenate([story, question],) conc = Reshape((1, int(conc.shape[1])))(conc) conc = Permute((2, 1))(conc) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class EmbedLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Dropout(0.3)(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Dropout(0.3)(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class ConvLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, model_cfg): super().__init__(model_cfg) self._cfg = model_cfg def _create_network_(self): hidden = self._cfg['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Convolution1D(64, 3, padding='same')(eb_story) eb_story = Convolution1D(32, 3, padding='same')(eb_story) eb_story = Convolution1D(16, 3, padding='same')(eb_story) # eb_story = Flatten()(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Convolution1D(64, 3, padding='same')(eb_question) eb_question = Convolution1D(32, 3, padding='same')(eb_question) eb_question = Convolution1D(16, 3, padding='same')(eb_question) # eb_question = Flatten()(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
[((367, 394), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ([], {}), '()\n', (392, 394), False, 'from pypagai.models.base import KerasModel\n'), ((620, 662), 'keras.Input', 'Input', (['(self._story_maxlen,)'], {'name': '"""story"""'}), "((self._story_maxlen,), name='story')\n", (625, 662), False, 'from keras import Model, Input\n'), ((683, 728), 'keras.Input', 'Input', (['(self._query_maxlen,)'], {'name': '"""question"""'}), "((self._query_maxlen,), name='question')\n", (688, 728), False, 'from keras import Model, Input\n'), ((746, 776), 'keras.layers.concatenate', 'concatenate', (['[story, question]'], {}), '([story, question])\n', (757, 776), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1042, 1091), 'keras.Model', 'Model', ([], {'inputs': '[story, question]', 'outputs': 'response'}), '(inputs=[story, question], outputs=response)\n', (1047, 1091), False, 'from keras import Model, Input\n'), ((1353, 1380), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ([], {}), '()\n', (1378, 1380), False, 'from pypagai.models.base import KerasModel\n'), ((1607, 1649), 'keras.Input', 'Input', (['(self._story_maxlen,)'], {'name': '"""story"""'}), "((self._story_maxlen,), name='story')\n", (1612, 1649), False, 'from keras import Model, Input\n'), ((1670, 1715), 'keras.Input', 'Input', (['(self._query_maxlen,)'], {'name': '"""question"""'}), "((self._query_maxlen,), name='question')\n", (1675, 1715), False, 'from keras import Model, Input\n'), ((1947, 1991), 'keras.layers.concatenate', 'concatenate', (['[eb_story, eb_question]'], {'axis': '(1)'}), '([eb_story, eb_question], axis=1)\n', (1958, 1991), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2165, 2214), 'keras.Model', 'Model', ([], {'inputs': '[story, question]', 'outputs': 'response'}), '(inputs=[story, question], outputs=response)\n', (2170, 2214), False, 'from keras import Model, Input\n'), ((2475, 2502), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ([], {}), '()\n', (2500, 2502), False, 'from pypagai.models.base import KerasModel\n'), ((2745, 2787), 'keras.Input', 'Input', (['(self._story_maxlen,)'], {'name': '"""story"""'}), "((self._story_maxlen,), name='story')\n", (2750, 2787), False, 'from keras import Model, Input\n'), ((2808, 2853), 'keras.Input', 'Input', (['(self._query_maxlen,)'], {'name': '"""question"""'}), "((self._query_maxlen,), name='question')\n", (2813, 2853), False, 'from keras import Model, Input\n'), ((3497, 3541), 'keras.layers.concatenate', 'concatenate', (['[eb_story, eb_question]'], {'axis': '(1)'}), '([eb_story, eb_question], axis=1)\n', (3508, 3541), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3715, 3764), 'keras.Model', 'Model', ([], {'inputs': '[story, question]', 'outputs': 'response'}), '(inputs=[story, question], outputs=response)\n', (3720, 3764), False, 'from keras import Model, Input\n'), ((847, 862), 'keras.layers.Permute', 'Permute', (['(2, 1)'], {}), '((2, 1))\n', (854, 862), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((889, 937), 'keras.layers.LSTM', 'LSTM', (['hidden'], {'dropout': '(0.2)', 'recurrent_dropout': '(0.2)'}), '(hidden, dropout=0.2, recurrent_dropout=0.2)\n', (893, 937), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((963, 1008), 'keras.layers.Dense', 'Dense', (['self._vocab_size'], {'activation': '"""softmax"""'}), "(self._vocab_size, activation='softmax')\n", (968, 1008), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1737, 1768), 'keras.layers.Embedding', 'Embedding', (['self._vocab_size', '(64)'], {}), '(self._vocab_size, 64)\n', (1746, 1768), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1795, 1807), 'keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (1802, 1807), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1841, 1872), 'keras.layers.Embedding', 'Embedding', (['self._vocab_size', '(64)'], {}), '(self._vocab_size, 64)\n', (1850, 1872), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1905, 1917), 'keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (1912, 1917), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2012, 2060), 'keras.layers.LSTM', 'LSTM', (['hidden'], {'dropout': '(0.2)', 'recurrent_dropout': '(0.2)'}), '(hidden, dropout=0.2, recurrent_dropout=0.2)\n', (2016, 2060), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2086, 2131), 'keras.layers.Dense', 'Dense', (['self._vocab_size'], {'activation': '"""softmax"""'}), "(self._vocab_size, activation='softmax')\n", (2091, 2131), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2875, 2906), 'keras.layers.Embedding', 'Embedding', (['self._vocab_size', '(64)'], {}), '(self._vocab_size, 64)\n', (2884, 2906), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2933, 2969), 'keras.layers.Convolution1D', 'Convolution1D', (['(64)', '(3)'], {'padding': '"""same"""'}), "(64, 3, padding='same')\n", (2946, 2969), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((2999, 3035), 'keras.layers.Convolution1D', 'Convolution1D', (['(32)', '(3)'], {'padding': '"""same"""'}), "(32, 3, padding='same')\n", (3012, 3035), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3065, 3101), 'keras.layers.Convolution1D', 'Convolution1D', (['(16)', '(3)'], {'padding': '"""same"""'}), "(16, 3, padding='same')\n", (3078, 3101), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3176, 3207), 'keras.layers.Embedding', 'Embedding', (['self._vocab_size', '(64)'], {}), '(self._vocab_size, 64)\n', (3185, 3207), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3240, 3276), 'keras.layers.Convolution1D', 'Convolution1D', (['(64)', '(3)'], {'padding': '"""same"""'}), "(64, 3, padding='same')\n", (3253, 3276), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3312, 3348), 'keras.layers.Convolution1D', 'Convolution1D', (['(32)', '(3)'], {'padding': '"""same"""'}), "(32, 3, padding='same')\n", (3325, 3348), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3384, 3420), 'keras.layers.Convolution1D', 'Convolution1D', (['(16)', '(3)'], {'padding': '"""same"""'}), "(16, 3, padding='same')\n", (3397, 3420), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3562, 3610), 'keras.layers.LSTM', 'LSTM', (['hidden'], {'dropout': '(0.2)', 'recurrent_dropout': '(0.2)'}), '(hidden, dropout=0.2, recurrent_dropout=0.2)\n', (3566, 3610), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((3636, 3681), 'keras.layers.Dense', 'Dense', (['self._vocab_size'], {'activation': '"""softmax"""'}), "(self._vocab_size, activation='softmax')\n", (3641, 3681), False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((1130, 1145), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)'}), '(lr=0.0002)\n', (1134, 1145), False, 'from keras.optimizers import Adam\n'), ((2253, 2268), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)'}), '(lr=0.0002)\n', (2257, 2268), False, 'from keras.optimizers import Adam\n'), ((3803, 3818), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)'}), '(lr=0.0002)\n', (3807, 3818), False, 'from keras.optimizers import Adam\n')]
joelouismarino/variational_rl
lib/variables/latent_variables/__init__.py
11dc14bfb56f3ebbfccd5de206b78712a8039a9a
from .fully_connected import FullyConnectedLatentVariable from .convolutional import ConvolutionalLatentVariable
[]
lpj0822/image_point_cloud_det
easyai/model/backbone/cls/pnasnet.py
7b20e2f42f3f2ff4881485da58ad188a1f0d0e0f
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: ''' PNASNet in PyTorch. Paper: Progressive Neural Architecture Search ''' from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.backbone_name import BackboneName from easyai.model.backbone.utility.base_backbone import * from easyai.model.base_block.utility.utility_block import ConvBNActivationBlock from easyai.model.base_block.cls.pnasnet_block import CellA, CellB __all__ = ['pnasnet_A', 'pnasnet_B'] class PNASNet(BaseBackbone): def __init__(self, data_channel=3, num_cells=6, num_planes=44, block=CellA, bnName=NormalizationType.BatchNormalize2d, activationName=ActivationType.ReLU): super().__init__() self.set_name(BackboneName.PNASNetA) self.data_channel = data_channel self.num_cells = num_cells self.block = block self.activation_name = activationName self.bn_name = bnName self.first_output = num_planes self.in_planes = self.first_output self.create_block_list() def create_block_list(self): self.block_out_channels = [] self.index = 0 layer1 = ConvBNActivationBlock(in_channels=self.data_channel, out_channels=self.first_output, kernel_size=3, stride=1, padding=1, bias=False, bnName=self.bn_name, activationName=self.activation_name) self.add_block_list(layer1.get_name(), layer1, self.first_output) self.make_layer(self.first_output, self.num_cells) self.downsample(self.first_output * 2) self.make_layer(self.first_output * 2, self.num_cells) self.downsample(self.first_output * 4) self.make_layer(self.first_output * 4, self.num_cells) def make_layer(self, planes, num_cells): for _ in range(num_cells): temp_block = self.block(self.in_planes, planes, stride=1, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(temp_block.get_name(), temp_block, planes) self.in_planes = planes def downsample(self, planes): down_block = self.block(self.in_planes, planes, stride=2, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(down_block.get_name(), down_block, planes) self.in_planes = planes def forward(self, x): output_list = [] for block in self._modules.values(): x = block(x) output_list.append(x) return output_list def pnasnet_A(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=44, block=CellA) model.set_name(BackboneName.PNASNetA) return model def pnasnet_B(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=32, block=CellB) model.set_name(BackboneName.PNASNetB) return model
[((1225, 1425), 'easyai.model.base_block.utility.utility_block.ConvBNActivationBlock', 'ConvBNActivationBlock', ([], {'in_channels': 'self.data_channel', 'out_channels': 'self.first_output', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)', 'bnName': 'self.bn_name', 'activationName': 'self.activation_name'}), '(in_channels=self.data_channel, out_channels=self.\n first_output, kernel_size=3, stride=1, padding=1, bias=False, bnName=\n self.bn_name, activationName=self.activation_name)\n', (1246, 1425), False, 'from easyai.model.base_block.utility.utility_block import ConvBNActivationBlock\n')]
cugxy/map_download
map_download/cmd/TerrainDownloader.py
02142b33edb2bc163f7ae971f443efe84c13e029
# -*- coding: utf-8 -*- # coding=utf-8 import json import os import math import logging import requests import time from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox def get_access_token(token): resp = None request_count = 0 url = "https://api.cesium.com/v1/assets/1/endpoint" while True: if request_count > 4: break try: request_count += 1 param = {'access_token': token} resp = requests.get(url, params=param, timeout=2) if resp.status_code != 200: continue break except Exception as e: resp = None time.sleep(3) if resp is None: return None resp_json = resp.json() return resp_json.get('accessToken') class TerrainDownloaderThread(BaseDownloaderThread): URL = "https://assets.cesium.com/1/{z}/{x}/{y}.terrain?extensions=octvertexnormals-watermask&v=1.1.0" def __init__(self, root_dir, bbox, token, task_q, logger=None, write_db=False): super(TerrainDownloaderThread, self).__init__( root_dir, bbox, task_q, logger, write_db=write_db, db_file_name='Terrain.db') self.token = token self._init_metadata( format='terrain', bounds='%f,%f,%f,%f' % (self.bbox.min_lng, self.bbox.min_lat, self.bbox.max_lng, self.bbox.max_lat)) def get_url(self, x, y, z): return self.URL.format(x=x, y=y, z=z) def _download(self, x, y, z): file_path = '%s/%s/%i/%i/%i.%s' % (self.root_dir, 'Terrain', z, x, y, 'terrain') if os.path.exists(file_path): self._data2DB(x, y, z, file_path) return 0 os.makedirs(os.path.dirname(file_path), exist_ok=True) resp = None requre_count = 0 _url = '' access_token = get_access_token(self.token) if access_token is None: return -1 param = {'extensions': 'octvertexnormals-watermask', 'v': '1.1.0', 'access_token': access_token} while True: if requre_count > 4: break try: _url = self.get_url(x, y, z) resp = requests.get(_url, params=param, stream=True, timeout=2) break except Exception as e: resp = None time.sleep(3) requre_count += 1 if resp is None: return -1 if resp.status_code != 200: return -1 try: with open(file_path, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): if chunk: f.write(chunk) except Exception as e: return -1 self._data2DB(x, y, z, file_path) return 1 class TerrainDownloadEngine(DownloadEngine): root_dir = '' def __init__(self, root_dir, bbox, token, thread_num, logger=None, write_db=False): super(TerrainDownloadEngine, self).__init__(bbox, thread_num, logger, write_db=write_db) self.root_dir = root_dir self.token = token def bbox2xyz(self, bbox, z): min_x, min_y = latlng2tile_terrain(bbox.min_lat, bbox.min_lng, z) max_x, max_y = latlng2tile_terrain(bbox.max_lat, bbox.max_lng, z) return math.floor(min_x), math.floor(min_y), math.ceil(max_x) + 1, math.ceil(max_y) + 1 def generate_metadata(self): try: metadatas = { "attribution": "© Analytical Graphics Inc., © CGIAR-CSI, Produced using Copernicus data and " "information funded by the European Union - EU-DEM layers", "available": [ [ { "endX": 1, "endY": 0, "startX": 0, "startY": 0 } ], [ { "endX": 3, "endY": 1, "startX": 0, "startY": 0 } ], [ { "endX": 7, "endY": 3, "startX": 0, "startY": 0 } ], [ { "endX": 15, "endY": 7, "startX": 0, "startY": 0 } ], [ { "endX": 31, "endY": 15, "startX": 0, "startY": 0 } ], [ { "endX": 63, "endY": 31, "startX": 0, "startY": 0 } ], [ { "endX": 127, "endY": 63, "startX": 0, "startY": 0 } ], [ { "endX": 255, "endY": 127, "startX": 0, "startY": 0 } ], [ { "endX": 511, "endY": 255, "startX": 0, "startY": 0 } ], [ { "endX": 1023, "endY": 511, "startX": 0, "startY": 0 } ], [ { "endX": 2047, "endY": 1023, "startX": 0, "startY": 0 } ], [ { "endX": 4095, "endY": 2047, "startX": 0, "startY": 0 } ], [ { "endX": 8191, "endY": 4095, "startX": 0, "startY": 0 } ], [ { "endX": 16383, "endY": 8191, "startX": 0, "startY": 0 } ], [ { "endX": 32767, "endY": 16383, "startX": 0, "startY": 0 } ] ], "bounds": [-180, -90, 180, 90, ], "description": "STK World Terrain Premium Tileset, v1.3. 10m - 30m resolution CONUS, 30m resolution " "SRTM between 60N and 60S, 30m Europe. Minimum global coverage of 1000m.", "extensions": ["watermask", "vertexnormals", "octvertexnormals", ], "format": "quantized-mesh-1.0", "maxzoom": 13, "minzoom": 0, "name": "world", "projection": "EPSG:4326", "scheme": "tms", "tilejson": "2.1.0", "tiles": ["{z}/{x}/{y}.terrain?v={version}", ], "version": "1.31376.0" } _dir = os.path.join(self.root_dir, 'Terrain') os.makedirs(_dir, exist_ok=True) metadatas_path = os.path.join(_dir, 'layer.json') with open(metadatas_path, 'w') as f: json.dump(metadatas, f) except Exception as e: if self.logger is not None: self.logger.exception(e) def run(self): try: self.generate_metadata() count = 0 bboxs = self.cut_bbox() for bbox in bboxs: _count = self.get_task_count(bbox) count += _count self.division_done_signal.emit(count) for bbox in bboxs: while True: if not self.running: time.sleep(0.01) else: break task_q = self.get_task_queue(bbox) self.threads = [] for i in range(self.thread_num): thread = TerrainDownloaderThread(self.root_dir, self.bbox, self.token, task_q, self.logger, write_db=self.write_db) thread.sub_progressBar_updated_signal.connect(self.sub_update_progressBar) self.threads.append(thread) for thread in self.threads: thread.start() for thread in self.threads: thread.wait() for t in self.threads: t.stop() t.quit() self.threads = [] self.download_done_signal.emit() except Exception as e: if self.logger is not None: self.logger.error(e) if __name__ == '__main__': if 1: logger = logging.getLogger('down') try: root = r'/Users/cugxy/Documents/data/downloader' formatter = logging.Formatter('%(levelname)s-%(message)s') hdlr = logging.StreamHandler() log_file = os.path.join(root, 'down.log') file_hdlr = logging.FileHandler(log_file) file_hdlr.setFormatter(formatter) logger.addHandler(file_hdlr) logger.addHandler(hdlr) logger.setLevel(logging.INFO) min_lng = -180.0 max_lng = 180.0 min_lat = -90.0 max_lat = 90.0 start_zoom = 0 end_zoom = 5 bbox = BoundBox(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom) d = TerrainDownloadEngine(root, bbox, 8, logger) d.start() time.sleep(10000) logger.error('main thread out') except Exception as e: logger.error(e) if 0: accessToken = get_access_token() pass
[((1646, 1671), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (1660, 1671), False, 'import os\n'), ((3201, 3251), 'map_download.cmd.BaseDownloader.latlng2tile_terrain', 'latlng2tile_terrain', (['bbox.min_lat', 'bbox.min_lng', 'z'], {}), '(bbox.min_lat, bbox.min_lng, z)\n', (3220, 3251), False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((3275, 3325), 'map_download.cmd.BaseDownloader.latlng2tile_terrain', 'latlng2tile_terrain', (['bbox.max_lat', 'bbox.max_lng', 'z'], {}), '(bbox.max_lat, bbox.max_lng, z)\n', (3294, 3325), False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((10233, 10258), 'logging.getLogger', 'logging.getLogger', (['"""down"""'], {}), "('down')\n", (10250, 10258), False, 'import logging\n'), ((526, 568), 'requests.get', 'requests.get', (['url'], {'params': 'param', 'timeout': '(2)'}), '(url, params=param, timeout=2)\n', (538, 568), False, 'import requests\n'), ((1760, 1786), 'os.path.dirname', 'os.path.dirname', (['file_path'], {}), '(file_path)\n', (1775, 1786), False, 'import os\n'), ((3341, 3358), 'math.floor', 'math.floor', (['min_x'], {}), '(min_x)\n', (3351, 3358), False, 'import math\n'), ((3360, 3377), 'math.floor', 'math.floor', (['min_y'], {}), '(min_y)\n', (3370, 3377), False, 'import math\n'), ((8434, 8472), 'os.path.join', 'os.path.join', (['self.root_dir', '"""Terrain"""'], {}), "(self.root_dir, 'Terrain')\n", (8446, 8472), False, 'import os\n'), ((8485, 8517), 'os.makedirs', 'os.makedirs', (['_dir'], {'exist_ok': '(True)'}), '(_dir, exist_ok=True)\n', (8496, 8517), False, 'import os\n'), ((8547, 8579), 'os.path.join', 'os.path.join', (['_dir', '"""layer.json"""'], {}), "(_dir, 'layer.json')\n", (8559, 8579), False, 'import os\n'), ((10357, 10403), 'logging.Formatter', 'logging.Formatter', (['"""%(levelname)s-%(message)s"""'], {}), "('%(levelname)s-%(message)s')\n", (10374, 10403), False, 'import logging\n'), ((10423, 10446), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (10444, 10446), False, 'import logging\n'), ((10470, 10500), 'os.path.join', 'os.path.join', (['root', '"""down.log"""'], {}), "(root, 'down.log')\n", (10482, 10500), False, 'import os\n'), ((10525, 10554), 'logging.FileHandler', 'logging.FileHandler', (['log_file'], {}), '(log_file)\n', (10544, 10554), False, 'import logging\n'), ((10903, 10969), 'map_download.cmd.BaseDownloader.BoundBox', 'BoundBox', (['max_lat', 'max_lng', 'min_lat', 'min_lng', 'start_zoom', 'end_zoom'], {}), '(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom)\n', (10911, 10969), False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((11065, 11082), 'time.sleep', 'time.sleep', (['(10000)'], {}), '(10000)\n', (11075, 11082), False, 'import time\n'), ((719, 732), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (729, 732), False, 'import time\n'), ((2222, 2278), 'requests.get', 'requests.get', (['_url'], {'params': 'param', 'stream': '(True)', 'timeout': '(2)'}), '(_url, params=param, stream=True, timeout=2)\n', (2234, 2278), False, 'import requests\n'), ((3379, 3395), 'math.ceil', 'math.ceil', (['max_x'], {}), '(max_x)\n', (3388, 3395), False, 'import math\n'), ((3401, 3417), 'math.ceil', 'math.ceil', (['max_y'], {}), '(max_y)\n', (3410, 3417), False, 'import math\n'), ((8645, 8668), 'json.dump', 'json.dump', (['metadatas', 'f'], {}), '(metadatas, f)\n', (8654, 8668), False, 'import json\n'), ((2380, 2393), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2390, 2393), False, 'import time\n'), ((9197, 9213), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (9207, 9213), False, 'import time\n')]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
34
Edit dataset card