text
stringlengths
3
1.05M
import Vue from 'vue'; import App from './App.vue'; import numeral from 'numeral'; import customNumeralLocale from '@/assets/js/customNumeralLocale.js'; numeral.register('locale', 'us-custom', customNumeralLocale); numeral.locale('us-custom'); Vue.filter('numeralFormat', (value, format = '0,0') => numeral(value).format(format)); Vue.config.productionTip = false; new Vue({ render: h => h(App), }).$mount('#app');
"""atelieom URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include, re_path from django.conf.urls.i18n import i18n_patterns from filebrowser.sites import site from django.conf import settings from django.conf.urls.static import static urlpatterns = [ i18n_patterns( path('admin/filebrowser/', site.urls), path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), path('tinymce/', include('tinymce.urls')), path('', include('mainpage.urls')), path('news/',include('articles.urls')), path('clothes', include('clothes.urls'))) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
""" core 模块里实现了 fastNLP 的核心框架,常用的功能都可以从 fastNLP 包中直接 import。当然你也同样可以从 core 模块的子模块中 import, 例如 :class:`~fastNLP.DataSetIter` 组件有两种 import 的方式:: # 直接从 fastNLP 中 import from fastNLP import DataSetIter # 从 core 模块的子模块 batch 中 import DataSetIter from fastNLP.core.batch import DataSetIter 对于常用的功能,你只需要在 :mod:`fastNLP` 中查看即可。如果想了解各个子模块的具体作用,您可以在下面找到每个子模块的具体文档。 """ __all__ = [ "DataSet", "Instance", "FieldArray", "Padder", "AutoPadder", "EngChar2DPadder", "Vocabulary", "DataSetIter", "BatchIter", "TorchLoaderIter", "Const", "Tester", "Trainer", "cache_results", "seq_len_to_mask", "get_seq_len", "logger", "Callback", "GradientClipCallback", "EarlyStopCallback", "FitlogCallback", "EvaluateCallback", "LRScheduler", "ControlC", "LRFinder", "TensorboardCallback", "WarmupCallback", 'SaveModelCallback', "CallbackException", "EarlyStopError", "LossFunc", "CrossEntropyLoss", "L1Loss", "BCELoss", "NLLLoss", "LossInForward", "CMRC2018Loss", "AccuracyMetric", "SpanFPreRecMetric", "CMRC2018Metric", "Optimizer", "SGD", "Adam", "AdamW", "SequentialSampler", "BucketSampler", "RandomSampler", "Sampler", ] from ._logger import logger from .batch import DataSetIter, BatchIter, TorchLoaderIter from .callback import Callback, GradientClipCallback, EarlyStopCallback, FitlogCallback, EvaluateCallback, \ LRScheduler, ControlC, LRFinder, TensorboardCallback, WarmupCallback, SaveModelCallback, CallbackException, \ EarlyStopError from .const import Const from .dataset import DataSet from .field import FieldArray, Padder, AutoPadder, EngChar2DPadder from .instance import Instance from .losses import LossFunc, CrossEntropyLoss, L1Loss, BCELoss, NLLLoss, LossInForward, CMRC2018Loss from .metrics import AccuracyMetric, SpanFPreRecMetric, CMRC2018Metric from .optimizer import Optimizer, SGD, Adam, AdamW from .sampler import SequentialSampler, BucketSampler, RandomSampler, Sampler from .tester import Tester from .trainer import Trainer from .utils import cache_results, seq_len_to_mask, get_seq_len from .vocabulary import Vocabulary
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const workoutSchema = new Schema( { day: { type: Date, default: Date.now, }, // totalDuration: Number, exercises: [ { type: { type: String, enum: ['cardio', 'resistance'], required: "Enter an exercise type", }, name: { type: String, trim: true, required: "Enter an exercise name", }, duration: { type: Number, //trim: true, required: "Enter the duration in minutes", }, weight: { type: Number, // required: function(){ // return this.type === "resistance" // } }, reps: { type: Number, }, sets: { type: Number, }, distance: { type: Number, }, }, ], }, { toJSON: { virtuals: true, }, } ); workoutSchema.virtual("totalDuration").get(function () { return this.exercises.reduce((a, x) => (a += x.duration), 0); }); const Workout = mongoose.model("Workout", workoutSchema); module.exports = Workout;
#!/usr/bin/env python from ..common import * from ..extractor import VideoExtractor import json class MusicPlayOn(VideoExtractor): name = "MusicPlayOn" stream_types = [ {'id': '720p HD'}, {'id': '360p SD'}, ] def prepare(self, **kwargs): content = get_content(self.url) self.title = match1(content, r'setup\[\'title\'\] = "([^"]+)";') for s in self.stream_types: quality = s['id'] src = match1(content, r'src: "([^"]+)", "data-res": "%s"' % quality) if src is not None: url = 'http://en.musicplayon.com%s' % src self.streams[quality] = {'url': url} site = MusicPlayOn() download = site.download_by_url # TBD: implement download_playlist
# -*- coding: utf-8 -*- """ Module to define and load pywikibot configuration default and user preferences. User preferences are loaded from a python file called user-config.py, which may be located in directory specified by the environment variable PYWIKIBOT2_DIR, or the same directory as pwb.py, or in a directory within the users home. See get_base_dir for more information. If user-config.py can not be found in any of those locations, this module will fail to load unless the environment variable PYWIKIBOT2_NO_USER_CONFIG is set to a value other than '0'. i.e. PYWIKIBOT2_NO_USER_CONFIG=1 will allow config to load without a user-config.py. However, warnings will be shown if user-config.py was not loaded. To prevent these warnings, set PYWIKIBOT2_NO_USER_CONFIG=2. Provides two functions to register family classes which can be used in the user-config: - register_family_file - register_families_folder Other functions made available to user-config: - user_home_path Sets module global base_dir and provides utility methods to build paths relative to base_dir: - makepath - datafilepath - shortpath """ # # (C) Rob W.W. Hooft, 2003 # (C) Pywikibot team, 2003-2015 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id: 731ed8a4832c79462c423c12f22828f18f6ea065 $' # import collections import os import stat import sys from warnings import warn if sys.platform == 'win32': if sys.version_info[0] > 2: import winreg else: import _winreg as winreg # This frozen set should contain all imported modules/variables, so it must # occur directly after the imports. At that point globals() only contains the # names and some magic variables (like __name__) _imports = frozenset(name for name in globals() if not name.startswith('_')) __no_user_config = os.environ.get('PYWIKIBOT2_NO_USER_CONFIG') if __no_user_config == '0': __no_user_config = None class _ConfigurationDeprecationWarning(UserWarning): """Feature that is no longer supported.""" pass # IMPORTANT: # Do not change any of the variables in this file. Instead, make # a file user-config.py, and overwrite values in there. # Note: all variables defined in this module are made available to bots as # configuration settings, *except* variable names beginning with an # underscore (example: _variable). Be sure to use an underscore on any # variables that are intended only for internal use and not to be exported # to other modules. _private_values = ['authenticate', 'proxy', 'db_password'] _deprecated_variables = ['use_SSL_onlogin', 'use_SSL_always', 'available_ssl_project'] # ############# ACCOUNT SETTINGS ############## # The family of sites we are working on. pywikibot will import # families/xxx_family.py so if you want to change this variable, # you need to write such a file if one does not exist. family = 'wikipedia' # The language code of the site we're working on. mylang = 'language' # If family and mylang are not modified from the above, the default is changed # to test:test, which is test.wikipedia.org, at the end of this module. # The dictionary usernames should contain a username for each site where you # have a bot account. Please set your usernames by adding such lines to your # user-config.py: # # usernames['wikipedia']['de'] = 'myGermanUsername' # usernames['wiktionary']['en'] = 'myEnglishUsername' # # If you have a unique username for all languages of a family, # you can use '*' # usernames['wikibooks']['*'] = 'mySingleUsername' # # If you have a sysop account on some wikis, this will be used to delete pages # or to edit locked pages if you add such lines to your # user-config.py: # # sysopnames['wikipedia']['de'] = 'myGermanUsername' # sysopnames['wiktionary']['en'] = 'myEnglishUsername' # # If you have a unique syop account for all languages of a family, # you can use '*' # sysopnames['myownwiki']['*'] = 'mySingleUsername' usernames = collections.defaultdict(dict) sysopnames = collections.defaultdict(dict) disambiguation_comment = collections.defaultdict(dict) # User agent format. # For the meaning and more help in customization see: # https://www.mediawiki.org/wiki/Manual:Pywikibot/User-agent user_agent_format = '{script_product} ({script_comments}) {pwb} ({revision}) {httplib2} {python}' # The default interface for communicating with the site # currently the only defined interface is 'APISite', so don't change this! site_interface = 'APISite' # number of days to cache namespaces, api configuration, etc. API_config_expiry = 30 # The maximum number of bytes which uses a GET request, if not positive # it'll always use POST requests maximum_GET_length = 255 # Some networks modify GET requests when they are not encrypted, to avoid # bug reports related to that disable those. If we are confident that bug # related to this are really because of the network this could be changed. enable_GET_without_SSL = False # Solve captchas in the webbrowser. Setting this to False will result in the # exception CaptchaError being thrown if a captcha is encountered. solve_captcha = True # Some sites will require password authentication to access the HTML pages at # the site. If you have any such site, add lines to your user-config.py of # the following form: # # authenticate['en.wikipedia.org'] = ('John','XXXXX') # # where John is your login name, and XXXXX your password. # Note: # 1. This is only for sites that use authentication in the form that gives # you a popup for name and password when you try to access any data, NOT # for, for example, wiki usernames # 2. You must use the hostname of the site, not its family/language pair authenticate = {} # # Secure connection overrides # # These settings are deprecated. They existed to support the Wikimedia # family which only served HTTPS on https://secure.wikimedia.org/<site>/<uri> # Use Family.protocol() use_SSL_onlogin = False # if available, use SSL when logging in use_SSL_always = False # if available, use SSL for all API queries # Available secure projects should be listed here. available_ssl_project = [] # By default you are asked for a password on the terminal. # A password file may be used. e.g. password_file = ".passwd" # The password file should consist of lines containing # Python tuples of any of the following formats: # (code, family, username, password) # (family, username, password) # (username, password) password_file = None # edit summary to use if not supplied by bot script # WARNING: this should NEVER be used in practice, ALWAYS supply a more # relevant summary for bot edits default_edit_summary = u'Pywikibot v.2' # What permissions to use to set private files to it # such as password file. # # stat.S_IRWXU 0o700 mask for owner permissions # stat.S_IRUSR 0o400 read permission for owner # stat.S_IWUSR 0o200 write permission for owner # stat.S_IXUSR 0o100 execute permission for owner # stat.S_IRWXG 0o070 mask for group permissions # stat.S_IRGRP 0o040 read permission for group # stat.S_IWGRP 0o020 write permission for group # stat.S_IXGRP 0o010 execute permission for group # stat.S_IRWXO 0o007 mask for others permissions # stat.S_IROTH 0o004 read permission for others # stat.S_IWOTH 0o002 write permission for others # stat.S_IXOTH 0o001 execute permission for others private_files_permission = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR # Allow user to stop warnings about file security # by setting this to true. ignore_file_security_warnings = False def user_home_path(path): """Return a file path to a file in the user home.""" return os.path.join(os.path.expanduser('~'), path) def get_base_dir(test_directory=None): r"""Return the directory in which user-specific information is stored. This is determined in the following order: 1. If the script was called with a -dir: argument, use the directory provided in this argument. 2. If the user has a PYWIKIBOT2_DIR environment variable, use the value of it. 3. If user-config is present in current directory, use the current directory. 4. If user-config is present in pwb.py directory, use that directory 5. Use (and if necessary create) a 'pywikibot' folder under 'Application Data' or 'AppData\Roaming' (Windows) or '.pywikibot' directory (Unix and similar) under the user's home directory. Set PYWIKIBOT2_NO_USER_CONFIG=1 to disable loading user-config.py @param test_directory: Assume that a user config file exists in this directory. Used to test whether placing a user config file in this directory will cause it to be selected as the base directory. @type test_directory: str or None @rtype: unicode """ def exists(directory): directory = os.path.abspath(directory) if directory == test_directory: return True else: return os.path.exists(os.path.join(directory, 'user-config.py')) if test_directory is not None: test_directory = os.path.abspath(test_directory) DIRNAME_WIN = u"Pywikibot" DIRNAME_WIN_FBCK = u"pywikibot" DIRNAME_UNIX = u".pywikibot" base_dir = "" for arg in sys.argv[1:]: if arg.startswith(str('-dir:')): base_dir = arg[5:] base_dir = os.path.expanduser(base_dir) break else: if ('PYWIKIBOT2_DIR' in os.environ and exists(os.path.abspath(os.environ['PYWIKIBOT2_DIR']))): base_dir = os.path.abspath(os.environ['PYWIKIBOT2_DIR']) elif exists('.'): base_dir = os.path.abspath('.') elif ('PYWIKIBOT2_DIR_PWB' in os.environ and exists(os.path.abspath(os.environ['PYWIKIBOT2_DIR_PWB']))): base_dir = os.path.abspath(os.environ['PYWIKIBOT2_DIR_PWB']) else: base_dir_cand = [] home = os.path.expanduser("~") if sys.platform == 'win32': import platform win_version = int(platform.version().split(".")[0]) if win_version == 5: sub_dir = ["Application Data"] elif win_version in (6, 10): sub_dir = ["AppData", "Roaming"] else: raise WindowsError(u'Windows version %s not supported yet.' % win_version) base_dir_cand.extend([[home] + sub_dir + [DIRNAME_WIN], [home] + sub_dir + [DIRNAME_WIN_FBCK]]) else: base_dir_cand.append([home, DIRNAME_UNIX]) for dir in base_dir_cand: dir = os.path.join(*dir) if not os.path.isdir(dir): os.makedirs(dir, mode=private_files_permission) if exists(dir): base_dir = dir break if not os.path.isabs(base_dir): base_dir = os.path.normpath(os.path.join(os.getcwd(), base_dir)) # make sure this path is valid and that it contains user-config file if not os.path.isdir(base_dir): raise RuntimeError("Directory '%s' does not exist." % base_dir) # check if user-config.py is in base_dir if not exists(base_dir): exc_text = "No user-config.py found in directory '%s'.\n" % base_dir if __no_user_config: if __no_user_config != '2': print(exc_text) else: exc_text += " Please check that user-config.py is stored in the correct location.\n" exc_text += " Directory where user-config.py is searched is determined as follows:\n\n" exc_text += " " + get_base_dir.__doc__ raise RuntimeError(exc_text) return base_dir _get_base_dir = get_base_dir # for backward compatibility _base_dir = get_base_dir() # Save base_dir for use by other modules base_dir = _base_dir for arg in sys.argv[1:]: if arg.startswith(str('-verbose')) or arg == str('-v'): print("The base directory is %s" % base_dir) break family_files = {} def register_family_file(family_name, file_path): """Register a single family class file.""" usernames[family_name] = {} sysopnames[family_name] = {} disambiguation_comment[family_name] = {} family_files[family_name] = file_path def register_families_folder(folder_path): """Register all family class files contained in a directory.""" for file_name in os.listdir(folder_path): if file_name.endswith("_family.py"): family_name = file_name[:-len("_family.py")] register_family_file(family_name, os.path.join(folder_path, file_name)) # Get the names of all known families, and initialize with empty dictionaries. # ‘families/’ is a subdirectory of the directory in which config2.py is found. register_families_folder(os.path.join(os.path.dirname(__file__), 'families')) register_family_file('wikiapiary', 'https://wikiapiary.com') # Set to True to override the {{bots}} exclusion protocol (at your own risk!) ignore_bot_templates = False # ############# USER INTERFACE SETTINGS ############## # The encoding that's used in the user's console, i.e. how strings are encoded # when they are read by raw_input(). On Windows systems' DOS box, this should # be 'cp850' ('cp437' for older versions). Linux users might try 'iso-8859-1' # or 'utf-8'. # This default code should work fine, so you don't have to think about it. # TODO: consider getting rid of this config variable. try: if sys.version_info[0] > 2 or not sys.stdout.encoding: console_encoding = sys.stdout.encoding else: console_encoding = sys.stdout.encoding.decode('ascii') except: # When using pywikibot inside a daemonized twisted application, # we get "StdioOnnaStick instance has no attribute 'encoding'" console_encoding = None # The encoding the user would like to see text transliterated to. This can be # set to a charset (e.g. 'ascii', 'iso-8859-1' or 'cp850'), and we will output # only characters that exist in that charset. However, the characters will be # output using console_encoding. # If this is not defined on Windows, we emit a Warning explaining the user # to either switch to a Unicode-able font and use # transliteration_target = None # or to keep using raster fonts and set # transliteration_target = console_encoding # After emitting the warning, this last option will be set. transliteration_target = None # The encoding in which textfiles are stored, which contain lists of page # titles. The most used is: 'utf-8'. 'utf-8-sig' recognizes BOM but it is # available on Python 2.5 or higher. For a complete list please see: # https://docs.python.org/2/library/codecs.html#standard-encodings textfile_encoding = 'utf-8' # tkinter isn't yet ready userinterface = 'terminal' # this can be used to pass variables to the UI init function # useful for e.g. # userinterface_init_kwargs = {'default_stream': 'stdout'} userinterface_init_kwargs = {} # i18n setting for user interface language # default is obtained from L{locale.getdefaultlocale} userinterface_lang = None # Should we transliterate characters that do not exist in the console # character set? # True: whenever possible # False: never - always replace them by question marks # Currently only works if interface 'terminal' is set. transliterate = True # Should the system bell ring if the bot expects user input? ring_bell = False # Colorization can be used to markup important text parts of the output. # On Linux/Unix terminals, ANSI escape codes are used for this. On Windows, # it is done by a DLL call via ctypes. ctypes is only available since # Python 2.5, so if you're using Python 2.4 or lower on Windows, you should # upgrade. # Set this to False if you're using Linux and your tty doesn't support # ANSI colors. try: # Don't print colorized when the output is, for example, piped to a file. colorized_output = sys.stdout.isatty() except: colorized_output = False # An indication of the size of your screen, or rather the size of the screen # to be shown, for flickrripper tkhorsize = 1600 tkvertsize = 1000 # ############# EXTERNAL EDITOR SETTINGS ############## # The command for the editor you want to use. If set to None, a simple Tkinter # editor will be used. editor = os.environ.get('EDITOR', None) # On Windows systems, this script tries to determine the default text editor. # Warning: DO NOT use an editor which doesn't support Unicode to edit pages! # You will BREAK non-ASCII symbols! editor_encoding = 'utf-8' # The temporary file name extension can be set in order to use syntax # highlighting in your text editor. editor_filename_extension = 'wiki' # ############# LOGFILE SETTINGS ############## # Defines for which scripts a logfile should be enabled. Logfiles will be # saved in the 'logs' subdirectory. # Example: # log = ['interwiki', 'weblinkchecker', 'table2wiki'] # It is also possible to enable logging for all scripts, using this line: # log = ['*'] # To disable all logging, use this: # log = [] # Per default, logging of interwiki.py is enabled because its logfiles can # be used to generate so-called warnfiles. # This setting can be overridden by the -log or -nolog command-line arguments. log = ['interwiki'] # filename defaults to modulename-bot.log logfilename = None # maximal size of a logfile in kilobytes. If the size reached that limit the # logfile will be renamed (if logfilecount is not 0) and the old file is filled # again. logfilesize must be an integer value logfilesize = 1024 # Number of rotating logfiles are created. The older files get the higher # number. If logfilecount is 0, no logfile will be archived but the current # logfile will be overwritten if the file size reached the logfilesize above. # If logfilecount is -1 there are no rotating logfiles but the files where # renamed if the logfile is full. The newest file gets the highest number until # some logfiles where deleted. logfilecount = 5 # set to 1 (or higher) to generate "informative" messages to terminal verbose_output = 0 # set to True to fetch the pywiki version online log_pywiki_repo_version = False # if True, include a lot of debugging info in logfile # (overrides log setting above) debug_log = [] # ############# INTERWIKI SETTINGS ############## # Should interwiki.py report warnings for missing links between foreign # languages? interwiki_backlink = True # Should interwiki.py display every new link it discovers? interwiki_shownew = True # Should interwiki.py output a graph PNG file on conflicts? # You need pydot for this: # https://pypi.python.org/pypi/pydot/1.0.2 # https://code.google.com/p/pydot/ interwiki_graph = False # Specifies that the robot should process that amount of subjects at a time, # only starting to load new pages in the original language when the total # falls below that number. Default is to process (at least) 100 subjects at # once. interwiki_min_subjects = 100 # If interwiki graphs are enabled, which format(s) should be used? # Supported formats include png, jpg, ps, and svg. See: # http://www.graphviz.org/doc/info/output.html # If you want to also dump the dot files, you can use this in your # user-config.py: # interwiki_graph_formats = ['dot', 'png'] # If you need a PNG image with an HTML image map, use this: # interwiki_graph_formats = ['png', 'cmap'] # If you only need SVG images, use: # interwiki_graph_formats = ['svg'] interwiki_graph_formats = ['png'] # You can post the contents of your autonomous_problems.dat to the wiki, # e.g. to https://de.wikipedia.org/wiki/Wikipedia:Interwiki-Konflikte . # This allows others to assist you in resolving interwiki problems. # To help these people, you can upload the interwiki graphs to your # webspace somewhere. Set the base URL here, e.g.: # 'https://www.example.org/~yourname/interwiki-graphs/' interwiki_graph_url = None # Save file with local articles without interwikis. without_interwiki = False # Experimental feature: # Store the page contents on disk (/cache/ directory) instead of loading # them in RAM. interwiki_contents_on_disk = False # ############# SOLVE_DISAMBIGUATION SETTINGS ############ # # Set disambiguation_comment[FAMILY][LANG] to a non-empty string to override # the default edit comment for the solve_disambiguation bot. # Use %s to represent the name of the disambiguation page being treated. # Example: # # disambiguation_comment['wikipedia']['en'] = \ # "Robot-assisted disambiguation ([[WP:DPL|you can help!]]): %s" sort_ignore_case = False # ############# IMAGE RELATED SETTINGS ############## # If you set this to True, images will be uploaded to Wikimedia # Commons by default. upload_to_commons = False # ############# SETTINGS TO AVOID SERVER OVERLOAD ############## # Slow down the robot such that it never requests a second page within # 'minthrottle' seconds. This can be lengthened if the server is slow, # but never more than 'maxthrottle' seconds. However - if you are running # more than one bot in parallel the times are lengthened. # By default, the get_throttle is turned off, and 'maxlag' is used to # control the rate of server access. Set minthrottle to non-zero to use a # throttle on read access. minthrottle = 0 maxthrottle = 60 # Slow down the robot such that it never makes a second page edit within # 'put_throttle' seconds. put_throttle = 10 # Sometimes you want to know when a delay is inserted. If a delay is larger # than 'noisysleep' seconds, it is logged on the screen. noisysleep = 3.0 # Defer bot edits during periods of database server lag. For details, see # https://www.mediawiki.org/wiki/Maxlag_parameter # You can set this variable to a number of seconds, or to None (or 0) to # disable this behavior. Higher values are more aggressive in seeking # access to the wiki. # Non-Wikimedia wikis may or may not support this feature; for families # that do not use it, it is recommended to set minthrottle (above) to # at least 1 second. maxlag = 5 # Maximum of pages which can be retrieved by special pages. Increase this if # you heavily use redirect.py with action "double", and especially if you're # running solve_disambiguation.py with the -primary argument. special_page_limit = 500 # Maximum number of times to retry an API request before quitting. max_retries = 25 # Minimum time to wait before resubmitting a failed API request. retry_wait = 5 # ############# TABLE CONVERSION BOT SETTINGS ############## # will split long paragraphs for better reading the source. # only table2wiki.py use it by now splitLongParagraphs = False # sometimes HTML-tables are indented for better reading. # That can do very ugly results. deIndentTables = True # table2wiki.py works quite stable, so you might switch to True table2wikiAskOnlyWarnings = True table2wikiSkipWarnings = False # ############# WEBLINK CHECKER SETTINGS ############## # How many external links should weblinkchecker.py check at the same time? # If you have a fast connection, you might want to increase this number so # that slow servers won't slow you down. max_external_links = 50 report_dead_links_on_talk = False # ############# DATABASE SETTINGS ############## # Setting to connect the database or replica of the database of the wiki. # db_name_format can be used to manipulate the dbName of site. # Example for a pywikibot running on wmflabs: # db_hostname = 'enwiki.labsdb' # db_name_format = '{0}_p' # db_connect_file = user_home_path('replica.my.cnf') db_hostname = 'localhost' db_username = '' db_password = '' db_name_format = '{0}' db_connect_file = user_home_path('.my.cnf') # ############# SEARCH ENGINE SETTINGS ############## # Yahoo! Search Web Services are not operational. # See https://phabricator.wikimedia.org/T106085 yahoo_appid = '' # To use Windows Live Search web service you must get an AppID from # http://www.bing.com/dev/en-us/dev-center msn_appid = '' # ############# FLICKR RIPPER SETTINGS ############## # Using the Flickr api flickr = { 'api_key': u'', # Provide your key! 'api_secret': u'', # Api secret of your key (optional) 'review': False, # Do we use automatically make our uploads reviewed? 'reviewer': u'', # If so, under what reviewer name? } # ############# COPYRIGHT SETTINGS ############## # Enable/disable search engine in copyright.py script copyright_google = True copyright_yahoo = True copyright_msn = False # Perform a deep check, loading URLs to search if 'Wikipedia' is present. # This may be useful to increase the number of correct results. If you haven't # a fast connection, you might want to keep them disabled. copyright_check_in_source_google = False copyright_check_in_source_yahoo = False copyright_check_in_source_msn = False # Web pages may contain a Wikipedia text without the word 'Wikipedia' but with # the typical '[edit]' tag as a result of a copy & paste procedure. You want # no report for this kind of URLs, even if they are copyright violations. # However, when enabled, these URLs are logged in a file. copyright_check_in_source_section_names = False # Limit number of queries for page. copyright_max_query_for_page = 25 # Skip a specified number of queries copyright_skip_query = 0 # Number of attempts on connection error. copyright_connection_tries = 10 # Behavior if an exceeded error occur. # # Possibilities: # # 0 = None # 1 = Disable search engine # 2 = Sleep (default) # 3 = Stop copyright_exceeded_in_queries = 2 copyright_exceeded_in_queries_sleep_hours = 6 # Append last modified date of URL to script result copyright_show_date = True # Append length of URL to script result copyright_show_length = True # By default the script tries to identify and skip text that contains a large # comma separated list or only numbers. But sometimes that might be the # only part unmodified of a slightly edited and not otherwise reported # copyright violation. You can disable this feature to try to increase the # number of results. copyright_economize_query = True # ############# HTTP SETTINGS ############## # Use a persistent http connection. An http connection has to be established # only once per site object, making stuff a whole lot faster. Do NOT EVER # use this if you share Site objects across threads without proper locking. # # DISABLED FUNCTION. Setting this variable will not have any effect. persistent_http = False # Default socket timeout. Set to None to disable timeouts. socket_timeout = 120 # set a pretty long timeout just in case... # ############# COSMETIC CHANGES SETTINGS ############## # The bot can make some additional changes to each page it edits, e.g. fix # whitespace or positioning of interwiki and category links. # This is an experimental feature; handle with care and consider re-checking # each bot edit if enabling this! cosmetic_changes = False # If cosmetic changes are switched on, and you also have several accounts at # projects where you're not familiar with the local conventions, you probably # only want the bot to do cosmetic changes on your "home" wiki which you # specified in config.mylang and config.family. # If you want the bot to also do cosmetic changes when editing a page on a # foreign wiki, set cosmetic_changes_mylang_only to False, but be careful! cosmetic_changes_mylang_only = True # The dictionary cosmetic_changes_enable should contain a tuple of languages # for each site where you wish to enable in addition to your own langlanguage # (if cosmetic_changes_mylang_only is set) # Please set your dictionary by adding such lines to your user-config.py: # cosmetic_changes_enable['wikipedia'] = ('de', 'en', 'fr') cosmetic_changes_enable = {} # The dictionary cosmetic_changes_disable should contain a tuple of languages # for each site where you wish to disable cosmetic changes. You may use it with # cosmetic_changes_mylang_only is False, but you can also disable your own # language. This also overrides the settings in the cosmetic_changes_enable # dictionary. Please set your dict by adding such lines to your user-config.py: # cosmetic_changes_disable['wikipedia'] = ('de', 'en', 'fr') cosmetic_changes_disable = {} # cosmetic_changes_deny_script is a list of scripts for which cosmetic changes # are disabled. You may add additional scripts by appending script names in # your user_config.py ("+=" operator is strictly recommended): # cosmetic_changes_deny_script += ['your_script_name_1', 'your_script_name_2'] # Appending the script name also works: # cosmetic_changes_deny_script.append('your_script_name') cosmetic_changes_deny_script = ['category_redirect', 'cosmetic_changes', 'newitem', 'touch'] # ############# REPLICATION BOT ################ # You can add replicate_replace to your user_config.py, which has the following # format: # # replicate_replace = { # 'wikipedia:li': {'Hoofdpagina': 'Veurblaad'} # } # # to replace all occurrences of 'Hoofdpagina' with 'Veurblaad' when writing to # liwiki. Note that this does not take the origin wiki into account. replicate_replace = {} # ############# FURTHER SETTINGS ############## # Proxy configuration # For proxy support, install socksipy or httplib2 0.7+ # then add these three lines to your user-config.py: # from httplib2 import ProxyInfo, socks # proxy = ProxyInfo(socks.PROXY_TYPE_HTTP, 'localhost', 8000) # del ProxyInfo, socks proxy = None # Simulate settings # Defines what additional actions the bots are NOT allowed to do (e.g. 'edit') # on the wiki server. Allows simulation runs of bots to be carried out without # changing any page on the server side. Use this setting to add more actions # in user-config.py for wikis with extra write actions. actions_to_block = [] # Set simulate to True or use -simulate option to block all actions given above. simulate = False # How many pages should be put to a queue in asynchronous mode. # If maxsize is <= 0, the queue size is infinite. # Increasing this value will increase memory space but could speed up # processing. As higher this value this effect will decrease. max_queue_size = 64 # Define the line separator. Pages retrieved via API have "\n" whereas # pages fetched from screen (mostly) have "\r\n". Interwiki and category # separator settings in family files should use multiplied of this. # LS is a shortcut alias. line_separator = LS = u'\n' # Settings to enable mwparserfromhell # <https://mwparserfromhell.readthedocs.org/en/latest/> # Currently used in textlib.extract_templates_and_params # This is more accurate than our current regex, but only works # if the user has already installed the library. use_mwparserfromhell = True # Pickle protocol version to use for storing dumps. # This config variable is not used for loading dumps. # Version 2 is common to both Python 2 and 3, and should # be used when dumps are accessed by both versions. # Version 4 is only available for Python 3.4 pickle_protocol = 2 # End of configuration section # ============================ def makepath(path): """Return a normalized absolute version of the path argument. - if the given path already exists in the filesystem the filesystem is not modified. - otherwise makepath creates directories along the given path using the dirname() of the path. You may append a '/' to the path if you want it to be a directory path. from holger@trillke.net 2002/03/18 """ dpath = os.path.normpath(os.path.dirname(path)) if not os.path.exists(dpath): os.makedirs(dpath) return os.path.normpath(os.path.abspath(path)) def datafilepath(*filename): """Return an absolute path to a data file in a standard location. Argument(s) are zero or more directory names, optionally followed by a data file name. The return path is offset to config.base_dir. Any directories in the path that do not already exist are created. """ return makepath(os.path.join(base_dir, *filename)) def shortpath(path): """Return a file path relative to config.base_dir.""" if path.startswith(base_dir): return path[len(base_dir) + len(os.path.sep):] return path def _win32_extension_command(extension): """Get the command from the Win32 registry for an extension.""" fileexts_key = r'Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts' key_name = fileexts_key + r'\.' + extension + r'\OpenWithProgids' _winreg = winreg # exists for git blame only; do not use try: key1 = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name) _progID = winreg.EnumValue(key1, 0)[0] _key2 = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '%s\shell\open\command' % _progID) _cmd = _winreg.QueryValueEx(_key2, None)[0] # See T102465 for issues relating to using this value. cmd = _cmd if cmd.find('%1'): cmd = cmd[:cmd.find('%1')] # Remove any trailing characher, which should be a quote or space # and then remove all whitespace. return cmd[:-1].strip() except WindowsError as e: # Catch any key lookup errors print('WARNING: Unable to find editor for files *.' + extension) print(e) def _detect_win32_editor(): """Detect the best Win32 editor.""" # Notepad is even worse than our Tkinter editor. unusable_exes = ['notepad.exe', 'py.exe', 'pyw.exe', 'python.exe', 'pythonw.exe'] for ext in ['py', 'txt']: editor = _win32_extension_command(ext) if editor: for unusable in unusable_exes: if unusable in editor.lower(): break else: return editor # System-level and User-level changes. # Store current variables and their types. _glv = dict((_key, _val) for _key, _val in globals().items() if _key[0] != '_' and _key not in _imports) _gl = list(_glv.keys()) _tp = {} for _key in _gl: _tp[_key] = type(globals()[_key]) # Create an environment for user-config.py which is # a shallow copy of the core config settings, so that # we can detect modified config items easily. _uc = {} for _key, _val in _glv.items(): if isinstance(_val, dict): if isinstance(_val, collections.defaultdict): _uc[_key] = collections.defaultdict(dict) else: _uc[_key] = {} if len(_val) > 0: _uc[_key].update(_val) else: _uc[_key] = _val # Get the user files _thislevel = 0 if __no_user_config: if __no_user_config != '2': print("WARNING: Skipping loading of user-config.py.") _fns = [] else: _fns = [os.path.join(_base_dir, "user-config.py")] for _filename in _fns: _thislevel += 1 if os.path.exists(_filename): _filestatus = os.stat(_filename) _filemode = _filestatus[0] _fileuid = _filestatus[4] if sys.platform == 'win32' or _fileuid in [os.getuid(), 0]: if sys.platform == 'win32' or _filemode & 0o02 == 0: with open(_filename, 'rb') as f: exec(compile(f.read(), _filename, 'exec'), _uc) else: print("WARNING: Skipped '%(fn)s': writeable by others." % {'fn': _filename}) else: print("WARNING: Skipped '%(fn)s': owned by someone else." % {'fn': _filename}) # Test for obsoleted and/or unknown variables. for _key, _val in list(_uc.items()): if _key.startswith('_'): pass elif _key in _imports: pass elif _key in _gl: nt = type(_val) ot = _tp[_key] ov = _glv[_key] if nt == ot or _val is None or ov is None: # nopep8 pass elif nt is int and (ot is float or ot is bool): pass elif ot is int and (nt is float or nt is bool): pass else: print("WARNING: Type of '%(_key)s' changed" % locals()) print(" %(was)s: %(old)s" % {'was': "Was", 'old': ot}) print(" %(now)s: %(new)s" % {'now': "Now", 'new': nt}) del nt, ot, ov else: print("WARNING: " "Configuration variable %(_key)r is defined but unknown.\n" "Misspelled?" % locals()) # Copy the user config settings into globals _modified = [_key for _key in _gl if _uc[_key] != globals()[_key] or _key in ('usernames', 'sysopnames', 'disambiguation_comment')] for _key in _modified: globals()[_key] = _uc[_key] if _key in _deprecated_variables: warn("'%s' is no longer a supported configuration variable.\n" "Please inform the maintainers if you depend on it." % _key, _ConfigurationDeprecationWarning) # Fix up default console_encoding if console_encoding is None: if sys.platform == 'win32': console_encoding = 'cp850' else: console_encoding = 'iso-8859-1' if sys.platform == 'win32' and editor is None: editor = _detect_win32_editor() if sys.platform == 'win32' and editor: # single character string literals from # https://docs.python.org/2/reference/lexical_analysis.html#string-literals # encode('unicode-escape') also changes Unicode characters if set(editor) & set('\a\b\f\n\r\t\v'): print('WARNING: The editor path contains probably invalid escaped ' 'characters. Make sure to use a raw-string (r"..." or r\'...\'), ' 'forward slashs as a path delimiter or to escape the normal ' 'path delimiter.') # Fix up default site if family == 'wikipedia' and mylang == 'language' and __no_user_config != '2': print("WARNING: family and mylang are not set.\n" "Defaulting to family='test' and mylang='test'.") family = mylang = 'test' # SECURITY WARNINGS if (not ignore_file_security_warnings and private_files_permission & (stat.S_IRWXG | stat.S_IRWXO) != 0): print("CRITICAL SECURITY WARNING: 'private_files_permission' is set" " to allow access from the group/others which" " could give them access to the sensitive files." " To avoid giving others access to sensitive files, pywikibot" " won't run with this setting. Choose a more restrictive" " permission or set 'ignore_file_security_warnings' to true.") sys.exit(1) # # When called as main program, list all configuration variables # if __name__ == "__main__": import types _all = 1 for _arg in sys.argv[1:]: if _arg == "modified": _all = 0 else: print("Unknown arg %(_arg)s ignored" % locals()) _k = list(globals().keys()) _k.sort() for _name in _k: if _name[0] != '_': if not type(globals()[_name]) in [types.FunctionType, types.ModuleType]: if _all or _name in _modified: _value = globals()[_name] if _name in _private_values and _value: if isinstance(_value, dict): _value = '{ ...xxxxxxxx... }' elif hasattr(_value, '__dict__'): _value = '%s( ...xxxxxxxx... )' % \ _value.__class__.__name__ else: _value = repr('xxxxxxxx') else: _value = repr(_value) print("%s=%s" % (_name, _value)) # cleanup all locally-defined variables for __var in list(globals().keys()): if __var.startswith("_") and not __var.startswith("__"): del sys.modules[__name__].__dict__[__var] del __var
/* @flow strict-local */ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; import type { Narrow } from '../types'; import { ViewPlaceholder } from '../common'; import { getInfoButtonFromNarrow, getExtraButtonFromNarrow } from './titleButtonFromNarrow'; const styles = StyleSheet.create({ wrapper: { flexDirection: 'row', }, }); type Props = {| color: string, narrow: Narrow, |}; export default class TitleNavButtons extends PureComponent<Props> { render() { const { color, narrow } = this.props; const InfoButton = getInfoButtonFromNarrow(narrow); const ExtraButton = getExtraButtonFromNarrow(narrow); return ( <View style={styles.wrapper}> {ExtraButton ? ( <ExtraButton color={color} narrow={narrow} /> ) : ( <ViewPlaceholder width={44} /> )} {InfoButton ? <InfoButton color={color} narrow={narrow} /> : <ViewPlaceholder width={44} />} </View> ); } }
''' Created on Aug 5, 2013 This file mostly contains access utility for BWTs that are already created on disk. @author: holtjma ''' import bisect import gc import gzip import heapq import math import numpy as np import os import pickle import pysam#@UnresolvedImport import shutil import sys import MSBWTGen #flags for samtools REVERSE_COMPLEMENTED_FLAG = 1 << 4#0x10 FIRST_SEGMENT_FLAG = 1 << 6#0x40 #SECOND_SEGMENT_FLAG = 1 << 7#0x80 class BasicBWT(object): ''' This class is the root class for ANY msbwt created by this code regardless of it being compressed or no. Shared Functions: __init__ constructIndexing countOccurrencesOfSeq findIndicesOfStr getSequenceDollarID recoverString loadMsbwt constructTotalCounts constructFMIndex getCharAtIndex getBWTRange getOccurrenceOfCharAtIndex getFullFMAtIndex ''' def __init__(self): ''' Constructor Nothing special, use this for all at the start ''' #valid characters are hard-coded for now self.numToChar = np.array(sorted(['$', 'A', 'C', 'G', 'N', 'T'])) self.charToNum = {} for i, c in enumerate(self.numToChar): self.charToNum[c] = i self.vcLen = len(self.numToChar) #this is purely for querying and determines how big our cache will be to shorten query times #TODO: experiment with this number self.cacheDepth = 6 def constructIndexing(self): ''' This helper function calculates the start and end index for each character in the BWT. Basically, the information generated here is for quickly finding offsets. This is run AFTER self.constructTotalCounts(...) ''' #mark starts and ends of key elements self.startIndex = [None]*self.vcLen self.endIndex = [None]*self.vcLen pos = 0 #go through the 1-mers for c in xrange(0, self.vcLen): #build start and end indexes self.startIndex[c] = pos pos += self.totalCounts[c] self.endIndex[c] = pos def countOccurrencesOfSeq(self, seq, givenRange=None): ''' This function counts the number of occurrences of the given sequence @param seq - the sequence to search for @param givenRange - the range to start from (if a partial search has already been run), default=whole range @return - an integer count of the number of times seq occurred in this BWT ''' #init the current range if givenRange == None: if not self.searchCache.has_key(seq[-self.cacheDepth:]): res = self.findIndicesOfStr(seq[-self.cacheDepth:]) self.searchCache[seq[-self.cacheDepth:]] = (int(res[0]), int(res[1])) l, h = self.searchCache[seq[-self.cacheDepth:]] seq = seq[0:-self.cacheDepth] else: l = givenRange[0] h = givenRange[1] #reverse sequence and convert to ints so we can iterate through it revSeq = [self.charToNum[c] for c in reversed(seq)] for c in revSeq: #get the start and end offsets l = self.getOccurrenceOfCharAtIndex(c, l) h = self.getOccurrenceOfCharAtIndex(c, h) #early exit for counts if l == h: return 0 #return the difference return h - l def findIndicesOfStr(self, seq, givenRange=None): ''' This function will search for a string and find the location of that string OR the last index less than it. It also will start its search within a given range instead of the whole structure @param seq - the sequence to search for @param givenRange - the range to search for, whole range by default @return - a python range representing the start and end of the sequence in the bwt ''' #init the current range if givenRange == None: if not self.searchCache.has_key(seq[-self.cacheDepth:]): res = self.findIndicesOfStr(seq[-self.cacheDepth:], [0, self.totalSize]) self.searchCache[seq[-self.cacheDepth:]] = (int(res[0]), int(res[1])) l, h = self.searchCache[seq[-self.cacheDepth:]] seq = seq[0:-self.cacheDepth] else: l = givenRange[0] h = givenRange[1] #reverse sequence and convert to ints so we can iterate through it revSeq = [self.charToNum[c] for c in reversed(seq)] for c in revSeq: #get the start and end offsets l = self.getOccurrenceOfCharAtIndex(c, l) h = self.getOccurrenceOfCharAtIndex(c, h) return (l, h) def getSequenceDollarID(self, strIndex, returnOffset=False): ''' This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indicating the dollar ID of the string the given character belongs to ''' #figure out the first hop backwards currIndex = strIndex prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) i = 0 #while we haven't looped back to the start while prevChar != 0: #figure out where to go from here prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) i += 1 if returnOffset: return (currIndex, i) else: return currIndex def recoverString(self, strIndex, withIndex=False): ''' This will return the string that starts at the given index @param strIndex - the index of the string we want to recover @return - string that we found starting at the specified '$' index ''' retNums = [] indices = [] #figure out the first hop backwards currIndex = strIndex prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) #while we haven't looped back to the start while currIndex != strIndex: #update the string retNums.append(prevChar) if withIndex: indices.append(currIndex) #figure out where to go from here prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) for i in xrange(0, self.vcLen): if strIndex < self.endIndex[i]: retNums.append(i) break if withIndex: indices.append(strIndex) #reverse the numbers, convert to characters, and join them in to a single sequence ret = ''.join(self.numToChar[retNums[::-1]]) #return what we found if withIndex: return (ret, indices[::-1]) else: return ret def getTotalSize(self): return self.totalSize class MultiStringBWT(BasicBWT): ''' This class is a BWT capable of hosting multiple strings inside one structure. Basically, this would allow you to search for a given string across several strings simultaneously. Note: this class is for the non-compressed version, for general purposes use the function loadBWT(...) which automatically detects whether this class or CompressedMSBWT is correct ''' def loadMsbwt(self, dirName, logger): ''' This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index on disk if it doesn't already exist @param dirName - the filename to load ''' #open the file with our BWT in it self.dirName = dirName self.bwt = np.load(self.dirName+'/msbwt.npy', 'r') #build auxiliary structures self.constructTotalCounts(logger) self.constructIndexing() self.constructFMIndex(logger) def constructTotalCounts(self, logger): ''' This function constructs the total count for each valid character in the array or loads them if they already exist. These will always be stored in '<DIR>/totalCounts.p', a pickled file ''' self.totalSize = self.bwt.shape[0] abtFN = self.dirName+'/totalCounts.p' if os.path.exists(abtFN): fp = open(abtFN, 'r') self.totalCounts = pickle.load(fp) fp.close() else: chunkSize = 2**20 if logger != None: logger.info('First time calculation of \'%s\'' % abtFN) #figure out the counts using the standard counting techniques, one chunk at a time self.totalCounts = [0]*self.vcLen i = 0 while i*chunkSize < self.bwt.shape[0]: self.totalCounts = np.add(self.totalCounts, np.bincount(self.bwt[i*chunkSize:(i+1)*chunkSize], minlength=self.vcLen)) i += 1 #save the total count to '<DIR>/totalCounts.p' fp = open(abtFN, 'w+') pickle.dump(self.totalCounts, fp) fp.close() def constructFMIndex(self, logger): ''' This function iterates through the BWT and counts the letters as it goes to create the FM index. For example, the string 'ACC$' would have BWT 'C$CA'. The FM index would iterate over this and count the occurence of the letter it found so you'd end up with this: BWT FM-index C 0 0 0 $ 0 0 1 C 1 0 1 A 1 0 2 1 1 2 This is necessary for finding the occurrence of a letter using the getOccurrenceOfCharAtIndex(...) function. In reality, this function creates a sampled FM-index so only one index every 2048 bases is filled in. This file is always stored in '<DIR>/fmIndex.npy' ''' #sampling method self.searchCache = {} self.bitPower = 11 self.binSize = 2**self.bitPower self.fmIndexFN = self.dirName+'/fmIndex.npy' if os.path.exists(self.fmIndexFN): self.partialFM = np.load(self.fmIndexFN, 'r') else: if logger != None: logger.info('First time calculation of \'%s\'' % self.fmIndexFN) #pre-allocate space self.partialFM = np.lib.format.open_memmap(self.fmIndexFN, 'w+', '<u8', (self.bwt.shape[0]/self.binSize+1, self.vcLen)) #now perform each count and store it to disk counts = np.zeros(dtype='<u8', shape=(self.vcLen,)) counts[:] = self.startIndex self.partialFM[0] = self.startIndex for j in xrange(1, self.partialFM.shape[0]): counts += np.bincount(self.bwt[self.binSize*(j-1):self.binSize*j], minlength=self.vcLen) self.partialFM[j] = counts def getCharAtIndex(self, index): ''' This function is only necessary for other functions which perform searches generically without knowing if the underlying structure is compressed or not @param index - the index to retrieve the character from ''' return self.bwt[index] def getBWTRange(self, start, end): ''' This function is only necessary for other functions which perform searches generically without knowing if the underlying structure is compressed or not @param start - the beginning of the range to retrieve @param end - the end of the range in normal python notation (bwt[end] is not part of the return) ''' return self.bwt[start:end] def getOccurrenceOfCharAtIndex(self, sym, index): ''' This functions gets the FM-index value of a character at the specified position @param sym - the character to find the occurrence level @param index - the index we want to find the occurrence level at @return - the number of occurrences of char before the specified index ''' #sampling method #get the bin we occupy binID = index >> self.bitPower #these two methods seem to have the same approximate run time if (binID << self.bitPower) == index: ret = self.partialFM[binID][sym] else: ret = self.partialFM[binID][sym] + np.bincount(self.bwt[binID << self.bitPower:index], minlength=6)[sym] return int(ret) def getFullFMAtIndex(self, index): ''' This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A 1 1 4 4 4 1 2 4 4 4 @return - the above information in the form of an array that already incorporates the offset value into the counts ''' #get the bin we occupy binID = index >> self.bitPower if binID << self.bitPower == index: ret = self.partialFM[binID] else: ret = self.partialFM[binID] + np.bincount(self.bwt[binID << self.bitPower:index], minlength=6) return ret def createKmerProfile(self, k, profileCsvFN): ''' TODO: this method is oldddddd, needs to be ported into BasicBWT AND reworked to do this better @param k - the length of the k-mers to profile @param profileCsvFN - the filename of the csv to create ''' searches = [('', 0, self.bwt.shape[0])] normTotal = 0 lines = [] while len(searches) > 0: (seq, start, end) = searches.pop(0) if len(seq) == k: lines.append(seq+','+str(end-start)) normTotal += (end-start)**2 else: nls = self.getFullFMAtIndex(start) nhs = self.getFullFMAtIndex(end) for c in xrange(self.vcLen-1, -1, -1): if nls[c] == nhs[c]: #do nothing pass else: newSeq = self.numToChar[c]+seq searches.insert(0, (newSeq, int(nls[c]), int(nhs[c]))) fp = open(profileCsvFN, 'w+') fp.write('total,'+str(math.sqrt(normTotal))+'\n') for l in sorted(lines): fp.write(l+'\n') fp.close() class CompressedMSBWT(BasicBWT): ''' This structure inherits from the BasicBWT and includes several functions with identical functionality to the MultiStringBWT class. However, the implementations are different as this class represents a version of the BWT that is stored in a compressed format. Generally speaking, this class is slower due to partial decompressions and more complicated routines. For understanding the compression, refer to MSBWTGen.compressBWT(...). ''' def loadMsbwt(self, dirName, logger): ''' This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory @param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail ''' #open the file with our BWT in it self.dirName = dirName self.bwt = np.load(self.dirName+'/comp_msbwt.npy', 'r') #build auxiliary structures self.constructTotalCounts(logger) self.constructIndexing() self.constructFMIndex(logger) def constructTotalCounts(self, logger): ''' This function constructs the total count for each valid character in the array and stores it under '<DIR>/totalCounts.p' since these values are independent of compression ''' self.letterBits = 3 self.numberBits = 8-self.letterBits self.numPower = 2**self.numberBits self.mask = 255 >> self.numberBits abtFN = self.dirName+'/totalCounts.p' if os.path.exists(abtFN): fp = open(abtFN, 'r') self.totalCounts = pickle.load(fp) fp.close() else: if logger != None: logger.info('First time calculation of \'%s\'' % abtFN) self.totalCounts = [0]*self.vcLen binSize = 2**15 end = 0 while end < self.bwt.shape[0]: start = end end = end + binSize if end > self.bwt.shape[0]: end = self.bwt.shape[0] #find a clean break in the characters while end < self.bwt.shape[0] and ((self.bwt[end] & self.mask) == (self.bwt[end-1] & self.mask)): end += 1 letters = np.bitwise_and(self.bwt[start:end], self.mask) counts = np.right_shift(self.bwt[start:end], self.letterBits, dtype='<u8') powers = np.zeros(dtype='<u8', shape=(end-start,)) #solve the actual powers i = 1 same = (letters[0:-1] == letters[1:]) while np.sum(same) > 0: (powers[i:])[same] += 1 i += 1 same = np.bitwise_and(same[0:-1], same[1:]) #each letter has a variable 'weight' which is the runlength of that region self.totalCounts += np.bincount(letters, np.multiply(counts, self.numPower**powers), minlength=self.vcLen) fp = open(abtFN, 'w+') pickle.dump(self.totalCounts, fp) fp.close() self.totalSize = int(np.sum(self.totalCounts)) def constructFMIndex(self, logger): ''' This function iterates through the BWT and counts the letters as it goes to create the FM index. For example, the string 'ACC$' would have BWT 'C$CA'. The FM index would iterate over this and count the occurence of the letter it found so you'd end up with this: BWT FM-index C 0 0 0 $ 0 0 1 C 1 0 1 A 1 0 2 1 1 2 This is necessary for finding the occurrence of a letter using the getOccurrenceOfCharAtIndex(...) function. In reality, this function creates a sampled FM-index more complicated than the uncompressed counter-part. This is because the 2048 size bins don't fall evenly all the time. A second data structure is used to tell you where to start a particular FM-index count. The two files necessary are '<DIR>/comp_fmIndex.npy' and '<DIR>/comp_refIndex.npy' ''' #sampling method self.searchCache = {} self.bitPower = 11 self.binSize = 2**self.bitPower self.fmIndexFN = self.dirName+'/comp_fmIndex.npy' self.fmRefFN = self.dirName+'/comp_refIndex.npy' if os.path.exists(self.fmIndexFN) and os.path.exists(self.fmRefFN): #both exist, just memmap them self.partialFM = np.load(self.fmIndexFN, 'r') self.refFM = np.load(self.fmRefFN, 'r') else: if logger != None: logger.info('First time calculation of \'%s\'' % self.fmIndexFN) #pre-allocate space samplingSize = int(math.ceil(float(self.totalSize)/self.binSize)) self.partialFM = np.lib.format.open_memmap(self.fmIndexFN, 'w+', '<u8', (samplingSize, self.vcLen)) self.refFM = np.lib.format.open_memmap(self.fmRefFN, 'w+', '<u8', (samplingSize,)) countsSoFar = np.cumsum(self.totalCounts)-self.totalCounts totalCounts = 0 prevStart = 0 bwtIndex = 0 chunkSize = 10000 samplingID = 0 #iterate through the whole file creating dynamically sized bins while bwtIndex < self.bwt.shape[0] and samplingID < samplingSize: #extract letters and counts so we can do sums letters = np.bitwise_and(self.bwt[bwtIndex:bwtIndex+chunkSize], self.mask) counts = np.right_shift(self.bwt[bwtIndex:bwtIndex+chunkSize], self.letterBits, dtype='<u8') #numpy methods for find the powers i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) offsets = np.cumsum(counts) #this is basically looking for a clean breakpoint for our bin to end moreToUpdate = True while moreToUpdate: prevStart = np.searchsorted(offsets, samplingID*self.binSize-totalCounts, 'right') if prevStart == letters.shape[0]: prevStart -= 1 while prevStart > 0 and letters[prevStart] == letters[prevStart-1]: prevStart -= 1 moreToUpdate = False else: while prevStart > 0 and letters[prevStart] == letters[prevStart-1]: prevStart -= 1 self.refFM[samplingID] = bwtIndex+prevStart if prevStart > 0: self.partialFM[samplingID][:] = np.add(countsSoFar, np.bincount(letters[0:prevStart], counts[0:prevStart], self.vcLen)) else: self.partialFM[samplingID][:] = countsSoFar samplingID += 1 bwtIndex += prevStart if prevStart > 0: countsSoFar += np.bincount(letters[0:prevStart], counts[0:prevStart], self.vcLen) totalCounts += np.sum(np.bincount(letters[0:prevStart], counts[0:prevStart], self.vcLen)) #we'll use this later when we do lookups self.offsetSum = np.sum(self.partialFM[0]) def getCharAtIndex(self, index): ''' Used for searching, this function masks the complexity behind retrieving a specific character at a specific index in our compressed BWT. @param index - the index to retrieve the character from @param return - return the character in our BWT that's at a particular index (integer format) ''' #get the bin we should start from binID = index >> self.bitPower bwtIndex = self.refFM[binID] #these are the values that indicate how far in we really are trueIndex = np.sum(self.partialFM[binID])-self.offsetSum dist = index-trueIndex #calculate how big of a region we actually need to 'decompress' if binID == self.refFM.shape[0]-1: endRange = self.bwt.shape[0] else: endRange = self.refFM[binID+1]+1 while endRange < self.bwt.shape[0] and (self.bwt[endRange] & self.mask) == (self.bwt[endRange-1] & self.mask): endRange += 1 #extract the symbols and counts associated with each byte letters = np.bitwise_and(self.bwt[bwtIndex:endRange], self.mask) counts = np.right_shift(self.bwt[bwtIndex:endRange], self.letterBits, dtype='<u8') #numpy methods for find the powers i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) #these are the true counts after raising to the appropriate power cs = np.cumsum(counts) x = np.searchsorted(cs, dist, 'right') return letters[x] def getBWTRange(self, start, end): ''' This function masks the complexity of retrieving a chunk of the BWT from the compressed format @param start - the beginning of the range to retrieve @param end - the end of the range in normal python notation (bwt[end] is not part of the return) @return - a range of integers representing the characters in the bwt from start to end ''' #set aside an array block to fill startBlockIndex = start >> self.bitPower endBlockIndex = int(math.floor(float(end)/self.binSize)) trueStart = startBlockIndex*self.binSize #first we will extract the range of blocks return self.decompressBlocks(startBlockIndex, endBlockIndex)[start-trueStart:end-trueStart] def decompressBlocks(self, startBlock, endBlock): ''' This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in decompression @param startBlock - the index of the start block we will decode @param endBlock - the index of the final block we will decode, if they are the same, we decode one block @return - an array of size blockSize*(endBlock-startBlock+1), interpreting that block is up to getBWTRange(...) ''' expectedIndex = startBlock*self.binSize trueIndex = np.sum(self.partialFM[startBlock])-self.offsetSum dist = expectedIndex - trueIndex #find the end of the region of interest startRange = self.refFM[startBlock] if endBlock >= self.refFM.shape[0]-1: endRange = self.bwt.shape[0] returnSize = self.binSize*(endBlock-startBlock)+(self.totalSize % self.binSize) else: endRange = self.refFM[endBlock+1]+1 returnSize = self.binSize*(endBlock-startBlock+1) while endRange < self.bwt.shape[0] and (self.bwt[endRange] & self.mask) == (self.bwt[endRange-1] & self.mask): endRange += 1 ret = np.zeros(dtype='<u1', shape=(returnSize,)) #split the letters and numbers in the compressed bwt letters = np.bitwise_and(self.bwt[startRange:endRange], self.mask) counts = np.right_shift(self.bwt[startRange:endRange], self.letterBits, dtype='<u8') #multiply counts where needed i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) #now I have letters and counts, time to fill in the array s = 0 lInd = 0 while dist > 0: if counts[lInd] < dist: dist -= counts[lInd] lInd += 1 else: counts[lInd] -= dist dist = 0 #we're at the correct letter index now while s < ret.shape[0]: if lInd >= letters.shape[0]: pass ret[s:s+counts[lInd]] = letters[lInd] s += counts[lInd] lInd += 1 return ret def getOccurrenceOfCharAtIndex(self, sym, index): ''' This functions gets the FM-index value of a character at the specified position @param sym - the character to find the occurrence level @param index - the index we want to find the occurrence level at @return - the number of occurrences of char before the specified index ''' return int(self.getFullFMAtIndex(index)[sym]) def getFullFMAtIndex(self, index): ''' This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A 1 1 4 4 4 1 2 4 4 4 @return - the above information in the form of an array that already incorporates the offset value into the counts ''' if index == self.totalSize: return np.cumsum(self.totalCounts) #get the bin we start from binID = index >> self.bitPower bwtIndex = self.refFM[binID] #figure out how far in we really are ret = np.copy(self.partialFM[binID]) trueIndex = np.sum(ret)-self.offsetSum dist = index-trueIndex if dist == 0: return ret #find the end of the region of interest if binID == self.refFM.shape[0]-1: endRange = self.bwt.shape[0] else: endRange = self.refFM[binID+1]+1 while endRange < self.bwt.shape[0] and (self.bwt[endRange] & self.mask) == (self.bwt[endRange-1] & self.mask): endRange += 1 #split the letters and numbers in the compressed bwt letters = np.bitwise_and(self.bwt[bwtIndex:endRange], self.mask) counts = np.right_shift(self.bwt[bwtIndex:endRange], self.letterBits, dtype='<u8') i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) cs = np.subtract(np.cumsum(counts), counts) x = np.searchsorted(cs, dist, 'left') if x > 1: ret += np.bincount(letters[0:x-1], counts[0:x-1], minlength=self.vcLen) ret[letters[x-1]] += dist-cs[x-1] return ret def loadBWT(bwtDir, logger=None): ''' Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated ''' if os.path.exists(bwtDir+'/msbwt.npy'): msbwt = MultiStringBWT() msbwt.loadMsbwt(bwtDir, logger) return msbwt elif os.path.exists(bwtDir+'/comp_msbwt.npy'): msbwt = CompressedMSBWT() msbwt.loadMsbwt(bwtDir, logger) return msbwt else: logger.error('Invalid BWT directory.') return None def createMSBWTFromSeqs(seqArray, mergedDir, numProcs, areUniform, logger): ''' This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer @param seqArray - a list of '$'-terminated sequences to be in the MSBWT @param mergedFN - the final destination filename for the BWT @param numProcs - the number of processes it's allowed to use ''' #wipe the auxiliary data stored here MSBWTGen.clearAuxiliaryData(mergedDir) #TODO: do we want a special case for N=1? there was one in early code, but we could just assume users aren't dumb seqFN = mergedDir+'/seqs.npy' offsetFN = mergedDir+'/offsets.npy' #sort the sequences seqCopy = sorted(seqArray) if areUniform: uniformLength = len(seqArray[0]) else: uniformLength = 0 #join into one massive string seqCopy = ''.join(seqCopy) #convert the sequences into uint8s and then save it seqCopy = np.fromstring(seqCopy, dtype='<u1') MSBWTGen.writeSeqsToFiles(seqCopy, seqFN, offsetFN, uniformLength) MSBWTGen.createFromSeqs(seqFN, offsetFN, mergedDir+'/msbwt.npy', numProcs, areUniform, logger) def createMSBWTFromFastq(fastqFNs, outputDir, numProcs, areUniform, logger): ''' This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading all string prior to computation @param fastqFNs - a list of fastq filenames to extract sequences from @param outputDir - the directory for all of the bwt related data @param numProcs - the number of processes it's allowed to use @areUniform - true if all the sequences passed into the function are of equal length ''' #generate the files we will reference and clear out the in memory array before making the BWT logger.info('Saving sorted sequences...') seqFN = outputDir+'/seqs.npy' offsetFN = outputDir+'/offsets.npy' abtFN = outputDir+'/about.npy' bwtFN = outputDir+'/msbwt.npy' MSBWTGen.clearAuxiliaryData(outputDir) preprocessFastqs(fastqFNs, seqFN, offsetFN, abtFN, areUniform, logger) MSBWTGen.createFromSeqs(seqFN, offsetFN, bwtFN, numProcs, areUniform, logger) def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger): ''' This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer @param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME @param outputDir - the directory for all of the bwt related data @param numProcs - the number of processes it's allowed to use @areUniform - true if all the sequences passed into the function are of equal length ''' #generate the files we will reference and clear out the in memory array before making the BWT logger.info('Saving sorted sequences...') seqFN = outputDir+'/seqs.npy' offsetFN = outputDir+'/offsets.npy' abtFN = outputDir+'/about.npy' bwtFN = outputDir+'/msbwt.npy' MSBWTGen.clearAuxiliaryData(outputDir) preprocessBams(bamFNs, seqFN, offsetFN, abtFN, areUniform, logger) MSBWTGen.createFromSeqs(seqFN, offsetFN, bwtFN, numProcs, areUniform, logger) def customiter(numpyArray): ''' dummy iterator, for some reason numpy doesn't like to act like one by default ''' for x in numpyArray: yield tuple(x) def preprocessFastqs(fastqFNs, seqFNPrefix, offsetFN, abtFN, areUniform, logger): ''' This function does the grunt work behind string extraction for fastq files @param fastqFNs - a list of .fq filenames for parsing @param seqFNPrefix - this is always of the form '<DIR>/seqs.npy' @param offsetFN - this is always of the form '<DIR>/offsets.npy' @param abtFN - this is always of the form '<DIR>/about.npy' @param areUniform - True if all sequences are of uniform length @param logger - logger object for output ''' #create a seqArray seqArray = [] tempFileId = 0 seqsPerFile = 1000000 maxSeqLen = -1 numSeqs = 0 subSortFNs = [] for fnID, fn in enumerate(fastqFNs): #open the file and read in starting form the second, every 4th line logger.info('Loading \''+fn+'\'...') if fn.endswith('.gz'): fp = gzip.open(fn, 'r') else: fp = open(fn, 'r') i = -1 #go through each line for line in fp: if i % 4 == 0: seqArray.append((line.strip('\n')+'$', fnID, i/4)) if len(seqArray) == seqsPerFile: if not areUniform or maxSeqLen == -1: maxSeqLen = 0 for seq, fID, seqID in seqArray: if len(seq) > maxSeqLen: maxSeqLen = len(seq) tempFN = seqFNPrefix+'.sortTemp.'+str(tempFileId)+'.npy' subSortFNs.append(tempFN) tempArray = np.lib.format.open_memmap(tempFN, 'w+', 'a'+str(maxSeqLen)+',<u1,<u8', (len(seqArray),)) tempArray[:] = sorted(seqArray) numSeqs += len(seqArray) del tempArray tempFileId += 1 seqArray = [] i += 1 fp.close() if len(seqArray) > 0: if not areUniform or maxSeqLen == -1: maxSeqLen = 0 for seq, fID, seqID in seqArray: if len(seq) > maxSeqLen: maxSeqLen = len(seq) tempFN = seqFNPrefix+'.sortTemp.'+str(tempFileId)+'.npy' subSortFNs.append(tempFN) tempArray = np.lib.format.open_memmap(tempFN, 'w+', 'a'+str(maxSeqLen)+',<u1,<u8', (len(seqArray),)) tempArray[:] = sorted(seqArray) numSeqs += len(seqArray) del tempArray tempFileId += 1 seqArray = [] logger.info('Pre-sorting '+str(numSeqs)+' sequences...') iters = [] for fn in subSortFNs: iters.append(customiter(np.load(fn, 'r'))) #save it tempFN = seqFNPrefix+'.temp.npy' fp = open(tempFN, 'w+') aboutFile = np.lib.format.open_memmap(abtFN, 'w+', '<u1,<u8', (numSeqs,)) ind = 0 for tup in heapq.merge(*iters): (seq, fID, seqID) = tup aboutFile[ind] = (fID, seqID) fp.write(seq) ind += 1 fp.close() #clean up disk space for fn in subSortFNs: os.remove(fn) #convert the sequences into uint8s and then save it del seqArray seqArray = np.memmap(tempFN) if areUniform: uniformLength = maxSeqLen else: uniformLength = 0 logger.info('Saving sorted sequences for BWT construction...') MSBWTGen.writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength) #wipe this del seqArray os.remove(tempFN) def preprocessBams(bamFNs, seqFNPrefix, offsetFN, abtFN, areUniform, logger): ''' This does the grunt work behind read extraction from a name-sorted BAM file. If it isn't sorted, this will not work as intended. @param bamFNs - a list of '.bam' filenames for parsing @param seqFNPrefix - this is always of the form '<DIR>/seqs.npy' @param offsetFN - this is always of the form '<DIR>/offsets.npy' @param abtFN - this is always of the form '<DIR>/about.npy' @param areUniform - True if all sequences are of uniform length @param logger - logger object for output ''' #create a seqArray seqArray = [] #prep to break this into several smaller sorted sequences tempFileId = 0 seqsPerFile = 10000000 maxSeqLen = -1 numSeqs = 0 subSortFNs = [] for fnID, fn in enumerate(bamFNs): #open the file and read in starting form the second, every 4th line logger.info('Loading \''+fn+'\'...') bamFile = pysam.Samfile(fn, 'rb') i = 0 nr = bamFile.next() constantSize = len(nr.seq) #go through each line while nr != None: #collect all reads that are the same as nr aligns = [] nqname = nr.qname while nr != None and nr.qname == nqname: aligns.append(nr) try: nr = bamFile.next() except: nr = None #reduce this to a simpler set reads = [None, None] for a in aligns: if len(a.seq) != constantSize: print 'DIFF SIZE='+str(len(a.seq)) if a.flag & REVERSE_COMPLEMENTED_FLAG == 0: #not reverse complemented seq = a.seq else: seq = reverseComplement(a.seq) if a.flag & FIRST_SEGMENT_FLAG == 0: #second segment if reads[1] == None: reads[1] = seq elif reads[1] != seq: logger.warning('Two sequences with same flag and different seqs: '+reads[1]+'\n'+str(a)) else: if reads[0] == None: reads[0] = seq elif reads[0] != seq: logger.warning('Two sequences with same flag and different seqs: '+reads[0]+'\n'+str(a)) for j, r in enumerate(reads): if r == None: continue if r[1-j] == None: seqArray.append((r+'$', fnID, i, 0xFF, 0xFFFFFFFFFFFFFFFF)) else: seqArray.append((r+'$', fnID, i, fnID, i+1-2*j)) if len(seqArray) == seqsPerFile: if not areUniform or maxSeqLen == -1: maxSeqLen = 0 for seq, fID, seqID, pfID, pseqID in seqArray: if len(seq) > maxSeqLen: maxSeqLen = len(seq) tempFN = seqFNPrefix+'.sortTemp.'+str(tempFileId)+'.npy' subSortFNs.append(tempFN) sys.stdout.write('\rWriting file '+str(tempFileId)) sys.stdout.flush() tempArray = np.lib.format.open_memmap(tempFN, 'w+', 'a'+str(maxSeqLen)+',<u1,<u8,<u1,<u8', (len(seqArray),)) tempArray[:] = sorted(seqArray) numSeqs += len(seqArray) del tempArray tempFileId += 1 seqArray = [] i += 1 sys.stdout.write('\n') if len(seqArray) > 0: if not areUniform or maxSeqLen == -1: maxSeqLen = 0 for seq, fID, seqID, pfID, pseqID in seqArray: if len(seq) > maxSeqLen: maxSeqLen = len(seq) tempFN = seqFNPrefix+'.sortTemp.'+str(tempFileId)+'.npy' subSortFNs.append(tempFN) tempArray = np.lib.format.open_memmap(tempFN, 'w+', 'a'+str(maxSeqLen)+',<u1,<u8,<u1,<u8', (len(seqArray),)) tempArray[:] = sorted(seqArray) numSeqs += len(seqArray) del tempArray tempFileId += 1 seqArray = [] logger.info('Pre-sorting '+str(numSeqs)+' sequences...') iters = [] for fn in subSortFNs: iters.append(customiter(np.load(fn, 'r'))) #save it tempFN = seqFNPrefix+'.temp.npy' fp = open(tempFN, 'w+') aboutFile = np.lib.format.open_memmap(abtFN, 'w+', '<u1,<u8,<u1,<u8', (numSeqs,)) ind = 0 for tup in heapq.merge(*iters): (seq, fID, seqID, pfID, pseqID) = tup aboutFile[ind] = (fID, seqID, pfID, pseqID) fp.write(seq) ind += 1 fp.close() for fn in subSortFNs: os.remove(fn) #convert the sequences into uint8s and then save it del seqArray seqArray = np.memmap(tempFN) if areUniform: uniformLength = maxSeqLen else: uniformLength = 0 logger.info('Saving sorted sequences for BWT construction...') MSBWTGen.writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength) #wipe this del seqArray os.remove(tempFN) def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger): ''' This function takes a series of sequences and creates a big BWT by merging the smaller ones Mostly a test function, no real purpose to the tool as of now @param seqArray - a list of '$'-terminated strings to be placed into the array @param mergedFN - the final destination filename for the merged BWT @param numProcs - the number of processors the merge is allowed to create ''' #first wipe away any traces of old information for the case of overwriting a BWT at mergedFN MSBWTGen.clearAuxiliaryData(mergedDir) #create two smaller ones midPoint = len(seqArray)/3 mergedDir1 = mergedDir+'0' mergedDir2 = mergedDir+'1' mergedDir3 = mergedDir+'2' try: shutil.rmtree(mergedDir1) except: pass try: shutil.rmtree(mergedDir2) except: pass try: shutil.rmtree(mergedDir3) except: pass os.makedirs(mergedDir1) os.makedirs(mergedDir2) os.makedirs(mergedDir3) createMSBWTFromSeqs(seqArray[0:midPoint], mergedDir1, numProcs, areUniform, logger) createMSBWTFromSeqs(seqArray[midPoint:2*midPoint], mergedDir2, numProcs, areUniform, logger) createMSBWTFromSeqs(seqArray[2*midPoint:], mergedDir3, numProcs, areUniform, logger) #now do the actual merging MSBWTGen.mergeNewMSBWT(mergedDir, [mergedDir1, mergedDir2, mergedDir3], numProcs, logger) def compareKmerProfiles(profileFN1, profileFN2): ''' This function takes two kmer profiles and compare them for similarity. @param profileFN1 - the first kmer-profile to compare to @param profileFN2 - the second kmer-profile to compare to @return - a tuple of the form (1-norm, 2-norm, sum of differences, normalized Dot product) ''' fp1 = open(profileFN1, 'r') fp2 = open(profileFN2, 'r') oneNorm = 0 twoNorm = 0 sumDeltas = 0 dotProduct = 0 tot1 = float(fp1.readline().strip('\n').split(',')[1]) tot2 = float(fp2.readline().strip('\n').split(',')[1]) (seq1, count1) = parseProfileLine(fp1) (seq2, count2) = parseProfileLine(fp2) while seq1 != None or seq2 != None: if seq1 == seq2: delta = abs(count1/tot1-count2/tot2) dotProduct += (count1/tot1)*(count2/tot2) (seq1, count1) = parseProfileLine(fp1) (seq2, count2) = parseProfileLine(fp2) elif seq2 == None or (seq1 != None and seq1 < seq2): delta = count1/tot1 (seq1, count1) = parseProfileLine(fp1) else: delta = count2/tot2 (seq2, count2) = parseProfileLine(fp2) if delta > oneNorm: oneNorm = delta twoNorm += delta*delta sumDeltas += delta fp1.close() fp2.close() twoNorm = math.sqrt(twoNorm) #print '1-norm:\t\t'+str(oneNorm) #print '2-norm:\t\t'+str(twoNorm) #print 'Delta sum:\t'+str(sumDeltas) return (oneNorm, twoNorm, sumDeltas, dotProduct) def parseProfileLine(fp): ''' Helper function for profile parsing @param fp - the file pointer to get the next line from @return - (kmer, kmerCount) as (string, int) ''' nextLine = fp.readline() if nextLine == None or nextLine == '': return (None, None) else: pieces = nextLine.strip('\n').split(',') return (pieces[0], int(pieces[1])) def interactiveTranscriptConstruction(bwtDir, seedKmer, endSeeds, threshold, numNodes, direction, logger): ''' This function is intended to be an interactive technique for constructing transcripts, probably to be released in a future version of msbwt @param bwtFN - the filename of the BWT to load @param seedKmer - the seed sequence to use for construction @param threshold - minimum number for a path to be considered a path @param direction - True is forward, False is backward @param logger - the logger @param ''' kmerLen = len(seedKmer) validChars = ['$', 'A', 'C', 'G', 'N', 'T'] pileups = [] logger.info('Loading '+bwtDir+'...') msbwt = loadBWT(bwtDir) if os.path.exists(bwtDir+'/origins.npy'): raise Exception("You haven\'t reimplemented the handling of origin files") origins = np.load(bwtDir+'/origins.npy', 'r') else: origins = None logger.info('Beginning with seed \''+seedKmer+'\', len='+str(kmerLen)) kmer = seedKmer pos = kmerLen ret = ''+kmer #these variable are for counting the average pileup totalPileup = 0 numCovered = 0 discoveredBlocks = [] discoveredEdges = [] pathTups = [] parentID = -1 blockID = 0 #TODO: make it an input #we're stating that 5 reads indicates a path here pathThreshold = threshold foundKmers = {} movingAverage = 0 for es in endSeeds: foundKmers[es] = 'END_SEED' terminate = False while not terminate and len(discoveredBlocks) < numNodes: if len(kmer) != kmerLen: print 'ERROR: DIFFERENT SIZED K-MER '+str(len(kmer)) raise Exception('ERROR') #First, perform all the counts of paths going both forwards and backwards counts = {} revCounts = {} maxV = 0 maxC = '' total = 0 numPaths = 0 numRevPaths = 0 for c in validChars: #forward counts fr1 = msbwt.findIndicesOfStr(kmer+c) fr2 = msbwt.findIndicesOfStr(reverseComplement(kmer+c)) #backward counts br1 = msbwt.findIndicesOfStr(c+kmer) br2 = msbwt.findIndicesOfStr(reverseComplement(c+kmer)) counts[c] = (fr1[1]-fr1[0])+(fr2[1]-fr2[0]) revCounts[c] = (br1[1]-br1[0])+(br2[1]-br2[0]) if c != '$': total += counts[c] if counts[c] > maxV: maxV = counts[c] maxC = c if counts[c] > pathThreshold: numPaths += 1 if revCounts[c] > pathThreshold: numRevPaths += 1 if origins != None: pass totalPileup += total numCovered += 1 if numRevPaths > 1: discoveredBlocks.append((parentID, ret, pileups, 'MERGE_'+str(blockID+1))) discoveredEdges.append((blockID, blockID+1, revCounts)) print 'INCOMING MERGE FOUND: '+str(discoveredBlocks[blockID]) parentID = blockID blockID += 1 ret = ''+kmer pileups = [] if total == 0: print 'No strings found.' discoveredBlocks.append((parentID, ret, pileups, 'TERMINAL')) pileups = [] print pathTups print discoveredBlocks if len(pathTups) == 0: terminate = True else: nextPathTup = pathTups.pop(0) print 'Handling1: '+str(nextPathTup) parentID = nextPathTup[1] direction = nextPathTup[2] kmer = nextPathTup[3] ret = ''+kmer discoveredEdges.append((parentID, blockID+1, nextPathTup[0])) blockID += 1 continue #now we identify this kmer as being part of the block foundKmers[kmer] = blockID r1 = msbwt.findIndicesOfStr(kmer) r2 = msbwt.findIndicesOfStr(reverseComplement(kmer)) kmerCount = (r1[1]-r1[0])+(r2[1]-r2[0]) pileups.append(kmerCount) if total == 0: perc = 0 else: perc = float(maxV)/total if numPaths > 1: #TODO: reverse ret if direction is reversed discoveredBlocks.append((parentID, ret, pileups, 'SPLIT')) for c in validChars[1:]: if counts[c] > pathThreshold: #counts, parent block, direction, starting seed if direction: pathSeed = kmer[1:]+c else: pathSeed = c+kmer[0:-1] pathTup = (counts[c], blockID, direction, pathSeed) pathTups.append(pathTup) print pathTups print discoveredBlocks if len(pathTups) == 0: terminate = True else: nextPathTup = pathTups.pop(0) print 'Handling2: '+str(nextPathTup) parentID = nextPathTup[1] direction = nextPathTup[2] kmer = nextPathTup[3] ret = ''+kmer pileups = [] discoveredEdges.append((parentID, blockID+1, nextPathTup[0])) blockID += 1 else: if direction: kmer = kmer[1:]+maxC ret += maxC else: kmer = maxC+kmer[0:-1] ret = maxC+ret pos += 1 movingAverage = .9*movingAverage+.1*maxV print str(pos)+':\t'+kmer+'\t'+str(perc)+'\t'+str(maxV)+'/'+str(total)+'\t'+str(total-maxV)+'\t'+str(movingAverage) while foundKmers.has_key(kmer) and not terminate: #TODO: reverse ret if direction is reversed discoveredBlocks.append((parentID, ret, pileups, 'MERGE_'+str(foundKmers[kmer]))) discoveredEdges.append((blockID, foundKmers[kmer], '')) print pathTups print discoveredBlocks if len(pathTups) == 0: terminate = True else: nextPathTup = pathTups.pop(0) print 'Handling3: '+str(nextPathTup) #pileups.append(nextPathTup[0]) parentID = nextPathTup[1] direction = nextPathTup[2] kmer = nextPathTup[3] ret = ''+kmer pileups = [] discoveredEdges.append((parentID, blockID+1, nextPathTup[0])) blockID += 1 return (discoveredBlocks, discoveredEdges) def reverseComplement(seq): ''' Helper function for generating reverse-complements ''' revComp = '' complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'} for c in reversed(seq): revComp += complement[c] return revComp
module.exports = { presets: [ ['@babel/preset-react', { runtime: 'automatic' }], '@babel/preset-flow', '@babel/preset-env', ], };
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from util import * from electrum_stratis.i18n import _ class UTXOList(MyTreeWidget): def __init__(self, parent=None): MyTreeWidget.__init__(self, parent, self.create_menu, [ _('Output'), _('Address'), _('Label'), _('Amount'), ''], 2) self.setSelectionMode(QAbstractItemView.ExtendedSelection) def get_name(self, x): return x.get('prevout_hash') + ":%d"%x.get('prevout_n') def on_update(self): self.wallet = self.parent.wallet item = self.currentItem() self.clear() self.utxos = self.wallet.get_utxos() for x in self.utxos: address = x.get('address') name = self.get_name(x) label = self.wallet.get_label(x.get('prevout_hash')) amount = self.parent.format_amount(x['value']) utxo_item = QTreeWidgetItem([name[0:10]+'...'+name[-10:], address, label, amount]) utxo_item.setFont(0, QFont(MONOSPACE_FONT)) utxo_item.setFont(1, QFont(MONOSPACE_FONT)) utxo_item.setData(0, Qt.UserRole, name) if self.wallet.is_frozen(address): utxo_item.setBackgroundColor(0, QColor('lightblue')) self.addChild(utxo_item) def create_menu(self, position): from electrum_stratis.wallet import Multisig_Wallet selected = [ x.data(0, Qt.UserRole).toString() for x in self.selectedItems()] if not selected: return coins = filter(lambda x: self.get_name(x) in selected, self.utxos) menu = QMenu() if len(selected) == 1: coin = coins[0] menu.addAction(_("Copy Address"), lambda: self.parent.app.clipboard().setText(coin.get('address'))) menu.addAction(_("Spend"), lambda: self.parent.spend_coins(coins)) menu.exec_(self.viewport().mapToGlobal(position))
/* * This is a part of the BugTrap package. * Copyright (c) 2005-2007 IntelleSoft. * All rights reserved. * * Description: Dynamic string holder. * Author: Maksim Pyatkovskiy. * * This source code is only intended as a supplement to the * BugTrap package reference and related electronic documentation * provided with the product. See these sources for detailed * information regarding the BugTrap package. */ #pragma once class CStrStream; /// Dynamic string holder. class CStrHolder { public: /// Initialize the object. CStrHolder(void); /// Destroy the object. ~CStrHolder(void); /// Makes a copy of string data. CStrHolder(PCSTR pszStrData); /// Makes a copy of string data. CStrHolder(PCWSTR pszStrData); /// Makes a copy of string data. CStrHolder(const CStrHolder& rStrHolder); /// Makes a copy of string data. CStrHolder(const CStrStream& rStrStream); /// Makes a copy of string data. CStrHolder& operator=(PCSTR pszStrData); /// Makes a copy of string data. CStrHolder& operator=(PCWSTR pszStrData); /// Makes a copy of string data. CStrHolder& operator=(const CStrHolder& rStrHolder); /// Makes a copy of string data. CStrHolder& operator=(const CStrStream& rStrStream); /// Get string data. operator PCTSTR(void) const; /// Free string data. void Free(void); /// Get string length. int GetLength(void) const; /// Return true if string is empty. BOOL IsEmpty(void) const; /// Get string character. TCHAR GetAt(int nPosition) const; /// Get string character. TCHAR operator[](int nPosition) const; /// Object comparison. friend bool operator==(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); /// Object comparison. friend bool operator!=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); /// Object comparison. friend bool operator<(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); /// Object comparison. friend bool operator<=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); /// Object comparison. friend bool operator>(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); /// Object comparison. friend bool operator>=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2); private: /// Release string data. void Release(void); /// Initialize sting data. void InitData(PCSTR pszStrData); /// Initialize sting data. void InitData(PCWSTR pszStrData); /// Initialize sting data. void InitData(const CStrHolder& rStrHolder); /// Initialize sting data. void InitData(const CStrStream& rStrStream); /// Copy string into existing holder. void CopyData(PCSTR pszStrData); /// Copy string into existing holder. void CopyData(PCWSTR pszStrData); /// Copy string into existing holder. void CopyData(const CStrHolder& rStrHolder); /// Copy string into existing holder. void CopyData(const CStrStream& rStrStream); /// Shared string data. struct CStringData { /// Usage counter. int m_nUsageCount; /// String length. int m_nLength; #pragma warning(push) #pragma warning(disable : 4200) // nonstandard extension used : zero-sized array in struct/union /// Pointer to the string. TCHAR m_szData[0]; #pragma warning(pop) }; /// Pointer to string data. CStringData* m_pData; /// Empty string data. static CStringData m_sdEmptyData; }; inline CStrHolder::CStrHolder(void) { m_pData = &m_sdEmptyData; } inline CStrHolder::~CStrHolder(void) { Release(); } /** * @return string data. */ inline CStrHolder::operator PCTSTR(void) const { _ASSERTE(m_pData != NULL); return m_pData->m_szData; } /** * @return string length. */ inline int CStrHolder::GetLength(void) const { _ASSERTE(m_pData != NULL); return m_pData->m_nLength; } /** * @return true if string is empty. */ inline BOOL CStrHolder::IsEmpty(void) const { _ASSERTE(m_pData != NULL); return (m_pData->m_nLength == 0); } /** * @param pszStrData - another string data. */ inline CStrHolder::CStrHolder(PCSTR pszStrData) { InitData(pszStrData); } /** * @param pszStrData - another string data. */ inline CStrHolder::CStrHolder(PCWSTR pszStrData) { InitData(pszStrData); } /** * @param rStrHolder - another string data. */ inline CStrHolder::CStrHolder(const CStrHolder& rStrHolder) { InitData(rStrHolder); } /** * @param rStrStream - another string data. */ inline CStrHolder::CStrHolder(const CStrStream& rStrStream) { InitData(rStrStream); } /** * @param pszStrData - another string data. * @return reference to itself. */ inline CStrHolder& CStrHolder::operator=(PCSTR pszStrData) { CopyData(pszStrData); return *this; } /** * @param pszStrData - another string data. * @return reference to itself. */ inline CStrHolder& CStrHolder::operator=(PCWSTR pszStrData) { CopyData(pszStrData); return *this; } /** * @param rStrHolder - another string data. * @return reference to itself. */ inline CStrHolder& CStrHolder::operator=(const CStrHolder& rStrHolder) { if (this != &rStrHolder) CopyData(rStrHolder); return *this; } /** * @param rStrStream - another string data. * @return reference to itself. */ inline CStrHolder& CStrHolder::operator=(const CStrStream& rStrStream) { CopyData(rStrStream); return *this; } inline void CStrHolder::Free(void) { Release(); m_pData = &m_sdEmptyData; } /** * @param pszStrData - another string data. */ inline void CStrHolder::CopyData(PCSTR pszStrData) { Release(); InitData(pszStrData); } /** * @param pszStrData - another string data. */ inline void CStrHolder::CopyData(PCWSTR pszStrData) { Release(); InitData(pszStrData); } /** * @param rStrStream - another string object. */ inline void CStrHolder::CopyData(const CStrStream& rStrStream) { Release(); InitData(rStrStream); } /** * @param nPosition - character position within the string. * @return character value. */ inline TCHAR CStrHolder::GetAt(int nPosition) const { _ASSERTE(nPosition < m_pData->m_nLength); if (nPosition >= m_pData->m_nLength) RaiseException(STATUS_ARRAY_BOUNDS_EXCEEDED, 0, 0, NULL); return m_pData->m_szData[nPosition]; } /** * @param nPosition - character position within the string. * @return character value. */ inline TCHAR CStrHolder::operator[](int nPosition) const { _ASSERTE(nPosition < m_pData->m_nLength); if (nPosition >= m_pData->m_nLength) RaiseException(STATUS_ARRAY_BOUNDS_EXCEEDED, 0, 0, NULL); return m_pData->m_szData[nPosition]; } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator==(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) == 0); } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator!=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) != 0); } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator<(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) < 0); } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator<=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) <= 0); } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator>(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) > 0); } /** * @param rStrHolder1 - 1st object. * @param rStrHolder2 - 2nd object. * @return comparison result. */ inline bool operator>=(const CStrHolder& rStrHolder1, const CStrHolder& rStrHolder2) { return (_tcscmp(rStrHolder1.m_pData->m_szData, rStrHolder2.m_pData->m_szData) >= 0); }
from wptserve.utils import isomorphic_decode def main(request, response): if b'Status' in request.GET: status = int(request.GET[b"Status"]) else: status = 302 headers = [] url = isomorphic_decode(request.GET[b'Redirect']) headers.append((b"Location", url)) if b"ACAOrigin" in request.GET: for item in request.GET[b"ACAOrigin"].split(b","): headers.append((b"Access-Control-Allow-Origin", item)) for suffix in [b"Headers", b"Methods", b"Credentials"]: query = b"ACA%s" % suffix header = b"Access-Control-Allow-%s" % suffix if query in request.GET: headers.append((header, request.GET[query])) if b"ACEHeaders" in request.GET: headers.append((b"Access-Control-Expose-Headers", request.GET[b"ACEHeaders"])) return status, headers, b""
from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic import TemplateView import home.views urlpatterns = patterns('', # Examples: # url(r'^$', 'searchblueprints.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$', 'home.views.index'), url(r'^start/', 'home.views.start', name='start'), url(r'^instruc/', 'home.views.instruc', name='instruc'), url(r'^howitworks/', 'home.views.howitworks', name='howitworks'), url(r'^compare/', 'home.views.compare', name='compare'), url(r'^crawler/', 'home.views.crawler', name='crawler'), url(r'^algorithms/','home.views.algorithms', name='algorithms'), url(r'^indexing/', 'home.views.indexing', name='indexing'), url(r'^search/', include('haystack.urls')), url(r'^runScript/(?P<types>.*)', 'home.views.runScript',name='crawler2'), )
from collections import OrderedDict, defaultdict from typing import Tuple, Union from orderedset import OrderedSet from plenum.common.constants import PROPAGATE, THREE_PC_PREFIX from plenum.common.messages.node_messages import Propagate from plenum.common.request import Request, ReqKey from plenum.common.types import f from plenum.server.quorums import Quorum from stp_core.common.log import getlogger logger = getlogger() class ReqState: """ Object to store the state of the request. """ def __init__(self, request: Request): self.request = request self.forwarded = False # forwardedTo helps in finding to how many replicas has this request # been forwarded to, helps in garbage collection self.forwardedTo = 0 self.propagates = {} self.finalised = None self.executed = False def req_with_acceptable_quorum(self, quorum: Quorum): digests = defaultdict(set) # this is workaround because we are getting a propagate from # somebody with non-str (byte) name for sender, req in filter(lambda x: isinstance( x[0], str), self.propagates.items()): digests[req.digest].add(sender) if quorum.is_reached(len(digests[req.digest])): return req def set_finalised(self, req): # TODO: make it much explicitly and simpler # !side affect! if `req` is an instance of a child of `Request` class # here we construct the parent from child it is rather implicit that # `finalised` contains not the same type than `propagates` has self.finalised = Request.fromState(req.__getstate__()) class Requests(OrderedDict): """ Storing client request object corresponding to each client and its request id. Key of the dictionary is a Tuple2 containing identifier, requestId. Used when Node gets an ordered request by a replica and needs to execute the request. Once the ordered request is executed by the node and returned to the transaction store, the key for that request is popped out """ def add(self, req: Request): """ Add the specified request to this request store. """ key = req.key if key not in self: self[key] = ReqState(req) return self[key] def forwarded(self, req: Request) -> bool: """ Returns whether the request has been forwarded or not """ return self[req.key].forwarded def mark_as_forwarded(self, req: Request, to: int): """ Works together with 'mark_as_executed' and 'free' methods. It marks request as forwarded to 'to' replicas. To let request be removed, it should be marked as executed and each of 'to' replicas should call 'free'. """ self[req.key].forwarded = True self[req.key].forwardedTo = to def add_propagate(self, req: Request, sender: str): """ Add the specified request to the list of received PROPAGATEs. :param req: the REQUEST to add :param sender: the name of the node sending the msg """ data = self.add(req) data.propagates[sender] = req def votes(self, req) -> int: """ Get the number of propagates for a given reqId and identifier. """ try: votes = len(self[req.key].propagates) except KeyError: votes = 0 return votes def req_with_acceptable_quorum(self, req: Request, quorum: Quorum): state = self[req.key] return state.req_with_acceptable_quorum(quorum) def set_finalised(self, req: Request): state = self[req.key] state.set_finalised(req) def mark_as_executed(self, req: Request): """ Works together with 'mark_as_forwarded' and 'free' methods. It makes request to be removed if all replicas request was forwarded to freed it. """ state = self[req.key] state.executed = True self._clean(state) def free(self, request_key): """ Works together with 'mark_as_forwarded' and 'mark_as_executed' methods. It makes request to be removed if all replicas request was forwarded to freed it and if request executor marked it as executed. """ state = self.get(request_key) if not state: return state.forwardedTo -= 1 self._clean(state) def _clean(self, state): if state.executed and state.forwardedTo <= 0: self.pop(state.request.key, None) def has_propagated(self, req: Request, sender: str) -> bool: """ Check whether the request specified has already been propagated. """ return req.key in self and sender in self[req.key].propagates def is_finalised(self, reqKey: str) -> bool: return reqKey in self and self[reqKey].finalised def digest(self, reqKey: str) -> str: if reqKey in self and self[reqKey].finalised: return self[reqKey].finalised.digest class Propagator: MAX_REQUESTED_KEYS_TO_KEEP = 1000 def __init__(self): self.requests = Requests() self.requested_propagates_for = OrderedSet() # noinspection PyUnresolvedReferences def propagate(self, request: Request, clientName): """ Broadcast a PROPAGATE to all other nodes :param request: the REQUEST to propagate """ if self.requests.has_propagated(request, self.name): logger.trace("{} already propagated {}".format(self, request)) else: self.requests.add_propagate(request, self.name) propagate = self.createPropagate(request, clientName) logger.info( "{} propagating request {} from client {}". format(self, request.key, clientName), extra={"cli": True, "tags": ["node-propagate"]} ) self.send(propagate) @staticmethod def createPropagate( request: Union[Request, dict], client_name) -> Propagate: """ Create a new PROPAGATE for the given REQUEST. :param request: the client REQUEST :return: a new PROPAGATE msg """ if not isinstance(request, (Request, dict)): logger.error("{}Request not formatted properly to create propagate" .format(THREE_PC_PREFIX)) return logger.trace("Creating PROPAGATE for REQUEST {}".format(request)) request = request.as_dict if isinstance(request, Request) else \ request if isinstance(client_name, bytes): client_name = client_name.decode() return Propagate(request, client_name) # noinspection PyUnresolvedReferences def canForward(self, request: Request): """ Determine whether to forward client REQUESTs to replicas, based on the following logic: - If exactly f+1 PROPAGATE requests are received, then forward. - If less than f+1 of requests then probably there's no consensus on the REQUEST, don't forward. - If more than f+1 then already forwarded to replicas, don't forward Even if the node hasn't received the client REQUEST itself, if it has received enough number of PROPAGATE messages for the same, the REQUEST can be forwarded. :param request: the client REQUEST """ if self.requests.forwarded(request): return 'already forwarded' # If not enough Propagates, don't bother comparing if not self.quorums.propagate.is_reached(self.requests.votes(request)): return 'not finalised' req = self.requests.req_with_acceptable_quorum(request, self.quorums.propagate) if req: self.requests.set_finalised(req) return None else: return 'not finalised' # noinspection PyUnresolvedReferences def forward(self, request: Request): """ Forward the specified client REQUEST to the other replicas on this node :param request: the REQUEST to propagate """ key = request.key num_replicas = self.replicas.num_replicas logger.debug('{} forwarding request {} to {} replicas' .format(self, key, num_replicas)) self.replicas.pass_message(ReqKey(key)) self.monitor.requestUnOrdered(key) self.requests.mark_as_forwarded(request, num_replicas) # noinspection PyUnresolvedReferences def recordAndPropagate(self, request: Request, clientName): """ Record the request in the list of requests and propagate. :param request: :param clientName: """ self.requests.add(request) self.propagate(request, clientName) self.tryForwarding(request) def tryForwarding(self, request: Request): """ Try to forward the request if the required conditions are met. See the method `canForward` for the conditions to check before forwarding a request. """ cannot_reason_msg = self.canForward(request) if cannot_reason_msg is None: # If haven't got the client request(REQUEST) for the corresponding # propagate request(PROPAGATE) but have enough propagate requests # to move ahead self.forward(request) else: logger.trace("{} not forwarding request {} to its replicas " "since {}".format(self, request, cannot_reason_msg)) def request_propagates(self, req_keys): """ Request PROPAGATEs for the given request keys. Since replicas can request PROPAGATEs independently of each other, check if it has been requested recently :param req_keys: :return: """ i = 0 for digest in req_keys: if digest not in self.requested_propagates_for: self.request_msg(PROPAGATE, {f.DIGEST.nm: digest}) self._add_to_recently_requested(digest) i += 1 else: logger.debug('{} already requested PROPAGATE recently for {}'. format(self, digest)) return i def _add_to_recently_requested(self, key): while len( self.requested_propagates_for) > self.MAX_REQUESTED_KEYS_TO_KEEP: self.requested_propagates_for.pop(last=False) self.requested_propagates_for.add(key)
/* Copyright 2009 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #pragma once #include <OpenImageIO/export.h> #include <OpenImageIO/oiioversion.h> #include <OpenImageIO/strutil.h> OIIO_NAMESPACE_BEGIN /// ErrorHandler is a simple class that accepts error messages /// (classified as errors, severe errors, warnings, info, messages, or /// debug output) and handles them somehow. By default it just prints /// the messages to stdout and/or stderr (and supresses some based on a /// "verbosity" level). /// /// The basic idea is that your library code has no idea whether some /// application that will use it someday will want errors or other /// output to be sent to the console, go to a log file, be intercepted /// by the calling application, or something else. So you punt, by /// having your library take a pointer to an ErrorHandler, passed in /// from the calling app (and possibly subclassed to have arbitrarily /// different behavior from the default console output) and make all /// error-like output via the ErrorHandler*. /// class OIIO_API ErrorHandler { public: /// Error categories. We use broad categories in the high order bits. /// A library may just use these categories, or may create individual /// error codes as long as they have the right high bits to designate /// their category (file not found = ERROR + 1, etc.). enum ErrCode { EH_NO_ERROR = 0, // never sent to handler EH_MESSAGE = 0 << 16, EH_INFO = 1 << 16, EH_WARNING = 2 << 16, EH_ERROR = 3 << 16, EH_SEVERE = 4 << 16, EH_DEBUG = 5 << 16 }; /// VerbosityLevel controls how much detail the calling app wants. /// enum VerbosityLevel { QUIET = 0, ///< Show MESSAGE, SEVERE, ERROR only NORMAL = 1, ///< Show MESSAGE, SEVERE, ERROR, WARNING VERBOSE = 2 ///< Like NORMAL, but also show INFO }; ErrorHandler() : m_verbosity(NORMAL) { } virtual ~ErrorHandler() {} /// Set desired verbosity level. void verbosity(int v) { m_verbosity = v; } /// Return the current verbosity level. int verbosity() const { return m_verbosity; } /// The main (or "full detail") method -- takes a code (with high /// bits being an ErrCode) and writes the message, with a prefix /// indicating the error category (no prefix for "MESSAGE") and /// error string. virtual void operator()(int errcode, const std::string& msg); // Base cases -- take a single string void info(const std::string& msg) { (*this)(EH_INFO, msg); } void warning(const std::string& msg) { (*this)(EH_WARNING, msg); } void error(const std::string& msg) { (*this)(EH_ERROR, msg); } void severe(const std::string& msg) { (*this)(EH_SEVERE, msg); } void message(const std::string& msg) { (*this)(EH_MESSAGE, msg); } #ifndef NDEBUG void debug(const std::string& msg) { (*this)(EH_DEBUG, msg); } #else void debug(const std::string&) {} #endif // // Formatted output with the same notation as Strutil::format. /// Use with caution! Some day this will change to be fmt-like rather /// than printf-like. // template<typename... Args> void info(const char* format, const Args&... args) { if (verbosity() >= VERBOSE) info(Strutil::format(format, args...)); } /// Warning message with printf-like formatted error message. /// Will not print unless verbosity >= NORMAL (i.e. will suppress /// for QUIET). template<typename... Args> void warning(const char* format, const Args&... args) { if (verbosity() >= NORMAL) warning(Strutil::format(format, args...)); } /// Error message with printf-like formatted error message. /// Will print regardless of verbosity. template<typename... Args> void error(const char* format, const Args&... args) { error(Strutil::format(format, args...)); } /// Severe error message with printf-like formatted error message. /// Will print regardless of verbosity. template<typename... Args> void severe(const char* format, const Args&... args) { severe(Strutil::format(format, args...)); } /// Prefix-less message with printf-like formatted error message. /// Will not print if verbosity is QUIET. Also note that unlike /// the other routines, message() will NOT append a newline. template<typename... Args> void message(const char* format, const Args&... args) { if (verbosity() > QUIET) message(Strutil::format(format, args...)); } /// Debugging message with printf-like formatted error message. /// This will not produce any output if not in DEBUG mode, or /// if verbosity is QUIET. template<typename... Args> void debug(const char* format, const Args&... args) { #ifndef NDEBUG debug(Strutil::format(format, args...)); #endif } // // Formatted output with printf notation. Use these if you specifically // want printf-notation, even after format() changes to python notation // for OIIO 2.1. // template<typename... Args> void infof(const char* format, const Args&... args) { if (verbosity() >= VERBOSE) info(Strutil::sprintf(format, args...)); } template<typename... Args> void warningf(const char* format, const Args&... args) { if (verbosity() >= NORMAL) warning(Strutil::sprintf(format, args...)); } template<typename... Args> void errorf(const char* format, const Args&... args) { error(Strutil::sprintf(format, args...)); } template<typename... Args> void severef(const char* format, const Args&... args) { severe(Strutil::sprintf(format, args...)); } template<typename... Args> void messagef(const char* format, const Args&... args) { if (verbosity() > QUIET) message(Strutil::sprintf(format, args...)); } template<typename... Args> void debugf(const char* format, const Args&... args) { #ifndef NDEBUG debug(Strutil::sprintf(format, args...)); #endif } /// One built-in handler that can always be counted on to be present /// and just echoes the error messages to the console (stdout or /// stderr, depending on the error category). static ErrorHandler& default_handler(); private: int m_verbosity; }; OIIO_NAMESPACE_END
"""Kernel Tuner interface module This module contains the main functions that Kernel Tuner offers to its users. Author ------ Ben van Werkhoven <b.vanwerkhoven@esciencenter.nl> Copyright and License --------------------- * Copyright 2016 Netherlands eScience Center Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function import json import os.path from collections import OrderedDict import importlib from datetime import datetime import logging import sys import numpy import kernel_tuner.util as util import kernel_tuner.core as core from kernel_tuner.runners.sequential import SequentialRunner from kernel_tuner.runners.simulation import SimulationRunner try: import torch except ImportError: torch = util.TorchPlaceHolder() from kernel_tuner.strategies import brute_force, random_sample, diff_evo, minimize, basinhopping, genetic_algorithm, mls, pso, simulated_annealing, firefly_algorithm, bayes_opt strategy_map = { "brute_force": brute_force, "random_sample": random_sample, "minimize": minimize, "basinhopping": basinhopping, "diff_evo": diff_evo, "genetic_algorithm": genetic_algorithm, "mls": mls, "pso": pso, "simulated_annealing": simulated_annealing, "firefly_algorithm": firefly_algorithm, "bayes_opt": bayes_opt, } class Options(OrderedDict): """read-only class for passing options around""" def __getattr__(self, name): if not name.startswith('_'): return self[name] return super(Options, self).__getattr__(name) def __deepcopy__(self, _): return self _kernel_options = Options([("kernel_name", ("""The name of the kernel in the code.""", "string")), ("kernel_source", ("""The CUDA, OpenCL, or C kernel code. It is allowed for the code to be passed as a string, a filename, a function that returns a string of code, or a list when the code needs auxilliary files. To support combined host and device code tuning, a list of filenames can be passed. The first file in the list should be the file that contains the host code. The host code is assumed to include or read in any of the files in the list beyond the first. The tunable parameters can be used within all files. Another alternative is to pass a code generating function. The purpose of this is to support the use of code generating functions that generate the kernel code based on the specific parameters. This function should take one positional argument, which will be used to pass a dict containing the parameters. The function should return a string with the source code for the kernel.""", "string or list and/or callable")), ("lang", ("""Specifies the language used for GPU kernels. The kernel_tuner automatically detects the language, but if it fails, you may specify the language using this argument, currently supported: "CUDA", "Cupy", "OpenCL", or "C".""", "string")), ("problem_size", ("""The size of the domain from which the grid dimensions of the kernel are computed. This can be specified using an int, string, function, or 1,2,3-dimensional tuple. In general, do not divide the problem_size yourself by the thread block sizes. Kernel Tuner does this for you based on tunable parameters, called "block_size_x", "block_size_y", and "block_size_z". If more or different parameters divide the grid dimensions use grid_div_x/y/z options to specify this. In most use-cases the problem_size is specified using a single integer or a tuple of integers, but Kernel Tuner supports more advanced use cases where the problem_size itself depends on the tunable parameters in some way. You are allowed to use a function or string to specify the problem_size. A function should accept a dictionary with the tunable parameters for this kernel configuration and directly return a tuple that specifies the problem size in all dimensions. When passing a string, you are allowed to write Python arithmetic and use the names of tunable parameters as variables in these expressions. Kernel Tuner will replace instances of the tunable parameters with their current value when computing the grid dimensions. This option exists for convenience, but do note that using a lambda function is probably safer. The string notation should only return the problem size for one dimension, but can be used inside a tuple, possibly in combination with integers or more strings in different dimensions. See the reduction CUDA example for an example use of this feature.""", "callable, string, int, or tuple(int or string, ..)")), ("arguments", ("""A list of kernel arguments, use numpy arrays for arrays, use numpy.int32 or numpy.float32 for scalars.""", "list")), ("grid_div_x", ("""A list of names of the parameters whose values divide the grid dimensions in the x-direction. The product of all grid divisor expressions is computed before dividing the problem_size in that dimension. Also note that the divison is treated as a float divison and resulting grid dimensions will be rounded up to the nearest integer number. Arithmetic expressions can be used if necessary inside the string containing a parameter name. For example, in some cases you may want to divide the problem size in the x-dimension with the number of warps rather than the number of threads in a block, in such cases one could for example use ["block_size_x/32"]. Another option is to pass a function to grid_div_x that accepts a dictionary with the tunable parameters and returns the grid divisor in this dimension, for example: grid_div_x=lambda p:p["block_size_x"]/32. If not supplied, ["block_size_x"] will be used by default, if you do not want any grid x-dimension divisors pass an empty list.""", "callable or list")), ("grid_div_y", ("""A list of names of the parameters whose values divide the grid dimensions in the y-direction, ["block_size_y"] by default. If you do not want to divide the problem_size, you should pass an empty list. See grid_div_x for more details.""", "list")), ("grid_div_z", ("""A list of names of the parameters whose values divide the grid dimensions in the z-direction, ["block_size_z"] by default. If you do not want to divide the problem_size, you should pass an empty list. See grid_div_x for more details.""", "list")), ("smem_args", ("""CUDA-specific feature for specifying shared memory options to the kernel. At the moment only 'size' is supported, but setting the shared memory configuration on Kepler GPUs for example could be added in the future. Size should denote the number of bytes for to use when dynamically allocating shared memory.""", "dict(string: numpy object)")), ("cmem_args", ("""CUDA-specific feature for specifying constant memory arguments to the kernel. In OpenCL these are handled as normal kernel arguments, but in CUDA you can copy to a symbol. The way you specify constant memory arguments is by passing a dictionary with strings containing the constant memory symbol name together with numpy objects in the same way as normal kernel arguments.""", "dict(string: numpy object)")), ("texmem_args", ("""CUDA-specific feature for specifying texture memory arguments to the kernel. You specify texture memory arguments by passing a dictionary with strings containing the texture reference name together with the texture contents. These contents can be either simply a numpy object, or a dictionary containing the numpy object under the key 'array' plus the configuration options 'filter_mode' ('point' or 'linear), 'address_mode' (a list of 'border', 'clamp', 'mirror', 'wrap' per axis), 'normalized_coordinates' (True/False).""", "dict(string: numpy object or dict)")), ("block_size_names", ("""A list of strings that replace the defaults for the names that denote the thread block dimensions. If not passed, the behavior defaults to ``["block_size_x", "block_size_y", "block_size_z"]``""", "list(string)"))]) _tuning_options = Options([("tune_params", ("""A dictionary containing the parameter names as keys, and lists of possible parameter settings as values. Kernel Tuner will try to compile and benchmark all possible combinations of all possible values for all tuning parameters. This typically results in a rather large search space of all possible kernel configurations. For each kernel configuration, each tuning parameter is replaced at compile-time with its current value. Currently, Kernel Tuner uses the convention that the following list of tuning parameters are used as thread block dimensions: * "block_size_x" thread block (work group) x-dimension * "block_size_y" thread block (work group) y-dimension * "block_size_z" thread block (work group) z-dimension Options for changing these defaults may be added later. If you don't want the thread block dimensions to be compiled in, you may use the built-in variables blockDim.xyz in CUDA or the built-in function get_local_size() in OpenCL instead.""", "dict( string : [...]")), ("restrictions", ("""An option to limit the search space with restrictions. The restrictions can be specified using a function or a list of strings. The function should take one argument, namely a dictionary with the tunable parameters of the kernel configuration, if the function returns True the configuration is considered to be part of the search space, or False otherwise. The other way to specify restrictions is using a list of strings containing boolean expression that must be satisfied by the kernel configuration. These expressions must all be true for the configuration to be part of the search space. For example: restrictions=["block_size_x==block_size_y*tile_size_y"] limits the search to configurations where the block_size_x equals the product of block_size_y and tile_size_y. The default is None.""", "callable or list(strings)")), ("answer", ("""A list of arguments, similar to what you pass to arguments, that contains the expected output of the kernel after it has executed and contains None for each argument that is input-only. The expected output of the kernel will then be used to verify the correctness of each kernel in the parameter space before it will be benchmarked.""", "list")), ("atol", ("""The maximum allowed absolute difference between two elements in the output and the reference answer, as passed to numpy.allclose(). Ignored if you have not passed a reference answer. Default value is 1e-6, that is 0.000001.""", "float")), ("verify", ("""Python function used for output verification. By default, numpy.allclose is used for output verification, if this does not suit your application, you can pass a different function here. The function is expected to have two positional arguments. The first is the reference result, the second is the output computed by the kernel being verified. The types of these arguments depends on the type of the output arguments you are verifying. The function may also have an optional argument named atol, to which the value will be passed that was specified using the atol option to tune_kernel. The function should return True when the output passes the test, and False when the output fails the test.""", "func(ref, ans, atol=None)")), ("strategy", ("""Specify the strategy to use for searching through the parameter space, choose from: * "brute_force" (default) iterates through the entire search space. * "random_sample" takes a random sample of the search space. * "minimize" uses a local minimization algorithm. * "basinhopping" combines global stepping with a local minimization at each step. * "diff_evo" differential evolution. * "genetic_algorithm" a genetic algorithm optimization strategy. * "mls" multi-start local search * "pso" particle swarm optimization * "firefly_algorithm" firefly algorithm strategy. * "simulated_annealing" simulated annealing strategy. * "bayes_opt" Bayesian Optimization strategy. Strategy-specific parameters and options are explained under strategy_options. """, "")), ("strategy_options", ("""A dict with options specific to the selected tuning strategy. * **"random_sample"** * "fraction", float, fraction of the search space to cover in [0,1], default 0.1. * **"minimize"** * "method", string, any of "Nelder-Mead", "Powell", "CG", "BFGS", "L-BFGS-B", "TNC", "COBYLA", or "SLSQP", default "L-BFGS-B". * **"basinhopping"** * "method", string, any of "Nelder-Mead", "Powell", "CG", "BFGS", "L-BFGS-B", "TNC", "COBYLA", or "SLSQP", default "L-BFGS-B". * "T", float, Temperature parameter for the accept or reject criterion, default 1.0. * **"diff_evo"** * "method", string, any of "best1bin", "best1exp", "rand1exp", "randtobest1exp", "best2exp", "rand2exp", "randtobest1bin", "best2bin", "rand2bin", "rand1bin", default "best1bin". * **"genetic_algorithm"** * "popsize", integer, population size, default 20. * "maxiter", integer, number of generations, default 50. * "method", string, crossover method any of "single_point", "two_point", "uniform", "disruptive_uniform", default "uniform". * "mutation_chance", integer, specifies the 1 in mutation_chance of a mutation, default 10. * "max_fevals", integer, specifies the maximum allowed number of unique function evaluations, default 100. * **"mls"** * "max_fevals", integer, specifies the maximum allowed number of unique function evaluations, default 100. * **"pso"** * "popsize", integer, population size, default 20. * "maxiter", integer, number of generations, default 100. * "w", float, inertia constant, default 0.5. * "c1", float, cognitive constant, default 2.0. * "c2", float, social constant, default 1.0. * **"firefly_algorithm"** * "popsize", integer, population size, default 20. * "maxiter", integer, number of generations, default 100. * "B0", float, B0 parameter, default 1.0. * "gamma", float, gamma parameter, default 1.0. * "alpha", float, alpha parameter, default 0.2. * **"simulated_annealing"** * "T", float, starting temperature parameter, default 1.0. * "T_min", float, end temperature parameter, default 0.001. * "alpha", float, alpha parameter, default 0.9. * "maxiter", integer, number of iterations of possibly accepting neighboring points, default 20. * **"bayes_opt"** * "method": any of "poi", "ei", "lcb", "lcb-srinivas", "multi", "multi-advanced", "multi-fast", default "multi-advanced". * "covariancekernel", any of "constantrbf", "rbf", "matern32", "matern52", default "matern32". * "covariancelengthscale", float, default 1.5. * "samplingmethod" any of "random", "lhs", default "lhs". """, "dict")), ("iterations", ("""The number of times a kernel should be executed and its execution time measured when benchmarking a kernel, 7 by default.""", "int")), ("verbose", ("""Sets whether or not to report about configurations that were skipped during the search. This could be due to several reasons: * kernel configuration fails one or more restrictions * too many threads per thread block * too much shared memory used by the kernel * too many resources requested for launch verbose is False by default.""", "bool")), ("cache", ("""filename for caching/logging benchmarked instances filename uses suffix ".json" if the file exists it is read and tuning continues from this file """, "string")), ("metrics", ("specifies user-defined metrics", "OrderedDict")), ("simulation_mode", ("Simulate an auto-tuning search from an existing cachefile", "bool")), ("observers", ("""A list of BenchmarkObservers""", "list"))]) _device_options = Options([("device", ("""CUDA/OpenCL device to use, in case you have multiple CUDA-capable GPUs or OpenCL devices you may use this to select one, 0 by default. Ignored if you are tuning host code by passing lang="C".""", "int")), ("platform", ("""OpenCL platform to use, in case you have multiple OpenCL platforms you may use this to select one, 0 by default. Ignored if not using OpenCL. """, "int")), ("quiet", ("""Control whether or not to print to the console which device is being used, False by default""", "boolean")), ("compiler", ("""A string containing your preferred compiler, only effective with lang="C". """, "string")), ("compiler_options", ("""A list of strings that specify compiler options.""", "list(string)"))]) def _get_docstring(opts): docstr = "" for k, v in opts.items(): docstr += " :param " + k + ": " + v[0] + "\n" docstr += " :type " + k + ": " + v[1] + "\n\n" return docstr _tune_kernel_docstring = """ Tune a CUDA kernel given a set of tunable parameters %s :returns: A list of dictionaries of all executed kernel configurations and their execution times. And a dictionary with information about the environment in which the tuning took place. This records device name, properties, version info, and so on. :rtype: list(dict()), dict() """ % _get_docstring(_kernel_options) + _get_docstring(_tuning_options) + _get_docstring(_device_options) #""" def tune_kernel(kernel_name, kernel_source, problem_size, arguments, tune_params, grid_div_x=None, grid_div_y=None, grid_div_z=None, restrictions=None, answer=None, atol=1e-6, verify=None, verbose=False, lang=None, device=0, platform=0, smem_args=None, cmem_args=None, texmem_args=None, compiler=None, compiler_options=None, log=None, iterations=7, block_size_names=None, quiet=False, strategy=None, strategy_options=None, cache=None, metrics=None, simulation_mode=False, observers=None): if log: logging.basicConfig(filename=kernel_name + datetime.now().strftime('%Y%m%d-%H:%M:%S') + '.log', level=log) kernelsource = core.KernelSource(kernel_name, kernel_source, lang) _check_user_input(kernel_name, kernelsource, arguments, block_size_names) # check for forbidden names in tune parameters util.check_tune_params_list(tune_params) # check whether block_size_names are used as expected util.check_block_size_params_names_list(block_size_names, tune_params) if iterations < 1: raise ValueError("Iterations should be at least one!") #sort all the options into separate dicts opts = locals() kernel_options = Options([(k, opts[k]) for k in _kernel_options.keys()]) tuning_options = Options([(k, opts[k]) for k in _tuning_options.keys()]) device_options = Options([(k, opts[k]) for k in _device_options.keys()]) tuning_options["snap"] = True logging.debug('tune_kernel called') logging.debug('kernel_options: %s', util.get_config_string(kernel_options)) logging.debug('tuning_options: %s', util.get_config_string(tuning_options)) logging.debug('device_options: %s', util.get_config_string(device_options)) if strategy: if strategy in strategy_map: strategy = strategy_map[strategy] else: raise ValueError("Strategy %s not recognized" % strategy) #make strategy_options into an Options object if tuning_options.strategy_options: if not isinstance(strategy_options, Options): tuning_options.strategy_options = Options(strategy_options) #select strategy based on user options if "fraction" in tuning_options.strategy_options and not tuning_options.strategy == 'random_sample': raise ValueError('It is not possible to use fraction in combination with strategies other than "random_sample". ' \ 'Please set strategy="random_sample", when using "fraction" in strategy_options') #check if method is supported by the selected strategy if "method" in tuning_options.strategy_options: method = tuning_options.strategy_options.method if not method in strategy.supported_methods: raise ValueError('Method %s is not supported for strategy %s' % (method, tuning_options.strategy)) #if no strategy_options dict has been passed, create empty dictionary else: tuning_options.strategy_options = Options({}) #if no strategy selected else: strategy = brute_force # select the runner for this job based on input selected_runner = SimulationRunner if simulation_mode is True else SequentialRunner with selected_runner(kernelsource, kernel_options, device_options, iterations, observers) as runner: #the user-specified function may or may not have an optional atol argument; #we normalize it so that it always accepts atol. tuning_options.verify = util.normalize_verify_function(tuning_options.verify) #process cache if cache: if cache[-5:] != ".json": cache += ".json" util.process_cache(cache, kernel_options, tuning_options, runner) else: tuning_options.cache = {} tuning_options.cachefile = None #call the strategy to execute the tuning process results, env = strategy.tune(runner, kernel_options, device_options, tuning_options) #finished iterating over search space if not device_options.quiet: if results: #checks if results is not empty best_config = min(results, key=lambda x: x['time']) units = getattr(runner, "units", None) print("best performing configuration:") util.print_config_output(tune_params, best_config, device_options.quiet, metrics, units) else: print("no results to report") if cache: util.close_cache(cache) return results, env tune_kernel.__doc__ = _tune_kernel_docstring _run_kernel_docstring = """Compile and run a single kernel Compiles and runs a single kernel once, given a specific instance of the kernels tuning parameters. However, instead of measuring execution time run_kernel returns the output of the kernel. The output is returned as a list of numpy arrays that contains the state of all the kernel arguments after execution on the GPU. To summarize what this function will do for you in one call: * Compile the kernel according to the set of parameters passed * Allocate GPU memory to hold all kernel arguments * Move the all data to the GPU * Execute the kernel on the GPU * Copy all data from the GPU back to the host and return it as a list of Numpy arrays This function was added to Kernel Tuner mostly to allow easy testing for kernel correctness. On purpose, the interface is a lot like `tune_kernel()`. %s :param params: A dictionary containing the tuning parameter names as keys and a single value per tuning parameter as values. :type params: dict( string: int ) :returns: A list of numpy arrays, similar to the arguments passed to this function, containing the output after kernel execution. :rtype: list """ % _get_docstring(_kernel_options) + _get_docstring(_device_options) def run_kernel(kernel_name, kernel_source, problem_size, arguments, params, grid_div_x=None, grid_div_y=None, grid_div_z=None, lang=None, device=0, platform=0, smem_args=None, cmem_args=None, texmem_args=None, compiler=None, compiler_options=None, block_size_names=None, quiet=False, log=None): if log: logging.basicConfig(filename=kernel_name + datetime.now().strftime('%Y%m%d-%H:%M:%S') + '.log', level=log) kernelsource = core.KernelSource(kernel_name, kernel_source, lang) _check_user_input(kernel_name, kernelsource, arguments, block_size_names) #sort options into separate dicts opts = locals() kernel_options = Options([(k, opts[k]) for k in _kernel_options.keys()]) device_options = Options([(k, opts[k]) for k in _device_options.keys()]) #detect language and create the right device function interface with core.DeviceInterface(kernelsource, iterations=1, **device_options) as dev: #move data to the GPU gpu_args = dev.ready_argument_list(arguments) instance = None try: #create kernel instance instance = dev.create_kernel_instance(kernelsource, kernel_options, params, False) if instance is None: raise Exception("cannot create kernel instance, too many threads per block") # see if the kernel arguments have correct type util.check_argument_list(instance.name, instance.kernel_string, arguments) #compile the kernel func = dev.compile_kernel(instance, False) if func is None: raise Exception("cannot compile kernel, too much shared memory used") #add shared memory arguments to compiled module if smem_args is not None: dev.copy_shared_memory_args(util.get_smem_args(smem_args, params)) #add constant memory arguments to compiled module if cmem_args is not None: dev.copy_constant_memory_args(cmem_args) #add texture memory arguments to compiled module if texmem_args is not None: dev.copy_texture_memory_args(texmem_args) finally: #delete temp files if instance is not None: instance.delete_temp_files() #run the kernel if not dev.run_kernel(func, gpu_args, instance): raise Exception("runtime error occured, too many resources requested") #copy data in GPU memory back to the host results = [] for i, arg in enumerate(arguments): if numpy.isscalar(arg): results.append(arg) elif isinstance(arg, torch.Tensor): results.append(arg.cpu()) else: results.append(numpy.zeros_like(arg)) dev.memcpy_dtoh(results[-1], gpu_args[i]) return results run_kernel.__doc__ = _run_kernel_docstring def _check_user_input(kernel_name, kernelsource, arguments, block_size_names): # see if the kernel arguments have correct type kernelsource.check_argument_lists(kernel_name, arguments) # check for types and length of block_size_names util.check_block_size_names(block_size_names)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Ingredient, IngredientTag from products.models import Price class PriceInlineAdmin(admin.TabularInline): model = Price readonly_fields = ('per_kg', 'created_at','updated_at') class IngredientAdmin(admin.ModelAdmin): view_on_site = True save_as = True # Allow cloning items by replacing "save and add another" list_display = ('name', 'updated_at', 'price_count') readonly_fields = ('created_at','updated_at','lowest_price','price_count') search_fields = ['name', 'description'] inlines = [PriceInlineAdmin] fieldsets = ( (None, { 'fields': ( ('name', 'description'), ('serving','owner') ), }), ('Tags', { 'classes': ('collapse',), 'fields': ( ('tags',), ) }), ('Nutrients (per KG)', { 'classes': ('collapse',), 'fields': ( 'kilojoules', 'protein', 'fat', 'saturatedfat', 'carbohydrate', 'sugar', 'fibre', 'sodium', ) }), ('Text Fields (intro, notes)', { 'classes': ('collapse',), 'fields': ( ('introduction'), ('notes'), ), }), ('Internal Properties', { 'classes': ('collapse',), 'fields': ( ('created_at','updated_at'), ('slug',), ('lowest_price',), ) }), ) admin.site.register(Ingredient,IngredientAdmin) admin.site.register(IngredientTag)
"Isoclines map for the predicted trajectory" from __future__ import division import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt import scipy.interpolate import time import scipy.stats as stats import numpy.random as random plt.close('all') # plot with various axes scales plt.figure(1) #with open('/home/vibek/Human_intention/src/Train_model/chair_predict.csv','r') as in_file, open('/home/vibek/Human_intention/src/Train_model/chair_predict_w.csv','w') as out_file: # seen = set() # for line in in_file: # if line in seen: continue # seen.add(line) # out_file.write(line) matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' data = np.genfromtxt('/home/vibek/Human_intention/src/Train_model/door_left_w.csv', delimiter=',') X = data[:,0] Y = data[:,1] Z = data[:,2] xi = np.linspace(X.min(), X.max(), 8, endpoint=True) yi = np.linspace(Y.min(), Y.max(), 8, endpoint=False) xi, yi = np.meshgrid(xi, yi) # Interpolate rbf = scipy.interpolate.Rbf(X, Y, Z, function='thin_plate') zi = rbf(xi, yi) plt.subplot(221) plt.imshow(zi, vmin=Z.min(), vmax=Z.max(), origin='upper', extent=[X.min(), X.max(), Y.min(), Y.max()], cmap=plt.cm.hot, aspect='auto') cp = plt.contour(xi, yi, zi) plt.clabel(cp, inline=True, fontsize=10) plt.scatter(X, Y, c=Z) plt.colorbar() plt.title("Contour Plot (probability)", size=15) plt.xlabel("X (m)", size=12) plt.ylabel("Y (m)", size=12) "Q-Q plot X" X.sort() norm=random.normal(0,2,len(X)) norm.sort() #plt.figure(figsize=(8,6),facecolor='1.0') plt.subplot(222) plt.plot(norm,X,"o") z = np.polyfit(norm, X, 1) p = np.poly1d(z) plt.plot(norm,p(norm),"k--", linewidth=2) plt.title("Q-Q plot (X-value)", size=15) plt.xlabel("Expected quantiles", size=12) plt.ylabel("Expreimental quantiles", size=12) plt.tick_params(labelsize=10) "Q-Q plot Y" Y.sort() norm=random.normal(0,2,len(Y)) norm.sort() #plt.figure(figsize=(8,6),facecolor='1.0') plt.subplot(223) plt.plot(norm,Y,"o") z = np.polyfit(norm, Y, 1) p = np.poly1d(z) plt.plot(norm,p(norm),"k--", linewidth=2) plt.title("Q-Q plot (Y-value)", size=15) plt.xlabel("Expected quantiles", size=12) plt.ylabel("Expreimental quantiles", size=12) plt.tick_params(labelsize=10) "Q-Q plot Z" Z.sort() norm=random.normal(0,2,len(Z)) norm.sort() #plt.figure(figsize=(8,6),facecolor='1.0') plt.subplot(224) plt.plot(norm,Z,"o") z = np.polyfit(norm, Z, 1) p = np.poly1d(z) plt.plot(norm,p(norm),"k--", linewidth=2) plt.title("Q-Q plot (Z-value)", size=15) plt.xlabel("Expected quantiles", size=12) plt.ylabel("Expreimental quantiles", size=12) plt.tick_params(labelsize=10) #k = stats.shapiro(X) #plt.plot(k) #if (k<0.05): # print "Variable not normal" #else: # print "Variable is normal" plt.show()
""" QR code generator """ import io import logging from base64 import b64encode import qrcode # I can decode the addresses produced correctly but the data load does not # appear to be identical to blockchain.info QR, not sure what's wrong def bitcoinqr(address, pixel_size=4, border_pixsels=0): """ QRCode """ return qrcode_datauri('bitcoin:%s' %(address), pixel_size) def qrcode_datauri(data, pixel_size=6, border_pixels=1, error_correction="H"): """ QRCode """ logging.debug(data) qrcode_object = qrcode.QRCode( error_correction=getattr( qrcode.constants, "ERROR_CORRECT_%s" % error_correction, "H" ), box_size=max(1, min(100, pixel_size)), border=max(1, min(100, border_pixels)), ) qrcode_object.add_data(data) qrcode_object.make(fit=True) qrcode_image = qrcode_object.make_image() byte_stream = io.BytesIO() qrcode_image.save(byte_stream) datauri = "data:image/png;base64,%s" % (b64encode(byte_stream.getvalue()).decode('utf-8')) byte_stream.close() return datauri
const fs = require('fs') const path = require('path') const inquirer = require('inquirer') const dedent = require('dedent') const root = process.cwd() const getAuthors = () => { const authorPath = path.join(root, 'data', 'authors') const authorList = fs.readdirSync(authorPath).map((filename) => path.parse(filename).name) return authorList } const getLayouts = () => { const layoutPath = path.join(root, 'layouts') const layoutList = fs .readdirSync(layoutPath) .map((filename) => path.parse(filename).name) .filter((file) => file.toLowerCase().includes('post')) return layoutList } const genFrontMatter = (answers) => { let d = new Date() const date = [ d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('0' + d.getDate()).slice(-2), ].join('-') const tagArray = answers.tags.split(',') tagArray.forEach((tag, index) => (tagArray[index] = tag.trim())) const tags = "'" + tagArray.join("','") + "'" const authorArray = answers.authors.length > 0 ? "'" + answers.authors.join("','") + "'" : '' let frontMatter = dedent`--- title: ${answers.title ? answers.title : 'Untitled'} date: '${date}' tags: [${answers.tags ? tags : ''}] draft: ${answers.draft === 'yes' ? true : false} summary: ${answers.summary ? answers.summary : ' '} images: [] layout: ${answers.layout} canonicalUrl: ${answers.canonicalUrl} ` if (answers.authors.length > 0) { frontMatter = frontMatter + '\n' + `authors: [${authorArray}]` } frontMatter = frontMatter + '\n---' return frontMatter } inquirer .prompt([ { name: 'title', message: 'Enter post title:', type: 'input', }, { name: 'extension', message: 'Choose post extension:', type: 'list', choices: ['mdx', 'md'], }, { name: 'authors', message: 'Choose authors:', type: 'checkbox', choices: getAuthors, }, { name: 'summary', message: 'Enter post summary:', type: 'input', }, { name: 'draft', message: 'Set post as draft?', type: 'list', choices: ['yes', 'no'], }, { name: 'tags', message: 'Any Tags? Separate them with , or leave empty if no tags.', type: 'input', }, { name: 'layout', message: 'Select layout', type: 'list', choices: getLayouts, }, { name: 'canonicalUrl', message: 'Enter canonical url:', type: 'input', }, ]) .then((answers) => { // Remove special characters and replace space with - const fileName = answers.title .toLowerCase() .replace(/[^a-zA-Z0-9 ]/g, '') .replace(/ /g, '-') .replace(/-+/g, '-') const frontMatter = genFrontMatter(answers) if (!fs.existsSync('data/post')) fs.mkdirSync('data/post', { recursive: true }) const filePath = `data/posts/${fileName ? fileName : 'untitled'}.${ answers.extension ? answers.extension : 'md' }` fs.writeFile(filePath, frontMatter, { flag: 'wx' }, (err) => { if (err) { throw err } else { console.log(`Post post generated successfully at ${filePath}`) } }) }) .catch((error) => { if (error.isTtyError) { console.log("Prompt couldn't be rendered in the current environment") } else { console.log('Something went wrong, sorry!') } })
/* * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. * * This file contains STAT definitions internal to the BCM library. */ #ifndef _BCM_INT_STAT_H #define _BCM_INT_STAT_H #include <bcm/stat.h> /* * Utility routines for statistics accumulation */ /* The REG_* macros require the following declaration in any function which * uses them: */ #define REG_MATH_DECL \ uint64 reg_val #define _BCM_SYNC_MODE_NO_SYNC 0 /* No hardware sync. */ #define _BCM_SYNC_MODE_SYNC 1 /* sync hardware and update cache. */ #define _BCM_SYNC_MODE_NO_CACHE 2 /* sync hardware and no cache update. */ #define REG_ADD(unit, port, sync_mode, reg, val) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ if (sync_mode == _BCM_SYNC_MODE_NO_CACHE) { \ SOC_IF_ERROR_RETURN(soc_counter_direct_get(unit, port, reg, \ 0, &reg_val)); \ } else if (sync_mode) { \ SOC_IF_ERROR_RETURN(soc_counter_sync_get(unit, port, reg, \ 0, &reg_val)); \ } else { \ SOC_IF_ERROR_RETURN(soc_counter_get(unit, port, reg, \ 0, &reg_val)); \ } \ COMPILER_64_ADD_64(val, reg_val); \ } #define REG_ADD_IDX(unit, port, sync_mode, reg, val, ar_idx) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ if (sync_mode) { \ SOC_IF_ERROR_RETURN(soc_counter_sync_get(unit, port, reg, \ ar_idx, &reg_val)); \ } else { \ SOC_IF_ERROR_RETURN(soc_counter_get(unit, port, reg, \ ar_idx, &reg_val)); \ } \ COMPILER_64_ADD_64(val, reg_val); \ } #define REG_SUB(unit, port, sync_mode, reg, val) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ if (sync_mode) { \ SOC_IF_ERROR_RETURN(soc_counter_sync_get(unit, port, reg, \ 0, &reg_val)); \ } else { \ SOC_IF_ERROR_RETURN(soc_counter_get(unit, port, reg, \ 0, &reg_val)); \ } \ if (COMPILER_64_GT(val, reg_val)) { \ COMPILER_64_SUB_64(val, reg_val); \ } else { \ COMPILER_64_ZERO(val); \ } \ } #define REG_SUB_IDX(unit, port, sync_mode, reg, val, ar_idx) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ if (sync_mode) { \ SOC_IF_ERROR_RETURN(soc_counter_sync_get(unit, port, reg, \ ar_idx, &reg_val)); \ } else { \ SOC_IF_ERROR_RETURN(soc_counter_get(unit, port, reg, \ ar_idx, &reg_val)); \ } \ COMPILER_64_SUB_64(val, reg_val); \ } #define REG_CLEAR(unit, port, reg, val) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ SOC_IF_ERROR_RETURN(soc_counter_clear_by_port_reg(unit, \ port, reg, \ 0, val)); \ } #define REG_CLEAR_IDX(unit, port, sync_mode, reg, val, ar_idx) \ if (SOC_REG_IS_COUNTER_TABLE(unit, reg) || \ (SOC_REG_IS_VALID(unit, reg) && SOC_REG_IS_COUNTER(unit, reg))) { \ SOC_IF_ERROR_RETURN(soc_counter_clear_by_port_reg(unit, \ port, reg, \ ar_idx, \ val)); \ } #define BCM_STAT_REG_OPER(unit, port, sync_mode, reg_op, ctr_reg, val) \ BCM_IF_ERROR_RETURN (_bcm_stat_reg_op(unit, port, sync_mode, reg_op, ctr_reg, val)) #define BCM_STAT_GENERIC_REG_OPER(unit, port, sync_mode, reg_op, ctr_reg, val) \ if (soc_feature(unit, soc_feature_cxl_mib) || \ soc_feature(unit, soc_feature_cd_mib)) { \ soc_reg_t ctr_reg_adj = ctr_reg##r; \ \ if (IS_CL_PORT(unit, port)) { \ if (SOC_REG_IS_VALID(unit, CLMIB_##ctr_reg##r)) { \ ctr_reg_adj = CLMIB_##ctr_reg##r; \ } \ } else if (IS_XL_PORT(unit, port)) { \ if (SOC_REG_IS_VALID(unit, XLMIB_##ctr_reg##r)) { \ ctr_reg_adj = XLMIB_##ctr_reg##r; \ } \ } else if (IS_CD_PORT(unit, port)) { \ if (SOC_REG_IS_COUNTER_TABLE(unit, CDMIB_##ctr_reg##f + \ SOC_COUNTER_TABLE_FIELD_START)) { \ ctr_reg_adj = CDMIB_##ctr_reg##f + SOC_COUNTER_TABLE_FIELD_START; \ } \ } \ BCM_STAT_REG_OPER(unit, port, sync_mode, reg_op, ctr_reg_adj, val); \ } else { \ BCM_STAT_REG_OPER(unit, port, sync_mode, reg_op, ctr_reg##r, val); \ } #define BCM_STAT_GENERIC_REG_VALIDATE(unit, port, ctr, valid) \ if (soc_feature(unit, soc_feature_cxl_mib) || \ soc_feature(unit, soc_feature_cd_mib)) { \ valid = FALSE; \ if (IS_CL_PORT(unit, port)) { \ if (SOC_REG_IS_VALID(unit, CLMIB_##ctr##r)) { \ valid = TRUE; \ } \ } else if (IS_XL_PORT(unit, port)) { \ if (SOC_REG_IS_VALID(unit, XLMIB_##ctr##r)) { \ valid = TRUE; \ } \ } else if (IS_CD_PORT(unit, port)) { \ if (SOC_REG_IS_COUNTER_TABLE(unit, CDMIB_##ctr##f + \ SOC_COUNTER_TABLE_FIELD_START)) { \ valid = TRUE; \ } \ } \ } else { \ valid = FALSE; \ if (SOC_REG_IS_VALID(unit, ctr##r)) { \ valid = TRUE; \ } \ } /* * For collecting addition non-DMA counters, unlike the non-DMA counter * in the soc_counter_non_dma_t, the counters collected here are not shown * in "show counter" command. */ enum { _BCM_STAT_EXTRA_COUNTER_EGRDROPPKTCOUNT = 0, _BCM_STAT_EXTRA_COUNTER_COUNT }; typedef enum _bcm_stat_oper_e { _BCM_STAT_GET, _BCM_STAT_CLEAR }_bcm_stat_oper_t; typedef enum _bcm_stat_reg_oper_e { _BCM_STAT_REG_ADD, _BCM_STAT_REG_SUB, _BCM_STAT_REG_CLEAR }_bcm_stat_reg_oper_t; typedef struct _bcm_stat_extra_counter_s { soc_reg_t reg; uint32 *ctr_prev; uint64 *count64; } _bcm_stat_extra_counter_t; /* Oversize packet error control */ extern SHR_BITDCL *_bcm_stat_ovr_control; #define COUNT_OVR_ERRORS(unit) \ (soc_feature(unit, soc_feature_stat_jumbo_adj) && \ ((_bcm_stat_ovr_control != NULL) && \ (SHR_BITGET(&_bcm_stat_ovr_control[(unit)],(port))))) /* Oversize packet size threshold accessor functions */ extern int _bcm_esw_stat_ovr_threshold_set(int unit, bcm_port_t port, int value); extern int _bcm_esw_stat_ovr_threshold_get(int unit, bcm_port_t port, int *value); extern int _bcm_esw_stat_ovr_error_control_set(int unit, bcm_port_t port, int value); extern int _bcm_esw_stat_ovr_error_control_get(int unit, bcm_port_t port, int *value); extern int _bcm_stat_reg_op(int unit, bcm_port_t port, int sync_mode, int reg_op, soc_reg_t ctr_reg, uint64 *val); extern int _bcm_stat_reg_idx_op(int unit, bcm_port_t port, int sync_mode, int reg_op, soc_reg_t ctr_reg, int ar_idx, uint64 *val); /* Library-private functions exported from stat_fe.c */ extern int _bcm_stat_fe_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_ge.c */ extern int _bcm_stat_ge_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val, int incl_non_ge_stat); /* Library-private functions exported from stat_xe.c */ extern int _bcm_stat_xe_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_hg.c */ extern int _bcm_stat_hg_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_generic.c */ extern int _bcm_stat_generic_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_mxq.c */ extern int _bcm_stat_mxq_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_clmib.c */ extern int bcmi_stat_clmib_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); /* Library-private functions exported from stat_preempt.c */ extern int bcmi_stat_preempt_ge_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val, int incl_non_ge_stat); extern int bcmi_stat_preempt_xl_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); extern int bcmi_stat_preempt_get_set(int unit, bcm_port_t port, int sync_mode, int stat_op, bcm_stat_val_t type, uint64 *val); extern int _bcm_stat_counter_extra_get(int unit, soc_reg_t reg, soc_port_t port, uint64 *val); extern int _bcm_stat_counter_non_dma_extra_get(int unit, soc_counter_non_dma_id_t non_dma_id, soc_port_t port, uint64 *val); extern int _bcm_esw_stat_detach(int unit); extern int _bcm_esw_stat_sync(int unit); /* Stat chunks for warm-boot functionality */ #ifdef BCM_WARM_BOOT_SUPPORT #define _BCM_STAT_WARM_BOOT_CHUNK_PORTS 0 #define _BCM_STAT_WARM_BOOT_CHUNK_FLEX 1 extern int _bcm_esw_stat_sync_version_above_equal(int unit,uint16 version); extern int _bcm_esw_stat_sync_version_below_equal(int unit,uint16 version); #endif #ifdef BCM_WARM_BOOT_SUPPORT_SW_DUMP extern void _bcm_stat_sw_dump(int unit); #endif /* BCM_WARM_BOOT_SUPPORT_SW_DUMP */ extern void _bcm_stat_flexctr_pool_info_sw_dump(int unit); #endif /* !_BCM_INT_STAT_H */
import random import numpy as np from agents.abstract_agent import Agent from gym_splendor_code.envs.mechanics.state_as_dict import StateAsDict class ValueNNAgent(Agent): def __init__(self, model): super().__init__() self.model = model def choose_act(self, mode, info=False): current_state_as_dict = StateAsDict(self.env.current_state_of_the_game) list_of_actions = self.env.action_space.list_of_actions if list_of_actions: best_action = None best_action_value = -100 for action in list_of_actions: state_copy = current_state_as_dict.to_state() action.execute(state_copy) current_value = self.model.get_value(state_copy) if current_value > best_action_value: best_action_value = current_value best_action = action if not info: return best_action if info: return best_action, best_action_value else: if not info: return None if info: return None, -1
#! python3 import requests resp = requests.get("http://clav-api.di.uminho.pt/v2/classes?nivel=3&apikey=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyNGNiYTg0OWJhYmI2NjdjYmZkYzE2ZSIsImlhdCI6MTY0OTE5NTY1MiwiZXhwIjoxNjUxNzg3NjUyfQ.EuvH713Qr6IZ073-5FMF6j5p_3tb6Trv0TOOF5ZHWOPUlCBqKU1H9DTo_ueoCyWhPbEd6F8xzNvn-UkG3J8Ppq65xF8uukoElnSIsi3kldXI2E_EHMv5ETIq-2SGpiBmLyv1zu2broi-nXw18XwKM-WWpoumw5mZacg1qyj4kokGm--WzPIDD15Uibu2ObsDfeHpbDt81Npq-WgEVe56F5w0TdAvY_b-Xvm77hXI4MuaatL9bsOtYEyiepLuBelDyVWjAIoon3-7tB1lwrPnC0OJ_cxKUyCdqx8sZPkmciyTmBsV8fDTyvTP1ibiryAQsDRK5TrG83CcWmStZyDnoQ") #print(resp.json()) for entrada in resp.json(): print(entrada)
""" Components that house MIDI events and other misc. data, """ from dataclasses import dataclass class TrackInfo(dataclass): """ An object that contains info about a specific track. The data in this object is used for keeping track of track statistics. We contain data about the track type, :param dataclass: [description] :type dataclass: [type] """ class TrackPattern(list): """ A collection of tracks. We contain a list of tracks that contain MIDI events. We keep track(haha) of statistics and data related to the MIDI data we contain. We do this by handling Meta events and yap-events. We also support playback of the MIDI data. This includes ALL MIDI track types, and supports tracks that are playing at diffrent speeds. """ pass class Track(list): """ A track of MIDI events. We offer some useful helper methods that make altering and adding MIDI events a relatively painless affair. We inherit the default python list, so we support all list operations. """ def __init__(self, *args): super().__init__(*args) self.name = '' # Name of the track
var prewidth; $(".gallery-grid").hover(function(){ prewidth = $(this).find(".gallery-info").css("top"); console.log(prewidth); $(this).find(".gallery-info").css("top",0); },function(){ $(this).find(".gallery-info").css("top",prewidth); }); function nestajanjePopUp(){ localStorage.setItem("accepted", "true"); //Animacija by Predrag Jovicic $(".closeButton").fadeOut(600); $("#popuphead").fadeOut(600); $("#popup input").fadeOut(300); $("#popup").animate({width:"0rem",opacity:"0"},1000); setTimeout(function(){$("#popup").hide();},1500); } $(".closeButton").click(nestajanjePopUp); $("#okdugme").click(nestajanjePopUp); $(document).ready(function(){ if (localStorage.getItem("accepted") === null) { $("#popup").slideDown(); localStorage.setItem("accepted",true); } });
/* * Inline Form Validation Engine 2.6.2, jQuery plugin * * Copyright(c) 2010, Cedric Dugas * http://www.position-absolute.com * * 2.0 Rewrite by Olivier Refalo * http://www.crionics.com * * Form validation engine allowing custom regex rules to be added. * Licensed under the MIT License */ (function($) { "use strict"; var methods = { /** * Kind of the constructor, called before any action * @param {Map} user options */ init: function(options) { var form = this; if (!form.data('jqv') || form.data('jqv') == null ) { options = methods._saveOptions(form, options); // bind all formError elements to close on click $(document).on("click", ".formError", function() { $(this).fadeOut(150, function() { // remove prompt once invisible $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); }); } return this; }, /** * Attachs jQuery.validationEngine to form.submit and field.blur events * Takes an optional params: a list of options * ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"}); */ attach: function(userOptions) { var form = this; var options; if(userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv'); options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class"; if (options.binded) { // delegate fields form.on(options.validationEventTrigger, "["+options.validateAttribute+"*=validate]:not([type=checkbox]):not([type=radio]):not(.datepicker)", methods._onFieldEvent); form.on("click", "["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]", methods._onFieldEvent); form.on(options.validationEventTrigger,"["+options.validateAttribute+"*=validate][class*=datepicker]", {"delay": 300}, methods._onFieldEvent); } if (options.autoPositionUpdate) { $(window).bind("resize", { "noAnimation": true, "formElem": form }, methods.updatePromptsPosition); } form.on("click","a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick); form.removeData('jqv_submitButton'); // bind form.submit form.on("submit", methods._onSubmitEvent); return this; }, /** * Unregisters any bindings that may point to jQuery.validaitonEngine */ detach: function() { var form = this; var options = form.data('jqv'); // unbind fields form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").off(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox],[class*=validate][type=radio]").off("click", methods._onFieldEvent); // unbind form.submit form.off("submit", methods._onSubmitEvent); form.removeData('jqv'); form.off("click", "a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick); form.removeData('jqv_submitButton'); if (options.autoPositionUpdate) $(window).off("resize", methods.updatePromptsPosition); return this; }, /** * Validates either a form or a list of fields, shows prompts accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validate: function() { var element = $(this); var valid = null; if (element.is("form") || element.hasClass("validationEngineContainer")) { if (element.hasClass('validating')) { // form is already validating. // Should abort old validation and start new one. I don't know how to implement it. return false; } else { element.addClass('validating'); var options = element.data('jqv'); var valid = methods._validateFields(this); // If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again setTimeout(function(){ element.removeClass('validating'); }, 100); if (valid && options.onSuccess) { options.onSuccess(); } else if (!valid && options.onFailure) { options.onFailure(); } } } else if (element.is('form') || element.hasClass('validationEngineContainer')) { element.removeClass('validating'); } else { // field validation var form = element.closest('form, .validationEngineContainer'), options = (form.data('jqv')) ? form.data('jqv') : $.validationEngine.defaults, valid = methods._validateField(element, options); if (valid && options.onFieldSuccess) options.onFieldSuccess(); else if (options.onFieldFailure && options.InvalidFields.length > 0) { options.onFieldFailure(); } } if(options.onValidationComplete) { // !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing return !!options.onValidationComplete(form, valid); } return valid; }, /** * Redraw prompts position, useful when you change the DOM state when validating */ updatePromptsPosition: function(event) { if (event && this == window) { var form = event.data.formElem; var noAnimation = event.data.noAnimation; } else var form = $(this.closest('form, .validationEngineContainer')); var options = form.data('jqv'); // No option, take default one form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){ var field = $(this); if (options.prettySelect && field.is(":hidden")) field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix); var prompt = methods._getPrompt(field); var promptText = $(prompt).find(".formErrorContent").html(); if(prompt) methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation); }); return this; }, /** * Displays a prompt on a element. * Note that the element needs an id! * * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight */ showPrompt: function(promptText, type, promptPosition, showArrow) { var form = this.closest('form, .validationEngineContainer'); var options = form.data('jqv'); // No option, take default one if(!options) options = methods._saveOptions(this, options); if(promptPosition) options.promptPosition=promptPosition; options.showArrow = showArrow==true; methods._showPrompt(this, promptText, type, false, options); return this; }, /** * Closes form error prompts, CAN be invidual */ hide: function() { var form = $(this).closest('form, .validationEngineContainer'); var options = form.data('jqv'); var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3; var closingtag; if($(this).is("form") || $(this).hasClass("validationEngineContainer")) { closingtag = "parentForm"+methods._getClassName($(this).attr("id")); } else { closingtag = methods._getClassName($(this).attr("id")) +"formError"; } $('.'+closingtag).fadeTo(fadeDuration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Closes all error prompts on the page */ hideAll: function() { var form = this; var options = form.data('jqv'); var duration = options ? options.fadeDuration:300; $('.formError').fadeTo(duration, 300, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function(event) { var field = $(this); var form = field.closest('form, .validationEngineContainer'); var options = form.data('jqv'); options.eventTrigger = "field"; // validate the current field window.setTimeout(function() { methods._validateField(field, options); if (options.InvalidFields.length == 0 && options.onFieldSuccess) { options.onFieldSuccess(); } else if (options.InvalidFields.length > 0 && options.onFieldFailure) { options.onFieldFailure(); } }, (event.data) ? event.data.delay : 0); }, /** * Called when the form is submited, shows prompts accordingly * * @param {jqObject} * form * @return false if form submission needs to be cancelled */ _onSubmitEvent: function() { var form = $(this); var options = form.data('jqv'); //check if it is trigger from skipped button if (form.data("jqv_submitButton")){ var submitButton = $("#" + form.data("jqv_submitButton")); if (submitButton){ if (submitButton.length > 0){ if (submitButton.hasClass("validate-skip") || submitButton.attr("data-validation-engine-skip") == "true") return true; } } } options.eventTrigger = "submit"; // validate each field // (- skip field ajax validation, not necessary IF we will perform an ajax form validation) var r=methods._validateFields(form); if (r && options.ajaxFormValidation) { methods._validateFormWithAjax(form, options); // cancel form auto-submission - process with async call onAjaxFormComplete return false; } if(options.onValidationComplete) { // !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing return !!options.onValidationComplete(form, r); } return r; }, /** * Return true if the ajax field validations passed so far * @param {Object} options * @return true, is all ajax validation passed so far (remember ajax is async) */ _checkAjaxStatus: function(options) { var status = true; $.each(options.ajaxValidCache, function(key, value) { if (!value) { status = false; // break the each return false; } }); return status; }, /** * Return true if the ajax field is validated * @param {String} fieldid * @param {Object} options * @return true, if validation passed, false if false or doesn't exist */ _checkAjaxFieldStatus: function(fieldid, options) { return options.ajaxValidCache[fieldid] == true; }, /** * Validates form fields, shows prompts accordingly * * @param {jqObject} * form * @param {skipAjaxFieldValidation} * boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked * * @return true if form is valid, false if not, undefined if ajax form validation is done */ _validateFields: function(form) { var options = form.data('jqv'); // this variable is set to true if an error is found var errorFound = false; // Trigger hook, start validation form.trigger("jqv.form.validating"); // first, evaluate status of non ajax fields var first_err=null; form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() { var field = $(this); var names = []; if ($.inArray(field.attr('name'), names) < 0) { errorFound |= methods._validateField(field, options); if (errorFound && first_err==null) if (field.is(":hidden") && options.prettySelect) first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); else { //Check if we need to adjust what element to show the prompt on //and and such scroll to instead if(field.data('jqv-prompt-at') instanceof jQuery ){ field = field.data('jqv-prompt-at'); } else if(field.data('jqv-prompt-at')) { field = $(field.data('jqv-prompt-at')); } first_err=field; } if (options.doNotShowAllErrosOnSubmit) return false; names.push(field.attr('name')); //if option set, stop checking validation rules after one error is found if(options.showOneMessage == true && errorFound){ return false; } } }); // second, check to see if all ajax calls completed ok // errorFound |= !methods._checkAjaxStatus(options); // third, check status and scroll the container accordingly form.trigger("jqv.form.result", [errorFound]); if (errorFound) { if (options.scroll) { var destination=first_err.offset().top; var fixleft = first_err.offset().left; //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType=options.promptPosition; if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1) positionType=positionType.substring(0,positionType.indexOf(":")); if (positionType!="bottomRight" && positionType!="bottomLeft") { var prompt_err= methods._getPrompt(first_err); if (prompt_err) { destination=prompt_err.offset().top; } } // Offset the amount the page scrolls by an amount in px to accomodate fixed elements at top of page if (options.scrollOffset) { destination -= options.scrollOffset; } // get the position of the first error, there should be at least one, no need to check this //var destination = form.find(".formError:not('.greenPopup'):first").offset().top; if (options.isOverflown) { var overflowDIV = $(options.overflownDIV); if(!overflowDIV.length) return false; var scrollContainerScroll = overflowDIV.scrollTop(); var scrollContainerPos = -parseInt(overflowDIV.offset().top); destination += scrollContainerScroll + scrollContainerPos - 5; var scrollContainer = $(options.overflownDIV + ":not(:animated)"); scrollContainer.animate({ scrollTop: destination }, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); } else { $("html, body").animate({ scrollTop: destination }, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); $("html, body").animate({scrollLeft: fixleft},1100) } } else if(options.focusFirstField) first_err.focus(); return false; } return true; }, /** * This method is called to perform an ajax form validation. * During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true * * @param {jqObject} form * @param {Map} options */ _validateFormWithAjax: function(form, options) { var data = form.serialize(); var type = (options.ajaxFormValidationMethod) ? options.ajaxFormValidationMethod : "GET"; var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action"); var dataType = (options.dataType) ? options.dataType : "json"; $.ajax({ type: type, url: url, cache: false, dataType: dataType, data: data, form: form, methods: methods, options: options, beforeSend: function() { return options.onBeforeAjaxFormValidation(form, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { if ((dataType == "json") && (json !== true)) { // getting to this case doesn't necessary means that the form is invalid // the server may return green or closing prompt actions // this flag helps figuring it out var errorInForm=false; for (var i = 0; i < json.length; i++) { var value = json[i]; var errorFieldId = value[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { // promptText or selector var msg = value[2]; // if the field is valid if (value[1] == true) { if (msg == "" || !msg){ // if for some reason, status==true and error="", just close the prompt methods._closePrompt(errorField); } else { // the field is valid, but we are displaying a green prompt if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) msg = txt; } if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true); } } else { // the field is invalid, show the red error prompt errorInForm|=true; if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true); } } } options.onAjaxFormComplete(!errorInForm, form, json, options); } else options.onAjaxFormComplete(true, form, json, options); } }); }, /** * Validates field, shows prompts accordingly * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @param {Map} * user options * @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.) */ _validateField: function(field, options, skipAjaxValidation) { if (!field.attr("id")) { field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter); ++$.validationEngine.fieldIdCounter; } if (!options.validateNonVisibleFields && (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden"))) return false; var rulesParsing = field.attr(options.validateAttribute); var getRules = /validate\[(.*)\]/.exec(rulesParsing); if (!getRules) return false; var str = getRules[1]; var rules = str.split(/\[|,|\]/); // true if we ran the ajax validation, tells the logic to stop messing with prompts var isAjaxValidator = false; var fieldName = field.attr("name"); var promptText = ""; var promptType = ""; var required = false; var limitErrors = false; options.isError = false; options.showArrow = true; // If the programmer wants to limit the amount of error messages per field, if (options.maxErrorsPerField > 0) { limitErrors = true; } var form = $(field.closest("form, .validationEngineContainer")); // Fix for adding spaces in the rules for (var i = 0; i < rules.length; i++) { rules[i] = rules[i].replace(" ", ""); // Remove any parsing errors if (rules[i] === '') { delete rules[i]; } } for (var i = 0, field_errors = 0; i < rules.length; i++) { // If we are limiting errors, and have hit the max, break if (limitErrors && field_errors >= options.maxErrorsPerField) { // If we haven't hit a required yet, check to see if there is one in the validation rules for this // field and that it's index is greater or equal to our current index if (!required) { var have_required = $.inArray('required', rules); required = (have_required != -1 && have_required >= i); } break; } var errorMsg = undefined; switch (rules[i]) { case "required": required = true; errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required); break; case "custom": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom); break; case "groupRequired": // Check is its the first of group, if not, reload validation with first field // AND continue normal validation on present field var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var firstOfGroup = form.find(classGroup).eq(0); if(firstOfGroup[0] != field[0]){ methods._validateField(firstOfGroup, options, skipAjaxValidation); options.showArrow = true; } errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired); if(errorMsg) required = true; options.showArrow = false; break; case "ajax": // AJAX defaults to returning it's loading message errorMsg = methods._ajax(field, rules, i, options); if (errorMsg) { promptType = "load"; } break; case "minSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize); break; case "maxSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize); break; case "min": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min); break; case "max": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max); break; case "past": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past); break; case "future": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future); break; case "dateRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange); } if (errorMsg) required = true; options.showArrow = false; break; case "dateTimeRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange); } if (errorMsg) required = true; options.showArrow = false; break; case "maxCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox); break; case "minCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox); break; case "equals": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals); break; case "funcCall": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall); break; case "creditCard": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard); break; case "condRequired": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired); if (errorMsg !== undefined) { required = true; } break; default: } var end_validation = false; // If we were passed back an message object, check what the status was to determine what to do if (typeof errorMsg == "object") { switch (errorMsg.status) { case "_break": end_validation = true; break; // If we have an error message, set errorMsg to the error message case "_error": errorMsg = errorMsg.message; break; // If we want to throw an error, but not show a prompt, return early with true case "_error_no_prompt": return true; break; // Anything else we continue on default: break; } } // If it has been specified that validation should end now, break if (end_validation) { break; } // If we have a string, that means that we have an error, so add it to the error message. if (typeof errorMsg == 'string') { promptText += errorMsg + "<br/>"; options.isError = true; field_errors++; } } // If the rules required is not added, an empty field is not validated if(!required && !(field.val()) && field.val().length < 1) options.isError = false; // Hack for radio/checkbox group button, the validation go into the // first radio/checkbox of the group var fieldType = field.prop("type"); var positionType=field.data("promptPosition") || options.promptPosition; if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) { if(positionType === 'inline') { field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:last")); } else { field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first")); } options.showArrow = false; } if(field.is(":hidden") && options.prettySelect) { field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); } if (options.isError && options.showPrompts){ methods._showPrompt(field, promptText, promptType, false, options); }else{ if (!isAjaxValidator) methods._closePrompt(field); } if (!isAjaxValidator) { field.trigger("jqv.field.result", [field, options.isError, promptText]); } /* Record error */ var errindex = $.inArray(field[0], options.InvalidFields); if (errindex == -1) { if (options.isError) options.InvalidFields.push(field[0]); } else if (!options.isError) { options.InvalidFields.splice(errindex, 1); } methods._handleStatusCssClasses(field, options); /* run callback function for each field */ if (options.isError && options.onFieldFailure) options.onFieldFailure(field); if (!options.isError && options.onFieldSuccess) options.onFieldSuccess(field); return options.isError; }, /** * Handling css classes of fields indicating result of validation * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @private */ _handleStatusCssClasses: function(field, options) { /* remove all classes */ if(options.addSuccessCssClassToField) field.removeClass(options.addSuccessCssClassToField); if(options.addFailureCssClassToField) field.removeClass(options.addFailureCssClassToField); /* Add classes */ if (options.addSuccessCssClassToField && !options.isError) field.addClass(options.addSuccessCssClassToField); if (options.addFailureCssClassToField && options.isError) field.addClass(options.addFailureCssClassToField); }, /******************** * _getErrorMessage * * @param form * @param field * @param rule * @param rules * @param i * @param options * @param originalValidationMethod * @return {*} * @private */ _getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) { // If we are using the custon validation type, build the index for the rule. // Otherwise if we are doing a function call, make the call and return the object // that is passed back. var rule_index = jQuery.inArray(rule, rules); if (rule === "custom" || rule === "funcCall") { var custom_validation_type = rules[rule_index + 1]; rule = rule + "[" + custom_validation_type + "]"; // Delete the rule from the rules array so that it doesn't try to call the // same rule over again delete(rules[rule_index]); } // Change the rule to the composite rule, if it was different from the original var alteredRule = rule; var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class"); var element_classes_array = element_classes.split(" "); // Call the original validation method. If we are dealing with dates or checkboxes, also pass the form var errorMsg; if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") { errorMsg = originalValidationMethod(form, field, rules, i, options); } else { errorMsg = originalValidationMethod(field, rules, i, options); } // If the original validation method returned an error and we have a custom error message, // return the custom message instead. Otherwise return the original error message. if (errorMsg != undefined) { var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, alteredRule, options); if (custom_message) errorMsg = custom_message; } return errorMsg; }, _getCustomErrorMessage:function (field, classes, rule, options) { var custom_message = false; var validityProp = /^custom\[.*\]$/.test(rule) ? methods._validityProp["custom"] : methods._validityProp[rule]; // If there is a validityProp for this rule, check to see if the field has an attribute for it if (validityProp != undefined) { custom_message = field.attr("data-errormessage-"+validityProp); // If there was an error message for it, return the message if (custom_message != undefined) return custom_message; } custom_message = field.attr("data-errormessage"); // If there is an inline custom error message, return it if (custom_message != undefined) return custom_message; var id = '#' + field.attr("id"); // If we have custom messages for the element's id, get the message for the rule from the id. // Otherwise, if we have custom messages for the element's classes, use the first class message we find instead. if (typeof options.custom_error_messages[id] != "undefined" && typeof options.custom_error_messages[id][rule] != "undefined" ) { custom_message = options.custom_error_messages[id][rule]['message']; } else if (classes.length > 0) { for (var i = 0; i < classes.length && classes.length > 0; i++) { var element_class = "." + classes[i]; if (typeof options.custom_error_messages[element_class] != "undefined" && typeof options.custom_error_messages[element_class][rule] != "undefined") { custom_message = options.custom_error_messages[element_class][rule]['message']; break; } } } if (!custom_message && typeof options.custom_error_messages[rule] != "undefined" && typeof options.custom_error_messages[rule]['message'] != "undefined"){ custom_message = options.custom_error_messages[rule]['message']; } return custom_message; }, _validityProp: { "required": "value-missing", "custom": "custom-error", "groupRequired": "value-missing", "ajax": "custom-error", "minSize": "range-underflow", "maxSize": "range-overflow", "min": "range-underflow", "max": "range-overflow", "past": "type-mismatch", "future": "type-mismatch", "dateRange": "type-mismatch", "dateTimeRange": "type-mismatch", "maxCheckbox": "range-overflow", "minCheckbox": "range-underflow", "equals": "pattern-mismatch", "funcCall": "custom-error", "creditCard": "pattern-mismatch", "condRequired": "value-missing" }, /** * Required validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @param {bool} condRequired flag when method is used for internal purpose in condRequired check * @return an error string if validation failed */ _required: function(field, rules, i, options, condRequired) { switch (field.prop("type")) { case "text": case "password": case "textarea": case "file": case "select-one": case "select-multiple": default: var field_val = $.trim( field.val() ); var dv_placeholder = $.trim( field.attr("data-validation-placeholder") ); var placeholder = $.trim( field.attr("placeholder") ); if ( ( !field_val ) || ( dv_placeholder && field_val == dv_placeholder ) || ( placeholder && field_val == placeholder ) ) { return options.allrules[rules[i]].alertText; } break; case "radio": case "checkbox": // new validation style to only check dependent field if (condRequired) { if (!field.attr('checked')) { return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } // old validation style var form = field.closest("form, .validationEngineContainer"); var name = field.attr("name"); if (form.find("input[name='" + name + "']:checked").size() == 0) { if (form.find("input[name='" + name + "']:visible").size() == 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } }, /** * Validate that 1 from the group field is required * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _groupRequired: function(field, rules, i, options) { var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var isValid = false; // Check all fields from the group field.closest("form, .validationEngineContainer").find(classGroup).each(function(){ if(!methods._required($(this), rules, i, options)){ isValid = true; return false; } }); if(!isValid) { return options.allrules[rules[i]].alertText; } }, /** * Validate rules * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _custom: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; var fn; if(!rule) { alert("jqv:custom rule not found - "+customRule); return; } if(rule["regex"]) { var ex=rule.regex; if(!ex) { alert("jqv:custom regex not found - "+customRule); return; } var pattern = new RegExp(ex); if (!pattern.test(field.val())) return options.allrules[customRule].alertText; } else if(rule["func"]) { fn = rule["func"]; if (typeof(fn) !== "function") { alert("jqv:custom parameter 'function' is no function - "+customRule); return; } if (!fn(field, rules, i, options)) return options.allrules[customRule].alertText; } else { alert("jqv:custom type not allowed "+customRule); return; } }, /** * Validate custom function outside of the engine scope * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _funcCall: function(field, rules, i, options) { var functionName = rules[i + 1]; var fn; if(functionName.indexOf('.') >-1) { var namespaces = functionName.split('.'); var scope = window; while(namespaces.length) { scope = scope[namespaces.shift()]; } fn = scope; } else fn = window[functionName] || options.customFunctions[functionName]; if (typeof(fn) == 'function') return fn(field, rules, i, options); }, /** * Field match * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _equals: function(field, rules, i, options) { var equalsField = rules[i + 1]; if (field.val() != $("#" + equalsField).val()) return options.allrules.equals.alertText; }, /** * Check the maximum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxSize: function(field, rules, i, options) { var max = rules[i + 1]; var len = field.val().length; if (len > max) { var rule = options.allrules.maxSize; return rule.alertText + max + rule.alertText2; } }, /** * Check the minimum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minSize: function(field, rules, i, options) { var min = rules[i + 1]; var len = field.val().length; if (len < min) { var rule = options.allrules.minSize; return rule.alertText + min + rule.alertText2; } }, /** * Check number minimum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _min: function(field, rules, i, options) { var min = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len < min) { var rule = options.allrules.min; if (rule.alertText2) return rule.alertText + min + rule.alertText2; return rule.alertText + min; } }, /** * Check number maximum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _max: function(field, rules, i, options) { var max = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len >max ) { var rule = options.allrules.max; if (rule.alertText2) return rule.alertText + max + rule.alertText2; //orefalo: to review, also do the translations return rule.alertText + max; } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _past: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate > pdate ) { var rule = options.allrules.past; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks date is in the future * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _future: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate < pdate ) { var rule = options.allrules.future; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks if valid date * * @param {string} date string * @return a bool based on determination of valid date */ _isDate: function (value) { var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/); return dateRegEx.test(value); }, /** * Checks if valid date time * * @param {string} date string * @return a bool based on determination of valid date time */ _isDateTime: function (value){ var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/); return dateTimeRegEx.test(value); }, //Checks if the start date is before the end date //returns true if end is later than start _dateCompare: function (start, end) { return (new Date(start.toString()) < new Date(end.toString())); }, /** * Checks date range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Checks date time range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateTimeRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Max number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; if (options.allrules.maxCheckbox.alertText2) return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2; return options.allrules.maxCheckbox.alertText; } }, /** * Min number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize < nbCheck) { options.showArrow = false; return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2; } }, /** * Checks that it is a valid credit card number according to the * Luhn checksum algorithm. * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _creditCard: function(field, rules, i, options) { //spaces and dashes may be valid characters, but must be stripped to calculate the checksum. var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, ''); var numDigits = cardNumber.length; if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) { var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String(); do { digit = parseInt(cardNumber.charAt(i)); luhn += (pos++ % 2 == 0) ? digit * 2 : digit; } while (--i >= 0) for (i = 0; i < luhn.length; i++) { sum += parseInt(luhn.charAt(i)); } valid = sum % 10 == 0; } if (!valid) return options.allrules.creditCard.alertText; }, /** * Ajax field validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return nothing! the ajax validator handles the prompts itself */ _ajax: function(field, rules, i, options) { var errorSelector = rules[i + 1]; var rule = options.allrules[errorSelector]; var extraData = rule.extraData; var extraDataDynamic = rule.extraDataDynamic; var data = { "fieldId" : field.attr("id"), "fieldValue" : field.val() }; if (typeof extraData === "object") { $.extend(data, extraData); } else if (typeof extraData === "string") { var tempData = extraData.split("&"); for(var i = 0; i < tempData.length; i++) { var values = tempData[i].split("="); if (values[0] && values[0]) { data[values[0]] = values[1]; } } } if (extraDataDynamic) { var tmpData = []; var domIds = String(extraDataDynamic).split(","); for (var i = 0; i < domIds.length; i++) { var id = domIds[i]; if ($(id).length) { var inputValue = field.closest("form, .validationEngineContainer").find(id).val(); var keyValue = id.replace('#', '') + '=' + escape(inputValue); data[id.replace('#', '')] = inputValue; } } } // If a field change event triggered this we want to clear the cache for this ID if (options.eventTrigger == "field") { delete(options.ajaxValidCache[field.attr("id")]); } // If there is an error or if the the field is already validated, do not re-execute AJAX if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) { $.ajax({ type: options.ajaxFormValidationMethod, url: rule.url, cache: false, dataType: "json", data: data, field: field, rule: rule, methods: methods, options: options, beforeSend: function() {}, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; //var errorField = $($("#" + errorFieldId)[0]); var errorField = $("#"+ errorFieldId).eq(0); // make sure we found the element if (errorField.length == 1) { var status = json[1]; // read the optional msg from the server var msg = json[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) { msg = txt; } } } else msg = rule.alertText; if (options.showPrompts) methods._showPrompt(errorField, msg, "", true, options); } else { options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) { msg = txt; } } } else msg = rule.alertTextOk; if (options.showPrompts) { // see if we should display a green prompt if (msg) methods._showPrompt(errorField, msg, "pass", true, options); else methods._closePrompt(errorField); } // If a submit form triggered this, we want to re-submit the form if (options.eventTrigger == "submit") field.closest("form").submit(); } } errorField.trigger("jqv.field.result", [errorField, options.isError, msg]); } }); return rule.alertTextLoad; } }, /** * Common method to handle ajax errors * * @param {Object} data * @param {Object} transport */ _ajaxError: function(data, transport) { if(data.status == 0 && transport == null) alert("The page is not served from a server! ajax call failed"); else if(typeof console != "undefined") console.log("Ajax error: " + data.status + " " + transport); }, /** * date -> string * * @param {Object} date */ _dateToString: function(date) { return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); }, /** * Parses an ISO date * @param {String} d */ _parseDate: function(d) { var dateParts = d.split("-"); if(dateParts==d) dateParts = d.split("/"); if(dateParts==d) { dateParts = d.split("."); return new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]); } return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]); }, /** * Builds or updates a prompt with the given information * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) { //Check if we need to adjust what element to show the prompt on if(field.data('jqv-prompt-at') instanceof jQuery ){ field = field.data('jqv-prompt-at'); } else if(field.data('jqv-prompt-at')) { field = $(field.data('jqv-prompt-at')); } var prompt = methods._getPrompt(field); // The ajax submit errors are not see has an error in the form, // When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time // Because no error was found befor submitting if(ajaxform) prompt = false; // Check that there is indded text if($.trim(promptText)){ if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); } }, /** * Builds and shades a prompt for the given field. * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(methods._getClassName(field.attr("id")) + "formError"); // add a class name to identify the parent form of the prompt prompt.addClass("parentForm"+methods._getClassName(field.closest('form, .validationEngineContainer').attr("id"))); prompt.addClass("formError"); switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); break; default: /* it has error */ //alert("unknown popup type:"+type); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt); // determine position type var positionType=field.data("promptPosition") || options.promptPosition; // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) if (typeof(positionType)=='string') { var pos=positionType.indexOf(":"); if(pos!=-1) positionType=positionType.substring(0,pos); } switch (positionType) { case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } // Add custom prompt class if (options.addPromptClass) prompt.addClass(options.addPromptClass); // Add custom prompt class defined in element var requiredOverride = field.attr('data-required-class'); if(requiredOverride !== undefined) { prompt.addClass(requiredOverride); } else { if(options.prettySelect) { if($('#' + field.attr('id')).next().is('select')) { var prettyOverrideClass = $('#' + field.attr('id').substr(options.usePrefix.length).substring(options.useSuffix.length)).attr('data-required-class'); if(prettyOverrideClass !== undefined) { prompt.addClass(prettyOverrideClass); } } } } prompt.css({ "opacity": 0 }); if(positionType === 'inline') { prompt.addClass("inline"); if(typeof field.attr('data-prompt-target') !== 'undefined' && $('#'+field.attr('data-prompt-target')).length > 0) { prompt.appendTo($('#'+field.attr('data-prompt-target'))); } else { field.after(prompt); } } else { field.before(prompt); } var pos = methods._calculatePosition(field, prompt, options); prompt.css({ 'position': positionType === 'inline' ? 'relative' : 'absolute', "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }).data("callerField", field); if (options.autoHidePrompt) { setTimeout(function(){ prompt.animate({ "opacity": 0 },function(){ prompt.closest('.formErrorOuter').remove(); prompt.remove(); }); }, options.autoHideDelay); } return prompt.animate({ "opacity": 0.87 }); }, /** * Updates the prompt text field - the field for which the prompt * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) { if (prompt) { if (typeof type !== "undefined") { if (type == "pass") prompt.addClass("greenPopup"); else prompt.removeClass("greenPopup"); if (type == "load") prompt.addClass("blackPopup"); else prompt.removeClass("blackPopup"); } if (ajaxed) prompt.addClass("ajaxed"); else prompt.removeClass("ajaxed"); prompt.find(".formErrorContent").html(promptText); var pos = methods._calculatePosition(field, prompt, options); var css = {"top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize}; if (noAnimation) prompt.css(css); else prompt.animate(css); } }, /** * Closes the prompt associated with the given field * * @param {jqObject} * field */ _closePrompt: function(field) { var prompt = methods._getPrompt(field); if (prompt) prompt.fadeTo("fast", 0, function() { prompt.parent('.formErrorOuter').remove(); prompt.remove(); }); }, closePrompt: function(field) { return methods._closePrompt(field); }, /** * Returns the error prompt matching the field if any * * @param {jqObject} * field * @return undefined or the error prompt (jqObject) */ _getPrompt: function(field) { var formId = $(field).closest('form, .validationEngineContainer').attr('id'); var className = methods._getClassName(field.attr("id")) + "formError"; var match = $("." + methods._escapeExpression(className) + '.parentForm' + methods._getClassName(formId))[0]; if (match) return $(match); }, /** * Returns the escapade classname * * @param {selector} * className */ _escapeExpression: function (selector) { return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1"); }, /** * returns true if we are in a RTLed document * * @param {jqObject} field */ isRTL: function(field) { var $document = $(document); var $body = $('body'); var rtl = (field && field.hasClass('rtl')) || (field && (field.attr('dir') || '').toLowerCase()==='rtl') || $document.hasClass('rtl') || ($document.attr('dir') || '').toLowerCase()==='rtl' || $body.hasClass('rtl') || ($body.attr('dir') || '').toLowerCase()==='rtl'; return Boolean(rtl); }, /** * Calculates prompt position * * @param {jqObject} * field * @param {jqObject} * the prompt * @param {Map} * options * @return positions */ _calculatePosition: function (field, promptElmt, options) { var promptTopPosition, promptleftPosition, marginTopSize; var fieldWidth = field.width(); var fieldLeft = field.position().left; var fieldTop = field.position().top; var fieldHeight = field.height(); var promptHeight = promptElmt.height(); // is the form contained in an overflown container? promptTopPosition = promptleftPosition = 0; // compensation for the arrow marginTopSize = -promptHeight; //prompt positioning adjustment support //now you can adjust prompt position //usage: positionType:Xshift,Yshift //for example: // bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally // topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top //You can use +pixels, - pixels. If no sign is provided than + is default. var positionType=field.data("promptPosition") || options.promptPosition; var shift1=""; var shift2=""; var shiftX=0; var shiftY=0; if (typeof(positionType)=='string') { //do we have any position adjustments ? if (positionType.indexOf(":")!=-1) { shift1=positionType.substring(positionType.indexOf(":")+1); positionType=positionType.substring(0,positionType.indexOf(":")); //if any advanced positioning will be needed (percents or something else) - parser should be added here //for now we use simple parseInt() //do we have second parameter? if (shift1.indexOf(",") !=-1) { shift2=shift1.substring(shift1.indexOf(",") +1); shift1=shift1.substring(0,shift1.indexOf(",")); shiftY=parseInt(shift2); if (isNaN(shiftY)) shiftY=0; }; shiftX=parseInt(shift1); if (isNaN(shift1)) shift1=0; }; }; switch (positionType) { default: case "topRight": promptleftPosition += fieldLeft + fieldWidth - 30; promptTopPosition += fieldTop; break; case "topLeft": promptTopPosition += fieldTop; promptleftPosition += fieldLeft; break; case "centerRight": promptTopPosition = fieldTop+4; marginTopSize = 0; promptleftPosition= fieldLeft + field.outerWidth(true)+5; break; case "centerLeft": promptleftPosition = fieldLeft - (promptElmt.width() + 2); promptTopPosition = fieldTop+4; marginTopSize = 0; break; case "bottomLeft": promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; promptleftPosition = fieldLeft; break; case "bottomRight": promptleftPosition = fieldLeft + fieldWidth - 30; promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; break; case "inline": promptleftPosition = 0; promptTopPosition = 0; marginTopSize = 0; }; //apply adjusments if any promptleftPosition += shiftX; promptTopPosition += shiftY; return { "callerTopPosition": promptTopPosition + "px", "callerleftPosition": promptleftPosition + "px", "marginTopSize": marginTopSize + "px" }; }, /** * Saves the user options and variables in the form.data * * @param {jqObject} * form - the form where the user option should be saved * @param {Map} * options - the user options * @return the user options (extended from the defaults) */ _saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 $.validationEngine.defaults.allrules = allRules; var userOptions = $.extend(true,{},$.validationEngine.defaults,options); form.data('jqv', userOptions); return userOptions; }, /** * Removes forbidden characters from class name * @param {String} className */ _getClassName: function(className) { if(className) return className.replace(/:/g, "_").replace(/\./g, "_"); }, /** * Escape special character for jQuery selector * http://totaldev.com/content/escaping-characters-get-valid-jquery-id * @param {String} selector */ _jqSelector: function(str){ return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); }, /** * Conditionally required field * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _condRequired: function(field, rules, i, options) { var idx, dependingField; for(idx = (i + 1); idx < rules.length; idx++) { dependingField = jQuery("#" + rules[idx]).first(); /* Use _required for determining wether dependingField has a value. * There is logic there for handling all field types, and default value; so we won't replicate that here * Indicate this special use by setting the last parameter to true so we only validate the dependingField on chackboxes and radio buttons (#462) */ if (dependingField.length && methods._required(dependingField, ["required"], 0, options, true) == undefined) { /* We now know any of the depending fields has a value, * so we can validate this field as per normal required code */ return methods._required(field, ["required"], 0, options); } } }, _submitButtonClick: function(event) { var button = $(this); var form = button.closest('form, .validationEngineContainer'); form.data("jqv_submitButton", button.attr("id")); } }; /** * Plugin entry point. * You may pass an action as a parameter or a list of options. * if none, the init and attach methods are being called. * Remember: if you pass options, the attached method is NOT called automatically * * @param {String} * method (optional) action */ $.fn.validationEngine = function(method) { var form = $(this); if(!form[0]) return form; // stop here if the form does not exist if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if(method != "showPrompt" && method != "hide" && method != "hideAll") methods.init.apply(form); return methods[method].apply(form, Array.prototype.slice.call(arguments, 1)); } else if (typeof method == 'object' || !method) { // default constructor with or without arguments methods.init.apply(form, arguments); return methods.attach.apply(form); } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }; // LEAK GLOBAL OPTIONS $.validationEngine= {fieldIdCounter: 0,defaults:{ // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: true, // Focus on the first input focusFirstField:true, // Show prompts, set to false to disable prompts showPrompts: true, // Should we attempt to validate non-visible input fields contained in the form? (Useful in cases of tabbed containers, e.g. jQuery-UI tabs) validateNonVisibleFields: false, // Opening box position, possible locations are: topLeft, // topRight, bottomLeft, centerRight, bottomRight, inline // inline gets inserted after the validated field or into an element specified in data-prompt-target promptPosition: "topRight", bindMethod:"bind", // internal, automatically set to true when it parse a _ajax rule inlineAjax: false, // if set to true, the form data is sent asynchronously via ajax to the form.action url (get) ajaxFormValidation: false, // The url to send the submit ajax validation (default to action) ajaxFormValidationURL: false, // HTTP method used for ajax validation ajaxFormValidationMethod: 'get', // Ajax form validation callback method: boolean onComplete(form, status, errors, options) // retuns false if the form.submit event needs to be canceled. onAjaxFormComplete: $.noop, // called right before the ajax call, may return false to cancel onBeforeAjaxFormValidation: $.noop, // Stops form from submitting and execute function assiciated with it onValidationComplete: false, // Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages doNotShowAllErrosOnSubmit: false, // Object where you store custom messages to override the default error messages custom_error_messages:{}, // true if you want to vind the input fields binded: true, // set to true, when the prompt arrow needs to be displayed showArrow: true, // did one of the validation fail ? kept global to stop further ajax validations isError: false, // Limit how many displayed errors a field can have maxErrorsPerField: false, // Caches field validation status, typically only bad status are created. // the array is used during ajax form validation to detect issues early and prevent an expensive submit ajaxValidCache: {}, // Auto update prompt position after window resize autoPositionUpdate: false, InvalidFields: [], onFieldSuccess: false, onFieldFailure: false, onSuccess: false, onFailure: false, validateAttribute: "class", addSuccessCssClassToField: "", addFailureCssClassToField: "", // Auto-hide prompt autoHidePrompt: false, // Delay before auto-hide autoHideDelay: 10000, // Fade out duration while hiding the validations fadeDuration: 0.3, // Use Prettify select library prettySelect: false, // Add css class on prompt addPromptClass : "", // Custom ID uses prefix usePrefix: "", // Custom ID uses suffix useSuffix: "", // Only show one message per error prompt showOneMessage: false }}; $(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"}); })(jQuery);
/* artifact generator: C:\My\wizzi\v4\node_modules\v4-wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: c:\my\wizzi\v4\kernel\wizzi-mtree\src\ittf\lib\loader\ittfinterpolate.js.ittf utc time: Tue, 10 Oct 2017 15:44:11 GMT */ 'use strict'; var jsWizziRunner = require('../jswizzi/jsWizziRunner'); /** rules: Macro expressions are enclosed by ${ and } delimiters. example: ${name}. A macro expression can be escaped and used as a literal, example: \$\{name}. A macro expression may contain paired graphs { }, example: ${ for { var i=0; i<10; i++} ; return i; }. An empty macro ${} is treated as a literal, it is not replaced. An unclosed delimiter ${ is treated as a literal, it is not an error. */ var state_text = 0; var state_tag = 1; var state_key = 2; function interpolate(template, jsWizziContext) { if (typeof template === 'undefined' || template === null) { return ''; } var l = template.length, result = [], ch, key, inside_tags = 0, state = state_text, replacer = null, keyOrCode; for (var i=0; i<l; i++) { ch = template[i]; if (ch == '\\') { console.log(template[i+1], template[i+2], template[i+3]); } if (state == state_text && ch == '\\' && i+3 < l && template[i+1] == '$' && template[i+2] == '\\' && template[i+3] == '{') { result.push('${'); i = i +3; continue; } if (ch == '$') { if (state == state_text) { state = state_tag; } else if (state == state_key) { key.push(ch); } else { // state == state_tag // case double result.push('$$'); state = state_text; } } else if (ch == '{') { if (state == state_text) { result.push(ch); } else if (state == state_key) { // case '{' inside $ { } inside_tags++; key.push(ch); } else { // state == state_tag // case ${ state = state_key; key = []; inside_tags = 0; } } else if (ch == '}') { if (state == state_text) { result.push(ch); } else if (state == state_key) { if (inside_tags > 0) { // case '{}' inside $ { } inside_tags--; key.push(ch); } else { keyOrCode = key.join(''); if (keyOrCode.replace(/\s/g,'').length == 0) { // case empty ${} - is ok do not replace result.push('${}'); } else { var replacer = evalKeyOrCode(keyOrCode, jsWizziContext); if (replacer && replacer.__is_error) { return replacer; } result.push(replacer); } state = state_text; } } else { // state == state_tag // case strange sequence '$}' but ok result.push('$}'); state = state_text; } } else { if (state == state_text) { result.push(ch); } else if (state == state_key) { key.push(ch); } else { // state == state_tag // case sequence '$*' is text result.push('$' + ch); state = state_text; } } } // check for unclosed macros if (state == state_key) { result.push('${' + key.join('')); } else if (state == state_tag) { result.push('$'); } return result.join(''); } function evalKeyOrCode(keyOrCode, jsWizziContext) { // log 'wizzi-mtree.loader.ittfInterpolate.evalKeyOrCode: ', keyOrCode var stm = keyOrCode.indexOf('return ') > -1 ? 'var _____result = function dummy() { ' + keyOrCode + ' }();' : 'var _____result = ' + keyOrCode + ';'; var notUsed = jsWizziRunner.run(stm, jsWizziContext); if (notUsed && notUsed.__is_error) { return notUsed; } // console.log("jsWizziContext.getValue('_____result')", jsWizziContext.getValue('_____result')); return jsWizziContext.getValue('_____result'); } module.exports = interpolate;
export const initialState = { selectedCompanies: [], selectedSlots: {}, // [{ company_id: slot}] fetchingCompanies: false, errorFetchingCompanies: null, fetchedCompanies: false, fetchingCompaniesData: false, errorFetchingCompaniesData: false, fetchedCompaniesData: false, companiesOnlyList: [], companiesData: [], companiesDataParsed: [] }
(function() { "use strict"; load("jstests/aggregation/extras/utils.js"); // For arrayEq(). load("jstests/libs/analyze_plan.js"); // For getPlanStages(). const coll = db.wildcard_nonblocking_sort; assert.commandWorked(coll.createIndex({"$**": 1}, {wildcardProjection: {"excludedField": 0}})); for (let i = 0; i < 50; i++) { assert.commandWorked(coll.insert({a: i, b: -i, x: [123], excludedField: i})); } function checkQueryHasSameResultsWhenUsingIdIndex(query, sort) { const l = coll.find(query).sort(sort).toArray(); const r = coll.find(query).sort(sort).hint({$natural: 1}).toArray(); assert(arrayEq(l, r)); } function checkQueryUsesSortType(query, sort, isBlocking) { const explain = assert.commandWorked(coll.find(query).sort(sort).explain()); const plan = explain.queryPlanner.winningPlan; const ixScans = getPlanStages(plan, "IXSCAN"); const sorts = getPlanStages(plan, "SORT"); if (isBlocking) { assert.eq(sorts.length, 1); assert.eq(sorts[0].sortPattern, sort); // A blocking sort may or may not use the index, so we don't check the length of // 'ixScans'. } else { assert.eq(sorts.length, 0); assert.eq(ixScans.length, 1); const sortKey = Object.keys(sort)[0]; assert.docEq(ixScans[0].keyPattern, {$_path: 1, [sortKey]: 1}); } } function checkQueryUsesNonBlockingSortAndGetsCorrectResults(query, sort) { checkQueryUsesSortType(query, sort, false); checkQueryHasSameResultsWhenUsingIdIndex(query, sort); } function checkQueryUsesBlockingSortAndGetsCorrectResults(query, sort) { checkQueryUsesSortType(query, sort, true); checkQueryHasSameResultsWhenUsingIdIndex(query, sort); } checkQueryUsesNonBlockingSortAndGetsCorrectResults({a: {$gte: 0}}, {a: 1}); checkQueryUsesNonBlockingSortAndGetsCorrectResults({a: {$gte: 0}, x: 123}, {a: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({x: {$elemMatch: {$eq: 123}}}, {x: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({x: {$elemMatch: {$eq: 123}}}, {a: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({a: {$gte: 0}}, {a: 1, b: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({a: {$exists: true}}, {a: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({}, {a: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({x: 123}, {a: 1}); checkQueryUsesBlockingSortAndGetsCorrectResults({excludedField: {$gte: 0}}, {excludedField: 1}); })();
/** * BSD 3-Clause License * * Copyright (c) 2021, Avonni Labs, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Component from '../../storybookWrappers/panel/panelWithDatatable'; customElements.define( 'ac-with-datatable-panel', Component.CustomElementConstructor ); export const PanelWithDatatable = ({ position, title, size, showPanel }) => { const element = document.createElement('ac-with-datatable-panel'); element.position = position; element.title = title; element.size = size; element.showPanel = showPanel; return element; };
class Translation(object): HELP_TEXT = """<b><u>BASIC COMMANDS</u></b>\n\n • /start :- Check Iam Alive\n • /help :- More Details\n • /about :- About Me\n • /sub :- Support and deploy\n • /stats :- User Count""" START_TEXT = """👋Hey {},Iam <a href="t.me/Psautofilter1bot">Psautofilter1bot</a>\n\nMake me an admin for your group and channel then connect me....🎉\n🙂To build a DonLee robot V2 like me, click on the /Subscribe command\nSubscribe to the update channel to learn about my updates and activity...\nClick on the Help /Help button for more information\n🧒 Maintained By <a href="https://t.me/pazzu_s">This Person</a> & <a href="https://t.me/{}">This Person</a>""" ABOUT_TEXT = """📃Bot : <a href="t.me/{}">Psautofilter1bot</a>\n🧒Pazzu420 : <a href="t.me/pazzu_s">PAZZU420</a>\n🧒Creator : <a href="t.me/{}">{}</a>\n📡Hosted On : <a href="https://t.me/PS_MOVIES1">Heroku</a>\n🗣️Language : <a href="https://docs.pyrogram.org">Python3</a>\n📚Library : <a href="https://docs.pyrogram.org">Pyrogram Asyncio 1.13.0 </a>\n🗒️Version : <a href="t.me/{}">2.9.0</a>\n📖Source Code : 🤐""" FSUB_TEXT = """ഹേയ് {} തായേ കാണുന്ന ചാനലിൽ നിങ്ങൾ ഇല്ല അത് കൊണ്ട് നിങ്ങൾക് സിനിമ കിട്ടില്ല...\nസിനിമ കിട്ടാനായി താഴെ കാണുന്ന 🔔 Join എന്ന ബട്ടനിൽ ക്ലിക്ക് ചെയ്തു ഞങ്ങളുടെ മെയിൻ ചാനലിൽ ജോയിൻ ചെയ്യുക എങ്കിൽ മാത്രമേ നിങ്ങൾക്ക് മൂവി ഈ ബോട്ട് വഴി ലഭിക്കുകയുള്ളു. അതു കഴ്ഞ്ഞു തായേ കാണുന്ന 👉"Try again"👈 എന്നുള്ളതിൽ ക്ലിക്ക് ചെയ്തു Start കൊടുത്താൽ നിങ്ങൾക്ക് മൂവി കിട്ടുന്നതാണ്...😁😁""" FILTER_TEXT = """<b><u>Manual Filter</u></b>\n\n• Add me as admin in your group and start filtering:\n\n<b><u>NOTE:</u></b>\n\n1. DonLee should have admin privillage.\n2. only admins can add filters in a chat.\n3. alert buttons have a limit of 64 characters.\n\n<b><u>Commands and Usage:</u></b>\n• /addfilter - Add filter for name\n• /filters - List all filters in chat\n• /delfilters - Delete filter\n• /delallfilters - Delete entire filters (Group Owner Only!)""" AUTOFILTER_TEXT = """<b><u>Auto Filter</u></b>\n\n<b><u>🤖 Bot Commands 🤖</u></b>\n <code>(Works Only In Groups):</code>\n\n<b><u>Add CMD</u></b>\n ☞ <code>/addchannel</code> <b>chat_id</b>\n ☞ <code>/addchannel</code> <b>@PS_MOVIES1</b>\n<b>- To Connect A Group With A Channel (Bot Should Be Admin With Full Previlages In Both Group And Channel)</b>\n\n<b><u>Deleted CMD</u></b>\n ☞ <code>/delchannel</code> <b>chat_id</b>\n ☞ <code>/delchannel</code> <b>@PS_MOVIES1</b>\n<b>- To disconnect A Group With A Channel</i></b>""" AUTOFILTER_TEXT2 = """<b><u>📃 MAIN INFORMATION 📃</u></b>\n\n ☞ <b>/settings</b> - <b>This Command Will Display You A Settings Pannel Instance Which Can Be Used To Tweek Bot's Settings Accordingly</b>\n\n ☞ <b>Channel</b> - <b>Button Will Show You All The Connected Chats With The Group And Will Show Buttons Correspnding To There Order For Furthur Controls</b>\n\n ☞ <b>Filter Types</b> - <b>Button Will Show You The 3 Filter Option Available In Bot... Pressing Each Buttons Will Either Enable or Disable Them And This Will Take Into Action As Soon As You Use Them Without The Need Of A Restart</b> \n\n ☞ <b>Configure</b> - <b>Button Will Helps You To Change No. of Pages/ Buttons Per Page/ Total Result Without Acutally Editing The Repo... Also It Provide Option To Enable/Disable For Showing Invite Link In Each Results</b>""" DYNO_TEXT = """👤Total Users {}\n🧐Total Chtas {}\n🤯Total Manul Filters {}\n🕐Bot Update Time {}""" INFORMATION_TEXT = """<b><u>Extra Modes</u></b>\n\n<b>NOTE:</b>\nthese are the extra features of Donlee Robot v2\n\n<b><u>Work Only Group:</u></b>:\n\n• No inline Message\n• No Forword Message\n\n<b><u>CMD Work Only Group:</u></b>\n• /report - report To admin\n\n<b><u>Commands and Usage:</u></b>\n• /id - get id about a user and group.\n• /info - get information about a user and Group.\n• /status - Get Bot Status""" CREDITS_TEXT = """<u><b>DEV</b></u>\n• Muhammed RK\n\n<b><u>TroJanzHEX</u></b>\n• Unlimitedfilter\n<b><u>CrazyBotsz</u></b>\n• ADV AutoFilter V2\n<b><u>Bughunter</u></b>\n• Report\n• Ban\n<b><u>Professor-99</u></b>\n• Broadcast Bot\n• DonLee Robot 2.9 IMDB poster\n• Forword and Inline Delete\n• unban\n• [Refresh Button] Donlee Robot\n<b><u>EvamariaTG</u></b>\n• Evamaria IMDB Poster""" CONNECTION_TEXT = """<b><u>Connection</u></b>\n\n- Used to connect bot to PM for managing filters \n- it helps to avoid spamming in groups.\n\nNOTE:\n1. Only admins can add a connection.\n2. Send /connect for connecting me to ur PM\n\nCommands and Usage:\n• /connect - connect a particular chat to your PM\n• /disconnect - disconnect from a chat\n• /connections - list all your connections""" DEV_TEXT = """<b><u>DEVELOPER INFO</b></u>\n\n• TG Name : <a href="t.me/pazzu_s">PAZZU420</a>\n• TG Username : <a href="t.me/pazzu_s">@pazzu_s</a>\n• Github : <a href="https://t.me/PS_MOVIES1">PAZZU420</a>\n• Insta : <a href="https://t.me/PS_MOVIES1">PAZZU420</a> \n• YouTube : <a href="https://t.me/PS_MOVIES1">PS MOVIES</a> \n• Whatsapp : None\n• Facebook : Mrk-YT""" GROUP_ADMIN_TEXT = """<b><u>Group Commands</u></b>\n\n<b><u>Bot Master</u></b>\n• /broadcast - Replay Any Message\n\n<b><u>Group Admin Only</u></b>\n• /ban - Reply Any User Text\n• /unban - Reply Banned User Text""" SUB_TEXT = """JOIN, SHARE, MAXIMUM SUPPORT""" SPELLING_TEXT = """Hey {} Check Your Spelling""" STATUS_TEXT = """<b><u>Bot Status</u></b>\nTotal Users <b>{}</b>""" SOURCE_TEXT = """<b><u>🥳 SOURCE CODE</b></u>\n\n📦 REPOSITORY :- https://t.me/PS_MOVIES1📺 DEPLOY VIDEO :- https://t.me/PS_MOVIES1\n\n👩‍👩‍👧‍👧 DEVELOPER TEAM <a href="https://t.me/PS_MOVIES1">PS MOVIES</a>"""
var assert = require('assert') var tape = require('tape') var {eval: ev, quote, bind, isBoundFun} = require('../eval') var syms = require('../symbols') var parse = require('../parse') var {isNumber, stringify, pretty, isArray} = require('../util') var unroll = require('../unroll') var flatten = require('../flatten') var { isSymbol, isFun, isBasic, isFunction, isArray, stringify } = require('../util') console.log(ev) console.log('test 1') function $(name) { return Symbol(name) } var a = $('a'), b = $('b'), add = $('add'), eq = $('eq') var scope = { add:function () { return [].slice.call(arguments).reduce((a,b) => a + b) }, eq: function (a, b) { return a === b } } tape('eval an inline function call', function (t) { var code = [[syms.fun, [a, b], [add, a, b, 3]], 1, 2] console.log(ev(code, scope)) t.equal(ev(code, scope), 6) t.end() }) var x = $('x'), y = $('y') var fun = [syms.fun, [x, y], [add, x, y]] // evaluating the exact same function twice should produce // two distinct bound functions. this might happen to a function // defined inside a loop tape('separately evaled functions are not equal', function (t) { t.notStrictEqual(ev(fun, scope), ev(fun, scope)) t.end() }) function U (ast) { return [syms.unquote, ast] } function Q (ast) { return [syms.quote, ast] } var quoted = ev(Q([a, b, U([add, 1, 2])]), scope) tape('quote and unquote', function (t) { t.strictEqual(quoted[0], a) t.strictEqual(quoted[1], b) t.strictEqual(quoted[2], 3) t.end() }) console.log('test 4, macros and quotes') var mac = [syms.mac, [x], Q([syms.def, U(x), [add, U(x), 1]])] var j = $('j'), k = $('k'), tmp = $('tmp') function dehygene (src) { return src.replace(/__\d+/g, '') } tape('macro eval', function (t) { var z = $('z') var incr_z = bind([mac, z], scope) //this macro operates on a symbol passed in, //so it does not need to have added hygene t.deepEqual(stringify(incr_z), '(def z (add z 1))') t.strictEquals(incr_z[1], z, 'a symbol passed to a macro will be equal to output') t.strictEquals(incr_z[2][1], z, 'a symbol passed to a macro will be equal to output, 2') //NOTE: if you use unquote outside of quote, it will run that code //at bind time. t.deepEqual(stringify(bind([add, 1, U([add, 7, 3]) ], scope)), '(add 1 10)') t.end() }) var swap = [syms.mac, [j, k], Q([syms.block, [syms.def, tmp, U(j)], [syms.set, U(j), U(k)], [syms.set, U(k), tmp] ]) ] tape('a macro that creates an internal var should be distinct between runs', function (t) { var scope1 = {__proto__: scope} var scope2 = {__proto__: scope} var swap_ab = bind([swap, a, b], scope1) var swap_xy = bind([swap, x, y], scope2) console.log(swap_ab) console.log(swap_xy) console.log(scope1) console.log(scope2) t.equal(dehygene(swap_ab[1][1].description), dehygene(swap_xy[1][1].description)) //XXX disable for now t.notStrictEqual(swap_ab[1][1], swap_xy[1][1]) console.log(swap_ab) console.log(swap_xy) t.end() }) //what about if a quote is inside an unquote inside a quote? // %(a b $(if (lt a b) %a %b)) //i think that's fully reasonable. //for this to be possible tape('references within a scope are identical, but quoted var defs get changed', function (t) { var scope = {} var ast = parse('(quote (block (def foo 1) (add foo (def bar 3)) ))') t.strictEquals(ast[1][1][1].description, ast[1][2][1].description) var _ast = ev(ast, scope) t.notEquals(dehygene(stringify(_ast)), stringify(_ast)) t.equals(dehygene(stringify(_ast)), '(block (def foo 1) (add foo (def bar 3)))') t.end() }) tape('what happens if a macro calls another macro?', function (t) { var scope = { add: function () { return [].slice.call(arguments).reduce((a, b)=>a+b, 0) }, sub: function () { return [].slice.call(arguments).reduce((a, b)=>a-b, 0) } } var src = ` (block (def defun (mac (name args body) &(def $name (fun $name $args $body)) )) (def defmac (mac (name args body) &(def $name (mac $name $args $body)) )) (defmac incr [x] &(set $x (add $x 1))) (defmac decr [x] &(set $x (sub $x 1))) ;;defun can still be self evaluating! [(defun three (z) {block (def y z) (incr y) (incr y) (incr y) }) 3] )` var ast = parse(src) var name1 = ast[1][2][1][0] t.equal(name1.description, 'name') var name2 = ast[1][2][2][1][1][1] t.equal(name2.description, 'name') //t.strictEqual(name1, name2) //t.ok(name1===name2) var name3 = ast[1][2][2] [1][2][1][1] t.equal(name3.description, 'name') //t.strictEqual(name1, name3) //t.ok(name1===name3) t.equal(ev(ast, scope), 6) t.end() }) tape('if a macro creates a var does not collide', function (t) { var scope = { assert: function (x) { if(!x) throw new Error('assertion failed:' + x) }, eq: function (a, b) { console.log('eq?', a, b); return a === b } } var src = ` (block (def defun (mac (name args body) &(def $name (fun $name $args $body)) )) (def defmac (mac (name args body) &(def $name (mac $name $args $body)) )) (defmac swap [x y] &(block (def tmp $x) (set $x $y) (set $y tmp) )) (defun swapsies (z) {block (def a 1) (def b 2) (def tmp 7) (swap a b) (assert (eq a 2)) (assert (eq b 1)) (assert (eq tmp 7)) (list a b tmp) }) )` var ast = parse(src) var swapsies = Symbol('swapsies') var _swap = ev(ast, scope) console.log(stringify(_swap.slice(0, 4))) console.log(_swap[3][1][1], _swap[3][4][1][2]) t.equal(_swap[3][1][1].description, _swap[3][4][1][2].description) var _scope = {swapsies: _swap, __proto__: scope} t.deepEqual(ev([swapsies, 0], _scope), [2,1,7]) t.end() }) tape('unroll', function (t) { var src = ` (block (def defun (mac (name args body) &(def $name (fun $name $args $body)) )) (defun foo (a) {add a a a}) (defun foofoo (b) {foo {foo b}}) ;; a function that has a inline function and a reference! (defun bar (x) [{fun (y) [if y (foofoo y) (foo y)]} x]) )` var ast = parse(src) var result = ev(ast, scope) var syms = require('../symbols') var unrolled = unroll(result) var Wat = require('../compile/wat') var wat = Wat(unrolled) t.equal(require('../wat2wasm')(wat)(4), 36) t.end() })
/********************************************************************************************/ /********************************************************************************************/ #include "sys_types.h" #include "sys_define.h" #include "stdio.h" #include "string.h" #include "stdlib.h" #include "assert.h" #include "drv_dev.h" #include "mtos_misc.h" #include "mtos_task.h" #include "mtos_sem.h" #include "mtos_printk.h" #include "mtos_mem.h" #include "mtos_fifo.h" #include "mtos_msg.h" #include "class_factory.h" #include "lib_memf.h" #include "lib_memp.h" #include "lib_rect.h" #include "lib_unicode.h" #include "common.h" #include "osd.h" #include "gpe.h" #include "gpe_vsb.h" #include "mdl.h" #include "mmi.h" #include "surface.h" #include "flinger.h" #include "gdi.h" #include "gdi_dc.h" #include "gdi_anim.h" #include "gui_resource.h" #include "gdi_private.h" RET_CODE dc_enter_drawing(dc_t *p_dc) { if(!intersect_rect(&p_dc->rc_output, &p_dc->rc_output, &p_dc->ecrgn.bound)) { return ERR_FAILURE; } if(dc_is_virtual_dc(p_dc)) { if(!is_rect_intersected(&p_dc->vtrl_rc, &p_dc->rc_output)) { return ERR_FAILURE; } } return SUCCESS; } void dc_leave_drawing(dc_t *p_dc) { } static void init_screen_dc(void) { gdi_main_t *p_gdi_info = NULL; rect_t *p_flinger_rect = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { p_gdi_info->top.screen_dc.type = TYPE_SCREEN; p_gdi_info->top.screen_dc.p_curn_flinger = p_gdi_info->top.p_flinger; p_gdi_info->top.screen_dc.p_back_flinger = NULL; gdi_init_cliprgn(&p_gdi_info->top.screen_dc.lcrgn, &p_gdi_info->cliprc_heap); gdi_init_cliprgn(&p_gdi_info->top.screen_dc.ecrgn, &p_gdi_info->cliprc_heap); p_gdi_info->top.screen_dc.p_gcrgn_info = NULL; p_flinger_rect = flinger_get_rect(p_gdi_info->top.p_flinger); p_gdi_info->top.screen_dc.dev_rc.left = p_gdi_info->top.screen_dc.dev_rc.top = 0; p_gdi_info->top.screen_dc.dev_rc.right = RECTWP(p_flinger_rect); p_gdi_info->top.screen_dc.dev_rc.bottom = RECTHP(p_flinger_rect); gdi_set_cliprgn(&p_gdi_info->top.screen_dc.lcrgn, &p_gdi_info->top.screen_dc.dev_rc); gdi_set_cliprgn(&p_gdi_info->top.screen_dc.ecrgn, &p_gdi_info->top.screen_dc.dev_rc); } if(p_gdi_info->bot.p_flinger != NULL) { p_gdi_info->bot.screen_dc.type = TYPE_SCREEN; p_gdi_info->bot.screen_dc.p_curn_flinger = p_gdi_info->bot.p_flinger; p_gdi_info->bot.screen_dc.p_back_flinger = NULL; gdi_init_cliprgn(&p_gdi_info->bot.screen_dc.lcrgn, &p_gdi_info->cliprc_heap); gdi_init_cliprgn(&p_gdi_info->bot.screen_dc.ecrgn, &p_gdi_info->cliprc_heap); p_gdi_info->bot.screen_dc.p_gcrgn_info = NULL; p_flinger_rect = flinger_get_rect(p_gdi_info->bot.p_flinger); p_gdi_info->bot.screen_dc.dev_rc.left = p_gdi_info->bot.screen_dc.dev_rc.top = 0; p_gdi_info->bot.screen_dc.dev_rc.right = RECTWP(p_flinger_rect); p_gdi_info->bot.screen_dc.dev_rc.bottom = RECTHP(p_flinger_rect); gdi_set_cliprgn(&p_gdi_info->bot.screen_dc.lcrgn, &p_gdi_info->bot.screen_dc.dev_rc); gdi_set_cliprgn(&p_gdi_info->bot.screen_dc.ecrgn, &p_gdi_info->bot.screen_dc.dev_rc); } } static void dc_init_cliprgn(void) { int i = 0; gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); for(i = 0; i < p_gdi_info->dc_slot_cnt; i++) { gdi_init_cliprgn(&p_gdi_info->p_dc_slot[i].lcrgn, &p_gdi_info->cliprc_heap); p_gdi_info->p_dc_slot[i].p_gcrgn_info = NULL; gdi_init_cliprgn(&p_gdi_info->p_dc_slot[i].ecrgn, &p_gdi_info->cliprc_heap); } } static void dc_init(dc_t *p_dc, rect_t *p_rc, crgn_info_t *p_gcrgn_info) { if(dc_is_general_dc(p_dc)) { p_dc->p_gcrgn_info = p_gcrgn_info; LOCK_GCRINFO(p_dc); if(p_dc->p_gcrgn_info != NULL) { gdi_copy_cliprgn(&p_dc->ecrgn, &p_dc->p_gcrgn_info->crgn); } else { gdi_set_cliprgn(&p_dc->ecrgn, p_rc); } p_dc->dev_rc = *p_rc; gdi_intersect_cliprect(&p_dc->ecrgn, p_rc); UNLOCK_GCRINFO(p_dc); } else if(dc_is_mem_dc(p_dc)) { p_dc->p_gcrgn_info = p_gcrgn_info; LOCK_GCRINFO(p_dc); gdi_set_cliprgn(&p_dc->ecrgn, p_rc); p_dc->dev_rc = *p_rc; UNLOCK_GCRINFO(p_dc); } } // this function generates effective clip region from // local clip region and global clip region. // if the global clip region has a new age, // this function empty effective clip region first, // and then intersect local clip region and global clip region. BOOL dc_generate_ecrgn(dc_t *p_dc, BOOL is_is_force) { cliprc_t *p_cr = NULL; // is global clip region is empty? if((!is_is_force) && (!dc_is_visible(p_dc))) { return FALSE; } // need regenerate? if(is_is_force) { /* copy local clipping region to effective clipping region. */ gdi_copy_cliprgn(&p_dc->ecrgn, &p_dc->lcrgn); /* transfer device coordinates to screen coordinates. */ p_cr = p_dc->ecrgn.p_head; while(NULL != p_cr) { coor_dp2sp(p_dc, &p_cr->rc.left, &p_cr->rc.top); coor_dp2sp(p_dc, &p_cr->rc.right, &p_cr->rc.bottom); p_cr = p_cr->p_next; } coor_dp2sp(p_dc, &p_dc->ecrgn.bound.left, &p_dc->ecrgn.bound.top); coor_dp2sp(p_dc, &p_dc->ecrgn.bound.right, &p_dc->ecrgn.bound.bottom); /* intersect with global clipping region. */ if(p_dc->lcrgn.p_head == NULL) { if(p_dc->p_gcrgn_info != NULL) { gdi_copy_cliprgn(&p_dc->ecrgn, &p_dc->p_gcrgn_info->crgn); } else { gdi_set_cliprgn(&p_dc->ecrgn, &p_dc->dev_rc); } } else { if(p_dc->p_gcrgn_info != NULL) { gdi_intersect_cliprgn( &p_dc->ecrgn, &p_dc->ecrgn, &p_dc->p_gcrgn_info->crgn); } } /* * update p_dc->dev_rc, and restrict the effective * clipping region more with p_dc->dev_rc. */ gdi_intersect_cliprect(&p_dc->ecrgn, &p_dc->dev_rc); } return TRUE; } void dc_reset_lcrgn(dc_t *p_dc) { if(p_dc->lcrgn.p_head == NULL) { rect_t rc; set_rect(&rc, 0, 0, 0x7FFF, 0x7FFF); gdi_set_cliprgn(&p_dc->lcrgn, &rc); } } BOOL gdi_init(gdi_cfg_t *p_config) { u32 slice = 0; u32 size = 0; class_handle_t p_gdi_handle = NULL; gdi_main_t *p_gdi_info = NULL; flinger_param_t param = {0}; p_gdi_handle = (void *)mmi_alloc_buf(sizeof(gdi_main_t)); memset((void *)p_gdi_handle, 0, sizeof(gdi_main_t)); class_register(GDI_CLASS_ID, p_gdi_handle); p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); slice = sizeof(cliprc_t); size = slice * p_config->max_cliprect_cnt; p_gdi_info->p_cliprc_heap_addr = mmi_create_memf(&p_gdi_info->cliprc_heap, p_config->max_cliprect_cnt, slice); MT_ASSERT(p_gdi_info->p_cliprc_heap_addr != NULL); size = sizeof(dc_t) * p_config->max_dc_cnt; p_gdi_info->p_dc_slot = (dc_t *)mmi_alloc_buf(size); MT_ASSERT(p_gdi_info->p_dc_slot != NULL); memset(p_gdi_info->p_dc_slot, 0, size); p_gdi_info->dc_slot_cnt = p_config->max_dc_cnt; dc_init_cliprgn(); MT_ASSERT(p_config->p_screen_rect != NULL); copy_rect(&p_gdi_info->screen_rect, p_config->p_screen_rect); //create top flinger. if(p_config->p_top != NULL) { param.cdef = p_config->cdef; param.ckey = p_config->ckey; param.format = p_config->format; param.p_pal = p_config->p_pal; param.p_cfg = p_config->p_top; param.p_flinger_rect = p_config->p_screen_rect; p_gdi_info->top.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->top.p_flinger != NULL); p_gdi_info->top.layer = p_config->p_top->layer; } //create bottom flinger. if(p_config->p_bot != NULL) { param.cdef = p_config->cdef; param.ckey = p_config->ckey; param.format = p_config->format; param.p_pal = p_config->p_pal; param.p_cfg = p_config->p_bot; param.p_flinger_rect = p_config->p_screen_rect; p_gdi_info->bot.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); p_gdi_info->bot.layer = p_config->p_bot->layer; } if(p_config->p_pal != NULL) { p_gdi_info->global_pal.cnt = p_config->p_pal->cnt; p_gdi_info->global_pal.p_entry = p_config->p_pal->p_entry; } p_gdi_info->screen_format = p_config->format; p_gdi_info->screen_cdef = p_config->cdef; p_gdi_info->screen_ckey = p_config->ckey; init_screen_dc(); gdi_init_vsurf(p_config->vsurf_buf_addr, p_config->vsurf_buf_size); gdi_init_anim(p_config->anim_addr, p_config->anim_size); return TRUE; } void gdi_release(void) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); gdi_release_vsurf(); gdi_release_anim(); mmi_free_buf(p_gdi_info->p_dc_slot); mmi_destroy_memf(&p_gdi_info->cliprc_heap, p_gdi_info->p_cliprc_heap_addr); p_gdi_info->p_cliprc_heap_addr = NULL; mmi_free_buf((void *)p_gdi_info); } BOOL gdi_reset_screen(screen_reset_t *p_scr_reset) { gdi_main_t *p_gdi_info = NULL; flinger_param_t param = {0}; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); p_gdi_info->screen_format = p_scr_reset->format; p_gdi_info->screen_cdef = p_scr_reset->cdef; p_gdi_info->screen_ckey = p_scr_reset->ckey; if(p_scr_reset->p_pal != NULL) { p_gdi_info->global_pal.cnt = p_scr_reset->p_pal->cnt; p_gdi_info->global_pal.p_entry = p_scr_reset->p_pal->p_entry; } //delete original flinger if(p_gdi_info->top.p_flinger != NULL) { flinger_enable(p_gdi_info->top.p_flinger, FALSE); flinger_set_display(p_gdi_info->top.p_flinger, FALSE); flinger_delete(p_gdi_info->top.p_flinger); } if(p_gdi_info->bot.p_flinger != NULL) { flinger_enable(p_gdi_info->bot.p_flinger, FALSE); flinger_set_display(p_gdi_info->bot.p_flinger, FALSE); flinger_delete(p_gdi_info->bot.p_flinger); } mtos_task_delay_ms(50); MT_ASSERT(p_scr_reset->p_screen_rect != NULL); copy_rect(&p_gdi_info->screen_rect, p_scr_reset->p_screen_rect); //create top flinger. if(p_scr_reset->p_top != NULL) { param.cdef = p_scr_reset->cdef; param.ckey = p_scr_reset->ckey; param.format = p_scr_reset->format; param.p_pal = p_scr_reset->p_pal; param.p_cfg = p_scr_reset->p_top; param.p_flinger_rect = p_scr_reset->p_screen_rect; p_gdi_info->top.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->top.p_flinger != NULL); p_gdi_info->top.layer = p_scr_reset->p_top->layer; gdi_empty_cliprgn(&p_gdi_info->top.screen_dc.lcrgn); gdi_empty_cliprgn(&p_gdi_info->top.screen_dc.ecrgn); flinger_set_alpha(p_gdi_info->top.p_flinger, 0xFF); } //create bottom flinger. if(p_scr_reset->p_bot != NULL) { param.cdef = p_scr_reset->cdef; param.ckey = p_scr_reset->ckey; param.format = p_scr_reset->format; param.p_pal = p_scr_reset->p_pal; param.p_cfg = p_scr_reset->p_bot; param.p_flinger_rect = p_scr_reset->p_screen_rect; p_gdi_info->bot.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); p_gdi_info->bot.layer = p_scr_reset->p_bot->layer; gdi_empty_cliprgn(&p_gdi_info->bot.screen_dc.lcrgn); gdi_empty_cliprgn(&p_gdi_info->bot.screen_dc.ecrgn); flinger_set_alpha(p_gdi_info->bot.p_flinger, 0xFF); } //init screen dc init_screen_dc(); return TRUE; } BOOL gdi_reset_screen_and_scale(screen_reset_t *p_scr_reset, void (*reset_cb)(void *)) { gdi_main_t *p_gdi_info = NULL; flinger_param_t param = {0}; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); p_gdi_info->screen_format = p_scr_reset->format; p_gdi_info->screen_cdef = p_scr_reset->cdef; p_gdi_info->screen_ckey = p_scr_reset->ckey; if(p_scr_reset->p_pal != NULL) { p_gdi_info->global_pal.cnt = p_scr_reset->p_pal->cnt; p_gdi_info->global_pal.p_entry = p_scr_reset->p_pal->p_entry; } //delete original flinger if(p_gdi_info->top.p_flinger != NULL) { flinger_enable(p_gdi_info->top.p_flinger, FALSE); flinger_set_display(p_gdi_info->top.p_flinger, FALSE); flinger_delete(p_gdi_info->top.p_flinger); } if(p_gdi_info->bot.p_flinger != NULL) { flinger_enable(p_gdi_info->bot.p_flinger, FALSE); flinger_set_display(p_gdi_info->bot.p_flinger, FALSE); flinger_delete(p_gdi_info->bot.p_flinger); } mtos_task_delay_ms(50); if(reset_cb != NULL) { reset_cb((void *)(p_scr_reset->p_screen_rect)); } //create top flinger. if(p_scr_reset->p_top != NULL) { param.cdef = p_scr_reset->cdef; param.ckey = p_scr_reset->ckey; param.format = p_scr_reset->format; param.p_pal = p_scr_reset->p_pal; param.p_cfg = p_scr_reset->p_top; param.p_flinger_rect = p_scr_reset->p_screen_rect; p_gdi_info->top.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->top.p_flinger != NULL); p_gdi_info->top.layer = p_scr_reset->p_top->layer; gdi_empty_cliprgn(&p_gdi_info->top.screen_dc.lcrgn); gdi_empty_cliprgn(&p_gdi_info->top.screen_dc.ecrgn); } //create bottom flinger. if(p_scr_reset->p_bot != NULL) { param.cdef = p_scr_reset->cdef; param.ckey = p_scr_reset->ckey; param.format = p_scr_reset->format; param.p_pal = p_scr_reset->p_pal; param.p_cfg = p_scr_reset->p_bot; param.p_flinger_rect = p_scr_reset->p_screen_rect; p_gdi_info->bot.p_flinger = flinger_create(&param); MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); p_gdi_info->bot.layer = p_scr_reset->p_bot->layer; gdi_empty_cliprgn(&p_gdi_info->bot.screen_dc.lcrgn); gdi_empty_cliprgn(&p_gdi_info->bot.screen_dc.ecrgn); } //init screen dc init_screen_dc(); return TRUE; } void gdi_release_screen(void) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { flinger_delete(p_gdi_info->top.p_flinger); p_gdi_info->top.p_flinger = NULL; } if(p_gdi_info->bot.p_flinger != NULL) { flinger_delete(p_gdi_info->bot.p_flinger); p_gdi_info->bot.p_flinger = NULL; } } void gdi_clear_screen(void) { rect_t orc = {0}; gdi_main_t *p_gdi_info = NULL; rect_t *p_flinger_rect = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { p_flinger_rect = flinger_get_rect(p_gdi_info->top.p_flinger); set_rect(&orc, 0, 0, RECTWP(p_flinger_rect), RECTHP(p_flinger_rect)); flinger_set_cliprect(p_gdi_info->top.p_flinger, NULL); flinger_fill_rect(p_gdi_info->top.p_flinger, &orc, p_gdi_info->screen_cdef); } if(p_gdi_info->bot.p_flinger != NULL) { p_flinger_rect = flinger_get_rect(p_gdi_info->bot.p_flinger); set_rect(&orc, 0, 0, RECTWP(p_flinger_rect), RECTHP(p_flinger_rect)); flinger_set_cliprect(p_gdi_info->bot.p_flinger, NULL); flinger_fill_rect(p_gdi_info->bot.p_flinger, &orc, p_gdi_info->screen_cdef); } } void gdi_clear_top_screen(void) { rect_t orc = {0}; gdi_main_t *p_gdi_info = NULL; rect_t *p_flinger_rect = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { p_flinger_rect = flinger_get_rect(p_gdi_info->top.p_flinger); set_rect(&orc, 0, 0, RECTWP(p_flinger_rect), RECTHP(p_flinger_rect)); flinger_set_cliprect(p_gdi_info->top.p_flinger, NULL); flinger_fill_rect(p_gdi_info->top.p_flinger, &orc, p_gdi_info->screen_cdef); } } void gdi_reset_trans(void) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { flinger_set_trans(p_gdi_info->top.p_flinger, p_gdi_info->screen_cdef, 0); } if(p_gdi_info->top.p_flinger != NULL) { flinger_set_trans(p_gdi_info->bot.p_flinger, p_gdi_info->screen_cdef, 0); } } lib_memf_t *gdi_get_cliprc_heap(void) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); return &p_gdi_info->cliprc_heap; } handle_t gdi_get_screen_handle(BOOL is_top_screen) { gdi_main_t *p_gdi_info = NULL; handle_t screen_handle = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(is_top_screen) { MT_ASSERT(p_gdi_info->top.p_flinger != NULL); screen_handle = (handle_t)flinger_get_surface(p_gdi_info->top.p_flinger, 0); } else { MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); screen_handle = (handle_t)flinger_get_surface(p_gdi_info->bot.p_flinger, 0); } return screen_handle; } void gdi_set_global_alpha(u8 alpha) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { flinger_set_alpha(p_gdi_info->top.p_flinger, alpha); } if(p_gdi_info->bot.p_flinger != NULL) { flinger_set_alpha(p_gdi_info->bot.p_flinger, alpha); } } void gdi_set_enable(BOOL is_enable) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { flinger_set_display(p_gdi_info->top.p_flinger, is_enable); } if(p_gdi_info->bot.p_flinger != NULL) { flinger_set_display(p_gdi_info->bot.p_flinger, is_enable); } } BOOL gdi_offset_screen(s16 x_off, s16 y_off) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { flinger_offset(p_gdi_info->top.p_flinger, x_off, y_off); } if(p_gdi_info->bot.p_flinger != NULL) { flinger_offset(p_gdi_info->bot.p_flinger, x_off, y_off); } return TRUE; } BOOL gdi_move_screen(s16 x, s16 y) { rect_t *p_flinger_rect = NULL; gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); if(p_gdi_info->top.p_flinger != NULL) { p_flinger_rect = flinger_get_rect(p_gdi_info->top.p_flinger); flinger_offset(p_gdi_info->top.p_flinger, x - p_flinger_rect->left, y - p_flinger_rect->top); } if(p_gdi_info->bot.p_flinger != NULL) { p_flinger_rect = flinger_get_rect(p_gdi_info->bot.p_flinger); flinger_offset(p_gdi_info->bot.p_flinger, x - p_flinger_rect->left, y - p_flinger_rect->top); return TRUE; } return FALSE; } pix_type_t gdi_get_screen_pixel_type(void) { gdi_main_t *p_gdi_info = NULL; pix_type_t screen_format = 0; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); screen_format = p_gdi_info->screen_format; return screen_format; } void gdi_get_screen_rect(rect_t *p_rc) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); MT_ASSERT(p_rc != NULL); copy_rect(p_rc, &p_gdi_info->screen_rect); } hdc_t gdi_get_dc(BOOL is_top, rect_t *p_src, rect_t *p_vrc, crgn_info_t *p_gcrgn_info, hdc_t parent) { int i = 0; dc_t *p_cdc = NULL; dc_t *p_pdc = dc_hdc2pdc(parent); gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); MT_ASSERT(p_gdi_info != NULL); for(i = 0; i < p_gdi_info->dc_slot_cnt; i++) { p_cdc = &p_gdi_info->p_dc_slot[i]; if(!p_cdc->is_used) { p_cdc->is_used = TRUE; if(p_pdc == NULL) { p_cdc->type = TYPE_GENERAL; if(is_top && (p_gdi_info->top.p_flinger != NULL)) { MT_ASSERT(p_gdi_info->top.p_flinger != NULL); p_cdc->p_curn_flinger = p_gdi_info->top.p_flinger; p_cdc->type |= TYPE_TOP; } else { MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); p_cdc->p_curn_flinger = p_gdi_info->bot.p_flinger; p_cdc->type &= (~TYPE_TOP); } p_cdc->p_back_flinger = NULL; copy_rect(&p_cdc->vtrl_rc, p_vrc); // try to create virtual surface if(gdi_create_vsurf((hdc_t)p_cdc, (s16)RECTWP(p_vrc), (s16)RECTHP(p_vrc)) == SUCCESS) { u32 cck = 0; // initialise virtual device rect //copy_rect(&p_cdc->vtrl_rc, p_vrc); // disable cck cck = flinger_get_colorkey(p_cdc->p_back_flinger); flinger_set_colorkey(p_cdc->p_back_flinger, SURFACE_INVALID_COLORKEY); // copy actual bits to virtual surface flinger_bitblt(p_cdc->p_back_flinger, p_vrc->left, p_vrc->top, RECTWP(p_vrc), RECTHP(p_vrc), p_cdc->p_curn_flinger, 0, 0, FLINGER_ROP_SET, 0); // enable ckk, again flinger_set_colorkey(p_cdc->p_back_flinger, cck); } // start gpe batch, if dc type is general gdi_start_batch(is_top && (p_gdi_info->top.p_flinger != NULL)); } else { p_cdc->type = p_pdc->type | TYPE_INHERIT; p_cdc->p_curn_flinger = p_pdc->p_curn_flinger; p_cdc->p_back_flinger = NULL; // chk, if need to update the first vitrual dev rect if(p_pdc->type & TYPE_VIRTUAL) { copy_rect(&p_cdc->vtrl_rc, &p_pdc->vtrl_rc); } } break; } } if(i >= p_gdi_info->dc_slot_cnt) { return HDC_INVALID; } dc_init(&p_gdi_info->p_dc_slot[i], p_src, p_gcrgn_info); return (hdc_t)(&p_gdi_info->p_dc_slot[i]); } void gdi_release_dc(hdc_t hdc) { dc_t *p_dc = dc_hdc2pdc(hdc); // chk, if need update if((p_dc->type & TYPE_VIRTUAL) && !(p_dc->type & TYPE_INHERIT)) { void *p_src_flinger = NULL; void *p_dst_flinger = NULL; rect_t orc = {0}, eff_rc = {0}; cliprc_t *p_crc = NULL; BOOL is_vsurf_delete = FALSE; p_src_flinger = p_dc->p_curn_flinger, p_dst_flinger = p_dc->p_back_flinger; // bitblt to the target dc // chk, lock rgn if(dc_is_general_dc(p_dc)) { LOCK_GCRINFO(p_dc); if(!dc_generate_ecrgn(p_dc, FALSE)) { UNLOCK_GCRINFO(p_dc); //delete vsurf. gdi_delete_vsurf(hdc); is_vsurf_delete = TRUE; } } if(!is_vsurf_delete) { /* virtual device coordinate is already screen coordinate, so, it don't need to convert */ copy_rect(&orc, &p_dc->vtrl_rc); /* set output rect */ copy_rect(&p_dc->rc_output, &orc); normalize_rect(&p_dc->rc_output); //ENTER_DRAWING(p_dc); if(dc_enter_drawing(p_dc) >= 0) { p_crc = p_dc->ecrgn.p_head; while(NULL != p_crc) { if(intersect_rect(&eff_rc, &p_dc->rc_output, &p_crc->rc)) { flinger_set_cliprect(p_dst_flinger, &eff_rc); flinger_bitblt(p_src_flinger, 0, 0, (u16)RECTW(orc), (u16)RECTH( orc), p_dst_flinger, (u16)orc.left, (u16)orc.top, FLINGER_ROP_SET, 0); } p_crc = p_crc->p_next; } #ifdef CACHE_ON extern void flush_dcache_all(); flush_dcache_all(); #endif /* disable clipper */ flinger_set_cliprect(p_dc->p_curn_flinger, NULL); //LEAVE_DRAWING(p_dc); dc_leave_drawing(p_dc); } UNLOCK_GCRINFO(p_dc); // delete virtual surface gdi_delete_vsurf(hdc); } } if(p_dc->type & TYPE_GENERAL && !(p_dc->type & TYPE_INHERIT)) /* is parent dc */ { // end gpe batch, if dc type is general gdi_end_batch((BOOL)(p_dc->type & TYPE_TOP), TRUE, &p_dc->ecrgn.bound); //gdi_end_batch(TRUE, &p_dc->dev_rc); } #ifdef CACHE_ON extern void flush_dcache_all(); if(p_dc->type & TYPE_GENERAL) /* is parent dc */ { flush_dcache_all(); } #endif gdi_empty_cliprgn(&p_dc->lcrgn); gdi_empty_cliprgn(&p_dc->ecrgn); p_dc->p_gcrgn_info = NULL; p_dc->is_used = FALSE; } void gdi_release_anim_dc(hdc_t hdc) { dc_t *p_dc = dc_hdc2pdc(hdc); if(!dc_is_anim_hdc(hdc)) { return; } if((p_dc->type & TYPE_VIRTUAL) && !(p_dc->type & TYPE_INHERIT)) { gdi_delete_vsurf(hdc); } if(p_dc->type & TYPE_ANIM) { gdi_delete_anim_surf(hdc); } gdi_empty_cliprgn(&p_dc->lcrgn); gdi_empty_cliprgn(&p_dc->ecrgn); p_dc->p_gcrgn_info = NULL; p_dc->is_used = FALSE; if(p_dc->anim_handle != NULL) { anim_free(p_dc->anim_handle); p_dc->anim_handle = NULL; } } void gdi_select_cliprgn(hdc_t hdc, const cliprgn_t *p_rgn) { dc_t *p_dc = NULL; p_dc = dc_hdc2pdc(hdc); if(dc_is_general_dc(p_dc)) { gdi_copy_cliprgn(&p_dc->lcrgn, p_rgn); /* for general DC, regenerate effective region. */ LOCK_GCRINFO(p_dc); dc_generate_ecrgn(p_dc, TRUE); UNLOCK_GCRINFO(p_dc); } else { gdi_copy_cliprgn(&p_dc->ecrgn, p_rgn); gdi_intersect_cliprect(&p_dc->ecrgn, &p_dc->dev_rc); } } typedef void (*fill_func_t)(void *p_flinger, rect_t *p_rc, u32 color); static void _fill_x_rect(hdc_t hdc, rect_t *p_rc, u32 color, fill_func_t p_fill_func) { dc_t *p_dc = NULL; cliprc_t *p_clip_rc = NULL; rect_t eff_rc, orc = *p_rc; if(RECTW(orc) <= 0 || RECTH(orc) <= 0) { return; } p_dc = dc_hdc2pdc(hdc); // chk, lock rgn if(dc_is_general_dc(p_dc)) { LOCK_GCRINFO(p_dc); if(!dc_generate_ecrgn(p_dc, FALSE)) { UNLOCK_GCRINFO(p_dc); return; } } /* transfer device coordinate to screen coordinate. */ coor_dp2sp(p_dc, &orc.left, &orc.top); coor_dp2sp(p_dc, &orc.right, &orc.bottom); copy_rect(&p_dc->rc_output, &orc); normalize_rect(&p_dc->rc_output); p_dc->cur_pixel = color; if(dc_enter_drawing(p_dc) < 0) { UNLOCK_GCRINFO(p_dc); return; } /* transfer screen coordinate to surface coordinate. */ coor_sp2sp(p_dc, &orc.left, &orc.top); coor_sp2sp(p_dc, &orc.right, &orc.bottom); normalize_rect(&orc); p_clip_rc = p_dc->ecrgn.p_head; while(NULL != p_clip_rc) { if(intersect_rect(&eff_rc, &p_dc->rc_output, &p_clip_rc->rc)) { /* transfer screen coordinate to surface coordinate. */ coor_sp2sp(p_dc, &eff_rc.left, &eff_rc.top); coor_sp2sp(p_dc, &eff_rc.right, &eff_rc.bottom); normalize_rect(&eff_rc); flinger_set_cliprect(p_dc->p_curn_flinger, &eff_rc); p_fill_func(p_dc->p_curn_flinger, &orc, p_dc->cur_pixel); } p_clip_rc = p_clip_rc->p_next; } /* disable clipper */ flinger_set_cliprect(p_dc->p_curn_flinger, NULL); //LEAVE_DRAWING(p_dc); dc_leave_drawing(p_dc); UNLOCK_GCRINFO(p_dc); } /* * fills a rectangle box. */ void gdi_fill_rect(hdc_t hdc, rect_t *p_rc, u32 color) { _fill_x_rect(hdc, p_rc, color, flinger_fill_rect); } u8 gdi_get_bpp(pix_type_t format) { u8 bpp = 0; switch(format) { case COLORFORMAT_RGB4BIT: bpp = 4; break; case COLORFORMAT_RGB8BIT: bpp = 8; break; case COLORFORMAT_RGB565: case COLORFORMAT_RGBA5551: case COLORFORMAT_ARGB1555: bpp = 16; break; case COLORFORMAT_RGBA8888: case COLORFORMAT_ARGB8888: bpp = 32; break; default: bpp = 0; MT_ASSERT(0); } return bpp; } void gdi_start_batch(BOOL is_top_screen) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); if(is_top_screen) { MT_ASSERT(p_gdi_info->top.p_flinger != NULL); flinger_start_batch(p_gdi_info->top.p_flinger); } else { MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); flinger_start_batch(p_gdi_info->bot.p_flinger); } } void gdi_end_batch(BOOL is_top_screen, BOOL is_sync, rect_t *p_rect) { gdi_main_t *p_gdi_info = NULL; p_gdi_info = (gdi_main_t *)class_get_handle_by_id(GDI_CLASS_ID); if(is_top_screen) { MT_ASSERT(p_gdi_info->top.p_flinger != NULL); flinger_end_batch(p_gdi_info->top.p_flinger, is_sync, p_rect); } else { MT_ASSERT(p_gdi_info->bot.p_flinger != NULL); flinger_end_batch(p_gdi_info->bot.p_flinger, is_sync, p_rect); } }
from acme import Product import random ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(n=30, price_range=(5, 10), weight_range=(5, 100)): """Generate n number of products within a specified price and weight range""" products = [] for i in range(1, n + 1): name = random.choice(ADJECTIVES) + ' ' + random.choice(NOUNS) price = random.randrange(price_range[0], price_range[1] + 1) weight = random.randrange(weight_range[0], weight_range[1] + 1) flammability = random.uniform(0.0, 2.5) product = Product(name, price, weight, flammability) products.append(product) return products def inventory_report(prod_list): """Creates an inventory report for a given product list""" prod_list = list(set(prod_list)) x = 0 price = 0 weight = 0 flammability = 0 stealability = 0 for item in prod_list: x += 1 price += item.price weight += item.weight flammability += item.flammability if stealability != 'Not so stealable...': stealability += 1 avg_price = price / x avg_weight = weight / x avg_flammability = flammability / x print(f'There are {x} unique products in this list. The average price is {avg_price}, ' f'average weight is {avg_weight},' f'and the average flammability is {avg_flammability}.') if stealability >= len(prod_list) / 2: print('Many of these items are highly stealable!') return avg_price, avg_weight, avg_flammability if __name__ == '__main__': inventory_report(generate_products())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python 3 script # Author : Aymeric LAMBRECHT import xml.etree.ElementTree as etree import uuid, subprocess, os.path, argparse, sys, logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s|%(levelname)s|%(funcName)s: %(message)s', datefmt='%H:%M:%S') DESCRIPTION = "Script to update categories of xmltv files for TVHeadend" parser = argparse.ArgumentParser(description = DESCRIPTION) requiredNamed = parser.add_argument_group('required named arguments') requiredNamed.add_argument('--xmltv', dest="XMLTV_PATH", help='Path of XMLTV File to list categories', action="store", type=str, default='', required=True) args = parser.parse_args() match_category = {} def init_categories(): # Correspondance chaines match_category['autre'] = 'Others' match_category['clips'] = 'Music / Ballet / Dance' match_category['classique'] = 'Serious / Classical / Religious / Historical movie / Drama' match_category['cérémonie'] = 'News / Current affairs' match_category['cirque'] = 'Sports' match_category['chorégraphique'] = 'Music / Ballet / Dance' match_category['concert'] = 'Music / Ballet / Dance' match_category['cyclisme'] = 'Sports' match_category['ballet'] = 'Music / Ballet / Dance' match_category['débat'] = 'Social / Political issues / Economics' match_category['dessin animé'] = 'Social / Political issues / Economics' match_category['divertissement'] = 'Show / Game show' match_category['divertissement-humour'] = 'Show / Game show' match_category['divers'] = 'Variety show' match_category['documentaire'] = 'Education / Science / Factual topics' match_category['Émission'] = 'Show / Game show' match_category['feuilleton'] = 'Movie / Drama' match_category['humour'] = 'Comedy' match_category['film'] = 'Movie / Drama' match_category['fitness'] = 'Fitness and health' match_category['fin'] = 'fin' match_category['hippisme'] = 'Sports' match_category['interview'] = 'Show / Game show' match_category['jazz'] = 'Jazz' match_category['jeu'] = 'News / Current affairs' match_category['jeunesse'] = 'Children\'s / Youth programmes' match_category['journal'] = 'News / Current affairs' match_category['kick-boxing'] = 'Sports' match_category['loterie'] = 'Show / Game show' match_category['météo'] = 'News / Current affairs' match_category['magazine'] = 'Education / Science / Factual topics' match_category['marathon'] = 'Sports' match_category['opéra'] = 'Arts / Culture (without music)' match_category['oratorio'] = 'Arts / Culture (without music)' match_category['politique'] = 'Social / Political issues / Economics' match_category['programme indéterminé'] = 'Others' match_category['pop'] = 'Rock / Pop' match_category['rap'] = 'Music / Ballet / Dance' match_category['reggae'] = 'Folk / Traditional music' match_category['rock'] = 'Rock / Pop' match_category['série'] = 'Movie / Drama' match_category['spectacle'] = 'Arts / Culture (without music)' match_category['sport'] = 'Sports' match_category['talk show'] = 'Show / Game show' match_category['téléfilm'] = 'Movie / Drama' match_category['téléfilm érotique'] = 'Adult movie / Drama' match_category['téléréalité'] = 'Show / Game show' match_category['théâtre'] = 'Arts / Culture (without music)' match_category['triathlon'] = 'Sports' match_category['variétés'] = 'Arts / Culture (without music)' match_category['vtt'] = 'Sports' def list_categories(): logging.debug("Entry Point") logging.debug("File: %s", args.XMLTV_PATH) tree = etree.parse(args.XMLTV_PATH) root = tree.getroot() list_categories = [] for programme in root.iter('programme'): # get category subelemnt's for each programme category = programme.find('category') if category is not None: # get category name's for each programme category_name = category.text # detect unrecognized category if category_name not in list_categories: list_categories.append(category_name) list_categories.sort() logging.debug("List categories finished") logging.debug("List of categories") for category_name in list_categories: logging.debug("> %s", category_name) logging.debug("TOTAL: %i categories", len(list_categories)) def try_match_category( value, match_category ): # print("[INFO] try_match_category with", value) subString = value.split(' ') length = len(subString) i = 0 while(i < length): for frCat, tvhCat in match_category.items(): # print("[INFO] frCat", frCat) # print("[INFO] tvhCat", tvhCat) if subString[i] in frCat: logging.debug("match found: %s >> %s", subString[i], tvhCat) return tvhCat i = i+1 return None def match_categories(): logging.debug("Entry Point") logging.debug("File: %s", args.XMLTV_PATH) tree = etree.parse(args.XMLTV_PATH) root = tree.getroot() unrecognized_category = [] if not root: logging.error("Root is null") return for programme in root.iter('programme'): # get category subelemnt's for each programme category_subelt = programme.find('category') if category_subelt is not None: # get category name's for each programme category_name = category_subelt.text # detect unrecognized category if category_name not in match_category: hts_category_identified = try_match_category(category_name, match_category) if hts_category_identified is None: if category_name not in unrecognized_category: unrecognized_category.append(category_name) else: match_category[category_name] = hts_category_identified logging.debug(">> UPDATE %40s -> %s", category_name, hts_category_identified) else: logging.debug("No category found") # build the new xml file with correct category names logging.debug("Migration OK") logging.debug("List of unrecognized category") for category in unrecognized_category: logging.debug("> %s", category) logging.debug("TOTAL: %i unrecognized category", len(unrecognized_category)) logging.debug("List of recognized category") for match in match_category: logging.debug("> %s", match) def generate_categories_sed(): for key, value in match_category.items(): #safestr = value.replace('/', '\/').replace('\'', '\'"\'"\'') safestr = value.replace("\"", "\\\"") #safekey = key.replace('\'', '\'"\'"\'') safekey = key.replace("\"", "\\\"") # safestr = value # logging.debug("sed -ri 's/<category lang=\"fr\">%s/<category lang=\"fr\">%s/g' \"$XMLTV_PATH\"", key, safestr) # print("sed -ri \"s/<category lang=\\\"fr\\\">{}/<category lang=\\\"fr\\\">{}/g\" \"$XMLTV_PATH\"".format(key, safestr)) # print("$SED_COMMAND \'s/<category lang=\\\"fr\\\">{}/<category lang=\\\"fr\\\">{}/g\' \"$XMLTV_PATH\"".format(key, safestr)) #print("echo \"{} -> {}\"".format(safekey, safestr)) #print("$SED_COMMAND \"s|<category lang=\\\"fr\\\">{}</category>|<category lang=\\\"fr\\\">{}</category>|g\" \"$XMLTV_PATH\"".format(safekey, safestr)) print("s|<category lang=\\\"fr\\\">{}</category>|<category lang=\\\"fr\\\">{}</category>|g;\\".format(safekey, safestr)) def main(): init_categories() list_categories() match_categories() generate_categories_sed() main()
import hasInterface from '../../../../../hasInterface'; import SweepLineSegment from './SweepLineSegment'; import SweepLineEvent from './SweepLineEvent'; import EdgeSetIntersector from './EdgeSetIntersector'; import extend from '../../../../../extend'; import Collections from '../../../../../java/util/Collections'; import SegmentIntersector from './SegmentIntersector'; import ArrayList from '../../../../../java/util/ArrayList'; import Edge from '../Edge'; import inherits from '../../../../../inherits'; import List from '../../../../../java/util/List'; export default function SimpleSweepLineIntersector() { EdgeSetIntersector.apply(this); this.events = new ArrayList(); this.nOverlaps = null; } inherits(SimpleSweepLineIntersector, EdgeSetIntersector); extend(SimpleSweepLineIntersector.prototype, { processOverlaps: function (start, end, ev0, si) { var ss0 = ev0.getObject(); for (var i = start; i < end; i++) { var ev1 = this.events.get(i); if (ev1.isInsert()) { var ss1 = ev1.getObject(); if (!ev0.isSameLabel(ev1)) { ss0.computeIntersections(ss1, si); this.nOverlaps++; } } } }, prepareEvents: function () { Collections.sort(this.events); for (var i = 0; i < this.events.size(); i++) { var ev = this.events.get(i); if (ev.isDelete()) { ev.getInsertEvent().setDeleteEventIndex(i); } } }, computeIntersections: function () { if (arguments.length === 1) { let si = arguments[0]; this.nOverlaps = 0; this.prepareEvents(); for (var i = 0; i < this.events.size(); i++) { var ev = this.events.get(i); if (ev.isInsert()) { this.processOverlaps(i, ev.getDeleteEventIndex(), ev, si); } } } else if (arguments.length === 3) { if (arguments[2] instanceof SegmentIntersector && (hasInterface(arguments[0], List) && hasInterface(arguments[1], List))) { let edges0 = arguments[0], edges1 = arguments[1], si = arguments[2]; this.add(edges0, edges0); this.add(edges1, edges1); this.computeIntersections(si); } else if (typeof arguments[2] === "boolean" && (hasInterface(arguments[0], List) && arguments[1] instanceof SegmentIntersector)) { let edges = arguments[0], si = arguments[1], testAllSegments = arguments[2]; if (testAllSegments) this.add(edges, null); else this.add(edges); this.computeIntersections(si); } } }, add: function () { if (arguments.length === 1) { let edges = arguments[0]; for (var i = edges.iterator(); i.hasNext(); ) { var edge = i.next(); this.add(edge, edge); } } else if (arguments.length === 2) { if (hasInterface(arguments[0], List) && arguments[1] instanceof Object) { let edges = arguments[0], edgeSet = arguments[1]; for (var i = edges.iterator(); i.hasNext(); ) { var edge = i.next(); this.add(edge, edgeSet); } } else if (arguments[0] instanceof Edge && arguments[1] instanceof Object) { let edge = arguments[0], edgeSet = arguments[1]; var pts = edge.getCoordinates(); for (var i = 0; i < pts.length - 1; i++) { var ss = new SweepLineSegment(edge, i); var insertEvent = new SweepLineEvent(edgeSet, ss.getMinX(), null); this.events.add(insertEvent); this.events.add(new SweepLineEvent(ss.getMaxX(), insertEvent)); } } } }, interfaces_: function () { return []; }, getClass: function () { return SimpleSweepLineIntersector; } });
# # Generated with FibreRopeBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from .crosssection import CrossSectionBlueprint from .crsaxialfrictionmodel import CRSAxialFrictionModelBlueprint class FibreRopeBlueprint(CrossSectionBlueprint,CRSAxialFrictionModelBlueprint): """""" def __init__(self, name="FibreRope", package_path="sima/riflex", description=""): super().__init__(name,package_path,description) self.attributes.append(Attribute("name","string","",default="")) self.attributes.append(Attribute("description","string","",default="")) self.attributes.append(Attribute("_id","string","",default="")) self.attributes.append(BlueprintAttribute("scriptableValues","sima/sima/ScriptableValue","",True,Dimension("*"))) self.attributes.append(Attribute("staticFriction","number","Static friction force corresponding to elongation",default=0.0)) self.attributes.append(Attribute("staticElongation","number","Relative elongation",default=0.0)) self.attributes.append(Attribute("dynamicFriction","number","Dynamic friction force corresponding to elongation",default=0.0)) self.attributes.append(Attribute("dynamicElongation","number","Relative elongation",default=0.0)) self.attributes.append(Attribute("axialFriction","boolean","Local axial friction model",default=False)) self.attributes.append(Attribute("scfkSpecification","boolean","Scaling of Froude-Krylov term in Morison’s equation in normal direction",default=True)) self.attributes.append(EnumAttribute("loadFormulation","sima/riflex/LoadFormulation","")) self.attributes.append(Attribute("hydrodynamicDiameter","number","Hydrodynamic diameter",default=0.0)) self.attributes.append(Attribute("addedMassTanDir","number","Added mass in tangential direction",default=0.0)) self.attributes.append(Attribute("addedMassNormDir","number","Added mass in normal direction",default=0.0)) self.attributes.append(Attribute("dampingNormDir","number","Damping coefficients in normal direction",default=0.0)) self.attributes.append(Attribute("cdt","number","Quadratic drag coefficient in tangential direction.",default=0.0)) self.attributes.append(Attribute("cdn","number","Quadratic drag coefficient in normal direction.",default=0.0)) self.attributes.append(Attribute("cmt","number","Added mass per unit length in tangential direction.",default=0.0)) self.attributes.append(Attribute("cmn","number","Added mass per unit length in normal direction.",default=0.0)) self.attributes.append(Attribute("cdtl","number","Linear drag force coefficient in tangential direction.",default=0.0)) self.attributes.append(Attribute("cdnl","number","Linear drag force coefficient in normal direction.",default=0.0)) self.attributes.append(Attribute("cdx","number","Quadratic drag coefficient in tangential direction.",default=0.0)) self.attributes.append(Attribute("cdy","number","Quadratic drag coefficient in normal direction.",default=0.0)) self.attributes.append(Attribute("amx","number","Added mass per unit length in tangential direction.",default=0.0)) self.attributes.append(Attribute("amy","number","Added mass per unit length in normal direction.",default=0.0)) self.attributes.append(Attribute("cdlx","number","Linear drag force coefficient in tangential direction.",default=0.0)) self.attributes.append(Attribute("cdly","number","Linear drag force coefficient in normal direction.",default=0.0)) self.attributes.append(EnumAttribute("hydrodynamicInputCode","sima/riflex/HydrodynamicInputCode","Hydrodynamic input code")) self.attributes.append(Attribute("scfk","number","Scaling factor for Froude-Krylov term in Morison’s equation in normal direction",default=1.0)) self.attributes.append(EnumAttribute("scfkt","sima/riflex/TangentialFroudeKrylovScaling","Scale for Froude-Krylov term in Morison’s equation in tangential direction")) self.attributes.append(Attribute("massDampingSpecification","boolean","Mass proportional Rayleigh damping",default=False)) self.attributes.append(Attribute("stiffnessDampingSpecification","boolean","Stiffness proportional Rayleigh damping",default=False)) self.attributes.append(Attribute("axialDampingSpecification","boolean","Local axial damping model",default=False)) self.attributes.append(Attribute("temperature","number","Temperature at which the specification applies",default=0.0)) self.attributes.append(Attribute("alpha","number","Thermal expansion coefficient",default=0.0)) self.attributes.append(Attribute("beta","number","Pressure expansion coefficient",default=0.0)) self.attributes.append(BlueprintAttribute("massDamping","sima/riflex/CRSMassDamping","",True)) self.attributes.append(BlueprintAttribute("stiffnessDamping","sima/riflex/CRSStiffnessDamping","",True)) self.attributes.append(BlueprintAttribute("axialDamping","sima/riflex/CRSAxialDamping","",True)) self.attributes.append(Attribute("defaultExpansion","boolean","Use default thermal and pressure expansion settings",default=True)) self.attributes.append(Attribute("cdax","number","Quadratic aerodynamic drag force coefficient per unit length in tangential direction",default=0.0)) self.attributes.append(Attribute("cday","number","Quadratic aerodynamic drag force coefficient per unit length in normal direction",default=0.0)) self.attributes.append(Attribute("cdaz","number","Quadratic aerodynamic drag force coefficient per unit length in z direction",default=0.0)) self.attributes.append(EnumAttribute("aerodynamicInputCode","sima/riflex/AerodynamicInputCode","Aerodynamic input code")) self.attributes.append(Attribute("aerodynamicDiameter","number","Aerodynamic diameter",default=0.0)) self.attributes.append(BlueprintAttribute("massVolume","sima/riflex/FibreRopeMassVolume","",True)) self.attributes.append(Attribute("tensionCapacity","number","Tension capacity",default=0.0)) self.attributes.append(Attribute("maxCurvature","number","Maximum curvature",default=0.0)) self.attributes.append(Attribute("submerged","boolean","Use formulation for partly submerged cross-section",default=False)) self.attributes.append(Attribute("tmax","number","",default=0.0)) self.attributes.append(BlueprintAttribute("fibreRopeModel","sima/simo/FibreRopeModel","",False))
module.exports = { preset: 'ts-jest', moduleDirectories: ['node_modules', 'src'], collectCoverage: true, collectCoverageFrom: ['src/**/*.ts', '!src/index.ts', '!src/domain/**'], coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80, }, }, };
# stdlib from typing import Optional # third party import pytest # ite absolute import ite.datasets as ds def test_sanity() -> None: with pytest.raises(BaseException): ds.load("test") @pytest.mark.parametrize( "train_ratio", [0.1, 0.5, 0.8], ) @pytest.mark.parametrize( "downsample", [None, 100, 1000], ) def test_dataset_twins_load(train_ratio: float, downsample: Optional[int]) -> None: # Data Input (11400 patients, 30 features, 2 potential outcomes) total = 11400 feat_count = 30 outcomes = 2 [Train_X, Train_T, Train_Y, Opt_Train_Y, Test_X, Test_Y] = ds.load( "twins", train_ratio, downsample=downsample, ) train_cnt = int(total * train_ratio) test_cnt = total - train_cnt if downsample: train_cnt = min(downsample, train_cnt) test_cnt = min(downsample, test_cnt) assert Train_X.shape == (train_cnt, feat_count) assert Train_T.shape == (train_cnt,) assert Train_Y.shape == (train_cnt,) assert Opt_Train_Y.shape == (train_cnt, outcomes) assert Test_X.shape == (test_cnt, feat_count) assert Test_Y.shape == (test_cnt, outcomes)
#ifndef WLR_RENDER_WLR_RENDERER_H #define WLR_RENDER_WLR_RENDERER_H #include <stdint.h> #include <wayland-server-protocol.h> #include <wlr/render/wlr_texture.h> #include <wlr/types/wlr_box.h> struct wlr_output; struct wlr_renderer; void wlr_renderer_begin(struct wlr_renderer *r, int width, int height); void wlr_renderer_end(struct wlr_renderer *r); void wlr_renderer_clear(struct wlr_renderer *r, const float color[static 4]); /** * Defines a scissor box. Only pixels that lie within the scissor box can be * modified by drawing functions. Providing a NULL `box` disables the scissor * box. */ void wlr_renderer_scissor(struct wlr_renderer *r, struct wlr_box *box); /** * Renders the requested texture. */ bool wlr_render_texture(struct wlr_renderer *r, struct wlr_texture *texture, const float projection[static 9], int x, int y, float alpha); /** * Renders the requested texture using the provided matrix. */ bool wlr_render_texture_with_matrix(struct wlr_renderer *r, struct wlr_texture *texture, const float matrix[static 9], float alpha); /** * Renders a solid rectangle in the specified color. */ void wlr_render_rect(struct wlr_renderer *r, const struct wlr_box *box, const float color[static 4], const float projection[static 9]); /** * Renders a solid quadrangle in the specified color with the specified matrix. */ void wlr_render_quad_with_matrix(struct wlr_renderer *r, const float color[static 4], const float matrix[static 9]); /** * Renders a solid ellipse in the specified color. */ void wlr_render_ellipse(struct wlr_renderer *r, const struct wlr_box *box, const float color[static 4], const float projection[static 9]); /** * Renders a solid ellipse in the specified color with the specified matrix. */ void wlr_render_ellipse_with_matrix(struct wlr_renderer *r, const float color[static 4], const float matrix[static 9]); /** * Returns a list of pixel formats supported by this renderer. */ const enum wl_shm_format *wlr_renderer_get_formats(struct wlr_renderer *r, size_t *len); /** * Returns true if this wl_buffer is a wl_drm buffer. */ bool wlr_renderer_resource_is_wl_drm_buffer(struct wlr_renderer *renderer, struct wl_resource *buffer); /** * Gets the width and height of a wl_drm buffer. */ void wlr_renderer_wl_drm_buffer_get_size(struct wlr_renderer *renderer, struct wl_resource *buffer, int *width, int *height); /** * Reads out of pixels of the currently bound surface into data. `stride` is in * bytes. */ bool wlr_renderer_read_pixels(struct wlr_renderer *r, enum wl_shm_format fmt, uint32_t stride, uint32_t width, uint32_t height, uint32_t src_x, uint32_t src_y, uint32_t dst_x, uint32_t dst_y, void *data); /** * Checks if a format is supported. */ bool wlr_renderer_format_supported(struct wlr_renderer *r, enum wl_shm_format fmt); /** * Destroys this wlr_renderer. Textures must be destroyed separately. */ void wlr_renderer_destroy(struct wlr_renderer *renderer); #endif
/** * \file appl_sample_example_5.c * * Source File for Generic OnOff Server and Light Lightness Server * Standalone application without CLI or menu based console input interface. * In this example, the server models are part of two different elements. */ /* * Copyright (C) 2018. Mindtree Ltd. * All rights reserved. */ #if (MESH_STANDALONE == 5) /* ----------------------------------------- Header File Inclusion */ #include "MS_common.h" #include "MS_access_api.h" #include "MS_config_api.h" #include "MS_health_server_api.h" #include "MS_generic_onoff_api.h" #include "MS_light_lightness_api.h" #include "blebrr.h" #include "nvsto.h" #include "model_state_handler_pl.h" /* Console Input/Output */ #define CONSOLE_OUT(...) printf(__VA_ARGS__) #define CONSOLE_IN(...) scanf(__VA_ARGS__) void appl_dump_bytes(UCHAR *buffer, UINT16 length); void appl_mesh_sample (void); /* ----------------------------------------- External Global Variables */ /* ----------------------------------------- Exported Global Variables */ /* ----------------------------------------- Static Global Variables */ /* ----------------------------------------- Functions */ /* Model Server - Foundation Models */ /* Health Server - Test Routines */ static void UI_health_self_test_00(UINT8 test_id, UINT16 company_id) { } static void UI_health_self_test_01(UINT8 test_id, UINT16 company_id) { } static void UI_health_self_test_FF(UINT8 test_id, UINT16 company_id) { } /* List of Self Tests */ static MS_HEALTH_SERVER_SELF_TEST UI_health_server_self_tests[] = { { 0x00, /* Test ID: 0x00 */ UI_health_self_test_00 }, { 0x01, /* Test ID: 0x01 */ UI_health_self_test_01 }, { 0xFF, /* Test ID: 0xFF */ UI_health_self_test_FF } }; /** * \brief Health Server application Asynchronous Notification Callback. * * \par Description * Health Server calls the registered callback to indicate events occurred to the * application. * * \param handle Model Handle. * \param event_type Health Server Event type. * \param event_param Parameter associated with the event if any or NULL. * \param param_len Size of the event parameter data. 0 if event param is NULL. */ static API_RESULT UI_health_server_cb ( MS_ACCESS_MODEL_HANDLE * handle, UINT8 event_type, UINT8 * event_param, UINT16 param_len ) { CONSOLE_OUT( "Health Server Callback. Not handled. Returning\n"); return API_SUCCESS; } API_RESULT UI_register_foundation_model_servers ( MS_ACCESS_ELEMENT_HANDLE element_handle ) { /* Configuration Server */ MS_ACCESS_MODEL_HANDLE UI_config_server_model_handle; MS_ACCESS_MODEL_HANDLE UI_health_server_model_handle; API_RESULT retval; /* Health Server */ UINT16 company_id; MS_HEALTH_SERVER_SELF_TEST * self_tests; UINT32 num_self_tests; CONSOLE_OUT("In Model Server - Foundation Models\n"); retval = MS_config_server_init(element_handle, &UI_config_server_model_handle); CONSOLE_OUT("Config Model Server Registration Status: 0x%04X\n", retval); /* Health Server */ company_id = MS_DEFAULT_COMPANY_ID; self_tests = &UI_health_server_self_tests[0]; num_self_tests = sizeof(UI_health_server_self_tests)/sizeof(MS_HEALTH_SERVER_SELF_TEST); retval = MS_health_server_init ( element_handle, &UI_health_server_model_handle, company_id, self_tests, num_self_tests, UI_health_server_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Health Server Initialized. Model Handle: 0x%04X\n", UI_health_server_model_handle); } else { CONSOLE_OUT( "[ERR] Sensor Server Initialization Failed. Result: 0x%04X\n", retval); } return retval; } /* ---- Generic OnOff States */ static MS_STATE_GENERIC_ONOFF_STRUCT UI_generic_onoff; /** -- Light - Lightness */ static MS_STATE_LIGHT_LIGHTNESS_STRUCT UI_light_lightness; /* Get/Set State Handlers */ /* Generic OnOff Model state Initialization */ void UI_generic_onoff_model_states_initialization(void) { EM_mem_set(&UI_generic_onoff, 0, sizeof(UI_generic_onoff)); } /* Generic OnOff Model Get Handler */ API_RESULT UI_generic_onoff_model_state_get(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { API_RESULT retval; retval = API_SUCCESS; switch(state_t) { case MS_STATE_GENERIC_ONOFF_T: { MS_STATE_GENERIC_ONOFF_STRUCT * param_p; param_p = (MS_STATE_GENERIC_ONOFF_STRUCT *)param; /* Ignoring Instance and direction right now */ *param_p = UI_generic_onoff; } break; default: break; } return retval; } /* Generic OnOff Model Set Handler */ API_RESULT UI_generic_onoff_model_state_set(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { API_RESULT retval; retval = API_SUCCESS; switch (state_t) { case MS_STATE_GENERIC_ONOFF_T: { MS_STATE_GENERIC_ONOFF_STRUCT * param_p; param_p = (MS_STATE_GENERIC_ONOFF_STRUCT *)param; /* Instantaneous Change */ UI_generic_onoff.onoff = param_p->onoff; *param_p = UI_generic_onoff; CONSOLE_OUT("[state] current: 0x%02X\n", UI_generic_onoff.onoff); CONSOLE_OUT("[state] target: 0x%02X\n", UI_generic_onoff.target_onoff); CONSOLE_OUT("[state] remaining_time: 0x%02X\n", UI_generic_onoff.transition_time); generic_onoff_set_pl(param_p->onoff); /* Ignoring Instance and direction right now */ } break; default: break; } return retval; } /* Light Lightness Model state Initialization */ void UI_light_lightness_model_states_initialization(void) { /* Light Lightness States */ EM_mem_set(&UI_light_lightness, 0, sizeof(UI_light_lightness)); UI_light_lightness.light_lightness_last.lightness_last = 0xFFFF; } /* Light Lightness Model Get Handler */ API_RESULT UI_light_lightness_model_state_get(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { MS_STATE_LIGHT_LIGHTNESS_STRUCT * param_p; API_RESULT retval; param_p = (MS_STATE_LIGHT_LIGHTNESS_STRUCT *)param; retval = API_SUCCESS; switch(state_t) { case MS_STATE_LIGHT_LIGHTNESS_DEFAULT_T: { /* Ignoring Instance and direction right now */ param_p->light_lightness_default = UI_light_lightness.light_lightness_default; } break; case MS_STATE_LIGHT_LIGHTNESS_RANGE_T: { /* Ignoring Instance and direction right now */ param_p->light_lightness_range = UI_light_lightness.light_lightness_range; param_p->range_status = 0x00; } break; case MS_STATE_LIGHT_LIGHTNESS_LINEAR_T: { /* Ignoring Instance and direction right now */ param_p->light_lightness_linear = UI_light_lightness.light_lightness_linear; } break; case MS_STATE_LIGHT_LIGHTNESS_LAST_T: { /* Ignoring Instance and direction right now */ param_p->light_lightness_last = UI_light_lightness.light_lightness_last; } break; case MS_STATE_LIGHT_LIGHTNESS_ACTUAL_T: { /* Ignoring Instance and direction right now */ param_p->light_lightness_actual = UI_light_lightness.light_lightness_actual; } break; default: break; } return retval; } /* Light Lightness Model Set Handler */ /* Todo: Remove the dependency */ #include "math.h" static void UI_light_lightness_set_actual(UINT16 state_inst, UINT16 actual) { UINT16 min, max; /* Generic OnOff binding */ min = UI_light_lightness.light_lightness_range.lightness_range_min; max = UI_light_lightness.light_lightness_range.lightness_range_max; if ((0 != min) && (actual < min)) { actual = min; } else if ((0 != max) && (actual > max)) { actual = max; } /* If Lightness Actual is non-zero, save as Lightness Last */ if (0x0000 != actual) { UI_light_lightness.light_lightness_last.lightness_last = actual; } UI_light_lightness.light_lightness_actual.lightness_actual = actual; /* Light Lightness Linear = ((Actual)^2) / 65535 */ UI_light_lightness.light_lightness_linear.lightness_linear = ((actual * actual) + 65534) / 65535; } static void UI_light_lightness_set_linear(UINT16 state_inst, UINT16 linear) { UINT16 actual; UINT32 mul_val; mul_val = linear * 65535; actual = (UINT16)sqrt(mul_val); /* Light Lightness actual = sqrt(Linear * 65535) */ UI_light_lightness_set_actual(state_inst, actual); } API_RESULT UI_light_lightness_model_state_set(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { MS_STATE_LIGHT_LIGHTNESS_STRUCT * param_p; API_RESULT retval; param_p = (MS_STATE_LIGHT_LIGHTNESS_STRUCT *)param; retval = API_SUCCESS; switch (state_t) { case MS_STATE_LIGHT_LIGHTNESS_DEFAULT_T: { /* Ignoring Instance and direction right now */ UI_light_lightness.light_lightness_default = param_p->light_lightness_default; } break; case MS_STATE_LIGHT_LIGHTNESS_RANGE_T: { /* Check range min and max */ if (param_p->light_lightness_range.lightness_range_min > param_p->light_lightness_range.lightness_range_max) { /* TODO: add macro define */ /** * Table 7.2: * 0x00 - Success * 0x01 - Cannot Set Range Min * 0x02 - Cannot Set Range Max */ param_p->range_status = 0x01; } else { /* Ignoring Instance and direction right now */ UI_light_lightness.light_lightness_range = param_p->light_lightness_range; param_p->range_status = 0x00; } } break; case MS_STATE_LIGHT_LIGHTNESS_LINEAR_T: { /* Instantaneous Change */ UI_light_lightness_set_linear(0, param_p->light_lightness_linear.lightness_linear); *param_p = UI_light_lightness; CONSOLE_OUT("[state] current: 0x%02X\n", param_p->light_lightness_linear.lightness_linear); CONSOLE_OUT("[state] target: 0x%02X\n", param_p->light_lightness_linear.lightness_target); CONSOLE_OUT("[state] remaining_time: 0x%02X\n", param_p->light_lightness_linear.transition_time); /* Ignoring Instance and direction right now */ } break; case MS_STATE_LIGHT_LIGHTNESS_LAST_T: { /* Ignoring Instance and direction right now */ UI_light_lightness.light_lightness_last = param_p->light_lightness_last; } break; case MS_STATE_LIGHT_LIGHTNESS_ACTUAL_T: { /* Instantaneous Change */ UI_light_lightness_set_actual(0, param_p->light_lightness_actual.lightness_actual); *param_p = UI_light_lightness; CONSOLE_OUT("[state] current: 0x%02X\n", param_p->light_lightness_actual.lightness_actual); CONSOLE_OUT("[state] target: 0x%02X\n", param_p->light_lightness_actual.lightness_target); CONSOLE_OUT("[state] remaining_time: 0x%02X\n", param_p->light_lightness_actual.transition_time); } break; default: break; } return retval; } /* Model state Initialization */ void UI_model_states_initialization(void) { /* Generic OnOff States */ UI_generic_onoff_model_states_initialization(); /* Light Lightness States */ UI_light_lightness_model_states_initialization(); } /* Generic OnOff Model Server */ /** * \brief Server Application Asynchronous Notification Callback. * * \par Description * Generic_Onoff server calls the registered callback to indicate events occurred to the application. * * \param [in] ctx Context of message received for a specific model instance. * \param [in] msg_raw Uninterpreted/raw received message. * \param [in] req_type Requested message type. * \param [in] state_params Model specific state parameters. * \param [in] ext_params Additional parameters. */ API_RESULT UI_generic_onoff_server_cb ( /* IN */ MS_ACCESS_MODEL_REQ_MSG_CONTEXT * ctx, /* IN */ MS_ACCESS_MODEL_REQ_MSG_RAW * msg_raw, /* IN */ MS_ACCESS_MODEL_REQ_MSG_T * req_type, /* IN */ MS_ACCESS_MODEL_STATE_PARAMS * state_params, /* IN */ MS_ACCESS_MODEL_EXT_PARAMS * ext_params ) { MS_STATE_GENERIC_ONOFF_STRUCT param; MS_ACCESS_MODEL_STATE_PARAMS current_state_params; API_RESULT retval; retval = API_SUCCESS; /* Check message type */ if (MS_ACCESS_MODEL_REQ_MSG_T_GET == req_type->type) { CONSOLE_OUT("[GENERIC_ONOFF] GET Request.\n"); UI_generic_onoff_model_state_get(state_params->state_type, 0, &param, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = &param; /* Using same as target state and remaining time as 0 */ } else if (MS_ACCESS_MODEL_REQ_MSG_T_SET == req_type->type) { CONSOLE_OUT("[GENERIC_ONOFF] SET Request.\n"); retval = UI_generic_onoff_model_state_set(state_params->state_type, 0, (MS_STATE_GENERIC_ONOFF_STRUCT *)state_params->state, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = (MS_STATE_GENERIC_ONOFF_STRUCT *)state_params->state; } /* See if to be acknowledged */ if (0x01 == req_type->to_be_acked) { CONSOLE_OUT("[GENERIC_ONOFF] Sending Response.\n"); /* Parameters: Request Context, Current State, Target State (NULL: to be ignored), Remaining Time (0: to be ignored), Additional Parameters (NULL: to be ignored) */ retval = MS_generic_onoff_server_state_update(ctx, &current_state_params, NULL, 0, NULL); } return retval; } API_RESULT UI_register_generic_onoff_model_server ( MS_ACCESS_ELEMENT_HANDLE element_handle ) { /* Generic OnOff Server */ MS_ACCESS_MODEL_HANDLE UI_generic_onoff_server_model_handle; API_RESULT retval; CONSOLE_OUT("In Generic OnOff Model Server\n"); retval = MS_generic_onoff_server_init ( element_handle, &UI_generic_onoff_server_model_handle, UI_generic_onoff_server_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Generic Onoff Server Initialized. Model Handle: 0x%04X\n", UI_generic_onoff_server_model_handle); } else { CONSOLE_OUT( "[ERR] Generic Onoff Server Initialization Failed. Result: 0x%04X\n", retval); } return retval; } /* Light Ligthness Model Server */ /** * \brief Server Application Asynchronous Notification Callback. * * \par Description * Light_Lightness server calls the registered callback to indicate events occurred to the application. * * \param [in] ctx Context of message received for a specific model instance. * \param [in] msg_raw Uninterpreted/raw received message. * \param [in] req_type Requested message type. * \param [in] state_params Model specific state parameters. * \param [in] ext_params Additional parameters. */ API_RESULT UI_light_lightness_server_cb ( /* IN */ MS_ACCESS_MODEL_REQ_MSG_CONTEXT * ctx, /* IN */ MS_ACCESS_MODEL_REQ_MSG_RAW * msg_raw, /* IN */ MS_ACCESS_MODEL_REQ_MSG_T * req_type, /* IN */ MS_ACCESS_MODEL_STATE_PARAMS * state_params, /* IN */ MS_ACCESS_MODEL_EXT_PARAMS * ext_params ) { MS_STATE_LIGHT_LIGHTNESS_STRUCT param; MS_ACCESS_MODEL_STATE_PARAMS current_state_params; API_RESULT retval; retval = API_SUCCESS; /* Check message type */ if (MS_ACCESS_MODEL_REQ_MSG_T_GET == req_type->type) { CONSOLE_OUT( "[LIGHT_LIGHTNESS] GET Request.\n"); UI_light_lightness_model_state_get(state_params->state_type, 0, &param, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = &param; } else if (MS_ACCESS_MODEL_REQ_MSG_T_SET == req_type->type) { CONSOLE_OUT( "[LIGHT_LIGHTNESS] SET Request.\n"); UI_light_lightness_model_state_set(state_params->state_type, 0, (MS_STATE_LIGHT_LIGHTNESS_STRUCT *)state_params->state, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = (MS_STATE_LIGHT_LIGHTNESS_STRUCT *)state_params->state; } /* See if to be acknowledged */ if (0x01 == req_type->to_be_acked) { CONSOLE_OUT( "[LIGHT_LIGHTNESS] Sending Response.\n"); /* Parameters: Request Context, Current State, Target State (NULL: to be ignored), Remaining Time (0: to be ignored), Additional Parameters (NULL: to be ignored) */ retval = MS_light_lightness_server_state_update(ctx, &current_state_params, NULL, 0, NULL); } return retval; } API_RESULT UI_register_light_lightness_model_server ( MS_ACCESS_ELEMENT_HANDLE element_handle ) { /* Generic OnOff Server */ MS_ACCESS_MODEL_HANDLE UI_light_lightness_server_model_handle; API_RESULT retval; retval = MS_light_lightness_server_init ( element_handle, &UI_light_lightness_server_model_handle, UI_light_lightness_server_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Light Lightness Server Initialized. Model Handle: 0x%04X\n", UI_light_lightness_server_model_handle); } else { CONSOLE_OUT( "[ERR] Light Lightness Server Initialization Failed. Result: 0x%04X\n", retval); } return retval; } /* Provisionee */ #define UI_PROV_OUTPUT_OOB_ACTIONS \ (PROV_MASK_OOOB_ACTION_BLINK | PROV_MASK_OOOB_ACTION_BEEP | \ PROV_MASK_OOOB_ACTION_VIBRATE | PROV_MASK_OOOB_ACTION_NUMERIC | \ PROV_MASK_OOOB_ACTION_ALPHANUMERIC) /** Output OOB Maximum size supported */ #define UI_PROV_OUTPUT_OOB_SIZE 0x08 /** Input OOB Actions supported */ #define UI_PROV_INPUT_OOB_ACTIONS \ (PROV_MASK_IOOB_ACTION_PUSH | PROV_MASK_IOOB_ACTION_TWIST | \ PROV_MASK_IOOB_ACTION_NUMERIC | PROV_MASK_IOOB_ACTION_ALPHANUMERIC) /** Input OOB Maximum size supported */ #define UI_PROV_INPUT_OOB_SIZE 0x08 /** Beacon setup timeout in seconds */ #define UI_PROV_SETUP_TIMEOUT_SECS 30 /** Attention timeout for device in seconds */ #define UI_PROV_DEVICE_ATTENTION_TIMEOUT 30 #define PROV_AUTHVAL_SIZE_PL 16 /** Authentication values for OOB Display - To be made random */ #define UI_DISPLAY_AUTH_DIGIT 3 #define UI_DISPLAY_AUTH_NUMERIC 35007 #define UI_DISPLAY_AUTH_STRING "f00l" /** Provisioning capabilities of local device */ DECL_STATIC PROV_CAPABILITIES_S UI_prov_capab = { /** Number of Elements */ 0x02, /** Supported algorithms */ PROV_MASK_ALGO_EC_FIPS_P256, /** Public key type */ PROV_MASK_PUBKEY_OOBINFO, /** Static OOB type */ PROV_MASK_STATIC_OOBINFO, /** Output OOB information */ { UI_PROV_OUTPUT_OOB_ACTIONS, UI_PROV_OUTPUT_OOB_SIZE }, /** Input OOB information */ { UI_PROV_INPUT_OOB_ACTIONS, UI_PROV_INPUT_OOB_SIZE }, }; /** Unprovisioned device identifier */ PROV_DEVICE_S UI_lprov_device = { /** UUID */ {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, /** OOB Flag */ 0x00, /** * Encoded URI Information * For example, to give a web address, "https://www.abc.com" * the URI encoded data would be - * 0x17 0x2F 0x2F 0x77 0x77 0x77 0x2E 0x61 0x62 0x63 0x2E 0x63 0x6F 0x6D * where 0x17 is the URI encoding for https: */ NULL }; /** Data exchanged during Provisiong procedure */ DECL_STATIC PROV_DATA_S UI_prov_data = { /** NetKey */ { 0x45, 0x74, 0x68, 0x65, 0x72, 0x4d, 0x69, 0x6e, 0x64, 0x4e, 0x65, 0x74, 0x4b, 0x65, 0x79, 0x00 }, /** Index of the NetKey */ 0x0000, /** Flags bitmask */ 0x00, /** Current value of the IV index */ 0x00000001, /** Unicast address of the primary element */ 0x0002 }; /** Current role of application - Provisioner/Device */ DECL_STATIC UCHAR UI_prov_role; /** Provisioning Handle */ DECL_STATIC PROV_HANDLE UI_prov_handle; API_RESULT UI_prov_callback ( PROV_HANDLE * phandle, UCHAR event_type, API_RESULT event_result, void * event_data, UINT16 event_datalen ) { PROV_DATA_S * rdata; PROV_OOB_TYPE_S * oob_info; API_RESULT retval; UCHAR authstr[PROV_AUTHVAL_SIZE_PL << 1]; UINT32 authnum; UCHAR authtype; UCHAR * pauth; UINT16 authsize; switch (event_type) { case PROV_EVT_PROVISIONING_SETUP: CONSOLE_OUT("Recvd PROV_EVT_PROVISIONING_SETUP\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Display the attention timeout */ CONSOLE_OUT("Attention TImeout - %d\n", *((UCHAR *)event_data)); break; case PROV_EVT_OOB_DISPLAY: CONSOLE_OUT("Recvd PROV_EVT_OOB_DISPLAY\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Authenticatio Type information */ oob_info = (PROV_OOB_TYPE_S *)event_data; CONSOLE_OUT("Authenticaion Action - 0x%02X\n", oob_info->action); CONSOLE_OUT("Authenticaion Size - 0x%02X\n", oob_info->size); /* If role is Device, the action is of Output OOB, else Input OOB */ if (PROV_ROLE_DEVICE == UI_prov_role) { if (PROV_OOOB_ACTION_ALPHANUMERIC == oob_info->action) { authtype = 1; } else if (PROV_OOOB_ACTION_NUMERIC == oob_info->action) { authtype = 2; } else { authtype = 0; } } else { if (PROV_IOOB_ACTION_ALPHANUMERIC == oob_info->action) { authtype = 1; } else if (PROV_IOOB_ACTION_NUMERIC == oob_info->action) { authtype = 2; } else { authtype = 0; } } if (1 == authtype) { EM_str_copy (authstr, UI_DISPLAY_AUTH_STRING); CONSOLE_OUT("\n\n>>> AuthVal - %s <<<\n\n", authstr); pauth = authstr; authsize = EM_str_len(authstr); } else if (2 == authtype) { authnum = (UINT32)UI_DISPLAY_AUTH_NUMERIC; CONSOLE_OUT("\n\n>>> AuthVal - %d <<<\n\n", authnum); pauth = (UCHAR *)&authnum; authsize = sizeof(UINT32); } else { authnum = (UINT32)UI_DISPLAY_AUTH_DIGIT; CONSOLE_OUT("\n\n>>> AuthVal - %d <<<\n\n", authnum); pauth = (UCHAR *)&authnum; authsize = sizeof(UINT32); } /* Call to input the oob */ CONSOLE_OUT("Setting the Authval...\n"); retval = MS_prov_set_authval(&UI_prov_handle, pauth, authsize); CONSOLE_OUT("Retval - 0x%04X\n", retval); break; case PROV_EVT_OOB_ENTRY: CONSOLE_OUT("Recvd PROV_EVT_OOB_ENTRY\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Authenticatio Type information */ oob_info = (PROV_OOB_TYPE_S *)event_data; CONSOLE_OUT("Authenticaion Action - 0x%02X\n", oob_info->action); CONSOLE_OUT("Authenticaion Size - 0x%02X\n", oob_info->size); break; case PROV_EVT_DEVINPUT_COMPLETE: CONSOLE_OUT("Recvd PROV_EVT_DEVINPUT_COMPLETE\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); break; case PROV_EVT_PROVDATA_INFO: CONSOLE_OUT("Recvd PROV_EVT_PROVDATA_INFO\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Provisioning Data */ rdata = (PROV_DATA_S *)event_data; CONSOLE_OUT("NetKey : "); appl_dump_bytes(rdata->netkey, PROV_KEY_NETKEY_SIZE); CONSOLE_OUT("Key ID : 0x%04X\n", rdata->keyid); CONSOLE_OUT("Flags : 0x%02X\n", rdata->flags); CONSOLE_OUT("IVIndex : 0x%08X\n", rdata->ivindex); CONSOLE_OUT("UAddr : 0x%04X\n", rdata->uaddr); /* Provide Provisioning Data to Access Layer */ MS_access_cm_set_prov_data ( rdata ); break; case PROV_EVT_PROVISIONING_COMPLETE: CONSOLE_OUT("Recvd PROV_EVT_PROVISIONING_COMPLETE\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); if (API_SUCCESS == event_result) { /* Already Set while handling PROV_EVT_PROVDATA_INFO */ } break; default: CONSOLE_OUT("Unknown Event - 0x%02X\n", event_type); } return API_SUCCESS; } void UI_register_prov(void) { API_RESULT retval; CONSOLE_OUT("Registering with Provisioning layer...\n"); retval = MS_prov_register(&UI_prov_capab, UI_prov_callback); CONSOLE_OUT("Retval - 0x%04X\n", retval); } void UI_setup_prov(UCHAR role, UCHAR brr) { API_RESULT retval; if (PROV_ROLE_PROVISIONER != role) { CONSOLE_OUT("Setting up Device for Provisioning ...\n"); retval = MS_prov_setup ( brr, role, &UI_lprov_device, UI_PROV_SETUP_TIMEOUT_SECS ); UI_prov_role = PROV_ROLE_DEVICE; } else { CONSOLE_OUT("Setting up Provisioner for Provisioning ...\n"); retval = MS_prov_setup ( brr, role, NULL, UI_PROV_SETUP_TIMEOUT_SECS ); UI_prov_role = PROV_ROLE_PROVISIONER; } CONSOLE_OUT("Retval - 0x%04X\n", retval); } void UI_prov_bind(UCHAR brr, UCHAR index) { API_RESULT retval; /* Call to bind with the selected device */ CONSOLE_OUT("Binding with the selected device...\n"); retval = MS_prov_bind(brr, &UI_lprov_device, UI_PROV_DEVICE_ATTENTION_TIMEOUT, &UI_prov_handle); CONSOLE_OUT("Retval - 0x%04X\n", retval); } void appl_mesh_sample (void) { MS_ACCESS_NODE_ID node_id; MS_ACCESS_ELEMENT_DESC element; MS_ACCESS_ELEMENT_HANDLE element_handle; MS_ACCESS_ELEMENT_DESC element_1; MS_ACCESS_ELEMENT_HANDLE element_handle_1; API_RESULT retval; UCHAR role, brr; MS_CONFIG * config_ptr; #ifdef MS_HAVE_DYNAMIC_CONFIG MS_CONFIG config; /* Initialize dynamic configuration */ MS_INIT_CONFIG(config); config_ptr = &config; #else config_ptr = NULL; #endif /* MS_HAVE_DYNAMIC_CONFIG */ /* Initialize OSAL */ EM_os_init(); /* Initialize Debug Module */ EM_debug_init(); /* Initialize Timer Module */ EM_timer_init(); timer_em_init(); /* Initialize utilities */ nvsto_init(); /* Initialize Mesh Stack */ MS_init(config_ptr); /* Register with underlying BLE stack */ blebrr_register(); /* Create Node */ retval = MS_access_create_node(&node_id); /* Register Element */ /** * TBD: Define GATT Namespace Descriptions from * https://www.bluetooth.com/specifications/assigned-numbers/gatt-namespace-descriptors * * Using 'main' (0x0106) as Location temporarily. */ element.loc = 0x0106; retval = MS_access_register_element ( node_id, &element, &element_handle ); if (API_SUCCESS == retval) { /* Register foundation model servers */ retval = UI_register_foundation_model_servers(element_handle); } if (API_SUCCESS == retval) { /* Register Generic OnOff model server */ retval = UI_register_generic_onoff_model_server(element_handle); } /* Register another Element */ /** * TBD: Define GATT Namespace Descriptions from * https://www.bluetooth.com/specifications/assigned-numbers/gatt-namespace-descriptors * * Using 'main' (0x0106) as Location temporarily. */ element_1.loc = 0x0106; retval = MS_access_register_element ( node_id, &element_1, &element_handle_1 ); if (API_SUCCESS == retval) { /* Register Light Lightness model server */ retval = UI_register_light_lightness_model_server(element_handle_1); } if (API_SUCCESS == retval) { /* Initialize model states */ UI_model_states_initialization(); } /* Configure as provisionee/device */ UI_register_prov(); /** * setup <role:[1 - Device, 2 - Provisioner]> <bearer:[1 - Adv, 2 - GATT] */ role = PROV_ROLE_DEVICE; brr = PROV_BRR_ADV; UI_setup_prov(role, brr); UI_prov_bind(brr, 0x00); return; } #endif /* (MESH_STANDALONE == 5) */
/* (C) 2014 EEMBC(R). All rights reserved. All EEMBC Benchmark Software are products of EEMBC and are provided under the terms of the EEMBC Benchmark License Agreements. The EEMBC Benchmark Software are proprietary intellectual properties of EEMBC and its Members and is protected under all applicable laws, including all applicable copyright laws. If you received this EEMBC Benchmark Software without having a currently effective EEMBC Benchmark License Agreement, you must discontinue use. Please refer to LICENSE.md for the specific license agreement that pertains to this Benchmark Software. */ /* Author : Shay Gal-On, EEMBC */ /* Topic: Description This file contains declarations of the various benchmark functions. */ /* Configuration: TOTAL_DATA_SIZE Define total size for data algorithms will operate on */ #ifndef _COREMARK_H_ #define _COREMARK_H_ #ifndef TOTAL_DATA_SIZE #define TOTAL_DATA_SIZE 2*1000 #endif #define SEED_ARG 0 #define SEED_FUNC 1 #define SEED_VOLATILE 2 #define MEM_STATIC 0 #define MEM_MALLOC 1 #define MEM_STACK 2 #include "core_portme.h" #if HAS_STDIO #include <stdio.h> #endif #if HAS_PRINTF #define ee_printf printf #endif /* Actual benchmark execution in iterate */ void *iterate(void *pres); /* Typedef: secs_ret For machines that have floating point support, get number of seconds as a double. Otherwise an unsigned int. */ #if HAS_FLOAT typedef double secs_ret; #else typedef ee_u32 secs_ret; #endif #if MAIN_HAS_NORETURN #define MAIN_RETURN_VAL #define MAIN_RETURN_TYPE void #else #define MAIN_RETURN_VAL 0 #define MAIN_RETURN_TYPE int #endif /* Misc useful functions */ ee_u16 crcu8(ee_u8 data, ee_u16 crc); ee_u16 crc16(ee_s16 newval, ee_u16 crc); ee_u16 crcu16(ee_u16 newval, ee_u16 crc); ee_u16 crcu32(ee_u32 newval, ee_u16 crc); ee_u8 check_data_types(); void *portable_malloc(ee_size_t size); void portable_free(void *p); ee_s32 parseval(char *valstring); /* Algorithm IDS */ #define ID_LIST (1<<0) #define ID_MATRIX (1<<1) #define ID_STATE (1<<2) #define ALL_ALGORITHMS_MASK (ID_LIST|ID_MATRIX|ID_STATE) #define NUM_ALGORITHMS 3 /* list data structures */ typedef struct list_data_s { ee_s16 data16; ee_s16 idx; } list_data; typedef struct list_head_s { struct list_head_s *next; struct list_data_s *info; } list_head; /*matrix benchmark related stuff */ #define MATDAT_INT 1 #if MATDAT_INT typedef ee_s16 MATDAT; typedef ee_s32 MATRES; #else typedef ee_f16 MATDAT; typedef ee_f32 MATRES; #endif typedef struct MAT_PARAMS_S { int N; MATDAT *A; MATDAT *B; MATRES *C; } mat_params; /* state machine related stuff */ /* List of all the possible states for the FSM */ typedef enum CORE_STATE { CORE_START=0, CORE_INVALID, CORE_S1, CORE_S2, CORE_INT, CORE_FLOAT, CORE_EXPONENT, CORE_SCIENTIFIC, NUM_CORE_STATES } core_state_e ; /* Helper structure to hold results */ typedef struct RESULTS_S { /* inputs */ ee_s16 seed1; /* Initializing seed */ ee_s16 seed2; /* Initializing seed */ ee_s16 seed3; /* Initializing seed */ void *memblock[4]; /* Pointer to safe memory location */ ee_u32 size; /* Size of the data */ ee_u32 iterations; /* Number of iterations to execute */ ee_u32 execs; /* Bitmask of operations to execute */ struct list_head_s *list; mat_params mat; /* outputs */ ee_u16 crc; ee_u16 crclist; ee_u16 crcmatrix; ee_u16 crcstate; ee_s16 err; /* ultithread specific */ core_portable port; } core_results; /* Multicore execution handling */ #if (MULTITHREAD>1) ee_u8 core_start_parallel(core_results *res); ee_u8 core_stop_parallel(core_results *res); #endif /* list benchmark functions */ list_head *core_list_init(ee_u32 blksize, list_head *memblock, ee_s16 seed); ee_u16 core_bench_list(core_results *res, ee_s16 finder_idx); /* state benchmark functions */ void core_init_state(ee_u32 size, ee_s16 seed, ee_u8 *p); ee_u16 core_bench_state(ee_u32 blksize, ee_u8 *memblock, ee_s16 seed1, ee_s16 seed2, ee_s16 step, ee_u16 crc); /* matrix benchmark functions */ ee_u32 core_init_matrix(ee_u32 blksize, void *memblk, ee_s32 seed, mat_params *p, ee_u32 N); ee_u16 core_bench_matrix(mat_params *p, ee_s16 seed, ee_u16 crc); extern volatile ee_u32 list_items; extern volatile ee_u32 state_size; extern volatile ee_u32 matrix_n; extern volatile ee_u32 total_data_size; extern volatile ee_u32 mem_req[32]; #endif /* _COREMARK_H_ */
let handler = async (m, { conn, text }) => { conn.hartatahta = conn.hartatahta ? conn.hartatahta : {} if (m.chat in conn.hartatahta) throw 'Masih ada yang sedang membuat\nTeks Custom Harta Tahta\ndi chat ini... tunggu sampai selesai' else conn.hartatahta[m.chat] = true m.reply('Sedang membuat...\nMohon tunggu sekitar 1 menit') try { let img = await ht(text ? text : ':v') conn.sendFile(m.chat, img, 'Harta Tahta.png', 'Nih Mantann', m) } finally { delete conn.hartatahta[m.chat] } } handler.help = ['customtahta <teks>'] handler.tags = ['sticker'] handler.command = /^(customtahta)$/i handler.limit = true module.exports = handler let { spawn } = require('child_process') let fs = require('fs') let path = require('path') let src = path.join(__dirname, '../src/') let tmp = path.join(__dirname, '../tmp/') let _font = path.join(src, 'font') let aesthetic = path.join(src, 'Aesthetic') function ht(text = '') { return new Promise((resolve, reject) => { let img = path.join(aesthetic, pickRandom(fs.readdirSync(aesthetic))) let font = path.join(_font, 'Roboto-Black.ttf') let w = 1024 let h = w let s = w + 'x' + h let xF = `(${noise('X', 2, w, 1)}+${noise('Y', 1, h, 1)})/2+128` let yF = `((${pickRandom(['', '-'])}${45 * w / 2048}*${pickRandom(['sin', 'cos'])}(X/${w}*4*PI))+${noise('X', 5, w, 0.8)}+${noise('Y', 2, h, 1)})/1.7+128` let fsize = 320 / 2048 * w let lh = 1.5 let format = ',format=rgb24' let layers = [ `[v:0]scale=${s}${format}[im]`, textArgs('', 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2-(text_h*${lh})`, w, h) + format + '[top]', textArgs(text, 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2`, w, h) + format + '[mid]', textArgs('', 'black', 'white', fsize, font, '(w-text_w)/2', `(h-text_h)/2+(text_h*${lh})`, w, h) + format + '[bot]', '[top][mid]blend=all_mode=addition[con]', '[con][bot]blend=all_mode=addition[txt]', `nullsrc=s=${s},geq='r=${xF}:g=${xF}:b=${xF}'[dx]`, `nullsrc=s=${s},geq='r=${yF}:g=${yF}:b=${yF}'[dy]`, '[txt][dx][dy]displace[wa]', '[im][wa]blend=all_mode=multiply:all_opacity=1' ] let o = 1 * new Date + '_harta_tahta.png' o = path.join(tmp, o) let args = [ '-y', '-i', img, '-filter_complex', layers.join(';'), '-frames:v', '1', o ] console.log(layers) console.log('ffmpeg', ...args) spawn('ffmpeg', args) .on('error', reject) .on('close', () => { try { resolve(fs.readFileSync(o)) fs.unlinkSync(o) } catch (e) { reject(e) } }) //.stderr.on('data', a => console.log(a+'')) }) } function noise(_var, depth = 4, s = 1024, freq) { let forms = [] for (let i = 0; i < depth; i++) forms.push( formula( _var, freq * rand(40, 80) * (s / 2048)/ s * ((i + 1) / 5), rand(-Math.PI, Math.PI), (i + 1) / depth * 8, 0 ) ) return forms.join('+') } function formula(_var, freq, offset, amp, add) { return `(${add.toFixed(3)}+${amp.toFixed(4)}*sin(${offset.toFixed(6)}+2*PI*${_var}*${freq.toFixed(6)}))` } function textArgs(text, background, color, size, fontfile, x = '200' , y = '200', w = 1024, h = 1024) { return `color=${background}:s=${w}x${h},drawtext=text='${text.replace(/[\\]/g, '\\$&')}':fontfile='${fontfile.replace(/[\\]/g, '\\$&')}':x=${x}:y=${y}:fontsize=${size}:fontcolor=${color}` } function pickRandom(list) { return list[Math.floor(Math.random() * list.length)] } function rand(min, max, q = 0.001) { return Math.floor((Math.random() * (max - min)) / q) * q }
import os import unittest2 as unittest from keystone.test.functional import common class TestExtensions(common.FunctionalTestCase): use_server = True def test_extensions_json(self): r = self.service_request(path='/extensions.json') self.assertTrue('json' in r.getheader('Content-Type')) content = r.json self.assertIsNotNone(content['extensions']) self.assertIsNotNone(content['extensions']['values']) def test_extensions_xml(self): r = self.service_request(path='/extensions.xml') self.assertTrue('xml' in r.getheader('Content-Type')) class TestAdminExtensions(common.ApiTestCase): use_server = True def test_extensions_json(self): r = self.admin_request(path='/extensions.json') self.assertTrue('json' in r.getheader('Content-Type')) content = r.json self.assertIsNotNone(content['extensions']) self.assertIsNotNone(content['extensions']['values']) found_osksadm = False found_oskscatalog = False found_hpidm = False for value in content['extensions']['values']: if value['extension']['alias'] == 'OS-KSADM': found_osksadm = True if value['extension']['alias'] == 'OS-KSCATALOG': found_oskscatalog = True if value['extension']['alias'] == 'HP-IDM': found_hpidm = True self.assertTrue(found_osksadm, "Missing OS-KSADM extension.") self.assertTrue(found_oskscatalog, "Missing OS-KSCATALOG extension.") if not common.isSsl() and 'HP-IDM_Disabled' not in os.environ: self.assertTrue(found_hpidm, "Missing HP-IDM extension.") def test_extensions_xml(self): r = self.admin_request(path='/extensions.xml') self.assertTrue('xml' in r.getheader('Content-Type')) content = r.xml extensions = content.findall( "{http://docs.openstack.org/common/api/v1.0}extension") found_osksadm = False found_oskscatalog = False found_hpidm = False for extension in extensions: if extension.get("alias") == 'OS-KSADM': found_osksadm = True if extension.get("alias") == 'OS-KSCATALOG': found_oskscatalog = True if extension.get("alias") == 'HP-IDM': found_hpidm = True self.assertTrue(found_osksadm, "Missing OS-KSADM extension.") self.assertTrue(found_oskscatalog, "Missing OS-KSCATALOG extension.") if not common.isSsl() and 'HP-IDM_Disabled' not in os.environ: self.assertTrue(found_hpidm, "Missing HP-IDM extension.") if __name__ == '__main__': unittest.main()
from __future__ import nested_scopes import weakref import sys from _pydevd_bundle.pydevd_comm import get_global_debugger from _pydevd_bundle.pydevd_constants import call_only_once from _pydev_imps._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import dict_items from _pydevd_bundle.pydevd_custom_frames import update_custom_frame, remove_custom_frame, add_custom_frame import stackless # @UnresolvedImport from _pydev_bundle import pydev_log # Used so that we don't loose the id (because we'll remove when it's not alive and would generate a new id for the # same tasklet). class TaskletToLastId: ''' So, why not a WeakKeyDictionary? The problem is that removals from the WeakKeyDictionary will create a new tasklet (as it adds a callback to remove the key when it's garbage-collected), so, we can get into a recursion. ''' def __init__(self): self.tasklet_ref_to_last_id = {} self._i = 0 def get(self, tasklet): return self.tasklet_ref_to_last_id.get(weakref.ref(tasklet)) def __setitem__(self, tasklet, last_id): self.tasklet_ref_to_last_id[weakref.ref(tasklet)] = last_id self._i += 1 if self._i % 100 == 0: # Collect at each 100 additions to the dict (no need to rush). for tasklet_ref in list(self.tasklet_ref_to_last_id.keys()): if tasklet_ref() is None: del self.tasklet_ref_to_last_id[tasklet_ref] _tasklet_to_last_id = TaskletToLastId() #======================================================================================================================= # _TaskletInfo #======================================================================================================================= class _TaskletInfo: _last_id = 0 def __init__(self, tasklet_weakref, tasklet): self.frame_id = None self.tasklet_weakref = tasklet_weakref last_id = _tasklet_to_last_id.get(tasklet) if last_id is None: _TaskletInfo._last_id += 1 last_id = _TaskletInfo._last_id _tasklet_to_last_id[tasklet] = last_id self._tasklet_id = last_id self.update_name() def update_name(self): tasklet = self.tasklet_weakref() if tasklet: if tasklet.blocked: state = 'blocked' elif tasklet.paused: state = 'paused' elif tasklet.scheduled: state = 'scheduled' else: state = '<UNEXPECTED>' try: name = tasklet.name except AttributeError: if tasklet.is_main: name = 'MainTasklet' else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_id = tasklet.thread_id if thread_id != -1: for thread in threading.enumerate(): if thread.ident == thread_id: if thread.name: thread_name = "of %s" % (thread.name,) else: thread_name = "of Thread-%s" % (thread.name or str(thread_id),) break else: # should not happen. thread_name = "of Thread-%s" % (str(thread_id),) thread = None else: # tasklet is no longer bound to a thread, because its thread ended thread_name = "without thread" tid = id(tasklet) tasklet = None else: state = 'dead' name = 'Tasklet-%s' % (self._tasklet_id,) thread_name = "" tid = '-' self.tasklet_name = '%s %s %s (%s)' % (state, name, thread_name, tid) if not hasattr(stackless.tasklet, "trace_function"): # bug https://bitbucket.org/stackless-dev/stackless/issue/42 # is not fixed. Stackless releases before 2014 def update_name(self): tasklet = self.tasklet_weakref() if tasklet: try: name = tasklet.name except AttributeError: if tasklet.is_main: name = 'MainTasklet' else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_id = tasklet.thread_id for thread in threading.enumerate(): if thread.ident == thread_id: if thread.name: thread_name = "of %s" % (thread.name,) else: thread_name = "of Thread-%s" % (thread.name or str(thread_id),) break else: # should not happen. thread_name = "of Thread-%s" % (str(thread_id),) thread = None tid = id(tasklet) tasklet = None else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_name = "" tid = '-' self.tasklet_name = '%s %s (%s)' % (name, thread_name, tid) _weak_tasklet_registered_to_info = {} #======================================================================================================================= # get_tasklet_info #======================================================================================================================= def get_tasklet_info(tasklet): return register_tasklet_info(tasklet) #======================================================================================================================= # register_tasklet_info #======================================================================================================================= def register_tasklet_info(tasklet): r = weakref.ref(tasklet) info = _weak_tasklet_registered_to_info.get(r) if info is None: info = _weak_tasklet_registered_to_info[r] = _TaskletInfo(r, tasklet) return info _application_set_schedule_callback = None #======================================================================================================================= # _schedule_callback #======================================================================================================================= def _schedule_callback(prev, next): ''' Called when a context is stopped or a new context is made runnable. ''' try: if not prev and not next: return current_frame = sys._getframe() if next: register_tasklet_info(next) # Ok, making next runnable: set the tracing facility in it. debugger = get_global_debugger() if debugger is not None: next.trace_function = debugger.get_thread_local_trace_func() frame = next.frame if frame is current_frame: frame = frame.f_back if hasattr(frame, 'f_trace'): # Note: can be None (but hasattr should cover for that too). frame.f_trace = debugger.get_thread_local_trace_func() debugger = None if prev: register_tasklet_info(prev) try: for tasklet_ref, tasklet_info in dict_items(_weak_tasklet_registered_to_info): # Make sure it's a copy! tasklet = tasklet_ref() if tasklet is None or not tasklet.alive: # Garbage-collected already! try: del _weak_tasklet_registered_to_info[tasklet_ref] except KeyError: pass if tasklet_info.frame_id is not None: remove_custom_frame(tasklet_info.frame_id) else: is_running = stackless.get_thread_info(tasklet.thread_id)[1] is tasklet if tasklet is prev or (tasklet is not next and not is_running): # the tasklet won't run after this scheduler action: # - the tasklet is the previous tasklet # - it is not the next tasklet and it is not an already running tasklet frame = tasklet.frame if frame is current_frame: frame = frame.f_back if frame is not None: # print >>sys.stderr, "SchedCB: %r, %d, '%s', '%s'" % (tasklet, frame.f_lineno, _filename, base) if debugger.get_file_type(frame) is None: tasklet_info.update_name() if tasklet_info.frame_id is None: tasklet_info.frame_id = add_custom_frame(frame, tasklet_info.tasklet_name, tasklet.thread_id) else: update_custom_frame(tasklet_info.frame_id, frame, tasklet.thread_id, name=tasklet_info.tasklet_name) elif tasklet is next or is_running: if tasklet_info.frame_id is not None: # Remove info about stackless suspended when it starts to run. remove_custom_frame(tasklet_info.frame_id) tasklet_info.frame_id = None finally: tasklet = None tasklet_info = None frame = None except: pydev_log.exception() if _application_set_schedule_callback is not None: return _application_set_schedule_callback(prev, next) if not hasattr(stackless.tasklet, "trace_function"): # Older versions of Stackless, released before 2014 # This code does not work reliable! It is affected by several # stackless bugs: Stackless issues #44, #42, #40 def _schedule_callback(prev, next): ''' Called when a context is stopped or a new context is made runnable. ''' try: if not prev and not next: return if next: register_tasklet_info(next) # Ok, making next runnable: set the tracing facility in it. debugger = get_global_debugger() if debugger is not None and next.frame: if hasattr(next.frame, 'f_trace'): next.frame.f_trace = debugger.get_thread_local_trace_func() debugger = None if prev: register_tasklet_info(prev) try: for tasklet_ref, tasklet_info in dict_items(_weak_tasklet_registered_to_info): # Make sure it's a copy! tasklet = tasklet_ref() if tasklet is None or not tasklet.alive: # Garbage-collected already! try: del _weak_tasklet_registered_to_info[tasklet_ref] except KeyError: pass if tasklet_info.frame_id is not None: remove_custom_frame(tasklet_info.frame_id) else: if tasklet.paused or tasklet.blocked or tasklet.scheduled: if tasklet.frame and tasklet.frame.f_back: f_back = tasklet.frame.f_back if debugger.get_file_type(f_back) is None: if tasklet_info.frame_id is None: tasklet_info.frame_id = add_custom_frame(f_back, tasklet_info.tasklet_name, tasklet.thread_id) else: update_custom_frame(tasklet_info.frame_id, f_back, tasklet.thread_id) elif tasklet.is_current: if tasklet_info.frame_id is not None: # Remove info about stackless suspended when it starts to run. remove_custom_frame(tasklet_info.frame_id) tasklet_info.frame_id = None finally: tasklet = None tasklet_info = None f_back = None except: pydev_log.exception() if _application_set_schedule_callback is not None: return _application_set_schedule_callback(prev, next) _original_setup = stackless.tasklet.setup #======================================================================================================================= # setup #======================================================================================================================= def setup(self, *args, **kwargs): ''' Called to run a new tasklet: rebind the creation so that we can trace it. ''' f = self.tempval def new_f(old_f, args, kwargs): debugger = get_global_debugger() if debugger is not None: debugger.enable_tracing() debugger = None # Remove our own traces :) self.tempval = old_f register_tasklet_info(self) # Hover old_f to see the stackless being created and *args and **kwargs to see its parameters. return old_f(*args, **kwargs) # This is the way to tell stackless that the function it should execute is our function, not the original one. Note: # setting tempval is the same as calling bind(new_f), but it seems that there's no other way to get the currently # bound function, so, keeping on using tempval instead of calling bind (which is actually the same thing in a better # API). self.tempval = new_f return _original_setup(self, f, args, kwargs) #======================================================================================================================= # __call__ #======================================================================================================================= def __call__(self, *args, **kwargs): ''' Called to run a new tasklet: rebind the creation so that we can trace it. ''' return setup(self, *args, **kwargs) _original_run = stackless.run #======================================================================================================================= # run #======================================================================================================================= def run(*args, **kwargs): debugger = get_global_debugger() if debugger is not None: debugger.enable_tracing() debugger = None return _original_run(*args, **kwargs) #======================================================================================================================= # patch_stackless #======================================================================================================================= def patch_stackless(): ''' This function should be called to patch the stackless module so that new tasklets are properly tracked in the debugger. ''' global _application_set_schedule_callback _application_set_schedule_callback = stackless.set_schedule_callback(_schedule_callback) def set_schedule_callback(callable): global _application_set_schedule_callback old = _application_set_schedule_callback _application_set_schedule_callback = callable return old def get_schedule_callback(): global _application_set_schedule_callback return _application_set_schedule_callback set_schedule_callback.__doc__ = stackless.set_schedule_callback.__doc__ if hasattr(stackless, "get_schedule_callback"): get_schedule_callback.__doc__ = stackless.get_schedule_callback.__doc__ stackless.set_schedule_callback = set_schedule_callback stackless.get_schedule_callback = get_schedule_callback if not hasattr(stackless.tasklet, "trace_function"): # Older versions of Stackless, released before 2014 __call__.__doc__ = stackless.tasklet.__call__.__doc__ stackless.tasklet.__call__ = __call__ setup.__doc__ = stackless.tasklet.setup.__doc__ stackless.tasklet.setup = setup run.__doc__ = stackless.run.__doc__ stackless.run = run patch_stackless = call_only_once(patch_stackless)
/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License versions 2.0 or 3.0 as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information ** to ensure GNU General Public Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. In addition, as a special ** exception, Nokia gives you certain additional rights. These rights ** are described in the Nokia Qt GPL Exception version 1.3, included in ** the file GPL_EXCEPTION.txt in this package. ** ** Qt for Windows(R) Licensees ** As a special exception, Nokia, as the sole copyright holder for Qt ** Designer, grants users of the Qt/Eclipse Integration plug-in the ** right for the Qt/Eclipse Integration to link to functionality ** provided by Qt Designer and its related libraries. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ****************************************************************************/ #ifndef QSCROLLBAR_H #define QSCROLLBAR_H #include <QtGui/qwidget.h> #include <QtGui/qabstractslider.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_SCROLLBAR class QScrollBarPrivate; class QStyleOptionSlider; class Q_GUI_EXPORT QScrollBar : public QAbstractSlider { Q_OBJECT public: explicit QScrollBar(QWidget *parent=0); explicit QScrollBar(Qt::Orientation, QWidget *parent=0); ~QScrollBar(); QSize sizeHint() const; bool event(QEvent *event); protected: void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void hideEvent(QHideEvent*); void sliderChange(SliderChange change); #ifndef QT_NO_CONTEXTMENU void contextMenuEvent(QContextMenuEvent *); #endif void initStyleOption(QStyleOptionSlider *option) const; #ifdef QT3_SUPPORT public: QT3_SUPPORT_CONSTRUCTOR QScrollBar(QWidget *parent, const char* name); QT3_SUPPORT_CONSTRUCTOR QScrollBar(Qt::Orientation, QWidget *parent, const char* name); QT3_SUPPORT_CONSTRUCTOR QScrollBar(int minValue, int maxValue, int lineStep, int pageStep, int value, Qt::Orientation, QWidget *parent=0, const char* name = 0); inline QT3_SUPPORT bool draggingSlider() { return isSliderDown(); } #endif private: friend Q_GUI_EXPORT QStyleOptionSlider qt_qscrollbarStyleOption(QScrollBar *scrollBar); Q_DISABLE_COPY(QScrollBar) Q_DECLARE_PRIVATE(QScrollBar) }; #endif // QT_NO_SCROLLBAR QT_END_NAMESPACE QT_END_HEADER #endif // QSCROLLBAR_H
/* * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include "sdkconfig.h" #include "esp_rom_efuse.h" #include "esp_system.h" #include "esp_efuse.h" #include "esp_efuse_table.h" /* esp_system.h APIs relating to MAC addresses */ #if CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR || \ CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_FOUR || \ CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_FOUR #define MAC_ADDR_UNIVERSE_BT_OFFSET 2 #else #define MAC_ADDR_UNIVERSE_BT_OFFSET 1 #endif #if CONFIG_IEEE802154_ENABLED #define ESP_MAC_ADDRESS_LEN 8 #else #define ESP_MAC_ADDRESS_LEN 6 #endif static const char *TAG = "system_api"; static uint8_t base_mac_addr[ESP_MAC_ADDRESS_LEN] = { 0 }; esp_err_t esp_base_mac_addr_set(const uint8_t *mac) { if (mac == NULL) { ESP_LOGE(TAG, "Base MAC address is NULL"); return ESP_ERR_INVALID_ARG; } if (mac[0] & 0x01) { ESP_LOGE(TAG, "Base MAC must be a unicast MAC"); return ESP_ERR_INVALID_ARG; } memcpy(base_mac_addr, mac, ESP_MAC_ADDRESS_LEN); return ESP_OK; } esp_err_t esp_base_mac_addr_get(uint8_t *mac) { if (mac == NULL) { return ESP_ERR_INVALID_ARG; } if (base_mac_addr[0] == 0 && memcmp(base_mac_addr, &base_mac_addr[1], ESP_MAC_ADDRESS_LEN - 1) == 0) { ESP_LOGI(TAG, "Base MAC address is not set"); return ESP_ERR_INVALID_MAC; } memcpy(mac, base_mac_addr, ESP_MAC_ADDRESS_LEN); return ESP_OK; } esp_err_t esp_efuse_mac_get_custom(uint8_t *mac) { #if !CONFIG_IDF_TARGET_ESP32 size_t size_bits = esp_efuse_get_field_size(ESP_EFUSE_USER_DATA_MAC_CUSTOM); assert((size_bits % 8) == 0); esp_err_t err = esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, size_bits); if (err != ESP_OK) { return err; } size_t size = size_bits / 8; if (mac[0] == 0 && memcmp(mac, &mac[1], size - 1) == 0) { ESP_LOGE(TAG, "eFuse MAC_CUSTOM is empty"); return ESP_ERR_INVALID_MAC; } #if (ESP_MAC_ADDRESS_LEN == 8) err = esp_efuse_read_field_blob(ESP_EFUSE_MAC_EXT, &mac[6], ESP_MAC_ADDRESS_LEN * 8 - size_bits); if (err != ESP_OK) { ESP_LOGE(TAG, "Reading MAC_EXT failed, error=%d", err); return err; } #endif return ESP_OK; #else uint8_t version; esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM_VER, &version, 8); if (version != 1) { ESP_LOGE(TAG, "Base MAC address from BLK3 of EFUSE version error, version = %d", version); return ESP_ERR_INVALID_VERSION; } uint8_t efuse_crc; esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48); esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM_CRC, &efuse_crc, 8); uint8_t calc_crc = esp_rom_efuse_mac_address_crc8(mac, 6); if (efuse_crc != calc_crc) { ESP_LOGE(TAG, "Base MAC address from BLK3 of EFUSE CRC error, efuse_crc = 0x%02x; calc_crc = 0x%02x", efuse_crc, calc_crc); return ESP_ERR_INVALID_CRC; } return ESP_OK; #endif } esp_err_t esp_efuse_mac_get_default(uint8_t *mac) { size_t size_bits = esp_efuse_get_field_size(ESP_EFUSE_MAC_FACTORY); assert((size_bits % 8) == 0); esp_err_t err = esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, size_bits); if (err != ESP_OK) { return err; } #if (ESP_MAC_ADDRESS_LEN == 8) err = esp_efuse_read_field_blob(ESP_EFUSE_MAC_EXT, &mac[6], ESP_MAC_ADDRESS_LEN * 8 - size_bits); if (err != ESP_OK) { ESP_LOGE(TAG, "Reading MAC_EXT failed, error=%d", err); return err; } #endif #ifdef CONFIG_IDF_TARGET_ESP32 // Only ESP32 has MAC CRC in efuse uint8_t efuse_crc; esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY_CRC, &efuse_crc, 8); uint8_t calc_crc = esp_rom_efuse_mac_address_crc8(mac, 6); if (efuse_crc != calc_crc) { // Small range of MAC addresses are accepted even if CRC is invalid. // These addresses are reserved for Espressif internal use. uint32_t mac_high = ((uint32_t)mac[0] << 8) | mac[1]; uint32_t mac_low = ((uint32_t)mac[2] << 24) | ((uint32_t)mac[3] << 16) | ((uint32_t)mac[4] << 8) | mac[5]; if (((mac_high & 0xFFFF) == 0x18fe) && (mac_low >= 0x346a85c7) && (mac_low <= 0x346a85f8)) { return ESP_OK; } else { ESP_LOGE(TAG, "Base MAC address from BLK0 of EFUSE CRC error, efuse_crc = 0x%02x; calc_crc = 0x%02x", efuse_crc, calc_crc); abort(); } } #endif // CONFIG_IDF_TARGET_ESP32 return ESP_OK; } esp_err_t esp_derive_local_mac(uint8_t *local_mac, const uint8_t *universal_mac) { if (local_mac == NULL || universal_mac == NULL) { ESP_LOGE(TAG, "mac address param is NULL"); return ESP_ERR_INVALID_ARG; } memcpy(local_mac, universal_mac, 6); const unsigned UL_BIT = 0x2; local_mac[0] |= UL_BIT; if (local_mac[0] == universal_mac[0]) { // universal_mac was already local, so flip this bit instead // (this is kept to be compatible with the previous behaviour of this function) local_mac[0] ^= 0x4; } return ESP_OK; } esp_err_t esp_read_mac(uint8_t *mac, esp_mac_type_t type) { uint8_t efuse_mac[ESP_MAC_ADDRESS_LEN]; if (mac == NULL) { ESP_LOGE(TAG, "mac address param is NULL"); return ESP_ERR_INVALID_ARG; } #if CONFIG_IEEE802154_ENABLED if (type < ESP_MAC_WIFI_STA || type > ESP_MAC_IEEE802154) { #else if (type < ESP_MAC_WIFI_STA || type > ESP_MAC_ETH) { #endif ESP_LOGE(TAG, "mac type is incorrect"); return ESP_ERR_INVALID_ARG; } // if base mac address is not set, read one from EFUSE and then write back if (esp_base_mac_addr_get(efuse_mac) != ESP_OK) { ESP_LOGI(TAG, "read default base MAC address from EFUSE"); esp_efuse_mac_get_default(efuse_mac); esp_base_mac_addr_set(efuse_mac); } switch (type) { case ESP_MAC_WIFI_STA: memcpy(mac, efuse_mac, 6); break; case ESP_MAC_WIFI_SOFTAP: #if CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP memcpy(mac, efuse_mac, 6); // as a result of some esp32s2 chips burned with one MAC address by mistake, // there are some MAC address are reserved for this bug fix. // related mistake MAC address is 0x7cdfa1003000~0x7cdfa1005fff, // reserved MAC address is 0x7cdfa1020000~0x7cdfa1022fff (MAC address + 0x1d000). #ifdef CONFIG_IDF_TARGET_ESP32S2 uint8_t mac_begin[6] = { 0x7c, 0xdf, 0xa1, 0x00, 0x30, 0x00 }; uint8_t mac_end[6] = { 0x7c, 0xdf, 0xa1, 0x00, 0x5f, 0xff }; if (memcmp(mac, mac_begin, 6) >= 0 && memcmp(mac_end, mac, 6) >= 0 ) { mac[3] += 0x02; // contain carry bit mac[4] += 0xd0; } else { mac[5] += 1; } #else mac[5] += 1; #endif // IDF_TARGET_ESP32S2 #else esp_derive_local_mac(mac, efuse_mac); #endif // CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP break; case ESP_MAC_BT: #if CONFIG_ESP_MAC_ADDR_UNIVERSE_BT memcpy(mac, efuse_mac, 6); #if !CONFIG_IDF_TARGET_ESP32H2 // esp32h2 chips do not have wifi module, so the mac address do not need to add the BT offset mac[5] += MAC_ADDR_UNIVERSE_BT_OFFSET; #endif //!CONFIG_IDF_TARGET_ESP32H2 #else return ESP_ERR_NOT_SUPPORTED; #endif // CONFIG_ESP_MAC_ADDR_UNIVERSE_BT break; case ESP_MAC_ETH: #if CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH memcpy(mac, efuse_mac, 6); mac[5] += 3; #else efuse_mac[5] += 1; esp_derive_local_mac(mac, efuse_mac); #endif // CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH break; #if CONFIG_IEEE802154_ENABLED case ESP_MAC_IEEE802154: memcpy(mac, efuse_mac, 8); break; #endif default: ESP_LOGE(TAG, "unsupported mac type"); break; } return ESP_OK; }
(function(e){e.fn.inlineStyler=function(t){var n=e.extend({propertyGroups:{"*":["border","border-radius","box-shadow","height","margin","padding","width","max-width","min-width","border-collapse","border-spacing","caption-side","empty-cells","table-layout","direction","font","font-family","font-style","font-variant","font-size","font-weight","letter-spacing","line-height","text-align","text-decoration","text-indent","text-overflow","text-shadow","text-transform","white-space","word-spacing","word-wrap","vertical-align","color","background","background-color","background-image","background-position","background-repeat","Opacity","bottom","clear","clip","cursor","display","float","left","opacity","outline ","overflow","position","resize ","right","top","visibility","z-index","list-style-image","list-style-position","list-style-type"],block:["margin","padding"]},elementGroups:{"*":["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","ARTICLE","ASIDE","AUDIO","B","BASE","BASEFONT","BDI","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CANVAS","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","COMMAND","DATALIST","DD","DEL","DETAILS","DFN","DIALOG","DIR","DIV","DL","DT","EM","EMBED","FIELDSET","FIGCAPTION","FIGURE","FONT","FOOTER","FORM","FRAME","FRAMESET","H1","HEAD","HEADER","HR","HTML","I","IFRAME","IMG","INPUT","INS","KBD","KEYGEN","LABEL","LEGEND","LI","LINK","MAP","MARK","MENU","META","METER","NAV","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","OUTPUT","P","PARAM","PRE","PROGRESS","Q","RP","RT","RUBY","S","SAMP","SCRIPT","SECTION","SELECT","SMALL","SOURCE","SPAN","STRIKE","STRONG","STYLE","SUB","SUMMARY","SUP","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TIME","TITLE","TR","TRACK","TT","U","UL","VAR","VIDEO","WBR"]}},t);this.each(function(t,r){for(var i in n.elementGroups){for(var s=0,o=n.elementGroups[i].length;s<o;s++){var u=e(this).find(n.elementGroups[i][s]);u.each(function(){if(e(this).attr("style")){var t=e(this).attr("style");var r=t.split(";")}else{var r=[]}for(var s=0,o=n.propertyGroups[i].length;s<o;s++){var u=n.propertyGroups[i][s];if(e(this).css(u)){r.push(u+":"+e(this).css(u))}}e(this).attr("style",r.join(";"))})}}})}})(jQuery)
import datetime from typing import Union, ClassVar from dataclasses import dataclass, asdict from json_coder import jsonify UNDEFINED_XPAIR = "undefined-x-pair" ROUTED_TYPES = ("get", "post", "put", "patch", "del", "all") INCOMING_REQ_TYPES = ("rpcIn", *ROUTED_TYPES) OUTGOING_REQ_TYPES = ("rpcOut",) MARK_START = "start" MARK_END = "end" LOG_SUBTYPES = [] class LogMeta(type): def __new__(cls, name, bases, attrs): new_cls = type.__new__(cls, name, bases, attrs) if attrs["_special_keys"]: LOG_SUBTYPES.append(new_cls) return new_cls @jsonify("logentry") @dataclass class LogEntry(metaclass=LogMeta): _special_keys: ClassVar = tuple() # ignore field for dataclasses timestamp: datetime.datetime data: dict platform: str @property def id(self): return (self.context_id, self.x_pair) @property def event(self): return self.data["event"] @property def fn(self): return self.data["fn"] @property def function(self): return self.fn["name"] @classmethod def match(cls, event): if not cls._special_keys: raise NotImplementedError("Cannot match log data without defined identifying keys.") return all(key in event.event for key in cls._special_keys) @property def x_pair(self): label_xpair = self.event.get("xPair", UNDEFINED_XPAIR) if label_xpair == UNDEFINED_XPAIR: return UNDEFINED_XPAIR _, xpair = label_xpair.split("-") return xpair @property def context_id(self): return self.event.get("contextId", None) class RequestLog(LogEntry): _special_keys: ClassVar = ("request",) @property def request(self): return self.event["request"] class PerfLog(LogEntry): _special_keys: ClassVar = ("perf",) @property def perf(self): return self.event["perf"] @property def type(self): return self.perf["entryType"] @property def perf_type(self): mark_type, perf_type, *_ = self.perf["mark"].split(":") return (mark_type, perf_type) @property def perf_type_data(self): perfs = self.perf["mark"].split(":") if len(perfs) < 3: return "" return ":".join(perfs[2:]) @property def perf_name(self): return self.perf["name"] def _get_perf_name(self): splitted = self.perf_name.split(":") fname, context_id, xpair, *perftype = splitted perftype = ":".join(perftype) return fname, context_id, xpair, perftype @staticmethod def is_incoming_entry(entry): return any(t == entry.perf_type[1] for t in INCOMING_REQ_TYPES) @staticmethod def is_routed_entry(entry): return any(t == entry.perf_type[1] for t in ROUTED_TYPES) @staticmethod def is_outgoing_entry(entry): return any(t == entry.perf_type[1] for t in OUTGOING_REQ_TYPES) class ColdstartLog(LogEntry): _special_keys: ClassVar = ("coldstart",) @property def coldstart(self): return self.event["coldstart"] class ArtilleryLog(LogEntry): _special_keys: ClassVar = ("url", "type") @property def called_id(self): return super().id @property def id(self): return (self.context_id, UNDEFINED_XPAIR) @property def type(self): return self.event["type"] @property def url(self): return self.event["url"] def cast_log_type(entry: LogEntry) -> Union[RequestLog, PerfLog]: for subtype in LOG_SUBTYPES: if subtype.match(entry): return subtype(**asdict(entry)) print(f"Unknown log type: {entry}") return entry
# # The Python Imaging Library. # $Id$ # # transform wrappers # # History: # 2002-04-08 fl Created # # Copyright (c) 2002 by Secret Labs AB # Copyright (c) 2002 by Fredrik Lundh # # See the README file for information on usage and redistribution. # from . import Image class Transform(Image.ImageTransformHandler): def __init__(self, data): self.data = data def getdata(self): return self.method, self.data def transform(self, size, image, **options): # can be overridden method, data = self.getdata() return image.transform(size, method, data, **options) class AffineTransform(Transform): """ Define an affine image transform. This function takes a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. This function can be used to scale, translate, rotate, and shear the original image. See :py:meth:`~PIL.Image.Image.transform` :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows from an affine transform matrix. """ method = Image.AFFINE class ExtentTransform(Transform): """ Define a transform to extract a subregion from an image. Maps a rectangle (defined by two corners) from the image to a rectangle of the given size. The resulting image will contain data sampled from between the corners, such that (x0, y0) in the input image will end up at (0,0) in the output image, and (x1, y1) at size. This method can be used to crop, stretch, shrink, or mirror an arbitrary rectangle in the current image. It is slightly slower than crop, but about as fast as a corresponding resize operation. See :py:meth:`~PIL.Image.Image.transform` :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the input image's coordinate system. See :ref:`coordinate-system`. """ method = Image.EXTENT class QuadTransform(Transform): """ Define a quad image transform. Maps a quadrilateral (a region defined by four corners) from the image to a rectangle of the given size. See :py:meth:`~PIL.Image.Image.transform` :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral. """ method = Image.QUAD class MeshTransform(Transform): """ Define a mesh image transform. A mesh transform consists of one or more individual quad transforms. See :py:meth:`~PIL.Image.Image.transform` :param data: A list of (bbox, quad) tuples. """ method = Image.MESH
from defusedxml import ElementTree as ET from xml.etree.ElementTree import ElementTree, Element from math import floor from typing import Tuple def cap(number, min_, max_): """Cap a value between a lower and/or upper bound (inclusive)""" if min_ is not None and number < min_: return min_ if max_ is not None and number > max_: return max_ return number def _str_to_bool(s): return s != "0" def _bool_to_str(b): return "1" if b else "0" class Card: def __init__(self, xml_element): self._card = xml_element self._item_action = self._card.find("ItemActionComponent") self._card_item_component = self._card.find("ItemComponent") def get_action_id(self): """The type of card/spell""" return self._item_action.get('action_id') @property def permanently_attached(self): """On wands cards (spells) can be permanently attached. They consume not slot and are always cast on use.""" return _str_to_bool(self._card_item_component.get("permanently_attached")) @permanently_attached.setter def permanently_attached(self, is_attached): self._card_item_component.set("permanently_attached", _bool_to_str(is_attached)) @property def uses_remaining(self): return int(self._card_item_component.get("uses_remaining")) @uses_remaining.setter def uses_remaining(self, uses): uses = cap(uses, -1, None) self._card_item_component.set("uses_remaining", str(uses)) @property def inventory_slot(self) -> Tuple[int, int]: x = self._card_item_component.get("inventory_slot.x") y = self._card_item_component.get("inventory_slot.y") return int(x), int(y) @inventory_slot.setter def inventory_slot(self, slot: Tuple[int, int]): # TODO set cap to actual inventory size x = cap(slot[0], 0, 15) y = cap(slot[1], 0, 15) self._card_item_component.set("inventory_slot.x", str(x)) self._card_item_component.set("inventory_slot.y", str(y)) class Wand: def __init__(self, xml_element): self._wand = xml_element self._abilities = self._wand.find("AbilityComponent") self._gun_config = self._abilities.find("gun_config") self._gun_action_config = self._abilities.find("gunaction_config") self.cards = [] cards = self._wand.findall("Entity[@tags='card_action']") for c in cards: self.cards.append(Card(c)) def get_name(self): return self._abilities.get("ui_name") @property def mana(self): return float(self._abilities.get("mana")) @mana.setter def mana(self, mana): self._abilities.set("mana", str(mana)) @property def mana_recharge(self): return float(self._abilities.get("mana_charge_speed")) @mana_recharge.setter def mana_recharge(self, mana_recharge): self._abilities.set("mana_charge_speed", str(mana_recharge)) @property def mana_max(self): return float(self._abilities.get("mana_max")) @mana_max.setter def mana_max(self, mana_max): self._abilities.set("mana_max", str(mana_max)) @property def spells_cast(self): """The number of spells cast simultaneously per shot.""" return int(self._gun_config.get("actions_per_round")) @spells_cast.setter def spells_cast(self, spells_cast): self._gun_config.set("actions_per_round", str(spells_cast)) @property def capacity(self): return int(self._gun_config.get("deck_capacity")) @capacity.setter def capacity(self, capacity): """Set the number of slots a Wand has. Capped at 30.""" # not sure if the game has a hard cap of slots for a wand but 28 is the biggest seen so far, # anything bigger than 30 would be hard to display in the game anyway capacity = cap(capacity, 0, 30) self._gun_config.set("deck_capacity", str(capacity)) @property def reload_time(self): return float(self._gun_config.get("reload_time")) @reload_time.setter def reload_time(self, reload_time): reload_time = cap(reload_time, 0, None) self._gun_config.set("reload_time", str(reload_time)) @property def cast_delay(self): return float(self._gun_action_config.get("fire_rate_wait")) @cast_delay.setter def cast_delay(self, cast_delay): cast_delay = cap(cast_delay, 0, None) self._gun_action_config.set("fire_rate_wait", str(cast_delay)) @property def shuffles(self): return _str_to_bool(self._gun_config.get("shuffle_deck_when_empty")) @shuffles.setter def shuffles(self, shuffles): self._gun_config.set("shuffle_deck_when_empty", _bool_to_str(shuffles)) @property def spread_degrees(self): """Sets/gets the spread in degrees ranging from 0 to 180""" return float(self._gun_action_config.get("spread_degrees")) @spread_degrees.setter def spread_degrees(self, degrees): # I assume 180 is max, I never tested was the maximum is but with a # spread higher than that, actually hitting something can be impossible. # 180° is already insane. degrees = cap(degrees, 0, 180) self._gun_action_config.set("spread_degrees", str(degrees)) class SaveGame: def __init__(self): self._quick_inventory = None self.inventory = [] self._full_inventory = None self._wallet = None self._damage_model = None self._inventory_component = None self._character_data = None self._element_tree = None self._root = None self.wands = [] def load(self, file_path): self._element_tree = ET.parse(file_path) self._root = self._element_tree.getroot() self._character_data = self._root.find("CharacterDataComponent") self._inventory_component = self._root.find("Inventory2Component") # full_inventory_slots = ( # inventory_component.get("full_inventory_slots_x"), inventory_component.get("full_inventory_slots_y")) self._damage_model = self._root.find("DamageModelComponent") self._wallet = self._root.find("WalletComponent") self._load_inventory() def _load_inventory(self): self._quick_inventory = self._root.find("Entity[@name='inventory_quick']") self.wands.clear() wands = self._quick_inventory.iterfind("Entity") for wand in wands: tags = wand.get("tags").split(",") if "wand" not in tags: continue w = Wand(wand) self.wands.append(w) self._full_inventory = self._root.find("Entity[@name='inventory_full']") cards = self._full_inventory.findall("Entity[@tags='card_action']") self.inventory.clear() for c in cards: self.inventory.append(Card(c)) @property def flying_needs_recharge(self): return self._character_data.get("flying_needs_recharge") == "1" @flying_needs_recharge.setter def flying_needs_recharge(self, b): self._character_data.set("flying_needs_recharge", _bool_to_str(b)) @property def inventory_bars(self): """Sets/Gets the number of bars of the full inventory as a number between 1 and 16 (inclusive) if value is outside the range it gets capped at min/maximum.""" return int(self._inventory_component.get("full_inventory_slots_y")) @inventory_bars.setter def inventory_bars(self, number_of_bars): number_of_bars = cap(number_of_bars, 1, 16) self._inventory_component.set("full_inventory_slots_y", str(number_of_bars)) @property def air_needed(self): """If set to true, player does not run out of air when underwater.""" return _str_to_bool(self._damage_model.get("air_needed")) @air_needed.setter def air_needed(self, b): self._damage_model.set("air_needed", _bool_to_str(b)) @property def current_health(self): hp = self._damage_model.get("hp") return self._float_to_health(float(hp)) @current_health.setter def current_health(self, health): hp = self._health_to_float(health) self._damage_model.set("hp", str(hp)) @property def max_health(self): hp = self._damage_model.get("max_hp") return self._float_to_health(float(hp)) @max_health.setter def max_health(self, health): hp = self._health_to_float(health) self._damage_model.set("max_hp", str(hp)) @property def health_cap(self): hp = self._damage_model.get("max_hp_cap") return self._float_to_health(float(hp)) @health_cap.setter def health_cap(self, health): hp = self._health_to_float(health) self._damage_model.set("max_hp_cap", str(hp)) @property def money(self): return int(self._wallet.get("money")) @money.setter def money(self, money): if money < 0: money = 0 self._wallet.set("money", str(money)) def save(self, file_path): self._element_tree.write(file_path) def clone_card(self, card): """Todo: implement inventory management, maybe""" pass def heal(self): """Sets the health to its current maximum""" self._damage_model.set("hp", self._damage_model.get("max_hp")) def export_inventory(self, file): """Exports the contents and the size of the current inventory.""" root = Element("inventory") root.set("inventory_slots_x", self._inventory_component.get("full_inventory_slots_x")) root.set("inventory_slots_y", self._inventory_component.get("full_inventory_slots_y")) root.append(self._full_inventory) root.append(self._quick_inventory) inventory_tree = ElementTree(root) inventory_tree.write(file) def import_inventory(self, file): """Imports a previously exported inventory and sets the size accordingly.""" tree: ElementTree = ET.parse(file) root = tree.getroot() size_x = root.get("inventory_slots_x") size_y = root.get("inventory_slots_y") imported_full_inventory = root.find("Entity[@name='inventory_full']") imported_quick_inventory = root.find("Entity[@name='inventory_quick']") self._root.remove(self._full_inventory) self._root.remove(self._quick_inventory) self._root.append(imported_quick_inventory) self._root.append(imported_full_inventory) self._load_inventory() self._inventory_component.set("full_inventory_slots_x", size_x) self._inventory_component.set("full_inventory_slots_y", size_y) def update_spell_library(self): pass @staticmethod def _float_to_health(f): """Converts the game's multiplier notation to the actual value as seen on the health bar""" return floor(f * 25) @staticmethod def _health_to_float(i): """Converts the value to the game's multiplier notation.""" return i / 25.0 def print_stuff(save): print("Flying nees recharge:", save.flying_needs_recharge) print("Number of inventory bars:", save.inventory_bars) print("Air needed:", save.air_needed) print("Money:", save.money) print(f"Health: {save.current_health} of {save.max_health}") print("Health cap:", save.health_cap) print() print("Wands") for wand in save.wands: print(wand.get_name()) print(f"Mana {wand.mana} of {wand.mana_max}") print("Mana recharge:", wand.mana_recharge) print("Shuffles:", wand.shuffles) print("Spread:", wand.spread_degrees) print("Spells cast:", wand.spells_cast) print("Capacity", wand.capacity) print("Reload", wand.reload_time) print("Cards:") for card in wand.cards: ammo = card.uses_remaining perm = card.permanently_attached print(card.inventory_slot, card.get_action_id(), "Permanent" if perm else "", ammo if ammo != -1 else "") print() print("Inventory") for card in save.inventory: ammo = card.uses_remaining print(card.inventory_slot, card.get_action_id(), ammo if ammo != -1 else "")
from games.game_interface import Game class Challenge(Game.Action): """This action cannot be played directly""" async def validate(self, game, sid, target=None) -> bool: return False async def activate(self, game, sid, target=None): pass class Income(Game.Action): async def validate(self, game, sid, target=None) -> bool: return game.players[sid].state['coins'] < 10 async def activate(self, game, sid, target=None): game.players[sid].state['coins'] += 1 class ForeignAid(Game.Action): async def validate(self, game, sid, target=None) -> bool: return game.players[sid].state['coins'] < 10 async def activate(self, game, sid, target=None): game.players[sid].state['coins'] += 2 class Coup(Game.Action): async def validate(self, game, sid, target=None) -> bool: return game.players[sid].state['coins'] >= 7 and target is not None and sid != target async def activate(self, game, sid, target=None): game.players[sid].state['coins'] -= 7 await game.kill(target) class Duke(Game.Action): async def validate(self, game, sid, target=None): return game.players[sid].state['coins'] < 10 async def activate(self, game, sid, target=None): game.players[sid].state['coins'] += 3 class Contessa(Game.Action): """This action cannot be played directly""" async def validate(self, game, sid, target=None) -> bool: return False async def activate(self, game, sid, target=None): pass class Captain(Game.Action): async def validate(self, game, sid, target=None): return game.players[sid].state['coins'] < 10 and target is not None and sid != target async def activate(self, game, sid, target=None): amount = min(2, game.players[target].state['coins']) game.players[target].state['coins'] -= amount game.players[sid].state['coins'] += amount class Assassin(Game.Action): async def validate(self, game, sid, target=None): return 3 <= game.players[sid].state['coins'] < 10 and target is not None and sid != target async def activate(self, game, sid, target=None): game.players[sid].state['coins'] -= 3 await game.kill(target) class Ambassador(Game.Action): async def validate(self, game, sid, target=None): return True async def activate(self, game, sid, target=None): await game.swap(sid, 2) class Inquisitor(Game.Action): async def validate(self, game, sid, target=None): return True async def activate(self, game, sid, target=None): if target is None: await game.swap(sid, 1) else: await game.lookup(sid, target)
import requests from ..constants import INDEX_FIELDS_URL, FOLDERS_URL class IndexFieldService: def __init__(self, vault): self.vault = vault def get_index_fields(self, query=''): """ get all index fields or filter by query :param query: string, example: "label = 'TestField'" :return: dict """ request_url = self.vault.base_url + INDEX_FIELDS_URL if query: request_url += '?q=' + query headers = self.vault.get_auth_headers() resp = requests.get(request_url, headers=headers).json() return resp def create_index_field(self, label, description, field_type, required, default_value, query_value_field='', query_display_field='', query_id='00000000-0000-0000-0000-000000000000', drop_down_list_id='00000000-0000-0000-0000-000000000000'): """ creates a new index field definition :param label: string :param description: string :param field_type: int example: TODO: document field_type ENUM :param required: bool :param default_value: string :param query_value_field: string, default: empty string :param query_display_field: string, default: empty string :param query_id: string uuid4, default: empty uuid4 :param drop_down_list_id: string uuid4, default: empty uuid4 :return: dict """ request_url = self.vault.base_url + INDEX_FIELDS_URL headers = self.vault.get_auth_headers() payload = { 'label': label, 'description': description, 'fieldType': field_type, 'queryId': query_id, 'dropDownListId': drop_down_list_id, 'queryValueField': query_value_field, 'queryDisplayField': query_display_field, 'required': required, 'defaultValue': default_value } resp = requests.post(request_url, headers=headers, data=payload).json() return resp def update_index_field(self, index_field_id, label, description, required, default_value, query_value_field='', query_display_field='', query_id='00000000-0000-0000-0000-000000000000', drop_down_list_id='00000000-0000-0000-0000-000000000000'): """ updates an index field definition :param index_field_id: string uuid4 :param label: string :param description: string :param required: bool :param default_value: string :param query_value_field: string, default: empty string :param query_display_field: string, default: empty string :param query_id: string uuid4, default: empty uuid4 :param drop_down_list_id: string uuid4, default: empty uuid4 :return: dict """ request_url = self.vault.base_url + INDEX_FIELDS_URL + '/' + index_field_id headers = self.vault.get_auth_headers() payload = { 'label': label, 'description': description, 'queryId': query_id, 'dropDownListId': drop_down_list_id, 'queryValueField': query_value_field, 'queryDisplayField': query_display_field, 'required': required, 'defaultValue': default_value } resp = requests.put(request_url, headers=headers, data=payload).json() return resp def relate_index_field_to_folder(self, field_id, folder_id): endpoint = INDEX_FIELDS_URL + '/' + field_id + '/' + FOLDERS_URL + '/' + folder_id request_url = self.vault.base_url + endpoint headers = self.vault.get_auth_headers() resp = requests.put(request_url, headers=headers).json() return resp
""" server side redis listener. - logging - exception handling """ import os import sys import json import toml import msgpack import requests import redis import threading import time import etcd import gevent from gevent.pool import Pool from gevent import monkey monkey.patch_all() conf_fn = os.sep.join( [os.path.split(os.path.realpath(__file__))[0], "listener.toml"]) # print conf_fn with open(conf_fn) as conf_fh: cfg = toml.loads(conf_fh.read()) conf = cfg["redis"] etcd_cfg = cfg["etcd"] db = redis.client.StrictRedis( host=conf["HOST"], port=conf["PORT"], db=conf["DB"]) etc = etcd.Client(host=etcd_cfg["HOST"], port=etcd_cfg["PORT"]) lua_file = conf["HEARTBEAT_LUA"] print lua_file with open(lua_file, "r") as fileh: lua_script = fileh.read() sha = db.script_load(lua_script) # print sha def strict_time(): if sys.platform == "win32": return time.clock() else: return time.time() def post(data): print data URL = conf["JSONRPC"] payload = { "jsonrpc": "2.0", "id": "r2", "method": "call", "params": { "method": conf["METHOD"], "table": conf["TABLE"], "pkey": conf["PKEY"], "columns": data, "context": { "user": "mt", "languageid": "1033", "sessionid": "123"}}} HEADERS = { 'content-type': 'application/json', 'accept': 'json', 'User-Agent': 'mabo'} payload = json.dumps(payload) resp = requests.post(URL, data=payload, headers=HEADERS) s = resp.text # .encode("utf8") v = json.loads(s) if "error" in v: print s.encode("utf8") def callback(): """ run in thread """ sub = db.pubsub() channels = ['new_data'] for channel in channels: sub.subscribe(channel) while True: for msg in sub.listen(): if msg["type"] == 'message': queue_len = db.llen("data_queue") for i in xrange(0, queue_len): v = db.lpop("data_queue") data = msgpack.unpackb(v) # print queue_len, data try: print data #del data["heartbeat"] #del data["time_precision"] data = {"id":data["id"], "ch_ori_eqpt":data["ch_ori_eqpt"]} post(data) except Exception as ex: print "post data exception:", ex else: # print "channel: %s" %(m["channel"]) pass def new_thread(): """ new thread """ t = threading.Thread(target=callback) t.setDaemon(True) t.start() def etcd_write(key): etc.write("/heartbeat/%s" % (key), 1, ttl=conf["SLEEP"]) pass def check_heartbeat(): """ check heartbeat by lua in redis and update etcd if no etcd? """ name = conf["NAME"] etcd_write(name) collectors = conf["COLLECTORS"] now = 1000 * time.time() for key in collectors: print now print 1000 * conf["SLEEP"] # status = db.evalsha(sha, 1, key, now, 1000 * conf["SLEEP"]) print "%s heartbeat: %s" % (key, status) if status == "On": etcd_write(key) #etc.write("/heartbeat/%s" % (key), 1, ttl=conf["SLEEP"]) def main(): """ main """ new_thread() pool = Pool(conf["POOL_SIZE"]) while True: pool.spawn(check_heartbeat) #print "1" gevent.sleep(conf["SLEEP"]) if __name__ == '__main__': main()
import torch from vap_turn_taking.utils import ( find_island_idx_len, get_dialog_states, get_last_speaker, ) class HoldShift: """ Hold/Shift extraction from VAD. Operates of Frames. Arguments: post_onset_shift: int, frames for shift onset cond pre_offset_shift: int, frames for shift offset cond post_onset_hold: int, frames for hold onset cond pre_offset_hold: int, frames for hold offset cond metric_pad: int, pad on silence (shift/hold) onset used for evaluating metric_dur: int, duration off silence (shift/hold) used for evaluating metric_pre_label_dur: int, frames prior to Shift-silence for prediction on-active shift non_shift_horizon: int, frames to define majority speaker window for Non-shift non_shift_majority_ratio: float, ratio of majority speaker Return: dict: {'shift', 'pre_shift', 'hold', 'pre_hold', 'non_shift'} Active: "---" Silent: "..." # SHIFTS onset: |<-- only A -->| A: ...........................|------------------- B: ----------------|.............................. offset: |<-- only B -->| SHIFT: |XXXXXXXXXX| ----------------------------------------------------------- # HOLDS onset: |<-- only B -->| A: ............................................... B: ----------------|..........|------------------- offset: |<-- only B -->| HOLD: |XXXXXXXXXX| ----------------------------------------------------------- # NON-SHIFT Horizon: |<-- B majority -->| A: .....................................|--------- B: ----------------|......|------|................ non_shift: |XXXXXXXXXXXXXXXXXXX| A future horizon window must contain 'majority' activity from from the last speaker. In these moments we "know" a shift is a WRONG prediction. But closer to activity from the 'other' speaker, a turn-shift is appropriate. ----------------------------------------------------------- # metrics e.g. shift onset: |<-- only A -->| A: ...............................|--------------- B: ----------------|.............................. offset: |<-- only B -->| SHIFT: |XXXXXXXXXXXXXX| metric: |...|XXXXXX| metric: |pad| dur | ----------------------------------------------------------- Using 'dialog states' consisting of 4 different states 0. Only A is speaking 1. Silence 2. Overlap 3. Only B is speaking Shift GAP: 0 -> 1 -> 3 3 -> 1 -> 0 Shift Overlap: 0 -> 2 -> 3 3 -> 2 -> 0 HOLD: 0 -> 1 -> 0 3 -> 1 -> 3 """ def __init__( self, post_onset_shift, pre_offset_shift, post_onset_hold, pre_offset_hold, non_shift_horizon, metric_pad, metric_dur, metric_pre_label_dur, metric_onset_dur, non_shift_majority_ratio=1, ): assert ( metric_onset_dur <= post_onset_shift ), "`metric_onset_dur` must be less or equal to `post_onset_shift`" self.post_onset_shift = post_onset_shift self.pre_offset_shift = pre_offset_shift self.post_onset_hold = post_onset_hold self.pre_offset_hold = pre_offset_hold self.metric_pad = metric_pad self.metric_dur = metric_dur self.min_silence = metric_pad + metric_dur self.metric_pre_label_dur = metric_pre_label_dur self.metric_onset_dur = metric_onset_dur self.non_shift_horizon = non_shift_horizon self.non_shift_majority_ratio = non_shift_majority_ratio # Templates self.shift_template = torch.tensor([[3, 1, 0], [0, 1, 3]]) # on Silence self.shift_overlap_template = torch.tensor([[3, 2, 0], [0, 2, 3]]) self.hold_template = torch.tensor([[0, 1, 0], [3, 1, 3]]) # on silence def __repr__(self): s = "Holds & Shifts" s += f"\n post_onset_shift: {self.post_onset_shift}" s += f"\n pre_offset_shift: {self.pre_offset_shift}" s += f"\n post_onset_hold: {self.post_onset_hold}" s += f"\n pre_offset_hold: {self.pre_offset_hold}" s += f"\n min_silence: {self.min_silence}" s += f"\n metric_pad: {self.metric_pad}" s += f"\n metric_dur: {self.metric_dur}" s += f"\n metric_pre_label_dur: {self.metric_pre_label_dur}" s += f"\n non_shift_horizon: {self.non_shift_horizon}" s += f"\n non_shift_majority_ratio: {self.non_shift_majority_ratio}" return s def fill_template(self, vad, ds, template): """ Used in practice to create VAD -> FILLED_VAD, where filled vad combines consecutive segments of activity from the same speaker as a single chunk. """ filled_vad = vad.clone() for b in range(ds.shape[0]): s, d, v = find_island_idx_len(ds[b]) if len(v) < 3: continue triads = v.unfold(0, size=3, step=1) next_speaker, steps = torch.where( (triads == template.unsqueeze(1)).sum(-1) == 3 ) for ns, pre in zip(next_speaker, steps): cur = pre + 1 # Fill the matching template filled_vad[b, s[cur] : s[cur] + d[cur], ns] = 1.0 return filled_vad def match_template( self, vad, ds, template, pre_cond_frames, post_cond_frames, pre_match=False, onset_match=False, max_frame=None, min_context=0, ): """ Creates a onehot vector where the steps matching the template. Return: match_oh: torch.Tensor (B, N, 2), where the last bin corresponds to the next speaker """ hold_cond = template[0, 0] == template[0, -1] match_oh = torch.zeros((*ds.shape, 2), device=ds.device, dtype=torch.float) pre_match_oh = None if pre_match: pre_match_oh = torch.zeros( (*ds.shape, 2), device=ds.device, dtype=torch.float ) onset_match_oh = None if onset_match: onset_match_oh = torch.zeros( (*ds.shape, 2), device=ds.device, dtype=torch.float ) for b in range(ds.shape[0]): s, d, v = find_island_idx_len(ds[b]) if len(v) < 3: continue triads = v.unfold(0, size=3, step=1) next_speaker, steps = torch.where( (triads == template.unsqueeze(1)).sum(-1) == 3 ) # ns: next_speaker, pre_step for ns, pre_step in zip(next_speaker, steps): # If template is of 'HOLD-type' then previous speaker is the # same as next speaker. Otherwise they are different. nos = 0 if ns == 1 else 1 # strictly the OTHER 'next speaker' ps = ns if hold_cond else nos # previous speaker cur = pre_step + 1 post = pre_step + 2 # Silence Condition: if the current step is silent (shift with gap and holds) # then we only care about silences over a certain duration. if v[cur] == 1 and d[cur] < self.min_silence: continue # Can this be useful? older way of only considering active segments where # pauses have not been filled... # Shifts are more sensible to overall activity around silence/overlap # and uses `filled_vad` as vad where consecutive # if vad is None: # if d[pre_step] >= pre_cond_frames and d[post] >= post_cond_frames: # match_oh[b, s[cur] : s[cur] + d[cur], ns] = 1.0 # continue # pre_condition # using a filled version of the VAD signal we check wheather # only the 'previous speaker, ps' was active. This will then include # activity from that speaker deliminated by silence/pauses/holds pre_start = s[cur] - pre_cond_frames # print('pre_start: ', pre_start, s[cur]) pre_cond1 = vad[b, pre_start : s[cur], ps].sum() == pre_cond_frames not_ps = 0 if ps == 1 else 1 pre_cond2 = vad[b, pre_start : s[cur], not_ps].sum() == 0 pre_cond = torch.logical_and(pre_cond1, pre_cond2) if not pre_cond: # pre_cond = vad[b, pre_start : s[cur], ps].sum() # print("pre cond Failed: ", pre_cond, pre_cond_frames) # # print(vad[b, pre_start:s[cur]+d[cur]+10]) # input() continue # single speaker post post_start = s[post] post_end = post_start + post_cond_frames post_cond1 = vad[b, post_start:post_end, ns].sum() == post_cond_frames post_cond2 = vad[b, post_start:post_end, nos].sum() == 0 post_cond = torch.logical_and(post_cond1, post_cond2) if not post_cond: # post_cond = vad[b, post_start:post_end, ns].sum() # print("post cond Failed: ", post_cond, post_cond_frames) # print(vad[b, pre_start:s[cur]+d[cur]+10]) # input() continue # start = s[cur] # end = s[cur] + d[cur] # if self.metric_pad > 0: # start += self.metric_pad # # if self.metric_dur > 0: # end = start + self.metric_dur # Max frame condition: # Can't have event outside of predictable window if max_frame is not None: if s[cur] >= max_frame: continue # Min context condition: if (s[cur] + self.metric_pad) < min_context: continue if pre_match: pre_match_oh[ b, s[cur] - self.metric_pre_label_dur : s[cur], ns ] = 1.0 # end = s[cur] + self.metric_pad + d[cur] end = s[cur] + self.metric_pad + self.metric_dur # Max frame condition: # Can't have event outside of predictable window if max_frame is not None: if end >= max_frame: continue match_oh[b, s[cur] + self.metric_pad : end, ns] = 1.0 if onset_match: end = s[post] + self.metric_onset_dur if max_frame is not None: if end >= max_frame: continue onset_match_oh[b, s[post] : end, ns] = 1.0 return match_oh, pre_match_oh, onset_match_oh def non_shifts( self, vad, last_speaker, horizon, majority_ratio=1, max_frame=None, min_context=0, ): """ Non-shifts are all parts of the VAD signal where a future of `horizon` frames "overwhelmingly" belongs to a single speaker. The `majority_ratio` is a threshold over which the ratio of activity must belong to the last/current-speaker. Arguments: vad: torch.Tensor, (B, N, 2) horizon: int, length in frames of the horizon majority_ratio: float, ratio of which the majority speaker must occupy """ EPS = 1e-5 # used to avoid nans nb = vad.size(0) # future windows vv = vad[:, 1:].unfold(1, size=horizon, step=1).sum(dim=-1) vv = vv / (vv.sum(-1, keepdim=True) + EPS) diff = vad.shape[1] - vv.shape[1] if max_frame is not None: vv = vv[:, :max_frame] # Majority_ratio. Add eps to value to not miss majority_ratio==1. # because we divided 1 maj_speaker_cond = majority_ratio <= (vv + EPS) # Last speaker a_last = last_speaker[:, : maj_speaker_cond.shape[1]] == 0 b_last = last_speaker[:, : maj_speaker_cond.shape[1]] == 1 a_non_shift = torch.logical_and(a_last, maj_speaker_cond[..., 0]) b_non_shift = torch.logical_and(b_last, maj_speaker_cond[..., 1]) ns = torch.stack((a_non_shift, b_non_shift), dim=-1).float() # fill to correct size (same as vad and all other events) z = torch.zeros((nb, diff, 2), device=ns.device) non_shift = torch.cat((ns, z), dim=1) # Min Context Condition # i.e. don't use negatives from before `min_context` if min_context > 0: non_shift[:, :min_context] = 0.0 return non_shift def __call__( self, vad, ds=None, filled_vad=None, max_frame=None, min_context=0, return_list=False, ): if ds is None: ds = get_dialog_states(vad) if vad.device != self.hold_template.device: self.shift_template = self.shift_template.to(vad.device) self.shift_overlap_template = self.shift_overlap_template.to(vad.device) self.hold_template = self.hold_template.to(vad.device) if filled_vad is None: filled_vad = self.fill_template(vad, ds, self.hold_template) shift_oh, pre_shift_oh, long_shift_onset = self.match_template( filled_vad, ds, self.shift_template, pre_cond_frames=self.pre_offset_shift, post_cond_frames=self.post_onset_shift, pre_match=True, onset_match=True, max_frame=max_frame, min_context=min_context, ) shift_ov_oh, _, _ = self.match_template( filled_vad, ds, self.shift_overlap_template, pre_cond_frames=self.pre_offset_shift, post_cond_frames=self.post_onset_shift, pre_match=False, onset_match=False, max_frame=max_frame, min_context=min_context, ) hold_oh, pre_hold_oh, long_hold_onset = self.match_template( filled_vad, ds, self.hold_template, pre_cond_frames=self.pre_offset_hold, post_cond_frames=self.post_onset_hold, pre_match=True, onset_match=True, max_frame=max_frame, min_context=min_context, ) last_speaker = get_last_speaker(vad, ds) non_shift_oh = self.non_shifts( vad, last_speaker, horizon=self.non_shift_horizon, majority_ratio=self.non_shift_majority_ratio, max_frame=max_frame, min_context=min_context, ) return { "shift": shift_oh, "pre_shift": pre_shift_oh, "long_shift_onset": long_shift_onset, "hold": hold_oh, "pre_hold": pre_hold_oh, "long_hold_onset": long_hold_onset, "shift_overlap": shift_ov_oh, "non_shift": non_shift_oh, } if __name__ == "__main__": import matplotlib.pyplot as plt from vap_turn_taking.plot_utils import plot_vad_oh, plot_event from vap_turn_taking.config.example_data import event_conf_frames, example plt.close("all") hs_kwargs = event_conf_frames["hs"] HS = HoldShift(**hs_kwargs) tt = HS(example["va"], max_frame=None) for k, v in tt.items(): if isinstance(v, torch.Tensor): print(f"{k}: {tuple(v.shape)}") else: print(f"{k}: {v}") print("shift: ", (example["shift"] != tt["shift"]).sum()) print("hold: ", (example["hold"] != tt["hold"]).sum()) fig, ax = plot_vad_oh(va[0]) # # _, ax = plot_event(tt["shift"][0], ax=ax) # _, ax = plot_event(s[0], color=["g", "g"], ax=ax) # _, ax = plot_event(h[0], color=["r", "r"], ax=ax) # _, ax = plot_event(bc[0], color=["b", "b"], ax=ax) # _, ax = plot_event(tt["shift_overlap"][0], ax=ax) # _, ax = plot_event(tt_bc["backchannel"][0], color=["b", "b"], alpha=0.2, ax=ax) # _, ax = plot_event(tt_bc["pre_backchannel"][0], alpha=0.2, ax=ax) # _, ax = plot_event(tt["hold"][0], color=["r", "r"], ax=ax) # _, ax = plot_event(tt['pre_shift'][0], color=['g', 'g'], alpha=0.2, ax=ax) # _, ax = plot_event(tt['pre_hold'][0], color=['r', 'r'], alpha=0.2, ax=ax) # _, ax = plot_event(tt['long_shift_onset'][0], color=['r', 'r'], alpha=0.2, ax=ax) _, ax = plot_event(tt["non_shift"][0], color=["r", "r"], alpha=0.2, ax=ax) plt.pause(0.1)
from django.db import models from gram.users import models as user_models from django.utils.encoding import python_2_unicode_compatible from taggit.managers import TaggableManager @python_2_unicode_compatible class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True @python_2_unicode_compatible class Image(TimeStampedModel): """ Image Model """ file = models.ImageField() location = models.CharField(max_length=140) caption = models.TextField(null=True) creator = models.ForeignKey(user_models.User, on_delete=models.CASCADE, null=True, related_name='images') tags = TaggableManager() @property def like_count(self): return self.likes.all().count() @property def comment_count(self): return self.comments.all().count() def __str__(self): return '{} - {}'.format(self.location, self.caption) class Meta: ordering=['-created_at'] @python_2_unicode_compatible class Comment(TimeStampedModel): """ Comment Model """ message = models.TextField() creator = models.ForeignKey(user_models.User,on_delete=models.CASCADE, null=True) image = models.ForeignKey(Image, on_delete=models.CASCADE, null=True, related_name='comments') def __str__(self): return '{} - {}'.format(self.message, self.creator) @python_2_unicode_compatible class Like(TimeStampedModel): """ Like Model """ creator = models.ForeignKey(user_models.User, on_delete=models.CASCADE, null=True) image = models.ForeignKey(Image, on_delete=models.CASCADE, null=True, related_name='likes') def __str__(self): return 'User: {} - Image Caption: {}'.format( self.creator.username, self.image)
import unittest from api.SendEmail import send_confirmation_email from api.mail import MockMailSender class TestSendEmail(unittest.TestCase): def setUp(self): self.user_adress = "unosuke@gmx.com" self.from_address = "no-reply@morpheus.com" self.subject = "Account confirmation" self.mail_template = "static/templates/useractivation.html" def tearDown(self): pass def test_send_email(self): mail_info = { 'username': "test", 'user_address': self.user_adress, 'from_address': self.from_address, 'subject': self.subject, 'mail_template': self.mail_template, 'activation_code': "", 'auth_url': "" } mail_sender = MockMailSender("localhost", 25) send_confirmation_email(mail_info, mail_sender) if __name__ == '__main__': unittest.main()
##################################################################### # # Predictive Failure Analysis (PFA) # Graph JES2 Resource Data # #This python script is for use with data that is collected, created, #and written by the PFA_JES2_RESOURCE_EXHAUSTION check only. Its #use with data from any other source will result in errors. # #Copyright 2021 IBM Corp. # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # #http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicable law or agreed to in writing, #software distributed under the License is distributed on an #"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, #either express or implied. See the License for the specific #language governing permissions and limitations under the License. ##################################################################### import sys import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np import platform import os #Make sure we have plenty of potential data points to plot. plt.rcParams['agg.path.chunksize']=10000 #Disable false positive warning pd.options.mode.chained_assignment = None # default='warn' #Which system are we running on? system = platform.system() keys = {"JQE":"Q","SPOOL":"S","BERT":"B","JOE":"J"} user_keys = ["JQE","SPOOL","BERT","JOE"] resource_header_data = ["Resource","STCK_Time","Current_Usage","Date_Time"] capacity_header_data = ["Resource","Capacity"] check_name = "PFA_JES2_Resource_Exhaustion" COLUMN_CHAR_LEN = 8 #Parse our command line arguments. if(len(sys.argv) == 4): data_filepath = sys.argv[1] capacity_filepath = sys.argv[2] key = sys.argv[3] key = key.upper() verbose = False elif(len(sys.argv) == 5 and (sys.argv[4] == '-v' or sys.argv[4] == '-verbose')): data_filepath = sys.argv[1] capacity_filepath = sys.argv[2] key = sys.argv[3] key = key.upper() verbose = True elif(len(sys.argv) == 2 and (sys.argv[1] == '-h' or sys.argv[1] == '-help')): print("The proper syntax for this script is the following:\n") print("'python Graph_JRE_Data.py data_file capacity_file jes2_resource'.\n") print("Valid JES2 Resources are: "+ str([key for key in user_keys]) + '\n') print("The file path values are case sensitive, but the JES2 resource is not.\n") print("For example, if this script and the required files are in the same directory, you would specify the following to graph the JES2 Spool data on system SY1:\n") print("'python Graph_JRE_Data.py SY1.5day.data SY1.capacity SPOOL'\n") print("You can also add -v to the end of the command for verbose mode. This option will print additional data ") print("that could help debug errors or verify the results. An example using verbose mode looks like the following:\n") print("'python Graph_JRE_Data.py SY1.5day.data Capacity.data BERT -v'\n") print("When this script is executed on z/OS, it saves the graph in a .pdf file that can be downloaded from the directory where this script was executed and displayed anywhere that supports displaying a .pdf file.") print("The file name is in the format of JESResource_graph.pdf.") print("For example, if you entered 'python Graph_JRE_Data.py SY1.5day.data SY1.capacity SPOOL' on z/OS the saved file would be:") print("SPOOL_graph.pdf and it would be located in the current working directory.") sys.exit() else: raise Exception("The supplied arguments are not correct. Specify the data_file_path, capacity_file_path, and JES2 resource in that order. For help enter 'python Graph_JRE_Data.py -h'") #Make sure we have proper input from the user. if(not os.path.exists(data_filepath)): raise Exception("The specified file or filepath for the data file does not exist. Verify the file and filepath then try again.") if(not os.path.exists(capacity_filepath)): raise Exception("The specified file or filepath for the capacity file does not exist. Verify the file and filepath then try again.") if key not in user_keys: raise Exception("The specified resource does not exist. Specify a resource that exists.") #Load up our data and assign correct header values so we can narrow it down to the pieces we want. data_file = pd.read_csv(data_filepath, sep="/|,", names=resource_header_data, header=None, engine="python") capacity_file = pd.read_csv(capacity_filepath, sep="/|,", names=capacity_header_data, header=None, engine="python") user_key = key key = keys[user_key] user_key = user_key.ljust(COLUMN_CHAR_LEN) data_file = data_file.join(capacity_file["Capacity"]) NUM_TO_PRINT = 10 PDF_FILENAME = user_key.strip()+"_graph.pdf" #This is the name of the .pdf file that gets saved when this script is ran on z/OS def process_data(data_file, capacity_file): the_capacity = capacity_file.loc[capacity_file['Resource'] == user_key,'Capacity'].values[0] the_data = data_file.loc[data_file['Resource'] == user_key] the_data['Capacity'].fillna(the_capacity, inplace=True) the_data['Capacity'] = the_data['Capacity'].astype(int) the_data.loc[:,('Date_Time')] = pd.to_datetime(the_data['Date_Time'].astype(str), format='%Y%m%d%H%M%S') if(verbose): print_details(the_data, NUM_TO_PRINT) return the_data def graph_data(the_data): y_values = [0,(the_data['Capacity'].max())*.25,(the_data['Capacity'].max())*.50,(the_data['Capacity'].max())*.75,(the_data['Capacity'].max())] y_ticks = [str(int(y)) for y in y_values] fig, ax = plt.subplots() ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M')) ax.set_ylim(0,the_data['Capacity'].max()*1.10) ax.plot(the_data['Date_Time'],the_data['Capacity'],'--r', label='Capacity') ax.plot(the_data['Date_Time'],the_data['Current_Usage']/1024,'-b', label='Current Usage') fig.suptitle(check_name + "\n" + user_key, fontsize=16) plt.yticks(y_values, y_ticks) plt.xlabel('Month-Day Time') fig.autofmt_xdate() ax.legend(bbox_to_anchor=(1.41, 1),loc="upper right") fig.subplots_adjust(right=0.75) if system != 'z/OS': plt.show(); else: fig.savefig(PDF_FILENAME) def print_details(data_frame, num_to_print): print("Now graphing " + check_name + " data on a " + system + " system.") print("JES2 resource is: " + user_key.strip()) print("data_filepath entered: " + data_filepath) print("capacity_filepath entered was: " + capacity_filepath) print("\nPreview of the data being graphed:") print(data_frame.head(num_to_print).to_string(index=False)) #Process and graph our data. the_data = process_data(data_file, capacity_file) user_key = user_key.strip() graph_data(the_data) if system == 'z/OS': print(PDF_FILENAME + ' has been created and is ready to be downloaded and viewed.')
const db = require('./../mongodb/db'); const FileUtil = require('./fileUtil'); const DistrictCodeModal = require('./../models/districtCode'); const StatCodeModal = require('./../models/statCode'); const districtFilePath = './../json/districtcode'; const statFilePath = './../json/statcode'; // const Storage = { // startCount: 0, // endCount: 0, // errorCount: 0, // async storageDistrictCode() { // this._storage(districtFilePath, DistrictCodeModal); // }, // async storageStatCode() { // this._storage(statFilePath, StatCodeModal); // }, // async _storage(foldPath, construct) { // try { // let files = await FileUtil.readdir(foldPath); // let fileData; // let fileArr; // for (let i = 0, len = files.length; i < len; i ++) { // if (!/\.json$/.test(files[i])) { // continue; // } // fileData = await FileUtil.readfile(foldPath + '/' +files[i]); // fileArr = fileData.split('\n'); // for (let j = 0, itemLen = fileArr.length; j < itemLen; j++) { // if (fileArr[j] && fileArr[j].trim()) { // let item = new construct(JSON.parse(fileArr[j])); // this.startCount ++; // item.save((err) => { // if (err) { // this.errorCount ++; // console.log(item + '入库失败!失败原因:' + err); // } else { // this.endCount ++; // // console.log(item.name + '入库成功!'); // } // }); // } // } // } // } catch (e) { // console.log(e); // } // } // } const Storage = (() => { let _startCount = 0; let _endCount = 0; let _errorCount = 0; let _startTime = Date.now(); let _storage = async (foldPath, construct) => { try { let files = await FileUtil.readdir(foldPath); let fileData; let fileArr; for (let i = 0, len = files.length; i < len; i ++) { if (!/\.json$/.test(files[i])) { continue; } fileData = await FileUtil.readfile(foldPath + '/' +files[i]); fileArr = fileData.split('\n'); for (let j = 0, itemLen = fileArr.length; j < itemLen; j++) { if (fileArr[j] && fileArr[j].trim()) { _startCount ++; // console.log(construct); let item = new construct(JSON.parse(fileArr[j])); item.save((err) => { if (err) { _errorCount ++; console.log(item + '入库失败!失败原因:' + err); } else { _endCount ++; // console.log(item.name + '入库成功!'); } }); } } } } catch (e) { console.log(e); } } (() => { setInterval(() => { console.log('解析' + _startCount + '条数据! 已完成' + _endCount + '条数据入库,' + '失败' + _errorCount + '条。已花费时间'+ (Date.now() - _startTime)) / (1000 * 60) + 'min'; }, 2000) })() return { storageDistrictCode() { _storage(districtFilePath, DistrictCodeModal); }, storageStatCode() { try { _storage(statFilePath, StatCodeModal); } catch (e) { console.log(e); } }, } })(); Storage.storageStatCode();
#include <stdlib.h> #include <stdio.h> #include <conio.h> #include "memory/memory.h" int main(int argc, char **argv) { m_init(20, 20); int error_code; m_id chunk_1 = m_malloc(13, &error_code); if (error_code != M_ERR_OK) abort(); m_id chunk_2 = m_malloc(20, &error_code); if (error_code != M_ERR_OK) abort(); m_id chunk_3 = m_malloc(50, &error_code); if (error_code != M_ERR_OK) abort(); m_id chunk_4 = m_malloc(150, &error_code); if (error_code != M_ERR_OK) abort(); m_write(chunk_1, "Hello World!", 13, &error_code); if (error_code != M_ERR_OK) abort(); m_write(chunk_2, "Operating Systems", 18, &error_code); if (error_code != M_ERR_OK) abort(); m_write(chunk_3, "Super dumb memory allocator", 28, &error_code); if (error_code != M_ERR_OK) abort(); m_write(chunk_4, "In the Age of Ancients the world was unformed, shrouded by fog. A land of gray crags, Archtrees and Everlasting Dragons", 120, &error_code); if (error_code != M_ERR_OK) abort(); char buffer[150]; printf("\nReading...\n\n"); m_read(chunk_1, buffer, 13, &error_code); if (error_code != M_ERR_OK) abort(); printf("%s\n", buffer); m_read(chunk_2, buffer, 18, &error_code); if (error_code != M_ERR_OK) abort(); printf("%s\n", buffer); m_read(chunk_3, buffer, 28, &error_code); if (error_code != M_ERR_OK) abort(); printf("%s\n", buffer); m_read(chunk_4, buffer, 120, &error_code); if (error_code != M_ERR_OK) abort(); printf("%s\n", buffer); printf("\nReading complite\n\n"); m_free(chunk_1, &error_code); if (error_code != M_ERR_OK) abort(); m_free(chunk_2, &error_code); if (error_code != M_ERR_OK) abort(); m_free(chunk_3, &error_code); if (error_code != M_ERR_OK) abort(); m_free(chunk_4, &error_code); if (error_code != M_ERR_OK) abort(); getch(); }
/* Graph Renderer Displays a graph of pie / bar charts with an optional legend. Options type (STRING) Defines the display type of the graph, can be one of pie column stackedColumn row stackedRow line stackedArea Default is column. title (STRING) Title string written at the top of the graph title_color (CSS Color Value) Color of the title text. Default is black. title_settings (SVG settings object) SVG settings for the title. x_title (STRING) Title written below the x-axis. y_title (STRING) Title written to the left of the y-axis. x_title_color (CSS Color Value) Color of the x-axis title string. Default is black. y_title_color (CSS Color Value) Color of the y-axis title string. Default is black. x_labels (ARRAY of STRING) List of the labels at the ticks of the x-axis. x_labels_rotation (STRING) A string representing the number of degrees to rotate the labels on the x-axis. Default is 0. y_labels (ARRAY of STRING) List of the labels at the ticks of the y-axis. If no list is passed will use the y-valus. x_tick_interval (INT) Determines how many ticks are actually drawn on the x-axis. Default is 0. y_tick_interval (INT) Determines how many ticks are actually drawn on the y-axis. Default is 30. x_labeled_tick_interval (INT) Determines which ticks on the x-axis get labels. Default is 1. y_labeled_tick_interval (INT) The number of y-axis ticks that get labels. Default is 5. default_line_color (CSS Color Value) Determines the color of lines if not specified for an individual line. Default is black. default_line_width (INT) Number of pixels lines should be wide if not specified for an individual line. Default is 1. show_legend (BOOLEAN) Turns the display of the legend on / off. Default ist true. legend_position (STRING) Can be one of left right top bottom chartArea (ARRAY of FLOAT) The values passed correspond to the left, top, width and height of the chart area respectively. The position is relative to the top left corner of the containing div. Values less than 1 are interpreted as fractions. Values greater than 1 are interpreted as absolute pixel values. Note that the labels are drawn to the left and bottom of these margins. legendArea (ARRAY of FLOAT) If this parameter is set, the legend_position parameter will not be used. Instead pass an array of floats. The values correspond to the left, top, width and height of the legend area respectively. The position is relative to the top left corner of the containing div. Values less than 1 are interpreted as fractions. Values greater than 1 are interpreted as absolute pixel values. width (INT) The width of the graph in pixel (including legend). height (INT) The height of the graph in pixel (including legend). data (ARRAY of OBJECT) List of data series. Each series has a name and a data attribute. The data attribute is a list of y-values for the series. onclick (FUNCTION) The passed function will be called when a bar / pie slice is clicked. It will receive an object with the attributes series - the name of the series this bar belongs to value - the value of the bar label - the label of the bar item - the svg element that was clicked index - the zero based index of this bar within its series series_index - the zero based index of this series normalize_stacked_area (boolean) If set to false the stacked area chart will not normalize the values */ (function () { var root = this; var standaloneGraph = root.standaloneGraph = { about: { name: "graph", title: "Graph", author: "Tobias Paczian", version: "1.0", defaults: { 'type': 'column', // [ column, stackedColumn, row, stackedRow, line, pie, stackedArea, deviation ] 'title': '', 'title_color': 'black', 'title_settings': { fontSize: '15px' }, 'x_title': '', 'y_title': '', 'y2_title': '', 'x_title_color': 'black', 'y_title_color': 'black', 'y2_title_color': 'black', 'x_labels': [], 'x_labels_rotation': null, 'y_labels': [], 'y_scale': 'linear', 'y2_labels': [], 'y2_scale': 'linear', 'x_tick_interval': 0, 'y_tick_interval': 30, 'y2_tick_interval': 30, 'x_labeled_tick_interval': 1, 'y_labeled_tick_interval': 5, 'y2_labeled_tick_interval': 5, 'default_line_color': 'black', 'default_line_width': 1, 'show_legend': false, 'legend_position': 'right', 'show_grid': false, 'short_axis_labels': false, 'normalize_stacked_area': true, 'width': 800, 'height': 400 }, options: [ { general: [ { name: 'type', type: 'select', description: "type of the graph", title: "type", options: [ { value: "column", selected: true }, { value: "stackedColumn", label: "stacked column" }, { value: "row" }, { value: "stackedRow", label: "stacked row" }, { value: "line" }, { value: "pie" }, { value: "stackedArea", label: "stacked area" }, { value: "deviation", label: "deviation" } ] }, { name: 'default_line_color', type: 'color', description: "default color of the data lines of the graph", title: "default line color" }, { name: 'default_line_width', type: 'int', description: "default width of the data lines of the graph in pixel", title: "default line width" }, { name: 'show_grid', type: 'select', description: "sets whether grid is displayed or not", title: "show grid", options: [ { value: 0, selected: true, label: "no" }, { value: 1, label: "yes" } ] } ] }, { text: [ { name: 'title', type: 'text', description: "title string of the graph", title: "title" }, { name: 'title_color', type: 'color', description: "color of the title string of the graph", title: "title color" }, { name: 'x_title', type: 'text', description: "title of the x-axis of the graph", title: "x title" }, { name: 'y_title', type: 'text', description: "title of the y-axis of the graph", title: "y title" }, { name: 'x_title_color', type: 'color', description: "color of the title of the x-axis of the graph", title: "x title color" }, { name: 'y_title_color', type: 'color', description: "color of the title of the y-axis of the graph", title: "y title color" }, { name: 'x_labels_rotation', type: 'int', description: "rotation in degrees of the x-axis labels", title: "x label rotation" } ] }, { layout: [ { name: 'width', type: 'int', description: "width of the graph in pixel", title: "width" }, { name: 'height', type: 'int', description: "height of the graph in pixel", title: "height" }, { name: 'show_legend', type: 'select', description: "sets whether the legend is displayed or not", title: "show legend", options: [ { value: 0, selected: true, label: "no" }, { value: 1, label: "yes" } ] }, { name: 'legend_position', type: 'select', description: "position of the legend", title: "legend position", options: [ { value: "left", selected: true }, { value: "right" }, { value: "top" }, { value: "bottom" } ] } ] }, { axes: [ { name: 'y_scale', type: 'select', description: "type of the scale of the y-axis", title: "y scale", options: [ { value: "linear", selected: true }, { value: "log" } ] }, { name: 'x_tick_interval', type: 'int', description: "pixel distance of the minor tickmarks on the x-axis", title: "minor x ticks" }, { name: 'y_tick_interval', type: 'int', description: "pixel distance of the minor tickmarks on the y-axis", title: "minor y ticks" }, { name: 'x_labeled_tick_interval', type: 'int', description: "pixel distance of the major tickmarks on the x-axis", title: "major x ticks" }, { name: 'y_labeled_tick_interval', type: 'int', description: "pixel distance of the major tickmarks on the y-axis", title: "major y ticks" }, { name: 'short_axis_labels', type: 'select', description: "sets whether the axis labels should be shortened or not", title: "short axis labels", options: [ { value: 0, selected: true, label: "no" }, { value: 1, label: "yes" } ] }, ] } ] }, exampleData: function () { return [ { "name": 'IE', "data": [95, 91, 78, 66] }, { "name": 'Netscape', "data": [3, 12, 18, 18] }, { "name": 'Firefox', "data": [0, 4, 8, 9] }, { "name": 'Chrome', "data": [0, 8, 18, 22] }, { "name": 'Gecko', "data": [1, 2, 3, 33] } ]; }, create: function (params) { var renderer = this; if (! window.hasOwnProperty('rendererGraph')) { window.rendererGraph = []; } var instance = { settings: {}, index: params.index }; jQuery.extend(true, instance, renderer); jQuery.extend(true, instance.settings, renderer.about.defaults, params); window.rendererGraph.push(instance); return instance; }, render: function (index) { var renderer = rendererGraph[index]; // get the target div var target = renderer.settings.target; var index = renderer.index; target.innerHTML = "<div id='graph_div"+index+"'></div>"; target.firstChild.setAttribute('style', "width: "+ renderer.settings.width+"px; height: "+renderer.settings.height+"px;"); jQuery('#graph_div'+index).svg(); var cmax = 0; if (renderer.settings.type == 'deviation' && ! renderer.settings.data[0].data.hasOwnProperty('upper')) { renderer.calculateData(renderer.settings.data, index); cmax = renderer.cmax; } rendererGraph[index].drawImage(jQuery('#graph_div'+index).svg('get'), cmax, index); return renderer; }, niceNum: function (range, round) { var exponent = Math.floor(Math.log10(range)); /** exponent of range */ var fraction = range / Math.pow(10, exponent); /** fractional part of range */ var niceFraction; /** nice, rounded fraction */ if (round) { if (fraction < 1.5) { niceFraction = 1; } else if (fraction < 3) { niceFraction = 2; } else if (fraction < 7) { niceFraction = 5; } else { niceFraction = 10; } } else { if (fraction <= 1) { niceFraction = 1; } else if (fraction <= 2) { niceFraction = 2; } else if (fraction <= 5) { niceFraction = 5; } else { niceFraction = 10; } } return niceFraction * Math.pow(10, exponent); }, /* get a nice scale, min, max and tick interval */ niceScale: function (params) { var minPoint = params.min; var maxPoint = params.max; var maxTicks = params.ticks || 10; var range = rendererGraph[0].niceNum(maxPoint - minPoint, false); var tickSpacing = rendererGraph[0].niceNum(range / (maxTicks - 1), true); var niceMin = Math.floor(minPoint / tickSpacing) * tickSpacing;; var niceMax = Math.ceil(maxPoint / tickSpacing) * tickSpacing; return { min: niceMin, max: niceMax, space: tickSpacing }; }, hover: function (title, value, event, e) { var id = e.currentTarget.ownerSVGElement.ownerSVGElement.parentNode.id; var index = id.substr(9); var renderer = rendererGraph[index]; var svg = jQuery('#'+id).svg('get'); if (title) { jQuery(this, svg.root()).attr('fill-opacity', .8); jQuery(this, svg.root()).attr('title', title+": "+value); } else { jQuery(this, svg.root()).attr('fill-opacity', 1); } if (event == 'click') { var num = parseInt(this.parentElement.className.baseVal.substr(this.parentElement.className.baseVal.search(/\d+/))); svg.graph.options({ explode: [ num ], explodeDist: 15 }); if (typeof(renderer.settings.onclick) == "function") { var label = ""; var i; for (i=0;i<this.parentElement.children.length;i++) { if (this.parentElement.children[i] === this) { if (this.getAttribute('r')) { i--; } label = svg.graph.xAxis.labels().labels[i]; break; } } renderer.settings.onclick({rendererIndex: index, series: title, value: value, label: label, item: this, index: i, series_index: num, svg: svg }); } } }, drawImage: function (svg, cmax, index) { var renderer = rendererGraph[index]; var chartAreas = [ [ 0.1, 0.1, 0.95, 0.9 ], // no legend [ 0.2, 0.1, 0.95, 0.9 ], // legend left [ 0.1, 0.1, 0.75, 0.9 ], // legend right [ 0.1, 0.25, 0.9, 0.9 ], // legend top [ 0.1, 0.1, 0.9, 0.8 ] ]; // legend bottom var legendAreas = [ [ 0.0, 0.0, 0.0, 0.0 ], // no legend [ 0.005, 0.1, 0.125, 0.5 ], // left [ 0.8, 0.1, 0.97, 0.5 ], // right [ 0.2, 0.1, 0.8, 0.2 ], // top [ 0.2, 0.9, 0.8, 0.995 ] ]; // bottom var fills = [ 'url(#fadeBlue)', 'url(#fadeRed)', 'url(#fadeGreen)', 'url(#fadeYellow)', 'url(#fadeLightblue)', 'url(#fadePurple)' ]; var colors = [ '#0044CC', // blue '#BD362F', // red '#51A351', // green '#F89406', // yellow '#2F96B4', // lightblue '#bd2fa6' // purple ]; var defs = svg.defs(); var max = 0; var y2max = 0; for (i=0; i<renderer.settings.data.length; i++) { for (h=0; h<renderer.settings.data[i].data.length; h++) { if (renderer.settings.data[i].settings && renderer.settings.data[i].settings.isY2) { if (parseFloat(renderer.settings.data[i].data[h]) > y2max) { y2max = parseFloat(renderer.settings.data[i].data[h]); } } else { if (parseFloat(renderer.settings.data[i].data[h]) > max) { max = parseFloat(renderer.settings.data[i].data[h]); } } } } max = cmax || max; svg.linearGradient(defs, 'fadeRed', [[0, '#EE5F5B'], [1, '#BD362F']]); svg.linearGradient(defs, 'fadeBlue', [[0, '#0088CC'], [1, '#0044CC']]); svg.linearGradient(defs, 'fadeGreen', [[0, '#62C462'], [1, '#51A351']]); svg.linearGradient(defs, 'fadeYellow', [[0, '#FBB450'], [1, '#F89406']]); svg.linearGradient(defs, 'fadeLightblue', [[0, '#5BC0DE'], [1, '#2F96B4']]); svg.linearGradient(defs, 'fadePurple', [[0, '#ee5be0'], [1, '#bd2fa6']]); svg.graph.shortAxisLabels = renderer.settings.short_axis_labels; svg.graph.normalizeStackedArea = renderer.settings.normalize_stacked_area; svg.graph.noDraw().title(renderer.settings.title, renderer.settings.title_color, renderer.settings.title_settings); svg.graph.noDraw().format('white', renderer.settings.show_grid ? 'gray' : 'white' ); if (renderer.settings.show_grid) { svg.graph.noDraw().gridlines({stroke: 'gray', strokeDashArray: '2,2'}, 'gray'); } for (i=0;i<renderer.settings.data.length;i++) { svg.graph.noDraw().addSeries( renderer.settings.data[i].name, renderer.settings.data[i].data, null, renderer.settings.data[i].lineColor || 'white', renderer.settings.data[i].lineWidth || renderer.settings.default_line_width, renderer.settings.data[i].settings ? renderer.settings.data[i].settings : {}); } svg.graph.xAxis.title(renderer.settings.x_title, renderer.settings.x_title_color). ticks(renderer.settings.x_labeled_tick_interval, renderer.settings.x_tick_interval). scale(0, 3); if (renderer.settings.x_labels.length) { svg.graph.xAxis.labelRotation = renderer.settings.x_labels_rotation; svg.graph.xAxis.labels(renderer.settings.x_labels); } var sy =this.niceScale({min: 0, max: max, ticks: renderer.settings.y_labeled_tick_interval }); svg.graph.yAxis. title(renderer.settings.y_title, renderer.settings.y_title_color). ticks(sy.max / renderer.settings.y_labeled_tick_interval, sy.max / renderer.settings.y_tick_interval, null, null, renderer.settings.y_scale). scale(0,max,renderer.settings.y_scale); if (renderer.settings.hasY2) { svg.graph.y2Axis. title(renderer.settings.y2_title || "", renderer.settings.y2_title_color). ticks(parseInt(y2max / renderer.settings.y2_labeled_tick_interval), parseInt(y2max / renderer.settings.y2_tick_interval), null, null, renderer.settings.y_scale). scale(0,y2max,renderer.settings.y2_scale); if (renderer.settings.y2_labels.length) { svg.graph.y2Axis.labels(renderer.settings.y2_labels); } } else { svg.graph.y2Axis = null; } if (renderer.settings.y_labels.length) { svg.graph.yAxis.labels(renderer.settings.y_labels); } svg.graph.legend.settings({fill: 'white', stroke: 'white'}); var chartType = renderer.settings.type; var chartLegend = 0; if (renderer.settings.show_legend) { switch (renderer.settings.legend_position) { case 'left': chartLegend = 1; break; case 'right': chartLegend = 2; break; case 'top': chartLegend = 3; break; case 'bottom': chartLegend = 4; break; }; } var chartOptions = { barWidth: renderer.settings.barWidth || 25 }; svg.graph.status(rendererGraph[index].hover); svg.graph.noDraw(). legend.show(renderer.settings.show_legend).area(renderer.settings.legendArea ? renderer.settings.legendArea : legendAreas[chartLegend]).end(); for (i=0; i< renderer.settings.data.length; i++) { svg.graph.noDraw().series(i).format(renderer.settings.data[i].fill || fills[i]).end(); } svg.graph.noDraw().area(renderer.settings.chartArea ? renderer.settings.chartArea : chartAreas[chartLegend]). type(chartType, chartOptions).redraw(); }, calculateData: function (data, index) { var renderer = rendererGraph[index]; var fivenumbers = []; var min = data[0].data[0]; var max = data[0].data[0]; for (var i=0;i<data.length;i++) { data[i].data = data[i].data.sort(function (a, b) { return a - b; }); if (data[i].data[0] < min) { min = data[i].data[0]; } if (data[i].data[data[i].data.length - 1] > max) { max = data[i].data[data[i].data.length - 1]; } fivenumbers[i] = []; fivenumbers[i]['min'] = data[i].data[0]; fivenumbers[i]['max'] = data[i].data[data[i].data.length - 1]; var boxarray = []; if (data[i].data.length % 2 == 1) { var med = parseInt(data[i].data.length / 2); fivenumbers[i]['median'] = data[i].data[med]; if ((med + 1) % 2 == 1) { fivenumbers[i]['lower'] = data[i].data[parseInt((med + 1) / 2)]; fivenumbers[i]['upper'] = data[i].data[med + parseInt((med + 1) / 2)]; } else { fivenumbers[i]['lower'] = ((data[i].data[(med + 1) / 2]) + (data[i].data[((med + 1) / 2) + 1])) / 2; fivenumbers[i]['upper'] = ((data[i].data[med + ((med + 1) / 2) - 1]) + (data[i].data[med + ((med + 1) / 2)])) / 2; } } else { var medup = data[i].data.length / 2; var medlow = (data[i].data.length / 2) - 1; fivenumbers[i]['median'] = (data[i].data[medlow] + data[i].data[medup]) / 2; if (medup % 2 == 1) { fivenumbers[i]['lower'] = data[i].data[medlow / 2]; fivenumbers[i]['upper'] = data[i].data[medup + (medlow / 2)]; } else { fivenumbers[i]['lower'] = (data[i].data[(medup / 2) - 1] + data[i].data[medup / 2]) / 2; fivenumbers[i]['upper'] = (data[i].data[medup + (medup / 2) - 1] + data[i].data[medup + (medup / 2)]) / 2; } } } for (var i=0; i<data.length; i++) { renderer.settings.data[i].data = [ fivenumbers[i] ]; } renderer.cmax = max; } } }).call(this);
"""Component to integrate the Home Assistant cloud.""" import logging import voluptuous as vol from homeassistant.auth.const import GROUP_ID_ADMIN from homeassistant.components.alexa import const as alexa_const from homeassistant.components.google_assistant import const as ga_c from homeassistant.const import ( CONF_MODE, CONF_NAME, CONF_REGION, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, entityfilter from homeassistant.loader import bind_hass from homeassistant.util.aiohttp import MockRequest from . import http_api from .const import ( CONF_ACME_DIRECTORY_SERVER, CONF_ALEXA, CONF_ALIASES, CONF_CLOUDHOOK_CREATE_URL, CONF_COGNITO_CLIENT_ID, CONF_ENTITY_CONFIG, CONF_FILTER, CONF_GOOGLE_ACTIONS, CONF_GOOGLE_ACTIONS_SYNC_URL, CONF_RELAYER, CONF_REMOTE_API_URL, CONF_SUBSCRIPTION_INFO_URL, CONF_USER_POOL_ID, DOMAIN, MODE_DEV, MODE_PROD, CONF_ALEXA_ACCESS_TOKEN_URL ) from .prefs import CloudPreferences _LOGGER = logging.getLogger(__name__) DEFAULT_MODE = MODE_PROD SERVICE_REMOTE_CONNECT = 'remote_connect' SERVICE_REMOTE_DISCONNECT = 'remote_disconnect' ALEXA_ENTITY_SCHEMA = vol.Schema({ vol.Optional(alexa_const.CONF_DESCRIPTION): cv.string, vol.Optional(alexa_const.CONF_DISPLAY_CATEGORIES): cv.string, vol.Optional(CONF_NAME): cv.string, }) GOOGLE_ENTITY_SCHEMA = vol.Schema({ vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string]), vol.Optional(ga_c.CONF_ROOM_HINT): cv.string, }) ASSISTANT_SCHEMA = vol.Schema({ vol.Optional(CONF_FILTER, default=dict): entityfilter.FILTER_SCHEMA, }) ALEXA_SCHEMA = ASSISTANT_SCHEMA.extend({ vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA} }) GACTIONS_SCHEMA = ASSISTANT_SCHEMA.extend({ vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA}, }) # pylint: disable=no-value-for-parameter CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Optional(CONF_MODE, default=DEFAULT_MODE): vol.In([MODE_DEV, MODE_PROD]), vol.Optional(CONF_COGNITO_CLIENT_ID): str, vol.Optional(CONF_USER_POOL_ID): str, vol.Optional(CONF_REGION): str, vol.Optional(CONF_RELAYER): str, vol.Optional(CONF_GOOGLE_ACTIONS_SYNC_URL): vol.Url(), vol.Optional(CONF_SUBSCRIPTION_INFO_URL): vol.Url(), vol.Optional(CONF_CLOUDHOOK_CREATE_URL): vol.Url(), vol.Optional(CONF_REMOTE_API_URL): vol.Url(), vol.Optional(CONF_ACME_DIRECTORY_SERVER): vol.Url(), vol.Optional(CONF_ALEXA): ALEXA_SCHEMA, vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA, vol.Optional(CONF_ALEXA_ACCESS_TOKEN_URL): str, }), }, extra=vol.ALLOW_EXTRA) class CloudNotAvailable(HomeAssistantError): """Raised when an action requires the cloud but it's not available.""" @bind_hass @callback def async_is_logged_in(hass) -> bool: """Test if user is logged in.""" return DOMAIN in hass.data and hass.data[DOMAIN].is_logged_in @bind_hass @callback def async_active_subscription(hass) -> bool: """Test if user has an active subscription.""" return \ async_is_logged_in(hass) and not hass.data[DOMAIN].subscription_expired @bind_hass async def async_create_cloudhook(hass, webhook_id: str) -> str: """Create a cloudhook.""" if not async_is_logged_in(hass): raise CloudNotAvailable hook = await hass.data[DOMAIN].cloudhooks.async_create(webhook_id, True) return hook['cloudhook_url'] @bind_hass async def async_delete_cloudhook(hass, webhook_id: str) -> None: """Delete a cloudhook.""" if DOMAIN not in hass.data: raise CloudNotAvailable await hass.data[DOMAIN].cloudhooks.async_delete(webhook_id) @bind_hass @callback def async_remote_ui_url(hass) -> str: """Get the remote UI URL.""" if not async_is_logged_in(hass): raise CloudNotAvailable if not hass.data[DOMAIN].remote.instance_domain: raise CloudNotAvailable return "https://" + hass.data[DOMAIN].remote.instance_domain def is_cloudhook_request(request): """Test if a request came from a cloudhook. Async friendly. """ return isinstance(request, MockRequest) async def async_setup(hass, config): """Initialize the Home Assistant cloud.""" from hass_nabucasa import Cloud from .client import CloudClient # Process configs if DOMAIN in config: kwargs = dict(config[DOMAIN]) else: kwargs = {CONF_MODE: DEFAULT_MODE} # Alexa/Google custom config alexa_conf = kwargs.pop(CONF_ALEXA, None) or ALEXA_SCHEMA({}) google_conf = kwargs.pop(CONF_GOOGLE_ACTIONS, None) or GACTIONS_SCHEMA({}) # Cloud settings prefs = CloudPreferences(hass) await prefs.async_initialize() # Cloud user if not prefs.cloud_user: user = await hass.auth.async_create_system_user( 'Home Assistant Cloud', [GROUP_ID_ADMIN]) await prefs.async_update(cloud_user=user.id) # Initialize Cloud websession = hass.helpers.aiohttp_client.async_get_clientsession() client = CloudClient(hass, prefs, websession, alexa_conf, google_conf) cloud = hass.data[DOMAIN] = Cloud(client, **kwargs) async def _startup(event): """Startup event.""" await cloud.start() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _startup) async def _shutdown(event): """Shutdown event.""" await cloud.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown) async def _service_handler(service): """Handle service for cloud.""" if service.service == SERVICE_REMOTE_CONNECT: await cloud.remote.connect() await prefs.async_update(remote_enabled=True) elif service.service == SERVICE_REMOTE_DISCONNECT: await cloud.remote.disconnect() await prefs.async_update(remote_enabled=False) hass.helpers.service.async_register_admin_service( DOMAIN, SERVICE_REMOTE_CONNECT, _service_handler) hass.helpers.service.async_register_admin_service( DOMAIN, SERVICE_REMOTE_DISCONNECT, _service_handler) loaded_binary_sensor = False async def _on_connect(): """Discover RemoteUI binary sensor.""" nonlocal loaded_binary_sensor if loaded_binary_sensor: return loaded_binary_sensor = True hass.async_create_task(hass.helpers.discovery.async_load_platform( 'binary_sensor', DOMAIN, {}, config)) cloud.iot.register_on_connect(_on_connect) await http_api.async_setup(hass) return True
# coding=utf-8 # Copyright 2018 The Dopamine Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Compact implementation of a simplified Rainbow agent in Jax. Specifically, we implement the following components from Rainbow: * n-step updates; * prioritized replay; and * distributional RL. These three components were found to significantly impact the performance of the Atari game-playing agent. Furthermore, our implementation does away with some minor hyperparameter choices. Specifically, we * keep the beta exponent fixed at beta=0.5, rather than increase it linearly; * remove the alpha parameter, which was set to alpha=0.5 throughout the paper. Details in "Rainbow: Combining Improvements in Deep Reinforcement Learning" by Hessel et al. (2018). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from dopamine.jax import networks from dopamine.jax.agents.dqn import dqn_agent from dopamine.replay_memory import prioritized_replay_buffer from flax import nn import gin import jax import jax.numpy as jnp import tensorflow as tf @functools.partial(jax.jit, static_argnums=(8)) def train(target_network, optimizer, states, actions, next_states, rewards, terminals, support, cumulative_gamma): """Run a training step.""" def loss_fn(model, target, mean_loss=True): logits = jax.vmap(model)(states).logits logits = jnp.squeeze(logits) # Fetch the logits for its selected action. We use vmap to perform this # indexing across the batch. chosen_action_logits = jax.vmap(lambda x, y: x[y])(logits, actions) loss = jax.vmap(networks.softmax_cross_entropy_loss_with_logits)( target, chosen_action_logits) if mean_loss: loss = jnp.mean(loss) return loss grad_fn = jax.value_and_grad(loss_fn) target = target_distribution(target_network, next_states, rewards, terminals, support, cumulative_gamma) mean_loss, grad = grad_fn(optimizer.target, target) # Get the loss without taking its mean. loss = loss_fn(optimizer.target, target, mean_loss=False) optimizer = optimizer.apply_gradient(grad) return optimizer, loss, mean_loss @functools.partial(jax.vmap, in_axes=(None, 0, 0, 0, None, None)) def target_distribution(target_network, next_states, rewards, terminals, support, cumulative_gamma): """Builds the C51 target distribution as per Bellemare et al. (2017). First, we compute the support of the Bellman target, r + gamma Z'. Where Z' is the support of the next state distribution: * Evenly spaced in [-vmax, vmax] if the current state is nonterminal; * 0 otherwise (duplicated num_atoms times). Second, we compute the next-state probabilities, corresponding to the action with highest expected value. Finally we project the Bellman target (support + probabilities) onto the original support. Args: target_network: Jax Module used for the target network. next_states: numpy array of batched next states. rewards: numpy array of batched rewards. terminals: numpy array of batched terminals. support: support for the distribution (static_argnum). cumulative_gamma: float, cumulative gamma to use (static_argnum). Returns: The target distribution from the replay. """ is_terminal_multiplier = 1. - terminals.astype(jnp.float32) # Incorporate terminal state to discount factor. gamma_with_terminal = cumulative_gamma * is_terminal_multiplier target_support = rewards + gamma_with_terminal * support next_state_target_outputs = target_network(next_states) q_values = jnp.squeeze(next_state_target_outputs.q_values) next_qt_argmax = jnp.argmax(q_values) probabilities = jnp.squeeze(next_state_target_outputs.probabilities) next_probabilities = probabilities[next_qt_argmax] return jax.lax.stop_gradient( project_distribution(target_support, next_probabilities, support)) @gin.configurable class JaxRainbowAgent(dqn_agent.JaxDQNAgent): """A compact implementation of a simplified Rainbow agent.""" def __init__(self, num_actions, observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, observation_dtype=dqn_agent.NATURE_DQN_DTYPE, stack_size=dqn_agent.NATURE_DQN_STACK_SIZE, network=networks.RainbowNetwork, num_atoms=51, vmin=None, vmax=10., gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=dqn_agent.linearly_decaying_epsilon, epsilon_train=0.01, epsilon_eval=0.001, epsilon_decay_period=250000, replay_scheme='prioritized', optimizer='adam', summary_writer=None, summary_writing_frequency=500, allow_partial_reload=False): """Initializes the agent and constructs the necessary components. Args: num_actions: int, number of actions the agent can take at any state. observation_shape: tuple of ints or an int. If single int, the observation is assumed to be a 2D square. observation_dtype: DType, specifies the type of the observations. Note that if your inputs are continuous, you should set this to jnp.float32. stack_size: int, number of frames to use in state stack. network: flax.nn Module that is initialized by shape in _create_network below. See dopamine.jax.networks.RainbowNetwork as an example. num_atoms: int, the number of buckets of the value function distribution. vmin: float, the value distribution support is [vmin, vmax]. If None, we set it to be -vmax. vmax: float, the value distribution support is [vmin, vmax]. gamma: float, discount factor with the usual RL meaning. update_horizon: int, horizon at which updates are performed, the 'n' in n-step update. min_replay_history: int, number of transitions that should be experienced before the agent begins training its value function. update_period: int, period between DQN updates. target_update_period: int, update period for the target network. epsilon_fn: function expecting 4 parameters: (decay_period, step, warmup_steps, epsilon). This function should return the epsilon value used for exploration during training. epsilon_train: float, the value to which the agent's epsilon is eventually decayed during training. epsilon_eval: float, epsilon used when evaluating the agent. epsilon_decay_period: int, length of the epsilon decay schedule. replay_scheme: str, 'prioritized' or 'uniform', the sampling scheme of the replay memory. optimizer: str, name of optimizer to use. summary_writer: SummaryWriter object for outputting training statistics. Summary writing disabled if set to None. summary_writing_frequency: int, frequency with which summaries will be written. Lower values will result in slower training. allow_partial_reload: bool, whether we allow reloading a partial agent (for instance, only the network parameters). """ # We need this because some tools convert round floats into ints. vmax = float(vmax) self._num_atoms = num_atoms # If vmin is not specified, set it to -vmax similar to C51. vmin = vmin if vmin else -vmax self._support = jnp.linspace(vmin, vmax, num_atoms) self._replay_scheme = replay_scheme super(JaxRainbowAgent, self).__init__( num_actions=num_actions, observation_shape=observation_shape, observation_dtype=observation_dtype, stack_size=stack_size, network=network.partial(num_atoms=num_atoms, support=self._support), gamma=gamma, update_horizon=update_horizon, min_replay_history=min_replay_history, update_period=update_period, target_update_period=target_update_period, epsilon_fn=epsilon_fn, epsilon_train=epsilon_train, epsilon_eval=epsilon_eval, epsilon_decay_period=epsilon_decay_period, optimizer=optimizer, summary_writer=summary_writer, summary_writing_frequency=summary_writing_frequency, allow_partial_reload=allow_partial_reload) def _create_network(self, name): """Builds a convolutional network that outputs Q-value distributions. Args: name: str, this name is passed to the Jax Module. Returns: network: Jax Model, the network instantiated by Jax. """ _, initial_params = self.network.init(self._rng, name=name, x=self.state, num_actions=self.num_actions, num_atoms=self._num_atoms, support=self._support) return nn.Model(self.network, initial_params) def _build_replay_buffer(self): """Creates the replay buffer used by the agent.""" if self._replay_scheme not in ['uniform', 'prioritized']: raise ValueError('Invalid replay scheme: {}'.format(self._replay_scheme)) # Both replay schemes use the same data structure, but the 'uniform' scheme # sets all priorities to the same value (which yields uniform sampling). return prioritized_replay_buffer.OutOfGraphPrioritizedReplayBuffer( observation_shape=self.observation_shape, stack_size=self.stack_size, update_horizon=self.update_horizon, gamma=self.gamma, observation_dtype=self.observation_dtype) def _train_step(self): """Runs a single training step. Runs training if both: (1) A minimum number of frames have been added to the replay buffer. (2) `training_steps` is a multiple of `update_period`. Also, syncs weights from online_network to target_network if training steps is a multiple of target update period. """ if self._replay.add_count > self.min_replay_history: if self.training_steps % self.update_period == 0: self._sample_from_replay_buffer() self.optimizer, loss, mean_loss = train( self.target_network, self.optimizer, self.replay_elements['state'], self.replay_elements['action'], self.replay_elements['next_state'], self.replay_elements['reward'], self.replay_elements['terminal'], self._support, self.cumulative_gamma) if self._replay_scheme == 'prioritized': # The original prioritized experience replay uses a linear exponent # schedule 0.4 -> 1.0. Comparing the schedule to a fixed exponent of # 0.5 on 5 games (Asterix, Pong, Q*Bert, Seaquest, Space Invaders) # suggested a fixed exponent actually performs better, except on Pong. probs = self.replay_elements['sampling_probabilities'] loss_weights = 1.0 / jnp.sqrt(probs + 1e-10) loss_weights /= jnp.max(loss_weights) # Rainbow and prioritized replay are parametrized by an exponent # alpha, but in both cases it is set to 0.5 - for simplicity's sake we # leave it as is here, using the more direct sqrt(). Taking the square # root "makes sense", as we are dealing with a squared loss. Add a # small nonzero value to the loss to avoid 0 priority items. While # technically this may be okay, setting all items to 0 priority will # cause troubles, and also result in 1.0 / 0.0 = NaN correction terms. self._replay.set_priority(self.replay_elements['indices'], jnp.sqrt(loss + 1e-10)) # Weight the loss by the inverse priorities. loss = loss_weights * loss mean_loss = jnp.mean(loss) if self.summary_writer is not None: summary = tf.compat.v1.Summary(value=[ tf.compat.v1.Summary.Value(tag='CrossEntropyLoss', simple_value=mean_loss)]) self.summary_writer.add_summary(summary, self.training_steps) if self.training_steps % self.target_update_period == 0: self._sync_weights() self.training_steps += 1 def _store_transition(self, last_observation, action, reward, is_terminal, priority=None): """Stores a transition when in training mode. Stores the following tuple in the replay buffer (last_observation, action, reward, is_terminal, priority). Args: last_observation: Last observation, type determined via observation_type parameter in the replay_memory constructor. action: An integer, the action taken. reward: A float, the reward. is_terminal: Boolean indicating if the current state is a terminal state. priority: Float. Priority of sampling the transition. If None, the default priority will be used. If replay scheme is uniform, the default priority is 1. If the replay scheme is prioritized, the default priority is the maximum ever seen [Schaul et al., 2015]. """ if priority is None: if self._replay_scheme == 'uniform': priority = 1. else: priority = self._replay.sum_tree.max_recorded_priority if not self.eval_mode: self._replay.add(last_observation, action, reward, is_terminal, priority) def project_distribution(supports, weights, target_support): """Projects a batch of (support, weights) onto target_support. Based on equation (7) in (Bellemare et al., 2017): https://arxiv.org/abs/1707.06887 In the rest of the comments we will refer to this equation simply as Eq7. Args: supports: Jax array of shape (num_dims) defining supports for the distribution. weights: Jax array of shape (num_dims) defining weights on the original support points. Although for the CategoricalDQN agent these weights are probabilities, it is not required that they are. target_support: Jax array of shape (num_dims) defining support of the projected distribution. The values must be monotonically increasing. Vmin and Vmax will be inferred from the first and last elements of this Jax array, respectively. The values in this Jax array must be equally spaced. Returns: A Jax array of shape (num_dims) with the projection of a batch of (support, weights) onto target_support. Raises: ValueError: If target_support has no dimensions, or if shapes of supports, weights, and target_support are incompatible. """ v_min, v_max = target_support[0], target_support[-1] # `N` in Eq7. num_dims = target_support.shape[0] # delta_z = `\Delta z` in Eq7. delta_z = (v_max - v_min) / (num_dims - 1) # clipped_support = `[\hat{T}_{z_j}]^{V_max}_{V_min}` in Eq7. clipped_support = jnp.clip(supports, v_min, v_max) # numerator = `|clipped_support - z_i|` in Eq7. numerator = jnp.abs(clipped_support - target_support[:, None]) quotient = 1 - (numerator / delta_z) # clipped_quotient = `[1 - numerator / (\Delta z)]_0^1` in Eq7. clipped_quotient = jnp.clip(quotient, 0, 1) # inner_prod = `\sum_{j=0}^{N-1} clipped_quotient * p_j(x', \pi(x'))` in Eq7. inner_prod = clipped_quotient * weights return jnp.squeeze(jnp.sum(inner_prod, -1))
'use strict'; myApp.controller('SwapiFilmsController', function SwapiFilmsController ($scope, $location, filmData){ $scope.films = filmData.getAllFilms(); });
// // JMWKWebView.h // CoreLib // // Created by CoreCode on 06.03.19. /* Copyright © 2020 CoreCode Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitationthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "CoreLib.h" #if __has_feature(modules) @import WebKit; #else #import <WebKit/WebKit.h> #endif @interface JMWKWebView : WKWebView <WKNavigationDelegate> @property (strong, nonatomic) IBInspectable NSString *localHTMLName; // this is loaded first @property (strong, nonatomic) IBInspectable NSString *remoteHTMLURL; // if this is set and internet is online the contents are replaced with the live version @property (strong, nonatomic) IBInspectable NSNumber *zoomFactor; @property (strong, nonatomic) IBInspectable NSString *scrollToAnchor; @property (assign, nonatomic) IBInspectable BOOL disableScrolling; @property (assign, nonatomic) BOOL openOnlyClicksInBrowser; @end
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var ggirsv = require('./routes/ggirsv'); var ka = require('./controllers/keepalive'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.use('/ggirsv', ggirsv); var rsv = require('./controllers/rsv'); function runRsv() { console.log('runRsv'); console.log(Date()); rsv.getRsv('R26', '10', '6', function (error, body) { if (error) { return console.error(error); } //{"result":1,"authcode":"1788"} console.log(body); }); rsv.getRsv('R26', '16', '6', function (error, body) { if (error) { return console.error(error); } console.log(body); }); rsv.getRsv('R27', '10', '6', function (error, body) { if (error) { return console.error(error); } console.log(body); }); setTimeout(setRsv, 60 * 1000 * 61); //setRsv after 1hour, 1min } function setRsv() { console.log('setRsv'); var triggerTime; //setTimeout when run sunday 6am UTC is saturday 21pm triggerTime = rsv.calcRsvTime(6, 21); setTimeout(runRsv, triggerTime); //triggerTime = rsv.calcRsvTime(1, 21); //monday //setTimeout(runRsv, triggerTime); } function setKeepAlive() { setInterval(ka.sendMsg, 1000 * 30); } { setRsv(); setKeepAlive(); } // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
""" WSGI config for gettingstarted project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "configs.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division, print_function, absolute_import import sys import hashlib try: import cPickle as pickle except ImportError: import pickle # shamelessly ripped from https://github.com/kennethreitz/requests/blob/master/requests/compat.py # Syntax sugar. _ver = sys.version_info is_py2 = _ver[0] == 2 is_py3 = _ver[0] == 3 if is_py2: basestring = basestring unicode = unicode range = xrange # range is now always an iterator import Queue as queue import thread as _thread try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # shamelously ripped from six https://github.com/benjaminp/six exec("""def reraise(exception_class, e, traceback=None): try: raise exception_class, e, traceback finally: traceback = None """) from SimpleHTTPServer import SimpleHTTPRequestHandler from BaseHTTPServer import HTTPServer import Cookie as cookies import urlparse import __builtin__ as builtins elif is_py3: basestring = (str, bytes) unicode = str long = int import queue import _thread from io import StringIO from http.server import HTTPServer, SimpleHTTPRequestHandler from http import cookies from urllib import parse as urlparse import builtins # ripped from six https://github.com/benjaminp/six def reraise(exception_class, e, traceback=None): """the 3 params correspond to the return value of sys.exc_info() https://docs.python.org/3/library/sys.html#sys.exc_info :param exception_class: BaseException, the class of the exception to reraise :param e: BaseException instance, the actual exception instance :param traceback: traceback, the stack trace """ try: # if value is None: # value = tp() e = exception_class("" if e is None else e) if e.__traceback__ is not traceback: raise e.with_traceback(traceback) raise e finally: e = None traceback = None Str = unicode if is_py2 else str Bytes = str if is_py2 else bytes class ByteString(Bytes): """Wrapper around a byte string b"" to make sure we have a byte string that will work across python versions and handle the most annoying encoding issues automatically :Example: # python 3 s = ByteString("foo) str(s) # calls __str__ and returns self.unicode() unicode(s) # errors out bytes(s) # calls __bytes__ and returns ByteString # python 2 s = ByteString("foo) str(s) # calls __str__ and returns ByteString unicode(s) # calls __unicode__ and returns String bytes(s) # calls __str__ and returns ByteString """ def __new__(cls, val=b"", encoding="UTF-8"): if isinstance(val, type(None)): return None if not isinstance(val, (bytes, bytearray)): if is_py2: val = unicode(val) else: val = str(val) #val = val.__str__() val = bytearray(val, encoding) instance = super(ByteString, cls).__new__(cls, val) instance.encoding = encoding return instance def __str__(self): return self if is_py2 else self.unicode() def unicode(self): s = self.decode(self.encoding) return String(s) __unicode__ = unicode def bytes(self): return self __bytes__ = bytes def raw(self): """because sometimes you need a vanilla bytes()""" return b"" + self def md5(self): # http://stackoverflow.com/a/5297483/5006 return hashlib.md5(self).hexdigest() class String(Str): """Wrapper around a unicode string "" to make sure we have a unicode string that will work across python versions and handle the most annoying encoding issues automatically :Example: # python 3 s = String("foo) str(s) # calls __str__ and returns String unicode(s) # errors out bytes(s) # calls __bytes__ and returns ByteString # python 2 s = String("foo) str(s) # calls __str__ and returns ByteString unicode(s) # calls __unicode__ and returns String bytes(s) # calls __str__ and returns ByteString """ def __new__(cls, val="", encoding="UTF-8"): if isinstance(val, type(None)): return None if not isinstance(val, (Str, int)): val = ByteString(val, encoding).unicode() instance = super(String, cls).__new__(cls, val) instance.encoding = encoding return instance def __str__(self): return self.bytes() if is_py2 else self def unicode(self): return self __unicode__ = unicode def bytes(self): s = self.encode(self.encoding) return ByteString(s) __bytes__ = bytes def raw(self): """because sometimes you need a vanilla str() (or unicode() in py2)""" return "" + self def md5(self): # http://stackoverflow.com/a/5297483/5006 return hashlib.md5(self.bytes()).hexdigest()
import React from 'react'; import Layout from '../components/layout/layout'; import HomeContent from '../components/home/home-content'; function IndexPage() { return ( <Layout> <HomeContent /> </Layout> ); } export default IndexPage;
'use strict'; var ValidationError = require('../error/validation_error'); var getType = require('../util/get_type'); module.exports = function validateConstants(options) { var key = options.key; var constants = options.value; var styleSpec = options.styleSpec; if (styleSpec.$version > 7) { if (constants) { return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; } else { return []; } } else { var type = getType(constants); if (type !== 'object') { return [new ValidationError(key, constants, 'object expected, %s found', type)]; } var errors = []; for (var constantName in constants) { if (constantName[0] !== '@') { errors.push(new ValidationError(key + '.' + constantName, constants[constantName], 'constants must start with "@"')); } } return errors; } };
# -*- coding: utf-8 -*- """ EVOKE Page class - allowing several "kinds" of pages, including default kinds: - page : a generic page, which can have child pages (of any kind) - file : a reference to a flat file, available for download its parent page - image : a reference to a an image flat file, available for display on its parent page Files and images are included as pages so that they can share the same uid sequence and hierarchy. written by Ian Howie Mackenzie 2006 onwards """ # import os from copy import copy from os.path import lexists, dirname from datetime import timedelta, datetime import pickle as pickle from io import StringIO # try to import PyRSS2Gen gracefully try: import PyRSS2Gen has_rss = True except ImportError: # print("no rss generator.") has_rss = False # local imports from .File import File from .Image import Image from evoke.lib import * from evoke.nevo import NevoDecorator import evoke html = NevoDecorator.make('Page', ['.', dirname(evoke.__file__), './User', ]) class Page(Image, File): "" #stage constants pagestages = ['posted', 'draft'] #kind constants postkinds = ['page'] contextkinds = [ 'image', 'file' ] #these are typically viewed in the context of their parents imageaddkinds = ['page', 'root', 'admin'] # kinds which can have images fileaddkinds = imageaddkinds #kinds which can have child files validchildkinds = {'root': ['page'], 'admin': ['page'], 'page': ['page']} # #### Kinds - convenience methods to ease listing class Kindlist(object): """ Allow us to call Page.kinds.<kind>(**params) instead of Page.list(kind=<kind>, **params) """ def __init__(self, Page): self.Page = Page def __getattr__(self, kind): "return a partially applied list function" def list(**params): # assume we want stage='posted', unless told otherwise params.setdefault('stage', 'posted') return self.Page.list(kind=kind, **params) return list @classmethod def __class_init__(self): """Import additional kind-classes""" self.kinds = self.Kindlist(self) # overrides @classmethod def get(self, uid, data={}): "override get" ob = self.__get__(uid, data) # look for override class for this kind override_classname = 'Page_%s' % ob.kind.replace(' ', '_') if hasattr(ob, override_classname): override_class = getattr(self, override_classname) bases = tuple([override_class, self] + list(ob.__class__.__bases__)) # TODO avoid duplicate base names with more elegance try: ob.__class__ = type(self.__name__, bases, {}) except TypeError: pass ob.__override_classname__ = override_classname ob.get = self.__get__ return ob def __repr__(self): "" return """<UID: %d | Name: %s | Kind: %s | Stage: %s>\n""" % ( self.uid, self.name, self.kind, self.stage) ########## access restrictions ############################ # admin (user.uid==2) has unlimited access # guests can view only posted material, and cannot edit or add def permitted(self, user): """ does user have access rights to this page? """ return (self.stage in [ "posted", "live" ]) or (self.kind == "image") or (user.is_admin()) def edit_permitted(self, user): """ does user have edit rights to this page? """ return (user.is_admin()) def editable(self, req): "is user allowed to edit this page?" return self.edit_permitted(req.user) @classmethod def visible(cls, user, pages): "filters out pages user is not allowed access to " return [p for p in pages if p.permitted(user)] def content_permitted(self, user): "can an article be posted here by req.user?" return self.edit_permitted(user) ### utility methods ######################################################## def get_pob(self): "parent object - cached for efficiency - assumes details wont change during lifespan of instance" if not hasattr(self, "pob"): self.pob = self.get(self.parent) return self.pob def get_container(self, immediate=False): "returns self, if immediate==True and self is a container, or else the containing ancestor, if there is one" # TO BE REWRITTEN...... see get_pref() if not hasattr(self, "_container"): if immediate and self.kind in self.containerkinds: self._container = self else: self._container = None for uid in reversed(self.lineage.split(".")): if uid: c = self.get(int(uid)) if c.kind in self.postkinds: self._container = c break return self._container def get_name(self): "gives '(untitled)' where there is no name" return self.name or '(untitled)' get_title = get_name def get_description(self): "" return "%s %s" % (self.status(full=True) or self.stage, self.kind) def status(self, full=False): "shows any non-'posted' status" s = "" if self.stage == "draft": s = 'draft' return s def tagline(self, showtime=True, long=False): "name and when: used in templates " name = self.Config.attribution == "full" and ( "by %s" % self.get(2).get_name()) or "" # when=self.get_pref('show_time') and self.when.nice(long=long) or "" when = showtime and self.when.nice(long=long) or "" return '%s %s' % (name, when) def has_children(self): "" if hasattr(self, "_children"): return len(self._children) else: return self.count(parent=self.uid) def get_children(self): "gives child objects, cached for efficiency" if not hasattr(self, "_children"): self._children = self.list(parent=self.uid, orderby="seq,uid") return self._children @classmethod def get_parents(self): "returns all parent objects (i.e. parents of further pages- not of images or files)" if not hasattr(self, "_parents"): puids = self.list_int( 'parent', distinct=True, kind='page', orderby="uid") if puids: self._parents = self.list(isin={'uid': puids}) else: self._parents = [] return self._parents def get_children_by_kind(self, kind="", orderby='seq,uid'): "get all children of given (or own) kind" return self.list( parent=self.uid, kind=kind or self.kind, orderby=orderby) def get_minrated_children_by_kind(self, kind="", orderby='seq,uid'): "get all children of given (or own) kind" return self.list( parent=self.uid, kind=kind or self.kind, where=f"rating>={self.minrating()}", orderby=orderby) def get_siblings_by_kind(self, kind=""): "get list of siblings of given (or own) kind" # return self.list(parent=self.parent,kind=kind or self.kind,where='stage!="dead"',orderby='seq,uid') sibs = self.list( parent=self.parent, kind=kind or self.kind, orderby='seq,uid') return [x.uid == self.uid and self or x for x in sibs] #put self in the list def get_older_item(self): "for articles and replies - in date then uid order (seq is ignored) - get next visible sibling of same kind as self" if self.kind in self.postkinds: dt = self.when.sql() sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid!=%s) and ((`when`<%s) or (`when`=%s and uid<%s))' % (self.uid, dt, dt, self.uid), limit=1, orderby='`when` desc, uid desc') return sib and sib[0] or None return None def get_newer_item(self): "for articles and replies - in date then uid order (seq is ignored) - get next visible sibling of same kind as self" if self.kind in self.postkinds: dt = self.when.sql() sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid!=%s) and ((`when`>%s) or (`when`=%s and uid>%s))' % (self.uid, dt, dt, self.uid), limit=1, orderby='`when`, uid') return sib and sib[0] or None return None def get_next_alphabetical_item(self): "get next sibling, in name order, of same kind as self" if self.kind in self.postkinds: sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid!=%s) and (name>="%s")' % (self.uid, self.name), limit=1, orderby='name') return sib and sib[0] or None return None def get_previous_alphabetical_item(self): "for name order (seq is ignored) - get previous sibling of same kind as self" if self.kind in self.postkinds: sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid!=%s) and (name<="%s")' % (self.uid, self.name), limit=1, orderby='name desc') return sib and sib[0] or None return None def get_next_uid_item(self): "get next sibling, in uid order, of same kind as self" if self.kind in self.postkinds: sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid>%s)' % (self.uid, ), limit=1, orderby='uid') return sib and sib[0] or None return None def get_previous_uid_item(self): "get previous sibling, in uid order, of same kind as self" if self.kind in self.postkinds: sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where='(uid<%s)' % (self.uid, ), limit=1, orderby='uid desc') return sib and sib[0] or None return None def get_next_seq_item(self): "get next sibling, in seq order, of same kind as self" if self.kind in self.postkinds: where = '((seq>%s) or ((seq=%s) and (uid>%s)))' % (self.seq, self.seq, self.uid) sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where=where, limit=1, orderby='seq, uid') return sib and sib[0] or None return None def get_previous_seq_item(self): "get previous sibling, in seq order, of same kind as self" if self.kind in self.postkinds: where = '((seq<%s) or ((seq=%s) and (uid<%s)))' % (self.seq, self.seq, self.uid) sib = self.list( parent=self.parent, kind=self.kind, stage='posted', where=where, limit=1, orderby='seq desc, uid desc') return sib and sib[0] or None return None def renumber_siblings(self): "numbers the siblings (ie sets the seq)" n = 1 for s in self.get_pob().get_children( ): #relies on them being sorted by seq,uid if s.seq != n: s.seq = n s.flush() n += 1 def renumber_siblings_by_kind(self): "numbers the siblings (ie sets the seq)" n = 1 for s in self.get_siblings_by_kind( ): #relies on them being sorted by seq,uid # print ">>>>>>>>>>>>>>>>",s.uid,s.seq,n if s.seq != n: s.seq = n s.flush() n += 1 def get_ancestry(self): "convert lineage to list of page objects - returned oldest first - cached" if not hasattr(self, "_ancestry"): self._ancestry = [] for uid in self.lineage.split("."): if uid: self._ancestry.append(self.get(int(uid))) return self._ancestry def get_ancestors(self, kind): "gets ancestry from (and including) the last occurrence of the given kind - returned oldest first" ancs = [] for uid in reversed(self.lineage.split(".")): if uid: a = self.get(int(uid)) ancs.append(a) if a.kind == kind: break return reversed(ancs) def set_lineage(self, pob=None): "sets lineage of self - doesn't flush" pob = pob or self.get_pob() self.lineage = '%s%s.' % (pob.lineage, pob.uid) # print ">>>> SET LINEAGE AS",self.lineage def set_descendant_lineage(self): """calculates, and flushes the lineage for all descendants """ def get_tree(pob): children = pob.list(parent=pob.uid) for s in children: if s.uid > 1: s.set_lineage(pob) # print ">>>> SET DESCENDANT LINEAGE AS",self.lineage s.flush() get_tree(s) get_tree(self) def clear_form(self, req): "blank the form variables" # DO WE NEED THIS ????? req.text = req.code = req.kind = req.name = '' ## page creation / maintenance ################################### def set_seq(self): "default sequence is generally based on 'when'" self.seq = self.when.count() def stamp(self): "date stamp (ie set 'when'), and set 'seq' - also sets thread latest-reply link (in 'seq') - DOESNT FLUSH SELF" self.when = DATE() self.set_seq() # THE FOLLOWING WORKED pre-markdown BUT NEEDS A DIFFERENT TRIGGER (i.e. not **) NOW... # # def expand_text(self, req): # "expands ** into child pages" # pages = self.text.sectioned() # if len(pages) > 1: # for s in reversed(pages[1:]): # n, t = s.split('\n', 1) # self.create_child_page(name=n, text=t) # return pages[0] def flush_page(self, req): "" #remove pesky carriage returns! self.text = self.text.replace("\r","") # self.text = self.expand_text(req) self.flush() # print "++++++++++++++ per MySQL ++++++++++++++++",self.get(self.uid).text def create_page(self, req): "generic create for most page kinds (not images or files) " req.setdefault('kind', 'page') # self.validate_name(self,req) if req.error: return None # update page = self.new() page.parent = self.uid #may be overridden later page.update(req) page.set_lineage() page.stage = req.stage or 'draft' page.stamp() page.flush_page(req) #O/S leave trail entry return page create_page.permit = "no way" def add_page(self, req): "generic add for most page kinds (not images or files) " page = self.create_page(req) if not page: return self.view(req) # return a redirect to avoid the user refreshing forms or copying invalid links return page.redirect( req, 'edit') # default is to return new page in edit mode add_page.permit = "create page" def save_text(self, req): "" # req.text=TEXT(req.text).cleaned() # removed by IHM 12/5/2016 to re-allow use of underlines to extend a style self.update(req) self.flush_page(req) self.clear_form(req) if "post" in req: return self.post(req) if not (req.error or req.message): req.message = "text saved at %s" % DATE().time( sec=True, date=False) return req.redirect( self.url('edit' if self.stage == 'draft' else 'view')) # anchor removed ###################### view (and edit) page ################################## def get_order(self, pref=''): "" p = pref or self.get_pref('order_by') if p == 'name': order = "name" elif p == 'latest': order = "`when` desc,uid desc" elif p == 'seq': order = "seq,uid" else: # order_by=='date' order = "`when`,uid" return order # old version with "first", and "pagemax" instead of "limit" # # def get_child_pages(self,req,first=False,pagemax=50,descend=False): # """pages sequenced according to 'order_by' preference # - optional req.year or req.date, or req.match # - optional req.limit, or pagemax, or first (mutually exclusive - first always starts at the beginning and gives the number to show) # """ def get_child_pages(self, req, limit=50, descend=False): """pages sequenced according to 'order_by' preference - optional req.year or req.date, or req.match - optional req.limit or limit (mutually exclusive - akin to pagesize in def page() in lib/library.py) """ if ('limit' in req): lim = safeint(req.limit) else: # default lim = limit order = self.get_order() if req.date: # date in integer yyyymmdd format where = "`when`=%d" % safeint( req.date) # date converted to safeint to foil SQL injection! elif req.year: where = "year(`when`)=%d" % safeint( req.year) # year converted to safeint to foil SQL injection! elif req.match: where = "name like '%s%%'" % req.match else: where = "" # get the pages if descend or self.get_pref( 'show_descendants' ): # shows every descendant posting you are allowed to see items = self._latest( req, kinds=self.postkinds, where=where, order=order, limit=lim) else: # if first: # lim="0,%s" % pagemax # else: # lim=page(req,pagemax) # items=self.list(parent=self.uid,isin={'kind':self.postkinds},where=where,orderby=order,limit=lim) items = self.list( parent=self.uid, stage='posted', isin={'kind': self.postkinds}, where=where, orderby=order, limit=page(req, lim)) if not req.page: req.page = 'view' # for paging return items def get_branch(self, isin={}, expand=False): "recursive fetch of entire branch (includes self) - can be filtered by 'isin' clause - can expand images, files etc to include their file data" def get_tree(pob): children = pob.list(parent=pob.uid, isin=isin) for s in children: self.branch.append(s) if expand and (s.kind in ['image', 'file']): s.data = s.filedata() get_tree(s) self.branch = [self] get_tree(self) return self.branch def create_child_page(self, name='', text=''): "creates a new child page, and returns it" ob = self.new() ob.parent = self.uid ob.kind = 'page' ob.stage = self.stage ob.when = DATE() ob.name = name ob.text = text ob.set_lineage() ob.flush() ob.renumber_siblings_by_kind() return ob @html def view_form(self, req): "" req.pages = self.get_child_pages(req) # for Page_view_form.evo req.pageuid = self.uid # for use in templates to test whether a given instance is the page instance req.page = "view" if not req.return_to: req.return_to = self.url( ) # allows us to return to this page, if required in template code def view(self, req): "page view" return self.view_form(req) @html def edit_form(self, req): "" req.pages = self.get_child_pages(req) # for template req.pageid = 'page_edit' req.page = "edit" req.edit = self.uid def edit(self, req): "page edit" #make sure we do have permission to edit... if not self.editable(req): req.error = 'you cannot edit this item' return self.view(req) # redirect images and files if self.kind == 'image': self.get_pob().redirect(req, "add_image?edit=%s" % self.uid) elif self.kind == 'file': self.get_pob().redirect(req, "add_file?edit=%s" % self.uid) return self.edit_form(req) edit.permit = 'edit page' def context(self, req): "show in the context of the parent" if self.kind in self.contextkinds: #show in context return self.get_pob().redirect(req, 'view', self.uid) return self.redirect(req, 'view') def swap(self, req): "swaps seq of two sibling pages OF THE SAME KIND, allowing rearrangement of list order" if req.swap: self.renumber_siblings_by_kind() swob = self.get(safeint(req.swap)) z = self.seq self.seq = swob.seq swob.seq = z self.flush() swob.flush() return req.redirect(self.get_pob().url( self.kind in ('file', 'image') and ('add_%s' % self.kind) or 'edit#me')) swap.permit = 'edit page' # def toggle_mode(self, req): # "mode is stored in the cached user object, for permanence" # mode = getattr(req.user, "mode", False) # print("BEFORE mode=", mode) # # req.user.toggle_mode() # print("AFTER mode=", req.user.mode) # url = "%s%s" % (req.return_to, req.user.mode and "/edit" or "") # return req.redirect(url) # # toggle_mode.permit = "admin page" ############# navbar ################# def get_navbar_links(self): """returns (name,href,title) for each navbar link - assumes that navbar items are: - the posted child pages of page 1 - an additions listing link - can be overridden by apps, to give whatever is required """ home = self.get(1) links = [(p.name, p.url(), p.name) for p in home.list( parent=home.uid, kind='page', stage='posted', where="uid!=2", orderby=home.get_order())] links.append(("latest", home.url("latest"), "what's new")) return links def navbar_links(self): """ gets navbar links via cache """ if not hasattr(self, "_navbarlinks"): self._navbarlinks = self.get_navbar_links() return self._navbarlinks ############# options ################ def add_option(self, req, label, method="", hint="", url=""): """adds pageoption (ie local option) if it is permitted (but if url is used in place of method, it is not checked for permission) """ if ((not method) or req.user.can(getattr(self, method))): url = url and self.abs_url(url) or self.url(method) act = [label, url, hint or ("%s %s" % (self.get_name(), label))] if 'pageoptions' in req: req.pageoptions.append(act) else: req.pageoptions = [act] def get_pageoptions(self, req): """ page options - this function is called from Page_header_start.evo to produce page tabs """ # view self.add_option(req, self.kind, 'view') # edit etc. if self.editable(req): uid = req.edit or req.view or self.uid self.add_option(req, 'edit', 'edit', hint='edit this page') # images if self.kind in self.imageaddkinds: self.add_option(req, "images", "add_image") # files if self.kind in self.fileaddkinds: self.add_option(req, "files", "add_file") # prefs if self.kind in self.default_prefs: self.add_option(req, "preferences", "preferences") # owner options if self.uid == 2: # can't use my() function here as different methods are required self.add_option(req, 'my details', 'details') drafts = self.drafts_count(req) if drafts: self.add_option(req, 'my drafts (%s)' % drafts, 'drafts') # move, copy, export, import moved here for convenience of access - BUT NOTE: SHOULD BE POSTs not GETs (IHM 13/12/2015) move = self.get_move(req) if move: self.add_option( req, 'cancel move', 'cancel_move', hint='cancel page move') if self.can_move_here(req): self.add_option( req, 'copy here', 'copy', hint='copy page %s here' % move.uid) if self.uid not in (move.uid, move.parent): self.add_option( req, 'move here', 'here', hint='move page %s here' % move.uid) else: if req.user.can('admin page'): self.add_option( req, 'move/copy', 'move', hint='mark for moving or copying') # temporarily disable Export/Imprt until it can be fully tested... (IHM Dec 2015) # if self.stage!='draft': # self.add_option(req,'export','export') # self.add_option(req,'import','import_eve') # remove single tabs if len(req.pageoptions) == 1: req.pageoptions = [] # pass back the result return req.pageoptions ############### actions ###################### def add_act(self, req, label, method="", confirm="", url="", hint="", hilite=False, key=""): """adds act if it is permitted (but if url is used in pace of method, it is not checked for permission) url will override method, but method can still be given to check permits """ if (not method ) or req.user.can(getattr(self, method.split('#', 1)[0])): # url=method and self.url(method) or self.abs_url(url) url = url and self.abs_url(url) or self.url(method) act = [ label, url, hint or confirm or method, confirm and ("return confirm('are you sure you wish to %s?')" % confirm) or "", hilite, key ] if 'actions' in req: req.actions.append(act) else: req.actions = [act] def add_delete(self, req): self.add_act(req, 'delete', 'kill', 'delete this %s' % self.kind) # def set_listing_actions(self,req): # "" def get_actions(self, req): "actions - note that action button forms should use method='get', as action parameters are passed in the URL" # stage changes if self.stage == 'posted': self.add_act(req, 'withdraw', 'withdraw', 'withdraw this %s and all its contents' % self.kind) elif self.stage == 'draft': if (self.text or self.get_images() or req.pages or req.contents) and not req.edit: self.add_act( req, 'post', 'post', hint='make this %s public' % self.kind, hilite=True) self.add_delete(req) return req.actions # TEMPRARY DISABLING OF MOVE/COPY/EXPORT/IMPORT # move, copy, export, import move = self.get_move(req) if move: self.add_act( req, 'cancel move', 'cancel_move', hint='cancel page move') if self.can_move_here(req): self.add_act(req, 'copy here', 'copy', 'copy page %s here' % move.uid) if self.uid not in (move.uid, move.parent): self.add_act(req, 'move here', 'here', 'move page %s here' % move.uid) else: if req.user.can('admin page'): self.add_act( req, 'move/copy', 'move', hint='mark for moving or copying') # temrarily disable Export/Imprt until it can be fully tested... (IHM Dec 2015) # if self.stage!='draft': # self.add_act(req,'export','export') # self.add_act(req,'import','import_eve') # and return return req.actions def can_move_here(self, req): """is it okay to move or copy the move object here? - this is a hook for override by inheriting classes" - default: can move anything here, provided we have a valid move uid """ return self.get_move(req) def _posted(self, req): """post a draft (inner workings) """ if self.stage != 'posted': #safety valve self.stage = 'posted' self.stamp() # store it all self.flush() req.message = 'your %s is posted' % (self.kind, ) return True return False _posted.permit = 'NOWAY' def post(self, req): """post a draft (requestable) """ if self._posted(req): # return the parent page return self.context(req) #else return self.view(req) post.permit = 'create page' def withdraw(self, req): "remove from posted: reset self and all posted descendants back to draft" if self.stage == 'posted': self.stage = 'draft' self.flush() #set message req.message = 'this %s is now draft' % self.kind return self.view(req) withdraw.permit = "admin page" def kill(self, req): "delete self and all childen!" if (self.stage == 'draft'): #safety first self.delete_branch() message = '%s "%s" has been deleted' % (self.kind, self.name) else: message = 'deletion denied' return req.redirect( self.get_pob().url('view?message=%s' % url_safe(message))) kill.permit = "create page" #creator can kill a page, but not if it has been been posted (as she can't withdraw it without admin permit) def delete_branch(self): "branch deletion - self and ALL child pages of any kind (the whole branch!) are deleted" for p in self.get_branch(): if p.kind == 'image': self.get(p.uid).delete_image() else: p.delete() def manage(self, req): "link to user edit" user = self.User.list(page=self.uid)[0] req.page = 'manage' # tabs need this return user.edit(req) manage.permit = 'edit user' def details(self, req): "link to edit of own details" req.page = 'details' return req.redirect(req.user.url("edit")) ###################### ratings / enable / disable ################### ratedkinds=("page","image") downratings=(-4,-4,-3,-2,-4,0,1) upratings=(0,-2,-1,-1,1,2,2) # non glyphicon version # access these via rating_symbol() rating_symbols=('&times;','?','&radic;','&hearts;','?','&radic;','&hearts;') def rating_symbol(self,rating=None): "give symbol for rating" # rating should be in (-4,-3,-2,-1,0,1,2) r=min(6,max(0,(rating if rating is not None else self.rating)+4)) return self.rating_symbols[r] # glyphicon version # access these via rating_class() rating_classes=('remove-sign','question-sign','ok-sign','heart','question-sign','ok-sign','heart') def rating_class(self,rating=None): "give class for rating" # rating should be in (-4,-3,-2,-1,0,1,2) r=min(6,max(0,(rating if rating is not None else self.rating)+4)) return "glyphicon glyphicon-%s" % self.rating_classes[r] # generic def set_rating(self,rating): "sets self.rating to rating" self.rating=rating self.flush() def minrating(self): "returns (cached) minimum rating accepted by global filter" if not hasattr(self, "_v_minrating"): self._v_minrating = self.list_int(item='rating',uid=1)[0] return self._v_minrating def set_global_filter(self,req): "sets root rating (used as a global filter) to req.rating" self.get(1).set_rating(req.rating) return req.redirect(self.url()) def rate_up(self,req): "increase rating" try: self.rating=self.upratings[self.rating+4] self.flush() except: pass return req.redirect(self.url()) def rate_down(self,req): "decrease rating" try: self.rating=self.downratings[self.rating+4] self.flush() except: pass return req.redirect(self.url()) def toggle_disable(self,req): "disable / enable" try: self.rating=(0,0,1,2,-3,-2,-1)[self.rating+4] self.flush() except: pass return req.redirect(self.url()) ###################### emails ########################## def email_enabled(self): "" return self.Config.mailfrom and self.Config.SMTPhost and True or False def email(self, TO, subject, text='', html=''): """convenient wrapper for library email function, supplying the configuration defaults Note that if self.Config.mailfrom has a False value, or no SMTPhost is set, no attempt will be made to send any email """ if self.email_enabled(): email( FROM=self.Config.mailfrom, TO=TO, subject=subject, text=text, html=html, SMTP=self.Config.SMTPhost, LOGIN=self.Config.SMTPlogin) ######################preferences ######################## # O/S : prefs should be stored in a separate table (rather than a column), for more efficient access # as currently every single pref can require multiple page fetches (up the lineage) to find its value # Alternatively, in get_pref(), lineage objects containing prefs should be cached when first accessed # CONTAINER code elsewhere should be replaced with same LINEAGE approach as in get_pref() page_default_prefs = { 'order_by': ('latest', 'order items by', ('date', 'latest', 'name', 'seq')), #'show_time': ('Y', 'show dates and times', 'checkbox'), # 'in_menu':('','in menu?','checkbox'), 'show_descendants': ('', 'show all descendants?', 'checkbox') } default_prefs = { # {kind:{name:(default,display-name,display-type/size/options),},} 'root': copy(page_default_prefs), 'admin': copy(page_default_prefs), 'page': copy(page_default_prefs), } def get_prefs(self): "returns dictionary of page preferences, from cache if possible - will use defaults if no prefs have yet been set" # # BUG! - THIS SHOULD TRAVERSE THE PREF HIERARCHY WHEN LOCAL PREF IS NOT YET CREATED, i.e. AS PER get_pref() # # preferences code NEEDS REDESIGN, to recognise use of empty strings # currently, only checkboxes can have an empty string as a valid override preference # PREFERENCES SHOULD BE TOTALLY AMALGAMATED WITH Config # if not hasattr(self, '_prefs'): self._prefs = {} if self.kind in self.default_prefs: defs = self.default_prefs[self.kind] if self.prefs: for i in self.prefs.split('\n'): if i: k, v = i.split('=') if k in defs: # check to skip old preferences that have been removed from defs if not v and ( defs[k][2] != 'checkbox' ): # non-checkboxes require a value v = None self._prefs[k] = v else: #prefs not yet created, so use defaults for k, v in list(defs.items()): self._prefs[k] = v[0] return self._prefs def get_pref(self, pref): "returns relevant pref from self.prefs, or container prefs, or Config" p = None # print "getting pref: ",pref, " for " ,self.kind,self.uid if self.kind in self.default_prefs: # check own prefs p = self.get_prefs().get(pref) # print "checking self: ",repr(p) if p is None: # check up along the lineage lineage = reversed(self.lineage.strip(".").split(".")) # print ">>> lineage = ",list(lineage) for l in lineage: if l: container = self.get(safeint(l)) if container.kind in self.default_prefs: # check container's prefs p = container.get_prefs().get(pref) # print "checking lineage: ",container.uid, container.name,"=>", repr(p) if not p is None: break if p is None: # check config p = getattr(self.Config, pref, '') # print "checking config: ",repr(p) # print "GOT ",repr(p) return p @html def preferences(self, req): "" req.page = 'preferences' preferences.permit = 'admin page' def update_prefs(self, req): "called by Page_preferences.evo: updates self.prefs" xprefs = self.get_prefs() self.prefs = '' for name, defn in list(self.default_prefs[self.kind].items()): default, displayname, typ = defn value = req.get(name, '').strip() # print "======",name,':',value,' ( ',req.get(name,''),' )' self.prefs += '%s=%s\n' % (name, value) # make any changes necessary - see change_theme() in music app as an example if (xprefs.get(name) != value) and hasattr(self, "change_%s" % name): getattr(self, "change_%s" % name)(req) self.flush() del self._prefs # clear cache return req.redirect(self.url()) update_prefs.permit = 'create page' def set_pref(self, pref, value): "updates a single pref in self.prefs - DOES NOT FLUSH" prefs = self.get_prefs() prefs[pref] = value self.prefs = '' for name, value in list(prefs.items()): self.prefs += '%s=%s\n' % (name, value) ###################### listings ######################### @html def listing(self, req): "" def drafts_count(self, req): return self.count(isin={'kind': self.postkinds}, stage='draft') def drafts(self, req, pagemax=50): "draft items" limit = page(req, pagemax) req.pages = self.list( isin={'kind': self.postkinds}, stage='draft', orderby="`when` desc,uid desc", limit=limit) req.title = 'drafts' req.page = 'drafts' # for paging return self.listing(req) # def _latest(self,req,kinds="",order="`when` desc",where="",limit=50, first=False): def _latest(self, req, kinds="", order="`when` desc", where="", limit=50): " what's new? - based on lineage of the page, so page 1 gives everything" # if first: # a non-False value for first must be the number of items to show (this overrides limit) # lim="0,%s" % first # else: lim = page(req, limit) if limit else "" _kinds = kinds or self.postkinds _where = '%s%s lineage like "%s%%"' % ( (where + " and ") if where else "", "rating>=0 and" if self.uid == 1 else "", self.lineage + str(self.uid) + '.') #print where # items = self.list(isin={'stage':('posted','live'),'kind':_kinds},where=_where,orderby=order,limit=lim) items = self.list( stage='posted', isin={'kind': _kinds}, where=_where, orderby=order, limit=lim) return items def latest(self, req): "" req.pages = self._latest(req) req.title = "latest" req.page = 'latest' # for paging return self.listing(req) def latest_rss(self, req): if not has_rss: return 'rss support required' def escape(s): "work around the entification of & < >" s = s.replace("&", "[amp]") s = s.replace(">", "[gt]") s = s.replace("<", "[lt]") return s def unescape(s): "work around the entification of & < >" s = s.replace("[amp]", "&") s = s.replace("[gt]", ">") s = s.replace("[lt]", "<") return s items = [ PyRSS2Gen.RSSItem( title=i.name, link="http://" + self.Config.domains[0] + i.url(), description=escape("<![CDATA[%s]]>" % i.text.formatted(req)), guid=PyRSS2Gen.Guid(i.url()), pubDate=i.when.datetime) for i in self._latest(req) ] rss = PyRSS2Gen.RSS2( self.name, "http://" + self.Config.domains[0] + self.url(), "recent activity for %s" % self.name, lastBuildDate=datetime.now(), items=items) outf = StringIO() rss.write_xml(outf, encoding='utf-8') outf.reset() res = unescape(outf.getvalue()) return res feed = latest_rss # @html # def news_area(self,req): # "wrappper-free news top 3" # req.wrapper=None def news(self, req): """ what's new? (latest 3 items) call this from e.g. a wrapper with self.get(1).news(req) """ where = '%s lineage like "%s%%"' % ( self.uid == 1 and "rating>=0 and" or "", self.lineage + str(self.uid) + '.') req.pages = self.list( stage='posted', isin={'kind': self.postkinds}, where=where, orderby="`when` desc", limit='0,3') req.title = "news" req.prep = 'from' req.wrapper = None return self.listing(req) ####################### search ######################## @html def results(self, req): "search results" def search_extra_objects(self, term): "dummy to allow inheriting classes to insert other object results" return [] def search(self, req): "search box supersearch" reslimit = 200 # we don't want more results than this... resleft = 0 resfound = 0 heads = [] term = req.searchfor.upper().replace('"', '').replace("'", '').replace( '*', '%') # is it a uid? if safeint(term): try: heads = [self.get(safeint(term))] except: heads = [] # search for matches.. if len(term) > 2: req.searchfor = term #store clean version # get title matches first heads.extend( self.list( where='name like "%%%s%%"' % term, orderby='uid desc')) # now get text matches if len(heads) < reslimit: resleft = reslimit - len(heads) # get head uids head_uids = [a.uid for a in heads] # extensions bodies = [ p for p in self.search_extra_objects(term) if p.uid not in head_uids ] resleft = resleft - len(bodies) # full text search of text bodies - remove any duplicates # if resleft>0: bodies.extend( self.list( where=("match `text` against ('%s' in boolean mode)" % term), orderby="uid desc")) # we could limit the above to reslimit, but we don't know what is to be filtered out below.... # note: "against('%s')" ignores any match that is in more than 50% of the rows # - we get round this by using "against('%s' in boolean mode) # however, boolean mode does not sort results by relevance (hence the orderby clause is added also) # boolean mode: + and - operators indicate that a word is required to be present or absent, respectively, # for a match to occur. # filter out duplicates bodies = [p for p in bodies if p.uid not in head_uids] # add together heads.extend(bodies) # filter out private items heads = self.visible(req.user, heads) resfound = len(heads) # cut to size heads = heads[:reslimit] # and display if len(heads) == 1: #show result req.message = '1 result found for "%s"' % term # return req.redirect(heads[0].url('view?searchfor=%s&message=%s' % (url_safe(term),url_safe(req.message)))) return req.redirect(heads[0].url('view?searchfor=%s')) # return heads[0].view(req) if heads: req.message = '%s results found for "%s" %s' % ( resfound, term, resfound > reslimit and ",first %s shown" % reslimit or "") else: req.warning = 'no results found matching "%s"' % term req.results = heads return self.get(1).results(req) # search.permit="guest"#allow anybody in ################ move / copy / export / import ################ @html def import_form(self, req): "" pass import_form.permit = 'admin page' def export(self, req): "use redirect to allow a useful filename" return req.redirect( self.url('%s.%s.eve' % (self.Config.domain, self.uid))) export.permit = 'admin page' def export_eve(self, req): """exports a pickle of self and all descendents (ie branch) data files (images etc) are included (by get_branch(expand=True)) user stub homepages are also included, so that authorship can be retained will only work for movekinds O/S - export requires local URLS to be replaced with external ones.. - see old versions of TEXT.py """ # get header info data = dict( version=self.Config.version, domain=self.Config.domain, ) # get the branch, and prepare it (note that this trashes the data in self) branch = [] for i in self.get_branch(expand=True): if i.stage != 'draft': #exlude draft items ????????????????? DO WE WANT?NEED TO EXLUDE THEM ???? i.text = i.text.exported(req) # expand the links in the text branch.append(i) # export it all data.update( branch=[b.for_export(extras=['data']) for b in branch], ) req.request.setHeader('content-type', 'application/octet-stream') return pickle.dumps( data, pickle.HIGHEST_PROTOCOL) #pickle using highest protocol (binary) export_eve.permit = 'admin page' def import_eve(self, req): """imports a pickled branch and adds it as a child of self" """ if not req.filename: return self.import_form(req) # fetch the data try: data = pickle.loads(req.filedata) except: raise req.error = 'cannot import "%s"' % req.filename return self.import_form(req) # convert from export dict format to objects branch = [self.get(0, data=i) for i in data['branch']] # convert and store the branch return self.store_branch(req, branch) import_eve.permit = 'admin page' def store_branch(self, req, branch): "converts branch to be a child of self, and adds it to the database" # fix the descendents for ob in branch: # print ">>>>>>>>>>>>>>> ob=",ob.__dict__ # ob.table=self.table # fix the table so we have the correct database! # ob.Config=self.Config # fix Config # print "content ",ob.uid,ob.kind,ob.name,ob._v_changed nob = self.new() for i in branch: # fix the parent of any child if i.parent == ob.uid: i.parent = nob.uid ob.uid = nob.uid if hasattr(ob, 'data'): # store file data if ob.kind == 'image': ob.code = '%s.%s' % (ob.uid, ob.code.split(".")[-1] ) # rename image files to use new uid ob.save_file(ob.data) ob.all_change() # print "flushing ",ob.uid,ob.kind,ob.name,ob._v_changed ob.flush() # here it req._import = self.get( branch[0].uid ) # get the local object (ie not the imported one, which won't work in here()) return self.here(req) def move(self, req): "marks page for moving (stored in user cache)" if not req.user.can('admin page'): return self.view(req) self.set_move(req) return req.redirect( self.url('view?message=%s' % url_safe( 'page %s marked for moving - now navigate to the required destination' % self.uid))) move.permit = 'create page' def copy(self, req): "duplicate self and all descendents (ie branch) - will only work for movekinds" move = self.get_move(req) if move: req._copying = True return self.store_branch(req, move.get_branch(expand=True)) req.warning = 'system was reset - page copy canceled' return self.view(req) copy.permit = 'create page' def cancel_move(self, req): "clear the session cache move uid" req.cache['page_move'] = None message = 'page move cancelled' return self.view(req) def here(self, req): "moves marked page here (as a child)" move = req._import or self.get_move(req) if move: # fix parent, lineage move.parent = self.uid move.set_lineage(self) move.set_descendant_lineage() move.flush() message = '"%s" %s here' % ( move.get_name(), (req._copying and 'copied') or (req._import and 'imported') or 'moved') req.cache['page_move'] = None # clear the session cache move uid else: req.warning = 'system was reset - page move canceled' return self.view(req) return req.redirect(self.url('view?message=%s' % url_safe(message))) here.permit = 'create page' def set_move(self, req): "stores self.uid in session cache (req.cache['page_move'])" req.cache['page_move'] = self.uid @classmethod def get_move(cls, req): "gets move uid from session cache (req.cache['page_move'])" move = req.cache.get('page_move', None) # print ">>>>>>>>>> move=",move if move: if cls.exists(move): return cls.get(move) return None ##### shortcuts def login(self, req): "shortcut to user login" req.return_to = self.url() return req.user.login_form(req) login.permit = "guest" ################ templates for mix-in classes ############## # # These are here for now, as evoke.render.html() uses the last item in the module name to # obtain the template name... # Note that the __module__ for an @html function declared in Image.py will be "Page.Image", # so it would be possible to derive "Page" from that.... @html def file_add(self, req): "" req.page = "add_file" # for tab display file_add.permit = 'edit page' @html def image_add(self, req): "" req.page = 'add_image' # for tab display image_add.permit = 'edit page' ################ utilities ################## # map old cells layout to Bootstrap def cell_to_col(self, cell): "map cell id in form <cells-per-row><position> to Bootstrap col-md-<cells>" cell = int(str(cell)[0]) # becomes less precise where cell=5 and cell>7 cell_col = {1: 12, 2: 6, 3: 4, 4: 3, 5: 2, 6: 2} return cell_col.get(cell, 1) def list_prefs(self, req): "lists prefs for self" prefs = self.get_prefs() o = self.prefs + '<br/><br/>' for i in prefs: o += '%s: %s<br/>' % (i, self.get_pref(i)) if req.pref: o += '%s: %s' % (req.pref, str(self.get_pref(req.pref))) return o def list_config(self, req): "lists self.Config settings" o = '' for i in sorted(self.Config.__dict__.items()): if i[0] == 'connect': i = (i[0], '*************') o += '<b>%s</b> : %s <br/>' % i return o list_config.permit = 'admin page' def list_items(self, req): "lists self's items" o = '' for i in sorted(self.__dict__.items()): o += '<b>%s</b> : %s <br/>' % i return o list_items.permit = 'admin page' def info(self, req): "" o = [] o.append("<b>module:</b> " + self.__class__.__module__) o.append("<b>class:</b> " + self.__class__.__name__) o.append("<b>bases:</b> " + ','.join( (b.__name__ for b in self.__class__.__bases__))) o.append("<b>dict:</b>") for (k, v) in list(self.__dict__.items()): o.append('<i>%s:</i> %s' % (k, str(v))) o.append("<b>class dict:</b>") for (k, v) in list(self.__class__.__dict__.items()): o.append('<i>%s:</i> %s' % (k, str(v))) return '<br/>'.join(o) info.permit = 'admin page' def delf(self, req): "removes superfluous line ends from text - e.g. emailed text" self.text = delf(self.text) self.flush() req.message = "line ends removed" return self.edit(req) delf.permit = 'admin page' ################# FIXES ######################## def fix_seq(self, req): "resets seq for current page" self.set_seq() self.flush() req.message = 'seq fixed' return self.view(req) fix_seq.permit = "admin page" def fix_lineage(cls, req, ret=True): 'set lineage throughout' s = cls.get(2) s.parent = 1 s.flush() s = cls.get(1) s.lineage = "." s.flush() s.set_descendant_lineage() if ret: req.message = 'lineage fixed!' return cls.get(1).view(req) fix_lineage.permit = 'admin page' fix_lineage = classmethod(fix_lineage) def testvar(cls, req): req.message = cls.Var.say('version') return cls.latest(req) def testbug(self, req): "" x = 1 + 'three' return self.view(req) ############## ONE-OFF FIXES ################## # def to_md(self,req): # "" # n=0 # for i in self.list(): # if i.text: # i.text=i.text.to_markdown(req) # i.flush() # n+=1 # req.message='%s pages converted to md' % n # return self.view(req)
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(require("./zip/zip_archive_writer")); __export(require("./zip/zip_archive_reader")); __export(require("./zip/zip_buffer_archive_reader")); __export(require("./zip/zip_blob_archive_reader")); __export(require("./zip/pack")); __export(require("./zip/unpack"));
""" This module is specifically intended for use when in environments where you're actively trying to share/develop tools across multiple applications which support PyQt, PySide or PySide2. The premise is that you can request the main application window using a common function regardless of the actual application - making it trivial to implement a tool which works in multiple host applications without any bespoke code. The current list of supported applications are: * Native Python * Maya * 3dsmax * Motion Builder """ import sys from ..vendor import Qt # Python 2/3 compat # TODO: Use six. try: long except NameError: long = int # ------------------------------------------------------------------------------ def get_host(): global HOST if HOST: pass elif ('maya.exe' in sys.executable or 'mayapy.exe' in sys.executable): HOST = 'Maya' elif ('motionbuilder.exe' in sys.executable or 'mobupy.exe' in sys.executable): HOST = 'Mobu' elif '3dsmax.exe' in sys.executable: HOST = 'Max' elif any(houdini_exec in sys.executable for houdini_exec in ['houdini.exe', 'houdinifx.exe', 'houdinicore.exe']): HOST = 'Houdini' return HOST # ------------------------------------------------------------------------------ # noinspection PyPep8Naming def mainWindow(): """ Returns the main window regardless of what the host is :return: """ return HOST_MAPPING[get_host()]() # ------------------------------------------------------------------------------ # noinspection PyUnresolvedReferences,PyPep8Naming def returnNativeWindow(): for candidate in Qt.QtWidgets.QApplication.topLevelWidgets(): if isinstance(candidate, Qt.QtWidgets.QMainWindow): return candidate # ------------------------------------------------------------------------------ # noinspection PyUnresolvedReferences,PyPep8Naming def _findWindowByTitle(title): # -- Find the main application window for candidate in Qt.QtWidgets.QApplication.topLevelWidgets(): # noinspection PyBroadException try: if title in candidate.windowTitle(): return candidate except Exception: pass # ------------------------------------------------------------------------------ # noinspection PyPep8Naming def returnModoMainWindow(): pass # ------------------------------------------------------------------------------ # noinspection PyPep8Naming def returnMaxMainWindow(): return _findWindowByTitle('Autodesk 3ds Max') # ------------------------------------------------------------------------------ # noinspection PyUnresolvedReferences,PyPep8Naming def returnMayaMainWindow(): from maya import OpenMayaUI as omui return Qt.QtCompat.wrapInstance( long(omui.MQtUtil.mainWindow()), Qt.QtWidgets.QWidget, ) # ------------------------------------------------------------------------------ # noinspection PyPep8Naming def returnHoudiniMainWindow(): import hou return hou.qt.mainWindow() # ------------------------------------------------------------------------------ # noinspection PyPep8Naming def returnMobuMainWindow(): return _findWindowByTitle('MotionBuilder 20') # ------------------------------------------------------------------------------ HOST = None HOST_MAPPING = { None: returnNativeWindow, 'Maya': returnMayaMainWindow, 'Max': returnMaxMainWindow, 'Modo': returnModoMainWindow, 'Mobu': returnMobuMainWindow, 'Houdini': returnHoudiniMainWindow, }
var __create = Object.create; var __defProp = Object.defineProperty; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value; var __assign = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); var __export = (target, all) => { for (var name in all) __defProp(target, name, {get: all[name], enumerable: true}); }; var __exportStar = (target, module2, desc) => { if (module2 && typeof module2 === "object" || typeof module2 === "function") { for (let key of __getOwnPropNames(module2)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable}); } return target; }; var __toModule = (module2) => { return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2); }; __markAsModule(exports); __export(exports, { default: () => unlockIcon_default }); var import_react = __toModule(require("react")); function UnlockIcon(props, svgRef) { return /* @__PURE__ */ import_react.default.createElement("svg", __assign({ "data-sanity-icon": "unlock", width: "1em", height: "1em", viewBox: "0 0 25 25", fill: "none", xmlns: "http://www.w3.org/2000/svg", ref: svgRef }, props), /* @__PURE__ */ import_react.default.createElement("path", { d: "M7.5 11.5H17.5V19.5H7.5V11.5Z", stroke: "currentColor", strokeWidth: 1.2 }), /* @__PURE__ */ import_react.default.createElement("path", { d: "M3.5 11.5V7.5C3.5 5.5 4.5 4.5 6.5 4.5C8.5 4.5 9.5 5.5 9.5 7.5V11.5", stroke: "currentColor", strokeWidth: 1.2 })); } const ForwardRef = import_react.default.forwardRef(UnlockIcon); var unlockIcon_default = ForwardRef;
#------------------------------------------------------------------------- # Copyright (c) Microsoft. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------- import os import sys from azure import ( WindowsAzureError, DEFAULT_HTTP_TIMEOUT, DEV_ACCOUNT_NAME, DEV_ACCOUNT_KEY, _ERROR_STORAGE_MISSING_INFO, ) from azure.http import HTTPError from azure.http.httpclient import _HTTPClient from azure.storage import _storage_error_handler #-------------------------------------------------------------------------- # constants for azure app setting environment variables AZURE_STORAGE_ACCOUNT = 'AZURE_STORAGE_ACCOUNT' AZURE_STORAGE_ACCESS_KEY = 'AZURE_STORAGE_ACCESS_KEY' EMULATED = 'EMULATED' #-------------------------------------------------------------------------- class _StorageClient(object): ''' This is the base class for BlobManager, TableManager and QueueManager. ''' def __init__(self, account_name=None, account_key=None, protocol='https', host_base='', dev_host='', timeout=DEFAULT_HTTP_TIMEOUT, sas_token=None): ''' account_name: your storage account name, required for all operations. account_key: your storage account key, required for all operations. protocol: Optional. Protocol. Defaults to http. host_base: Optional. Live host base url. Defaults to Azure url. Override this for on-premise. dev_host: Optional. Dev host url. Defaults to localhost. timeout: Optional. Timeout for the http request, in seconds. sas_token: Optional. Token to use to authenticate with shared access signature. ''' self.account_name = account_name self.account_key = account_key self.requestid = None self.protocol = protocol self.host_base = host_base self.dev_host = dev_host self.sas_token = sas_token # the app is not run in azure emulator or use default development # storage account and key if app is run in emulator. self.use_local_storage = False # check whether it is run in emulator. if EMULATED in os.environ: self.is_emulated = os.environ[EMULATED].lower() != 'false' else: self.is_emulated = False # get account_name and account key. If they are not set when # constructing, get the account and key from environment variables if # the app is not run in azure emulator or use default development # storage account and key if app is run in emulator. if not self.account_name and not self.account_key: if self.is_emulated: self.account_name = DEV_ACCOUNT_NAME self.account_key = DEV_ACCOUNT_KEY self.protocol = 'http' self.use_local_storage = True else: self.account_name = os.environ.get(AZURE_STORAGE_ACCOUNT) self.account_key = os.environ.get(AZURE_STORAGE_ACCESS_KEY) if not self.account_name: raise WindowsAzureError(_ERROR_STORAGE_MISSING_INFO) self._httpclient = _HTTPClient( service_instance=self, protocol=self.protocol, timeout=timeout) self._batchclient = None self._filter = self._perform_request_worker def with_filter(self, filter): ''' Returns a new service which will process requests with the specified filter. Filtering operations can include logging, automatic retrying, etc... The filter is a lambda which receives the HTTPRequest and another lambda. The filter can perform any pre-processing on the request, pass it off to the next lambda, and then perform any post-processing on the response. ''' res = type(self)(self.account_name, self.account_key, self.protocol, self.host_base, self.dev_host, self._httpclient.timeout) old_filter = self._filter def new_filter(request): return filter(request, old_filter) res._filter = new_filter return res def set_proxy(self, host, port, user=None, password=None): ''' Sets the proxy server host and port for the HTTP CONNECT Tunnelling. host: Address of the proxy. Ex: '192.168.0.100' port: Port of the proxy. Ex: 6000 user: User for proxy authorization. password: Password for proxy authorization. ''' self._httpclient.set_proxy(host, port, user, password) @property def timeout(self): return self._httpclient.timeout @timeout.setter def timeout(self, value): self._httpclient.timeout = value def _get_host(self): if self.use_local_storage: return self.dev_host else: return self.account_name + self.host_base def _perform_request_worker(self, request): return self._httpclient.perform_request(request) def _perform_request(self, request, text_encoding='utf-8'): ''' Sends the request and return response. Catches HTTPError and hand it to error handler ''' try: if self._batchclient is not None: return self._batchclient.insert_request_to_batch(request) else: resp = self._filter(request) if sys.version_info >= (3,) and isinstance(resp, bytes) and \ text_encoding: resp = resp.decode(text_encoding) except HTTPError as ex: _storage_error_handler(ex) return resp
import argparse class GitHubArgumentParseError(Exception): """ Raised when there is an error parsing arguments for a CLI invocation from GitHub. """ class CustomHelpAction(argparse._HelpAction): """ Custom argparse action that handles -h and --help flags in Bugout Slack argument parsers. This is part of the dirty hack to get around the annoying exit behaviour of argparse. The other part of this is the custom ArgumentParser subclass we use (defined below). """ def __init__( self, option_strings, dest=argparse.SUPPRESS, default=argparse.SUPPRESS, help=None, ): super().__init__(option_strings, dest, default, help) def __call__(self, parser, namespace, values, option_string=None): raise GitHubArgumentParseError(parser.format_help()) class BugoutGitHubArgumentParser(argparse.ArgumentParser): """ Parser for CLI invocations via GitHub. Modified version of parse_raw_text() from slack/commands.py """ def error(self, message): message_with_usage = f"{self.format_usage()}\n{message}" raise GitHubArgumentParseError(message_with_usage) def register(self, registry_name, value, object): registry = self._registries.setdefault(registry_name, {}) if value == "help": registry[value] = CustomHelpAction else: registry[value] = object
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ cache = [[]] for index in range(len(s) - 1, -1, -1): tmp, suffix = [], s[index:] for cursor in range(index + 1, len(s)): sub = s[index:cursor] if sub == sub[::-1]: for this_list in cache[len(s) - cursor]: next_list = this_list[:] next_list.insert(0, sub) tmp.append(next_list) if suffix == suffix[::-1]: tmp.append([suffix]) cache.append(tmp) return cache[-1]
/** * Module dependencies. */ var qs = require('querystring'); var parse = require('url').parse; var base64id = require('base64id'); var transports = require('./transports'); var EventEmitter = require('events').EventEmitter; var Socket = require('./socket'); var util = require('util'); var debug = require('debug')('engine'); var cookieMod = require('cookie'); /** * Module exports. */ module.exports = Server; /** * Server constructor. * * @param {Object} options * @api public */ function Server (opts) { if (!(this instanceof Server)) { return new Server(opts); } this.clients = {}; this.clientsCount = 0; opts = opts || {}; this.wsEngine = opts.wsEngine || process.env.EIO_WS_ENGINE || 'uws'; this.pingTimeout = opts.pingTimeout || 60000; this.pingInterval = opts.pingInterval || 25000; this.upgradeTimeout = opts.upgradeTimeout || 10000; this.maxHttpBufferSize = opts.maxHttpBufferSize || 10E7; this.transports = opts.transports || Object.keys(transports); this.allowUpgrades = false !== opts.allowUpgrades; this.allowRequest = opts.allowRequest; this.cookie = false !== opts.cookie ? (opts.cookie || 'io') : false; this.cookiePath = false !== opts.cookiePath ? (opts.cookiePath || '/') : false; this.cookieHttpOnly = false !== opts.cookieHttpOnly; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || true) : false; this.httpCompression = false !== opts.httpCompression ? (opts.httpCompression || {}) : false; this.initialPacket = opts.initialPacket; var self = this; // initialize compression options ['perMessageDeflate', 'httpCompression'].forEach(function (type) { var compression = self[type]; if (true === compression) self[type] = compression = {}; if (compression && null == compression.threshold) { compression.threshold = 1024; } }); this.init(); } /** * Protocol errors mappings. */ Server.errors = { UNKNOWN_TRANSPORT: 0, UNKNOWN_SID: 1, BAD_HANDSHAKE_METHOD: 2, BAD_REQUEST: 3, FORBIDDEN: 4 }; Server.errorMessages = { 0: 'Transport unknown', 1: 'Session ID unknown', 2: 'Bad handshake method', 3: 'Bad request', 4: 'Forbidden' }; /** * Inherits from EventEmitter. */ util.inherits(Server, EventEmitter); /** * Hash of open clients. * * @api public */ Server.prototype.clients; /** * Initialize websocket server * * @api private */ Server.prototype.init = function () { if (!~this.transports.indexOf('websocket')) return; if (this.ws) this.ws.close(); var wsModule; try { wsModule = require(this.wsEngine); } catch (ex) { this.wsEngine = 'ws'; // keep require('ws') as separate expression for packers (browserify, etc) wsModule = require('ws'); } this.ws = new wsModule.Server({ noServer: true, clientTracking: false, perMessageDeflate: this.perMessageDeflate, maxPayload: this.maxHttpBufferSize }); }; /** * Returns a list of available transports for upgrade given a certain transport. * * @return {Array} * @api public */ Server.prototype.upgrades = function (transport) { if (!this.allowUpgrades) return []; return transports[transport].upgradesTo || []; }; /** * Verifies a request. * * @param {http.IncomingMessage} * @return {Boolean} whether the request is valid * @api private */ Server.prototype.verify = function (req, upgrade, fn) { // transport check var transport = req._query.transport; if (!~this.transports.indexOf(transport)) { debug('unknown transport "%s"', transport); return fn(Server.errors.UNKNOWN_TRANSPORT, false); } // sid check var sid = req._query.sid; if (sid) { if (!this.clients.hasOwnProperty(sid)) { return fn(Server.errors.UNKNOWN_SID, false); } if (!upgrade && this.clients[sid].transport.name !== transport) { debug('bad request: unexpected transport without upgrade'); return fn(Server.errors.BAD_REQUEST, false); } } else { // handshake is GET only if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false); if (!this.allowRequest) return fn(null, true); return this.allowRequest(req, fn); } fn(null, true); }; /** * Prepares a request by processing the query string. * * @api private */ Server.prototype.prepare = function (req) { // try to leverage pre-existing `req._query` (e.g: from connect) if (!req._query) { req._query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {}; } }; /** * Closes all clients. * * @api public */ Server.prototype.close = function () { debug('closing all open clients'); for (var i in this.clients) { if (this.clients.hasOwnProperty(i)) { this.clients[i].close(true); } } if (this.ws) { debug('closing webSocketServer'); this.ws.close(); // don't delete this.ws because it can be used again if the http server starts listening again } return this; }; /** * Handles an Engine.IO HTTP request. * * @param {http.IncomingMessage} request * @param {http.ServerResponse|http.OutgoingMessage} response * @api public */ Server.prototype.handleRequest = function (req, res) { debug('handling "%s" http request "%s"', req.method, req.url); this.prepare(req); req.res = res; var self = this; this.verify(req, false, function (err, success) { if (!success) { sendErrorMessage(req, res, err); return; } if (req._query.sid) { debug('setting new request for existing client'); self.clients[req._query.sid].transport.onRequest(req); } else { self.handshake(req._query.transport, req); } }); }; /** * Sends an Engine.IO Error Message * * @param {http.ServerResponse} response * @param {code} error code * @api private */ function sendErrorMessage (req, res, code) { var headers = { 'Content-Type': 'application/json' }; var isForbidden = !Server.errorMessages.hasOwnProperty(code); if (isForbidden) { res.writeHead(403, headers); res.end(JSON.stringify({ code: Server.errors.FORBIDDEN, message: code || Server.errorMessages[Server.errors.FORBIDDEN] })); return; } if (req.headers.origin) { headers['Access-Control-Allow-Credentials'] = 'true'; headers['Access-Control-Allow-Origin'] = req.headers.origin; } else { headers['Access-Control-Allow-Origin'] = '*'; } res.writeHead(400, headers); res.end(JSON.stringify({ code: code, message: Server.errorMessages[code] })); } /** * generate a socket id. * Overwrite this method to generate your custom socket id * * @param {Object} request object * @api public */ Server.prototype.generateId = function (req) { return base64id.generateId(); }; /** * Handshakes a new client. * * @param {String} transport name * @param {Object} request object * @api private */ Server.prototype.handshake = function (transportName, req) { var id = this.generateId(req); debug('handshaking client "%s"', id); try { var transport = new transports[transportName](req); if ('polling' === transportName) { transport.maxHttpBufferSize = this.maxHttpBufferSize; transport.httpCompression = this.httpCompression; } else if ('websocket' === transportName) { transport.perMessageDeflate = this.perMessageDeflate; } if (req._query && req._query.b64) { transport.supportsBinary = false; } else { transport.supportsBinary = true; } } catch (e) { sendErrorMessage(req, req.res, Server.errors.BAD_REQUEST); return; } var socket = new Socket(id, this, transport, req); var self = this; if (false !== this.cookie) { transport.on('headers', function (headers) { headers['Set-Cookie'] = cookieMod.serialize(self.cookie, id, { path: self.cookiePath, httpOnly: self.cookiePath ? self.cookieHttpOnly : false }); }); } transport.onRequest(req); this.clients[id] = socket; this.clientsCount++; socket.once('close', function () { delete self.clients[id]; self.clientsCount--; }); this.emit('connection', socket); }; /** * Handles an Engine.IO HTTP Upgrade. * * @api public */ Server.prototype.handleUpgrade = function (req, socket, upgradeHead) { this.prepare(req); var self = this; this.verify(req, true, function (err, success) { if (!success) { abortConnection(socket, err); return; } var head = new Buffer(upgradeHead.length); upgradeHead.copy(head); upgradeHead = null; // delegate to ws self.ws.handleUpgrade(req, socket, head, function (conn) { self.onWebSocket(req, conn); }); }); }; /** * Called upon a ws.io connection. * * @param {ws.Socket} websocket * @api private */ Server.prototype.onWebSocket = function (req, socket) { socket.on('error', onUpgradeError); if (!transports[req._query.transport].prototype.handlesUpgrades) { debug('transport doesnt handle upgraded requests'); socket.close(); return; } // get client id var id = req._query.sid; // keep a reference to the ws.Socket req.websocket = socket; if (id) { var client = this.clients[id]; if (!client) { debug('upgrade attempt for closed client'); socket.close(); } else if (client.upgrading) { debug('transport has already been trying to upgrade'); socket.close(); } else if (client.upgraded) { debug('transport had already been upgraded'); socket.close(); } else { debug('upgrading existing transport'); // transport error handling takes over socket.removeListener('error', onUpgradeError); var transport = new transports[req._query.transport](req); if (req._query && req._query.b64) { transport.supportsBinary = false; } else { transport.supportsBinary = true; } transport.perMessageDeflate = this.perMessageDeflate; client.maybeUpgrade(transport); } } else { // transport error handling takes over socket.removeListener('error', onUpgradeError); this.handshake(req._query.transport, req); } function onUpgradeError () { debug('websocket error before upgrade'); // socket.close() not needed } }; /** * Captures upgrade requests for a http.Server. * * @param {http.Server} server * @param {Object} options * @api public */ Server.prototype.attach = function (server, options) { var self = this; options = options || {}; var path = (options.path || '/engine.io').replace(/\/$/, ''); var destroyUpgradeTimeout = options.destroyUpgradeTimeout || 1000; // normalize path path += '/'; function check (req) { if ('OPTIONS' === req.method && false === options.handlePreflightRequest) { return false; } return path === req.url.substr(0, path.length); } // cache and clean up listeners var listeners = server.listeners('request').slice(0); server.removeAllListeners('request'); server.on('close', self.close.bind(self)); server.on('listening', self.init.bind(self)); // add request handler server.on('request', function (req, res) { if (check(req)) { debug('intercepting request for path "%s"', path); if ('OPTIONS' === req.method && 'function' === typeof options.handlePreflightRequest) { options.handlePreflightRequest.call(server, req, res); } else { self.handleRequest(req, res); } } else { for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].call(server, req, res); } } }); if (~self.transports.indexOf('websocket')) { server.on('upgrade', function (req, socket, head) { if (check(req)) { self.handleUpgrade(req, socket, head); } else if (false !== options.destroyUpgrade) { // default node behavior is to disconnect when no handlers // but by adding a handler, we prevent that // and if no eio thing handles the upgrade // then the socket needs to die! setTimeout(function () { if (socket.writable && socket.bytesWritten <= 0) { return socket.end(); } }, destroyUpgradeTimeout); } }); } }; /** * Closes the connection * * @param {net.Socket} socket * @param {code} error code * @api private */ function abortConnection (socket, code) { if (socket.writable) { var message = Server.errorMessages.hasOwnProperty(code) ? Server.errorMessages[code] : (code || ''); var length = Buffer.byteLength(message); socket.write( 'HTTP/1.1 400 Bad Request\r\n' + 'Connection: close\r\n' + 'Content-type: text/html\r\n' + 'Content-Length: ' + length + '\r\n' + '\r\n' + message ); } socket.destroy(); }
import os,json,requests,time,random,task1,task12,task13 from bs4 import BeautifulSoup from pprint import pprint def count_movies(moviesLst): dicT={} for dic in moviesLst: for dic0 in dic["cast"]: if dic0["imdb_id"] not in dicT: dicT[dic0["imdb_id"]]={} count=0 for x in moviesLst: for y in x["cast"]: if y["imdb_id"]==dic0["imdb_id"]: count+=1 break dicT[dic0["imdb_id"]]["name"]=dic0["name"] dicT[dic0["imdb_id"]]["movies_did"]=count return dicT moviesLst=task1.top_250movies() cast=task12.movie_Cast(moviesLst) Lst=task13.movie_detailsLst(moviesLst,cast) pprint(count_movies(Lst))
"""This module containes SQLAlchemy models.""" from datetime import datetime from app import db # Association table for many-to-many relationship between orgs and users users = db.Table( # pylint: disable=invalid-name 'users', db.Column('org_id', db.Integer, db.ForeignKey('organization.id'), primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('app_user.id'), primary_key=True)) # Association table for many-to-many relationship between lists and users list_users = db.Table( # pylint: disable=invalid-name 'list_users', db.Column('list_id', db.String(64), db.ForeignKey('email_list.list_id'), primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('app_user.id'), primary_key=True)) class AppUser(db.Model): # pylint: disable=too-few-public-methods """Stores users.""" id = db.Column(db.Integer, primary_key=True) signup_timestamp = db.Column(db.DateTime, default=datetime.utcnow) name = db.Column(db.String(64)) email = db.Column(db.String(64), index=True, unique=True) email_hash = db.Column(db.String(64), index=True, unique=True) approved = db.Column(db.Boolean) def __repr__(self): return '<AppUser {}>'.format(self.id) class ListStats(db.Model): # pylint: disable=too-few-public-methods """Stores stats associated with a MailChimp list.""" id = db.Column(db.Integer, primary_key=True) analysis_timestamp = db.Column(db.DateTime, default=datetime.utcnow) frequency = db.Column(db.Float) subscribers = db.Column(db.Integer) open_rate = db.Column(db.Float) hist_bin_counts = db.Column(db.String(512)) subscribed_pct = db.Column(db.Float) unsubscribed_pct = db.Column(db.Float) cleaned_pct = db.Column(db.Float) pending_pct = db.Column(db.Float) high_open_rt_pct = db.Column(db.Float) cur_yr_inactive_pct = db.Column(db.Float) list_id = db.Column(db.String(64), db.ForeignKey('email_list.list_id', name='fk_list_id')) def __repr__(self): return '<ListStats {}>'.format(self.id) class EmailList(db.Model): # pylint: disable=too-few-public-methods """Stores individual MailChimp lists.""" list_id = db.Column(db.String(64), primary_key=True) list_name = db.Column(db.String(128)) api_key = db.Column(db.String(64)) data_center = db.Column(db.String(64)) store_aggregates = db.Column(db.Boolean) monthly_updates = db.Column(db.Boolean) monthly_update_users = db.relationship( AppUser, secondary=list_users, backref='lists', lazy='subquery') org_id = db.Column(db.Integer, db.ForeignKey('organization.id', name='fk_org_id')) analyses = db.relationship(ListStats, backref='list') def __repr__(self): return '<EmailList {}>'.format(self.list_id) class Organization(db.Model): # pylint: disable=too-few-public-methods """Stores a media or journalism organization.""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), index=True, unique=True) financial_classification = db.Column(db.String(32)) coverage_scope = db.Column(db.String(32)) coverage_focus = db.Column(db.String(64)) platform = db.Column(db.String(64)) employee_range = db.Column(db.String(32)) budget = db.Column(db.String(64)) affiliations = db.Column(db.String(512)) lists = db.relationship(EmailList, backref='org') users = db.relationship(AppUser, secondary=users, backref='orgs') def __repr__(self): return '<Organization {}>'.format(self.id)
import React from "react"; import PropTypes from "prop-types"; import Head from "next/head"; import settings from "../../settings"; const socialTags = ({ type, url, title, description, image, createdAt, updatedAt, }) => { const metaTags = [ { name: "twitter:card", content: "summary_large_image" }, { name: "twitter:site", content: settings && settings.meta && settings.meta.social && settings.meta.social.twitter, }, { name: "twitter:title", content: title }, { name: "twitter:description", content: description }, { name: "twitter:creator", content: settings && settings.meta && settings.meta.social && settings.meta.social.twitter, }, { name: "twitter:image:src", content: image }, { name: "twitter:card", content: "summary_large_image" }, { name: "og:title", content: title }, { name: "og:type", content: type }, { name: "og:url", content: url }, { name: "og:image", content: image }, { name: "og:description", content: description }, { name: "og:site_name", content: settings && settings.meta && settings.meta.title, }, { name: "og:published_time", content: createdAt || new Date().toISOString(), }, { name: "og:modified_time", content: updatedAt || new Date().toISOString(), }, ]; return metaTags; }; const SEO = (props) => { const { title, description, image } = props; return ( <Head> <title>{title} | App</title> <meta name="description" content={description} /> <meta itemprop="name" content={title} /> <meta itemprop="description" content={description} /> <meta itemprop="image" content={image} /> {socialTags(props).map(({ name, content }) => { return <meta key={name} name={name} content={content} />; })} </Head> ); }; SEO.defaultProps = { url: "/", type: "article", title: settings && settings.meta && settings.meta.title, description: settings && settings.meta && settings.meta.description, image: settings && settings.meta && settings.meta.social && settings.meta.social.graphic, }; SEO.propTypes = { url: PropTypes.string, type: PropTypes.string, title: PropTypes.string, description: PropTypes.string, image: PropTypes.string, }; export default SEO;
// // ____ _ __ _ _____ // / ___\ /_\ /\/\ /\ /\ /__\ /_\ \_ \ // \ \ //_\\ / \ / / \ \ / \// //_\\ / /\/ // /\_\ \ / _ \ / /\/\ \ \ \_/ / / _ \ / _ \ /\/ /_ // \____/ \_/ \_/ \/ \/ \___/ \/ \_/ \_/ \_/ \____/ // // Copyright Samurai development team and other contributors // // http://www.samurai-framework.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #import "IDEAAppletConfig.h" #import "IDEAAppletCoreConfig.h" #pragma mark - #undef singleton #define singleton( __class ) \ property (nonatomic, readonly) __class * sharedInstance; \ - (__class *)sharedInstance; \ + (__class *)sharedInstance; #undef def_singleton #define def_singleton( __class ) \ dynamic sharedInstance; \ - (__class *)sharedInstance { \ \ return [__class sharedInstance]; \ } \ + (__class *)sharedInstance { \ \ static dispatch_once_t once; \ static __strong id __singleton__ = nil; \ dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \ return __singleton__; \ } #pragma mark - //@interface NSObject(Singleton) // //+ (id)sharedInstance; //- (id)sharedInstance; // //+ (id)sharedInstanceOrNew; //- (id)sharedInstanceOrNew; // //@end
var searchData= [ ['timecodetominutes_523',['timeCodeToMinutes',['../BrokerCommon_8h.html#a5f7fe934c97e99cd812171e90c7945cd',1,'ace_time::internal']]], ['timeoffset_524',['TimeOffset',['../classace__time_1_1TimeOffset.html#a0fca23cf055036370aadd89ca307aae8',1,'ace_time::TimeOffset::TimeOffset()'],['../classace__time_1_1OffsetDateTime.html#a168e05a532edbaed7afa4e75fbf636d7',1,'ace_time::OffsetDateTime::timeOffset() const'],['../classace__time_1_1OffsetDateTime.html#a298bf16b90a1c657a66d9b5d77b0b1cb',1,'ace_time::OffsetDateTime::timeOffset(TimeOffset timeOffset)'],['../classace__time_1_1ZonedDateTime.html#ade77d29873786f45459a07d2271d8c64',1,'ace_time::ZonedDateTime::timeOffset()']]], ['timeperiod_525',['TimePeriod',['../classace__time_1_1TimePeriod.html#a45fb93e84da2991a366a5ebf31b66dde',1,'ace_time::TimePeriod::TimePeriod(uint8_t hour, uint8_t minute, uint8_t second, int8_t sign=1)'],['../classace__time_1_1TimePeriod.html#a0ee304d6c42e01c56ed14783da5a85af',1,'ace_time::TimePeriod::TimePeriod(int32_t seconds=0)']]], ['timezone_526',['timeZone',['../classace__time_1_1ZonedDateTime.html#a09369bb6bb3ca5c2f10c68c72c5edfd4',1,'ace_time::ZonedDateTime::timeZone() const'],['../classace__time_1_1ZonedDateTime.html#ad1c861034107afc92fb24a320c0696ba',1,'ace_time::ZonedDateTime::timeZone(const TimeZone &amp;timeZone)'],['../classace__time_1_1TimeZone.html#afc1cbc5b5e4cd6f2cff0788a4acb9ed9',1,'ace_time::TimeZone::TimeZone()']]], ['timezonedata_527',['TimeZoneData',['../structace__time_1_1TimeZoneData.html#a795549e3491feb49b15bb4d6039f9ac8',1,'ace_time::TimeZoneData::TimeZoneData(uint32_t zid)'],['../structace__time_1_1TimeZoneData.html#ae24aeb66c44724d8520e8f986644f871',1,'ace_time::TimeZoneData::TimeZoneData(int16_t stdMinutes, int16_t dstMinutes)'],['../structace__time_1_1TimeZoneData.html#a76f99ffc11d0866de37bcc7eb803a975',1,'ace_time::TimeZoneData::TimeZoneData()']]], ['todeltaminutes_528',['toDeltaMinutes',['../ExtendedBrokers_8h.html#ad2a05a157983a0d725bbb4e450b5a1f4',1,'ace_time::extended']]], ['toepochdays_529',['toEpochDays',['../classace__time_1_1LocalDate.html#a2458b6708b65f747a21852505fcbf51c',1,'ace_time::LocalDate::toEpochDays()'],['../classace__time_1_1LocalDateTime.html#a54dacb94b696d4ebdc7e25f3666cb9cb',1,'ace_time::LocalDateTime::toEpochDays()'],['../classace__time_1_1OffsetDateTime.html#a8320d5d690f484b89c69bd907c3fda20',1,'ace_time::OffsetDateTime::toEpochDays()'],['../classace__time_1_1ZonedDateTime.html#a541d3478b947751a548c3315b5e9d33f',1,'ace_time::ZonedDateTime::toEpochDays()']]], ['toepochseconds_530',['toEpochSeconds',['../classace__time_1_1LocalDate.html#af1a1350bc5637a4296729b2bc3f61d49',1,'ace_time::LocalDate::toEpochSeconds()'],['../classace__time_1_1LocalDateTime.html#af174b568718ea7b54528f916806020b8',1,'ace_time::LocalDateTime::toEpochSeconds()'],['../classace__time_1_1OffsetDateTime.html#a6bf75ca2f12bc07db60d00e7e5fc5589',1,'ace_time::OffsetDateTime::toEpochSeconds()'],['../classace__time_1_1ZonedDateTime.html#acfa87cc440b6b3ab00c6aeac190892b3',1,'ace_time::ZonedDateTime::toEpochSeconds()']]], ['tohourminute_531',['toHourMinute',['../classace__time_1_1TimeOffset.html#a20d77892ff9d4a252dcb0cc2e19d3c13',1,'ace_time::TimeOffset']]], ['tominutes_532',['toMinutes',['../classace__time_1_1TimeOffset.html#a08191e46cf33309fc06f4429505fcf4c',1,'ace_time::TimeOffset']]], ['tooffsetminutes_533',['toOffsetMinutes',['../ExtendedBrokers_8h.html#ad0e195ee026f5b86948c1e6ae1f9c130',1,'ace_time::extended']]], ['toseconds_534',['toSeconds',['../classace__time_1_1LocalTime.html#a53f1dd8b1eea2592a760bedcdf6d1442',1,'ace_time::LocalTime::toSeconds()'],['../classace__time_1_1TimeOffset.html#a91835a600c3d1a29a94b3fb38ea32e14',1,'ace_time::TimeOffset::toSeconds()'],['../classace__time_1_1TimePeriod.html#ae94aa6fd79718e72eaa1a3f3c4caed9e',1,'ace_time::TimePeriod::toSeconds()']]], ['tosuffix_535',['toSuffix',['../BrokerCommon_8h.html#ae980919d070889e10164c643f1411c5f',1,'ace_time::internal']]], ['totemperature256_536',['toTemperature256',['../structace__time_1_1hw_1_1HardwareTemperature.html#ade0fda64feee924ee4e0624ec54ddb2f',1,'ace_time::hw::HardwareTemperature']]], ['totimezonedata_537',['toTimeZoneData',['../classace__time_1_1TimeZone.html#af4e12e7f8296fefe6b979fd5b9af5ba7',1,'ace_time::TimeZone']]], ['tounixdays_538',['toUnixDays',['../classace__time_1_1LocalDate.html#a3d0016f49d1d4c9a594762dcdeae6a19',1,'ace_time::LocalDate::toUnixDays()'],['../classace__time_1_1LocalDateTime.html#aff5edbf310e5a21b68edfc0666f88d99',1,'ace_time::LocalDateTime::toUnixDays()'],['../classace__time_1_1OffsetDateTime.html#a2b2b3c883185c6ecbca5203a02fbe436',1,'ace_time::OffsetDateTime::toUnixDays()'],['../classace__time_1_1ZonedDateTime.html#af8821b987370687df8eece04fbd16199',1,'ace_time::ZonedDateTime::toUnixDays()']]], ['tounixseconds_539',['toUnixSeconds',['../classace__time_1_1LocalDate.html#a72dd21859dba6a0563b95673040fe940',1,'ace_time::LocalDate::toUnixSeconds()'],['../classace__time_1_1LocalDateTime.html#aa467da788e335995e84b5e1122845e99',1,'ace_time::LocalDateTime::toUnixSeconds()'],['../classace__time_1_1OffsetDateTime.html#acbbe25fd44a233f95c94ab03bddfb5a6',1,'ace_time::OffsetDateTime::toUnixSeconds()'],['../classace__time_1_1ZonedDateTime.html#ab5032901906035cce6b4fd1d1cfe55ef',1,'ace_time::ZonedDateTime::toUnixSeconds()']]], ['transitionstoragetemplate_540',['TransitionStorageTemplate',['../classace__time_1_1extended_1_1TransitionStorageTemplate.html#a8ffed64413579a5a4f677ff5337176af',1,'ace_time::extended::TransitionStorageTemplate']]] ];
/* Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'flash', 'eo', { access: 'Atingi skriptojn', accessAlways: 'Ĉiam', accessNever: 'Neniam', accessSameDomain: 'Sama domajno', alignAbsBottom: 'Absoluta Malsupro', alignAbsMiddle: 'Absoluta Centro', alignBaseline: 'TekstoMalsupro', alignTextTop: 'TekstoSupro', bgcolor: 'Fona Koloro', chkFull: 'Permesi tutekranon', chkLoop: 'Iteracio', chkMenu: 'Ebligi flaŝmenuon', chkPlay: 'Aŭtomata legado', flashvars: 'Variabloj por Flaŝo', hSpace: 'Horizontala Spaco', properties: 'Flaŝatributoj', propertiesTab: 'Atributoj', quality: 'Kvalito', qualityAutoHigh: 'Aŭtomate alta', qualityAutoLow: 'Aŭtomate malalta', qualityBest: 'Plej bona', qualityHigh: 'Alta', qualityLow: 'Malalta', qualityMedium: 'Meza', scale: 'Skalo', scaleAll: 'Montri ĉion', scaleFit: 'Origina grando', scaleNoBorder: 'Neniu bordero', title: 'Flaŝatributoj', vSpace: 'Vertikala Spaco', validateHSpace: 'Horizontala Spaco devas esti nombro.', validateSrc: 'Bonvolu entajpi la retadreson (URL)', validateVSpace: 'Vertikala Spaco devas esti nombro.', windowMode: 'Fenestra reĝimo', windowModeOpaque: 'Opaka', windowModeTransparent: 'Travidebla', windowModeWindow: 'Fenestro' } );
var columns = [ {title: "QVC", dataKey: "QVC"}, {title: "TP", dataKey: "TP"}, {title: "MP", dataKey: "MP"}, {title: "TVC", dataKey: "TVC"}, {title: "TFC", dataKey: "TFC"}, {title: "TC", dataKey: "TC"}, {title: "AVC", dataKey: "AVC"}, {title: "AFC", dataKey: "AFC"}, {title: "ATC", dataKey: "ATC"}, {title: "MC", dataKey: "MC"}, {title: "TR", dataKey: "TR"}, {title: "MR", dataKey: "MR"}, {title: "Profit", dataKey: "Profit"} ]; var verses = []; console.log(QVC); for(let i = 0; i < rows; i++){ verses.push({ "QVC": QVC[i].toFixed(2), "TP": TP[i].toFixed(2), "MP": MP[i].toFixed(2), "TVC": TVC[i].toFixed(2), "TFC": TFC[i].toFixed(2), "TC": TC[i].toFixed(2), "AVC": AVC[i].toFixed(2), "AFC": AFC[i].toFixed(2), "ATC": ATC[i].toFixed(2), "MC": MC[i].toFixed(2), "TR": TR[i].toFixed(2), "MR": MR[i].toFixed(2), "Profit": Profit[i].toFixed(2) }) } console.log(verses); // Only pt supported (not mm or in) var doc = new jsPDF('p', 'pt'); doc.autoTable(columns, verses, { styles: {fillColor: [100, 255, 255], textColor:0}, columnStyles: { id: {fillColor: 255} }, margin: {top: 60}, addPageContent: function(data) { doc.text("Header", 40, 30); } }); doc.save('table.pdf');
module.exports = { tabWidth: 2,// tab缩进大小,默认为2 useTabs: false,// 使用tab缩进,默认false semi: true,// 使用分号, 默认true singleQuote: true, // 使用单引号, 默认false(在jsx中配置无效, 默认都是双引号) trailingComma: 'all', // 行尾逗号,默认none,可选 none|es5|all // es5 包括es5中的数组、对象 // all 包括函数对象等所有可选 bracketSpacing: true, // 对象中的空格 默认true // true: { foo: bar } // false: {foo: bar} jsxBracketSameLine: false, // JSX标签闭合位置 默认false // false: <div // className="" // style={{}} // > // true: <div // className="" // style={{}} > arrowParens: 'avoid', // 箭头函数参数括号 默认avoid 可选 avoid| always // avoid 能省略括号的时候就省略 例如x => x // always 总是有括号 };
from pycoin.networks.bitcoinish import create_bitcoinish_network network = create_bitcoinish_network( symbol="BTDX", network_name="Bitcloud", subnet_name="mainnet", wif_prefix_hex="99", sec_prefix="BTDXSEC:", address_prefix_hex="19", pay_to_script_prefix_hex="05", bip32_prv_prefix_hex="0488ADE4", bip32_pub_prefix_hex="0488B21E", magic_header_hex="E4E8BDFD", default_port=8329, dns_bootstrap=[ "seed.bitcloud.network" ])
# -*- coding=utf-8 -*- from __future__ import absolute_import, print_function import itertools import os from fnmatch import fnmatch import attr import io import re import six import vistir from .environment import PYENV_ROOT, ASDF_DATA_DIR from .exceptions import InvalidPythonVersion six.add_move(six.MovedAttribute("Iterable", "collections", "collections.abc")) from six.moves import Iterable try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache version_re = re.compile(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.?(?P<patch>(?<=\.)[0-9]+)") PYTHON_IMPLEMENTATIONS = ( "python", "ironpython", "jython", "pypy", "anaconda", "miniconda", "stackless", "activepython", "micropython" ) RULES_BASE = ["*{0}", "*{0}?", "*{0}?.?", "*{0}?.?m"] RULES = [rule.format(impl) for impl in PYTHON_IMPLEMENTATIONS for rule in RULES_BASE] KNOWN_EXTS = {"exe", "py", "fish", "sh", ""} KNOWN_EXTS = KNOWN_EXTS | set( filter(None, os.environ.get("PATHEXT", "").split(os.pathsep)) ) MATCH_RULES = [] for rule in RULES: MATCH_RULES.extend( [ "{0}.{1}".format(rule, ext) if ext else "{0}".format(rule) for ext in KNOWN_EXTS ] ) @lru_cache(maxsize=1024) def get_python_version(path): """Get python version string using subprocess from a given path.""" version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"] try: c = vistir.misc.run(version_cmd, block=True, nospin=True, return_object=True, combine_stderr=False, write_to_stdout=False) except OSError: raise InvalidPythonVersion("%s is not a valid python path" % path) if not c.out: raise InvalidPythonVersion("%s is not a valid python path" % path) return c.out.strip() @lru_cache(maxsize=1024) def parse_python_version(version_str): m = version_re.match(version_str) if not m: raise InvalidPythonVersion("%s is not a python version" % version_str) return m.groupdict() def optional_instance_of(cls): return attr.validators.optional(attr.validators.instance_of(cls)) def path_is_executable(path): return os.access(str(path), os.X_OK) @lru_cache(maxsize=1024) def path_is_known_executable(path): return ( path_is_executable(path) or os.access(str(path), os.R_OK) and path.suffix in KNOWN_EXTS ) @lru_cache(maxsize=1024) def looks_like_python(name): if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS): return False return any(fnmatch(name, rule) for rule in MATCH_RULES) @lru_cache(maxsize=1024) def path_is_python(path): return path_is_executable(path) and looks_like_python(path.name) @lru_cache(maxsize=1024) def ensure_path(path): """ Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path` """ if isinstance(path, vistir.compat.Path): return path path = vistir.compat.Path(os.path.expandvars(path)) return path.absolute() def _filter_none(k, v): if v: return True return False # TODO: Reimplement in vistir def normalize_path(path): return os.path.normpath(os.path.normcase( os.path.abspath(os.path.expandvars(os.path.expanduser(str(path)))) )) @lru_cache(maxsize=1024) def filter_pythons(path): """Return all valid pythons in a given path""" if not isinstance(path, vistir.compat.Path): path = vistir.compat.Path(str(path)) if not path.is_dir(): return path if path_is_python(path) else None return filter(path_is_python, path.iterdir()) # TODO: Port to vistir def unnest(item): if isinstance(item, Iterable) and not isinstance(item, six.string_types): item, target = itertools.tee(item, 2) else: target = item for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): el, el_copy = itertools.tee(el, 2) for sub in unnest(el_copy): yield sub else: yield el def parse_pyenv_version_order(filename="version"): version_order_file = normalize_path(os.path.join(PYENV_ROOT, filename)) if os.path.exists(version_order_file) and os.path.isfile(version_order_file): with io.open(version_order_file, encoding="utf-8") as fh: contents = fh.read() version_order = [v for v in contents.splitlines()] return version_order return [] def parse_asdf_version_order(filename=".tool-versions"): version_order_file = normalize_path(os.path.join("~", filename)) if os.path.exists(version_order_file) and os.path.isfile(version_order_file): with io.open(version_order_file, encoding="utf-8") as fh: contents = fh.read() python_section = next(iter( line for line in contents.splitlines() if line.startswith("python") ), None) if python_section: python_key, _, versions = python_section.partition(" ") if versions: return versions.split() return [] # TODO: Reimplement in vistir def is_in_path(path, parent): return normalize_path(str(path)).startswith(normalize_path(str(parent)))
/** * @function create * @return {RFuncClint} - A client instance */ 'use strict' const RFuncClint = require('./rfunc_client') /** @lends create */ function create (...args) { return new RFuncClint(...args) } module.exports = create
#!/usr/bin/env python3 ############################################################################### # # # RMG - Reaction Mechanism Generator # # # # Copyright (c) 2002-2019 Prof. William H. Green (whgreen@mit.edu), # # Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) # # # # Permission is hereby granted, free of charge, to any person obtaining a # # copy of this software and associated documentation files (the 'Software'), # # to deal in the Software without restriction, including without limitation # # the rights to use, copy, modify, merge, publish, distribute, sublicense, # # and/or sell copies of the Software, and to permit persons to whom the # # Software is furnished to do so, subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included in # # all copies or substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # # DEALINGS IN THE SOFTWARE. # # # ############################################################################### """ This module provides the :class:`StatMechJob` class, which represents a statistical mechanics job used to compute and save the statistical mechanics information for a single species or transition state. """ import logging import math import os.path import matplotlib.pyplot as plt import numpy as np import rmgpy.constants as constants from rmgpy.exceptions import InputError, ElementError, StatmechError from rmgpy.molecule.molecule import Molecule from rmgpy.species import TransitionState, Species from rmgpy.statmech.ndTorsions import HinderedRotor2D, HinderedRotorClassicalND from rmgpy.statmech.rotation import LinearRotor, NonlinearRotor from rmgpy.statmech.torsion import HinderedRotor, FreeRotor from rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.vibration import HarmonicOscillator from rmgpy.quantity import Quantity from arkane.common import ArkaneSpecies, symbol_by_number, get_principal_moments_of_inertia from arkane.encorr.corr import get_atom_correction, get_bac from arkane.ess import GaussianLog, Log, MolproLog, OrcaLog, QChemLog, TeraChemLog from arkane.output import prettify from arkane.util import determine_qm_software ################################################################################ class ScanLog(object): """ Represent a text file containing a table of angles and corresponding scan energies. """ angleFactors = { 'radians': 1.0, 'rad': 1.0, 'degrees': 180.0 / math.pi, 'deg': 180.0 / math.pi, } energyFactors = { 'J/mol': 1.0, 'kJ/mol': 1.0 / 1000., 'cal/mol': 1.0 / 4.184, 'kcal/mol': 1.0 / 4184., 'cm^-1': 1.0 / (constants.h * constants.c * 100. * constants.Na), 'hartree': 1.0 / (constants.E_h * constants.Na), } def __init__(self, path): self.path = path def load(self): """ Load the scan energies from the file. Returns arrays containing the angles (in radians) and energies (in J/mol). """ angles, energies = [], [] angle_units, energy_units, angle_factor, energy_factor = None, None, None, None with open(self.path, 'r') as stream: for line in stream: line = line.strip() if line == '': continue tokens = line.split() if angle_units is None or energy_units is None: angle_units = tokens[1][1:-1] energy_units = tokens[3][1:-1] try: angle_factor = ScanLog.angleFactors[angle_units] except KeyError: raise ValueError('Invalid angle units {0!r}.'.format(angle_units)) try: energy_factor = ScanLog.energyFactors[energy_units] except KeyError: raise ValueError('Invalid energy units {0!r}.'.format(energy_units)) else: angles.append(float(tokens[0]) / angle_factor) energies.append(float(tokens[1]) / energy_factor) angles = np.array(angles) energies = np.array(energies) energies -= energies[0] return angles, energies def save(self, angles, energies, angle_units='radians', energy_units='kJ/mol'): """ Save the scan energies to the file using the given `angles` in radians and corresponding energies `energies` in J/mol. The file is created to use the given `angle_units` for angles and `energy_units` for energies. """ assert len(angles) == len(energies) try: angle_factor = ScanLog.angleFactors[angle_units] except KeyError: raise ValueError('Invalid angle units {0!r}.'.format(angle_units)) try: energy_factor = ScanLog.energyFactors[energy_units] except KeyError: raise ValueError('Invalid energy units {0!r}.'.format(energy_units)) with open(self.path, 'w') as stream: stream.write('{0:>24} {1:>24}\n'.format( 'Angle ({0})'.format(angle_units), 'Energy ({0})'.format(energy_units), )) for angle, energy in zip(angles, energies): stream.write('{0:23.10f} {1:23.10f}\n'.format(angle * angle_factor, energy * energy_factor)) ################################################################################ def hinderedRotor(scanLog, pivots, top, symmetry=None, fit='best'): """Read a hindered rotor directive, and return the attributes in a list""" return [scanLog, pivots, top, symmetry, fit] def freeRotor(pivots, top, symmetry): """Read a free rotor directive, and return the attributes in a list""" return [pivots, top, symmetry] def hinderedRotor2D(scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry='none'): """Read a two dimensional hindered rotor directive, and return the attributes in a list""" return [scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry] def hinderedRotorClassicalND(calcPath, pivots, tops, sigmas, semiclassical): """Read an N dimensional hindered rotor directive, and return the attributes in a list""" return [calcPath, pivots, tops, sigmas, semiclassical] class StatMechJob(object): """ A representation of a Arkane statistical mechanics job. This job is used to compute and save the statistical mechanics information for a single species or transition state. """ def __init__(self, species, path): self.species = species self.path = path self.modelChemistry = '' self.frequencyScaleFactor = 1.0 self.includeHinderedRotors = True self.applyAtomEnergyCorrections = True self.applyBondEnergyCorrections = True self.bondEnergyCorrectionType = 'p' self.atomEnergies = None self.bonds = None self.arkane_species = ArkaneSpecies(species=species) self.hindered_rotor_plots = [] def execute(self, output_directory=None, plot=False, pdep=False): """ Execute the statmech job, saving the results within the `output_directory`. If `plot` is True, then plots of the hindered rotor fits will be saved. """ self.load(pdep, plot) if output_directory is not None: try: self.write_output(output_directory) except Exception as e: logging.warning("Could not write statmech output file due to error: " "{0} in species {1}".format(e, self.species.label)) if plot: hr_dir = os.path.join(output_directory, 'plots') if not os.path.exists(hr_dir): os.mkdir(hr_dir) try: self.save_hindered_rotor_figures(hr_dir) except Exception as e: logging.warning("Could not save hindered rotor scans due to error: " "{0} in species {1}".format(e, self.species.label)) logging.debug('Finished statmech job for species {0}.'.format(self.species)) logging.debug(repr(self.species)) def load(self, pdep=False, plot=False): """ Load the statistical mechanics parameters for each conformer from the associated files on disk. Creates :class:`Conformer` objects for each conformer and appends them to the list of conformers on the species object. """ path = self.path is_ts = isinstance(self.species, TransitionState) file_extension = os.path.splitext(path)[1] if file_extension in ['.yml', '.yaml']: self.arkane_species.load_yaml(path=path, label=self.species.label, pdep=pdep) self.species.conformer = self.arkane_species.conformer if is_ts: self.species.frequency = self.arkane_species.imaginary_frequency else: self.species.transport_data = self.arkane_species.transport_data self.species.energy_transfer_model = self.arkane_species.energy_transfer_model if self.arkane_species.adjacency_list is not None: self.species.molecule = [Molecule().from_adjacency_list(adjlist=self.arkane_species.adjacency_list)] elif self.arkane_species.inchi is not None: self.species.molecule = [Molecule().from_inchi(inchistr=self.arkane_species.inchi)] elif self.arkane_species.smiles is not None: self.species.molecule = [Molecule().from_smiles(smilesstr=self.arkane_species.smiles)] return logging.info('Loading statistical mechanics parameters for {0}...'.format(self.species.label)) global_context = { '__builtins__': None, } local_context = { '__builtins__': None, 'True': True, 'False': False, 'HinderedRotor': hinderedRotor, 'FreeRotor': freeRotor, 'HinderedRotor2D': hinderedRotor2D, 'HinderedRotorClassicalND': hinderedRotorClassicalND, # File formats 'GaussianLog': GaussianLog, 'MolproLog': MolproLog, 'OrcaLog': OrcaLog, 'QChemLog': QChemLog, 'TeraChemLog': TeraChemLog, 'ScanLog': ScanLog, 'Log': Log } directory = os.path.abspath(os.path.dirname(path)) with open(path, 'r') as f: try: exec(f.read(), global_context, local_context) except (NameError, TypeError, SyntaxError): logging.error('The species file {0} was invalid:'.format(path)) raise if self.bonds is None: try: self.bonds = local_context['bonds'] except KeyError: self.bonds = {} try: linear = local_context['linear'] except KeyError: linear = None try: external_symmetry = local_context['externalSymmetry'] except KeyError: external_symmetry = None try: spin_multiplicity = local_context['spin_multiplicity'] except KeyError: spin_multiplicity = 0 try: optical_isomers = local_context['opticalIsomers'] except KeyError: logging.debug('No opticalIsomers provided, estimating them from the quantum file.') optical_isomers = None try: energy = local_context['energy'] except KeyError: raise InputError('Required attribute "energy" not found in species file {0!r}.'.format(path)) if isinstance(energy, dict): energy = {k.lower(): v for k, v in energy.items()} # Make model chemistries lower-case try: energy = energy[self.modelChemistry] except KeyError: raise InputError('Model chemistry {0!r} not found in from dictionary of energy values in species file ' '{1!r}.'.format(self.modelChemistry, path)) if isinstance(energy, Log) and not os.path.isfile(energy.path): modified_energy_path = os.path.join(directory, energy.path) if not os.path.isfile(modified_energy_path): raise InputError('Could not find single point energy file for species {0} ' 'in the specified path {1}'.format(self.species.label, energy.path)) else: energy.path = modified_energy_path e0, e_electronic = None, None # E0 = e_electronic + ZPE energy_log = None if isinstance(energy, Log) and type(energy).__name__ == 'Log': energy_log = determine_qm_software(energy.path) elif isinstance(energy, Log) and type(energy).__name__ != 'Log': energy_log = energy elif isinstance(energy, float): e_electronic = energy elif isinstance(energy, tuple) and len(energy) == 2: # this is likely meant to be a quantity object with ZPE already accounted for energy = Quantity(energy) e0 = energy.value_si # in J/mol elif isinstance(energy, tuple) and len(energy) == 3: if energy[2].lower() == 'e_electronic': energy = Quantity(energy[:2]) e_electronic = energy.value_si / constants.E_h / constants.Na # convert J/mol to Hartree elif energy[2].lower() in ['e0']: energy = Quantity(energy[:2]) e0 = energy.value_si # in J/mol else: raise InputError('The third argument for E0 energy value should be e_elect (for energy w/o ZPE) ' 'or E0 (including the ZPE). Got: {0}'.format(energy[2])) try: statmech_log = local_context['frequencies'] except KeyError: raise InputError('Required attribute "frequencies" not found in species file {0!r}.'.format(path)) if not os.path.isfile(statmech_log.path): modified_statmech_path = os.path.join(directory, statmech_log.path) if not os.path.isfile(modified_statmech_path): raise InputError('Could not find Arkane statmech file for species {0} ' 'in the specified path {1}'.format(self.species.label, statmech_log.path)) else: statmech_log.path = modified_statmech_path if isinstance(statmech_log, Log) and type(statmech_log).__name__ == 'Log': statmech_log = determine_qm_software(statmech_log.path) try: geom_log = local_context['geometry'] if not os.path.isfile(geom_log.path): modified_geom_path = os.path.join(directory, geom_log.path) if not os.path.isfile(modified_geom_path): raise InputError('Could not find Arkane statmech file for species {0} ' 'in the specified path {1}'.format(self.species.label, geom_log.path)) else: geom_log.path = modified_geom_path if isinstance(geom_log, Log) and type(geom_log).__name__ == 'Log': geom_log = determine_qm_software(geom_log.path) except KeyError: geom_log = statmech_log logging.debug("Reading geometry from the specified frequencies file.") if 'frequencyScaleFactor' in local_context: logging.warning('Ignoring frequency scale factor in species file {0!r}.'.format(path)) rotors = [] if self.includeHinderedRotors: self.raw_hindered_rotor_data = [] try: rotors = local_context['rotors'] except KeyError: pass # If hindered/free rotors are included in Statmech job, ensure that the same (freq) log file is used for # both the species's optimized geometry and Hessian. This approach guarantees that the geometry and Hessian # will be defined in the same Cartesian coordinate system ("Input Orientation", as opposed to # "Standard Orientation", or something else). Otherwise, if the geometry and Hessian are read from different # log files, it is very easy for them to be defined in different coordinate systems, unless the user is very # careful. The current implementation only performs this check for Gaussian logs. If QChem logs are used, only # a warning is output reminding the user to ensure the geometry and Hessian are defined in consistent # coordinates. if len(rotors) > 0: if isinstance(statmech_log, GaussianLog): if statmech_log.path != geom_log.path: raise InputError('For {0!r}, the geometry log, {1!r}, and frequency log, {2!r}, are not the same. ' 'In order to ensure the geometry and Hessian of {0!r} are defined in consistent ' 'coordinate systems for hindered/free rotor projection, either use the frequency ' 'log for both geometry and frequency, or remove rotors.'.format( self.species.label, geom_log.path, statmech_log.path)) elif isinstance(statmech_log, QChemLog): logging.warning('QChem log will be used for Hessian of {0!r}. Please verify that the geometry ' 'and Hessian of {0!r} are defined in the same coordinate system'.format( self.species.label)) logging.debug(' Reading molecular degrees of freedom...') conformer, unscaled_frequencies = statmech_log.load_conformer(symmetry=external_symmetry, spin_multiplicity=spin_multiplicity, optical_isomers=optical_isomers, label=self.species.label) for mode in conformer.modes: if isinstance(mode, (Translation, IdealGasTranslation)): break else: # Sometimes the translational mode is not appended to modes for monoatomic species conformer.modes.append(IdealGasTranslation(mass=self.species.molecular_weight)) if conformer.spin_multiplicity == 0: raise ValueError("Could not read spin multiplicity from log file {0},\n" "please specify the multiplicity in the input file.".format(self.path)) logging.debug(' Reading optimized geometry...') coordinates, number, mass = geom_log.load_geometry() if self.species.conformer is not None and len(self.species.conformer.modes): # check that conformer has an IdealGasTranslation mode, append one if it doesn't for mode in self.species.conformer.modes: if isinstance(mode, IdealGasTranslation): break else: self.species.conformer.modes.append(IdealGasTranslation(mass=(mass, "amu"))) # check that conformer has a LinearRotor or a NonlinearRotor mode, append one if it doesn't for mode in self.species.conformer.modes: if isinstance(mode, (LinearRotor, NonlinearRotor)): break else: # get the moments of inertia and the external symmetry moments_of_inertia = get_principal_moments_of_inertia(coords=self.species.conformer.coordinates, numbers=self.species.conformer.number) symmetry = geom_log.get_symmetry_properties()[1] if any([moment_of_inertia == 0.0 for moment_of_inertia in moments_of_inertia]): # this is a linear rotor moments_of_inertia = [moment_of_inertia for moment_of_inertia in moments_of_inertia if moment_of_inertia != 0.0] if abs(moments_of_inertia[0] - moments_of_inertia[1]) > 0.01: raise StatmechError(f'Expected two identical moments of inertia for a linear rigis rotor, ' f'but got {moments_of_inertia}') self.species.conformer.modes.append(LinearRotor(inertia=(moments_of_inertia[0], "amu*angstrom^2"), symmetry=symmetry)) else: # this is a non-linear rotor self.species.conformer.modes.append(NonlinearRotor(inertia=(moments_of_inertia, "amu*angstrom^2"), symmetry=symmetry)) # Infer atoms from geometry atoms = {} for atom_num in number: try: symbol = symbol_by_number[atom_num] except KeyError: raise ElementError('Could not recognize element number {0}.'.format(atom_num)) atoms[symbol] = atoms.get(symbol, 0) + 1 # Save atoms for use in writing thermo output if isinstance(self.species, Species): self.species.props['element_counts'] = atoms conformer.coordinates = (coordinates, "angstroms") conformer.number = number conformer.mass = (mass, "amu") # The 1.014 factor represents the relationship between the harmonic frequencies scaling factor # and the zero point energy scaling factor, see https://pubs.acs.org/doi/10.1021/ct100326h Section 3.1.3. zpe_scale_factor = self.frequencyScaleFactor / 1.014 logging.debug(' Reading energy...') if e0 is None: if e_electronic is None: # The energy read from the log file is without the ZPE e_electronic = energy_log.load_energy(zpe_scale_factor) # in J/mol else: e_electronic *= constants.E_h * constants.Na # convert Hartree/particle into J/mol if self.applyAtomEnergyCorrections: atom_corrections = get_atom_correction(self.modelChemistry, atoms, self.atomEnergies) else: atom_corrections = 0 logging.warning('Atom corrections are not being used. Do not trust energies and thermo.') if self.applyBondEnergyCorrections: if not self.bonds and hasattr(self.species, 'molecule') and self.species.molecule: self.bonds = self.species.molecule[0].enumerate_bonds() bond_corrections = get_bac(self.modelChemistry, self.bonds, coordinates, number, bac_type=self.bondEnergyCorrectionType, multiplicity=conformer.spin_multiplicity) else: bond_corrections = 0 e_electronic_with_corrections = e_electronic + atom_corrections + bond_corrections # Get ZPE only for polyatomic species (monoatomic species don't have frequencies, so ZPE = 0) zpe = statmech_log.load_zero_point_energy() * zpe_scale_factor if len(number) > 1 else 0 logging.debug('Scaled zero point energy (ZPE) is {0} J/mol'.format(zpe)) e0 = e_electronic_with_corrections + zpe logging.debug(' Harmonic frequencies scaling factor used = {0:g}'.format(self.frequencyScaleFactor)) logging.debug(' Zero point energy scaling factor used = {0:g}'.format(zpe_scale_factor)) logging.debug(' Scaled ZPE (0 K) = {0:g} kcal/mol'.format(zpe / 4184.)) logging.debug(' E0 (0 K) = {0:g} kcal/mol'.format(e0 / 4184.)) conformer.E0 = (e0 * 0.001, "kJ/mol") # If loading a transition state, also read the imaginary frequency if is_ts: neg_freq = statmech_log.load_negative_frequency() self.species.frequency = (neg_freq * self.frequencyScaleFactor, "cm^-1") # Read and fit the 1D hindered rotors if applicable # If rotors are found, the vibrational frequencies are also # recomputed with the torsional modes removed hessian = statmech_log.load_force_constant_matrix() if hessian is not None and len(mass) > 1 and len(rotors) > 0: logging.debug(' Fitting {0} hindered rotors...'.format(len(rotors))) rotor_count = 0 for j, q in enumerate(rotors): symmetry = None if len(q) == 3: # No potential scan is given, this is a free rotor pivots, top, symmetry = q inertia = conformer.get_internal_reduced_moment_of_inertia(pivots, top) * constants.Na * 1e23 rotor = FreeRotor(inertia=(inertia, "amu*angstrom^2"), symmetry=symmetry) conformer.modes.append(rotor) rotor_count += 1 elif len(q) == 8: scan_dir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry = q logging.info("Calculating energy levels for 2D-HR, may take a while...") rotor = HinderedRotor2D(name='r' + str(j), torsigma1=symmetry1, torsigma2=symmetry2, symmetry=symmetry, calc_path=os.path.join(directory, scan_dir), pivots1=pivots1, pivots2=pivots2, top1=top1, top2=top2) rotor.run() conformer.modes.append(rotor) rotor_count += 2 elif len(q) == 5 and isinstance(q[1][0], list): scan_dir, pivots, tops, sigmas, semiclassical = q rotor = HinderedRotorClassicalND(pivots, tops, sigmas, calc_path=os.path.join(directory, scan_dir), conformer=conformer, F=hessian, semiclassical=semiclassical, is_linear=linear, is_ts=is_ts) rotor.run() conformer.modes.append(rotor) rotor_count += len(pivots) elif len(q) in [4, 5]: # This is a hindered rotor if len(q) == 5: scan_log, pivots, top, symmetry, fit = q elif len(q) == 4: # the symmetry number will be derived from the scan scan_log, pivots, top, fit = q # Load the hindered rotor scan energies if not os.path.isfile(scan_log.path): modified_scan_path = os.path.join(directory, scan_log.path) if not os.path.isfile(modified_scan_path): raise InputError('Could not find scan energy file for species {0} ' 'in the specified path {1}'.format(self.species.label, scan_log.path)) else: scan_log.path = modified_scan_path if isinstance(scan_log, Log) and type(scan_log).__name__ == 'Log': scan_log = determine_qm_software(scan_log.path) if isinstance(scan_log, (GaussianLog, QChemLog)): v_list, angle = scan_log.load_scan_energies() try: pivot_atoms = scan_log.load_scan_pivot_atoms() except Exception as e: logging.warning("Unable to find pivot atoms in scan due to error: {}".format(e)) pivot_atoms = 'N/A' try: frozen_atoms = scan_log.load_scan_frozen_atoms() except Exception as e: logging.warning("Unable to find pivot atoms in scan due to error: {}".format(e)) frozen_atoms = 'N/A' elif isinstance(scan_log, ScanLog): angle, v_list = scan_log.load() # no way to find pivot atoms or frozen atoms from ScanLog pivot_atoms = 'N/A' frozen_atoms = 'N/A' else: raise InputError('Invalid log file type {0} for scan log.'.format(scan_log.__class__)) if symmetry is None: symmetry = determine_rotor_symmetry(v_list, self.species.label, pivots) self.raw_hindered_rotor_data.append((self.species.label, rotor_count, symmetry, angle, v_list, pivot_atoms, frozen_atoms)) inertia = conformer.get_internal_reduced_moment_of_inertia(pivots, top) * constants.Na * 1e23 cosine_rotor = HinderedRotor(inertia=(inertia, "amu*angstrom^2"), symmetry=symmetry) cosine_rotor.fit_cosine_potential_to_data(angle, v_list) fourier_rotor = HinderedRotor(inertia=(inertia, "amu*angstrom^2"), symmetry=symmetry) fourier_rotor.fit_fourier_potential_to_data(angle, v_list) Vlist_cosine = np.zeros_like(angle) Vlist_fourier = np.zeros_like(angle) for i in range(angle.shape[0]): Vlist_cosine[i] = cosine_rotor.get_potential(angle[i]) Vlist_fourier[i] = fourier_rotor.get_potential(angle[i]) if fit == 'cosine': rotor = cosine_rotor rotor_count += 1 conformer.modes.append(rotor) elif fit == 'fourier': rotor = fourier_rotor rotor_count += 1 conformer.modes.append(rotor) elif fit == 'best': rms_cosine = np.sqrt(np.sum((Vlist_cosine - v_list) * (Vlist_cosine - v_list)) / (len(v_list) - 1)) / 4184. rms_fourier = np.sqrt(np.sum((Vlist_fourier - v_list) * (Vlist_fourier - v_list)) / (len(v_list) - 1)) / 4184. # Keep the rotor with the most accurate potential rotor = cosine_rotor if rms_cosine < rms_fourier else fourier_rotor # However, keep the cosine rotor if it is accurate enough, the # fourier rotor is not significantly more accurate, and the cosine # rotor has the correct symmetry if rms_cosine < 0.05 and rms_cosine / rms_fourier < 2.0 and rms_cosine / rms_fourier < 4.0 \ and symmetry == cosine_rotor.symmetry: rotor = cosine_rotor conformer.modes.append(rotor) if plot: try: self.create_hindered_rotor_figure(angle, v_list, cosine_rotor, fourier_rotor, rotor, rotor_count) except Exception as e: logging.warning("Could not plot hindered rotor graph due to error: {0}".format(e)) rotor_count += 1 logging.debug(' Determining frequencies from reduced force constant matrix...') frequencies = np.array(project_rotors(conformer, hessian, rotors, linear, is_ts, label=self.species.label)) elif len(conformer.modes) > 2: if len(rotors) > 0: logging.warning('Force Constant Matrix Missing Ignoring rotors, if running Gaussian if not already ' 'present you need to add the keyword iop(7/33=1) in your Gaussian frequency job for ' 'Gaussian to generate the force constant matrix, if running Molpro include keyword ' 'print, hessian') frequencies = conformer.modes[2].frequencies.value_si rotors = np.array([]) else: if len(rotors) > 0: logging.warning('Force Constant Matrix Missing Ignoring rotors, if running Gaussian if not already ' 'present you need to add the keyword iop(7/33=1) in your Gaussian frequency job for ' 'Gaussian to generate the force constant matrix, if running Molpro include keyword' 'print, hessian') frequencies = np.array([]) rotors = np.array([]) for mode in conformer.modes: if isinstance(mode, HarmonicOscillator): mode.frequencies = (frequencies * self.frequencyScaleFactor, "cm^-1") # save supporting information for calculation self.supporting_info = [self.species.label] optical_isomers_read, symmetry_read, point_group_read = statmech_log.get_symmetry_properties() self.supporting_info.append(external_symmetry if external_symmetry else symmetry_read) self.supporting_info.append(optical_isomers if optical_isomers else optical_isomers_read) self.supporting_info.append(point_group_read) for mode in conformer.modes: if isinstance(mode, (LinearRotor, NonlinearRotor)): self.supporting_info.append(mode) break else: self.supporting_info.append(None) if unscaled_frequencies: self.supporting_info.append(unscaled_frequencies) else: self.supporting_info.append(None) if is_ts: self.supporting_info.append(neg_freq) else: self.supporting_info.append(None) self.supporting_info.append(e_electronic) self.supporting_info.append(e_electronic + zpe) self.supporting_info.append(e0) self.supporting_info.append(list([symbol_by_number[x] for x in number])) # atom symbols self.supporting_info.append(coordinates) try: t1d = energy_log.get_T1_diagnostic() except (NotImplementedError, AttributeError): t1d = None self.supporting_info.append(t1d) try: d1d = energy_log.get_D1_diagnostic() except (NotImplementedError, AttributeError): d1d = None self.supporting_info.append(d1d) # save conformer self.species.conformer = conformer def write_output(self, output_directory): """ Save the results of the statmech job to the `output.py` file located in `output_directory`. """ output_file = os.path.join(output_directory, 'output.py') logging.info('Saving statistical mechanics parameters for {0}...'.format(self.species.label)) f = open(output_file, 'a') conformer = self.species.conformer coordinates = conformer.coordinates.value_si * 1e10 number = conformer.number.value_si f.write('# Coordinates for {0} in Input Orientation (angstroms):\n'.format(self.species.label)) for i in range(coordinates.shape[0]): x = coordinates[i, 0] y = coordinates[i, 1] z = coordinates[i, 2] f.write('# {0} {1:9.4f} {2:9.4f} {3:9.4f}\n'.format(symbol_by_number[number[i]], x, y, z)) result = 'conformer(label={0!r}, E0={1!r}, modes={2!r}, spin_multiplicity={3:d}, optical_isomers={4:d}'.format( self.species.label, conformer.E0, conformer.modes, conformer.spin_multiplicity, conformer.optical_isomers, ) try: result += ', frequency={0!r}'.format(self.species.frequency) except AttributeError: pass result += ')' f.write('{0}\n\n'.format(prettify(result))) f.close() def create_hindered_rotor_figure(self, angle, v_list, cosine_rotor, fourier_rotor, rotor, rotor_index): """ Plot the potential for the rotor, along with its cosine and Fourier series potential fits, and save it in the `hindered_rotor_plots` attribute. """ phi = np.arange(0, 6.3, 0.02, np.float64) Vlist_cosine = np.zeros_like(phi) Vlist_fourier = np.zeros_like(phi) for i in range(phi.shape[0]): Vlist_cosine[i] = cosine_rotor.get_potential(phi[i]) Vlist_fourier[i] = fourier_rotor.get_potential(phi[i]) fig = plt.figure(figsize=(6, 5)) plt.plot(angle, v_list / 4184., 'ok') linespec = '-r' if rotor is cosine_rotor else '--r' plt.plot(phi, Vlist_cosine / 4184., linespec) linespec = '-b' if rotor is fourier_rotor else '--b' plt.plot(phi, Vlist_fourier / 4184., linespec) plt.legend(['scan', 'cosine', 'fourier'], loc=1) plt.xlim(0, 2 * constants.pi) plt.xlabel('Angle') plt.ylabel('Potential (kcal/mol)') plt.title('{0} hindered rotor #{1:d}'.format(self.species.label, rotor_index + 1)) axes = fig.get_axes()[0] axes.set_xticks([float(j * constants.pi / 4) for j in range(0, 9)]) axes.set_xticks([float(j * constants.pi / 8) for j in range(0, 17)], minor=True) axes.set_xticklabels( ['$0$', '$\pi/4$', '$\pi/2$', '$3\pi/4$', '$\pi$', '$5\pi/4$', '$3\pi/2$', '$7\pi/4$', '$2\pi$']) self.hindered_rotor_plots.append((fig, rotor_index)) plt.close(fig) def save_hindered_rotor_figures(self, directory): """ Save hindered rotor plots as set of files of the form ``rotor_[species_label]_0.pdf`` in the specified directory """ if hasattr(self, 'hindered_rotor_plots'): for fig, rotor_index in self.hindered_rotor_plots: fig.savefig(os.path.join(directory, 'rotor_{0}_{1:d}.pdf'.format(self.species.label, rotor_index))) ################################################################################ def is_linear(coordinates): """ Determine whether or not the species is linear from its 3D coordinates First, try to reduce the problem into just two dimensions, use 3D if the problem cannot be reduced `coordinates` is a numpy.array of the species' xyz coordinates """ # epsilon is in degrees # (from our experience, linear molecules have precisely 180.0 degrees between all atom triples) epsilon = 0.1 number_of_atoms = len(coordinates) if number_of_atoms == 1: return False if number_of_atoms == 2: return True # A tensor containing all distance vectors in the molecule d = -np.array([c[:, np.newaxis] - c[np.newaxis, :] for c in coordinates.T]) for i in range(2, len(coordinates)): u1 = d[:, 0, 1] / np.linalg.norm(d[:, 0, 1]) # unit vector between atoms 0 and 1 u2 = d[:, 1, i] / np.linalg.norm(d[:, 1, i]) # unit vector between atoms 1 and i a = math.degrees(np.arccos(np.clip(np.dot(u1, u2), -1.0, 1.0))) # angle between atoms 0, 1, i if abs(180 - a) > epsilon and abs(a) > epsilon: return False return True def project_rotors(conformer, hessian, rotors, linear, is_ts, get_projected_out_freqs=False, label=None): """ For a given `conformer` with associated force constant matrix `hessian`, lists of rotor information `rotors`, `pivots`, and `top1`, and the linearity of the molecule `linear`, project out the nonvibrational modes from the force constant matrix and use this to determine the vibrational frequencies. The list of vibrational frequencies is returned in cm^-1. Refer to Gaussian whitepaper (http://gaussian.com/vib/) for procedure to calculate harmonic oscillator vibrational frequencies using the force constant matrix. """ n_rotors = 0 for rotor in rotors: if len(rotor) == 8: n_rotors += 2 elif len(rotor) == 5 and isinstance(rotor[1][0], list): n_rotors += len(rotor[1]) else: n_rotors += 1 mass = conformer.mass.value_si coordinates = conformer.coordinates.value if linear is None: linear = is_linear(coordinates) if linear: logging.info('Determined species {0} to be linear.'.format(label)) n_atoms = len(conformer.mass.value) n_vib = 3 * n_atoms - (5 if linear else 6) - n_rotors - (1 if is_ts else 0) # Put origin in center of mass xm = 0.0 ym = 0.0 zm = 0.0 totmass = 0.0 for i in range(n_atoms): xm += mass[i] * coordinates[i, 0] ym += mass[i] * coordinates[i, 1] zm += mass[i] * coordinates[i, 2] totmass += mass[i] xm /= totmass ym /= totmass zm /= totmass for i in range(n_atoms): coordinates[i, 0] -= xm coordinates[i, 1] -= ym coordinates[i, 2] -= zm # Make vector with the root of the mass in amu for each atom amass = np.sqrt(mass / constants.amu) # Rotation matrix inertia = conformer.get_moment_of_inertia_tensor() inertia_xyz = np.linalg.eigh(inertia)[1] external = 6 if linear: external = 5 d = np.zeros((n_atoms * 3, external), np.float64) # Transform the coordinates to the principal axes p = np.dot(coordinates, inertia_xyz) for i in range(n_atoms): # Projection vectors for translation d[3 * i + 0, 0] = amass[i] d[3 * i + 1, 1] = amass[i] d[3 * i + 2, 2] = amass[i] # Construction of the projection vectors for external rotation for i in range(n_atoms): d[3 * i, 3] = (p[i, 1] * inertia_xyz[0, 2] - p[i, 2] * inertia_xyz[0, 1]) * amass[i] d[3 * i + 1, 3] = (p[i, 1] * inertia_xyz[1, 2] - p[i, 2] * inertia_xyz[1, 1]) * amass[i] d[3 * i + 2, 3] = (p[i, 1] * inertia_xyz[2, 2] - p[i, 2] * inertia_xyz[2, 1]) * amass[i] d[3 * i, 4] = (p[i, 2] * inertia_xyz[0, 0] - p[i, 0] * inertia_xyz[0, 2]) * amass[i] d[3 * i + 1, 4] = (p[i, 2] * inertia_xyz[1, 0] - p[i, 0] * inertia_xyz[1, 2]) * amass[i] d[3 * i + 2, 4] = (p[i, 2] * inertia_xyz[2, 0] - p[i, 0] * inertia_xyz[2, 2]) * amass[i] if not linear: d[3 * i, 5] = (p[i, 0] * inertia_xyz[0, 1] - p[i, 1] * inertia_xyz[0, 0]) * amass[i] d[3 * i + 1, 5] = (p[i, 0] * inertia_xyz[1, 1] - p[i, 1] * inertia_xyz[1, 0]) * amass[i] d[3 * i + 2, 5] = (p[i, 0] * inertia_xyz[2, 1] - p[i, 1] * inertia_xyz[2, 0]) * amass[i] # Make sure projection matrix is orthonormal inertia = np.identity(n_atoms * 3, np.float64) p = np.zeros((n_atoms * 3, 3 * n_atoms + external), np.float64) p[:, 0:external] = d[:, 0:external] p[:, external:external + 3 * n_atoms] = inertia[:, 0:3 * n_atoms] for i in range(3 * n_atoms + external): norm = 0.0 for j in range(3 * n_atoms): norm += p[j, i] * p[j, i] for j in range(3 * n_atoms): if norm > 1E-15: p[j, i] /= np.sqrt(norm) else: p[j, i] = 0.0 for j in range(i + 1, 3 * n_atoms + external): proj = 0.0 for k in range(3 * n_atoms): proj += p[k, i] * p[k, j] for k in range(3 * n_atoms): p[k, j] -= proj * p[k, i] # Order p, there will be vectors that are 0.0 i = 0 while i < 3 * n_atoms: norm = 0.0 for j in range(3 * n_atoms): norm += p[j, i] * p[j, i] if norm < 0.5: p[:, i:3 * n_atoms + external - 1] = p[:, i + 1:3 * n_atoms + external] else: i += 1 # T is the transformation vector from cartesian to internal coordinates T = np.zeros((n_atoms * 3, 3 * n_atoms - external), np.float64) T[:, 0:3 * n_atoms - external] = p[:, external:3 * n_atoms] # Generate mass-weighted force constant matrix # This converts the axes to mass-weighted Cartesian axes # Units of Fm are J/m^2*kg = 1/s^2 weighted_hessian = hessian.copy() for i in range(n_atoms): for j in range(n_atoms): for u in range(3): for v in range(3): weighted_hessian[3 * i + u, 3 * j + v] /= math.sqrt(mass[i] * mass[j]) hessian_int = np.dot(T.T, np.dot(weighted_hessian, T)) # Get eigenvalues of internal force constant matrix, V = 3N-6 * 3N-6 eig, v = np.linalg.eigh(hessian_int) logging.debug('Frequencies from internal Hessian') for i in range(3 * n_atoms - external): with np.warnings.catch_warnings(): np.warnings.filterwarnings('ignore', r'invalid value encountered in sqrt') logging.debug(np.sqrt(eig[i]) / (2 * math.pi * constants.c * 100)) # Now we can start thinking about projecting out the internal rotations d_int = np.zeros((3 * n_atoms, n_rotors), np.float64) counter = 0 for i, rotor in enumerate(rotors): if len(rotor) == 5 and isinstance(rotor[1][0], list): scan_dir, pivots_list, tops, sigmas, semiclassical = rotor elif len(rotor) == 5: scanLog, pivots, top, symmetry, fit = rotor pivots_list = [pivots] tops = [top] elif len(rotor) == 3: pivots, top, symmetry = rotor pivots_list = [pivots] tops = [top] elif len(rotor) == 8: scan_dir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry = rotor pivots_list = [pivots1, pivots2] tops = [top1, top2] else: raise ValueError("{} not a proper rotor format".format(rotor)) for k in range(len(tops)): top = tops[k] pivots = pivots_list[k] # Determine pivot atom if pivots[0] in top: pivot1 = pivots[0] pivot2 = pivots[1] elif pivots[1] in top: pivot1 = pivots[1] pivot2 = pivots[0] else: raise ValueError('Could not determine pivot atom for rotor {}.'.format(label)) # Projection vectors for internal rotation e12 = coordinates[pivot1 - 1, :] - coordinates[pivot2 - 1, :] for j in range(n_atoms): atom = j + 1 if atom in top: e31 = coordinates[atom - 1, :] - coordinates[pivot1 - 1, :] d_int[3 * (atom - 1):3 * (atom - 1) + 3, counter] = np.cross(e31, e12) * amass[atom - 1] else: e31 = coordinates[atom - 1, :] - coordinates[pivot2 - 1, :] d_int[3 * (atom - 1):3 * (atom - 1) + 3, counter] = np.cross(e31, -e12) * amass[atom - 1] counter += 1 # Normal modes in mass weighted cartesian coordinates vmw = np.dot(T, v) eigm = np.zeros((3 * n_atoms - external, 3 * n_atoms - external), np.float64) for i in range(3 * n_atoms - external): eigm[i, i] = eig[i] fm = np.dot(vmw, np.dot(eigm, vmw.T)) # Internal rotations are not normal modes => project them on the normal modes and orthogonalize # d_int_proj = (3N-6) x (3N) x (3N) x (Nrotors) d_int_proj = np.dot(vmw.T, d_int) # Reconstruct d_int for i in range(n_rotors): for j in range(3 * n_atoms): d_int[j, i] = 0 for k in range(3 * n_atoms - external): d_int[j, i] += d_int_proj[k, i] * vmw[j, k] # Ortho normalize for i in range(n_rotors): norm = 0.0 for j in range(3 * n_atoms): norm += d_int[j, i] * d_int[j, i] for j in range(3 * n_atoms): d_int[j, i] /= np.sqrt(norm) for j in range(i + 1, n_rotors): proj = 0.0 for k in range(3 * n_atoms): proj += d_int[k, i] * d_int[k, j] for k in range(3 * n_atoms): d_int[k, j] -= proj * d_int[k, i] # calculate the frequencies corresponding to the internal rotors int_proj = np.dot(fm, d_int) kmus = np.array([np.linalg.norm(int_proj[:, i]) for i in range(int_proj.shape[1])]) int_rotor_freqs = np.sqrt(kmus) / (2.0 * math.pi * constants.c * 100.0) if get_projected_out_freqs: return int_rotor_freqs # Do the projection d_int_proj = np.dot(vmw.T, d_int) proj = np.dot(d_int, d_int.T) inertia = np.identity(n_atoms * 3, np.float64) proj = inertia - proj fm = np.dot(proj, np.dot(fm, proj)) # Get eigenvalues of mass-weighted force constant matrix eig, v = np.linalg.eigh(fm) eig.sort() # Convert eigenvalues to vibrational frequencies in cm^-1 # Only keep the modes that don't correspond to translation, rotation, or internal rotation logging.debug('Frequencies from projected Hessian') for i in range(3 * n_atoms): with np.warnings.catch_warnings(): np.warnings.filterwarnings('ignore', r'invalid value encountered in sqrt') logging.debug(np.sqrt(eig[i]) / (2 * math.pi * constants.c * 100)) return np.sqrt(eig[-n_vib:]) / (2 * math.pi * constants.c * 100) def assign_frequency_scale_factor(freq_level): """ Assign the frequency scaling factor according to the model chemistry. Refer to https://comp.chem.umn.edu/freqscale/index.html for future updates of these factors Sources: [1] I.M. Alecu, J. Zheng, Y. Zhao, D.G. Truhlar, J. Chem. Theory Comput. 2010, 6, 2872, DOI: 10.1021/ct100326h [2] http://cccbdb.nist.gov/vibscalejust.asp [3] http://comp.chem.umn.edu/freqscale/190107_Database_of_Freq_Scale_Factors_v4.pdf [4] Calculated as described in 10.1021/ct100326h [5] J.A. Montgomery, M.J. Frisch, J. Chem. Phys. 1999, 110, 2822–2827, DOI: 10.1063/1.477924 Args: freq_level (str, unicode): The frequency level of theory. Returns: float: The frequency scaling factor (1 by default). """ freq_dict = {'hf/sto-3g': 0.817, # [2] 'hf/6-31g': 0.903, # [2] 'hf/6-31g(d)': 0.899, # [2] 'hf/6-31g(d,p)': 0.903, # [2] 'hf/6-31g+(d,p)': 0.904, # [2] 'hf/6-31+g(d,p)': 0.915 * 1.014, # [1] Table 7 'pm3': 0.940 * 1.014, # [1] Table 7, the 0.940 value is the ZPE scale factor 'pm6': 1.078 * 1.014, # [1] Table 7, the 1.078 value is the ZPE scale factor 'b3lyp/6-31g(d,p)': 0.961, # [2] 'b3lyp/6-311g(d,p)': 0.967, # [2] 'b3lyp/6-311+g(3df,2p)': 0.967, # [2] 'b3lyp/6-311+g(3df,2pd)': 0.970, # [2] 'm06-2x/6-31g(d,p)': 0.952, # [2] 'm06-2x/6-31+g(d,p)': 0.979, # [3] 'm06-2x/6-311+g(d,p)': 0.983, # [3] 'm06-2x/6-311++g(d,p)': 0.983, # [3] 'm06-2x/cc-pvtz': 0.955, # [2] 'm06-2x/aug-cc-pvdz': 0.993, # [3] 'm06-2x/aug-cc-pvtz': 0.985, # [1] Table 3, [3] 'm06-2x/def2-tzvp': 0.984, # [3] 'm06-2x/def2-qzvp': 0.983, # [3] 'm06-2x/def2-tzvpp': 0.983, # [1] Table 3, [3] 'm08so/mg3s*': 0.995, # [1] Table 3, taken as 'M08-SO/MG3S' 'wb97x-d/aug-cc-pvtz': 0.988, # [3], taken as 'ωB97X-D/maug-cc-pVTZ' 'wb97xd/6-311++g(d,p)': 0.988, # [4] 'wb97xd/def2tzvp': 0.988, # [4] 'apfd/def2tzvp': 0.993, # [4] 'apfd/def2tzvpp': 0.992, # [4] 'mp2_rmp2_pvdz': 0.953, # [2], taken as 'MP2/cc-pVDZ' 'mp2_rmp2_pvtz': 0.950, # [2], taken as 'MP2/cc-pVTZ' 'mp2_rmp2_pvqz': 0.962, # [2], taken as 'MP2/cc-pVQZ' 'cbs-qb3': 0.99 * 1.014, # [5], the 0.99 value is the ZPE scale factor of CBS-QB3 'cbs-qb3-paraskevas': 0.99 * 1.014, # [5], the 0.99 value is the ZPE scale factor of CBS-QB3 'ccsd-f12/cc-pvdz-f12': 0.947, # [2], taken as 'CCSD/cc-pVDZ' 'ccsd(t)/cc-pvdz': 0.979, # [2] 'ccsd(t)/cc-pvtz': 0.975, # [2] 'ccsd(t)/cc-pvqz': 0.970, # [2] 'ccsd(t)/aug-cc-pvdz': 0.963, # [2] 'ccsd(t)/aug-cc-pvtz': 1.001, # [3] 'ccsd(t)/aug-cc-pvqz': 0.975, # [2] 'ccsd(t)/cc-pv(t+d)z': 0.965, # [2] 'ccsd(t)-f12/cc-pvdz-f12': 0.997, # [3], taken as 'CCSD(T)-F12a/cc-pVDZ-F12' 'ccsd(t)-f12/cc-pvtz-f12': 0.998, # [3], taken as 'CCSD(T)-F12a/cc-pVTZ-F12' 'ccsd(t)-f12/cc-pvqz-f12': 0.998, # [3], taken as 'CCSD(T)-F12b/VQZF12//CCSD(T)-F12a/TZF' 'ccsd(t)-f12/cc-pcvdz-f12': 0.997, # [3], taken as 'CCSD(T)-F12a/cc-pVDZ-F12' 'ccsd(t)-f12/cc-pcvtz-f12': 0.998, # [3], taken as 'CCSD(T)-F12a/cc-pVTZ-F12' 'ccsd(t)-f12/aug-cc-pvdz': 0.997, # [3], taken as 'CCSD(T)/cc-pVDZ' 'ccsd(t)-f12/aug-cc-pvtz': 0.998, # [3], taken as CCSD(T)-F12a/cc-pVTZ-F12 'ccsd(t)-f12/aug-cc-pvqz': 0.998, # [3], taken as 'CCSD(T)-F12b/VQZF12//CCSD(T)-F12a/TZF' } scaling_factor = freq_dict.get(freq_level.lower(), 1) if scaling_factor == 1: logging.warning('No frequency scaling factor found for model chemistry {0}. Assuming a value of unity. ' 'This will affect the partition function and all quantities derived from it ' '(thermo quantities and rate coefficients).'.format(freq_level)) else: logging.info('Assigned a frequency scale factor of {0} for the frequency level of theory {1}'.format( scaling_factor, freq_level)) return scaling_factor def determine_rotor_symmetry(energies, label, pivots): """ Determine the rotor symmetry number from the potential scan given in :list:`energies` in J/mol units Assumes the list represents a 360 degree scan str:`label` is the species name, used for logging and error messages list:`pivots` are the rotor's pivots, used for logging and error messages The *worst* resolution for each peak and valley is determined. The first criterion for a symmetric rotor is that the highest peak and the lowest peak must be within the worst peak resolution (and the same is checked for valleys). A second criterion for a symmetric rotor is that the highest and lowest peaks must be within 10% of the highest peak value. This is only applied if the highest peak is above 2 kJ/mol. """ symmetry = None min_e = min(energies) max_e = max(energies) if max_e > 2000: tol = 0.10 * max_e # tolerance for the second criterion else: tol = max_e peaks, valleys = list(), [energies[0]] # the peaks and valleys of the scan worst_peak_resolution, worst_valley_resolution = 0, max(energies[1] - energies[0], energies[-2] - energies[-1]) for i, e in enumerate(energies): # identify peaks and valleys, and determine worst resolutions in the scan if i != 0 and i != len(energies) - 1: last_point = energies[i - 1] next_point = energies[i + 1] # this is an intermediate point in the scan if e > last_point and e > next_point: # this is a local peak if any([diff > worst_peak_resolution for diff in [e - last_point, e - next_point]]): worst_peak_resolution = max(e - last_point, e - next_point) peaks.append(e) elif e < last_point and e < next_point: # this is a local valley if any([diff > worst_valley_resolution for diff in [energies[i - 1] - e, next_point - e]]): worst_valley_resolution = max(last_point - e, next_point - e) valleys.append(e) # The number of peaks and valley must always be the same (what goes up must come down), if it isn't then there's # something seriously wrong with the scan if len(peaks) != len(valleys): raise InputError('Rotor of species {0} between pivots {1} does not have the same number' ' of peaks and valleys.'.format(label, pivots)) min_peak = min(peaks) max_peak = max(peaks) min_valley = min(valleys) max_valley = max(valleys) # Criterion 1: worst resolution if max_peak - min_peak > worst_peak_resolution: # The rotor cannot be symmetric symmetry = 1 reason = 'worst peak resolution criterion' elif max_valley - min_valley > worst_valley_resolution: # The rotor cannot be symmetric symmetry = 1 reason = 'worst valley resolution criterion' # Criterion 2: 10% * max_peak elif max_peak - min_peak > tol: # The rotor cannot be symmetric symmetry = 1 reason = '10% of the maximum peak criterion' else: # We declare this rotor as symmetric and the symmetry number is the number of peaks (and valleys) symmetry = len(peaks) reason = 'number of peaks and valleys, all within the determined resolution criteria' if symmetry not in [1, 2, 3]: logging.warning('Determined symmetry number {0} for rotor of species {1} between pivots {2}; ' 'you should make sure this makes sense'.format(symmetry, label, pivots)) else: logging.info('Determined a symmetry number of {0} for rotor of species {1} between pivots {2}' ' based on the {3}.'.format(symmetry, label, pivots, reason)) return symmetry
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """BERT finetuning runner with TF-Hub.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import optimization import run_classifier_ner_BERT import tokenization import tensorflow as tf import tensorflow_hub as hub flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string( "bert_hub_module_handle", None, "Handle for the BERT TF-Hub module.") def create_model(is_training, input_ids, input_mask, segment_ids, labels, num_labels, bert_hub_module_handle): """Creates a classification model.""" tags = set() if is_training: tags.add("train") bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True) bert_inputs = dict( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids) bert_outputs = bert_module( inputs=bert_inputs, signature="tokens", as_dict=True) # In the demo, we are doing a simple classification task on the entire # segment. # # If you want to use the token-level output, use # bert_outputs["sequence_output"] instead. output_layer = bert_outputs["pooled_output"] hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope("loss"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) probabilities = tf.nn.softmax(logits, axis=-1) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, logits, probabilities) def model_fn_builder(num_labels, learning_rate, num_train_steps, num_warmup_steps, use_tpu, bert_hub_module_handle): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) (total_loss, per_example_loss, logits, probabilities) = create_model( is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, bert_hub_module_handle) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy(label_ids, predictions) loss = tf.metrics.mean(per_example_loss) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits]) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics) elif mode == tf.estimator.ModeKeys.PREDICT: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={"probabilities": probabilities}) else: raise ValueError( "Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode)) return output_spec return model_fn def create_tokenizer_from_hub_module(bert_hub_module_handle): """Get the vocab file and casing info from the Hub module.""" with tf.Graph().as_default(): bert_module = hub.Module(bert_hub_module_handle) tokenization_info = bert_module(signature="tokenization_info", as_dict=True) with tf.Session() as sess: vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"], tokenization_info["do_lower_case"]]) return tokenization.FullTokenizer( vocab_file=vocab_file, do_lower_case=do_lower_case) def main(_): tf.logging.set_verbosity(tf.logging.INFO) processors = { "cola": run_classifier_ner_BERT.ColaProcessor, "mnli": run_classifier_ner_BERT.MnliProcessor, "mrpc": run_classifier_ner_BERT.MrpcProcessor, } if not FLAGS.do_train and not FLAGS.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.") tf.gfile.MakeDirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host)) train_examples = None num_train_steps = None num_warmup_steps = None if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) model_fn = model_fn_builder( num_labels=len(label_list), learning_rate=FLAGS.learning_rate, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_tpu=FLAGS.use_tpu, bert_hub_module_handle=FLAGS.bert_hub_module_handle) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.contrib.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size, predict_batch_size=FLAGS.predict_batch_size) if FLAGS.do_train: train_features = run_classifier_ner_BERT.convert_examples_to_features( train_examples, label_list, FLAGS.max_seq_length, tokenizer) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = run_classifier_ner_BERT.input_fn_builder( features=train_features, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) estimator.train(input_fn=train_input_fn, max_steps=num_train_steps) if FLAGS.do_eval: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_features = run_classifier_ner_BERT.convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Num examples = %d", len(eval_examples)) tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) # This tells the estimator to run through the entire set. eval_steps = None # However, if running eval on the TPU, you will need to specify the # number of steps. if FLAGS.use_tpu: # Eval will be slightly WRONG on the TPU because it will truncate # the last batch. eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size) eval_drop_remainder = True if FLAGS.use_tpu else False eval_input_fn = run_classifier_ner_BERT.input_fn_builder( features=eval_features, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with tf.gfile.GFile(output_eval_file, "w") as writer: tf.logging.info("***** Eval results *****") for key in sorted(result.keys()): tf.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) if FLAGS.do_predict: predict_examples = processor.get_test_examples(FLAGS.data_dir) if FLAGS.use_tpu: # Discard batch remainder if running on TPU n = len(predict_examples) predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)] predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record") run_classifier_ner_BERT.file_based_convert_examples_to_features( predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.logging.info("***** Running prediction*****") tf.logging.info(" Num examples = %d", len(predict_examples)) tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size) predict_input_fn = run_classifier_ner_BERT.file_based_input_fn_builder( input_file=predict_file, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=FLAGS.use_tpu) result = estimator.predict(input_fn=predict_input_fn) output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv") with tf.gfile.GFile(output_predict_file, "w") as writer: tf.logging.info("***** Predict results *****") for prediction in result: probabilities = prediction["probabilities"] output_line = "\t".join( str(class_probability) for class_probability in probabilities) + "\n" writer.write(output_line) if __name__ == "__main__": flags.mark_flag_as_required("data_dir") flags.mark_flag_as_required("task_name") flags.mark_flag_as_required("bert_hub_module_handle") flags.mark_flag_as_required("output_dir") tf.app.run()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: ericyuan """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import linear_model from sklearn.model_selection import cross_validate from pykalman import KalmanFilter class CRESULT: '''class for storage results ''' def __init__(self): pass class Reg: '''class for OLS estimation''' def __str__(self): return("Regression class for outputting better results") # R sqaure def rsquare(self, y, yhat): SST = sum((y - np.mean(y))**2) SSReg = sum((yhat - np.mean(y))**2) Rsquared = SSReg/SST return Rsquared def ols(self, x, y, cv = 5, scoring = ['explained_variance', 'neg_mean_squared_error']): x = pd.DataFrame(x) y = pd.DataFrame(y) # Create linear regression object OLS = linear_model.LinearRegression(fit_intercept = False) # Train the model using the training sets OLS.fit(x, y) # get the results OLSresult = CRESULT() coefs = OLS.coef_ scores = cross_validate(OLS, x, y, scoring=scoring, \ cv=cv, return_train_score=False) # store the results OLSresult.e1 = scores['test_'+scoring[0]] OLSresult.e2 = scores['test_'+scoring[1]] OLSresult.coefs = coefs # fitted value fitted = OLS.predict(x.values) OLSresult.fitted = fitted OLSresult.r2 = self.rsquare(y.values, fitted)[0] return OLSresult # remove outliers class Outlier(object): def __init__(self, data, up_bound, low_bound): ''' data: dataframe ''' self.data = data # x std self.up_bound = up_bound # x std self.low_bound = low_bound def __transform(self, x, mean, std): ''' transform ''' if x >= self.up_bound: return self.up_bound*std + mean elif x <= self.low_bound: return self.low_bound*std + mean else: return x*std + mean def remove(self, col, transform = True): ''' data: dataframe object col: columns' name, list ''' for each_col in col: # mean mean = self.data[each_col].mean() # std std = self.data[each_col].std() self.data['help'] = self.data[each_col].map(lambda x: \ (x - mean)*1.0/std) if transform: self.data[each_col] = self.data['help'].map(lambda x: \ self.__transform(x, mean, std)) else: self.data = self.data[(self.data['help'] <= self.up_bound)&(self.data['help'] >= self.low_bound)] del self.data['help'] return self.data class Kalman: ''' Kalman filter for Regression Estimation Input: all dataset including two assets which we want to explore Output: Analysis Result Notice: index must be time format ''' def __init__(self, data): self.data = data def analysis(self, asset1, asset2, visual = False): # Kalman Filter delta = 1e-5 trans_cov = delta / (1 - delta) * np.eye(2) obs_mat = np.vstack([self.data[asset1], \ np.ones(self.data[asset1].shape)]).T[:, np.newaxis] # set parameters kf = KalmanFilter(n_dim_obs = 1, n_dim_state = 2, initial_state_mean=np.zeros(2), initial_state_covariance = np.ones((2, 2)), transition_matrices = np.eye(2), observation_matrices = obs_mat, observation_covariance = 1.0, transition_covariance = trans_cov) # calculate rolling beta and intercept state_means, state_covs = kf.filter(self.data[asset2].values) beta_slope = pd.DataFrame(dict(slope=state_means[:, 0], \ intercept=state_means[:, 1]), index = self.data.index) if visual == True: # visualization for correlation cm = plt.cm.get_cmap('jet') colors = np.linspace(0.1, 1, len(self.data)) sc = plt.scatter(self.data[asset1], self.data[asset2], \ s=30, c=colors, cmap=cm, edgecolor='k', alpha=0.7) cb = plt.colorbar(sc) cb.ax.set_yticklabels([str(p.date()) for p in \ self.data[::len(self.data)//9].index]); plt.xlabel(asset1) plt.ylabel(asset2) plt.show() # plot beta and slope beta_slope.plot(subplots = True) plt.show() # visualize the correlation between assest prices over time cm = plt.cm.get_cmap('jet') colors = np.linspace(0.1, 1, len(self.data)) sc = plt.scatter(self.data[asset1], self.data[asset2], \ s=50, c=colors, cmap=cm, edgecolor='k', alpha=0.7) cb = plt.colorbar(sc) cb.ax.set_yticklabels([str(p.date()) for p in self.data[::len(self.data)//9].index]); plt.xlabel(asset1) plt.ylabel(asset2) # add regression lines step = 5 xi = np.linspace(self.data[asset1].min(), self.data[asset1].max(), 2) colors_l = np.linspace(0.1, 1, len(state_means[::step])) for i, beta in enumerate(state_means[::step]): plt.plot(xi, beta[0] * xi + beta[1], alpha=.2, lw=1, c=cm(colors_l[i])) return beta_slope # from index name based on dict, get industry and rating def getX(name, dicty): res = dicty[dicty['code'] == name]['name'].values[0].split(' ') ind = res[0] rating = res[1] return(ind, rating) # parameters estimation def est(data, indexName, dicty): ind, rating = getX(indexName, dicty) bondReg = Reg() try: resUtilitiesBBB = bondReg.ols(x = data[[ind, rating]], y = data[indexName]) return(resUtilitiesBBB.coefs[0], ind + ' ' + rating, indexName, \ resUtilitiesBBB.e1, resUtilitiesBBB.e2, resUtilitiesBBB.r2) except: return 0 # plot #def bondPlot(industry, rating, index, res, data): # y = data[index] # slope_rating = res[res['indexname'] == index]['ratingCoef'] # slope_sec = res[res['indexname'] == index]['indRes'] # intercept = res[res['indexname'] == index]['intercept'] # # x = slope_sec*data[industry] + slope_rating*data[rating] + intercept # print(slope_rating, slope_sec, intercept, data[industry], data[rating]) # plotdf = pd.DataFrame({'x':x, 'y':y}) # sns.regplot('x','y',plotdf) # plt.xlabel('x') # plt.ylabel('y') # return plotdf def bondplot(industry, rating, index, data): reg = Reg() res = reg.ols(data[[industry, rating]], data[index]) # plt.scatter(new_df['IGUUIA3M Index'], res.fitted.T.tolist()[0]) sns.regplot(data[index], res.fitted.T.tolist()[0]) print(np.corrcoef(data[index], res.fitted.T.tolist()[0])) plt.show() plotdata = pd.DataFrame({'x': data[index], 'y': res.fitted.T.tolist()[0]}) plotdata.index = data['date'] return plotdata def rollingReg(end, step, data, x, y, start = 0): length = len(data) reg = Reg() ax = plt.gca() # minx = 0 # maxx = 0 # loop while end < length: regdata = data.iloc[start:end] res = reg.ols(regdata[x], regdata[y]) # max, min value for fitted # minx = min(minx, min(res.fitted)) # maxx = max(maxx, max(res.fitted)) # plot sns.regplot(regdata[y], res.fitted.T.tolist()[0], ax = ax) # update start += step end += step plt.xlim(-5, 5) plt.ylim(min(data[y]), max(data[y]))
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ diff = 0 for i in range(len(prices) - 1): if prices[i] < prices[i + 1]: diff = max(diff, max(prices[i + 1:]) - prices[i]) return diff
// pages/about/about.js Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, onLoad: function () { wx.setNavigationBarTitle({ title: '关于我们', }) } })
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Chain Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import tensorflow as tf from tensorflow_probability.python import bijectors as tfb from tensorflow.python.ops.distributions import bijector from tensorflow.python.ops.distributions.bijector_test_util import assert_scalar_congruency class ShapeChanging(bijector.Bijector): """Only used for op_ndims manipulation.""" def __init__(self, forward_min_event_ndims=0, inverse_min_event_ndims=3): super(ShapeChanging, self).__init__( forward_min_event_ndims=forward_min_event_ndims, inverse_min_event_ndims=inverse_min_event_ndims, validate_args=False, name="shape_changer") class ChainBijectorTest(tf.test.TestCase): """Tests the correctness of the Y = Chain(bij1, bij2, bij3) transformation.""" def testBijector(self): with self.test_session(): chain = tfb.Chain((tfb.Exp(), tfb.Softplus())) self.assertEqual("chain_of_exp_of_softplus", chain.name) x = np.asarray([[[1., 2.], [2., 3.]]]) self.assertAllClose(1. + np.exp(x), self.evaluate(chain.forward(x))) self.assertAllClose(np.log(x - 1.), self.evaluate(chain.inverse(x))) self.assertAllClose( -np.sum(np.log(x - 1.), axis=2), self.evaluate(chain.inverse_log_det_jacobian(x, event_ndims=1))) self.assertAllClose( np.sum(x, axis=2), self.evaluate(chain.forward_log_det_jacobian(x, event_ndims=1))) def testBijectorIdentity(self): with self.test_session(): chain = tfb.Chain() self.assertEqual("identity", chain.name) x = np.asarray([[[1., 2.], [2., 3.]]]) self.assertAllClose(x, self.evaluate(chain.forward(x))) self.assertAllClose(x, self.evaluate(chain.inverse(x))) self.assertAllClose( 0., self.evaluate(chain.inverse_log_det_jacobian(x, event_ndims=1))) self.assertAllClose( 0., self.evaluate(chain.forward_log_det_jacobian(x, event_ndims=1))) def testScalarCongruency(self): with self.test_session(): chain = tfb.Chain((tfb.Exp(), tfb.Softplus())) assert_scalar_congruency( chain, lower_x=1e-3, upper_x=1.5, rtol=0.05) def testShapeGetters(self): with self.test_session(): chain = tfb.Chain([ tfb.SoftmaxCentered(validate_args=True), tfb.SoftmaxCentered(validate_args=True), ]) x = tf.TensorShape([1]) y = tf.TensorShape([2 + 1]) self.assertAllEqual(y, chain.forward_event_shape(x)) self.assertAllEqual( y.as_list(), self.evaluate(chain.forward_event_shape_tensor(x.as_list()))) self.assertAllEqual(x, chain.inverse_event_shape(y)) self.assertAllEqual( x.as_list(), self.evaluate(chain.inverse_event_shape_tensor(y.as_list()))) def testMinEventNdimsChain(self): chain = tfb.Chain([tfb.Exp(), tfb.Exp(), tfb.Exp()]) self.assertEqual(0, chain.forward_min_event_ndims) self.assertEqual(0, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Affine(), tfb.Affine(), tfb.Affine()]) self.assertEqual(1, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Exp(), tfb.Affine()]) self.assertEqual(1, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Affine(), tfb.Exp()]) self.assertEqual(1, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Affine(), tfb.Exp(), tfb.Softplus(), tfb.Affine()]) self.assertEqual(1, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) def testMinEventNdimsShapeChangingAddDims(self): chain = tfb.Chain([ShapeChanging()]) self.assertEqual(0, chain.forward_min_event_ndims) self.assertEqual(3, chain.inverse_min_event_ndims) chain = tfb.Chain([ShapeChanging(), tfb.Affine()]) self.assertEqual(1, chain.forward_min_event_ndims) self.assertEqual(4, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Affine(), ShapeChanging()]) self.assertEqual(0, chain.forward_min_event_ndims) self.assertEqual(3, chain.inverse_min_event_ndims) chain = tfb.Chain([ShapeChanging(), ShapeChanging()]) self.assertEqual(0, chain.forward_min_event_ndims) self.assertEqual(6, chain.inverse_min_event_ndims) def testMinEventNdimsShapeChangingRemoveDims(self): chain = tfb.Chain([ShapeChanging(3, 0)]) self.assertEqual(3, chain.forward_min_event_ndims) self.assertEqual(0, chain.inverse_min_event_ndims) chain = tfb.Chain([ShapeChanging(3, 0), tfb.Affine()]) self.assertEqual(3, chain.forward_min_event_ndims) self.assertEqual(0, chain.inverse_min_event_ndims) chain = tfb.Chain([tfb.Affine(), ShapeChanging(3, 0)]) self.assertEqual(4, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) chain = tfb.Chain([ShapeChanging(3, 0), ShapeChanging(3, 0)]) self.assertEqual(6, chain.forward_min_event_ndims) self.assertEqual(0, chain.inverse_min_event_ndims) def testMinEventNdimsShapeChangingAddRemoveDims(self): chain = tfb.Chain( [ShapeChanging(2, 1), ShapeChanging(3, 0), ShapeChanging(1, 2)]) self.assertEqual(4, chain.forward_min_event_ndims) self.assertEqual(1, chain.inverse_min_event_ndims) def testChainExpAffine(self): scale_diag = np.array([1., 2., 3.], dtype=np.float32) chain = tfb.Chain([tfb.Exp(), tfb.Affine(scale_diag=scale_diag)]) x = [0., np.log(2., dtype=np.float32), np.log(3., dtype=np.float32)] y = [1., 4., 27.] self.assertAllClose(y, self.evaluate(chain.forward(x))) self.assertAllClose(x, self.evaluate(chain.inverse(y))) self.assertAllClose( np.log(6, dtype=np.float32) + np.sum(scale_diag * x), self.evaluate(chain.forward_log_det_jacobian(x, event_ndims=1))) self.assertAllClose( -np.log(6, dtype=np.float32) - np.sum(scale_diag * x), self.evaluate(chain.inverse_log_det_jacobian(y, event_ndims=1))) def testChainAffineExp(self): scale_diag = np.array([1., 2., 3.], dtype=np.float32) chain = tfb.Chain([tfb.Affine(scale_diag=scale_diag), tfb.Exp()]) x = [0., np.log(2., dtype=np.float32), np.log(3., dtype=np.float32)] y = [1., 4., 9.] self.assertAllClose(y, self.evaluate(chain.forward(x))) self.assertAllClose(x, self.evaluate(chain.inverse(y))) self.assertAllClose( np.log(6, dtype=np.float32) + np.sum(x), self.evaluate(chain.forward_log_det_jacobian(x, event_ndims=1))) self.assertAllClose( -np.log(6, dtype=np.float32) - np.sum(x), self.evaluate(chain.inverse_log_det_jacobian(y, event_ndims=1))) def testChainIldjWithPlaceholder(self): chain = tfb.Chain((tfb.Exp(), tfb.Exp())) samples = tf.placeholder(dtype=np.float32, shape=[None, 10], name="samples") ildj = chain.inverse_log_det_jacobian(samples, event_ndims=0) self.assertTrue(ildj is not None) with self.test_session(): ildj.eval({samples: np.zeros([2, 10], np.float32)}) if __name__ == "__main__": tf.test.main()
#! /usr/bin/python import rospy import cv2 # OpenCV from cv_bridge import CvBridge, CvBridgeError # converts between ROS Image messages and OpenCV images from std_msgs.msg import String from sensor_msgs.msg import Image import numpy as np import math as m from enum import Enum from find_corners import find_corners """ This code reads an image in over a ROS topic and attempts to output a thrust vector according to the position of the line""" bridge = CvBridge() class Corner(Enum): LOOKING = 0 FOLLOWING = 1 EXITING = 2 # class StartPoint(Enum): # UP = 0 # RIGHT = 1 # DOWN = 2 # LEFT = 3 class Vector: prev_vector = [] x_cam_width = 640 y_cam_height = 480 def __init__(self, thrust_vect=[], resultant_vect=[], start_point=[]): self.thrust_vect = thrust_vect self.resultant_vect = resultant_vect self.start_point = start_point """ Function attempts to locate a corner if there is one. If no corner is detected it returns""" def get_corner_detect(self, img): corner_detected = find_corners(img) if not corner_detected: return Corner.NO_CORNER else: return corner_detected def get_vector_start_point(self): origin = [0, 0] prev_mag = m.sqrt((self.prev_vector[0]) ** 2 + (self.prev_vector[1] ** 2)) unit_vect = [self.prev_vector[0] / prev_mag, self.prev_vector[1] / prev_mag] if (abs(unit_vect[0]) > abs(unit_vect[1])): if (unit_vect[0] > 0): # This origin point is the left middle print("left middle") start_point = [origin[0], origin[1] + self.y_cam_height / 2] else: # This origin point is the right middle print("right middle") start_point = [origin[0] + self.x_cam_width, origin[1] + self.y_cam_height / 2] else: if (unit_vect[1] < 0): # This origin point is the bottom middle print("bottom middle") start_point = [origin[0] + self.x_cam_width / 2, origin[1] + self.y_cam_height] else: # This origin point is the top middle start_point = [origin[0] + self.x_cam_width / 2, origin[1]] print("top middle") self.start_point = start_point def get_thrust_vect(self, center): self.resultant_vect = [center[0] - self.start_point[0], center[1] - self.start_point[1]] self.thrust_vect = [self.resultant_vect[0] - self.prev_vector[0], self.resultant_vect[1] - self.prev_vector[1]] return self.thrust_vect, self.resultant_vect class View: at_beginning = True beginning_frames_seen = 0; thresh_rngs = {"red": [(0 / 2, 150, 115), (35 / 2, 255, 255)], "blue": [(182 / 2, 10 * 2.56, 12 * 2.56), (265 / 2, 100 * 2.56, 100 * 2.56)]} def __init__(self, cnt=None, at_beginning=True): self.cnt = cnt def compare_cnts(self, ex_cnt): return cv2.matchShapes(self.cnt, ex_cnt, 1, 0.0) < .02 def get_largest(img): # grab all of the contours im, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # iterate through contours to find one with largest area largest_area = -1 largest_cnt = -1 for i in range(len(contours)): area = cv2.contourArea(contours[i]) if largest_area < area: largest_area = area largest_cnt = contours[i] return largest_cnt def draw_rect(img, contour): x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) x_c = x + int(w / 2) y_c = y + int(h / 2) cv2.circle(img, (x_c, y_c), 3, (255, 0, 0), -1) return [x_c, y_c] def draw_center(img, contour): # Obtain coordinates of the center of mass of the largest contour moment = cv2.moments(contour) Cx = int(moment['m10'] / moment['m00']) Cy = int(moment['m01'] / moment['m00']) # Print the center of mass onto the screen cv2.circle(img, (Cx, Cy), 3, (0, 255, 0), -1) return [Cx, Cy] def traverse_line(img_og, contour, vects): if contour.all() != -1: cv2.drawContours(img_og, [contour], 0, (0, 255, 0), 3) center_rect = draw_rect(img_og, contour) center_cnt = draw_center(img_og, contour) # find moment if cv2.isContourConvex(contour): center = center_cnt else: center = center_rect cv2.circle(img_og, (center[0], center[1]), 7, (0, 0, 0), -1) vects.get_vector_start_point() thrust_vect, resultant_vect = vects.get_thrust_vect(center) else: thrust_vect = np.multiply(Vector.prev_vector, -1) resultant_vect = [0, 0] #### MAGNITUDES ARE CURRENTLY AN ISSUE -- Need a base_load thrust # draw previous vector - yellow cv2.line(img_og, (vects.start_point[0], vects.start_point[1]), (vects.start_point[0] + Vector.prev_vector[0], vects.start_point[1] + Vector.prev_vector[1]), (18, 222, 218), 6) # draw resultant vector - orange cv2.line(img_og, (vects.start_point[0], vects.start_point[1]), (vects.start_point[0] + resultant_vect[0], vects.start_point[1] + resultant_vect[1]), (15, 125, 210), 3) # draw thrust vector - red cv2.line(img_og, (center[0] - thrust_vect[0], center[1] - thrust_vect[1]), (center[0], center[1]), (0, 0, 255), 1) return thrust_vect, resultant_vect # functions that manipulates the data that comes the camera def process(data): # convert img to cv image and convert to HSV img = bridge.imgmsg_to_cv2(data, "bgr8") img_og = img img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # blurring (median and then gaussian) img = cv2.medianBlur(img, 5) img = cv2.GaussianBlur(img, (5, 5), 0) # red # img = cv2.inRange(img,View.thresh_rngs["red"][0],View.thresh_rngs["red"][1]) # blue img = cv2.inRange(img, View.thresh_rngs["blue"][0], View.thresh_rngs["blue"][1]) # erode and dilate image img = cv2.erode(img, np.ones((5, 5))) img = cv2.dilate(img, np.ones((10, 10))) # contouring contour = get_largest(img) view = View(contour) vects = Vector() if View.at_beginning: print("at beginning") View.beginning_frames_seen += 1 ''' #Code to be run only at the start sq_cnts, circ_cnts = get_ex_cnts() wall_md_pt, center, init_shape = match_beginning(img,view.cnt,sq_cnts,circ_cnts) Vector.prev_vector = [center[0] - wall_md_pt[0],center[1] - wall_md_pt[1]] ''' Vector.prev_vector = [0, 5] vects.start_point = [Vector.x_cam_width / 2, Vector.y_cam_height] center = [Vector.x_cam_width / 2, Vector.y_cam_height / 2] thrust_vect, resultant_vect = vects.get_thrust_vect(center) if (View.beginning_frames_seen == 5): View.at_beginning = False # draw previous vector - yellow cv2.line(img_og, (vects.start_point[0], vects.start_point[1]), (vects.start_point[0] + Vector.prev_vector[0], vects.start_point[1] + Vector.prev_vector[1]), (18, 222, 218), 7) # draw resultant vector - orange cv2.line(img_og, (vects.start_point[0], vects.start_point[1]), (vects.start_point[0] + resultant_vect[0], vects.start_point[1] + resultant_vect[1]), (15, 125, 210), 5) # draw thrust vector - red cv2.line(img_og, (center[0] - thrust_vect[0], center[1] - thrust_vect[1]), (center[0], center[1]), (0, 0, 255), 3) else: thrust_vect, resultant_vect = traverse_line(img_og, view.cnt, vects) # print("curr_thr: [%d, %d], resultant: [%d, %d]" % (thrust_vect[0], thrust_vect[1], resultant_vect[0], resultant_vect[1])) # Publish unit thrust vector thrust_mag = m.sqrt((thrust_vect(center)[0]) ** 2 + (thrust_vect(center)[1]) ** 2) unit_thrust_vect = [thrust_vect[0] / prev_mag, thrust_vect[1] / thrust_mag] pub = rospy.Publisher("thrust_output_topic", String, queue_size=10) pub.publish(String(unit_thrust_vect)) # Set resultant vect to prev_vector Vector.prev_vector = resultant_vect # Show images cv2.imshow("Filtered", img) cv2.imshow("Image", img_og) cv2.waitKey(3) if __name__ == "__main__": rospy.init_node('line_follow', anonymous=True) rospy.Subscriber("/usb_cam/image_raw", Image, process) rospy.spin()
/* * Copyright (c) 2000-2005 Silicon Graphics, Inc. * Copyright (c) 2013 Red Hat, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_bit.h" #include "xfs_mount.h" #include "xfs_da_format.h" #include "xfs_da_btree.h" #include "xfs_inode.h" #include "xfs_trans.h" #include "xfs_inode_item.h" #include "xfs_bmap.h" #include "xfs_attr.h" #include "xfs_attr_sf.h" #include "xfs_attr_remote.h" #include "xfs_attr_leaf.h" #include "xfs_error.h" #include "xfs_trace.h" #include "xfs_buf_item.h" #include "xfs_cksum.h" #include "xfs_dir2.h" STATIC int xfs_attr_shortform_compare(const void *a, const void *b) { xfs_attr_sf_sort_t *sa, *sb; sa = (xfs_attr_sf_sort_t *)a; sb = (xfs_attr_sf_sort_t *)b; if (sa->hash < sb->hash) { return -1; } else if (sa->hash > sb->hash) { return 1; } else { return sa->entno - sb->entno; } } #define XFS_ISRESET_CURSOR(cursor) \ (!((cursor)->initted) && !((cursor)->hashval) && \ !((cursor)->blkno) && !((cursor)->offset)) /* * Copy out entries of shortform attribute lists for attr_list(). * Shortform attribute lists are not stored in hashval sorted order. * If the output buffer is not large enough to hold them all, then we * we have to calculate each entries' hashvalue and sort them before * we can begin returning them to the user. */ int xfs_attr_shortform_list(xfs_attr_list_context_t *context) { attrlist_cursor_kern_t *cursor; xfs_attr_sf_sort_t *sbuf, *sbp; xfs_attr_shortform_t *sf; xfs_attr_sf_entry_t *sfe; xfs_inode_t *dp; int sbsize, nsbuf, count, i; int error; ASSERT(context != NULL); dp = context->dp; ASSERT(dp != NULL); ASSERT(dp->i_afp != NULL); sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data; ASSERT(sf != NULL); if (!sf->hdr.count) return 0; cursor = context->cursor; ASSERT(cursor != NULL); trace_xfs_attr_list_sf(context); /* * If the buffer is large enough and the cursor is at the start, * do not bother with sorting since we will return everything in * one buffer and another call using the cursor won't need to be * made. * Note the generous fudge factor of 16 overhead bytes per entry. * If bufsize is zero then put_listent must be a search function * and can just scan through what we have. */ if (context->bufsize == 0 || (XFS_ISRESET_CURSOR(cursor) && (dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) { for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) { error = context->put_listent(context, sfe->flags, sfe->nameval, (int)sfe->namelen, (int)sfe->valuelen, &sfe->nameval[sfe->namelen]); /* * Either search callback finished early or * didn't fit it all in the buffer after all. */ if (context->seen_enough) break; if (error) return error; sfe = XFS_ATTR_SF_NEXTENTRY(sfe); } trace_xfs_attr_list_sf_all(context); return 0; } /* do no more for a search callback */ if (context->bufsize == 0) return 0; /* * It didn't all fit, so we have to sort everything on hashval. */ sbsize = sf->hdr.count * sizeof(*sbuf); sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS); /* * Scan the attribute list for the rest of the entries, storing * the relevant info from only those that match into a buffer. */ nsbuf = 0; for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) { if (unlikely( ((char *)sfe < (char *)sf) || ((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) { XFS_CORRUPTION_ERROR("xfs_attr_shortform_list", XFS_ERRLEVEL_LOW, context->dp->i_mount, sfe); kmem_free(sbuf); return -EFSCORRUPTED; } sbp->entno = i; sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen); sbp->name = sfe->nameval; sbp->namelen = sfe->namelen; /* These are bytes, and both on-disk, don't endian-flip */ sbp->valuelen = sfe->valuelen; sbp->flags = sfe->flags; sfe = XFS_ATTR_SF_NEXTENTRY(sfe); sbp++; nsbuf++; } /* * Sort the entries on hash then entno. */ xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare); /* * Re-find our place IN THE SORTED LIST. */ count = 0; cursor->initted = 1; cursor->blkno = 0; for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) { if (sbp->hash == cursor->hashval) { if (cursor->offset == count) { break; } count++; } else if (sbp->hash > cursor->hashval) { break; } } if (i == nsbuf) { kmem_free(sbuf); return 0; } /* * Loop putting entries into the user buffer. */ for ( ; i < nsbuf; i++, sbp++) { if (cursor->hashval != sbp->hash) { cursor->hashval = sbp->hash; cursor->offset = 0; } error = context->put_listent(context, sbp->flags, sbp->name, sbp->namelen, sbp->valuelen, &sbp->name[sbp->namelen]); if (error) return error; if (context->seen_enough) break; cursor->offset++; } kmem_free(sbuf); return 0; } STATIC int xfs_attr_node_list(xfs_attr_list_context_t *context) { attrlist_cursor_kern_t *cursor; xfs_attr_leafblock_t *leaf; xfs_da_intnode_t *node; struct xfs_attr3_icleaf_hdr leafhdr; struct xfs_da3_icnode_hdr nodehdr; struct xfs_da_node_entry *btree; int error, i; struct xfs_buf *bp; struct xfs_inode *dp = context->dp; struct xfs_mount *mp = dp->i_mount; trace_xfs_attr_node_list(context); cursor = context->cursor; cursor->initted = 1; /* * Do all sorts of validation on the passed-in cursor structure. * If anything is amiss, ignore the cursor and look up the hashval * starting from the btree root. */ bp = NULL; if (cursor->blkno > 0) { error = xfs_da3_node_read(NULL, dp, cursor->blkno, -1, &bp, XFS_ATTR_FORK); if ((error != 0) && (error != -EFSCORRUPTED)) return error; if (bp) { struct xfs_attr_leaf_entry *entries; node = bp->b_addr; switch (be16_to_cpu(node->hdr.info.magic)) { case XFS_DA_NODE_MAGIC: case XFS_DA3_NODE_MAGIC: trace_xfs_attr_list_wrong_blk(context); xfs_trans_brelse(NULL, bp); bp = NULL; break; case XFS_ATTR_LEAF_MAGIC: case XFS_ATTR3_LEAF_MAGIC: leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &leafhdr, leaf); entries = xfs_attr3_leaf_entryp(leaf); if (cursor->hashval > be32_to_cpu( entries[leafhdr.count - 1].hashval)) { trace_xfs_attr_list_wrong_blk(context); xfs_trans_brelse(NULL, bp); bp = NULL; } else if (cursor->hashval <= be32_to_cpu( entries[0].hashval)) { trace_xfs_attr_list_wrong_blk(context); xfs_trans_brelse(NULL, bp); bp = NULL; } break; default: trace_xfs_attr_list_wrong_blk(context); xfs_trans_brelse(NULL, bp); bp = NULL; } } } /* * We did not find what we expected given the cursor's contents, * so we start from the top and work down based on the hash value. * Note that start of node block is same as start of leaf block. */ if (bp == NULL) { cursor->blkno = 0; for (;;) { __uint16_t magic; error = xfs_da3_node_read(NULL, dp, cursor->blkno, -1, &bp, XFS_ATTR_FORK); if (error) return error; node = bp->b_addr; magic = be16_to_cpu(node->hdr.info.magic); if (magic == XFS_ATTR_LEAF_MAGIC || magic == XFS_ATTR3_LEAF_MAGIC) break; if (magic != XFS_DA_NODE_MAGIC && magic != XFS_DA3_NODE_MAGIC) { XFS_CORRUPTION_ERROR("xfs_attr_node_list(3)", XFS_ERRLEVEL_LOW, context->dp->i_mount, node); xfs_trans_brelse(NULL, bp); return -EFSCORRUPTED; } dp->d_ops->node_hdr_from_disk(&nodehdr, node); btree = dp->d_ops->node_tree_p(node); for (i = 0; i < nodehdr.count; btree++, i++) { if (cursor->hashval <= be32_to_cpu(btree->hashval)) { cursor->blkno = be32_to_cpu(btree->before); trace_xfs_attr_list_node_descend(context, btree); break; } } if (i == nodehdr.count) { xfs_trans_brelse(NULL, bp); return 0; } xfs_trans_brelse(NULL, bp); } } ASSERT(bp != NULL); /* * Roll upward through the blocks, processing each leaf block in * order. As long as there is space in the result buffer, keep * adding the information. */ for (;;) { leaf = bp->b_addr; error = xfs_attr3_leaf_list_int(bp, context); if (error) { xfs_trans_brelse(NULL, bp); return error; } xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &leafhdr, leaf); if (context->seen_enough || leafhdr.forw == 0) break; cursor->blkno = leafhdr.forw; xfs_trans_brelse(NULL, bp); error = xfs_attr3_leaf_read(NULL, dp, cursor->blkno, -1, &bp); if (error) return error; } xfs_trans_brelse(NULL, bp); return 0; } /* * Copy out attribute list entries for attr_list(), for leaf attribute lists. */ int xfs_attr3_leaf_list_int( struct xfs_buf *bp, struct xfs_attr_list_context *context) { struct attrlist_cursor_kern *cursor; struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entries; struct xfs_attr_leaf_entry *entry; int retval; int i; struct xfs_mount *mp = context->dp->i_mount; trace_xfs_attr_list_leaf(context); leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(mp->m_attr_geo, &ichdr, leaf); entries = xfs_attr3_leaf_entryp(leaf); cursor = context->cursor; cursor->initted = 1; /* * Re-find our place in the leaf block if this is a new syscall. */ if (context->resynch) { entry = &entries[0]; for (i = 0; i < ichdr.count; entry++, i++) { if (be32_to_cpu(entry->hashval) == cursor->hashval) { if (cursor->offset == context->dupcnt) { context->dupcnt = 0; break; } context->dupcnt++; } else if (be32_to_cpu(entry->hashval) > cursor->hashval) { context->dupcnt = 0; break; } } if (i == ichdr.count) { trace_xfs_attr_list_notfound(context); return 0; } } else { entry = &entries[0]; i = 0; } context->resynch = 0; /* * We have found our place, start copying out the new attributes. */ retval = 0; for (; i < ichdr.count; entry++, i++) { if (be32_to_cpu(entry->hashval) != cursor->hashval) { cursor->hashval = be32_to_cpu(entry->hashval); cursor->offset = 0; } if (entry->flags & XFS_ATTR_INCOMPLETE) continue; /* skip incomplete entries */ if (entry->flags & XFS_ATTR_LOCAL) { xfs_attr_leaf_name_local_t *name_loc = xfs_attr3_leaf_name_local(leaf, i); retval = context->put_listent(context, entry->flags, name_loc->nameval, (int)name_loc->namelen, be16_to_cpu(name_loc->valuelen), &name_loc->nameval[name_loc->namelen]); if (retval) return retval; } else { xfs_attr_leaf_name_remote_t *name_rmt = xfs_attr3_leaf_name_remote(leaf, i); int valuelen = be32_to_cpu(name_rmt->valuelen); if (context->put_value) { xfs_da_args_t args; memset((char *)&args, 0, sizeof(args)); args.geo = context->dp->i_mount->m_attr_geo; args.dp = context->dp; args.whichfork = XFS_ATTR_FORK; args.valuelen = valuelen; args.rmtvaluelen = valuelen; args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS); args.rmtblkno = be32_to_cpu(name_rmt->valueblk); args.rmtblkcnt = xfs_attr3_rmt_blocks( args.dp->i_mount, valuelen); retval = xfs_attr_rmtval_get(&args); if (retval) return retval; retval = context->put_listent(context, entry->flags, name_rmt->name, (int)name_rmt->namelen, valuelen, args.value); kmem_free(args.value); } else { retval = context->put_listent(context, entry->flags, name_rmt->name, (int)name_rmt->namelen, valuelen, NULL); } if (retval) return retval; } if (context->seen_enough) break; cursor->offset++; } trace_xfs_attr_list_leaf_end(context); return retval; } /* * Copy out attribute entries for attr_list(), for leaf attribute lists. */ STATIC int xfs_attr_leaf_list(xfs_attr_list_context_t *context) { int error; struct xfs_buf *bp; trace_xfs_attr_leaf_list(context); context->cursor->blkno = 0; error = xfs_attr3_leaf_read(NULL, context->dp, 0, -1, &bp); if (error) return error; error = xfs_attr3_leaf_list_int(bp, context); xfs_trans_brelse(NULL, bp); return error; } int xfs_attr_list_int( xfs_attr_list_context_t *context) { int error; xfs_inode_t *dp = context->dp; uint lock_mode; XFS_STATS_INC(xs_attr_list); if (XFS_FORCED_SHUTDOWN(dp->i_mount)) return -EIO; /* * Decide on what work routines to call based on the inode size. */ lock_mode = xfs_ilock_attr_map_shared(dp); if (!xfs_inode_hasattr(dp)) { error = 0; } else if (dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) { error = xfs_attr_shortform_list(context); } else if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) { error = xfs_attr_leaf_list(context); } else { error = xfs_attr_node_list(context); } xfs_iunlock(dp, lock_mode); return error; } #define ATTR_ENTBASESIZE /* minimum bytes used by an attr */ \ (((struct attrlist_ent *) 0)->a_name - (char *) 0) #define ATTR_ENTSIZE(namelen) /* actual bytes used by an attr */ \ ((ATTR_ENTBASESIZE + (namelen) + 1 + sizeof(u_int32_t)-1) \ & ~(sizeof(u_int32_t)-1)) /* * Format an attribute and copy it out to the user's buffer. * Take care to check values and protect against them changing later, * we may be reading them directly out of a user buffer. */ STATIC int xfs_attr_put_listent( xfs_attr_list_context_t *context, int flags, unsigned char *name, int namelen, int valuelen, unsigned char *value) { struct attrlist *alist = (struct attrlist *)context->alist; attrlist_ent_t *aep; int arraytop; ASSERT(!(context->flags & ATTR_KERNOVAL)); ASSERT(context->count >= 0); ASSERT(context->count < (ATTR_MAX_VALUELEN/8)); ASSERT(context->firstu >= sizeof(*alist)); ASSERT(context->firstu <= context->bufsize); /* * Only list entries in the right namespace. */ if (((context->flags & ATTR_SECURE) == 0) != ((flags & XFS_ATTR_SECURE) == 0)) return 0; if (((context->flags & ATTR_ROOT) == 0) != ((flags & XFS_ATTR_ROOT) == 0)) return 0; arraytop = sizeof(*alist) + context->count * sizeof(alist->al_offset[0]); context->firstu -= ATTR_ENTSIZE(namelen); if (context->firstu < arraytop) { trace_xfs_attr_list_full(context); alist->al_more = 1; context->seen_enough = 1; return 1; } aep = (attrlist_ent_t *)&context->alist[context->firstu]; aep->a_valuelen = valuelen; memcpy(aep->a_name, name, namelen); aep->a_name[namelen] = 0; alist->al_offset[context->count++] = context->firstu; alist->al_count = context->count; trace_xfs_attr_list_add(context); return 0; } /* * Generate a list of extended attribute names and optionally * also value lengths. Positive return value follows the XFS * convention of being an error, zero or negative return code * is the length of the buffer returned (negated), indicating * success. */ int xfs_attr_list( xfs_inode_t *dp, char *buffer, int bufsize, int flags, attrlist_cursor_kern_t *cursor) { xfs_attr_list_context_t context; struct attrlist *alist; int error; /* * Validate the cursor. */ if (cursor->pad1 || cursor->pad2) return -EINVAL; if ((cursor->initted == 0) && (cursor->hashval || cursor->blkno || cursor->offset)) return -EINVAL; /* * Check for a properly aligned buffer. */ if (((long)buffer) & (sizeof(int)-1)) return -EFAULT; if (flags & ATTR_KERNOVAL) bufsize = 0; /* * Initialize the output buffer. */ memset(&context, 0, sizeof(context)); context.dp = dp; context.cursor = cursor; context.resynch = 1; context.flags = flags; context.alist = buffer; context.bufsize = (bufsize & ~(sizeof(int)-1)); /* align */ context.firstu = context.bufsize; context.put_listent = xfs_attr_put_listent; alist = (struct attrlist *)context.alist; alist->al_count = 0; alist->al_more = 0; alist->al_offset[0] = context.bufsize; error = xfs_attr_list_int(&context); ASSERT(error <= 0); return error; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.J2C = { validate(buffer) { // TODO: this doesn't seem right. SIZ marker doesnt have to be right after the SOC return buffer.toString('hex', 0, 4) === 'ff4fff51'; }, calculate(buffer) { return { height: buffer.readUInt32BE(12), width: buffer.readUInt32BE(8), }; } };
/***************************************************************************/ /* */ /* afhints.h */ /* */ /* Auto-fitter hinting routines (specification). */ /* */ /* Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __AFHINTS_H__ #define __AFHINTS_H__ #include "aftypes.h" #define xxAF_SORT_SEGMENTS FT_BEGIN_HEADER /* * The definition of outline glyph hints. These are shared by all * script analysis routines (until now). */ typedef enum AF_Dimension_ { AF_DIMENSION_HORZ = 0, /* x coordinates, */ /* i.e., vertical segments & edges */ AF_DIMENSION_VERT = 1, /* y coordinates, */ /* i.e., horizontal segments & edges */ AF_DIMENSION_MAX /* do not remove */ } AF_Dimension; /* hint directions -- the values are computed so that two vectors are */ /* in opposite directions iff `dir1 + dir2 == 0' */ typedef enum AF_Direction_ { AF_DIR_NONE = 4, AF_DIR_RIGHT = 1, AF_DIR_LEFT = -1, AF_DIR_UP = 2, AF_DIR_DOWN = -2 } AF_Direction; /* point hint flags */ typedef enum AF_Flags_ { AF_FLAG_NONE = 0, /* point type flags */ AF_FLAG_CONIC = 1 << 0, AF_FLAG_CUBIC = 1 << 1, AF_FLAG_CONTROL = AF_FLAG_CONIC | AF_FLAG_CUBIC, /* point extremum flags */ AF_FLAG_EXTREMA_X = 1 << 2, AF_FLAG_EXTREMA_Y = 1 << 3, /* point roundness flags */ AF_FLAG_ROUND_X = 1 << 4, AF_FLAG_ROUND_Y = 1 << 5, /* point touch flags */ AF_FLAG_TOUCH_X = 1 << 6, AF_FLAG_TOUCH_Y = 1 << 7, /* candidates for weak interpolation have this flag set */ AF_FLAG_WEAK_INTERPOLATION = 1 << 8, /* all inflection points in the outline have this flag set */ AF_FLAG_INFLECTION = 1 << 9 } AF_Flags; /* edge hint flags */ typedef enum AF_Edge_Flags_ { AF_EDGE_NORMAL = 0, AF_EDGE_ROUND = 1 << 0, AF_EDGE_SERIF = 1 << 1, AF_EDGE_DONE = 1 << 2 } AF_Edge_Flags; typedef struct AF_PointRec_* AF_Point; typedef struct AF_SegmentRec_* AF_Segment; typedef struct AF_EdgeRec_* AF_Edge; typedef struct AF_PointRec_ { FT_UShort flags; /* point flags used by hinter */ FT_Char in_dir; /* direction of inwards vector */ FT_Char out_dir; /* direction of outwards vector */ FT_Pos ox, oy; /* original, scaled position */ FT_Short fx, fy; /* original, unscaled position (font units) */ FT_Pos x, y; /* current position */ FT_Pos u, v; /* current (x,y) or (y,x) depending on context */ AF_Point next; /* next point in contour */ AF_Point prev; /* previous point in contour */ } AF_PointRec; typedef struct AF_SegmentRec_ { FT_Byte flags; /* edge/segment flags for this segment */ FT_Char dir; /* segment direction */ FT_Short pos; /* position of segment */ FT_Short min_coord; /* minimum coordinate of segment */ FT_Short max_coord; /* maximum coordinate of segment */ FT_Short height; /* the hinted segment height */ AF_Edge edge; /* the segment's parent edge */ AF_Segment edge_next; /* link to next segment in parent edge */ AF_Segment link; /* (stem) link segment */ AF_Segment serif; /* primary segment for serifs */ FT_Pos num_linked; /* number of linked segments */ FT_Pos score; /* used during stem matching */ FT_Pos len; /* used during stem matching */ AF_Point first; /* first point in edge segment */ AF_Point last; /* last point in edge segment */ AF_Point* contour; /* ptr to first point of segment's contour */ } AF_SegmentRec; typedef struct AF_EdgeRec_ { FT_Short fpos; /* original, unscaled position (font units) */ FT_Pos opos; /* original, scaled position */ FT_Pos pos; /* current position */ FT_Byte flags; /* edge flags */ FT_Char dir; /* edge direction */ FT_Fixed scale; /* used to speed mUp interpolation between edges */ AF_Width blue_edge; /* non-NULL if this is a blue edge */ AF_Edge link; AF_Edge serif; FT_Short num_linked; FT_Int score; AF_Segment first; AF_Segment last; } AF_EdgeRec; typedef struct AF_AxisHintsRec_ { FT_Int num_segments; FT_Int max_segments; AF_Segment segments; #ifdef AF_SORT_SEGMENTS FT_Int mid_segments; #endif FT_Int num_edges; FT_Int max_edges; AF_Edge edges; AF_Direction major_dir; } AF_AxisHintsRec, *AF_AxisHints; typedef struct AF_GlyphHintsRec_ { FT_Memory memory; FT_Fixed x_scale; FT_Pos x_delta; FT_Fixed y_scale; FT_Pos y_delta; FT_Pos edge_distance_threshold; FT_Int max_points; FT_Int num_points; AF_Point points; FT_Int max_contours; FT_Int num_contours; AF_Point* contours; AF_AxisHintsRec axis[AF_DIMENSION_MAX]; FT_UInt32 scaler_flags; /* copy of scaler flags */ FT_UInt32 other_flags; /* free for script-specific */ /* implementations */ AF_ScriptMetrics metrics; FT_Pos xmin_delta; /* used for warping */ FT_Pos xmax_delta; } AF_GlyphHintsRec; #define AF_HINTS_TEST_SCALER( h, f ) ( (h)->scaler_flags & (f) ) #define AF_HINTS_TEST_OTHER( h, f ) ( (h)->other_flags & (f) ) #ifdef AF_DEBUG #define AF_HINTS_DO_HORIZONTAL( h ) \ ( !_af_debug_disable_horz_hints && \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_HORIZONTAL ) ) #define AF_HINTS_DO_VERTICAL( h ) \ ( !_af_debug_disable_vert_hints && \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_VERTICAL ) ) #define AF_HINTS_DO_ADVANCE( h ) \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_ADVANCE ) #define AF_HINTS_DO_BLUES( h ) ( !_af_debug_disable_blue_hints ) #else /* !AF_DEBUG */ #define AF_HINTS_DO_HORIZONTAL( h ) \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_HORIZONTAL ) #define AF_HINTS_DO_VERTICAL( h ) \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_VERTICAL ) #define AF_HINTS_DO_ADVANCE( h ) \ !AF_HINTS_TEST_SCALER( h, AF_SCALER_FLAG_NO_ADVANCE ) #define AF_HINTS_DO_BLUES( h ) 1 #endif /* !AF_DEBUG */ FT_LOCAL( AF_Direction ) af_direction_compute( FT_Pos dx, FT_Pos dy ); FT_LOCAL( FT_Error ) af_axis_hints_new_segment( AF_AxisHints axis, FT_Memory memory, AF_Segment *asegment ); FT_LOCAL( FT_Error) af_axis_hints_new_edge( AF_AxisHints axis, FT_Int fpos, AF_Direction dir, FT_Memory memory, AF_Edge *edge ); FT_LOCAL( void ) af_glyph_hints_init( AF_GlyphHints hints, FT_Memory memory ); /* * recompute all AF_Point in a AF_GlyphHints from the definitions * in a source outline */ FT_LOCAL( void ) af_glyph_hints_rescale( AF_GlyphHints hints, AF_ScriptMetrics metrics ); FT_LOCAL( FT_Error ) af_glyph_hints_reload( AF_GlyphHints hints, FT_Outline* outline ); FT_LOCAL( void ) af_glyph_hints_save( AF_GlyphHints hints, FT_Outline* outline ); FT_LOCAL( void ) af_glyph_hints_align_edge_points( AF_GlyphHints hints, AF_Dimension dim ); FT_LOCAL( void ) af_glyph_hints_align_strong_points( AF_GlyphHints hints, AF_Dimension dim ); FT_LOCAL( void ) af_glyph_hints_align_weak_points( AF_GlyphHints hints, AF_Dimension dim ); #ifdef AF_USE_WARPER FT_LOCAL( void ) af_glyph_hints_scale_dim( AF_GlyphHints hints, AF_Dimension dim, FT_Fixed scale, FT_Pos delta ); #endif FT_LOCAL( void ) af_glyph_hints_done( AF_GlyphHints hints ); /* */ #define AF_SEGMENT_LEN( seg ) ( (seg)->max_coord - (seg)->min_coord ) #define AF_SEGMENT_DIST( seg1, seg2 ) ( ( (seg1)->pos > (seg2)->pos ) \ ? (seg1)->pos - (seg2)->pos \ : (seg2)->pos - (seg1)->pos ) FT_END_HEADER #endif /* __AFHINTS_H__ */ /* END */
//Evaluate these: //#1 [2] === [2] //false {} === {} //false //#2 what is the value of property a for each object. const object1 = { a: 5 }; //4 const object2 = object1; //4 const object3 = object2; //4 const object4 = { a: 5}; //5 object1.a = 4; //#3 create two classes: an Animal class and a Mamal class. // create a cow that accepts a name, type and color and has a sound method that moo's her name, type and color. class Animal{ constructor(name,type,color){ this.name=name; this.type=type; this.color=color; } } class Mamal extends Animal{ constructor(name,type,color){ super(name,type,color); } sound() { console.log(`Moooo I'm ${this.name} and I'm a ${this.color} ${this.type}`); } } const cow = new Mamal('Shelly', 'cow', 'brown');