prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>types.py<|end_file_name|><|fim▁begin|>import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators import id_code_ee_is_valid PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple( "AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # Base64-encoded DER-encoded certificate ], ) SignResult = namedtuple( "SignResult", [ "session_id", "digest", "verification_code", ], ) # Note: MobileID doesn't return a certificate for SignStatus. It is set from a previous call to `/certificate` SignStatusResult = namedtuple( "SignStatusResult", [ "signature", "signature_algorithm", "certificate", ], ) class UserInput(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, self.phone_number): if not raise_exception:<|fim▁hole|> if not raise_exception: return False raise InvalidIdCode if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData): session_id: str<|fim▁end|>
return False raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code):
<|file_name|>SceneManager.hpp<|end_file_name|><|fim▁begin|>#pragma once //! Include the SDL2_Engine objects #include "../__LibraryManagement.hpp" #include "../Utilities/IGlobal.hpp" #include "../Utilities/TypeID.hpp" namespace SDL2_Engine { //! Prototype the Scene Manager Initialiser object namespace Initialisation { struct SceneManagerInitialiser; } namespace Scenes { //! Prototype the ISceneBase object class ISceneBase; /* * Name: SceneManager * Author: Mitchell Croft * Created: 11/10/2017 * Modified: 06/11/2017 * * Purpose: * Provide an interface for controlling the updating and rendering of * 'scenes' throughout the runtime of the program **/ class SDL2_LIB_INC SceneManager : public Utilities::IGlobal { public: ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////----------------------------------Management Functions-------------------------------//////// ///////////////////////////////////////////////////////////////////////////////////////////////////// /* SceneManager : addScene - Add a new Scene of a specified type with specified values Created: 11/10/2017 Modified: 11/10/2017 Template T - The type of Scene to create Template TArgs - A parameter pack of types used to setup the new Scene param[in] pArgs - A parameter pack of values used to setup the new Scene return bool - Returns true if the Scene was successfully created and introduced to the Manager */ template<typename T, typename ... TArgs> inline bool addScene(TArgs ... pArgs) { //Ensure the template is of the correct type static_assert(std::is_base_of<ISceneBase, T>::value, "Can not add a type that is not a subclass of ISceneBase as a new Scene in the Scene Manager"); //Initialise the new Scene return initialiseScene(new T(pArgs...), Utilities::typeToID<T>()); } /* SceneManager : retrieveScene - Retrieve the first active Scene of the specified type Created: 06/11/2017 Modified: 06/11/2017 Template T - The type of Scene to retrieve return T* - Returns a pointer to the first Scene of type T or nullptr if not found */ template<typename T> inline T* retrieveScene() { //Ensure the template is of the correct type static_assert(std::is_base_of<ISceneBase, T>::value, "Can not retrieve a type that is not a subclass of ISceneBase from the Scene Manager"); //Find the Scene return (T*)retrieveScene(Utilities::typeToID<T>()); } /* SceneManager : retrieveScene - Retrieve the first active Scene of the specified type Created: 06/11/2017 Modified: 06/11/2017 param[in] pID - The Type ID of the Scene to retrieve return ISceneBase* - Returns a pointer to the first active Scene of with a matching typeID or nullptr if not found */ ISceneBase* retrieveScene(const Utilities::typeID& pID); /* SceneManager : removeScene - Flag the first Scene of the specified type for removal Created: 11/10/2017 Modified: 11/10/2017 Template T - The type of Scene to remove return bool - Returns true if a Scene of the specified type was flagged */ template<typename T> inline bool removeScene() { //Ensure the template is of the correct type static_assert(std::is_base_of<ISceneBase, T>::value, "Can not remove a type that is not a subclass of ISceneBase from the Scene Manager"); return removeScene(Utilities::typeToID<T>()); } /* SceneManager : removeScene - Flag the first scene of the specified type for removal Created: 11/10/2017 Modified: 11/10/2017 param[in] pID - The Type ID of the Scene to remove return bool - Returns true if a Scene of the specified type was flagged */ bool removeScene(const Utilities::typeID& pID); /* SceneManager : removeScenes - Flag all scenes of the specified type for removal Created: 11/10/2017 Modified: 11/10/2017 Template T - The type of Scene to remove return bool - Returns true if a Scene of the specified type was flagged */ template<typename T> inline bool removeScenes() { //Ensure the template is of the correct type static_assert(std::is_base_of<ISceneBase, T>::value, "Can not remove a type that is not a subclass of ISceneBase from the Scene Manager"); return removeScenes(Utilities::typeToID<T>()); } /* SceneManager : removeScenes - Flag of scenes of the specified type for removal Created: 11/10/2017 Modified: 11/10/2017 param[in] pID - The Type ID of the Scene to remove return bool - Returns true if a Scene of the specified type was flagged */ bool removeScenes(const Utilities::typeID& pID); /* SceneManager : quit - Flag to the program that it should terminate Created: 11/10/2017 Modified: 11/10/2017 */ void quit(); ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////-------------------------------------Data Accessors----------------------------------//////// ///////////////////////////////////////////////////////////////////////////////////////////////////// /* SceneManager : isRunning - Get the running flag of the program Created: 11/10/2017<|fim▁hole|> Modified: 11/10/2017 return const bool& - Returns a constant reference to the running flag */ const bool& isRunning() const; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////--------------------------------Construction/Destruction-----------------------------//////// ///////////////////////////////////////////////////////////////////////////////////////////////////// /* SceneManager : Constructor - Initialise with default values Created: 11/10/2017 Modified: 11/10/2017 param[in] pSetup - Defines how the Scene Manager should be setup */ SceneManager(Initialisation::SceneManagerInitialiser* pSetup); /* SceneManager : createInterface - Verify and setup starting information Created: 11/10/2017 Modified: 11/10/2017 return bool - Returns true if the Resources Manager was setup correctly */ bool createInterface() override; /* SceneManager : destroyInterface - Deallocate internal memory allocated Created: 11/10/2017 Modified: 11/10/2017 */ void destroyInterface() override; /* SceneManager : update - Update and render the contained Scenes Created: 11/10/2017 Modified: 02/11/2017 */ void update() override; private: //! Define the internal protected elements for the Renderer struct SceneManagerInternalData; SceneManagerInternalData* mData; //! Initialise a new scene bool initialiseScene(ISceneBase* pScene, const Utilities::typeID& pID); }; } }<|fim▁end|>
<|file_name|>AsymmetricMatcher.test.ts<|end_file_name|><|fim▁begin|>/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {OptionsReceived} from '../types'; import prettyFormat from '../'; const {AsymmetricMatcher} = prettyFormat.plugins; let options: OptionsReceived; function fnNameFor(func: (...any: Array<any>) => any) { if (func.name) { return func.name; } const matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/); return matches ? matches[1] : '<anonymous>'; } beforeEach(() => { options = {plugins: [AsymmetricMatcher]}; }); [ String, Function, Array, Object, RegExp, Symbol, Function, () => {}, function namedFuntction() {}, ].forEach(type => { test(`supports any(${fnNameFor(type)})`, () => { const result = prettyFormat(expect.any(type), options); expect(result).toEqual(`Any<${fnNameFor(type)}>`); }); test(`supports nested any(${fnNameFor(type)})`, () => { const result = prettyFormat( { test: { nested: expect.any(type), }, }, options, ); expect(result).toEqual( `Object {\n "test": Object {\n "nested": Any<${fnNameFor( type, )}>,\n },\n}`, ); }); }); test(`anything()`, () => { const result = prettyFormat(expect.anything(), options); expect(result).toEqual('Anything'); }); test(`arrayContaining()`, () => {<|fim▁hole|>]`); }); test(`arrayNotContaining()`, () => { const result = prettyFormat(expect.not.arrayContaining([1, 2]), options); expect(result).toEqual(`ArrayNotContaining [ 1, 2, ]`); }); test(`objectContaining()`, () => { const result = prettyFormat(expect.objectContaining({a: 'test'}), options); expect(result).toEqual(`ObjectContaining { "a": "test", }`); }); test(`objectNotContaining()`, () => { const result = prettyFormat( expect.not.objectContaining({a: 'test'}), options, ); expect(result).toEqual(`ObjectNotContaining { "a": "test", }`); }); test(`stringContaining(string)`, () => { const result = prettyFormat(expect.stringContaining('jest'), options); expect(result).toEqual(`StringContaining "jest"`); }); test(`not.stringContaining(string)`, () => { const result = prettyFormat(expect.not.stringContaining('jest'), options); expect(result).toEqual(`StringNotContaining "jest"`); }); test(`stringMatching(string)`, () => { const result = prettyFormat(expect.stringMatching('jest'), options); expect(result).toEqual('StringMatching /jest/'); }); test(`stringMatching(regexp)`, () => { const result = prettyFormat(expect.stringMatching(/(jest|niema).*/), options); expect(result).toEqual('StringMatching /(jest|niema).*/'); }); test(`stringMatching(regexp) {escapeRegex: false}`, () => { const result = prettyFormat(expect.stringMatching(/regexp\d/gi), options); expect(result).toEqual('StringMatching /regexp\\d/gi'); }); test(`stringMatching(regexp) {escapeRegex: true}`, () => { options.escapeRegex = true; const result = prettyFormat(expect.stringMatching(/regexp\d/gi), options); expect(result).toEqual('StringMatching /regexp\\\\d/gi'); }); test(`stringNotMatching(string)`, () => { const result = prettyFormat(expect.not.stringMatching('jest'), options); expect(result).toEqual('StringNotMatching /jest/'); }); test(`supports multiple nested asymmetric matchers`, () => { const result = prettyFormat( { test: { nested: expect.objectContaining({ a: expect.arrayContaining([1]), b: expect.anything(), c: expect.any(String), d: expect.stringContaining('jest'), e: expect.stringMatching('jest'), f: expect.objectContaining({test: 'case'}), }), }, }, options, ); expect(result).toEqual(`Object { "test": Object { "nested": ObjectContaining { "a": ArrayContaining [ 1, ], "b": Anything, "c": Any<String>, "d": StringContaining "jest", "e": StringMatching /jest/, "f": ObjectContaining { "test": "case", }, }, }, }`); }); describe(`indent option`, () => { const val = { nested: expect.objectContaining({ a: expect.arrayContaining([1]), b: expect.anything(), c: expect.any(String), d: expect.stringContaining('jest'), e: expect.stringMatching('jest'), f: expect.objectContaining({ composite: ['exact', 'match'], primitive: 'string', }), }), }; const result = `Object { "nested": ObjectContaining { "a": ArrayContaining [ 1, ], "b": Anything, "c": Any<String>, "d": StringContaining "jest", "e": StringMatching /jest/, "f": ObjectContaining { "composite": Array [ "exact", "match", ], "primitive": "string", }, }, }`; test(`default implicit: 2 spaces`, () => { expect(prettyFormat(val, options)).toEqual(result); }); test(`default explicit: 2 spaces`, () => { options.indent = 2; expect(prettyFormat(val, options)).toEqual(result); }); // Tests assume that no strings in val contain multiple adjacent spaces! test(`non-default: 0 spaces`, () => { options.indent = 0; expect(prettyFormat(val, options)).toEqual(result.replace(/ {2}/g, '')); }); test('non-default: 4 spaces', () => { options.indent = 4; expect(prettyFormat(val, options)).toEqual( result.replace(/ {2}/g, ' '.repeat(4)), ); }); }); describe(`maxDepth option`, () => { test(`matchers as leaf nodes`, () => { options.maxDepth = 2; const val = { // ++depth === 1 nested: [ // ++depth === 2 expect.arrayContaining( // ++depth === 3 [1], ), expect.objectContaining({ // ++depth === 3 composite: ['exact', 'match'], primitive: 'string', }), expect.stringContaining('jest'), expect.stringMatching('jest'), expect.any(String), expect.anything(), ], }; const result = prettyFormat(val, options); expect(result).toEqual(`Object { "nested": Array [ [ArrayContaining], [ObjectContaining], StringContaining "jest", StringMatching /jest/, Any<String>, Anything, ], }`); }); test(`matchers as internal nodes`, () => { options.maxDepth = 2; const val = [ // ++depth === 1 expect.arrayContaining([ // ++depth === 2 'printed', { // ++depth === 3 properties: 'not printed', }, ]), expect.objectContaining({ // ++depth === 2 array: [ // ++depth === 3 'items', 'not', 'printed', ], primitive: 'printed', }), ]; const result = prettyFormat(val, options); expect(result).toEqual(`Array [ ArrayContaining [ "printed", [Object], ], ObjectContaining { "array": [Array], "primitive": "printed", }, ]`); }); }); test(`min option`, () => { options.min = true; const result = prettyFormat( { test: { nested: expect.objectContaining({ a: expect.arrayContaining([1]), b: expect.anything(), c: expect.any(String), d: expect.stringContaining('jest'), e: expect.stringMatching('jest'), f: expect.objectContaining({test: 'case'}), }), }, }, options, ); expect(result).toEqual( `{"test": {"nested": ObjectContaining {"a": ArrayContaining [1], "b": Anything, "c": Any<String>, "d": StringContaining "jest", "e": StringMatching /jest/, "f": ObjectContaining {"test": "case"}}}}`, ); });<|fim▁end|>
const result = prettyFormat(expect.arrayContaining([1, 2]), options); expect(result).toEqual(`ArrayContaining [ 1, 2,
<|file_name|>splif_fingerprints.py<|end_file_name|><|fim▁begin|>""" SPLIF Fingerprints for molecular complexes. """ import logging import itertools import numpy as np from deepchem.utils.hash_utils import hash_ecfp_pair from deepchem.utils.rdkit_utils import load_complex from deepchem.utils.rdkit_utils import compute_all_ecfp from deepchem.utils.rdkit_utils import MoleculeLoadException from deepchem.utils.rdkit_utils import compute_contact_centroid from deepchem.feat import ComplexFeaturizer from deepchem.utils.hash_utils import vectorize from deepchem.utils.voxel_utils import voxelize from deepchem.utils.voxel_utils import convert_atom_pair_to_voxel from deepchem.utils.geometry_utils import compute_pairwise_distances from deepchem.utils.geometry_utils import subtract_centroid from typing import Tuple, Dict, List logger = logging.getLogger(__name__) SPLIF_CONTACT_BINS = [(0, 2.0), (2.0, 3.0), (3.0, 4.5)] def compute_splif_features_in_range(frag1: Tuple, frag2: Tuple, pairwise_distances: np.ndarray, contact_bin: List, ecfp_degree: int = 2) -> Dict: """Computes SPLIF features for close atoms in molecular complexes. Finds all frag1 atoms that are > contact_bin[0] and < contact_bin[1] away from frag2 atoms. Then, finds the ECFP fingerprints for the contacting atoms. Returns a dictionary mapping (frag1_index_i, frag2_index_j) --> (frag1_ecfp_i, frag2_ecfp_j) Parameters ---------- frag1: Tuple A tuple of (coords, mol) returned by `load_molecule`. frag2: Tuple A tuple of (coords, mol) returned by `load_molecule`. contact_bins: np.ndarray Ranges of pair distances which are placed in separate bins. pairwise_distances: np.ndarray Array of pairwise fragment-fragment distances (Angstroms) ecfp_degree: int ECFP radius """ contacts = np.nonzero((pairwise_distances > contact_bin[0]) & (pairwise_distances < contact_bin[1])) frag1_atoms = set([int(c) for c in contacts[0].tolist()]) frag1_ecfp_dict = compute_all_ecfp( frag1[1], indices=frag1_atoms, degree=ecfp_degree) frag2_ecfp_dict = compute_all_ecfp(frag2[1], degree=ecfp_degree) splif_dict = { contact: (frag1_ecfp_dict[contact[0]], frag2_ecfp_dict[contact[1]]) for contact in zip(contacts[0], contacts[1]) } return splif_dict def featurize_splif(frag1, frag2, contact_bins, pairwise_distances, ecfp_degree): """Computes SPLIF featurization of fragment interactions binding pocket. For each contact range (i.e. 1 A to 2 A, 2 A to 3 A, etc.) compute a dictionary mapping (frag1_index_i, frag2_index_j) tuples --> (frag1_ecfp_i, frag2_ecfp_j) tuples. Return a list of such splif dictionaries. Parameters ---------- frag1: Tuple A tuple of (coords, mol) returned by `load_molecule`. frag2: Tuple A tuple of (coords, mol) returned by `load_molecule`. contact_bins: np.ndarray Ranges of pair distances which are placed in separate bins. pairwise_distances: np.ndarray Array of pairwise fragment-fragment distances (Angstroms) ecfp_degree: int ECFP radius, the graph distance at which fragments are computed. Returns ------- Dictionaries of SPLIF interactions suitable for `vectorize` or `voxelize`. """ splif_dicts = []<|fim▁hole|> splif_dicts.append( compute_splif_features_in_range(frag1, frag2, pairwise_distances, contact_bin, ecfp_degree)) return splif_dicts class SplifFingerprint(ComplexFeaturizer): """Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchmark study." Journal of chemical information and modeling 54.9 (2014): 2555-2561. SPLIF fingerprints are a subclass of `ComplexFeaturizer`. It requires 3D coordinates for a molecular complex. For each ligand atom, it identifies close pairs of atoms from different molecules. These atom pairs are expanded to 2D circular fragments and a fingerprint for the union is turned on in the bit vector. Note that we slightly generalize the original paper by not requiring the interacting molecules to be proteins or ligands. This is conceptually pretty similar to `ContactCircularFingerprint` but computes ECFP fragments only for direct contacts instead of the entire contact region. For a macromolecular complex, returns a vector of shape `(len(contact_bins)*size,)` """ def __init__(self, contact_bins=None, radius=2, size=8): """ Parameters ---------- contact_bins: list[tuple] List of contact bins. If not specified is set to default `[(0, 2.0), (2.0, 3.0), (3.0, 4.5)]`. radius : int, optional (default 2) Fingerprint radius used for circular fingerprints. size: int, optional (default 8) Length of generated bit vector. """ if contact_bins is None: self.contact_bins = SPLIF_CONTACT_BINS else: self.contact_bins = contact_bins self.size = size self.radius = radius def _featurize(self, datapoint, **kwargs): """ Compute featurization for a molecular complex Parameters ---------- datapoint: Tuple[str, str] Filenames for molecule and protein. """ if 'complex' in kwargs: datapoint = kwargs.get("complex") raise DeprecationWarning( 'Complex is being phased out as a parameter, please pass "datapoint" instead.' ) try: fragments = load_complex(datapoint, add_hydrogens=False) except MoleculeLoadException: logger.warning("This molecule cannot be loaded by Rdkit. Returning None") return None pairwise_features = [] # We compute pairwise contact fingerprints for (frag1, frag2) in itertools.combinations(fragments, 2): # Get coordinates distances = compute_pairwise_distances(frag1[0], frag2[0]) # distances = compute_pairwise_distances(prot_xyz, lig_xyz) vectors = [ vectorize(hash_ecfp_pair, feature_dict=splif_dict, size=self.size) for splif_dict in featurize_splif( frag1, frag2, self.contact_bins, distances, self.radius) ] pairwise_features += vectors pairwise_features = np.concatenate(pairwise_features) return pairwise_features class SplifVoxelizer(ComplexFeaturizer): """Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel in which they originated. This technique may be useful for downstream learning methods such as convolutional networks. Featurizes a macromolecular complex into a tensor of shape `(voxels_per_edge, voxels_per_edge, voxels_per_edge, size)` where `voxels_per_edge = int(box_width/voxel_width)`. References ---------- .. [1] Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchmark study." Journal of chemical information and modeling 54.9 (2014): 2555-2561. """ def __init__(self, cutoff: float = 4.5, contact_bins: List = None, radius: int = 2, size: int = 8, box_width: float = 16.0, voxel_width: float = 1.0): """ Parameters ---------- cutoff: float (default 4.5) Distance cutoff in angstroms for molecules in complex. contact_bins: list[tuple] List of contact bins. If not specified is set to default `[(0, 2.0), (2.0, 3.0), (3.0, 4.5)]`. radius : int, optional (default 2) Fingerprint radius used for circular fingerprints. size: int, optional (default 8) Length of generated bit vector. box_width: float, optional (default 16.0) Size of a box in which voxel features are calculated. Box is centered on a ligand centroid. voxel_width: float, optional (default 1.0) Size of a 3D voxel in a grid. """ self.cutoff = cutoff if contact_bins is None: self.contact_bins = SPLIF_CONTACT_BINS else: self.contact_bins = contact_bins self.size = size self.radius = radius self.box_width = box_width self.voxel_width = voxel_width self.voxels_per_edge = int(self.box_width / self.voxel_width) def _featurize(self, datapoint, **kwargs): """ Compute featurization for a molecular complex Parameters ---------- datapoint: Tuple[str, str] Filenames for molecule and protein. """ if 'complex' in kwargs: datapoint = kwargs.get("complex") raise DeprecationWarning( 'Complex is being phased out as a parameter, please pass "datapoint" instead.' ) try: fragments = load_complex(datapoint, add_hydrogens=False) except MoleculeLoadException: logger.warning("This molecule cannot be loaded by Rdkit. Returning None") return None pairwise_features = [] # We compute pairwise contact fingerprints centroid = compute_contact_centroid(fragments, cutoff=self.cutoff) for (frag1, frag2) in itertools.combinations(fragments, 2): distances = compute_pairwise_distances(frag1[0], frag2[0]) frag1_xyz = subtract_centroid(frag1[0], centroid) frag2_xyz = subtract_centroid(frag2[0], centroid) xyzs = [frag1_xyz, frag2_xyz] pairwise_features.append( np.concatenate( [ voxelize( convert_atom_pair_to_voxel, hash_function=hash_ecfp_pair, coordinates=xyzs, box_width=self.box_width, voxel_width=self.voxel_width, feature_dict=splif_dict, nb_channel=self.size) for splif_dict in featurize_splif( frag1, frag2, self.contact_bins, distances, self.radius) ], axis=-1)) # Features are of shape (voxels_per_edge, voxels_per_edge, voxels_per_edge, 1) so we should concatenate on the last axis. return np.concatenate(pairwise_features, axis=-1)<|fim▁end|>
for i, contact_bin in enumerate(contact_bins):
<|file_name|>_rvs_sampling.py<|end_file_name|><|fim▁begin|>import numpy as np from scipy._lib._util import check_random_state def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None): """ Generate random samples from a probability density function using the ratio-of-uniforms method. Parameters ---------- pdf : callable A function with signature `pdf(x)` that is proportional to the probability density function of the distribution. umax : float The upper bound of the bounding rectangle in the u-direction. vmin : float The lower bound of the bounding rectangle in the v-direction. vmax : float The upper bound of the bounding rectangle in the v-direction. size : int or tuple of ints, optional Defining number of random variates (default is 1). c : float, optional. Shift parameter of ratio-of-uniforms method, see Notes. Default is 0. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- rvs : ndarray The random variates distributed according to the probability distribution defined by the pdf. Notes ----- Given a univariate probability density function `pdf` and a constant `c`, define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``. If `(U, V)` is a random vector uniformly distributed over `A`, then `V/U + c` follows a distribution according to `pdf`. The above result (see [1]_, [2]_) can be used to sample random variables using only the pdf, i.e. no inversion of the cdf is required. Typical choices of `c` are zero or the mode of `pdf`. The set `A` is a subset of the rectangle ``R = [0, umax] x [vmin, vmax]`` where - ``umax = sup sqrt(pdf(x))`` - ``vmin = inf (x - c) sqrt(pdf(x))`` - ``vmax = sup (x - c) sqrt(pdf(x))`` In particular, these values are finite if `pdf` is bounded and ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails). One can generate `(U, V)` uniformly on `R` and return `V/U + c` if `(U, V)` are also in `A` which can be directly verified. The algorithm is not changed if one replaces `pdf` by k * `pdf` for any constant k > 0. Thus, it is often convenient to work with a function that is proportional to the probability density function by dropping unneccessary normalization factors. Intuitively, the method works well if `A` fills up most of the enclosing rectangle such that the probability is high that `(U, V)` lies in `A` whenever it lies in `R` as the number of required iterations becomes too large otherwise. To be more precise, note that the expected number of iterations to draw `(U, V)` uniformly distributed on `R` such that `(U, V)` is also in `A` is given by the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``, where `area(pdf)` is the integral of `pdf` (which is equal to one if the probability density function is used but can take on other values if a function proportional to the density is used). The equality holds since the area of `A` is equal to 0.5 * area(pdf) (Theorem 7.1 in [1]_). If the sampling fails to generate a single random variate after 50000 iterations (i.e. not a single draw is in `A`), an exception is raised. If the bounding rectangle is not correctly specified (i.e. if it does not contain `A`), the algorithm samples from a distribution different from the one given by `pdf`. It is therefore recommended to perform a test such as `~scipy.stats.kstest` as a check. References ---------- .. [1] L. Devroye, "Non-Uniform Random Variate Generation", Springer-Verlag, 1986. .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian random variates", Statistics and Computing, 24(4), p. 547--557, 2014. .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random Variables Using the Ratio of Uniform Deviates", ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977. Examples -------- >>> from scipy import stats >>> rng = np.random.default_rng() Simulate normally distributed random variables. It is easy to compute the bounding rectangle explicitly in that case. For simplicity, we drop the normalization factor of the density. >>> f = lambda x: np.exp(-x**2 / 2) >>> v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) >>> umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound >>> rvs = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=2500, ... random_state=rng) The K-S test confirms that the random variates are indeed normally distributed (normality is not rejected at 5% significance level): >>> stats.kstest(rvs, 'norm')[1] 0.250634764150542 The exponential distribution provides another example where the bounding rectangle can be determined explicitly. >>> rvs = stats.rvs_ratio_uniforms(lambda x: np.exp(-x), umax=1,<|fim▁hole|> >>> stats.kstest(rvs, 'expon')[1] 0.21121052054580314 """ if vmin >= vmax: raise ValueError("vmin must be smaller than vmax.") if umax <= 0: raise ValueError("umax must be positive.") size1d = tuple(np.atleast_1d(size)) N = np.prod(size1d) # number of rvs needed, reshape upon return # start sampling using ratio of uniforms method rng = check_random_state(random_state) x = np.zeros(N) simulated, i = 0, 1 # loop until N rvs have been generated: expected runtime is finite. # to avoid infinite loop, raise exception if not a single rv has been # generated after 50000 tries. even if the expected numer of iterations # is 1000, the probability of this event is (1-1/1000)**50000 # which is of order 10e-22 while simulated < N: k = N - simulated # simulate uniform rvs on [0, umax] and [vmin, vmax] u1 = umax * rng.uniform(size=k) v1 = rng.uniform(vmin, vmax, size=k) # apply rejection method rvs = v1 / u1 + c accept = (u1**2 <= pdf(rvs)) num_accept = np.sum(accept) if num_accept > 0: x[simulated:(simulated + num_accept)] = rvs[accept] simulated += num_accept if (simulated == 0) and (i*N >= 50000): msg = ("Not a single random variate could be generated in {} " "attempts. The ratio of uniforms method does not appear " "to work for the provided parameters. Please check the " "pdf and the bounds.".format(i*N)) raise RuntimeError(msg) i += 1 return np.reshape(x, size1d)<|fim▁end|>
... vmin=0, vmax=2*np.exp(-1), size=1000, ... random_state=rng)
<|file_name|>editor_id.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="id_ID"> <context> <name>AbstractRuntimeEngine</name> <message> <source>World map testing via IPC is not supported</source> <translation type="unfinished"></translation> </message> <message> <source>World map testing is not supported</source> <translation type="unfinished"></translation> </message> <message> <source>This feature is not implemented</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AppSettings</name> <message> <source>Settings</source> <translation type="unfinished"></translation> </message> <message> <source>Main</source> <translation type="unfinished"></translation> </message> <message> <source>Window layout</source> <translation type="unfinished"></translation> </message> <message> <source>Separate Sub-windows (Classic style)</source> <translation type="unfinished"></translation> </message> <message> <source>Tabbed Sub-windows (Modern style)</source> <translation type="unfinished"></translation> </message> <message> <source>Music player</source> <translation type="unfinished"></translation> </message> <message> <source>Music will automatically play when you open a level file</source> <comment>Pop-up hint text</comment> <translation type="unfinished"></translation> </message> <message> <source>Autoplay music after opening file</source> <translation type="unfinished"></translation> </message> <message> <source>Performance</source> <translation type="unfinished"></translation> </message> <message> <source>Animation</source> <translation type="unfinished"></translation> </message> <message> <source>Maximum number of elements which can be animated at any given time. If this limit is exceeded, animation will be paused until you raise the limit or remove excess elements.</source> <comment>Pop-up hint text</comment> <translation type="unfinished"></translation> </message> <message> <source>Animation items limit</source> <translation type="unfinished"></translation> </message> <message> <source>Collision detection</source> <translation type="unfinished"></translation> </message> <message> <source>Files</source> <translation type="unfinished"></translation> </message> <message> <source>Associate file extensions</source> <translation type="unfinished"></translation> </message> <message> <source>Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Middle mouse button actions</source> <translation type="unfinished"></translation> </message> <message> <source>Change the placement mode of the selected item</source> <translation type="unfinished"></translation> </message> <message> <source>Toggle drag-to-scroll while selection is empty</source> <translation type="unfinished"></translation> </message> <message> <source>Placement mode</source> <translation type="unfinished"></translation> </message> <message> <source>Properties box will not be shown atomatically when you select an item to place, like when choosing an item from the item toolbox or from the tileset item box.</source> <comment>Pop-up hint</comment> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t show properties box when placing items</source> <translation type="unfinished"></translation> </message> <message> <source>History</source> <translation type="unfinished"></translation> </message> <message> <source>Max history entries:</source> <translation type="unfinished"></translation> </message> <message> <source>Maximum number of remembered history actions.</source> <translation type="unfinished"></translation> </message> <message> <source>Screen capture default size</source> <translation type="unfinished"></translation> </message> <message> <source>Use custom:</source> <translation type="unfinished"></translation> </message> <message> <source>Width:</source> <translation type="unfinished"></translation> </message> <message> <source>Height:</source> <translation type="unfinished"></translation> </message> <message> <source>Fit to window size</source> <translation type="unfinished"></translation> </message> <message> <source>Defaults</source> <translation type="unfinished"></translation> </message> <message> <source>Classic Events tabs to auto-expand</source> <translation type="unfinished"></translation> </message> <message> <source>Common</source> <translation type="unfinished"></translation> </message> <message> <source>Layer movement</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger event</source> <translation type="unfinished"></translation> </message> <message> <source>Hold buttons</source> <translation type="unfinished"></translation> </message> <message> <source>Extra</source> <translation type="unfinished"></translation> </message> <message> <source>Note: Some of those settings will take change on application restart</source> <translation type="unfinished"></translation> </message> <message> <source>Enable auto-scaling on the High-DPI screens</source> <translation type="unfinished"></translation> </message> <message> <source>Copy selected items to cursor position</source> <translation type="unfinished"></translation> </message> <message> <source>Autoscroll section</source> <translation type="unfinished"></translation> </message> <message> <source>Layer visibility</source> <translation type="unfinished"></translation> </message> <message> <source>Section settings</source> <translation type="unfinished"></translation> </message> <message> <source>NPC settings</source> <translation type="unfinished"></translation> </message> <message> <source>Generator</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <source>Warp</source> <translation type="unfinished"></translation> </message> <message> <source>Projectile</source> <translation type="unfinished"></translation> </message> <message> <source>Delay (seconds):</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Warps and Doors</source> <translation type="unfinished"></translation> </message> <message> <source>Warp type:</source> <translation type="unfinished"></translation> </message> <message> <source>0 - Instant</source> <translation type="unfinished"></translation> </message> <message> <source>1 - Pipe</source> <translation type="unfinished"></translation> </message> <message> <source>2 - Door</source> <translation type="unfinished"></translation> </message> <message> <source>3 - Portal</source> <translation type="unfinished"></translation> </message> <message> <source>View</source> <translation type="unfinished"></translation> </message> <message> <source>World Map Item toolbox</source> <translation type="unfinished"></translation> </message> <message> <source>Display tabs horizontally</source> <translation type="unfinished"></translation> </message> <message> <source>Display tabs vertically</source> <translation type="unfinished"></translation> </message> <message> <source>Level Item toolbox</source> <translation type="unfinished"></translation> </message> <message> <source>Theme</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset Item toolbox</source> <translation type="unfinished"></translation> </message> <message> <source>Logging</source> <translation type="unfinished"></translation> </message> <message> <source>Log level</source> <translation type="unfinished"></translation> </message> <message> <source>Browse</source> <translation type="unfinished"></translation> </message> <message> <source>Log file</source> <translation type="unfinished"></translation> </message> <message> <source>Environment</source> <translation type="unfinished"></translation> </message> <message> <source>Default zoom:</source> <translation type="unfinished"></translation> </message> <message> <source>Default zoom which will be installed on file opening or file creation.</source> <translation type="unfinished"></translation> </message> <message> <source>Font</source> <translation type="unfinished"></translation> </message> <message> <source>Font size</source> <translation type="unfinished"></translation> </message> <message> <source>Use default</source> <translation type="unfinished"></translation> </message> <message> <source>Set log file</source> <translation type="unfinished"></translation> </message> <message> <source>Text files (*.txt *.log)</source> <translation type="unfinished"></translation> </message> <message> <source>Success</source> <translation type="unfinished"></translation> </message> <message> <source>All file associations have been set</source> <translation type="unfinished"></translation> </message> <message> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <source>Palette</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AsyncStarCounter</name> <message> <source>Calculating total star count in accessible levels</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>Counting stars...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioCvt_Sox_gui</name> <message> <source>Convert Audio (SoX)</source> <translation type="unfinished"></translation> </message> <message> <source>SoX executable path:</source> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Make backup</source> <translation type="unfinished"></translation> </message> <message> <source>Resample to</source> <translation type="unfinished"></translation> </message> <message> <source>Start</source> <translation type="unfinished"></translation> </message> <message> <source>SoX error</source> <translation type="unfinished"></translation> </message> <message> <source>SoX executable path is not defined. Please set SoX path first</source> <translation type="unfinished"></translation> </message> <message> <source>SoX executable path is invalid. Please set SoX path first</source> <translation type="unfinished"></translation> </message> <message> <source>Nothing to do.</source> <translation type="unfinished"></translation> </message> <message> <source>No files to convert</source> <translation type="unfinished"></translation> </message> <message> <source>Stop</source> <translation type="unfinished"></translation> </message> <message> <source>Operation canceled</source> <translation type="unfinished"></translation> </message> <message> <source>Sorry, SoX has crashed</source> <translation type="unfinished"></translation> </message> <message> <source>SoX returned a non-zero exit code: %1 %2</source> <translation type="unfinished"></translation> </message> <message> <source>Operation complete</source> <translation type="unfinished"></translation> </message> <message> <source>All files successfully converted! %1</source> <translation type="unfinished"></translation> </message> <message> <source>No tasks defined. Nothing to do.</source> <translation type="unfinished"></translation> </message> <message> <source>Open SoX executable path</source> <translation type="unfinished"></translation> </message> <message> <source>Select file to convert</source> <translation type="unfinished"></translation> </message> <message> <source>What do you want?</source> <translation type="unfinished"></translation> </message> <message> <source>Convert music of current level section</source> <translation type="unfinished"></translation> </message> <message> <source>Convert all music files on current level</source> <translation type="unfinished"></translation> </message> <message> <source>Convert specified files</source> <translation type="unfinished"></translation> </message> <message> <source>Convert into new format (select a tab to choose target format)</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t change format</source> <translation type="unfinished"></translation> </message> <message> <source>The files&apos; format will not be changed</source> <translation type="unfinished"></translation> </message> <message> <source>Set bitrate</source> <translation type="unfinished"></translation> </message> <message> <source>Files will be converted into MP3</source> <translation type="unfinished"></translation> </message> <message> <source>Files will be converted into FLAC</source> <translation type="unfinished"></translation> </message> <message> <source>Files will be converted into OGG</source> <translation type="unfinished"></translation> </message> <message> <source>Set quality</source> <translation type="unfinished"></translation> </message> <message> <source>Files will be converted into WAV</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Here you can quickly convert your music or SFX files which have been&lt;br&gt;formatted incorrectly (wrong sample rate, bad codec, etc.).&lt;/p&gt; &lt;p&gt;This feature uses the &lt;a href=&quot;http://sox.sourceforge.net/&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;SoX&lt;/span&gt;&lt;/a&gt; audio converter.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BankFileList</name> <message> <source>Select WOPL bank file</source> <translation type="unfinished"></translation> </message> <message> <source>Please select the WOPL instruments bank file to use</source> <translation type="unfinished"></translation> </message> <message> <source>Select WOPN bank file</source> <translation type="unfinished"></translation> </message> <message> <source>Please select the WOPN instruments bank file to use</source> <translation type="unfinished"></translation> </message> <message> <source>Select SoundFont bank file</source> <translation type="unfinished"></translation> </message> <message> <source>Please select the SoundFont bank file to add</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BlocksPerSecondDialog</name> <message> <source>Blocks per second calculator</source> <translation type="unfinished"></translation> </message> <message> <source> blocks</source> <translation type="unfinished"></translation> </message> <message> <source>per </source> <translation type="unfinished"></translation> </message> <message> <source> second</source> <translation type="unfinished"></translation> </message> <message> <source>Move time:</source> <translation type="unfinished"></translation> </message> <message> <source>Distance:</source> <translation type="unfinished"></translation> </message> <message> <source>Size of one block:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BookmarksBox</name> <message> <source>Position bookmarks</source> <translation type="unfinished"></translation> </message> <message> <source>Remove selected bookmark from list</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remember current screen position on the level map or on the world map and store a bookmark.</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Scroll to the saved position in the selected item. You also can double-click an item to scroll to its bookmarked position.</source> <translation type="unfinished"></translation> </message> <message> <source>Go To...</source> <translation type="unfinished"></translation> </message> <message> <source>Rename Bookmark</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ConfigManager</name> <message> <source>Configuration Manager</source> <translation type="unfinished"></translation> </message> <message> <source>Please select the game configuration you want to start the Editor with</source> <translation type="unfinished"></translation> </message> <message> <source>Ask every startup</source> <translation type="unfinished"></translation> </message> <message> <source>No config packs were found</source> <translation type="unfinished"></translation> </message> <message> <source>No configuration packages were found!&lt;br&gt; Please download and install them into this directory&lt;br&gt; &lt;br&gt; %1&lt;br&gt; &lt;br&gt; You can use any configuration package here:&lt;br&gt;%2</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration package is not configured!</source> <translation type="unfinished"></translation> </message> <message> <source>&quot;%1&quot; configuration package is not configured yet. Do you want to configure it?</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration script failed</source> <translation type="unfinished"></translation> </message> <message> <source>Configuring tool encountered an error: %1 at line %2. File path: %3</source> <translation type="unfinished"></translation> </message> <message> <source>No configuration needed</source> <translation type="unfinished"></translation> </message> <message> <source>This config pack has no configuring tool.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ConfigStatus</name> <message> <source>Current configuration status</source> <translation type="unfinished"></translation> </message> <message> <source>Status</source> <translation type="unfinished"></translation> </message> <message> <source>Objects defined:</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration name:</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration path:</source> <translation type="unfinished"></translation> </message> <message> <source>Directories</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration directories:</source> <translation type="unfinished"></translation> </message> <message> <source>Name</source> <translation type="unfinished"></translation> </message> <message> <source>Path</source> <translation type="unfinished"></translation> </message> <message> <source>Errors</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration Loading Errors:</source> <translation type="unfinished"></translation> </message> <message> <source>Music (level) (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Music (world map) (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Music (special) (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Sounds (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Level: Blocks (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Level: Background objects (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Level: Background images (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Level: NPCs (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>World map: Terrain tiles (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>World map: Scenery (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>World map: Path tiles (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>World map: Level entrance tiles (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Default rotation rules (%1)</source> <translation type="unfinished"></translation> </message> <message> <source>Level data</source> <translation type="unfinished"></translation> </message> <message> <source>World map data</source> <translation type="unfinished"></translation> </message> <message> <source>Characters</source> <translation type="unfinished"></translation> </message> <message> <source>Game worlds</source> <translation type="unfinished"></translation> </message> <message> <source>Music</source> <translation type="unfinished"></translation> </message> <message> <source>Sounds</source> <translation type="unfinished"></translation> </message> <message> <source>Custom data</source> <translation type="unfinished"></translation> </message> <message> <source>[Error list is empty, congratulations!]</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CrashHandler</name> <message> <source>Crash</source> <translation type="unfinished"></translation> </message> <message> <source>Uh-oh, PGE Editor has crashed :(&lt;br&gt;Detailed crash information:</source> <translation type="unfinished"></translation> </message> <message> <source>Exit from application</source> <translation type="unfinished"></translation> </message> <message> <source>Crash recovery</source> <comment>Crash recovery - emergency file saving after crash. A title of message box.</comment> <translation type="unfinished"></translation> </message> <message> <source>Since the last crash, the editor recovered some files. Please save them before doing anything else.</source> <translation type="unfinished"></translation> </message> <message> <source>You might want to report this data to developers:</source> <translation type="unfinished"></translation> </message> <message> <source>Copy report into clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>Post a report at PGE Forum (wohlsoft.ru/forum/)</source> <translation type="unfinished"></translation> </message> <message> <source>Make an issue at GitHub repository (WohlSoft/PGE-Project)</source> <translation type="unfinished"></translation> </message> <message> <source>While making a report, please explain what you did to cause a crash error. - Please give a list of actions you did to cause a crash. - If a crash happened with editing a specific file, please attach it to the report. - What operating system you are using?</source> <translation type="unfinished"></translation> </message> <message> <source>Copied!</source> <translation type="unfinished"></translation> </message> <message> <source>Join the official Moondust Discord server to submit the report</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CustomCounterGUI</name> <message> <source>Custom Counter</source> <translation type="unfinished"></translation> </message> <message> <source>Please add the Item IDs which will be in this custom group:</source> <translation type="unfinished"></translation> </message> <message> <source>Item type:</source> <translation type="unfinished"></translation> </message> <message> <source>Counter name:</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Block</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Terrain tile</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Path</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Music</source> <translation type="unfinished"></translation> </message> <message> <source>Change item...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CustomMusicSetup</name> <message> <source>Music setup</source> <translation type="unfinished"></translation> </message> <message> <source>Play music</source> <translation type="unfinished"></translation> </message> <message> <source>Synthesizer type:</source> <translation type="unfinished"></translation> </message> <message> <source>Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Reset</source> <translation type="unfinished"></translation> </message> <message> <source>Tempo:</source> <translation type="unfinished"></translation> </message> <message> <source>Extra settings</source> <translation type="unfinished"></translation> </message> <message> <source>Custom bank:</source> <translation type="unfinished"></translation> </message> <message> <source>Volume model:</source> <translation type="unfinished"></translation> </message> <message> <source>Deep vibrato</source> <translation type="unfinished"></translation> </message> <message> <source>Bank:</source> <comment>The OPL3 timbre/instruments bank to change the MIDI music sounding.</comment> <translation type="unfinished"></translation> </message> <message> <source>Deep tremolo</source> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>The timbre bank declares the sounding of MIDI music. Use different banks to compare the sounding difference.</source> <translation type="unfinished"></translation> </message> <message> <source>Volume model declares how music volumes, note velocities and expression will be scaled.</source> <translation type="unfinished"></translation> </message> <message> <source>The number of emulated OPL3 chips. Increase the count of chips to get wider polyphony (18 of two-operator voices per chip, or 6 four-operator voices per chip), or decrease it if you have the choppy music playback.</source> <translation type="unfinished"></translation> </message> <message> <source>Chips number:</source> <translation type="unfinished"></translation> </message> <message> <source>Chiptune</source> <translation type="unfinished"></translation> </message> <message> <source>Track number</source> <translation type="unfinished"></translation> </message> <message> <source>To begin</source> <translation type="unfinished"></translation> </message> <message> <source>Previous</source> <translation type="unfinished"></translation> </message> <message> <source>Next</source> <translation type="unfinished"></translation> </message> <message> <source>Tip: to preview the settings result, enable music playing, please. (Look for the play/stop note icon on the main window toolbar).</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI</source> <translation type="unfinished"></translation> </message> <message> <source>libADLMIDI (OPL3 Synth emulation)</source> <translation type="unfinished"></translation> </message> <message> <source>libOPNMIDI (YM2612 Synth emulation)</source> <translation type="unfinished"></translation> </message> <message> <source>Timidity (needed a bank)</source> <translation type="unfinished"></translation> </message> <message> <source>Native MIDI (Not recommended, buggy)</source> <translation type="unfinished"></translation> </message> <message> <source>[Auto]</source> <translation type="unfinished"></translation> </message> <message> <source>Generic</source> <comment>Volume model for libADLMIDI</comment> <translation type="unfinished"></translation> </message> <message> <source>Native OPL3</source> <comment>Volume model for libADLMIDI</comment> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>General</source> <comment>FluidSynth general options group</comment> <translation type="unfinished"></translation> </message> <message> <source>Max polyphony</source> <comment>FluidSynth option</comment> <translation type="unfinished"></translation> </message> <message> <source>SoundFont banks list (can be re-ordered by drag &amp; drop)</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb</source> <comment>FluidSynth option</comment> <translation type="unfinished"></translation> </message> <message> <source>Room size</source> <comment>FluidSynth: Reverb effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Damping</source> <comment>FluidSynth: Reverb effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Width</source> <comment>FluidSynth: Reverb effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <comment>FluidSynth: Reverb effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Chorus</source> <comment>FluidSynth option</comment> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <comment>FluidSynth: Chorus effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Speed</source> <comment>FluidSynth: Chorus effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Depth (ms)</source> <comment>FluidSynth: Chorus effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Voice count (N)</source> <comment>FluidSynth: Chorus effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>Type</source> <comment>FluidSynth: Chorus effect option</comment> <translation type="unfinished"></translation> </message> <message> <source>FluidSynth (needed an SF2-bank)</source> <translation type="unfinished"></translation> </message> <message> <source>Native OPN2</source> <comment>Volume model for libOPNMIDI</comment> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <comment>FluidSynth Chorus type value</comment> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <comment>FluidSynth Chorus type value</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>DataConfig</name> <message> <source>You have a legacy configuration package. &lt;br&gt;Editor will be started, but you may have a some problems with items or settings. &lt;br&gt; &lt;br&gt;Please download and install latest version of a configuration package: &lt;br&gt; &lt;br&gt;Download: %1 &lt;br&gt;Note: most of config packs are updates togeter with PGE,&lt;br&gt; therefore you can use same link to get updated version</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DebuggerBox</name> <message> <source>Debugger</source> <translation type="unfinished"></translation> </message> <message> <source>Mouse coordinates</source> <translation type="unfinished"></translation> </message> <message> <source>Go to point:</source> <translation type="unfinished"></translation> </message> <message> <source>Go!</source> <translation type="unfinished"></translation> </message> <message> <source>Contents</source> <translation type="unfinished"></translation> </message> <message> <source>Custom counters</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Refresh</source> <translation type="unfinished"></translation> </message> <message> <source>Edit</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DevConsole</name> <message> <source>Developer Console</source> <translation type="unfinished"></translation> </message> <message> <source>Type commands here...</source> <translation type="unfinished"></translation> </message> <message> <source>Send Command</source> <translation type="unfinished"></translation> </message> <message> <source>System</source> <translation type="unfinished"></translation> </message> <message> <source>Clear System Log</source> <translation type="unfinished"></translation> </message> <message> <source>Clear All Logs</source> <translation type="unfinished"></translation> </message> <message> <source>Clear %1 Log</source> <translation type="unfinished"></translation> </message> <message> <source>Prints this help text</source> <translation type="unfinished"></translation> </message> <message> <source>Prints a test command</source> <translation type="unfinished"></translation> </message> <message> <source>Prints the editor version</source> <translation type="unfinished"></translation> </message> <message> <source>Quits the program</source> <translation type="unfinished"></translation> </message> <message> <source>Saves the application settings</source> <translation type="unfinished"></translation> </message> <message> <source>Args: {SomeString} Calculates MD5 hash of string</source> <translation type="unfinished"></translation> </message> <message> <source>Arg: {String array} validates the PGE-X string array</source> <translation type="unfinished"></translation> </message> <message> <source>Simulates crash signal</source> <translation type="unfinished"></translation> </message> <message> <source>Args: {[Number] Gigabytes} | Floods the memory with megabytes</source> <translation type="unfinished"></translation> </message> <message> <source>Throws an unhandled exception to crash the editor</source> <translation type="unfinished"></translation> </message> <message> <source>Does a segmentation violation</source> <translation type="unfinished"></translation> </message> <message> <source>Arg: {Path to file} tests if the file is in the PGE-X file format</source> <translation type="unfinished"></translation> </message> <message> <source>Args: {Music type (lvl wld spc), Music ID} Play default music by specific ID</source> <translation type="unfinished"></translation> </message> <message> <source>Args: {engine commands} Send a command or message into the PGE Engine if it&apos;s running</source> <translation type="unfinished"></translation> </message> <message> <source>Shows various important paths!</source> <translation type="unfinished"></translation> </message> <message> <source>Creates and deletes ItemSelectDialog to analyze memory leaking</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ExportToImage</name> <message> <source>Export to image</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a &lt;span style=&quot; font-weight:600;&quot;&gt;Width&lt;/span&gt; of target image. Target image will be scaled to this width.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source> px</source> <translation type="unfinished"></translation> </message> <message> <source>Keep original aspect ratio</source> <translation type="unfinished"></translation> </message> <message> <source>Width</source> <translation type="unfinished"></translation> </message> <message> <source>Force vertical background tiling</source> <translation type="unfinished"></translation> </message> <message> <source>Export current section to image</source> <translation type="unfinished"></translation> </message> <message> <source>Height</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a &lt;span style=&quot; font-weight:600;&quot;&gt;Height&lt;/span&gt; of target image. Target image will be scaled to this height.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;With this option will be calculated opposite value for height or width for make target image with correct proportions.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Please, select target image size:</source> <translation type="unfinished"></translation> </message> <message> <source>Hide warps and water markers (recommended)</source> <translation type="unfinished"></translation> </message> <message> <source>Hide editor-only meta-signs pictures</source> <translation type="unfinished"></translation> </message> <message> <source>Hide grid (if it is shown)</source> <translation type="unfinished"></translation> </message> <message> <source>Hide invisible blocks and meta-objects</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FileListBrowser</name> <message> <source>Files list</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a list of level files, what placed with your current file in the same folder.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Please select a file from the list:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>GreetingDialog</name> <message> <source>Welcome!</source> <translation type="unfinished"></translation> </message> <message> <source>Choose the workspace layout you want to use:</source> <translation type="unfinished"></translation> </message> <message> <source>Modern</source> <translation type="unfinished"></translation> </message> <message> <source>Classic</source> <translation type="unfinished"></translation> </message> <message> <source>Modern UI designed for convenience, works well on screens of various sizes.</source> <translation type="unfinished"></translation> </message> <message> <source>A classic interface which will be familiar to long-time users of SMBX or the legacy editor.</source> <translation type="unfinished"></translation> </message> <message> <source>Welcome to PGE Editor!</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;p&gt;&lt;b&gt;Tip 1:&lt;/b&gt; You still be able to toggle UI via &lt;u&gt;Help&lt;/u&gt; menu or toggling toolboxes from &lt;u&gt;View&lt;/u&gt; menu and toggling sub-windows and tabs mode in the &lt;u&gt;Window&lt;/u&gt; menu.&lt;br/&gt; &lt;br/&gt; &lt;b&gt;Tip 2:&lt;/b&gt; Unlike the legacy editor, many features can be quickly accessed from the context menu (opened by right-clicking), as well as toolboxes in toolbars and menus. This editor also allows you to select multiple objects at once!&lt;br/&gt; &lt;br/&gt; &lt;b&gt;Tip 3:&lt;/b&gt; Use middle mouse button to toggle placing of selected element or duplicate group!&lt;/p&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementAddLayer</name> <message> <source>Add Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementAddWarp</name> <message> <source>Add Warp</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementChangeLayerVisibility</name> <message> <source>Toggle the visibility of a layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementChangedNewLayer</name> <message> <source>New Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementLayerChanged</name> <message> <source>Change Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementMergeLayer</name> <message> <source>Merge Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementModification</name> <message> <source>Simple Modification History</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementModifyEvent</name> <message> <source>Remove Event</source> <translation type="unfinished"></translation> </message> <message> <source>Add Event</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementNewLayer</name> <message> <source>New Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementPlaceDoor</name> <message> <source>Place Door</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementRemoveLayer</name> <message> <source>Remove Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementRemoveLayerAndSave</name> <message> <source>Remove Layer and keep items</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementRemoveWarp</name> <message> <source>Remove Warp</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementRenameEvent</name> <message> <source>Rename Event</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementRenameLayer</name> <message> <source>Rename Layer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementReplacePlayerPoint</name> <message> <source>Place Player Point</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementResizeBlock</name> <message> <source>Resize Block</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementResizeSection</name> <message> <source>Resize Section</source> <translation type="unfinished"></translation> </message> </context> <context> <name>HistoryElementResizeWater</name> <message> <source>Resize Water</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Installer</name> <message> <source>PGE Level file</source> <comment>File Types</comment> <translation type="unfinished"></translation> </message> <message> <source>PGE World Map</source> <comment>File Types</comment> <translation type="unfinished"></translation> </message> <message> <source>SMBX Level file</source> <comment>File Types</comment> <translation type="unfinished"></translation> </message> <message> <source>SMBX World Map</source> <comment>File Types</comment> <translation type="unfinished"></translation> </message> <message> <source>Please wait...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemBGO</name> <message> <source>Layer: </source> <translation type="unfinished"></translation> </message> <message> <source>Add to new layer...</source> <translation type="unfinished"></translation> </message> <message> <source>[hidden]</source> <translation type="unfinished"></translation> </message> <message> <source>Change Z-Offset...</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Background-2</source> <translation type="unfinished"></translation> </message> <message> <source>Background</source> <translation type="unfinished"></translation> </message> <message> <source>Default</source> <translation type="unfinished"></translation> </message> <message> <source>Foreground</source> <translation type="unfinished"></translation> </message> <message> <source>Foreground-2</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 in this section into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>BGO-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1 in this section</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Offset</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter the Z-value offset:</source> <translation type="unfinished"></translation> </message> <message> <source>Margin of section</source> <translation type="unfinished"></translation> </message> <message> <source>Please select how far items can travel beyond the section boundaries (in pixels) before they are removed.</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Edit raw user data...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemBlock</name> <message> <source>Layer: </source> <translation type="unfinished"></translation> </message> <message> <source>Add to new layer...</source> <translation type="unfinished"></translation> </message> <message> <source>[hidden]</source> <translation type="unfinished"></translation> </message> <message> <source>Invisible</source> <translation type="unfinished"></translation> </message> <message> <source>Slippery</source> <translation type="unfinished"></translation> </message> <message> <source>Resize</source> <translation type="unfinished"></translation> </message> <message> <source>Change included NPC...</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 in this section into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Make message box...</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Block-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1 in this section</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Margin of section</source> <translation type="unfinished"></translation> </message> <message> <source>Please select how far items can travel beyond the section boundaries (in pixels) before they are removed.</source> <translation type="unfinished"></translation> </message> <message> <source>Event name</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter the name of event:</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter the message which will be shown. (Max line length is 27 characters)</source> <translation type="unfinished"></translation> </message> <message> <source>Hit message text</source> <translation type="unfinished"></translation> </message> <message> <source>Event created</source> <translation type="unfinished"></translation> </message> <message> <source>Message event created!</source> <translation type="unfinished"></translation> </message> <message> <source>&apos;Hit&apos; event slot is used</source> <translation type="unfinished"></translation> </message> <message> <source>Sorry, but the &apos;Hit&apos; event slot already used by the event: &apos;%1&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Edit raw user data...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemBoxListModel</name> <message> <source>Search by Name</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Search by ID</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Search by ID (Contained)</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Sort by</source> <comment>Search settings pop-up menu, sort submenu</comment> <translation type="unfinished"></translation> </message> <message> <source>Name</source> <comment>Sort by name</comment> <translation type="unfinished"></translation> </message> <message> <source>ID</source> <comment>Sort by ID</comment> <translation type="unfinished"></translation> </message> <message> <source>Descending</source> <comment>Descending sorting order</comment> <translation type="unfinished"></translation> </message> <message> <source>Uniform item sizes view</source> <comment>Align elements inside of Item Box list in uniform view</comment> <translation type="unfinished"></translation> </message> <message> <source>Show custom elements</source> <comment>Show custom elements only in Item Box List</comment> <translation type="unfinished"></translation> </message> <message> <source>Show standard elements</source> <comment>Show standard elements only in Item Box List</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemDoor</name> <message> <source>Open target level: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Layer: </source> <translation type="unfinished"></translation> </message> <message> <source>Add to new layer...</source> <translation type="unfinished"></translation> </message> <message> <source>[hidden]</source> <translation type="unfinished"></translation> </message> <message> <source>Jump to exit</source> <translation type="unfinished"></translation> </message> <message> <source>Jump to entrance</source> <translation type="unfinished"></translation> </message> <message> <source>No Vehicles</source> <translation type="unfinished"></translation> </message> <message> <source>Allow NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Locked</source> <translation type="unfinished"></translation> </message> <message> <source>Need a bomb</source> <translation type="unfinished"></translation> </message> <message> <source>Required special state</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemLevel</name> <message> <source>Open target file: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Path background</source> <translation type="unfinished"></translation> </message> <message> <source>Big Path background</source> <translation type="unfinished"></translation> </message> <message> <source>Always Visible</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Level-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemMsgBox</name> <message> <source>Set message box</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a message, what will be displayed if player will do talk with this NPC.&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Note:&lt;/span&gt; All quotes and new-line characters will be removed.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Enter the NPC&apos;s dialog message: (Max length per line is 27 characters)</source> <translation type="unfinished"></translation> </message> <message> <source>Friendly (Non-friendly NPCs can&apos;t be talked to)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemMusic</name> <message> <source>&lt;Silence&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Play this</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>World-Music-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemNPC</name> <message> <source>Layer: </source> <translation type="unfinished"></translation> </message> <message> <source>Add to new layer...</source> <translation type="unfinished"></translation> </message> <message> <source>[hidden]</source> <translation type="unfinished"></translation> </message> <message> <source>Edit NPC-Configuration</source> <translation type="unfinished"></translation> </message> <message> <source>New NPC-Configuration</source> <translation type="unfinished"></translation> </message> <message> <source>Set %1</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Friendly</source> <translation type="unfinished"></translation> </message> <message> <source>Doesn&apos;t move</source> <translation type="unfinished"></translation> </message> <message> <source>Set message...</source> <translation type="unfinished"></translation> </message> <message> <source>Set as Boss</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 in this section into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Change included NPC...</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>NPC-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1 in this section</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Margin of section</source> <translation type="unfinished"></translation> </message> <message> <source>Please select how far items can travel beyond the section boundaries (in pixels) before they are removed.</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Edit raw user data...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemPath</name> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Path-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemPhysEnv</name> <message> <source>Layer: </source> <translation type="unfinished"></translation> </message> <message> <source>Add to new layer...</source> <translation type="unfinished"></translation> </message> <message> <source>[hidden]</source> <translation type="unfinished"></translation> </message> <message> <source>Environment type</source> <translation type="unfinished"></translation> </message> <message> <source>Water</source> <translation type="unfinished"></translation> </message> <message> <source>Quicksand</source> <translation type="unfinished"></translation> </message> <message> <source>Custom liquid</source> <translation type="unfinished"></translation> </message> <message> <source>Gravity Field</source> <translation type="unfinished"></translation> </message> <message> <source>Touch Event (Once)</source> <translation type="unfinished"></translation> </message> <message> <source>Touch Event (Every frame)</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Touch Event (Once)</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Touch Event (Every frame)</source> <translation type="unfinished"></translation> </message> <message> <source>Mouse click Event</source> <translation type="unfinished"></translation> </message> <message> <source>NPC/Player Touch Event (Once)</source> <translation type="unfinished"></translation> </message> <message> <source>NPC/Player Touch Event (Every frame)</source> <translation type="unfinished"></translation> </message> <message> <source>Collision script</source> <translation type="unfinished"></translation> </message> <message> <source>Mouse click Script</source> <translation type="unfinished"></translation> </message> <message> <source>Collision Event</source> <translation type="unfinished"></translation> </message> <message> <source>Air chamber</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Hurting Field</source> <translation type="unfinished"></translation> </message> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Resize</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemPlayerPoint</name> <message> <source>Set %1</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemScene</name> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemSelectDialog</name> <message> <source>Select Item</source> <translation type="unfinished"></translation> </message> <message> <source>Blocks</source> <translation type="unfinished"></translation> </message> <message> <source>Filter:</source> <translation type="unfinished"></translation> </message> <message> <source>Category:</source> <translation type="unfinished"></translation> </message> <message> <source>Group:</source> <translation type="unfinished"></translation> </message> <message> <source>[all]</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Terrain tile</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Path</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Music</source> <translation type="unfinished"></translation> </message> <message> <source>Extra Data:</source> <translation type="unfinished"></translation> </message> <message> <source>[Empty]</source> <translation type="unfinished"></translation> </message> <message> <source>NPC from List</source> <translation type="unfinished"></translation> </message> <message> <source>Coins</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file first, if you want to select custom music file.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ItemTile</name> <message> <source>Copy preferences</source> <translation type="unfinished"></translation> </message> <message> <source>Tile-ID: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y</source> <translation type="unfinished"></translation> </message> <message> <source>Position: X, Y, Width, Height</source> <translation type="unfinished"></translation> </message> <message> <source>Position: Left, Top, Right, Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Transform into</source> <translation type="unfinished"></translation> </message> <message> <source>Transform all %1 into</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all %1</source> <translation type="unfinished"></translation> </message> <message> <source>Preferences have been copied: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>JsonSettingsWidget</name> <message> <source>Browse</source> <translation type="unfinished"></translation> </message> <message> <source>Play</source> <translation type="unfinished"></translation> </message> <message> <source>[empty]</source> <translation type="unfinished"></translation> </message> <message> <source>W</source> <comment>Width, shortly</comment> <translation type="unfinished"></translation> </message> <message> <source>H</source> <comment>Height, shortly</comment> <translation type="unfinished"></translation> </message> <message> <source>%1 coins</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LevelEdit</name> <message> <source>Untitled %1</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a level title for &apos;%1&apos;!</source> <translation type="unfinished"></translation> </message> <message> <source>Saving</source> <translation type="unfinished"></translation> </message> <message> <source>Level title: </source> <translation type="unfinished"></translation> </message> <message> <source>Make custom folder</source> <translation type="unfinished"></translation> </message> <message> <source>Save As</source> <translation type="unfinished"></translation> </message> <message> <source>Which version do you want to save as? (from 0 to 64) List of known SMBX versions and format codes: %1 (To allow level file work in specific SMBX version, version code must be less or equal specific code)</source> <translation type="unfinished"></translation> </message> <message> <source>Extension is not set</source> <translation type="unfinished"></translation> </message> <message> <source>File Extension isn&apos;t defined, please enter file extension!</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX file version</source> <translation type="unfinished"></translation> </message> <message> <source>The SMBX64 limit has been exceeded</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to save file anyway? Exciting of SMBX64 limits may crash SMBX with &apos;Subscript out of range&apos; error. Installed LunaLUA partially extends than limits.</source> <translation type="unfinished"></translation> </message> <message> <source>File save error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot save file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source>File read error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot read file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source>Loading level data</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>Incorrect custom configs</source> <translation type="unfinished"></translation> </message> <message> <source>This level has some incorrect config files which are can&apos;t be loaded. To avoid this message box in next time, please fix next errors in your config files in the the current and in the custom folders: %1</source> <translation type="unfinished"></translation> </message> <message> <source>&apos;%1&apos; has been modified. Do you want to save your changes?</source> <translation type="unfinished"></translation> </message> <message> <source> not saved</source> <translation type="unfinished"></translation> </message> <message> <source>Export current section to image</source> <translation type="unfinished"></translation> </message> <message> <source>PNG Image (*.png)</source> <translation type="unfinished"></translation> </message> <message> <source>Saving section image...</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait...</source> <translation type="unfinished"></translation> </message> <message> <source>1/%1 Loading user data...</source> <translation type="unfinished"></translation> </message> <message> <source>1/%1 Loading Backgrounds...</source> <translation type="unfinished"></translation> </message> <message> <source>2/%1 Loading BGOs...</source> <translation type="unfinished"></translation> </message> <message> <source>3/%1 Loading Blocks...</source> <translation type="unfinished"></translation> </message> <message> <source>4/%1 Loading NPCs...</source> <translation type="unfinished"></translation> </message> <message> <source>5/%1 Loading PhysEZ...</source> <comment>PhysEZ - Physical Environment Zone.</comment> <translation type="unfinished"></translation> </message> <message> <source>6/%1 Loading Doors...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LevelFileList</name> <message> <source>Level files list</source> <translation type="unfinished"></translation> </message> <message> <source>Please, select level file from list for use them:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LevelItemBox</name> <message> <source>Blocks</source> <translation type="unfinished"></translation> </message> <message> <source>Category:</source> <translation type="unfinished"></translation> </message> <message> <source>Group:</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Copy graphic to custom folder</source> <translation type="unfinished"></translation> </message> <message> <source>Copy graphic to episode folder</source> <translation type="unfinished"></translation> </message> <message> <source>Search</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;Save file first&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Level items browser</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LevelProps</name> <message> <source>Level Properties</source> <translation type="unfinished"></translation> </message> <message> <source>Disable player controls</source> <translation type="unfinished"></translation> </message> <message> <source>Drop</source> <translation type="unfinished"></translation> </message> <message> <source>Jump</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Alt-Jump</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Start</source> <translation type="unfinished"></translation> </message> <message> <source>Alt-Run</source> <translation type="unfinished"></translation> </message> <message> <source>Run</source> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <translation type="unfinished"></translation> </message> <message> <source>Title</source> <translation type="unfinished"></translation> </message> <message> <source>Level name:</source> <translation type="unfinished"></translation> </message> <message> <source>Physics</source> <translation type="unfinished"></translation> </message> <message> <source>Default</source> <translation type="unfinished"></translation> </message> <message> <source>Physics type:</source> <translation type="unfinished"></translation> </message> <message> <source>Timer</source> <translation type="unfinished"></translation> </message> <message> <source>Enable</source> <translation type="unfinished"></translation> </message> <message> <source> sec.</source> <translation type="unfinished"></translation> </message> <message> <source>Kill all players</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger event</source> <translation type="unfinished"></translation> </message> <message> <source>Time limit:</source> <translation type="unfinished"></translation> </message> <message> <source>Timer type:</source> <translation type="unfinished"></translation> </message> <message> <source>Event:</source> <translation type="unfinished"></translation> </message> <message> <source>General</source> <translation type="unfinished"></translation> </message> <message> <source>No settings available</source> <translation type="unfinished"></translation> </message> <message> <source>Error in the file %1: %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LunaTesterEngine</name> <message> <source>Test level</source> <comment>Run the LunaTester based level testing.</comment> <translation type="unfinished"></translation> </message> <message> <source>Starts level testing in the legacy engine. To have this feature work, latest LunaLUA must be installed. Otherwise, it will be very limited.</source> <translation type="unfinished"></translation> </message> <message> <source>Reset checkpoints</source> <translation type="unfinished"></translation> </message> <message> <source>Reset all checkpoint states to initial state.</source> <translation type="unfinished"></translation> </message> <message> <source>Disable OpenGL</source> <comment>Disable OpenGL on LunaTester side</comment> <translation type="unfinished"></translation> </message> <message> <source>Disable OpenGL rendering engine and use the GDI. Useful if your video card does not support OpenGL or LunaLua is crashing on the attempt to use it.</source> <translation type="unfinished"></translation> </message> <message> <source>Keep running in background</source> <comment>Keep Legacy Engine be running in background to speed-up testing starts after first launch.</comment> <translation type="unfinished"></translation> </message> <message> <source>Allows to start level testing very fast after first launch. Requires powerful computer, otherwise engine will freeze on next test launch. Suggested to disable this feature on slow machines or if any troubles are happens while attempts to run a testing.</source> <translation type="unfinished"></translation> </message> <message> <source>Terminate running process</source> <comment>Ends the LunaTester process, regardless of whether it&apos;s in the background or foreground, so the engine can be loaded from scratch.</comment> <translation type="unfinished"></translation> </message> <message> <source>Ends the LunaTester process so the engine can be loaded from scratch.</source> <translation type="unfinished"></translation> </message> <message> <source>Start Game</source> <comment>Launch LunaTester as a normal game.</comment> <translation type="unfinished"></translation> </message> <message> <source>Launch LunaTester as a normal game.</source> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to close LunaTester? If you are testing a level, this will immediately end it!</source> <translation type="unfinished"></translation> </message> <message> <source>LunaTester has been successfully closed.</source> <translation type="unfinished"></translation> </message> <message> <source>LunaTester is not running.</source> <translation type="unfinished"></translation> </message> <message> <source>Please select a path to LunaTester:</source> <translation type="unfinished"></translation> </message> <message> <source>Use default</source> <comment>Using default LunaTester path, specified by a config pack</comment> <translation type="unfinished"></translation> </message> <message> <source>Custom</source> <comment>Using a user selected LunaTester path</comment> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Checkpoints successfully reseted!</source> <translation type="unfinished"></translation> </message> <message> <source>LunaLUA tester is not started!</source> <translation type="unfinished"></translation> </message> <message> <source>Vanilla SMBX detected!</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to send level into LunaLUA-SMBX!</source> <translation type="unfinished"></translation> </message> <message> <source>LunaTester error</source> <translation type="unfinished"></translation> </message> <message> <source>Change the path to LunaTester...</source> <comment>Open a dialog to choose the location of LunaTester (aka SMBX2 data root directory).</comment> <translation type="unfinished"></translation> </message> <message> <source>Select the location of LunaTester.</source> <translation type="unfinished"></translation> </message> <message> <source>Path to LunaTester</source> <comment>Title of dialog</comment> <translation type="unfinished"></translation> </message> <message> <source>Select a location of LunaTester</source> <comment>Directory select dialog title</comment> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 limits are exceeded!</source> <translation type="unfinished"></translation> </message> <message> <source>Violation of SMBX64 standard has been found! %1 , legacy engine may crash! Suggested to remove all excess elements. Do you want to continue the process?</source> <translation type="unfinished"></translation> </message> <message> <source>LunaTester directory check failed</source> <comment>A title of a message box that shows when some of the files or directories not exist.</comment> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start LunaTester because &quot;%1&quot; is not found! That might happen due to any of the following reasons:</source> <comment>A text of a message box that shows when some of the files or directories not exist.</comment> <translation type="unfinished"></translation> </message> <message> <source>- Incorrect location of LunaTester (or SMBX2 data root) was specified, please check the LunaTester location setup. - Possible removal of files by your antivirus (false positive or an infection of the file), please check your antivirus&apos; quarantine or report of recently removed threats. - Incorrect installation of SMBX2 has caused missing files, please reinstall SMBX2 to fix your problem.</source> <comment>Description of a problem, showing when LunaTester is NOT a default engine in a current config pack.</comment> <translation type="unfinished"></translation> </message> <message> <source>- Possible removal of files by your antivirus (false positive or an infection of the file), please check your antivirus&apos; quarantine or report of recently removed threats. - Incorrect installation of SMBX2 has caused missing files, please reinstall SMBX2 to fix your problem.</source> <comment>Description of a problem, showing when LunaTester is a default engine in a current config pack.</comment> <translation type="unfinished"></translation> </message> <message> <source>&quot;%1&quot; not found! You have a Vanilla SMBX! That means, impossible to launch level testing with a LunaTester. LunaLua is required to run level testing with SMBX Engine.</source> <translation type="unfinished"></translation> </message> <message> <source>Test saved level/world</source> <comment>Run the testing of current file in LunaTester from disk.</comment> <translation type="unfinished"></translation> </message> <message> <source>Wine settings...</source> <comment>Open Wine settings to choose which Wine toolchain use</comment> <translation type="unfinished"></translation> </message> <message> <source>Select a Wine toolchain for use.</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to start: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Crashed: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Timed out: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Write error: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Read error: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Unknown error: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Error has occured: (Error %1) %2</source> <translation type="unfinished"></translation> </message> <message> <source>LunaTester is still active</source> <translation type="unfinished"></translation> </message> <message> <source>Unable to recognize capabilities of selected LunaLua path, game may not work. Please select a different path.</source> <translation type="unfinished"></translation> </message> <message> <source>To change a setup of Wine, you will need to shut down a currently working LunaTester. Do you want to shut down the LunaTester now?</source> <translation type="unfinished"></translation> </message> <message> <source>Incompatible LunaDll found</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to start a LunaTester due to an incompatible LunaDll.dll module found in the path: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Incompatible LunaLua</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to start a LunaTester due to an incompatible LunaLua in the path: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to launch an episode out of LunaTester worlds root.</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to launch an episode because of an invalid world file.</source> <translation type="unfinished"></translation> </message> <message> <source>To change a path to LunaTester, you will need to shut down a currently running game. Do you want to shut down LunaTester now?</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot launch the episode because the world map file is saved in an unsupported format. Please save the world map in the SMBX64-WLD format.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlCloneSection</name> <message> <source>Clone section</source> <translation type="unfinished"></translation> </message> <message> <source>Please select the source file and the section to clone, as well as the destination file and target section to clone into.</source> <translation type="unfinished"></translation> </message> <message> <source>Source</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Note:&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; text-decoration: underline;&quot;&gt;SMBX-8...64&lt;/span&gt; and &lt;span style=&quot; text-decoration: underline;&quot;&gt;SMBX-38A&lt;/span&gt; formats are not supported by more than 21 sections.&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; text-decoration: underline;&quot;&gt;SMBX-1...7&lt;/span&gt; formats are not supported by more than 6 sections.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Destiation</source> <translation type="unfinished"></translation> </message> <message> <source>Margin (How far outside of the target section items can be copied, in pixels):</source> <translation type="unfinished"></translation> </message> <message> <source>Section</source> <translation type="unfinished"></translation> </message> <message> <source>[Uninitialized]</source> <translation type="unfinished"></translation> </message> <message> <source>[Used]</source> <translation type="unfinished"></translation> </message> <message> <source>Initialize new section</source> <translation type="unfinished"></translation> </message> <message> <source>Sections aren&apos;t selected</source> <translation type="unfinished"></translation> </message> <message> <source>Source and Destination sections should be selected!</source> <translation type="unfinished"></translation> </message> <message> <source>Empty section</source> <translation type="unfinished"></translation> </message> <message> <source>Source section is empty! Please select another section, or clear.</source> <translation type="unfinished"></translation> </message> <message> <source>Section is used</source> <translation type="unfinished"></translation> </message> <message> <source>Destination section is in use, therefore it will be overridden with removing of all it&apos;s objects. Do you want to continue?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlEventsBox</name> <message> <source>Classic Events</source> <translation type="unfinished"></translation> </message> <message> <source>Events list</source> <translation type="unfinished"></translation> </message> <message> <source>Layer visibly</source> <translation type="unfinished"></translation> </message> <message> <source>Disable smoke effects</source> <translation type="unfinished"></translation> </message> <message> <source>Show</source> <translation type="unfinished"></translation> </message> <message> <source>Toggle</source> <translation type="unfinished"></translation> </message> <message> <source>Hide</source> <translation type="unfinished"></translation> </message> <message> <source>Layers movement</source> <translation type="unfinished"></translation> </message> <message> <source>Horisontal speed:</source> <translation type="unfinished"></translation> </message> <message> <source>bps</source> <translation type="unfinished"></translation> </message> <message> <source>Vertical speed:</source> <translation type="unfinished"></translation> </message> <message> <source>Set moving layer</source> <translation type="unfinished"></translation> </message> <message> <source>Autoscroll section</source> <translation type="unfinished"></translation> </message> <message> <source>Section</source> <translation type="unfinished"></translation> </message> <message> <source>Section settings</source> <translation type="unfinished"></translation> </message> <message> <source>Current section:</source> <translation type="unfinished"></translation> </message> <message> <source>Set size and position</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t change</source> <translation type="unfinished"></translation> </message> <message> <source>Capture...</source> <translation type="unfinished"></translation> </message> <message> <source>Reset to default</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Top</source> <translation type="unfinished"></translation> </message> <message> <source>Define new:</source> <translation type="unfinished"></translation> </message> <message> <source>Bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Set music</source> <translation type="unfinished"></translation> </message> <message> <source>Replace music to:</source> <translation type="unfinished"></translation> </message> <message> <source>Set background</source> <translation type="unfinished"></translation> </message> <message> <source>Replace background to:</source> <translation type="unfinished"></translation> </message> <message> <source>Common</source> <translation type="unfinished"></translation> </message> <message> <source>Do end game:</source> <translation type="unfinished"></translation> </message> <message> <source>Play sound:</source> <translation type="unfinished"></translation> </message> <message> <source>Test</source> <translation type="unfinished"></translation> </message> <message> <source>Display message:</source> <translation type="unfinished"></translation> </message> <message> <source>Nothing</source> <translation type="unfinished"></translation> </message> <message> <source>Game end &quot;Bowser defeat&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Player Control hold keys</source> <translation type="unfinished"></translation> </message> <message> <source>Run</source> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <translation type="unfinished"></translation> </message> <message> <source>Drop</source> <translation type="unfinished"></translation> </message> <message> <source>Alt-run</source> <translation type="unfinished"></translation> </message> <message> <source>Start</source> <translation type="unfinished"></translation> </message> <message> <source>Jump</source> <translation type="unfinished"></translation> </message> <message> <source>Alt-jump</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger event</source> <translation type="unfinished"></translation> </message> <message> <source>Delay</source> <translation type="unfinished"></translation> </message> <message> <source>Autostart event</source> <translation type="unfinished"></translation> </message> <message> <source>Create copy of event</source> <translation type="unfinished"></translation> </message> <message> <source>[Silence]</source> <translation type="unfinished"></translation> </message> <message> <source>[none]</source> <translation type="unfinished"></translation> </message> <message> <source>New Event %1</source> <translation type="unfinished"></translation> </message> <message> <source>Copyed Event %1</source> <translation type="unfinished"></translation> </message> <message> <source>Get section size</source> <translation type="unfinished"></translation> </message> <message> <source>Please, set current section to %1 for capture data for this event</source> <translation type="unfinished"></translation> </message> <message> <source>Please, enter message (Max line length is 27 characters)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlHistoryManager</name> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Place</source> <translation type="unfinished"></translation> </message> <message> <source>Place &amp; Overwrite</source> <translation type="unfinished"></translation> </message> <message> <source>Move</source> <translation type="unfinished"></translation> </message> <message> <source>Rotate</source> <translation type="unfinished"></translation> </message> <message> <source>Flip</source> <translation type="unfinished"></translation> </message> <message> <source>Transform</source> <translation type="unfinished"></translation> </message> <message> <source>Undone: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Redone: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlItemProperties</name> <message> <source>Item Properties</source> <translation type="unfinished"></translation> </message> <message> <source>Block</source> <translation type="unfinished"></translation> </message> <message> <source>Slippery</source> <translation type="unfinished"></translation> </message> <message> <source>Resize</source> <translation type="unfinished"></translation> </message> <message> <source>Block contents:</source> <translation type="unfinished"></translation> </message> <message> <source>Destroyed: </source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t reset event to &apos;none&apos;</source> <translation type="unfinished"></translation> </message> <message> <source>Events</source> <translation type="unfinished"></translation> </message> <message> <source>Hited:</source> <translation type="unfinished"></translation> </message> <message> <source>Layer empty:</source> <translation type="unfinished"></translation> </message> <message> <source>Layer:</source> <translation type="unfinished"></translation> </message> <message> <source>Invisible</source> <translation type="unfinished"></translation> </message> <message> <source>Width:</source> <translation type="unfinished"></translation> </message> <message> <source>Height:</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Position</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Offset:</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Layer:</source> <translation type="unfinished"></translation> </message> <message> <source>Background-2</source> <translation type="unfinished"></translation> </message> <message> <source>Background</source> <translation type="unfinished"></translation> </message> <message> <source>Default</source> <translation type="unfinished"></translation> </message> <message> <source>Foreground</source> <translation type="unfinished"></translation> </message> <message> <source>Foreground-2</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 defines:</source> <translation type="unfinished"></translation> </message> <message> <source>Sort priority:</source> <translation type="unfinished"></translation> </message> <message> <source>This is a sorting array priority. With this option you can make this BGO as Foreground. (if value set to -1: will be used default value from global BGO config). This option using the SMBX&apos;s bug of BGO rendering. For this can be works, you need to place any Foreground BGO. This option will not be saved in LVL file, and you need set them secondary after reload of the file.</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Death:</source> <translation type="unfinished"></translation> </message> <message> <source>Talk:</source> <translation type="unfinished"></translation> </message> <message> <source>Activate:</source> <translation type="unfinished"></translation> </message> <message> <source>Attach to:</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Generator</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <source>Warp</source> <translation type="unfinished"></translation> </message> <message> <source>Projectile</source> <translation type="unfinished"></translation> </message> <message> <source>Delay (seconds):</source> <translation type="unfinished"></translation> </message> <message> <source>Contains of current NPC-Container</source> <translation type="unfinished"></translation> </message> <message> <source>Auto-increment</source> <translation type="unfinished"></translation> </message> <message> <source>Talk message:</source> <translation type="unfinished"></translation> </message> <message> <source>Friendly</source> <translation type="unfinished"></translation> </message> <message> <source>Doesn&apos;t move</source> <translation type="unfinished"></translation> </message> <message> <source>Set as Boss</source> <translation type="unfinished"></translation> </message> <message> <source>Block ID: %1, Array ID: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Position: [%1, %2]</source> <translation type="unfinished"></translation> </message> <message> <source>%1 coins</source> <translation type="unfinished"></translation> </message> <message> <source>[empty]</source> <translation type="unfinished"></translation> </message> <message> <source>BGO ID: %1, Array ID: %2</source> <translation type="unfinished"></translation> </message> <message> <source>NPC ID: %1, Array ID: %2</source> <translation type="unfinished"></translation> </message> <message> <source>[none]</source> <translation type="unfinished"></translation> </message> <message> <source>Error in the file %1: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Up-Left</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Up-Right</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Down-Left</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> <message> <source>Down-Right</source> <comment>Throwing direction of NPC, spawned via Generator object.</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlLayersBox</name> <message> <source>Layers</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Lock</source> <translation type="unfinished"></translation> </message> <message> <source>Layers merge</source> <translation type="unfinished"></translation> </message> <message> <source>Layer with name &apos;%1&apos; already exist, do you want to merge layers?</source> <translation type="unfinished"></translation> </message> <message> <source>New Layer %1</source> <translation type="unfinished"></translation> </message> <message> <source>Remove layer</source> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to remove this layer? All objects on this layer will be moved to the &apos;Default&apos; layer.</source> <translation type="unfinished"></translation> </message> <message> <source>Rename layer</source> <translation type="unfinished"></translation> </message> <message> <source>Remove layer with items</source> <translation type="unfinished"></translation> </message> <message> <source>Remove Layer and keep items</source> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to remove this layer? All elements of this layer will be moved to the &apos;Default&apos; layer!</source> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to remove this layer? All elements of this layer will be removed too!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlScene</name> <message> <source>Search User Backgrounds %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User Blocks %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User BGOs %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User NPCs %1</source> <translation type="unfinished"></translation> </message> <message> <source>Wrong custom images</source> <translation type="unfinished"></translation> </message> <message> <source>This level have a wrong custom graphics files. You will see &apos;ghosties&apos; or other dummy images instead custom GFX of items, what used broken images. It occurred because, for example, the BMP format with GIF extension was used. Please, reconvert your images to valid format and try to reload this level.</source> <translation type="unfinished"></translation> </message> <message> <source>LEVELSCENE_CONTEXTMENU_SectionProperties...</source> <comment>Section properties...</comment> <translation type="unfinished"></translation> </message> <message> <source>LEVELSCENE_CONTEXTMENU_LevelProperties...</source> <comment>Level properties...</comment> <translation type="unfinished"></translation> </message> <message> <source>Player start points: %1 Blocks: %2 Background objects&apos;s: %3 Non-playable characters&apos;s: %4 Warp entries: %5 Physical env. zones: %6 </source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlSearchBox</name> <message> <source>Search of items on the level</source> <translation type="unfinished"></translation> </message> <message> <source>Block</source> <translation type="unfinished"></translation> </message> <message> <source>Reset Search Fields</source> <translation type="unfinished"></translation> </message> <message> <source>Data</source> <translation type="unfinished"></translation> </message> <message> <source>Layer:</source> <translation type="unfinished"></translation> </message> <message> <source>Slippery:</source> <translation type="unfinished"></translation> </message> <message> <source>Contains NPC:</source> <translation type="unfinished"></translation> </message> <message> <source>[empty]</source> <translation type="unfinished"></translation> </message> <message> <source>Invisible:</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <source>Search Block</source> <translation type="unfinished"></translation> </message> <message> <source>Search?</source> <translation type="unfinished"></translation> </message> <message> <source>Ev. Destroyed:</source> <translation type="unfinished"></translation> </message> <message> <source>Ev. Hited</source> <translation type="unfinished"></translation> </message> <message> <source>Ev. Layer Empty:</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>Search BGO</source> <translation type="unfinished"></translation> </message> <message> <source>Sort priority:</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>[None]</source> <translation type="unfinished"></translation> </message> <message> <source>Attached layer:</source> <translation type="unfinished"></translation> </message> <message> <source>Search NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Evt activate:</source> <translation type="unfinished"></translation> </message> <message> <source>Evt death:</source> <translation type="unfinished"></translation> </message> <message> <source>Evt talk:</source> <translation type="unfinished"></translation> </message> <message> <source>Evt empty layer:</source> <translation type="unfinished"></translation> </message> <message> <source>Doesn&apos;t move</source> <translation type="unfinished"></translation> </message> <message> <source>Friendly</source> <translation type="unfinished"></translation> </message> <message> <source>Set as Boss</source> <translation type="unfinished"></translation> </message> <message> <source>Contains Msg:</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Case Sensitive?</source> <translation type="unfinished"></translation> </message> <message> <source>Next Block</source> <translation type="unfinished"></translation> </message> <message> <source>Stop Search</source> <translation type="unfinished"></translation> </message> <message> <source>Search Complete</source> <translation type="unfinished"></translation> </message> <message> <source>Block search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next BGO</source> <translation type="unfinished"></translation> </message> <message> <source>BGO search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next NPC</source> <translation type="unfinished"></translation> </message> <message> <source>NPC search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Search in selection group</source> <translation type="unfinished"></translation> </message> <message> <source>Search in current section</source> <translation type="unfinished"></translation> </message> <message> <source>Select all</source> <translation type="unfinished"></translation> </message> <message> <source>%1 found elements were selected.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlSectionProps</name> <message> <source>Section Settings</source> <translation type="unfinished"></translation> </message> <message> <source>Leaving for the screen, the player enters the screen on the other side</source> <translation type="unfinished"></translation> </message> <message> <source>Off screen exit</source> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Edit a custom background config...</source> <translation type="unfinished"></translation> </message> <message> <source>No turn back (disable moving to left)</source> <comment>Please, translate as &quot;One way scrolling&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Underwater</source> <translation type="unfinished"></translation> </message> <message> <source>Wrap horizontaly</source> <comment>This must be translated as &quot;Connect left and right sides&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Wrap vertically</source> <translation type="unfinished"></translation> </message> <message> <source>Current Section</source> <translation type="unfinished"></translation> </message> <message> <source>Section:</source> <translation type="unfinished"></translation> </message> <message> <source>Style</source> <translation type="unfinished"></translation> </message> <message> <source>Background image</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <source>Resize section</source> <translation type="unfinished"></translation> </message> <message> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <source>Music</source> <translation type="unfinished"></translation> </message> <message> <source>Custom</source> <comment>Flag of custom music on the level</comment> <translation type="unfinished"></translation> </message> <message> <source>Music file:</source> <translation type="unfinished"></translation> </message> <message> <source>[No image]</source> <translation type="unfinished"></translation> </message> <message> <source>[Silence]</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file first, if you want to manage custom background config files.</source> <translation type="unfinished"></translation> </message> <message> <source>Choose a background first</source> <translation type="unfinished"></translation> </message> <message> <source>Please, choose the background image first.</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file first, if you want to select custom music file.</source> <translation type="unfinished"></translation> </message> <message> <source>Name that will appear in the editor</source> <comment>A comment in the template of Background2 INI file.</comment> <translation type="unfinished"></translation> </message> <message> <source>Backdrop fill color</source> <comment>A comment in the template of Background2 INI file.</comment> <translation type="unfinished"></translation> </message> <message> <source>Add layers here, for example:</source> <comment>A comment in the template of Background2 INI file.</comment> <translation type="unfinished"></translation> </message> <message> <source>Error in the file %1: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Change the extra format specific settings of a custom music</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LvlWarpBox</name> <message> <source>Warps and Doors</source> <translation type="unfinished"></translation> </message> <message> <source>Main</source> <translation type="unfinished"></translation> </message> <message> <source>Layer:</source> <translation type="unfinished"></translation> </message> <message> <source>No Vehicles</source> <comment>In the SMBX - this option named as &quot;No Yoshi&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Allow NPC</source> <comment>Please, translate as &quot;Allow items&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Locked</source> <translation type="unfinished"></translation> </message> <message> <source>Set Exit</source> <translation type="unfinished"></translation> </message> <message> <source>Place exit point or quickly jump to existing warp</source> <translation type="unfinished"></translation> </message> <message> <source>Point already placed</source> <translation type="unfinished"></translation> </message> <message> <source>Defines the type of warp: 0 - Instant, player will be teleported movement speed will be reset to 0. 1 - Pipe, directional warp entrance and exit. 2 - Door, player can enter with up key. 3 - Portal, player will be teleported, but preserving movement speed.</source> <translation type="unfinished"></translation> </message> <message> <source>0 - Instant</source> <translation type="unfinished"></translation> </message> <message> <source>1 - Pipe</source> <translation type="unfinished"></translation> </message> <message> <source>2 - Door</source> <translation type="unfinished"></translation> </message> <message> <source>3 - Portal</source> <translation type="unfinished"></translation> </message> <message> <source>Message which will be shown if the player does not have the required number of stars</source> <translation type="unfinished"></translation> </message> <message> <source>Need stars message</source> <translation type="unfinished"></translation> </message> <message> <source>Need stars</source> <translation type="unfinished"></translation> </message> <message> <source>Required number of stars to enter this warp</source> <translation type="unfinished"></translation> </message> <message> <source>Warp type</source> <translation type="unfinished"></translation> </message> <message> <source>If this setting is enabled, even if this warp leads to another level, the number of existing and collected stars in the level will not be shown.</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t show level completion amount</source> <translation type="unfinished"></translation> </message> <message> <source>Place entrance point or quickly jump to already placed</source> <translation type="unfinished"></translation> </message> <message> <source>Set Entrance</source> <translation type="unfinished"></translation> </message> <message> <source>On-Enter event:</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger event when he player enters this warp</source> <translation type="unfinished"></translation> </message> <message> <source>Any mounted vehicles will be removed when player passes through this warp. They will be given back when player finishes the level or lose a life.</source> <translation type="unfinished"></translation> </message> <message> <source>Player can carry items and NPCs through this warp.</source> <translation type="unfinished"></translation> </message> <message> <source>Entrance closed with a lock. Need a key to open it.</source> <translation type="unfinished"></translation> </message> <message> <source>Entrance closed with a lock. Need to blow up the lock to open it.</source> <translation type="unfinished"></translation> </message> <message> <source>Bomb needed</source> <translation type="unfinished"></translation> </message> <message> <source>The player can only enter this warp under a special state. The special state is defined by the active configuration pack.</source> <translation type="unfinished"></translation> </message> <message> <source>Sp. State only</source> <translation type="unfinished"></translation> </message> <message> <source>Allow entering from both sides of this warp.</source> <translation type="unfinished"></translation> </message> <message> <source>Two-way warp</source> <translation type="unfinished"></translation> </message> <message> <source>Cannon shoot exit</source> <translation type="unfinished"></translation> </message> <message> <source>Projectile speed:</source> <translation type="unfinished"></translation> </message> <message> <source>The speed at which the player will exit the warp. Measured in pixels per 1/65 seconds.</source> <translation type="unfinished"></translation> </message> <message> <source>The direction in which the player will exit the warp.</source> <translation type="unfinished"></translation> </message> <message> <source>Cannon exit</source> <translation type="unfinished"></translation> </message> <message> <source>Pipe direction</source> <translation type="unfinished"></translation> </message> <message> <source>Entrance</source> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <translation type="unfinished"></translation> </message> <message> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <translation type="unfinished"></translation> </message> <message> <source>Exit</source> <translation type="unfinished"></translation> </message> <message> <source>Warp to World map</source> <translation type="unfinished"></translation> </message> <message> <source>X:</source> <translation type="unfinished"></translation> </message> <message> <source>Target coordinates of player on the world map when you exit from a level through this warp.</source> <translation type="unfinished"></translation> </message> <message> <source>Y:</source> <translation type="unfinished"></translation> </message> <message> <source>Browse the world map to set an exit point</source> <translation type="unfinished"></translation> </message> <message> <source>Set</source> <translation type="unfinished"></translation> </message> <message> <source>Level door</source> <translation type="unfinished"></translation> </message> <message> <source>Entering this warp ends the current level If this flag is enabled, you can only place a warp entrance.</source> <translation type="unfinished"></translation> </message> <message> <source>To other level</source> <translation type="unfinished"></translation> </message> <message> <source>Prevents any in-level warp to exit at this warp. Used for creating a warp from another level. If this flag is enabled, you can only place a warp exit.</source> <translation type="unfinished"></translation> </message> <message> <source>From other level</source> <translation type="unfinished"></translation> </message> <message> <source>Warp to other level</source> <translation type="unfinished"></translation> </message> <message> <source>If this field is not empty, player will travel from the current level to the specified one.</source> <translation type="unfinished"></translation> </message> <message> <source>Level file:</source> <translation type="unfinished"></translation> </message> <message> <source>Determines the warp through which the player will enter the target level. If set to zero, the player will start at the pre-defined level start point.</source> <translation type="unfinished"></translation> </message> <message> <source>Browse for another level file</source> <translation type="unfinished"></translation> </message> <message> <source>Show a blank screen instead of loading screen. In the Legacy Engine level loading screen, it would otherwise show the current playable character(s) and number of lives.</source> <translation type="unfinished"></translation> </message> <message> <source>Hide level enter screen</source> <translation type="unfinished"></translation> </message> <message> <source>Warp #</source> <comment>Translate as &quot;Door #&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Brings the player&apos;s held item to the target level of this warp.</source> <translation type="unfinished"></translation> </message> <message> <source>Allow inter-level NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Choose a warp entry to edit</source> <translation type="unfinished"></translation> </message> <message> <source>Create a new warp entry. Every warp point pair requires a warp entry.</source> <translation type="unfinished"></translation> </message> <message> <source>Remove current warp entry with all placed points.</source> <translation type="unfinished"></translation> </message> <message> <source>World map files not found</source> <translation type="unfinished"></translation> </message> <message> <source>You haven&apos;t available world map files with this level file. Please, put this level file with a world map, or create new world map in the same fomder with this level file. File path: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Select world map file</source> <translation type="unfinished"></translation> </message> <message> <source>Found more than one world map files. Please, select necessary world map in a list:</source> <translation type="unfinished"></translation> </message> <message> <source>File open error</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t open the file!</source> <translation type="unfinished"></translation> </message> <message> <source>Please save the file</source> <translation type="unfinished"></translation> </message> <message> <source>Please save the file before selecting levels.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainWindow</name> <message> <source>File</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation type="unfinished"></translation> </message> <message> <source>Open Recent</source> <translation type="unfinished"></translation> </message> <message> <source>Language</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Current section</source> <translation type="unfinished"></translation> </message> <message> <source>Section modifications</source> <translation type="unfinished"></translation> </message> <message> <source>World</source> <translation type="unfinished"></translation> </message> <message> <source>View</source> <translation type="unfinished"></translation> </message> <message> <source>Window</source> <translation type="unfinished"></translation> </message> <message> <source>Tools</source> <translation type="unfinished"></translation> </message> <message> <source>Palettes and tilesets</source> <translation type="unfinished"></translation> </message> <message> <source>External tools</source> <translation type="unfinished"></translation> </message> <message> <source>Custom data</source> <translation type="unfinished"></translation> </message> <message> <source>Edit</source> <translation type="unfinished"></translation> </message> <message> <source>Test</source> <translation type="unfinished"></translation> </message> <message> <source>Script</source> <translation type="unfinished"></translation> </message> <message> <source>General</source> <translation type="unfinished"></translation> </message> <message> <source>Wrap Horizontally</source> <translation type="unfinished"></translation> </message> <message> <source>CommonEdit Bar</source> <translation type="unfinished"></translation> </message> <message> <source>EditingTools</source> <translation type="unfinished"></translation> </message> <message> <source>LevelObj Tools</source> <translation type="unfinished"></translation> </message> <message> <source>World map Toolbar</source> <translation type="unfinished"></translation> </message> <message> <source>Level Sections Switch</source> <translation type="unfinished"></translation> </message> <message> <source>Section Settings</source> <translation type="unfinished"></translation> </message> <message> <source>Underwater</source> <translation type="unfinished"></translation> </message> <message> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <source>Warps and Doors</source> <translation type="unfinished"></translation> </message> <message> <source>Events</source> <translation type="unfinished"></translation> </message> <message> <source>Layers</source> <translation type="unfinished"></translation> </message> <message> <source>Placing</source> <translation type="unfinished"></translation> </message> <message> <source>Resizing</source> <translation type="unfinished"></translation> </message> <message> <source>Go to left-bottom of the section</source> <translation type="unfinished"></translation> </message> <message> <source>Return to the left-bottom of the Level Section or x=0:y=0 coordinate on the World map</source> <translation type="unfinished"></translation> </message> <message> <source>Go to the left-top of the section</source> <translation type="unfinished"></translation> </message> <message> <source>Return to the left-top of the Level Section or x=0:y=0 coordinate on the World map</source> <translation type="unfinished"></translation> </message> <message> <source>Lock Scenery tiles</source> <translation type="unfinished"></translation> </message> <message> <source>Rectangular fill</source> <translation type="unfinished"></translation> </message> <message> <source>Rectangular Fill (Shift+S)</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset Item Box</source> <translation type="unfinished"></translation> </message> <message> <source>Debugger</source> <translation type="unfinished"></translation> </message> <message> <source>Testing options...</source> <translation type="unfinished"></translation> </message> <message> <source>Position bookmarks</source> <translation type="unfinished"></translation> </message> <message> <source>Open...</source> <translation type="unfinished"></translation> </message> <message> <source>Help</source> <translation type="unfinished"></translation> </message> <message> <source>Set align grid size</source> <translation type="unfinished"></translation> </message> <message> <source>LunaLUA scripts</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration</source> <translation type="unfinished"></translation> </message> <message> <source>Plugins</source> <translation type="unfinished"></translation> </message> <message> <source>Open (Ctrl+O)</source> <translation type="unfinished"></translation> </message> <message> <source>Level...</source> <translation type="unfinished"></translation> </message> <message> <source>World map...</source> <translation type="unfinished"></translation> </message> <message> <source>NPC config...</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Save (Ctrl+S)</source> <translation type="unfinished"></translation> </message> <message> <source>Save as...</source> <translation type="unfinished"></translation> </message> <message> <source>Save as (Ctrl+Shift+S)</source> <translation type="unfinished"></translation> </message> <message> <source>Close</source> <translation type="unfinished"></translation> </message> <message> <source>Save all</source> <translation type="unfinished"></translation> </message> <message> <source>Save all (Ctrl+Alt+S)</source> <translation type="unfinished"></translation> </message> <message> <source>About</source> <translation type="unfinished"></translation> </message> <message> <source>Contents</source> <translation type="unfinished"></translation> </message> <message> <source>Contents (F1)</source> <translation type="unfinished"></translation> </message> <message> <source>Section 1</source> <translation type="unfinished">Bagian 1</translation> </message> <message> <source>Section 2</source> <translation type="unfinished">Bagian 2</translation> </message> <message> <source>Section 3</source> <translation type="unfinished">Bagian 3</translation> </message> <message> <source>Section 4</source> <translation type="unfinished">Bagian 4</translation> </message> <message> <source>Section 5</source> <translation type="unfinished">Bagian 5</translation> </message> <message> <source>Section 6</source> <translation type="unfinished">Bagian 6</translation> </message> <message> <source>Section 7</source> <translation type="unfinished">Bagian 7</translation> </message> <message> <source>Section 8</source> <translation type="unfinished">Bagian 8</translation> </message> <message> <source>Section 9</source> <translation type="unfinished">Bagian 9</translation> </message> <message> <source>Section 10</source> <translation type="unfinished">Bagian 10</translation> </message> <message> <source>Section 11</source> <translation type="unfinished">Bagian 11</translation> </message> <message> <source>Section 12</source> <translation type="unfinished">Bagian 12</translation> </message> <message> <source>Section 13</source> <translation type="unfinished">Bagian 13</translation> </message> <message> <source>Section 14</source> <translation type="unfinished">Bagian 14</translation> </message> <message> <source>Section 15</source> <translation type="unfinished">Bagian 15</translation> </message> <message> <source>Section 16</source> <translation type="unfinished">Bagian 16</translation> </message> <message> <source>Section 17</source> <translation type="unfinished">Bagian 17</translation> </message> <message> <source>Section 18</source> <translation type="unfinished">Bagian 18</translation> </message> <message> <source>Section 19</source> <translation type="unfinished">Bagian 19</translation> </message> <message> <source>Section 20</source> <translation type="unfinished">Bagian 20</translation> </message> <message> <source>Offscreen exit</source> <translation type="unfinished"></translation> </message> <message> <source>No turn back</source> <translation type="unfinished"></translation> </message> <message> <source>Export to image...</source> <translation type="unfinished"></translation> </message> <message> <source>Export current section to image (F12)</source> <translation type="unfinished"></translation> </message> <message> <source>Properties...</source> <translation type="unfinished"></translation> </message> <message> <source>Disable world map</source> <translation type="unfinished"></translation> </message> <message> <source>Restart level after fail</source> <translation type="unfinished"></translation> </message> <message> <source>Select and Move</source> <translation type="unfinished"></translation> </message> <message> <source>Select (S)</source> <translation type="unfinished"></translation> </message> <message> <source>Eriser</source> <translation type="unfinished"></translation> </message> <message> <source>Eriser (E)</source> <translation type="unfinished"></translation> </message> <message> <source>Reload configuration pack</source> <translation type="unfinished"></translation> </message> <message> <source>Attach to grid</source> <translation type="unfinished"></translation> </message> <message> <source>Lock all Blocks</source> <translation type="unfinished"></translation> </message> <message> <source>Lock all BGO</source> <translation type="unfinished"></translation> </message> <message> <source>Lock all NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Lock all door objects</source> <translation type="unfinished"></translation> </message> <message> <source>Lock all water squares</source> <translation type="unfinished"></translation> </message> <message> <source>Set first player position</source> <translation type="unfinished"></translation> </message> <message> <source>Set first player start point</source> <translation type="unfinished"></translation> </message> <message> <source>Set second player position</source> <translation type="unfinished"></translation> </message> <message> <source>Set second player start point</source> <translation type="unfinished"></translation> </message> <message> <source>Play music</source> <translation type="unfinished"></translation> </message> <message> <source>Play music (F11)</source> <translation type="unfinished"></translation> </message> <message> <source>Reload file data</source> <translation type="unfinished"></translation> </message> <message> <source>Reload current file data</source> <translation type="unfinished"></translation> </message> <message> <source>Scroll hand</source> <translation type="unfinished"></translation> </message> <message> <source>Scrolling (D)</source> <translation type="unfinished"></translation> </message> <message> <source>Undo</source> <translation type="unfinished"></translation> </message> <message> <source>Redo</source> <translation type="unfinished"></translation> </message> <message> <source>Animation</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Enable animation on animated objects&lt;/p&gt;&lt;p&gt;&lt;span style=&quot; font-style:italic; color:#aa0000;&quot;&gt;If the map has too many objects, it&apos;s recommended to &lt;/span&gt;&lt;span style=&quot; font-weight:600; font-style:italic; color:#aa0000;&quot;&gt;disable&lt;/span&gt;&lt;span style=&quot; font-style:italic; color:#aa0000;&quot;&gt; this option!&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;empty&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Copy</source> <translation type="unfinished"></translation> </message> <message> <source>Copy selected items</source> <translation type="unfinished"></translation> </message> <message> <source>Prevent overlap</source> <translation type="unfinished"></translation> </message> <message> <source>Prevents similar items from overlapping each other. Objects will not be able to be placed on top of each other, and attempting to do so will result in the selected object returning to its original position. If this flag is disabled, you will be able to move elements over each other with no limitation. Objects will never be allowed to overlap when placing new objects, unless you are duplicating or pasting from the clipboard, which will always allow overlapping.</source> <translation type="unfinished"></translation> </message> <message> <source>Draw Water zone</source> <translation type="unfinished"></translation> </message> <message> <source>Hold mouse button on map and move mouse for draw water zone</source> <translation type="unfinished"></translation> </message> <message> <source>Draw QuickSand zone</source> <translation type="unfinished"></translation> </message> <message> <source>Hold mouse button on map and move mouse for draw quicksand zone</source> <translation type="unfinished"></translation> </message> <message> <source>Paste</source> <translation type="unfinished"></translation> </message> <message> <source>[No opened files]</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished"></translation> </message> <message> <source>Select only</source> <translation type="unfinished"></translation> </message> <message> <source>Application settings</source> <translation type="unfinished"></translation> </message> <message> <source>Current configuration status...</source> <translation type="unfinished"></translation> </message> <message> <source>Level Search</source> <translation type="unfinished"></translation> </message> <message> <source>Search for an Item on the Level</source> <translation type="unfinished"></translation> </message> <message> <source>Refresh menus</source> <translation type="unfinished"></translation> </message> <message> <source>Fullscreen</source> <translation type="unfinished"></translation> </message> <message> <source>Tilesets Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Fix Lazily-made graphics (LazyFixTool)...</source> <translation type="unfinished"></translation> </message> <message> <source>Convert GIF with mask to PNG (GIFs2PNG)...</source> <translation type="unfinished"></translation> </message> <message> <source>Convert PNG to GIF with mask (PNG2GIFs)...</source> <translation type="unfinished"></translation> </message> <message> <source>World settings</source> <translation type="unfinished"></translation> </message> <message> <source>Lock Terrain tiles</source> <translation type="unfinished"></translation> </message> <message> <source>Lock Paths</source> <translation type="unfinished"></translation> </message> <message> <source>Lock Levels</source> <translation type="unfinished"></translation> </message> <message> <source>Lock Music Boxes</source> <translation type="unfinished"></translation> </message> <message> <source>Circular fill</source> <translation type="unfinished"></translation> </message> <message> <source>Circular fill (Shift+C)</source> <translation type="unfinished"></translation> </message> <message> <source>Show grid</source> <translation type="unfinished"></translation> </message> <message> <source>Modern GUI</source> <translation type="unfinished"></translation> </message> <message> <source>Variables</source> <translation type="unfinished"></translation> </message> <message> <source>Go to top-right of the section</source> <translation type="unfinished"></translation> </message> <message> <source>Go to right-bottom of the section</source> <translation type="unfinished"></translation> </message> <message> <source>Script Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Run configure tool...</source> <translation type="unfinished"></translation> </message> <message> <source>Open local script</source> <translation type="unfinished"></translation> </message> <message> <source>Open the level / world map local script. If it does not exist, a file will be created.</source> <translation type="unfinished"></translation> </message> <message> <source>Open episode script</source> <translation type="unfinished"></translation> </message> <message> <source>Open the episode common script. If it does not exist, a file will be created.</source> <translation type="unfinished"></translation> </message> <message> <source>Level local (%1)</source> <translation type="unfinished"></translation> </message> <message> <source>Local level script for current level. New script file name to replace old &quot;lunadll.lua&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Level global (%1)</source> <translation type="unfinished"></translation> </message> <message> <source>Global level script for entire episode. New script file name to replace old &quot;lunaworld.lua&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>World map script (%1)</source> <translation type="unfinished"></translation> </message> <message> <source>Global world map script. New script file name to replace old &quot;lunaoverworld.lua&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Welcome dialog</source> <translation type="unfinished"></translation> </message> <message> <source>Overwrite mode</source> <translation type="unfinished"></translation> </message> <message> <source>Exit</source> <comment>Because in some languages the &quot;exit from programm&quot; and &quot;exit door&quot; have diffirence words, please, translate this as &quot;Exit&quot;</comment> <extracomment>Exit from the editor</extracomment> <translation type="unfinished"></translation> </message> <message> <source>Section 0</source> <translation>Bagian 0</translation> </message> <message> <source>Apply (Enter)</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel (Esc)</source> <translation type="unfinished"></translation> </message> <message> <source>Line</source> <translation type="unfinished"></translation> </message> <message> <source>Line (Shift+D)</source> <translation type="unfinished"></translation> </message> <message> <source>World map Search</source> <comment>Must be like &quot;Search on the world map&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Show Developer Console</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset Groups Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Zoom In</source> <translation type="unfinished"></translation> </message> <message> <source>Zoom Out</source> <translation type="unfinished"></translation> </message> <message> <source>Reset Zoom</source> <translation type="unfinished"></translation> </message> <message> <source>Change configuration pack...</source> <translation type="unfinished"></translation> </message> <message> <source>Semi-transparent paths</source> <translation type="unfinished"></translation> </message> <message> <source>Export section to image...</source> <translation type="unfinished"></translation> </message> <message> <source>Export whole level section to image</source> <translation type="unfinished"></translation> </message> <message> <source>Fill</source> <translation type="unfinished"></translation> </message> <message> <source>Clear unused data</source> <translation type="unfinished"></translation> </message> <message> <source>Show properties</source> <translation type="unfinished"></translation> </message> <message> <source>Show properties of item</source> <translation type="unfinished"></translation> </message> <message> <source>Sprite Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Import...</source> <translation type="unfinished"></translation> </message> <message> <source>Import</source> <translation type="unfinished"></translation> </message> <message> <source>Bookmark specific camera positions. You can use these bookmarks to easily return to important places on a large map.</source> <translation type="unfinished"></translation> </message> <message> <source>Clone section to...</source> <translation type="unfinished"></translation> </message> <message> <source>Rotate left</source> <translation type="unfinished"></translation> </message> <message> <source>Rotate right</source> <translation type="unfinished"></translation> </message> <message> <source>Flip horizontal</source> <translation type="unfinished"></translation> </message> <message> <source>Flip vertical</source> <translation type="unfinished"></translation> </message> <message> <source>Align selected</source> <translation type="unfinished"></translation> </message> <message> <source>Fix wrong masks</source> <translation type="unfinished"></translation> </message> <message> <source>This tool will fix all wrong masks of images which causing display bugs</source> <translation type="unfinished"></translation> </message> <message> <source>Delete section</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t fill out of section</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX-like GUI</source> <translation type="unfinished"></translation> </message> <message> <source>Run testing of saved file</source> <translation type="unfinished"></translation> </message> <message> <source>Change log</source> <translation type="unfinished"></translation> </message> <message> <source>Check for updates...</source> <translation type="unfinished"></translation> </message> <message> <source>Convert Audio files...</source> <translation type="unfinished"></translation> </message> <message> <source>Clear NPC garbadge...</source> <translation type="unfinished"></translation> </message> <message> <source>More sections...</source> <translation type="unfinished"></translation> </message> <message> <source>Tip of the day...</source> <translation type="unfinished"></translation> </message> <message> <source>Launch game engine application.</source> <translation type="unfinished"></translation> </message> <message> <source>Open folder of current file</source> <translation type="unfinished"></translation> </message> <message> <source>Open folder which contains currently opened file</source> <translation type="unfinished"></translation> </message> <message> <source>Open custom data folder</source> <translation type="unfinished"></translation> </message> <message> <source>Open a custom folder: a folder with a name equal to the basen ame of the currently opened file.</source> <translation type="unfinished"></translation> </message> <message> <source>Wrap Vertically</source> <translation type="unfinished"></translation> </message> <message> <source>[all]</source> <translation type="unfinished"></translation> </message> <message> <source>File open error</source> <translation type="unfinished"></translation> </message> <message> <source>[None]</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>%1 blocks, %2 BGO, %3 NPC, %4 Water items have been copied to clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>%1 tiles, %2 sceneries, %3 paths, %4 levels, %5 music boxes items have been copied to clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>%1 blocks, %2 BGO, %3 NPC, %4 Water items have been moved to clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>%1 tiles, %2 sceneries, %3 paths, %4 levels, %5 music boxes items have been moved to clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration is loaded with errors</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot create NPC config file: The configuration pack was loaded, but contains errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Create new NPC.txt configuration file</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot create level file: The configuration pack was loaded, but contains errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot create world map file: The configuration pack was loaded, but contains errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Untitled file</source> <translation type="unfinished"></translation> </message> <message> <source>Please save file to the disk first.</source> <translation type="unfinished"></translation> </message> <message> <source>Editor cannot open files: Configuration package is loaded with errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Open file</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot open file: The configuration pack was loaded, but contains errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t open the file: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Level file loaded</source> <translation type="unfinished"></translation> </message> <message> <source>World map file loaded</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t read the file</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Config loaded</source> <translation type="unfinished"></translation> </message> <message> <source>Game save statistics</source> <translation type="unfinished"></translation> </message> <message> <source>Bad file</source> <translation type="unfinished"></translation> </message> <message> <source>This file have unknown extension</source> <translation type="unfinished"></translation> </message> <message> <source>File not saved</source> <translation type="unfinished"></translation> </message> <message> <source>File doesn&apos;t saved on disk.</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t open the file! File not exist.</source> <translation type="unfinished"></translation> </message> <message> <source>Reload file and custom stuff</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to save before reload stuff?</source> <translation type="unfinished"></translation> </message> <message> <source>Reloading error</source> <translation type="unfinished"></translation> </message> <message> <source>Level file reloaded</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Config reloaded</source> <translation type="unfinished"></translation> </message> <message> <source>Saving of file...</source> <translation type="unfinished"></translation> </message> <message> <source>Saving</source> <translation type="unfinished"></translation> </message> <message> <source>File saved</source> <translation type="unfinished"></translation> </message> <message> <source>Saving of files...</source> <translation type="unfinished"></translation> </message> <message> <source>Clonning of section...</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait...</source> <translation type="unfinished"></translation> </message> <message> <source>Section has been clonned</source> <translation type="unfinished"></translation> </message> <message> <source>Section has been successfully cloned! Do you want to clone another section?</source> <translation type="unfinished"></translation> </message> <message> <source>Remove section</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to remove all objects of this section?</source> <translation type="unfinished"></translation> </message> <message> <source>Margin of section</source> <translation type="unfinished"></translation> </message> <message> <source>Please select how far items can travel beyond the section boundaries (in pixels) before they are removed.</source> <translation type="unfinished"></translation> </message> <message> <source>Section has been removed</source> <translation type="unfinished"></translation> </message> <message> <source>Section %1 has been successfully deleted!</source> <translation type="unfinished"></translation> </message> <message> <source>Please select how far items can rotate beyond the section boundaries (in pixels) before they are removed.</source> <translation type="unfinished"></translation> </message> <message> <source>Sub-windows</source> <translation type="unfinished"></translation> </message> <message> <source>Tab Windows</source> <translation type="unfinished"></translation> </message> <message> <source>Close current</source> <translation type="unfinished"></translation> </message> <message> <source>Cascade</source> <translation type="unfinished"></translation> </message> <message> <source>Tiled</source> <translation type="unfinished"></translation> </message> <message> <source>[No files open]</source> <translation type="unfinished"></translation> </message> <message> <source>Engine is not found</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start testing, engine is not found: %1 Please, choose the engine application yourself!</source> <translation type="unfinished"></translation> </message> <message> <source>Choose the Engine application</source> <translation type="unfinished"></translation> </message> <message> <source>Engine already runned</source> <translation type="unfinished"></translation> </message> <message> <source>Engine is already testing another level. Do you want to abort current testing process?</source> <translation type="unfinished"></translation> </message> <message> <source>World map testing of saved file</source> <translation type="unfinished"></translation> </message> <message> <source>File is not saved! Do you want to save file or you want to run test of copy which is currently saved on the disk?</source> <translation type="unfinished"></translation> </message> <message> <source>Save file first</source> <translation type="unfinished"></translation> </message> <message> <source>To run testing of saved file, please save them into disk first! You can run testing without saving of file if you will use &quot;Run testing&quot; menu item.</source> <translation type="unfinished"></translation> </message> <message> <source>PGE Engine testing</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t show this message again.</source> <translation type="unfinished"></translation> </message> <message> <source>Hello! You are attempting to test a level in the PGE Engine. The PGE Engine is still at an early stage in development, and there are several features which are missing or do not work correctly. If you are making levels or episodes for the old SMBX Engine and you want to test them with a complete feature-set, please test them in SMBX directly. Use PGE Testing for cases when you want to test the PGE Engine itself or you want to test levels with PGE-specific features.</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration is busy</source> <translation type="unfinished"></translation> </message> <message> <source>Reloading configuration pack</source> <translation type="unfinished"></translation> </message> <message> <source>Reloading configuration</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration successfully reloaded!</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration changed</source> <translation type="unfinished"></translation> </message> <message> <source>Select directory with custom data to import.</source> <translation type="unfinished"></translation> </message> <message> <source>File is untitled</source> <translation type="unfinished"></translation> </message> <message> <source>File doesn&apos;t use custom graphics. </source> <translation type="unfinished"></translation> </message> <message> <source>Nothing to do.</source> <translation type="unfinished"></translation> </message> <message> <source>This file is not use GIF graphics with transparent masks or haven&apos;t custom graphics.</source> <translation type="unfinished"></translation> </message> <message> <source>Fixing of masks...</source> <translation type="unfinished"></translation> </message> <message> <source>Done</source> <translation type="unfinished"></translation> </message> <message> <source>Masks has been fixed! Please reload current file to apply result.</source> <translation type="unfinished"></translation> </message> <message> <source>Current Language changed to %1</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration error</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration can&apos;t be loaded. See %1 for more information.</source> <translation type="unfinished"></translation> </message> <message> <source>Loading theme...</source> <translation type="unfinished"></translation> </message> <message> <source>Initializing dock widgets...</source> <translation type="unfinished"></translation> </message> <message> <source>Initalizing plugins...</source> <translation type="unfinished"></translation> </message> <message> <source>Finishing loading...</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration package is loaded with errors.</source> <translation type="unfinished"></translation> </message> <message> <source>Open</source> <translation type="unfinished"></translation> </message> <message> <source>No file loaded!</source> <translation type="unfinished"></translation> </message> <message> <source>NPC garbage clean-up</source> <translation type="unfinished"></translation> </message> <message> <source>Everything is fine, level has no NPC garbage!</source> <translation type="unfinished"></translation> </message> <message> <source>Found %1 junk NPC&apos;s. Do you want to remove them? Press &quot;Help&quot; to show info about the junk NPCs we found.</source> <translation type="unfinished"></translation> </message> <message> <source>NPC garbabe has been removed! This operation can be undone with Ctrl+Z or Edit/Undo action.</source> <translation type="unfinished"></translation> </message> <message> <source>Section %1</source> <translation type="unfinished"></translation> </message> <message> <source>Initialize section %1...</source> <translation type="unfinished"></translation> </message> <message> <source>File is not saved</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to open/create script file. Please save the file first.</source> <translation type="unfinished"></translation> </message> <message> <source>Default by item</source> <translation type="unfinished"></translation> </message> <message> <source>Custom...</source> <translation type="unfinished"></translation> </message> <message> <source>Select</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Erase</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Items</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Player</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Section</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>World settings</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Warps and Doors</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Water</source> <comment>Vanilla-like toolbar</comment> <translation type="unfinished"></translation> </message> <message> <source>Options</source> <translation type="unfinished"></translation> </message> <message> <source>Custom align grid size</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter grid alignment size:</source> <translation type="unfinished"></translation> </message> <message> <source>When reloading the configuration, all opened files will be closed and restored after reloading. Do you want to continue?</source> <translation type="unfinished"></translation> </message> <message> <source>The configuration pack has changed! To start using the new configuration pack, you need to restart the Editor. Do you want to continue?</source> <translation type="unfinished"></translation> </message> <message> <source>Level items browser</source> <translation type="unfinished"></translation> </message> <message> <source>Items browser with a search</source> <translation type="unfinished"></translation> </message> <message> <source>World map items browser</source> <translation type="unfinished"></translation> </message> <message> <source>Music change points</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration can&apos;t be loaded: %1. See %2 for more information.</source> <translation type="unfinished"></translation> </message> <message> <source>Test level</source> <translation type="unfinished"></translation> </message> <message> <source>Start Game</source> <translation type="unfinished"></translation> </message> <message> <source>Test world map</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;no extra settings&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Show camera grid</source> <translation type="unfinished"></translation> </message> <message> <source>Level is incompatible</source> <translation type="unfinished"></translation> </message> <message> <source>This level file was created in an editor that was using an unrecognized config pack. This most likely means this level was designed to be used with a different engine rather than %1. It is likely that some blocks/NPCs/scripts/etc will not be compatible, and may cause unexpected gameplay results or errors. Filename: %2 Level&apos;s config pack ID: %3 Expected config pack ID: %4</source> <translation type="unfinished"></translation> </message> <message> <source>World map is incompatible</source> <translation type="unfinished"></translation> </message> <message> <source>This world map file was created in an editor that was using an unrecognized config pack. This most likely means this world map was designed to be used with a different engine rather than %1. It is likely that some terrain/levels/scripts/etc will not be compatible, and may cause unexpected gameplay results or errors. Filename: %2 Level&apos;s config pack ID: %3 Expected config pack ID: %4</source> <translation type="unfinished"></translation> </message> <message> <source>Running the 32-bit Editor a 64-bit processor</source> <translation type="unfinished"></translation> </message> <message> <source>You are using the 32-bit version of the Editor on a 64-bit processor. This Editor version targeted to legacy architectures and Windows XP compatibility. We highly recommend getting the 64-bit version of the Editor to have better compatibility with modern architectures and to extend a limit of memory usage. For 32-bit applications, there is a 2 GB memory limit.</source> <translation type="unfinished"></translation> </message> <message> <source>Editor, version %1</source> <translation type="unfinished"></translation> </message> <message> <source>Moondust Maintainer is not found</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start the utility, Moondust Maintainer is not found: %1 Please, choose the Moondust Maintainer application yourself!</source> <translation type="unfinished"></translation> </message> <message> <source>Choose the Moondust Maintainer application</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MusicFileList</name> <message> <source>Select Custom music</source> <translation type="unfinished"></translation> </message> <message> <source>Select SFX file</source> <translation type="unfinished"></translation> </message> <message> <source>Please select SFX file to use</source> <translation type="unfinished"></translation> </message> <message> <source>Please select music file to use as custom</source> <translation type="unfinished"></translation> </message> </context> <context> <name>NpcEdit</name> <message> <source>NPC ID</source> <translation type="unfinished"></translation> </message> <message> <source>Physics</source> <translation type="unfinished"></translation> </message> <message> <source>Width</source> <translation type="unfinished"></translation> </message> <message> <source> px</source> <translation type="unfinished"></translation> </message> <message> <source>Height</source> <translation type="unfinished"></translation> </message> <message> <source>Speed multiplier</source> <translation type="unfinished"></translation> </message> <message> <source>Player collision top</source> <translation type="unfinished"></translation> </message> <message> <source>Player collision</source> <translation type="unfinished"></translation> </message> <message> <source>NPC collision top</source> <translation type="unfinished"></translation> </message> <message> <source>NPC collision</source> <translation type="unfinished"></translation> </message> <message> <source>Disable Gravity</source> <translation type="unfinished"></translation> </message> <message> <source>Turn on cliff</source> <translation type="unfinished"></translation> </message> <message> <source>Disable Block collision</source> <translation type="unfinished"></translation> </message> <message> <source>Reset</source> <translation type="unfinished"></translation> </message> <message> <source>Graphics</source> <translation type="unfinished"></translation> </message> <message> <source>Alignment in the editor:</source> <translation type="unfinished"></translation> </message> <message> <source>Grid size</source> <translation type="unfinished"></translation> </message> <message> <source>offset y</source> <translation type="unfinished"></translation> </message> <message> <source>offset x</source> <translation type="unfinished"></translation> </message> <message> <source>Frame style</source> <translation type="unfinished"></translation> </message> <message> <source>Frames</source> <translation type="unfinished"></translation> </message> <message> <source>General</source> <translation type="unfinished"></translation> </message> <message> <source>Frame speed multiplier</source> <translation type="unfinished"></translation> </message> <message> <source>Single sprite</source> <translation type="unfinished"></translation> </message> <message> <source>Left-Right direction</source> <translation type="unfinished"></translation> </message> <message> <source>Left-Right-Grabbed</source> <translation type="unfinished"></translation> </message> <message> <source>Foreground</source> <translation type="unfinished"></translation> </message> <message> <source>In game</source> <translation type="unfinished"></translation> </message> <message> <source>Grab side</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t kill on fireball</source> <translation type="unfinished"></translation> </message> <message> <source>Score</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t be eaten</source> <translation type="unfinished"></translation> </message> <message> <source>Jump hurt</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t hurt</source> <translation type="unfinished"></translation> </message> <message> <source>[none]</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t freeze on fireball</source> <translation type="unfinished"></translation> </message> <message> <source>Grab top</source> <translation type="unfinished"></translation> </message> <message> <source>Grid offset X</source> <translation type="unfinished"></translation> </message> <message> <source>Grid offset Y</source> <translation type="unfinished"></translation> </message> <message> <source>Middle of cell by center</source> <translation type="unfinished"></translation> </message> <message> <source>Edge of cell by center</source> <translation type="unfinished"></translation> </message> <message> <source>Align at</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t kill on hammer</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t kill by other NPC&apos;s</source> <translation type="unfinished"></translation> </message> <message> <source>Default health level</source> <translation type="unfinished"></translation> </message> <message> <source>Preview</source> <translation type="unfinished"></translation> </message> <message> <source>Modyfied</source> <translation type="unfinished"></translation> </message> <message> <source>Name:</source> <translation type="unfinished"></translation> </message> <message> <source>Load file error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot read file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source>Save As</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX custom NPC config file (npc-*.txt)</source> <translation type="unfinished"></translation> </message> <message> <source>File save error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot save file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source> not saved</source> <translation type="unfinished"></translation> </message> <message> <source>&apos;%1&apos; has been modified. Do you want to save your changes?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PGE_EditorPluginInfo</name> <message> <source>Plugin Manager</source> <translation type="unfinished"></translation> </message> <message> <source>Name:</source> <translation type="unfinished"></translation> </message> <message> <source>Author:</source> <translation type="unfinished"></translation> </message> <message> <source>Version:</source> <translation type="unfinished"></translation> </message> <message> <source>Description:</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load &quot;%1&quot; package! Error description: %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PGE_EditorPluginManager</name> <message> <source>%1 at line %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PgeEngine</name> <message> <source>Test level/world</source> <comment>Run the testing of current file in PGE Engine via interprocessing tunnel.</comment> <translation type="unfinished"></translation> </message> <message> <source>Test saved level/world</source> <comment>Run the testing of current file in PGE Engine from disk.</comment> <translation type="unfinished"></translation> </message> <message> <source>Start Game</source> <comment>Launch PGE Engine as a normal game</comment> <translation type="unfinished"></translation> </message> <message> <source>Unsupported yet</source> <translation type="unfinished"></translation> </message> <message> <source>Currently this is not supported for world maps yet. Please use &apos;Test saved level/world&apos; action tu run a world map test.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QMessageBox</name> <message> <source>File association failed.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QObject</name> <message> <source>Invizible</source> <translation type="unfinished"></translation> </message> <message> <source>Slippery</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Z-Offset</source> <translation type="unfinished"></translation> </message> <message> <source>Friendly</source> <translation type="unfinished"></translation> </message> <message> <source>Boss</source> <translation type="unfinished"></translation> </message> <message> <source>Not Moveable</source> <translation type="unfinished"></translation> </message> <message> <source>Message</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Included NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Water Type</source> <translation type="unfinished"></translation> </message> <message> <source>Layer</source> <translation type="unfinished"></translation> </message> <message> <source>No Vehicles</source> <translation type="unfinished"></translation> </message> <message> <source>Two-way warp</source> <translation type="unfinished"></translation> </message> <message> <source>Allow NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Allow NPC inter level</source> <translation type="unfinished"></translation> </message> <message> <source>Locked</source> <translation type="unfinished"></translation> </message> <message> <source>Need a bomb</source> <translation type="unfinished"></translation> </message> <message> <source>Hide number of stars</source> <translation type="unfinished"></translation> </message> <message> <source>Enable cannon exit</source> <translation type="unfinished"></translation> </message> <message> <source>Special state required</source> <translation type="unfinished"></translation> </message> <message> <source>Hide level entering scene</source> <translation type="unfinished"></translation> </message> <message> <source>Warp Type</source> <translation type="unfinished"></translation> </message> <message> <source>Need Stars</source> <translation type="unfinished"></translation> </message> <message> <source>Need Stars message</source> <translation type="unfinished"></translation> </message> <message> <source>Cannon exit projectile speed</source> <translation type="unfinished"></translation> </message> <message> <source>Entrance Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Exit Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Set Level Exit</source> <translation type="unfinished"></translation> </message> <message> <source>Set Level Entrance</source> <translation type="unfinished"></translation> </message> <message> <source>Level Warp To</source> <translation type="unfinished"></translation> </message> <message> <source>Activate Generator</source> <translation type="unfinished"></translation> </message> <message> <source>Generator Type</source> <translation type="unfinished"></translation> </message> <message> <source>Generator Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Generator Time</source> <translation type="unfinished"></translation> </message> <message> <source>Attach Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Event Block Destroyed</source> <translation type="unfinished"></translation> </message> <message> <source>Event Block Hited</source> <translation type="unfinished"></translation> </message> <message> <source>Event Layer Empty</source> <translation type="unfinished"></translation> </message> <message> <source>Event NPC Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Event NPC Die</source> <translation type="unfinished"></translation> </message> <message> <source>Event NPC Talk</source> <translation type="unfinished"></translation> </message> <message> <source>Event Warp Enter</source> <translation type="unfinished"></translation> </message> <message> <source>NPC Special Data</source> <translation type="unfinished"></translation> </message> <message> <source>Autostart</source> <translation type="unfinished"></translation> </message> <message> <source>Layer Smoke Effect</source> <translation type="unfinished"></translation> </message> <message> <source>Add Hide Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Remove Hide Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Add Show Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Remove Show Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Add Toggle Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Remove Toggle Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Moving Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Layer Speed Horizontal</source> <translation type="unfinished"></translation> </message> <message> <source>Layer Speed Vertical</source> <translation type="unfinished"></translation> </message> <message> <source>Autoscroll Layer</source> <translation type="unfinished"></translation> </message> <message> <source>Autoscroll Layer Speed Horizontal</source> <translation type="unfinished"></translation> </message> <message> <source>Autoscroll Layer Speed Vertical</source> <translation type="unfinished"></translation> </message> <message> <source>Section Size</source> <translation type="unfinished"></translation> </message> <message> <source>Section Music</source> <translation type="unfinished"></translation> </message> <message> <source>Section Background</source> <translation type="unfinished"></translation> </message> <message> <source>Sound</source> <translation type="unfinished"></translation> </message> <message> <source>End Game</source> <translation type="unfinished"></translation> </message> <message> <source>Up Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Down Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Left Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Right Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Run Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Alt Run Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Jump Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Alt Jump Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Drop Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Start Key Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger Activate</source> <translation type="unfinished"></translation> </message> <message> <source>Trigger Delay</source> <translation type="unfinished"></translation> </message> <message> <source>Is Warp</source> <translation type="unfinished"></translation> </message> <message> <source>No Back</source> <translation type="unfinished"></translation> </message> <message> <source>Off Screen Exit</source> <translation type="unfinished"></translation> </message> <message> <source>Underwater</source> <translation type="unfinished"></translation> </message> <message> <source>Background Image</source> <translation type="unfinished"></translation> </message> <message> <source>Music</source> <translation type="unfinished"></translation> </message> <message> <source>Custom Music</source> <translation type="unfinished"></translation> </message> <message> <source>BGO Sorting Priority</source> <translation type="unfinished"></translation> </message> <message> <source>Unknown</source> <translation type="unfinished"></translation> </message> <message> <source>Always Visible</source> <translation type="unfinished"></translation> </message> <message> <source>Big Path Background</source> <translation type="unfinished"></translation> </message> <message> <source>Character</source> <translation type="unfinished"></translation> </message> <message> <source>Door ID</source> <translation type="unfinished"></translation> </message> <message> <source>Game start point</source> <translation type="unfinished"></translation> </message> <message> <source>Goto X</source> <translation type="unfinished"></translation> </message> <message> <source>Goto Y</source> <translation type="unfinished"></translation> </message> <message> <source>Hub styled world</source> <translation type="unfinished"></translation> </message> <message> <source>Intro Level</source> <translation type="unfinished"></translation> </message> <message> <source>Level file</source> <translation type="unfinished"></translation> </message> <message> <source>Level title</source> <translation type="unfinished"></translation> </message> <message> <source>Path Background</source> <translation type="unfinished"></translation> </message> <message> <source>Exit at bottom</source> <translation type="unfinished"></translation> </message> <message> <source>Exit at left</source> <translation type="unfinished"></translation> </message> <message> <source>Exit at right</source> <translation type="unfinished"></translation> </message> <message> <source>Exit at top</source> <translation type="unfinished"></translation> </message> <message> <source>Restart after fail</source> <translation type="unfinished"></translation> </message> <message> <source>Total stars</source> <translation type="unfinished"></translation> </message> <message> <source>We&apos;re sorry, but PGE Editor has crashed. Reason: Out of memory! To prevent this, try closing other uneccessary programs to free up more memory.</source> <translation type="unfinished"></translation> </message> <message> <source>We&apos;re sorry, but PGE Editor has crashed. Reason: Unhandled Exception Please inform our forum staff so we can try to fix this problem, Thank you Forum link: wohlsoft.ru/forum</source> <translation type="unfinished"></translation> </message> <message> <source>Terminal was closed [SIGHUP]</source> <translation type="unfinished"></translation> </message> <message> <source>Quit command [SIGQUIT]</source> <translation type="unfinished"></translation> </message> <message> <source>Editor was abourted because alarm() time out! [SIGALRM]</source> <translation type="unfinished"></translation> </message> <message> <source>Editor was abourted because physical memory error! [SIGBUS]</source> <translation type="unfinished"></translation> </message> <message> <source>Wrong CPU Instruction [SIGILL]</source> <translation type="unfinished"></translation> </message> <message> <source>Floating-point exception [SIGFPE]</source> <translation type="unfinished"></translation> </message> <message> <source>Aborted! [SIGABRT]</source> <translation type="unfinished"></translation> </message> <message> <source>Signal Segmentation Violation [SIGSEGV]</source> <translation type="unfinished"></translation> </message> <message> <source>Interrupted! [SIGINT]</source> <translation type="unfinished"></translation> </message> <message> <source>We&apos;re sorry, but PGE Editor has crashed. Reason: %1 </source> <translation type="unfinished"></translation> </message> <message> <source>Cut top here</source> <translation type="unfinished"></translation> </message> <message> <source>Cut bottom here</source> <translation type="unfinished"></translation> </message> <message> <source>Cut left here</source> <translation type="unfinished"></translation> </message> <message> <source>Cut right here</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t snap to grid</source> <translation type="unfinished"></translation> </message> <message> <source>Disable minimal size limit</source> <translation type="unfinished"></translation> </message> <message> <source>Loading BGOs...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Backgrounds...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Blocks...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading NPCs...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Music...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Sound...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Level images...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Paths images...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Sceneries...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Tiles...</source> <translation type="unfinished"></translation> </message> <message> <source>Bad File</source> <translation type="unfinished"></translation> </message> <message> <source>Bad file format File: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Line Number: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Line Data: %1</source> <translation type="unfinished"></translation> </message> <message> <source>File open error</source> <translation type="unfinished"></translation> </message> <message> <source>Unknown values are presented</source> <translation type="unfinished"></translation> </message> <message> <source>Your file have an unknown values which will be removed when you will save file</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 section The maximum number of sections is %2. All boundaries and settings of more than 21 sections will be lost.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 blocks The maximum number of blocks is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Background Objects The maximum number of Background Objects is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 NPC&apos;s The maximum number of NPC&apos;s is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Warps The maximum number of Warps is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Water Boxes The maximum number of Water Boxes is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Layers The maximum number of Layers is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Events The maximum number of Events is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>A some issues are found on preparing to save SMBX64 Level file format: %1Please remove excess elements (or settings) from this level or save file into LVLX format.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Tiles The maximum number of Tiles is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Sceneries The maximum number of Sceneries is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Paths The maximum number of Paths is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Levels The maximum number of Levels is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX64 standard isn&apos;t allows to save %1 Music Boxes The maximum number of Music Boxes is %2.</source> <translation type="unfinished"></translation> </message> <message> <source>A some issues are found on preparing to save SMBX64 World map file format: %1Please remove excess elements (or settings) from this world map or save file into WLDX format.</source> <translation type="unfinished"></translation> </message> <message> <source>Loading rotation rules table...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Tilesets...</source> <translation type="unfinished"></translation> </message> <message> <source>Loading Tileset groups...</source> <translation type="unfinished"></translation> </message> <message> <source>Finishing loading...</source> <translation type="unfinished"></translation> </message> <message> <source>Disable logging</source> <translation type="unfinished"></translation> </message> <message> <source>System messages</source> <translation type="unfinished"></translation> </message> <message> <source>Fatal</source> <translation type="unfinished"></translation> </message> <message> <source>Critical</source> <translation type="unfinished"></translation> </message> <message> <source>Warning</source> <translation type="unfinished"></translation> </message> <message> <source>Debug</source> <translation type="unfinished"></translation> </message> <message> <source>Initializing tileset categories...</source> <translation type="unfinished"></translation> </message> <message> <source>LTR</source> <translation type="unfinished"></translation> </message> <message> <source>Block user data change</source> <translation type="unfinished"></translation> </message> <message> <source>BGO user data change</source> <translation type="unfinished"></translation> </message> <message> <source>NPC user data change</source> <translation type="unfinished"></translation> </message> <message> <source>Level Settings</source> <translation type="unfinished"></translation> </message> <message> <source>Section extra settings</source> <translation type="unfinished"></translation> </message> <message> <source>Default</source> <comment>Name of pallete</comment> <translation type="unfinished"></translation> </message> <message> <source>Dark blue</source> <comment>Name of pallete</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>SanBaEiRuntimeEngine</name> <message> <source>Test level</source> <comment>Run the testing of current file in SMBX-38A via interprocessing tunnel.</comment> <translation type="unfinished"></translation> </message> <message> <source>Test level in battle mode</source> <comment>Run a battle testing of current file in SMBX-38A via interprocessing tunnel.</comment> <translation type="unfinished"></translation> </message> <message> <source>Test saved level/world</source> <comment>Run the testing of current file in SMBX-38A from disk.</comment> <translation type="unfinished"></translation> </message> <message> <source>Reset checkpoints</source> <translation type="unfinished"></translation> </message> <message> <source>Reset all checkpoint states to initial state.</source> <translation type="unfinished"></translation> </message> <message> <source>Enable magic hand</source> <comment>Allow real-time picking-up of elements while playing a level test.</comment> <translation type="unfinished"></translation> </message> <message> <source>Allows real-time editing: picking-up elements from a level scene, placing new elements, selected at back in the editor, and erasing. Doesn&apos;t works when running a test of a saved file.</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t auto-suspend game</source> <comment>Don&apos;t pause game when it&apos;s window is unfocused</comment> <translation type="unfinished"></translation> </message> <message> <source>Game will always run and it will never suspend while window is unfocused.</source> <translation type="unfinished"></translation> </message> <message> <source>Change the path to SMBX-38A...</source> <comment>Select the path to SMBX-38A executable.</comment> <translation type="unfinished"></translation> </message> <message> <source>Select the path to SMBX-38A executable.</source> <translation type="unfinished"></translation> </message> <message> <source>Wine settings...</source> <comment>Open Wine settings to choose which Wine toolchain use</comment> <translation type="unfinished"></translation> </message> <message> <source>Select a Wine toolchain for use.</source> <translation type="unfinished"></translation> </message> <message> <source>Start Game</source> <comment>Launch SMBX-38A as a normal game</comment> <translation type="unfinished"></translation> </message> <message> <source>Checkpoints successfully reseted!</source> <translation type="unfinished"></translation> </message> <message> <source>Path to SMBX-38A</source> <comment>Title of dialog</comment> <translation type="unfinished"></translation> </message> <message> <source>Please select a path to SMBX-38A executable:</source> <translation type="unfinished"></translation> </message> <message> <source>Use default</source> <comment>Using default SMBX-38A path, specified by an applcation path of Editor</comment> <translation type="unfinished"></translation> </message> <message> <source>Custom</source> <comment>Using a user selected SMBX-38A path</comment> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Select a path to SMBX-38A executable</source> <comment>File dialog title</comment> <translation type="unfinished"></translation> </message> <message> <source>SMBX-38A is still active</source> <translation type="unfinished"></translation> </message> <message> <source>To change a setup of Wine, you will need to shut down a currently working SMBX-38A. Do you want to shut down the SMBX-38A now?</source> <translation type="unfinished"></translation> </message> <message> <source>Executable not found</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to prepare a temp file for a test run.</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to launch a level because of an invalid file.</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot launch the level because the level file is saved in an unsupported format. Please save the level in the SMBX-38A or the SMBX64-LVL format.</source> <translation type="unfinished"></translation> </message> <message> <source>Caution</source> <translation type="unfinished"></translation> </message> <message> <source>Your level is not in SMBX-38A format. That means, the game WILL automatically convert it into SMBX-38A format. Your level will become incompatible with a Classic SMBX. Do you want to continue on your own risk?</source> <translation type="unfinished"></translation> </message> <message> <source>Impossible to launch an episode because of an invalid file.</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot launch the episode because the world map file is saved in an unsupported format. Please save the level in the SMBX-38A or the SMBX64-WLD format.</source> <translation type="unfinished"></translation> </message> <message> <source>Your world map is not in SMBX-38A format. That means, the game will automatically convert it into SMBX-38A format. Your episode will become incompatible with a Classic SMBX. Do you want to continue on your own risk?</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start SMBX-38A game because &quot;%1&quot; is not found. That might happen because of incorrect path to SMBX-38A executable was specified, please check the SMBX-38A path setup.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SavingNotificationDialog</name> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Discard</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScriptEditor</name> <message> <source>Script editor</source> <translation type="unfinished"></translation> </message> <message> <source>Add script</source> <translation type="unfinished"></translation> </message> <message> <source>Remove script</source> <translation type="unfinished"></translation> </message> <message> <source>Script</source> <translation type="unfinished"></translation> </message> <message> <source>Export as...</source> <translation type="unfinished"></translation> </message> <message> <source>Import</source> <translation type="unfinished"></translation> </message> <message> <source>Import from file...</source> <translation type="unfinished"></translation> </message> <message> <source>Close script editor</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation type="unfinished"></translation> </message> <message> <source>Empty script has been added!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SmartImporter</name> <message> <source>File not saved</source> <translation type="unfinished"></translation> </message> <message> <source>You need to save the level, so you can import custom graphics!</source> <translation type="unfinished"></translation> </message> <message> <source>You need to save the world, so you can import custom graphics!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TestingSettings</name> <message> <source>2 Player settings</source> <translation type="unfinished"></translation> </message> <message> <source>PLSET_Character</source> <comment>Character</comment> <translation type="unfinished"></translation> </message> <message> <source>PLSET_State</source> <comment>Character</comment> <translation type="unfinished"></translation> </message> <message> <source>Extra settings</source> <translation type="unfinished"></translation> </message> <message> <source>Debug info</source> <comment>Enable printing of the debug information.</comment> <translation type="unfinished"></translation> </message> <message> <source>Allows you to destroy any objects with no exceptions.</source> <translation type="unfinished"></translation> </message> <message> <source>Allows you to walk everywhere on the world map without limiting by paths.</source> <translation type="unfinished"></translation> </message> <message> <source>World freedom</source> <translation type="unfinished"></translation> </message> <message> <source>Playable character will not take damage on dangerous contacts and will not burn in the lava.</source> <translation type="unfinished"></translation> </message> <message> <source>God mode</source> <translation type="unfinished"></translation> </message> <message> <source>Allows you to fly up to the space!</source> <translation type="unfinished"></translation> </message> <message> <source>Testing settings</source> <translation type="unfinished"></translation> </message> <message> <source>PLSET_VehicleID</source> <comment>translate as &quot;Vehicle&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>PLSET_VehicleType</source> <comment>translate as &quot;Vehicle type&quot;</comment> <translation type="unfinished"></translation> </message> <message> <source>Unlimited flying</source> <translation type="unfinished"></translation> </message> <message> <source>Physics debug</source> <comment>Enable debug drawing of physical objects (draw all hit boxes).</comment> <translation type="unfinished"></translation> </message> <message> <source>Show frame speed</source> <translation type="unfinished"></translation> </message> <message> <source>Number of players</source> <translation type="unfinished"></translation> </message> <message> <source>1 player</source> <translation type="unfinished"></translation> </message> <message> <source>2 player</source> <translation type="unfinished"></translation> </message> <message> <source>1 Player settings</source> <translation type="unfinished"></translation> </message> <message> <source>Bulldozer mode</source> <translation type="unfinished"></translation> </message> <message> <source>Cheats</source> <translation type="unfinished"></translation> </message> <message> <source>Initial state</source> <translation type="unfinished"></translation> </message> <message> <source>Start with stars:</source> <translation type="unfinished"></translation> </message> <message> <source>Debug</source> <translation type="unfinished"></translation> </message> <message> <source>Player settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TheXTechEngine</name> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Test level</source> <comment>Run the testing of current file in TheXTech via interprocessing tunnel.</comment> <translation type="unfinished"></translation> </message> <message> <source>Test saved level</source> <comment>Run the testing of current file in TheXTech from disk.</comment> <translation type="unfinished"></translation> </message> <message> <source>Start Game</source> <comment>Launch TheXTech as a normal game</comment> <translation type="unfinished"></translation> </message> <message> <source>Please select a path to TheXTech executable:</source> <translation type="unfinished"></translation> </message> <message> <source>Use default</source> <comment>Using default TheXTech path, specified by an applcation path of Editor</comment> <translation type="unfinished"></translation> </message> <message> <source>Custom</source> <comment>Using a user selected TheXTech path</comment> <translation type="unfinished"></translation> </message> <message> <source>Select a path to TheXTech executable</source> <comment>File dialog title</comment> <translation type="unfinished"></translation> </message> <message> <source>Test level in battle mode</source> <comment>Run a battle testing of current file in TheXTech via interprocessing tunnel.</comment> <translation type="unfinished"></translation> </message> <message> <source>Graphics type</source> <comment>Choose a rendering system: software or accelerated</comment> <translation type="unfinished"></translation> </message> <message> <source>Default</source> <comment>Automatically selected rendering engine</comment> <translation type="unfinished"></translation> </message> <message> <source>Software</source> <comment>Software rendering</comment> <translation type="unfinished"></translation> </message> <message> <source>Accelerated</source> <comment>Hardware accelerated rendering</comment> <translation type="unfinished"></translation> </message> <message> <source>Accelerated with V-Sync</source> <comment>Hardware accelerated rendering with vertical synchronization support</comment> <translation type="unfinished"></translation> </message> <message> <source>Enable magic hand</source> <comment>Allow real-time picking-up of elements while playing a level test.</comment> <translation type="unfinished"></translation> </message> <message> <source>Allows real-time editing: picking-up elements from a level scene, placing new elements, selected at back in the editor, and erasing. Doesn&apos;t works when running a test of a saved file.</source> <translation type="unfinished"></translation> </message> <message> <source>Enable max FPS</source> <comment>When running non-vsync, run game with a maximum possible frame-rate</comment> <translation type="unfinished"></translation> </message> <message> <source>When playing a game without V-Sync, run a game with a maximum possible frame-rate.</source> <translation type="unfinished"></translation> </message> <message> <source>Enable grab all</source> <comment>Allow player to grab absolutely any NPCs in a game.</comment> <translation type="unfinished"></translation> </message> <message> <source>Allow player to grab any NPCs in a game.</source> <translation type="unfinished"></translation> </message> <message> <source>Path to TheXTech</source> <comment>Title of dialog</comment> <translation type="unfinished"></translation> </message> <message> <source>Change the path to TheXTech...</source> <comment>Select the path to TheXTech executable.</comment> <translation type="unfinished"></translation> </message> <message> <source>Select the path to TheXTech executable.</source> <translation type="unfinished"></translation> </message> <message> <source>Executable not found</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start TheXTech game because &quot;%1&quot; is not found. That might happen because of incorrect path to TheXTech executable was specified, please check the TheXTech path setup.</source> <translation type="unfinished"></translation> </message> <message> <source>TheXtech start failed</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start TheXTech because of following reason: %3. Command: &quot;%1&quot; Arguments: %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TilesetEditor</name> <message> <source>Tileset Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Items</source> <translation type="unfinished"></translation> </message> <message> <source>Block</source> <translation type="unfinished"></translation> </message> <message> <source>BGO</source> <translation type="unfinished"></translation> </message> <message> <source>NPC</source> <translation type="unfinished"></translation> </message> <message> <source>Terrain tile</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Path</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <source>Clear</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset name:</source> <translation type="unfinished"></translation> </message> <message> <source>Open</source> <translation type="unfinished"></translation> </message> <message> <source>Height:</source> <translation type="unfinished"></translation> </message> <message> <source>Width:</source> <translation type="unfinished"></translation> </message> <message> <source>Show custom only</source> <translation type="unfinished"></translation> </message> <message> <source>Current Level/World specific</source> <translation type="unfinished"></translation> </message> <message> <source>Delete this tileset</source> <translation type="unfinished"></translation> </message> <message> <source>Show default only</source> <translation type="unfinished"></translation> </message> <message> <source>Search</source> <translation type="unfinished"></translation> </message> <message> <source>Search settings</source> <translation type="unfinished"></translation> </message> <message> <source>Search by Name</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Search by ID</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Search by ID (Contained)</source> <comment>Element search criteria</comment> <translation type="unfinished"></translation> </message> <message> <source>Sort by</source> <comment>Search settings pop-up menu, sort submenu</comment> <translation type="unfinished"></translation> </message> <message> <source>Name</source> <comment>Sort by name</comment> <translation type="unfinished"></translation> </message> <message> <source>ID</source> <comment>Sort by ID</comment> <translation type="unfinished"></translation> </message> <message> <source>Descending</source> <comment>Descending sorting order</comment> <translation type="unfinished"></translation> </message> <message> <source>Clean tileset editor</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to clean tileset editor to create a new tileset?</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a filename!</source> <translation type="unfinished"></translation> </message> <message> <source>Filename:</source> <translation type="unfinished"></translation> </message> <message> <source>Open Tileset</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset!</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset! Data may be corrupted!</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset box editor</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t show this message again.</source> <translation type="unfinished"></translation> </message> <message> <source>Welcome to tileset editor! This is an editor of global tilesets. All tilesets which made here will be saved in this folder: %1 I.e. there are will work globally for this configuration package and can be used in the gropus of tilesets. If you wish to create level/world specific tilesets with using of custom graphics, please open the Tileset Item Box and find the button &quot;New Tileset&quot; in the &quot;Custom&quot; tab.</source> <translation type="unfinished"></translation> </message> <message> <source>Remove tileset</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to remove this tileset?</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset removed</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset has been removed!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TilesetGroupEditor</name> <message> <source>Tileset Group editor</source> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <translation type="unfinished"></translation> </message> <message> <source>Order weight</source> <translation type="unfinished"></translation> </message> <message> <source>Tileset group name:</source> <translation type="unfinished"></translation> </message> <message> <source>Category:</source> <translation type="unfinished"></translation> </message> <message> <source>Defines the custom order priority. If weight values are equal between of different tileset group or equal to -1, tileset groups will be ordered alphabetically.</source> <translation type="unfinished"></translation> </message> <message> <source>Open</source> <translation type="unfinished"></translation> </message> <message> <source>Close</source> <translation type="unfinished"></translation> </message> <message> <source>Tilesets list:</source> <translation type="unfinished"></translation> </message> <message> <source>Preview</source> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <translation type="unfinished"></translation> </message> <message> <source>Remove tileset</source> <translation type="unfinished"></translation> </message> <message> <source>Add tileset</source> <translation type="unfinished"></translation> </message> <message> <source>Save</source> <translation type="unfinished"></translation> </message> <message> <source>Select Tileset</source> <translation type="unfinished"></translation> </message> <message> <source>There is already a file called &apos;%1&apos;! Import anyway and overwrite?</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset!</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset! Data may be corrupted!</source> <translation type="unfinished"></translation> </message> <message> <source>Select Tileset Group</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset group!</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to load tileset group! Data may be corrupted!</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a filename!</source> <translation type="unfinished"></translation> </message> <message> <source>Filename:</source> <translation type="unfinished"></translation> </message> <message> <source>Category order weight</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TilesetItemBox</name> <message> <source>Tileset Item Box</source> <translation type="unfinished"></translation> </message> <message> <source>Search: </source> <translation type="unfinished"></translation> </message> <message> <source>New tileset</source> <translation type="unfinished"></translation> </message> <message> <source>File not saved</source> <translation type="unfinished"></translation> </message> <message> <source>File doesn&apos;t saved on disk.</source> <translation type="unfinished"></translation> </message> <message> <source>Group:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TipOfDay</name> <message> <source>Tip of day</source> <translation type="unfinished"></translation> </message> <message> <source>Did you know?</source> <translation type="unfinished"></translation> </message> <message> <source>Show tip at startup</source> <translation type="unfinished"></translation> </message> <message> <source>Previouse tip</source> <translation type="unfinished"></translation> </message> <message> <source>Next tip</source> <translation type="unfinished"></translation> </message> <message> <source>Close</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ToNewLayerBox</name> <message> <source>Add to new layer</source> <translation type="unfinished"></translation> </message> <message> <source>New layer name</source> <translation type="unfinished"></translation> </message> <message> <source>Hidden</source> <translation type="unfinished"></translation> </message> <message> <source>Locked</source> <translation type="unfinished"></translation> </message> <message> <source>Layer exists</source> <translation type="unfinished"></translation> </message> <message> <source>Layer &quot;%1&quot; is exist, please, set other name.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UpdateChecker</name> <message> <source>Check for updates</source> <translation type="unfinished"></translation> </message> <message> <source>Stable builds</source> <translation type="unfinished"></translation> </message> <message> <source>Check for latest stable builds</source> <translation type="unfinished"></translation> </message> <message> <source>Check automatically every startup</source> <translation type="unfinished"></translation> </message> <message> <source>Close</source> <translation type="unfinished"></translation> </message> <message> <source>Click to check updates</source> <translation type="unfinished"></translation> </message> <message> <source>Check laboratory updates</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can get bug fixes and new features before new stable will be released</source> <translation type="unfinished"></translation> </message> <message> <source>Laboratory builds</source> <translation type="unfinished"></translation> </message> <message> <source>Check stable updates</source> <translation type="unfinished"></translation> </message> <message> <source>This is an update checker dialog. Here you can check available updates.</source> <translation type="unfinished"></translation> </message> <message> <source>Checking...</source> <translation type="unfinished"></translation> </message> <message> <source>HTTP</source> <translation type="unfinished"></translation> </message> <message> <source>Check failed: %1.</source> <translation type="unfinished"></translation> </message> <message> <source>Check failed!</source> <translation type="unfinished"></translation> </message> <message> <source>Redirect to %1 ?</source> <translation type="unfinished"></translation> </message> <message> <source>You have a latest version!</source> <translation type="unfinished"></translation> </message> <message> <source>Available new update!</source> <translation type="unfinished"></translation> </message> <message> <source>Latest update is</source> <translation type="unfinished"></translation> </message> <message> <source>One or more SSL errors has occurred: %1</source> <translation type="unfinished"></translation><|fim▁hole|><context> <name>UserDataEdit</name> <message> <source>User data editing</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VariablesBox</name> <message> <source>Variables [Under Construction]</source> <translation type="unfinished"></translation> </message> <message> <source>Show variables group</source> <translation type="unfinished"></translation> </message> <message> <source>Global</source> <translation type="unfinished"></translation> </message> <message> <source>Local</source> <translation type="unfinished"></translation> </message> <message> <source>All</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WLD_ItemProps</name> <message> <source>Item Properties</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Big path background</source> <translation type="unfinished"></translation> </message> <message> <source>Path background</source> <translation type="unfinished"></translation> </message> <message> <source>Game start point</source> <translation type="unfinished"></translation> </message> <message> <source>Always visible</source> <translation type="unfinished"></translation> </message> <message> <source>You can set a condition to open path in specified direction (controls at each side of those arrows), dependent on level exit code.</source> <translation type="unfinished"></translation> </message> <message> <source>Level file:</source> <translation type="unfinished"></translation> </message> <message> <source>Level title</source> <translation type="unfinished"></translation> </message> <message> <source>Enter to door ID:</source> <translation type="unfinished"></translation> </message> <message> <source>Browse</source> <translation type="unfinished"></translation> </message> <message> <source>Go to coordinates:</source> <translation type="unfinished"></translation> </message> <message> <source>Set</source> <translation type="unfinished"></translation> </message> <message> <source>Open path by exists:</source> <translation type="unfinished"></translation> </message> <message> <source>Open the Western (left) path by exit type</source> <comment>Condition to open path by direction (like on compass) when level is completed with different exit ways</comment> <translation type="unfinished"></translation> </message> <message> <source>Open the Eastern (right) path by exit type</source> <comment>Condition to open path by direction (like on compass) when level is completed with different exit ways</comment> <translation type="unfinished"></translation> </message> <message> <source>Open the Northern (upper) path by exit type</source> <comment>Condition to open path by direction (like on compass) when level is completed with different exit ways</comment> <translation type="unfinished"></translation> </message> <message> <source>Open the Southern (lower) path by exit type</source> <comment>Condition to open path by direction (like on compass) when level is completed with different exit ways</comment> <translation type="unfinished"></translation> </message> <message> <source>Level ID: %1, Array ID: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Position: [%1, %2]</source> <translation type="unfinished"></translation> </message> <message> <source>* - Any</source> <translation type="unfinished"></translation> </message> <message> <source>0 - None</source> <translation type="unfinished"></translation> </message> <message> <source>1 - Card Roulette Exit</source> <translation type="unfinished"></translation> </message> <message> <source>2 - SMB3 Boss Exit</source> <translation type="unfinished"></translation> </message> <message> <source>3 - Walked Offscreen</source> <translation type="unfinished"></translation> </message> <message> <source>4 - Secret Exit</source> <translation type="unfinished"></translation> </message> <message> <source>5 - Crystal Sphare Exit</source> <translation type="unfinished"></translation> </message> <message> <source>6 - Warp Exit</source> <translation type="unfinished"></translation> </message> <message> <source>7 - Star Exit</source> <translation type="unfinished"></translation> </message> <message> <source>8 - Tape Exit</source> <translation type="unfinished"></translation> </message> <message> <source>Placement mode</source> <translation type="unfinished"></translation> </message> <message> <source>Place item on the map first and call &apos;Properties&apos; context menu item.</source> <translation type="unfinished"></translation> </message> <message> <source>Please save the file</source> <translation type="unfinished"></translation> </message> <message> <source>Please save the file before selecting levels.</source> <translation type="unfinished"></translation> </message> <message> <source>9 - Hawk Mouth Exit</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WLD_SetPoint</name> <message> <source>Selecting point on the world map</source> <translation type="unfinished"></translation> </message> <message> <source>Note: Use the mousewheel to scroll on the map. You can scroll horizontally by holding down the CTRL key.</source> <translation type="unfinished"></translation> </message> <message> <source>Current Point:</source> <translation type="unfinished"></translation> </message> <message> <source>You will change current position to the last selected point. If point is not set, position will not be changed.</source> <translation type="unfinished"></translation> </message> <message> <source>Go to point</source> <translation type="unfinished"></translation> </message> <message> <source>Start and stop animation of placed on the map items.</source> <translation type="unfinished"></translation> </message> <message> <source>Animation</source> <translation type="unfinished"></translation> </message> <message> <source>You will return to the x0-y0 position of the map.</source> <translation type="unfinished"></translation> </message> <message> <source>Reset position</source> <translation type="unfinished"></translation> </message> <message> <source>Loading World map data</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>1/%1 Loading user data</source> <translation type="unfinished"></translation> </message> <message> <source>1/%1 Applying Tiles</source> <translation type="unfinished"></translation> </message> <message> <source>2/%1 Applying Sceneries...</source> <translation type="unfinished"></translation> </message> <message> <source>3/%1 Applying Paths...</source> <translation type="unfinished"></translation> </message> <message> <source>4/%1 Applying Levels...</source> <translation type="unfinished"></translation> </message> <message> <source>5/%1 Applying Musics...</source> <translation type="unfinished"></translation> </message> <message> <source>Point is not selected</source> <translation type="unfinished"></translation> </message> <message> <source>Select the point on the world map first.</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration package has errors</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot load the &quot;%1&quot; world map because of errors in a configuration package.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WineSetup</name> <message> <source>Wine configuration</source> <translation type="unfinished"></translation> </message> <message> <source>Test</source> <translation type="unfinished"></translation> </message> <message> <source>Wine config</source> <translation type="unfinished"></translation> </message> <message> <source>Version dialog</source> <translation type="unfinished"></translation> </message> <message> <source>Stop process</source> <translation type="unfinished"></translation> </message> <message> <source>Not running</source> <translation type="unfinished"></translation> </message> <message> <source>Import</source> <translation type="unfinished"></translation> </message> <message> <source>Specify a custom environment (PlayOnLinux/Mac)</source> <translation type="unfinished"></translation> </message> <message> <source>Wine home prefix</source> <translation type="unfinished"></translation> </message> <message> <source>Browse...</source> <translation type="unfinished"></translation> </message> <message> <source>Location of Wine</source> <translation type="unfinished"></translation> </message> <message> <source>System default</source> <translation type="unfinished"></translation> </message> <message> <source>Custom:</source> <translation type="unfinished"></translation> </message> <message> <source>Enable Wine debug printing into &quot;WineDebug&quot; console</source> <translation type="unfinished"></translation> </message> <message> <source>Import setup from PlayOnMac</source> <translation type="unfinished"></translation> </message> <message> <source>Import setup from PlayOnLinux</source> <translation type="unfinished"></translation> </message> <message> <source>Select a Wine install prefix path</source> <translation type="unfinished"></translation> </message> <message> <source>Select a Wine home prefix path</source> <translation type="unfinished"></translation> </message> <message> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start &quot;%1&quot; because of: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Not running</source> <comment>State of a test app</comment> <translation type="unfinished"></translation> </message> <message> <source>Starting...</source> <comment>State of a test app</comment> <translation type="unfinished"></translation> </message> <message> <source>Running...</source> <comment>State of a test app</comment> <translation type="unfinished"></translation> </message> <message> <source>A user-local Wine prefix which contains settings, C-Drive root directory, and some other things.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a system-wide installed Wine from a PATH environment.</source> <translation type="unfinished"></translation> </message> <message> <source>Specify a custom Wine install prefix (a directory which contains &quot;bin&quot;, &quot;lib&quot;, and &quot;share&quot; directories with a working Wine toolchain).</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WldHistoryManager</name> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Place</source> <translation type="unfinished"></translation> </message> <message> <source>Place &amp; Overwrite</source> <translation type="unfinished"></translation> </message> <message> <source>Move</source> <translation type="unfinished"></translation> </message> <message> <source>Rotate</source> <translation type="unfinished"></translation> </message> <message> <source>Flip</source> <translation type="unfinished"></translation> </message> <message> <source>Transform</source> <translation type="unfinished"></translation> </message> <message> <source>Undone: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Redone: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WldSaveImage</name> <message> <source>Export to image</source> <translation type="unfinished"></translation> </message> <message> <source>Hide grid (if it is shown)</source> <translation type="unfinished"></translation> </message> <message> <source>Please, select target image size:</source> <translation type="unfinished"></translation> </message> <message> <source>Height</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;With this option will be calculated opposite value for height or width for make target image with correct proportions.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Keep original aspect ratio</source> <translation type="unfinished"></translation> </message> <message> <source>Export selected rectangle to image</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a &lt;span style=&quot; font-weight:600;&quot;&gt;Width&lt;/span&gt; of target image. Target image will be scaled to this width.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source> px</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This is a &lt;span style=&quot; font-weight:600;&quot;&gt;Height&lt;/span&gt; of target image. Target image will be scaled to this height.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Width</source> <translation type="unfinished"></translation> </message> <message> <source>Hide all paths and levels like &quot;game already stated&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Hide music boxes</source> <translation type="unfinished"></translation> </message> <message> <source>Will be exported: Top: %1 Left: %2 Right: %3 Bottom: %4</source> <translation type="unfinished"></translation> </message> <message> <source>Hide meta-objects</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WldScene</name> <message> <source>Search User Tiles %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User Sceneries %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User Paths %1</source> <translation type="unfinished"></translation> </message> <message> <source>Search User Levels %1</source> <translation type="unfinished"></translation> </message> <message> <source>Wrong custom images</source> <translation type="unfinished"></translation> </message> <message> <source>This level have a wrong custom graphics files. You will see &apos;ghosties&apos; or other dummy images instead custom GFX of items, what used broken images. It occurred because, for example, the BMP format with GIF extension was used. Please, reconvert your images to valid format and try to reload this level.</source> <translation type="unfinished"></translation> </message> <message> <source>Tiles: %1 Sceneries: %2 Paths: %3 Levels: %4 Music boxes: %5 </source> <translation type="unfinished"></translation> </message> </context> <context> <name>WldSearchBox</name> <message> <source>Search of items on the World Map</source> <translation type="unfinished"></translation> </message> <message> <source>Search?</source> <translation type="unfinished"></translation> </message> <message> <source>Data</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <source>[empty]</source> <translation type="unfinished"></translation> </message> <message> <source>Reset Search Fields</source> <translation type="unfinished"></translation> </message> <message> <source>Search Tile</source> <translation type="unfinished"></translation> </message> <message> <source>Terrain tile</source> <translation type="unfinished"></translation> </message> <message> <source>Search Terrain Tile</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Search Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Path</source> <translation type="unfinished"></translation> </message> <message> <source>Search Path</source> <translation type="unfinished"></translation> </message> <message> <source>Level</source> <translation type="unfinished"></translation> </message> <message> <source>Level file</source> <translation type="unfinished"></translation> </message> <message> <source>Big Path Background</source> <translation type="unfinished"></translation> </message> <message> <source>Always Visible</source> <translation type="unfinished"></translation> </message> <message> <source>Game start point</source> <translation type="unfinished"></translation> </message> <message> <source>Contains Title</source> <translation type="unfinished"></translation> </message> <message> <source>Path background</source> <translation type="unfinished"></translation> </message> <message> <source>Search Level</source> <translation type="unfinished"></translation> </message> <message> <source>Music box</source> <translation type="unfinished"></translation> </message> <message> <source>Search Music</source> <translation type="unfinished"></translation> </message> <message> <source>Next Level</source> <translation type="unfinished"></translation> </message> <message> <source>Stop Search</source> <translation type="unfinished"></translation> </message> <message> <source>Search Complete</source> <translation type="unfinished"></translation> </message> <message> <source>Level search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next Tile</source> <translation type="unfinished"></translation> </message> <message> <source>Tile search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next Path</source> <translation type="unfinished"></translation> </message> <message> <source>Path search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Next Music</source> <translation type="unfinished"></translation> </message> <message> <source>Music search completed!</source> <translation type="unfinished"></translation> </message> <message> <source>Search in selection group</source> <translation type="unfinished"></translation> </message> <message> <source>Select all</source> <translation type="unfinished"></translation> </message> <message> <source>%1 found elements were selected.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WorldEdit</name> <message> <source>1/%1 Loading user data</source> <translation type="unfinished"></translation> </message> <message> <source>1/%1 Applying Tiles</source> <translation type="unfinished"></translation> </message> <message> <source>2/%1 Applying Sceneries...</source> <translation type="unfinished"></translation> </message> <message> <source>3/%1 Applying Paths...</source> <translation type="unfinished"></translation> </message> <message> <source>4/%1 Applying Levels...</source> <translation type="unfinished"></translation> </message> <message> <source>5/%1 Applying Musics...</source> <translation type="unfinished"></translation> </message> <message> <source>Untitled %1</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a episode title for &apos;%1&apos;!</source> <translation type="unfinished"></translation> </message> <message> <source>Saving</source> <translation type="unfinished"></translation> </message> <message> <source>Episode Title: </source> <translation type="unfinished"></translation> </message> <message> <source>Make custom folder</source> <translation type="unfinished"></translation> </message> <message> <source>Note: Custom folders are not supported for legacy SMBX Engine!</source> <translation type="unfinished"></translation> </message> <message> <source>Save As</source> <translation type="unfinished"></translation> </message> <message> <source>Extension is not set</source> <translation type="unfinished"></translation> </message> <message> <source>File Extension isn&apos;t defined, please enter file extension!</source> <translation type="unfinished"></translation> </message> <message> <source>SMBX file version</source> <translation type="unfinished"></translation> </message> <message> <source>Which version do you want to save as? (from 0 to 64)</source> <translation type="unfinished"></translation> </message> <message> <source>The SMBX64 limit has been exceeded</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to save file anyway? Exciting of SMBX64 limits may crash SMBX with &apos;overflow&apos; error. Installed LunaLUA partially extends than limits.</source> <translation type="unfinished"></translation> </message> <message> <source>File save error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot save file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source>File read error</source> <translation type="unfinished"></translation> </message> <message> <source>Cannot read file %1: %2.</source> <translation type="unfinished"></translation> </message> <message> <source>Loading World map data</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>Incorrect custom configs</source> <translation type="unfinished"></translation> </message> <message> <source>This world map has some incorrect config files which are can&apos;t be loaded. To avoid this message box in next time, please fix next errors in your config files in the current and in the custom folders: %1</source> <translation type="unfinished"></translation> </message> <message> <source>&apos;%1&apos; has been modified. Do you want to save your changes?</source> <translation type="unfinished"></translation> </message> <message> <source> not saved</source> <translation type="unfinished"></translation> </message> <message> <source>World title:</source> <translation type="unfinished"></translation> </message> <message> <source>Export selected area to image</source> <translation type="unfinished"></translation> </message> <message> <source>PNG Image (*.png)</source> <translation type="unfinished"></translation> </message> <message> <source>Saving section image...</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WorldItemBox</name> <message> <source>Terrain</source> <translation type="unfinished"></translation> </message> <message> <source>Scenery</source> <translation type="unfinished"></translation> </message> <message> <source>Paths</source> <translation type="unfinished"></translation> </message> <message> <source>Levels</source> <translation type="unfinished"></translation> </message> <message> <source>Music Box</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file first, if you want to select custom music file.</source> <translation type="unfinished"></translation> </message> <message> <source>World Map Items browser</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WorldMusicBoxItemBox</name> <message> <source>Music boxes</source> <translation type="unfinished"></translation> </message> <message> <source>Music Box</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file</source> <translation type="unfinished"></translation> </message> <message> <source>Please, save file first, if you want to select custom music file.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WorldSettingsBox</name> <message> <source>World Settings</source> <translation type="unfinished"></translation> </message> <message> <source>Count</source> <translation type="unfinished"></translation> </message> <message> <source>Intro level:</source> <translation type="unfinished"></translation> </message> <message> <source>Disable characters:</source> <translation type="unfinished"></translation> </message> <message> <source>Credits of this episode (SMBX allows only 5 lines):</source> <translation type="unfinished"></translation> </message> <message> <source>Episode title:</source> <translation type="unfinished"></translation> </message> <message> <source>Restart last level after fail</source> <translation type="unfinished"></translation> </message> <message> <source>Hub-styled world (without world map)</source> <translation type="unfinished"></translation> </message> <message> <source>Total stars:</source> <translation type="unfinished"></translation> </message> <message> <source>Browse</source> <translation type="unfinished"></translation> </message> <message> <source>Counting...</source> <translation type="unfinished"></translation> </message> <message> <source>Calculating total star count in accessible levels</source> <translation type="unfinished"></translation> </message> <message> <source>Abort</source> <translation type="unfinished"></translation> </message> <message> <source>Counting stars...</source> <translation type="unfinished"></translation> </message> <message> <source>The name of the level that will be loaded when the game first loads.</source> <translation type="unfinished"></translation> </message> <message> <source>Main hub level:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>aboutDialog</name> <message> <source>About</source> <translation type="unfinished"></translation> </message> <message> <source>Close</source> <translation type="unfinished"></translation> </message> <message> <source>By Wohlstand</source> <translation type="unfinished"></translation> </message> <message> <source>Editor, version %1</source> <translation type="unfinished"></translation> </message> <message> <source>Revision</source> <translation type="unfinished"></translation> </message> <message> <source>Build date</source> <translation type="unfinished"></translation> </message> <message> <source>Our project site</source> <translation type="unfinished"></translation> </message> <message> <source>This program is distributed under %1</source> <translation type="unfinished"></translation> </message> <message> <source>Architecture: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tileset</name> <message> <source>Drag &amp; Drop items into this box! Right-click to remove!</source> <translation type="unfinished"></translation> </message> </context> </TS><|fim▁end|>
</message> </context>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>mod rustzx; mod settings; mod sound; pub(crate) mod video; // main re-export pub use self::{rustzx::RustzxApp, settings::Settings};<|fim▁end|>
//! This module provides main application class. mod events;
<|file_name|>predictor.py<|end_file_name|><|fim▁begin|># Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import cv2 import torch from torchvision import transforms as T from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer from maskrcnn_benchmark.structures.image_list import to_image_list from maskrcnn_benchmark.modeling.roi_heads.mask_head.inference import Masker from maskrcnn_benchmark import layers as L from maskrcnn_benchmark.utils import cv2_util class COCODemo(object): # COCO categories for pretty print CATEGORIES = [ "__background", "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", ] def __init__( self, cfg, confidence_threshold=0.7, show_mask_heatmaps=False, masks_per_dim=2, min_image_size=224, ): self.cfg = cfg.clone() self.model = build_detection_model(cfg) self.model.eval() self.device = torch.device(cfg.MODEL.DEVICE) self.model.to(self.device) self.min_image_size = min_image_size save_dir = cfg.OUTPUT_DIR checkpointer = DetectronCheckpointer(cfg, self.model, save_dir=save_dir) _ = checkpointer.load(cfg.MODEL.WEIGHT) self.transforms = self.build_transform() mask_threshold = -1 if show_mask_heatmaps else 0.5 self.masker = Masker(threshold=mask_threshold, padding=1) # used to make colors for each class self.palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1]) self.cpu_device = torch.device("cpu") self.confidence_threshold = confidence_threshold self.show_mask_heatmaps = show_mask_heatmaps self.masks_per_dim = masks_per_dim def build_transform(self): """ Creates a basic transformation that was used to train the models """ cfg = self.cfg # we are loading images with OpenCV, so we don't need to convert them # to BGR, they are already! So all we need to do is to normalize # by 255 if we want to convert to BGR255 format, or flip the channels # if we want it to be in RGB in [0-1] range. if cfg.INPUT.TO_BGR255: to_bgr_transform = T.Lambda(lambda x: x * 255) else: to_bgr_transform = T.Lambda(lambda x: x[[2, 1, 0]]) normalize_transform = T.Normalize( mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD ) transform = T.Compose( [ T.ToPILImage(), T.Resize(self.min_image_size), T.ToTensor(), to_bgr_transform, normalize_transform, ] ) return transform def run_on_opencv_image(self, image): """ Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()` """ predictions = self.compute_prediction(image) top_predictions = self.select_top_predictions(predictions) result = image.copy() if self.show_mask_heatmaps: return self.create_mask_montage(result, top_predictions) result = self.overlay_boxes(result, top_predictions) if self.cfg.MODEL.MASK_ON: result = self.overlay_mask(result, top_predictions) if self.cfg.MODEL.KEYPOINT_ON: result = self.overlay_keypoints(result, top_predictions) result = self.overlay_class_names(result, top_predictions) return result def compute_prediction(self, original_image): """ Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()` """ # apply pre-processing to image image = self.transforms(original_image) # convert to an ImageList, padded so that it is divisible by # cfg.DATALOADER.SIZE_DIVISIBILITY image_list = to_image_list(image, self.cfg.DATALOADER.SIZE_DIVISIBILITY) image_list = image_list.to(self.device) # compute predictions with torch.no_grad(): predictions = self.model(image_list) predictions = [o.to(self.cpu_device) for o in predictions] # always single image is passed at a time prediction = predictions[0] # reshape prediction (a BoxList) into the original image size height, width = original_image.shape[:-1] prediction = prediction.resize((width, height)) if prediction.has_field("mask"): # if we have masks, paste the masks in the right position # in the image, as defined by the bounding boxes masks = prediction.get_field("mask") # always single image is passed at a time masks = self.masker([masks], [prediction])[0] prediction.add_field("mask", masks) return prediction def select_top_predictions(self, predictions): """ Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. It should contain the field `scores`. Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()` """ scores = predictions.get_field("scores") keep = torch.nonzero(scores > self.confidence_threshold).squeeze(1) predictions = predictions[keep] scores = predictions.get_field("scores") _, idx = scores.sort(0, descending=True) return predictions[idx] def compute_colors_for_labels(self, labels): """ Simple function that adds fixed colors depending on the class """ colors = labels[:, None] * self.palette colors = (colors % 255).numpy().astype("uint8") return colors def overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `labels`. """ labels = predictions.get_field("labels") boxes = predictions.bbox colors = self.compute_colors_for_labels(labels).tolist() for box, color in zip(boxes, colors): box = box.to(torch.int64) top_left, bottom_right = box[:2].tolist(), box[2:].tolist() image = cv2.rectangle( image, tuple(top_left), tuple(bottom_right), tuple(color), 1 ) return image def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite <|fim▁hole|> def overlay_keypoints(self, image, predictions): keypoints = predictions.get_field("keypoints") kps = keypoints.keypoints scores = keypoints.get_field("logits") kps = torch.cat((kps[:, :, 0:2], scores[:, :, None]), dim=2).numpy() for region in kps: image = vis_keypoints(image, region.transpose((1, 0))) return image def create_mask_montage(self, image, predictions): """ Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask`. """ masks = predictions.get_field("mask") masks_per_dim = self.masks_per_dim masks = L.interpolate( masks.float(), scale_factor=1 / masks_per_dim ).byte() height, width = masks.shape[-2:] max_masks = masks_per_dim ** 2 masks = masks[:max_masks] # handle case where we have less detections than max_masks if len(masks) < max_masks: masks_padded = torch.zeros(max_masks, 1, height, width, dtype=torch.uint8) masks_padded[: len(masks)] = masks masks = masks_padded masks = masks.reshape(masks_per_dim, masks_per_dim, height, width) result = torch.zeros( (masks_per_dim * height, masks_per_dim * width), dtype=torch.uint8 ) for y in range(masks_per_dim): start_y = y * height end_y = (y + 1) * height for x in range(masks_per_dim): start_x = x * width end_x = (x + 1) * width result[start_y:end_y, start_x:end_x] = masks[y, x] return cv2.applyColorMap(result.numpy(), cv2.COLORMAP_JET) def overlay_class_names(self, image, predictions): """ Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `scores` and `labels`. """ scores = predictions.get_field("scores").tolist() labels = predictions.get_field("labels").tolist() labels = [self.CATEGORIES[i] for i in labels] boxes = predictions.bbox template = "{}: {:.2f}" for box, score, label in zip(boxes, scores, labels): x, y = box[:2] s = template.format(label, score) cv2.putText( image, s, (x, y), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1 ) return image import numpy as np import matplotlib.pyplot as plt from maskrcnn_benchmark.structures.keypoint import PersonKeypoints def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7): """Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). """ dataset_keypoints = PersonKeypoints.NAMES kp_lines = PersonKeypoints.CONNECTIONS # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv. cmap = plt.get_cmap('rainbow') colors = [cmap(i) for i in np.linspace(0, 1, len(kp_lines) + 2)] colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors] # Perform the drawing on a copy of the image, to allow for blending. kp_mask = np.copy(img) # Draw mid shoulder / mid hip first for better visualization. mid_shoulder = ( kps[:2, dataset_keypoints.index('right_shoulder')] + kps[:2, dataset_keypoints.index('left_shoulder')]) / 2.0 sc_mid_shoulder = np.minimum( kps[2, dataset_keypoints.index('right_shoulder')], kps[2, dataset_keypoints.index('left_shoulder')]) mid_hip = ( kps[:2, dataset_keypoints.index('right_hip')] + kps[:2, dataset_keypoints.index('left_hip')]) / 2.0 sc_mid_hip = np.minimum( kps[2, dataset_keypoints.index('right_hip')], kps[2, dataset_keypoints.index('left_hip')]) nose_idx = dataset_keypoints.index('nose') if sc_mid_shoulder > kp_thresh and kps[2, nose_idx] > kp_thresh: cv2.line( kp_mask, tuple(mid_shoulder), tuple(kps[:2, nose_idx]), color=colors[len(kp_lines)], thickness=2, lineType=cv2.LINE_AA) if sc_mid_shoulder > kp_thresh and sc_mid_hip > kp_thresh: cv2.line( kp_mask, tuple(mid_shoulder), tuple(mid_hip), color=colors[len(kp_lines) + 1], thickness=2, lineType=cv2.LINE_AA) # Draw the keypoints. for l in range(len(kp_lines)): i1 = kp_lines[l][0] i2 = kp_lines[l][1] p1 = kps[0, i1], kps[1, i1] p2 = kps[0, i2], kps[1, i2] if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh: cv2.line( kp_mask, p1, p2, color=colors[l], thickness=2, lineType=cv2.LINE_AA) if kps[2, i1] > kp_thresh: cv2.circle( kp_mask, p1, radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA) if kps[2, i2] > kp_thresh: cv2.circle( kp_mask, p2, radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA) # Blend the keypoints. return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)<|fim▁end|>
<|file_name|>transpiler.js<|end_file_name|><|fim▁begin|>/* globals describe, it */ import Compiler from '../src/transpiler/compiler'; import assert from 'assert'; import fs from 'fs'; function compare(source, target) { const compiler = new Compiler(source); assert.equal(target, compiler.compiled); } describe('Transpiler', function() { it('should transpile a empty program', function() { compare('', ''); }); it('should transpile a declaration with no value', function() { compare('politico salario.,', 'var salario;'); }); it('should transpile a declaration with int value', function() { compare('politico salario = 100000.,', 'var salario = 100000;'); }); it('should transpile a declaration with string value', function() { compare('politico salario = \'salario\'.,', 'var salario = \'salario\';'); }); it('should transpile a declaration with boolean value', function() { compare('politico salario = true.,', 'var salario = true;'); compare('politico salario = false.,', 'var salario = false;'); }); it('should transpile a attribution of an expression', function() { compare('salario = salario + i.,', 'salario = salario + i;'); }); it('should transpile a print with no value', function() { compare('midiaGolpista().,', 'console.log();'); }); <|fim▁hole|> }); it('should transpile a print with expression', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \' + 1000).,', 'console.log(\'Número abaixo de 100.000: \' + 1000);'); }); it('should transpile a print with multiple values', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \', 1000).,', 'console.log(\'Número abaixo de 100.000: \', 1000);'); }); it('should transpile a empty loop', function() { compare('euViVoceVeja (i = 0., i < 10000., i++) {}', 'for (i = 0; i < 10000; i++) {\n}'); }); it('should transpile a empty if', function() { compare('porque (salario < 100000) {}', 'if (salario < 100000) {\n}'); }); it('should transpile a empty if with empty else', function() { compare('porque (salario < 100000) {} casoContrario {}', 'if (salario < 100000) {\n}'); }); it('should transpile expression `1 + 1`', function() { compare('1 + 1', '1 + 1;'); }); it('should transpile expression `1 + 4 / 2`', function() { compare('1 + 4 / 2', '1 + 4 / 2;'); }); it('should transpile expression `4 / 2 + 1`', function() { compare('4 / 2 + 1', '4 / 2 + 1;'); }); it('should transpile expression `4 / 2 + 1 * 3 - 2`', function() { compare('4 / 2 + 1 * 3 - 2', '4 / 2 + 1 * 3 - 2;'); }); it('should transpile example 1', function() { const source = fs.readFileSync('Example - Loop.dilmalang').toString(); const target = fs.readFileSync('Example - Loop.js').toString().replace(/\n$/, ''); compare(source, target); }); });<|fim▁end|>
it('should transpile a print with string', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \').,', 'console.log(\'Número abaixo de 100.000: \');');
<|file_name|>FairHeader_Test_Query.graphql.ts<|end_file_name|><|fim▁begin|>/* tslint:disable */ /* eslint-disable */ import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type FairHeader_Test_QueryVariables = {}; export type FairHeader_Test_QueryResponse = { readonly fair: { readonly " $fragmentRefs": FragmentRefs<"FairHeader_fair">; } | null; }; export type FairHeader_Test_Query = { readonly response: FairHeader_Test_QueryResponse; readonly variables: FairHeader_Test_QueryVariables; }; /* query FairHeader_Test_Query { fair(id: "example") { ...FairHeader_fair id } } fragment FairHeaderIcon_fair on Fair { name profile {<|fim▁hole|> icon { desktop: cropped(width: 100, height: 100, version: "square140") { src srcSet } mobile: cropped(width: 60, height: 60, version: "square140") { src srcSet } } id } } fragment FairHeader_fair on Fair { ...FairHeaderIcon_fair name exhibitionPeriod } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "example" } ], v1 = { "kind": "Literal", "name": "version", "value": "square140" }, v2 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "src", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "srcSet", "storageKey": null } ], v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "FairHeader_Test_Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Fair", "kind": "LinkedField", "name": "fair", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "FairHeader_fair" } ], "storageKey": "fair(id:\"example\")" } ], "type": "Query" }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "FairHeader_Test_Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Fair", "kind": "LinkedField", "name": "fair", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Profile", "kind": "LinkedField", "name": "profile", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "icon", "plural": false, "selections": [ { "alias": "desktop", "args": [ { "kind": "Literal", "name": "height", "value": 100 }, (v1/*: any*/), { "kind": "Literal", "name": "width", "value": 100 } ], "concreteType": "CroppedImageUrl", "kind": "LinkedField", "name": "cropped", "plural": false, "selections": (v2/*: any*/), "storageKey": "cropped(height:100,version:\"square140\",width:100)" }, { "alias": "mobile", "args": [ { "kind": "Literal", "name": "height", "value": 60 }, (v1/*: any*/), { "kind": "Literal", "name": "width", "value": 60 } ], "concreteType": "CroppedImageUrl", "kind": "LinkedField", "name": "cropped", "plural": false, "selections": (v2/*: any*/), "storageKey": "cropped(height:60,version:\"square140\",width:60)" } ], "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "exhibitionPeriod", "storageKey": null }, (v3/*: any*/) ], "storageKey": "fair(id:\"example\")" } ] }, "params": { "id": null, "metadata": {}, "name": "FairHeader_Test_Query", "operationKind": "query", "text": "query FairHeader_Test_Query {\n fair(id: \"example\") {\n ...FairHeader_fair\n id\n }\n}\n\nfragment FairHeaderIcon_fair on Fair {\n name\n profile {\n icon {\n desktop: cropped(width: 100, height: 100, version: \"square140\") {\n src\n srcSet\n }\n mobile: cropped(width: 60, height: 60, version: \"square140\") {\n src\n srcSet\n }\n }\n id\n }\n}\n\nfragment FairHeader_fair on Fair {\n ...FairHeaderIcon_fair\n name\n exhibitionPeriod\n}\n" } }; })(); (node as any).hash = 'd21850d49af37a798ce9cacad82ca4a2'; export default node;<|fim▁end|>
<|file_name|>DmnParse.java<|end_file_name|><|fim▁begin|>/* 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. */ package org.activiti.dmn.engine.impl.parser; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.activiti.dmn.engine.ActivitiDmnException; import org.activiti.dmn.engine.DmnEngineConfiguration; import org.activiti.dmn.engine.impl.context.Context; import org.activiti.dmn.engine.impl.io.InputStreamSource; import org.activiti.dmn.engine.impl.io.ResourceStreamSource; import org.activiti.dmn.engine.impl.io.StreamSource; import org.activiti.dmn.engine.impl.io.StringStreamSource; import org.activiti.dmn.engine.impl.io.UrlStreamSource; import org.activiti.dmn.engine.impl.persistence.entity.DecisionTableEntity; import org.activiti.dmn.engine.impl.persistence.entity.DmnDeploymentEntity; import org.activiti.dmn.model.Decision; import org.activiti.dmn.model.DmnDefinition; import org.activiti.dmn.xml.constants.DmnXMLConstants; import org.activiti.dmn.xml.converter.DmnXMLConverter; import org.activiti.dmn.xml.exception.DmnXMLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Specific parsing of one BPMN 2.0 XML file, created by the {@link DmnParse}. * * @author Tijs Rademakers * @author Joram Barrez */ public class DmnParse implements DmnXMLConstants { protected static final Logger LOGGER = LoggerFactory.getLogger(DmnParse.class); protected String name; protected boolean validateSchema = true; protected StreamSource streamSource; protected String sourceSystemId; protected DmnDefinition dmnDefinition; protected String targetNamespace; /** The deployment to which the parsed decision tables will be added. */ protected DmnDeploymentEntity deployment; /** The end result of the parsing: a list of decision tables. */ protected List<DecisionTableEntity> decisionTables = new ArrayList<DecisionTableEntity>(); public DmnParse deployment(DmnDeploymentEntity deployment) { this.deployment = deployment; return this; } public DmnParse execute(DmnEngineConfiguration dmnEngineConfig) { try { DmnXMLConverter converter = new DmnXMLConverter(); boolean enableSafeDmnXml = dmnEngineConfig.isEnableSafeDmnXml(); String encoding = dmnEngineConfig.getXmlEncoding(); if (encoding != null) { dmnDefinition = converter.convertToDmnModel(streamSource, validateSchema, enableSafeDmnXml, encoding); } else { dmnDefinition = converter.convertToDmnModel(streamSource, validateSchema, enableSafeDmnXml); } if (dmnDefinition != null && dmnDefinition.getDecisions() != null) { for (Decision decision : dmnDefinition.getDecisions()) { DecisionTableEntity decisionTableEntity = Context.getDmnEngineConfiguration().getDecisionTableEntityManager().create(); decisionTableEntity.setKey(decision.getId()); decisionTableEntity.setName(decision.getName()); decisionTableEntity.setResourceName(name); decisionTableEntity.setDeploymentId(deployment.getId()); decisionTableEntity.setParentDeploymentId(deployment.getParentDeploymentId()); decisionTableEntity.setDescription(decision.getDescription()); decisionTables.add(decisionTableEntity); } } } catch (Exception e) { if (e instanceof ActivitiDmnException) { throw (ActivitiDmnException) e; } else if (e instanceof DmnXMLException) { throw (DmnXMLException) e; } else { throw new ActivitiDmnException("Error parsing XML", e); } } return this; } public DmnParse name(String name) { this.name = name; return this; } public DmnParse sourceInputStream(InputStream inputStream) { if (name == null) { name("inputStream"); } setStreamSource(new InputStreamSource(inputStream)); return this; } public DmnParse sourceUrl(URL url) { if (name == null) { name(url.toString()); } setStreamSource(new UrlStreamSource(url)); return this; } public DmnParse sourceUrl(String url) { try { return sourceUrl(new URL(url)); } catch (MalformedURLException e) { throw new ActivitiDmnException("malformed url: " + url, e); } } public DmnParse sourceResource(String resource) { if (name == null) { name(resource); } setStreamSource(new ResourceStreamSource(resource)); return this; } public DmnParse sourceString(String string) { if (name == null) { name("string"); } setStreamSource(new StringStreamSource(string)); return this; } protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new ActivitiDmnException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } public String getSourceSystemId() { return sourceSystemId; } public DmnParse setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; return this; } /*<|fim▁hole|> public boolean isValidateSchema() { return validateSchema; } public void setValidateSchema(boolean validateSchema) { this.validateSchema = validateSchema; } public List<DecisionTableEntity> getDecisionTables() { return decisionTables; } public String getTargetNamespace() { return targetNamespace; } public DmnDeploymentEntity getDeployment() { return deployment; } public void setDeployment(DmnDeploymentEntity deployment) { this.deployment = deployment; } public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }<|fim▁end|>
* ------------------- GETTERS AND SETTERS ------------------- */
<|file_name|>app.spec.ts<|end_file_name|><|fim▁begin|>import { it, inject, injectAsync, beforeEachProviders } from '@angular/core/testing'; // to use Translate Service, we need Http, and to test Http we need to mock the backend import { BaseRequestOptions, Http, Response, ResponseOptions } from '@angular/http'; import {MockBackend} from '@angular/http/testing'; import {provide} from "@angular/core"; // Load the implementations that should be tested // import {Api} from './services/api/api'; import { AppComponent } from './app'; describe('AppComponent', () => { // provide our implementations or mocks to the dependency injector beforeEachProviders(() => [ // App, // Api, BaseRequestOptions, MockBackend, // Provide a mocked (fake) backend for Http provide(Http, { useFactory: function useFactory(backend, defaultOptions) { return new Http(backend, defaultOptions); }, deps: [MockBackend, BaseRequestOptions] }) ]); it('should have a non-empty appHeaderMenuModel', inject([AppComponent], (app: AppComponent) => {<|fim▁hole|><|fim▁end|>
expect(app.appHeaderMenuModel.length).toBeGreaterThan(0); })); });
<|file_name|>issue-74954.rs<|end_file_name|><|fim▁begin|>// check-pass fn main() { if let Some([b'@', filename @ ..]) = Some(b"@abc123") { println!("filename {:?}", filename); }<|fim▁hole|><|fim▁end|>
}
<|file_name|>test_artificial_1024_Fisher_MovingMedian_0__100.py<|end_file_name|><|fim▁begin|>import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art <|fim▁hole|> art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "Fisher", sigma = 0.0, exog_count = 100, ar_order = 0);<|fim▁end|>
<|file_name|>no_0343_integer_break.rs<|end_file_name|><|fim▁begin|>struct Solution; impl Solution { pub fn integer_break(n: i32) -> i32 { let mut dp = vec![0; n as usize + 1]; for i in 2..=n { let mut cur_max = 0; for j in 1..i { cur_max = cur_max.max((j * (i - j)).max(j * dp[(i - j) as usize])); } dp[i as usize] = cur_max; } dp[n as usize] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_integer_break1() { assert_eq!(Solution::integer_break(2), 1); } #[test] fn test_integer_break2() { assert_eq!(Solution::integer_break(10), 36); }<|fim▁hole|><|fim▁end|>
}
<|file_name|>index.js<|end_file_name|><|fim▁begin|>export * from './achievement'; export * from './auth'; export * from './chatlinks';<|fim▁hole|>export * from './test';<|fim▁end|>
export * from './forum'; export * from './help'; export * from './emotes'; export * from './rank';
<|file_name|>MidiHashUtil.java<|end_file_name|><|fim▁begin|>/* * Created on 5 Sep 2007 * * Copyright (c) 2004-2007 Paul John Leonard * * http://www.frinika.com * * This file is part of Frinika. * * Frinika 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 2 of the License, or * (at your option) any later version. * Frinika 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 Frinika; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.frinika.tootX.midi; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.ShortMessage; public class MidiHashUtil { static public long hashValue(ShortMessage mess) { byte data[] = mess.getMessage(); long cmd = mess.getCommand(); if (cmd == ShortMessage.PITCH_BEND) { return ((long) data[0] << 8); } else { return (((long) data[0] << 8) + data[1]); } } <|fim▁hole|> long cntrl = hash & 0xFF; long cmd = (hash >> 8) & 0xFF; long chn = (hash >> 16) & 0xFF; System.out.println(chn + " " + cmd + " " + cntrl); } static ShortMessage reconstructShortMessage(long hash, ShortMessage mess) { if (mess == null) mess=new ShortMessage(); int status = (int) ((hash >> 8) & 0xFF); int data1 = (int) (hash & 0xFF); try { mess.setMessage(status, data1, 0); } catch (InvalidMidiDataException ex) { Logger.getLogger(MidiHashUtil.class.getName()).log(Level.SEVERE, null, ex); } return mess; } }<|fim▁end|>
static public void hashDisp(long hash) {
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate osmpbfreader; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use(bson, doc)] extern crate bson; extern crate mongodb; use std::collections::HashMap; use std::env::args; use mongodb::coll::options::WriteModel; use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; use std::mem; // Structure holding a river, used for bson serialization #[derive(Serialize, Deserialize, Debug)] pub struct River { pub paths: Vec<(f64,f64)> } fn process_file(filename : &String, rivers_coll : &mongodb::coll::Collection) { let r = std::fs::File::open(&std::path::Path::new(filename)).unwrap(); println!("Parsing {:?}...",filename); let mut pbf = osmpbfreader::OsmPbfReader::new(r); let objs = pbf.get_objs_and_deps(|obj| { obj.is_way() && obj.tags().contains_key("waterway") && ( obj.tags().get("waterway").unwrap()=="river" || obj.tags().get("waterway").unwrap()=="stream" || obj.tags().get("waterway").unwrap()=="canal" ) && obj.tags().contains_key("name") && obj.tags().get("name").unwrap().len()>0 }).unwrap();<|fim▁hole|> for (_id, obj) in &objs { match obj { osmpbfreader::OsmObj::Node(n) => { nodes.insert( n.id, (n.lat(),n.lon()) ); } osmpbfreader::OsmObj::Way(w) => { let mut path = Vec::new(); for node_id in &w.nodes { match nodes.get(&node_id) { Some(node) => path.push((node.0,node.1)), None => { panic!(); } } } // Insert into MongoDB let river = River { paths: path }; let names : Vec<String> = obj.tags().iter().filter(|tag| tag.0.starts_with("name:")).map(|tag| tag.1.clone()).collect(); let serialized_river = bson::to_bson(&river); // Serialize match serialized_river { Ok(sr) => { if let bson::Bson::Document(docu) = sr { // Documentize bulk.push(WriteModel::UpdateOne { filter: doc!{"_id": obj.tags().get("name").unwrap().to_string()}, update: doc!{"$push": docu, "$addToSet": {"names": {"$each": bson::to_bson(&names).unwrap()}}}, upsert: Some(true) }); if bulk.len()>100 { println!("Insert into db... {}",bulk.len()); let mut bulk2 = Vec::new(); // create new empty bulk mem::swap(&mut bulk, &mut bulk2); // bulk <-> bulk2 let result = rivers_coll.bulk_write(bulk2, true); // send full bulk println!("Number of rivers inserted: ins:{} match:{} modif:{} del:{} upset:{}",result.inserted_count,result.matched_count,result.modified_count,result.deleted_count,result.upserted_count); match result.bulk_write_exception { Some(exception) => { if exception.message.len()>0 { println!("ERROR: {}",exception.message); } } None => () } //bulk.clear(); // bulk is now a new empty bulk thanks to swaping, clear is unecessary } // Compiler will drop bulk2 (the full bulk) at this point } else { println!("Error converting the BSON object into a MongoDB document"); } }, Err(_) => println!("Error serializing the River as a BSON object") } }, osmpbfreader::OsmObj::Relation(_) => () } } if bulk.len()>0 { println!("Insert into db... {} river(s)",bulk.len()); let result = rivers_coll.bulk_write(bulk, true); // send remaining bulk println!("Number of rivers inserted: match:{} ins:{} modif:{} del:{} upsert:{}",result.matched_count,result.inserted_count,result.modified_count,result.deleted_count,result.upserted_count); match result.bulk_write_exception { Some(exception) => { if exception.message.len()>0 { println!("ERROR(s): {}",exception.message); } } None => () } } } fn main() { // Connect to MongoDB client and select collection let client = Client::connect("localhost", 27017).ok().expect("Failed to initialize client."); let rivers_coll = client.db("wwsupdb").collection("osm"); match rivers_coll.drop() { Ok(_) => println!("Collection droped"), Err(_) => panic!() } for arg in args().skip(1) { process_file(&arg, &rivers_coll); } }<|fim▁end|>
println!("Objs got"); let mut nodes = HashMap::new(); let mut bulk = Vec::new();
<|file_name|>pagervisor.go<|end_file_name|><|fim▁begin|>package main import ( "fmt" "os" "os/signal" "syscall" ) <|fim▁hole|> func Info(format string, params ...interface{}) { Print("Info: " + format, params...) } func Error(err error) { Print("Error: %s", err) } func Fatal(err error) { Print("Fatal: %s", err) os.Exit(1) } func main() { var config Config var err error if config, err = LoadConfig(); err != nil { Fatal(err) } if err = config.Verify(); err != nil { Fatal(err) } var svcmon ServiceMonitor if svcmon, err = NewServiceMonitor(&config); err != nil { Fatal(err) } cleanup := func() { svcmon.Close() } defer cleanup() sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, syscall.SIGINT) signal.Notify(sigchan, syscall.SIGTERM) quit := make(chan bool) go func() { <-sigchan cleanup() quit <- true }() go func() { if err = svcmon.Run(); err != nil { Fatal(err) } quit <- true }() <-quit }<|fim▁end|>
func Print(format string, params ...interface{}) { fmt.Fprintf(os.Stderr, format+"\n", params...) }
<|file_name|>04.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # This example illustrates how to use non-homogeneous(nonzero) # Dirichlet boundary conditions. # # PDE: Poisson equation -Laplace u = CONST_F, where CONST_F is # a constant right-hand side. It is not difficult to see that # the function u(x,y) = (-CONST_F/4)*(x^2 + y^2) satisfies the # above PDE. Since also the Dirichlet boundary conditions # are chosen to match u(x,y), this function is the exact # solution. # # Note that since the exact solution is a quadratic polynomial, # Hermes will compute it exactly if all mesh elements are quadratic # or higher (then the exact solution lies in the finite element space). # If some elements in the mesh are linear, Hermes will only find # an approximation. # Import modules from hermes2d import (Mesh, MeshView, H1Shapeset, PrecalcShapeset, H1Space, LinSystem, Solution, ScalarView, WeakForm, DummySolver) from hermes2d.examples.c04 import set_bc from hermes2d.examples import get_example_mesh from hermes2d.forms import set_forms # Below you can play with the parameters CONST_F, P_INIT, and UNIFORM_REF_LEVEL. INIT_REF_NUM = 2 # number of initial uniform mesh refinements P_INIT = 2 # initial polynomial degree in all elements # Load the mesh file mesh = Mesh() mesh.load(get_example_mesh()) # Perform initial mesh refinements<|fim▁hole|># Create an H1 space with default shapeset space = H1Space(mesh, P_INIT) set_bc(space) # Initialize the weak formulation wf = WeakForm() set_forms(wf) # Initialize the linear system ls = LinSystem(wf) ls.set_spaces(space) # Assemble and solve the matrix problem sln = Solution() ls.assemble() ls.solve_system(sln) # Visualize the solution sln.plot() # Visualize the mesh mesh.plot(space=space)<|fim▁end|>
for i in range(INIT_REF_NUM): mesh.refine_all_elements()
<|file_name|>RateLimiterTest.java<|end_file_name|><|fim▁begin|>package org.asteriskjava.pbx.agi; import static org.junit.Assert.assertTrue; import org.asteriskjava.pbx.agi.RateLimiter; import org.junit.Test;<|fim▁hole|> @Test public void test() throws InterruptedException { long now = System.currentTimeMillis(); RateLimiter limiter = new RateLimiter(3); for (int i = 0; i < 15; i++) { limiter.acquire(); System.out.println(System.currentTimeMillis()); Thread.sleep(100); } // this should have taken around 5 seconds assertTrue(System.currentTimeMillis() - now > 4000L); } }<|fim▁end|>
public class RateLimiterTest {
<|file_name|>gensim_test.py<|end_file_name|><|fim▁begin|>import gensim import numpy as np from gensim.models import word2vec import jieba from TextSta_v2 import TextSta from gensim.corpora.dictionary import Dictionary <|fim▁hole|>word_list = jieba.lcut(sentense_file) tmp_dic = Dictionary() tmp_dic(word_list) # sentences = word2vec.Text8Corpus() # 加载语料 # model = word2vec.Word2Vec(sentences, size=10) # 默认window=5<|fim▁end|>
path = u"C:\\Users\\xiangrufan\\Desktop\\NLP\\Astro_NLP\\resource\\复旦分类语料\\answer\\C3-Art\\C3-Art0002.txt" text = TextSta(path,encoding="GBK") sentense_file = text.sen(all_return=True)
<|file_name|>it2me_helpee_channel.js<|end_file_name|><|fim▁begin|>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * * It2MeHelpeeChannel relays messages between the Hangouts web page (Hangouts) * and the It2Me Native Messaging Host (It2MeHost) for the helpee (the Hangouts * participant who is receiving remoting assistance). * * It runs in the background page. It contains a chrome.runtime.Port object, * representing a connection to Hangouts, and a remoting.It2MeHostFacade object, * representing a connection to the IT2Me Native Messaging Host. * * Hangouts It2MeHelpeeChannel It2MeHost * |---------runtime.connect()-------->| | * |-----------hello message---------->| | * |<-----helloResponse message------->| | * |----------connect message--------->| | * | |-----showConfirmDialog()----->| * | |----------connect()---------->| * | |<-------hostStateChanged------| * | | (RECEIVED_ACCESS_CODE) | * |<---connect response (access code)-| | * | | | * * Hangouts will send the access code to the web app on the helper side. * The helper will then connect to the It2MeHost using the access code. * * Hangouts It2MeHelpeeChannel It2MeHost * | |<-------hostStateChanged------| * | | (CONNECTED) | * |<-- hostStateChanged(CONNECTED)----| | * |-------disconnect message--------->| | * |<--hostStateChanged(DISCONNECTED)--| | * * * It also handles host downloads and install status queries: * * Hangouts It2MeHelpeeChannel * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |--------downloadHost message------>| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(true)---| */ 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * @param {chrome.runtime.Port} hangoutPort * @param {remoting.It2MeHostFacade} host * @param {remoting.HostInstaller} hostInstaller * @param {function()} onDisposedCallback Callback to notify the client when * the connection is torn down. * * @constructor * @implements {base.Disposable} */ remoting.It2MeHelpeeChannel = function(hangoutPort, host, hostInstaller, onDisposedCallback) { /** * @type {chrome.runtime.Port} * @private */ this.hangoutPort_ = hangoutPort; /** * @type {remoting.It2MeHostFacade} * @private */ this.host_ = host; /** * @type {?remoting.HostInstaller} * @private */ this.hostInstaller_ = hostInstaller; /** * @type {remoting.HostSession.State} * @private */ this.hostState_ = remoting.HostSession.State.UNKNOWN; /** * @type {?function()} * @private */ this.onDisposedCallback_ = onDisposedCallback; this.onHangoutMessageRef_ = this.onHangoutMessage_.bind(this); this.onHangoutDisconnectRef_ = this.onHangoutDisconnect_.bind(this); }; /** @enum {string} */ remoting.It2MeHelpeeChannel.HangoutMessageTypes = { CONNECT: 'connect', CONNECT_RESPONSE: 'connectResponse', DISCONNECT: 'disconnect', DOWNLOAD_HOST: 'downloadHost', ERROR: 'error', HELLO: 'hello', HELLO_RESPONSE: 'helloResponse', HOST_STATE_CHANGED: 'hostStateChanged', IS_HOST_INSTALLED: 'isHostInstalled', IS_HOST_INSTALLED_RESPONSE: 'isHostInstalledResponse' }; /** @enum {string} */ remoting.It2MeHelpeeChannel.Features = { REMOTE_ASSISTANCE: 'remoteAssistance' }; remoting.It2MeHelpeeChannel.prototype.init = function() { this.hangoutPort_.onMessage.addListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.addListener(this.onHangoutDisconnectRef_); }; remoting.It2MeHelpeeChannel.prototype.dispose = function() { if (this.host_ !== null) { this.host_.unhookCallbacks(); this.host_.disconnect(); this.host_ = null; } if (this.hangoutPort_ !== null) { this.hangoutPort_.onMessage.removeListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.removeListener(this.onHangoutDisconnectRef_); this.hostState_ = remoting.HostSession.State.DISCONNECTED; try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: this.hostState_ }); } catch (e) { // |postMessage| throws if |this.hangoutPort_| is disconnected // It is safe to ignore the exception. } this.hangoutPort_.disconnect(); this.hangoutPort_ = null; } if (this.onDisposedCallback_ !== null) { this.onDisposedCallback_(); this.onDisposedCallback_ = null; } }; /** * Message Handler for incoming runtime messages from Hangouts. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutMessage_ = function(message) { try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; switch (message.method) { case MessageTypes.HELLO: this.hangoutPort_.postMessage({ method: MessageTypes.HELLO_RESPONSE, supportedFeatures: base.values(remoting.It2MeHelpeeChannel.Features) }); return true; case MessageTypes.IS_HOST_INSTALLED: this.handleIsHostInstalled_(message); return true; case MessageTypes.DOWNLOAD_HOST: this.handleDownloadHost_(message); return true; case MessageTypes.CONNECT: this.handleConnect_(message); return true; case MessageTypes.DISCONNECT: this.dispose(); return true; } throw new Error('Unsupported message method=' + message.method); } catch(e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } return false; }; /** * Queries the |hostInstaller| for the installation status. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleIsHostInstalled_ = function(message) { /** @type {remoting.It2MeHelpeeChannel} */ var that = this; /** @param {boolean} installed */ function sendResponse(installed) { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; that.hangoutPort_.postMessage({ method: MessageTypes.IS_HOST_INSTALLED_RESPONSE, result: installed }); } this.hostInstaller_.isInstalled().then( sendResponse, this.sendErrorResponse_.bind(this, message) ); }; /** * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleDownloadHost_ = function(message) { try { this.hostInstaller_.download(); } catch (e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } }; /** * Disconnect the session if the |hangoutPort| gets disconnected. * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutDisconnect_ = function() { this.dispose(); }; /** * Connects to the It2Me Native messaging Host and retrieves the access code. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleConnect_ = function(message) { var email = getStringAttr(message, 'email'); if (!email) { throw new Error('Missing required parameter: email'); } if (this.hostState_ !== remoting.HostSession.State.UNKNOWN) { throw new Error('An existing connection is in progress.'); } this.showConfirmDialog_().then( this.initializeHost_.bind(this) ).then( this.fetchOAuthToken_.bind(this) ).then( this.connectToHost_.bind(this, email), this.sendErrorResponse_.bind(this, message) ); }; /** * Prompts the user before starting the It2Me Native Messaging Host. This * ensures that even if Hangouts is compromised, an attacker cannot start the * host without explicit user confirmation. * * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialog_ = function() { if (base.isAppsV2()) { return this.showConfirmDialogV2_(); } else { return this.showConfirmDialogV1_(); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV1_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = base.escapeHTML(messageHeader) + '\n' + '- ' + base.escapeHTML(message1) + '\n' + '- ' + base.escapeHTML(message2) + '\n'; if(window.confirm(message)) { return Promise.resolve(); } else { return Promise.reject(new Error(remoting.Error.CANCELLED)); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV2_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = '<div>' + base.escapeHTML(messageHeader) + '</div>' + '<ul class="insetList">' + '<li>' + base.escapeHTML(message1) + '</li>' + '<li>' + base.escapeHTML(message2) + '</li>' + '</ul>'; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { /** @param {number} result */ function confirmDialogCallback(result) { if (result === 1) { resolve(); } else { reject(new Error(remoting.Error.CANCELLED)); } } remoting.MessageWindow.showConfirmWindow( '', // Empty string to use the package name as the dialog title. message, l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_ACCEPT'), l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_DECLINE'), confirmDialogCallback ); }); }; /** * @return {Promise} A promise that resolves when the host is initialized. * @private */ remoting.It2MeHelpeeChannel.prototype.initializeHost_ = function() { /** @type {remoting.It2MeHostFacade} */ var host = this.host_; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { if (host.initialized()) { resolve(); } else { host.initialize(resolve, reject); } }); }; /** * @return {Promise} Promise that resolves with the OAuth token as the value. */ remoting.It2MeHelpeeChannel.prototype.fetchOAuthToken_ = function() { if (base.isAppsV2()) { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve){ // TODO(jamiewalch): Make this work with {interactive: true} as well. chrome.identity.getAuthToken({ 'interactive': false }, resolve); }); } else { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve) { /** @type {remoting.OAuth2} */ var oauth2 = new remoting.OAuth2(); var onAuthenticated = function() { oauth2.callWithToken( resolve, function() { throw new Error('Authentication failed.'); }); }; /** @param {remoting.Error} error */ var onError = function(error) { if (error != remoting.Error.NOT_AUTHENTICATED) { throw new Error('Unexpected error fetch auth token: ' + error); } oauth2.doAuthRedirect(onAuthenticated); }; oauth2.callWithToken(resolve, onError); }); } }; /** * Connects to the It2Me Native Messaging Host and retrieves the access code * in the |onHostStateChanged_| callback. * * @param {string} email * @param {string} accessToken * @private */ remoting.It2MeHelpeeChannel.prototype.connectToHost_ = function(email, accessToken) { base.debug.assert(this.host_.initialized()); this.host_.connect( email, 'oauth2:' + accessToken, this.onHostStateChanged_.bind(this), base.doNothing, // Ignore |onNatPolicyChanged|. console.log.bind(console), // Forward logDebugInfo to console.log. remoting.settings.XMPP_SERVER_FOR_IT2ME_HOST, remoting.settings.XMPP_SERVER_USE_TLS, remoting.settings.DIRECTORY_BOT_JID, this.onHostConnectError_); }; /** * @param {remoting.Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.onHostConnectError_ = function(error) { this.sendErrorResponse_(null, error); }; /** * @param {remoting.HostSession.State} state * @private */ remoting.It2MeHelpeeChannel.prototype.onHostStateChanged_ = function(state) { this.hostState_ = state; var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; var HostState = remoting.HostSession.State; switch (state) { case HostState.RECEIVED_ACCESS_CODE: var accessCode = this.host_.getAccessCode(); this.hangoutPort_.postMessage({ method: MessageTypes.CONNECT_RESPONSE, accessCode: accessCode }); break; case HostState.CONNECTED: case HostState.DISCONNECTED: this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: state }); break; case HostState.ERROR: this.sendErrorResponse_(null, remoting.Error.UNEXPECTED); break; case HostState.INVALID_DOMAIN_ERROR: this.sendErrorResponse_(null, remoting.Error.INVALID_HOST_DOMAIN); break; default: // It is safe to ignore other state changes. } }; /** * @param {?{method:string, data:Object.<string,*>}} incomingMessage<|fim▁hole|> function(incomingMessage, error) { if (error instanceof Error) { error = error.message; } console.error('Error responding to message method:' + (incomingMessage ? incomingMessage.method : 'null') + ' error:' + error); this.hangoutPort_.postMessage({ method: remoting.It2MeHelpeeChannel.HangoutMessageTypes.ERROR, message: error, request: incomingMessage }); };<|fim▁end|>
* @param {string|Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.sendErrorResponse_ =
<|file_name|>ArrayTypearg.java<|end_file_name|><|fim▁begin|>/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * @test * @bug 4881205 * @summary generics: array as generic argument type fails * @author gafter * * @compile -source 1.5 ArrayTypearg.java */ import java.util.List; import java.util.ArrayList; <|fim▁hole|> Object o1 = list.get(0)[0]; } }<|fim▁end|>
class ArrayTypearg { private void foo() { List<Object[]> list = new ArrayList<Object[]>();
<|file_name|>FindItemsForFavoriteSearchResponse.java<|end_file_name|><|fim▁begin|>// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.marketplace.search.v1.services; import com.leansoft.nano.annotation.*; /** * * Reserved for future use. * */ @RootElement(name = "findItemsForFavoriteSearchResponse", namespace = "http://www.ebay.com/marketplace/search/v1/services") public class FindItemsForFavoriteSearchResponse extends BaseFindingServiceResponse { @Element private CategoryHistogramContainer categoryHistogramContainer; @Element private AspectHistogramContainer aspectHistogramContainer; @Element private ConditionHistogramContainer conditionHistogramContainer; /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.CategoryHistogramContainer */ public CategoryHistogramContainer getCategoryHistogramContainer() { return this.categoryHistogramContainer;<|fim▁hole|> /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.CategoryHistogramContainer */ public void setCategoryHistogramContainer(CategoryHistogramContainer categoryHistogramContainer) { this.categoryHistogramContainer = categoryHistogramContainer; } /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.AspectHistogramContainer */ public AspectHistogramContainer getAspectHistogramContainer() { return this.aspectHistogramContainer; } /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.AspectHistogramContainer */ public void setAspectHistogramContainer(AspectHistogramContainer aspectHistogramContainer) { this.aspectHistogramContainer = aspectHistogramContainer; } /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.ConditionHistogramContainer */ public ConditionHistogramContainer getConditionHistogramContainer() { return this.conditionHistogramContainer; } /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.ConditionHistogramContainer */ public void setConditionHistogramContainer(ConditionHistogramContainer conditionHistogramContainer) { this.conditionHistogramContainer = conditionHistogramContainer; } }<|fim▁end|>
}
<|file_name|>ls.js<|end_file_name|><|fim▁begin|>/* * Elfenben - Javascript using tree syntax! This is the compiler written in javascipt * */ var version = "1.0.16", banner = "// Generated by Elfenben v" + version + "\n", isWhitespace = /\s/, isFunction = /^function\b/, validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/, noReturn = /^var\b|^set\b|^throw\b/, isHomoiconicExpr = /^#args-if\b|^#args-shift\b|^#args-second\b/, noSemiColon = false, indentSize = 4, indent = -indentSize, keywords = {}, macros = {}, errors = [], include_dirs = [__dirname + "/../includes", "includes"], fs, path, SourceNode = require('source-map').SourceNode if (typeof window === "undefined") { fs = require('fs') path = require('path') } if (!String.prototype.repeat) { String.prototype.repeat = function(num) { return new Array(num + 1).join(this) } } var parse = function(code, filename) { code = "(" + code + ")" var length = code.length, pos = 1, lineno = 1, colno = 1, token_begin_colno = 1 var parser = function() { var tree = [], token = "", isString = false, isSingleString = false, isJSArray = 0, isJSObject = 0, isListComplete = false, isComment = false, isRegex = false, isEscape = false, handleToken = function() { if (token) { tree.push(new SourceNode(lineno, token_begin_colno - 1, filename, token, token)) token = "" } } tree._line = lineno tree._filename = filename while (pos < length) { var c = code.charAt(pos) pos++ colno++ if (c == "\n") { lineno++ colno = 1 if (isComment) { isComment = false } } if (isComment) { continue } if (isEscape) { isEscape = false token += c continue } // strings if (c == '"' || c == '`') { isString = !isString token += c continue } if (isString) { if (c === "\n") { token += "\\n" } else { if (c === "\\") { isEscape = true } token += c } continue } if (c == "'") { isSingleString = !isSingleString token += c continue } if (isSingleString) { token += c continue } // data types if (c == '[') { isJSArray++ token += c continue } if (c == ']') { if (isJSArray === 0) { handleError(4, tree._line, tree._filename) } isJSArray-- token += c continue } if (isJSArray) { token += c continue } if (c == '{') { isJSObject++ token += c continue } if (c == '}') { if (isJSObject === 0) { handleError(6, tree._line, tree._filename) } isJSObject-- token += c continue } if (isJSObject) { token += c continue } if (c == ";") { isComment = true continue } // regex // regex in function position with first char " " is a prob. Use \s instead. if (c === "/" && !(tree.length === 0 && token.length === 0 && isWhitespace.test(code.charAt(pos)))) { isRegex = !isRegex token += c continue } if (isRegex) { if (c === "\\") { isEscape = true } token += c continue } if (c == "(") { handleToken() // catch e.g. "blah(" token_begin_colno = colno tree.push(parser()) continue } if (c == ")") { isListComplete = true handleToken() token_begin_colno = colno break } if (isWhitespace.test(c)) { if (c == '\n') lineno-- handleToken() if (c == '\n') lineno++ token_begin_colno = colno continue } token += c } if (isString) handleError(3, tree._line, tree._filename) if (isRegex) handleError(14, tree._line, tree._filename) if (isSingleString) handleError(3, tree._line, tree._filename) if (isJSArray > 0) handleError(5, tree._line, tree._filename) if (isJSObject > 0) handleError(7, tree._line, tree._filename) if (!isListComplete) handleError(8, tree._line, tree._filename) return tree } var ret = parser() if (pos < length) { handleError(10) } return ret } var handleExpressions = function(exprs) { indent += indentSize var ret = new SourceNode(), l = exprs.length, indentstr = " ".repeat(indent) exprs.forEach(function(expr, i, exprs) { var exprName, tmp = null, r = "" if (Array.isArray(expr)) { exprName = expr[0].name if (exprName === "include") ret.add(handleExpression(expr)) else tmp = handleExpression(expr) } else { tmp = expr } if (i === l - 1 && indent) { if (!noReturn.test(exprName)) r = "return " } if (tmp) { var endline = noSemiColon ? "\n" : ";\n" noSemiColon = false ret.add([indentstr + r, tmp, endline]) } }) indent -= indentSize return ret } var handleExpression = function(expr) { if (!expr || !expr[0]) { return null } var command = expr[0].name if (macros[command]) { expr = macroExpand(expr) if (Array.isArray(expr)) { return handleExpression(expr) } else { return expr } } if (typeof command === "string") { if (keywords[command]) { return keywords[command](expr) } if (command.charAt(0) === ".") { var ret = new SourceNode() ret.add(Array.isArray(expr[1]) ? handleExpression(expr[1]) : expr[1]) ret.prepend("(") ret.add([")", expr[0]]) return ret } } handleSubExpressions(expr) var fName = expr[0] if (!fName) { handleError(1, expr._line) } if (isFunction.test(fName)) fName = new SourceNode(null, null, null, ['(', fName, ')']) exprNode = new SourceNode (null, null, null, expr.slice(1)).join(",") return new SourceNode (null, null, null, [fName, "(", exprNode, ")"]) } var handleSubExpressions = function(expr) { expr.forEach(function(value, i, t) { if (Array.isArray(value)) t[i] = handleExpression(value) }) } var macroExpand = function(tree) { var command = tree[0].name, template = macros[command]["template"], code = macros[command]["code"], replacements = {} for (var i = 0; i < template.length; i++) { if (template[i].name == "rest...") { replacements["~rest..."] = tree.slice(i + 1) } else { if (tree.length === i + 1) { // we are here if any macro arg is not set handleError(12, tree._line, tree._filename, command) } replacements["~" + template[i].name] = tree[i + 1] } } var replaceCode = function(source) { var ret = [] ret._line = tree._line ret._filename = tree._filename // Handle homoiconic expressions in macro var expr_name = source[0] ? source[0].name : "" if (isHomoiconicExpr.test(expr_name)) { var replarray = replacements["~" + source[1].name] if (expr_name === "#args-shift") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argshift = replarray.shift() if (typeof argshift === "undefined") { handleError(12, tree._line, tree._filename, command) } return argshift } if (expr_name === "#args-second") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argsecond = replarray.splice(1, 1)[0] if (typeof argsecond === "undefined") { handleError(12, tree._line, tree._filename, command) } return argsecond } if (expr_name === "#args-if") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } if (replarray.length) { return replaceCode(source[2]) } else if (source[3]) { return replaceCode(source[3]) } else { return } } } for (var i = 0; i < source.length; i++) { if (Array.isArray(source[i])) { var replcode = replaceCode(source[i]) if (typeof replcode !== "undefined") { ret.push(replcode) } } else { var token = source[i], tokenbak = token, isATSign = false if (token.name.indexOf("@") >= 0) { isATSign = true tokenbak = new SourceNode(token.line, token.column, token.source, token.name.replace("@", ""), token.name.replace("@", "")) } if (replacements[tokenbak.name]) { var repl = replacements[tokenbak.name] if (isATSign || tokenbak.name == "~rest...") { for (var j = 0; j < repl.length; j++) { ret.push(repl[j]) } } else { ret.push(repl) } } else { ret.push(token) } } } return ret } return replaceCode(code) } var handleCompOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) if (arr[0] == "=") arr[0] = "===" if (arr[0] == "!=") arr[0] = "!==" var op = arr.shift() var ret = new SourceNode() for (i = 0; i < arr.length - 1; i++) ret.add (new SourceNode (null, null, null, [arr[i], " ", op, " ", arr[i + 1]])) ret.join (' && ') ret.prepend('(') ret.add(')') return ret } var handleArithOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) var op = new SourceNode() op.add([" ", arr.shift(), " "]) var ret = new SourceNode() ret.add(arr) ret.join (op) ret.prepend("(") ret.add(")") return ret } var handleLogicalOperator = handleArithOperator var handleVariableDeclarations = function(arr, varKeyword){ if (arr.length < 3) handleError(0, arr._line, arr._filename) if (arr.length > 3) { indent += indentSize } handleSubExpressions(arr) var ret = new SourceNode () ret.add(varKeyword + " ") for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } if (!validName.test(arr[i])) handleError(9, arr._line, arr._filename) ret.add([arr[i], ' = ', arr[i + 1]]) } if (arr.length > 3) { indent -= indentSize } return ret } keywords["var"] = function(arr) { return handleVariableDeclarations(arr, "var") } keywords["const"] = function(arr) { return handleVariableDeclarations(arr, "const") } keywords["let"] = function(arr) { return handleVariableDeclarations(arr, "let") } keywords["new"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(handleExpression(arr.slice(1))) ret.prepend ("new ") return ret } keywords["throw"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(Array.isArray(arr[1]) ? handleExpression(arr[1]) : arr[1]) ret.prepend("(function(){throw ") ret.add(";})()") return ret } keywords["set"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) if (arr.length == 4) { arr[1] = (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2]) + "[" + arr[1] + "]" arr[2] = arr[3] } return new SourceNode(null, null, null, [arr[1], " = ", (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2])]) } keywords["function"] = function(arr) { var ret var fName, fArgs, fBody if (arr.length < 2) handleError(0, arr._line, arr._filename) if(Array.isArray(arr[1])) { // an anonymous function fArgs = arr[1] fBody = arr.slice(2) } else if(!Array.isArray(arr[1]) && Array.isArray(arr[2])) { // a named function fName = arr[1] fArgs = arr[2] fBody = arr.slice(3) } else handleError(0, arr._line) ret = new SourceNode(null, null, null, fArgs) ret.join(",") ret.prepend("function" + (fName ? " " + fName.name : "") + "(") ret.add([") {\n",handleExpressions(fBody), " ".repeat(indent), "}"]) if(fName) noSemiColon = true return ret } keywords["try"] = function(arr) { if (arr.length < 3) handleError(0, arr._line, arr._filename) var c = arr.pop(), ind = " ".repeat(indent), ret = new SourceNode() ret.add(["(function() {\n" + ind + "try {\n", handleExpressions(arr.slice(1)), "\n" + ind + "} catch (e) {\n" + ind + "return (", (Array.isArray(c) ? handleExpression(c) : c), ")(e);\n" + ind + "}\n" + ind + "})()"]) return ret } keywords["if"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) indent += indentSize handleSubExpressions(arr) var ret = new SourceNode() ret.add(["(", arr[1], " ?\n" + " ".repeat(indent), arr[2], " :\n" + " ".repeat(indent), (arr[3] || "undefined"), ")"]) indent -= indentSize return ret } keywords["get"] = function(arr) { if (arr.length != 3) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return new SourceNode(null, null, null, [arr[2], "[", arr[1], "]"]) } keywords["str"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) var ret = new SourceNode() ret.add(arr.slice(1)) ret.join (",") ret.prepend("[") ret.add("].join('')") return ret } keywords["array"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("[]") return ret } indent += indentSize handleSubExpressions(arr) ret.add("[\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; ++i) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add(arr[i]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "]") return ret } keywords["object"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("{}") return ret } indent += indentSize handleSubExpressions(arr) ret.add("{\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add([arr[i], ': ', arr[i + 1]]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "}") <|fim▁hole|> var included = [] return function(filename) { if (included.indexOf(filename) !== -1) return "" included.push(filename) var code = fs.readFileSync(filename) var tree = parse(code, filename) return handleExpressions(tree) } })() keywords["include"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) indent -= indentSize var filename = arr[1].name if (typeof filename === "string") filename = filename.replace(/["']/g, "") var found = false; include_dirs.concat([path.dirname(arr._filename)]) .forEach(function(prefix) { if (found) { return; } try { filename = fs.realpathSync(prefix + '/' +filename) found = true; } catch (err) { } }); if (!found) { handleError(11, arr._line, arr._filename) } var ret = new SourceNode() ret = includeFile(filename) indent += indentSize return ret } keywords["javascript"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) noSemiColon = true arr[1].replaceRight(/"/g, '') return arr[1] } keywords["macro"] = function(arr) { if (arr.length != 4) handleError(0, arr._line, arr._filename) macros[arr[1].name] = {template: arr[2], code: arr[3]} return "" } keywords["+"] = handleArithOperator keywords["-"] = handleArithOperator keywords["*"] = handleArithOperator keywords["/"] = handleArithOperator keywords["%"] = handleArithOperator keywords["="] = handleCompOperator keywords["!="] = handleCompOperator keywords[">"] = handleCompOperator keywords[">="] = handleCompOperator keywords["<"] = handleCompOperator keywords["<="] = handleCompOperator keywords["||"] = handleLogicalOperator keywords["&&"] = handleLogicalOperator keywords["!"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return "(!" + arr[1] + ")" } var handleError = function(no, line, filename, extra) { throw new Error(errors[no] + ((extra) ? " - " + extra : "") + ((line) ? "\nLine no " + line : "") + ((filename) ? "\nFile " + filename : "")) } errors[0] = "Syntax Error" errors[1] = "Empty statement" errors[2] = "Invalid characters in function name" errors[3] = "End of File encountered, unterminated string" errors[4] = "Closing square bracket, without an opening square bracket" errors[5] = "End of File encountered, unterminated array" errors[6] = "Closing curly brace, without an opening curly brace" errors[7] = "End of File encountered, unterminated javascript object '}'" errors[8] = "End of File encountered, unterminated parenthesis" errors[9] = "Invalid character in var name" errors[10] = "Extra chars at end of file. Maybe an extra ')'." errors[11] = "Cannot Open include File" errors[12] = "Invalid no of arguments to " errors[13] = "Invalid Argument type to " errors[14] = "End of File encountered, unterminated regular expression" var _compile = function(code, filename, withSourceMap, a_include_dirs) { indent = -indentSize if (a_include_dirs) include_dirs = a_include_dirs var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) if (withSourceMap) { var outputFilename = path.basename(filename, '.elf') + '.js' var sourceMapFile = outputFilename + '.map' var output = outputNode.toStringWithSourceMap({ file: outputFilename }); fs.writeFileSync(sourceMapFile, output.map) return output.code + "\n//# sourceMappingURL=" + path.relative(path.dirname(filename), sourceMapFile); } else return outputNode.toString() } exports.version = version exports._compile = _compile exports.parseWithSourceMap = function(code, filename) { var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) return outputNode.toStringWithSourceMap(); }<|fim▁end|>
return ret } var includeFile = (function () {
<|file_name|>tyencode.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Type encoding #![allow(unused_must_use)] // as with encoding, everything is a no-fail MemWriter #![allow(non_camel_case_types)] use std::cell::RefCell; use std::io::prelude::*; use middle::region; use middle::subst; use middle::subst::VecPerParamSpace; use middle::ty::ParamTy; use middle::ty::{self, Ty}; use util::nodemap::FnvHashMap; use syntax::abi::Abi; use syntax::ast; use syntax::diagnostic::SpanHandler; use rbml::writer::Encoder; macro_rules! mywrite { ($w:expr, $($arg:tt)*) => ({ write!($w.writer, $($arg)*); }) } pub struct ctxt<'a, 'tcx: 'a> { pub diag: &'a SpanHandler, // Def -> str Callback: pub ds: fn(ast::DefId) -> String, // The type context. pub tcx: &'a ty::ctxt<'tcx>, pub abbrevs: &'a abbrev_map<'tcx> } // Compact string representation for Ty values. API TyStr & parse_from_str. // Extra parameters are for converting to/from def_ids in the string rep. // Whatever format you choose should not contain pipe characters. pub struct ty_abbrev { s: String } pub type abbrev_map<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>; pub fn enc_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) { match cx.abbrevs.borrow_mut().get(&t) { Some(a) => { w.writer.write_all(a.s.as_bytes()); return; } None => {} } // type abbreviations needs a stable position let pos = w.mark_stable_position(); match t.sty { ty::TyBool => mywrite!(w, "b"), ty::TyChar => mywrite!(w, "c"), ty::TyInt(t) => { match t { ast::TyIs => mywrite!(w, "is"), ast::TyI8 => mywrite!(w, "MB"), ast::TyI16 => mywrite!(w, "MW"), ast::TyI32 => mywrite!(w, "ML"), ast::TyI64 => mywrite!(w, "MD") } } ty::TyUint(t) => { match t { ast::TyUs => mywrite!(w, "us"), ast::TyU8 => mywrite!(w, "Mb"), ast::TyU16 => mywrite!(w, "Mw"), ast::TyU32 => mywrite!(w, "Ml"), ast::TyU64 => mywrite!(w, "Md") } } ty::TyFloat(t) => { match t { ast::TyF32 => mywrite!(w, "Mf"), ast::TyF64 => mywrite!(w, "MF"), } } ty::TyEnum(def, substs) => { mywrite!(w, "t[{}|", (cx.ds)(def)); enc_substs(w, cx, substs); mywrite!(w, "]"); } ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => { mywrite!(w, "x["); enc_trait_ref(w, cx, principal.0); enc_existential_bounds(w, cx, bounds); mywrite!(w, "]"); } ty::TyTuple(ref ts) => { mywrite!(w, "T["); for t in ts { enc_ty(w, cx, *t); } mywrite!(w, "]"); } ty::TyBox(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); } ty::TyRawPtr(mt) => { mywrite!(w, "*"); enc_mt(w, cx, mt); } ty::TyRef(r, mt) => { mywrite!(w, "&"); enc_region(w, cx, *r); enc_mt(w, cx, mt); } ty::TyArray(t, sz) => { mywrite!(w, "V"); enc_ty(w, cx, t); mywrite!(w, "/{}|", sz); } ty::TySlice(t) => { mywrite!(w, "V"); enc_ty(w, cx, t); mywrite!(w, "/|"); } ty::TyStr => { mywrite!(w, "v"); } ty::TyBareFn(Some(def_id), f) => { mywrite!(w, "F"); mywrite!(w, "{}|", (cx.ds)(def_id)); enc_bare_fn_ty(w, cx, f); } ty::TyBareFn(None, f) => { mywrite!(w, "G"); enc_bare_fn_ty(w, cx, f); } ty::TyInfer(_) => { cx.diag.handler().bug("cannot encode inference variable types"); } ty::TyParam(ParamTy {space, idx, name}) => { mywrite!(w, "p[{}|{}|{}]", idx, space.to_uint(), name) } ty::TyStruct(def, substs) => { mywrite!(w, "a[{}|", (cx.ds)(def)); enc_substs(w, cx, substs); mywrite!(w, "]"); } ty::TyClosure(def, ref substs) => { mywrite!(w, "k[{}|", (cx.ds)(def)); enc_substs(w, cx, &substs.func_substs); for ty in &substs.upvar_tys { enc_ty(w, cx, ty); } mywrite!(w, "."); mywrite!(w, "]"); } ty::TyProjection(ref data) => { mywrite!(w, "P["); enc_trait_ref(w, cx, data.trait_ref); mywrite!(w, "{}]", data.item_name); } ty::TyError => { mywrite!(w, "e"); } } let end = w.mark_stable_position(); let len = end - pos; fn estimate_sz(u: u64) -> u64 { let mut n = u; let mut len = 0; while n != 0 { len += 1; n = n >> 4; } return len; } let abbrev_len = 3 + estimate_sz(pos) + estimate_sz(len); if abbrev_len < len { // I.e. it's actually an abbreviation. cx.abbrevs.borrow_mut().insert(t, ty_abbrev { s: format!("#{:x}:{:x}#", pos, len) }); } } fn enc_mutability(w: &mut Encoder, mt: ast::Mutability) { match mt { ast::MutImmutable => (), ast::MutMutable => mywrite!(w, "m"), } } fn enc_mt<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, mt: ty::TypeAndMut<'tcx>) { enc_mutability(w, mt.mutbl); enc_ty(w, cx, mt.ty); } fn enc_opt<T, F>(w: &mut Encoder, t: Option<T>, enc_f: F) where F: FnOnce(&mut Encoder, T), { match t { None => mywrite!(w, "n"), Some(v) => { mywrite!(w, "s"); enc_f(w, v); } } } fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, v: &VecPerParamSpace<T>, mut op: F) where F: FnMut(&mut Encoder, &ctxt<'a, 'tcx>, &T), { for &space in &subst::ParamSpace::all() { mywrite!(w, "["); for t in v.get_slice(space) { op(w, cx, t); } mywrite!(w, "]"); } } pub fn enc_substs<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, substs: &subst::Substs<'tcx>) { enc_region_substs(w, cx, &substs.regions); enc_vec_per_param_space(w, cx, &substs.types, |w, cx, &ty| enc_ty(w, cx, ty)); } fn enc_region_substs(w: &mut Encoder, cx: &ctxt, substs: &subst::RegionSubsts) { match *substs { subst::ErasedRegions => { mywrite!(w, "e"); } subst::NonerasedRegions(ref regions) => { mywrite!(w, "n"); enc_vec_per_param_space(w, cx, regions, |w, cx, &r| enc_region(w, cx, r)); } } } pub fn enc_region(w: &mut Encoder, cx: &ctxt, r: ty::Region) { match r { ty::ReLateBound(id, br) => { mywrite!(w, "b[{}|", id.depth); enc_bound_region(w, cx, br); mywrite!(w, "]"); } ty::ReEarlyBound(ref data) => { mywrite!(w, "B[{}|{}|{}|{}]", data.param_id, data.space.to_uint(), data.index, data.name); } ty::ReFree(ref fr) => { mywrite!(w, "f["); enc_destruction_scope_data(w, fr.scope); mywrite!(w, "|"); enc_bound_region(w, cx, fr.bound_region); mywrite!(w, "]"); } ty::ReScope(scope) => { mywrite!(w, "s"); enc_scope(w, cx, scope); mywrite!(w, "|"); } ty::ReStatic => { mywrite!(w, "t"); } ty::ReEmpty => { mywrite!(w, "e"); } ty::ReInfer(_) => { // these should not crop up after typeck cx.diag.handler().bug("cannot encode region variables"); } } } fn enc_scope(w: &mut Encoder, _cx: &ctxt, scope: region::CodeExtent) { match scope { region::CodeExtent::ParameterScope { fn_id, body_id } => mywrite!(w, "P[{}|{}]", fn_id, body_id), region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id), region::CodeExtent::Remainder(region::BlockRemainder { block: b, first_statement_index: i }) => mywrite!(w, "B[{}|{}]", b, i), region::CodeExtent::DestructionScope(node_id) => mywrite!(w, "D{}", node_id), } } fn enc_destruction_scope_data(w: &mut Encoder, d: region::DestructionScopeData) { mywrite!(w, "{}", d.node_id); } fn enc_bound_region(w: &mut Encoder, cx: &ctxt, br: ty::BoundRegion) { match br { ty::BrAnon(idx) => { mywrite!(w, "a{}|", idx); } ty::BrNamed(d, name) => { mywrite!(w, "[{}|{}]", (cx.ds)(d), name); } ty::BrFresh(id) => { mywrite!(w, "f{}|", id); } ty::BrEnv => { mywrite!(w, "e|"); } } } pub fn enc_trait_ref<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, s: ty::TraitRef<'tcx>) { mywrite!(w, "{}|", (cx.ds)(s.def_id)); enc_substs(w, cx, s.substs); } fn enc_unsafety(w: &mut Encoder, p: ast::Unsafety) { match p { ast::Unsafety::Normal => mywrite!(w, "n"), ast::Unsafety::Unsafe => mywrite!(w, "u"), } } fn enc_abi(w: &mut Encoder, abi: Abi) { mywrite!(w, "["); mywrite!(w, "{}", abi.name()); mywrite!(w, "]") } pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, ft: &ty::BareFnTy<'tcx>) { enc_unsafety(w, ft.unsafety); enc_abi(w, ft.abi); enc_fn_sig(w, cx, &ft.sig); } pub fn enc_closure_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, ft: &ty::ClosureTy<'tcx>) { enc_unsafety(w, ft.unsafety); enc_fn_sig(w, cx, &ft.sig); enc_abi(w, ft.abi); } fn enc_fn_sig<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, fsig: &ty::PolyFnSig<'tcx>) { mywrite!(w, "["); for ty in &fsig.0.inputs { enc_ty(w, cx, *ty); } mywrite!(w, "]"); if fsig.0.variadic { mywrite!(w, "V"); } else { mywrite!(w, "N"); } match fsig.0.output { ty::FnConverging(result_type) => { enc_ty(w, cx, result_type); } ty::FnDiverging => { mywrite!(w, "z"); } } } pub fn enc_builtin_bounds(w: &mut Encoder, _cx: &ctxt, bs: &ty::BuiltinBounds) { for bound in bs { match bound { ty::BoundSend => mywrite!(w, "S"), ty::BoundSized => mywrite!(w, "Z"), ty::BoundCopy => mywrite!(w, "P"), ty::BoundSync => mywrite!(w, "T"), } } mywrite!(w, "."); } pub fn enc_existential_bounds<'a,'tcx>(w: &mut Encoder, cx: &ctxt<'a,'tcx>, bs: &ty::ExistentialBounds<'tcx>) { enc_builtin_bounds(w, cx, &bs.builtin_bounds); enc_region(w, cx, bs.region_bound); for tp in &bs.projection_bounds { mywrite!(w, "P"); enc_projection_predicate(w, cx, &tp.0); } mywrite!(w, "."); } pub fn enc_region_bounds<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, rs: &[ty::Region]) { for &r in rs { mywrite!(w, "R"); enc_region(w, cx, r); } mywrite!(w, "."); } pub fn enc_type_param_def<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, v: &ty::TypeParameterDef<'tcx>) { mywrite!(w, "{}:{}|{}|{}|{}|", v.name, (cx.ds)(v.def_id), v.space.to_uint(), v.index, (cx.ds)(v.default_def_id)); enc_opt(w, v.default, |w, t| enc_ty(w, cx, t)); enc_object_lifetime_default(w, cx, v.object_lifetime_default); } fn enc_object_lifetime_default<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, default: ty::ObjectLifetimeDefault) { match default { ty::ObjectLifetimeDefault::Ambiguous => mywrite!(w, "a"), ty::ObjectLifetimeDefault::BaseDefault => mywrite!(w, "b"), ty::ObjectLifetimeDefault::Specific(r) => { mywrite!(w, "s"); enc_region(w, cx, r); } } } pub fn enc_predicate<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, p: &ty::Predicate<'tcx>) { match *p {<|fim▁hole|> enc_trait_ref(w, cx, trait_ref.0.trait_ref); } ty::Predicate::Equate(ty::Binder(ty::EquatePredicate(a, b))) => { mywrite!(w, "e"); enc_ty(w, cx, a); enc_ty(w, cx, b); } ty::Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(a, b))) => { mywrite!(w, "r"); enc_region(w, cx, a); enc_region(w, cx, b); } ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(a, b))) => { mywrite!(w, "o"); enc_ty(w, cx, a); enc_region(w, cx, b); } ty::Predicate::Projection(ty::Binder(ref data)) => { mywrite!(w, "p"); enc_projection_predicate(w, cx, data) } } } fn enc_projection_predicate<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, data: &ty::ProjectionPredicate<'tcx>) { enc_trait_ref(w, cx, data.projection_ty.trait_ref); mywrite!(w, "{}|", data.projection_ty.item_name); enc_ty(w, cx, data.ty); }<|fim▁end|>
ty::Predicate::Trait(ref trait_ref) => { mywrite!(w, "t");
<|file_name|>plot_queue.py<|end_file_name|><|fim▁begin|>''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+', dest="files") parser.add_argument('--maxy', help="Max mbps on y-axis..", type=int, default=1000, action="store", dest="maxy") parser.add_argument('--miny', help="Min mbps on y-axis..", type=int, default=0, action="store", dest="miny") parser.add_argument('--legend', '-l', help="Legend to use if there are multiple plots. File names used as default.", action="store", nargs="+", default=None, dest="legend") parser.add_argument('--out', '-o', help="Output png file for the plot.", default=None, # Will show the plot dest="out") parser.add_argument('-s', '--summarise', help="Summarise the time series plot (boxplot). First 10 and last 10 values are ignored.", default=False, dest="summarise", action="store_true") parser.add_argument('--cdf', help="Plot CDF of queue timeseries (first 10 and last 10 values are ignored)", default=False, dest="cdf", action="store_true") parser.add_argument('--labels', help="Labels for x-axis if summarising; defaults to file names", required=False, default=[], nargs="+", dest="labels")<|fim▁hole|>args = parser.parse_args() if args.labels is None: args.labels = args.files if args.legend is None: args.legend = args.files to_plot=[] def get_style(i): if i == 0: return {'color': 'red'} else: return {'color': 'black', 'ls': '-.'} for i, f in enumerate(args.files): data = read_list(f) xaxis = map(float, col(0, data)) start_time = xaxis[0] xaxis = map(lambda x: x - start_time, xaxis) qlens = map(float, col(1, data)) if args.summarise or args.cdf: to_plot.append(qlens[10:-10]) else: plt.plot(xaxis, qlens, label=args.legend[i], lw=2, **get_style(i)) plt.title("Queue sizes") plt.ylabel("Packets") plt.grid(True) #yaxis = range(0, 1101, 50) #ylabels = map(lambda y: str(y) if y%100==0 else '', yaxis) #plt.yticks(yaxis, ylabels) #plt.ylim((0,1100)) plt.ylim((args.miny,args.maxy)) if args.summarise: plt.xlabel("Link Rates") plt.boxplot(to_plot) xaxis = range(1, 1+len(args.files)) plt.xticks(xaxis, args.labels) for x in xaxis: y = pc99(to_plot[x-1]) print x, y if x == 1: s = '99pc: %d' % y offset = (-20,20) else: s = str(y) offset = (-10, 20) plt.annotate(s, (x,y+1), xycoords='data', xytext=offset, textcoords='offset points', arrowprops=dict(arrowstyle="->")) elif args.cdf: for i,data in enumerate(to_plot): xs, ys = cdf(map(int, data)) plt.plot(xs, ys, label=args.legend[i], lw=2, **get_style(i)) plt.ylabel("Fraction") plt.xlabel("Packets") plt.ylim((0, 1.0)) plt.legend(args.legend, loc="upper left") plt.title("") else: plt.xlabel("Seconds") if args.legend: plt.legend(args.legend, loc="upper left") else: plt.legend(args.files) if args.out: plt.savefig(args.out) else: plt.show()<|fim▁end|>
<|file_name|>poller.py<|end_file_name|><|fim▁begin|>from zope.interface import implementer from six import iteritems from twisted.internet.defer import DeferredQueue, inlineCallbacks, maybeDeferred, returnValue from .utils import get_spider_queues from .interfaces import IPoller @implementer(IPoller) class QueuePoller(object):<|fim▁hole|> def __init__(self, config): self.config = config self.update_projects() self.dq = DeferredQueue() @inlineCallbacks def poll(self): if not self.dq.waiting: return for p, q in iteritems(self.queues): c = yield maybeDeferred(q.count) if c: msg = yield maybeDeferred(q.pop) if msg is not None: # In case of a concurrently accessed queue returnValue(self.dq.put(self._message(msg, p))) def next(self): return self.dq.get() def update_projects(self): self.queues = get_spider_queues(self.config) def _message(self, queue_msg, project): d = queue_msg.copy() d['_project'] = project d['_spider'] = d.pop('name') return d<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import cuda_convnet import corrmm<|fim▁end|>
from .base import * # TODO: import the relevant names instead of importing everything.
<|file_name|>CheckpointConfigurationUpdateMarshaller.java<|end_file_name|><|fim▁begin|>/* * Copyright 2014-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://aws.amazon.com/apache2.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. */ package com.amazonaws.services.kinesisanalyticsv2.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.kinesisanalyticsv2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CheckpointConfigurationUpdateMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CheckpointConfigurationUpdateMarshaller { private static final MarshallingInfo<String> CONFIGURATIONTYPEUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConfigurationTypeUpdate").build(); private static final MarshallingInfo<Boolean> CHECKPOINTINGENABLEDUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CheckpointingEnabledUpdate").build(); private static final MarshallingInfo<Long> CHECKPOINTINTERVALUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.LONG) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CheckpointIntervalUpdate").build();<|fim▁hole|> private static final CheckpointConfigurationUpdateMarshaller instance = new CheckpointConfigurationUpdateMarshaller(); public static CheckpointConfigurationUpdateMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(CheckpointConfigurationUpdate checkpointConfigurationUpdate, ProtocolMarshaller protocolMarshaller) { if (checkpointConfigurationUpdate == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(checkpointConfigurationUpdate.getConfigurationTypeUpdate(), CONFIGURATIONTYPEUPDATE_BINDING); protocolMarshaller.marshall(checkpointConfigurationUpdate.getCheckpointingEnabledUpdate(), CHECKPOINTINGENABLEDUPDATE_BINDING); protocolMarshaller.marshall(checkpointConfigurationUpdate.getCheckpointIntervalUpdate(), CHECKPOINTINTERVALUPDATE_BINDING); protocolMarshaller.marshall(checkpointConfigurationUpdate.getMinPauseBetweenCheckpointsUpdate(), MINPAUSEBETWEENCHECKPOINTSUPDATE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }<|fim▁end|>
private static final MarshallingInfo<Long> MINPAUSEBETWEENCHECKPOINTSUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.LONG) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MinPauseBetweenCheckpointsUpdate").build();
<|file_name|>query_test.go<|end_file_name|><|fim▁begin|>package main import ( "testing" <|fim▁hole|> _ "bitbucket.org/ikeikeikeike/antenna/conf/inits" libm "bitbucket.org/ikeikeikeike/antenna/lib/models" "bitbucket.org/ikeikeikeike/antenna/models" "bitbucket.org/ikeikeikeike/antenna/models/character" _ "bitbucket.org/ikeikeikeike/antenna/routers" ) func TestQuery1(t *testing.T) { models.Pictures().Filter("characters__character__name", "悟空").Count() for _, c := range character.CachedCharacters() { if c.Id > 0 && len([]rune(c.Name)) > 2 && !libm.ReHK3.MatchString(c.Name) { pp.Println(c.Name) } } }<|fim▁end|>
"github.com/k0kubun/pp"
<|file_name|>gauge.rs<|end_file_name|><|fim▁begin|>use crate::{ buffer::Buffer, layout::Rect, style::{Color, Style}, symbols, text::{Span, Spans}, widgets::{Block, Widget}, }; /// A widget to display a task progress. /// /// # Examples: /// /// ``` /// # use tui::widgets::{Widget, Gauge, Block, Borders}; /// # use tui::style::{Style, Color, Modifier}; /// Gauge::default() /// .block(Block::default().borders(Borders::ALL).title("Progress")) /// .gauge_style(Style::default().fg(Color::White).bg(Color::Black).add_modifier(Modifier::ITALIC)) /// .percent(20); /// ``` #[derive(Debug, Clone)] pub struct Gauge<'a> { block: Option<Block<'a>>, ratio: f64, label: Option<Span<'a>>, use_unicode: bool, style: Style, gauge_style: Style, } impl<'a> Default for Gauge<'a> { fn default() -> Gauge<'a> { Gauge { block: None, ratio: 0.0, label: None, use_unicode: false, style: Style::default(), gauge_style: Style::default(), } } } impl<'a> Gauge<'a> { pub fn block(mut self, block: Block<'a>) -> Gauge<'a> { self.block = Some(block); self } pub fn percent(mut self, percent: u16) -> Gauge<'a> { assert!( percent <= 100, "Percentage should be between 0 and 100 inclusively." ); self.ratio = f64::from(percent) / 100.0; self } /// Sets ratio ([0.0, 1.0]) directly. pub fn ratio(mut self, ratio: f64) -> Gauge<'a> { assert!( (0.0..=1.0).contains(&ratio), "Ratio should be between 0 and 1 inclusively." ); self.ratio = ratio; self } pub fn label<T>(mut self, label: T) -> Gauge<'a> where T: Into<Span<'a>>, { self.label = Some(label.into()); self } pub fn style(mut self, style: Style) -> Gauge<'a> { self.style = style; self } pub fn gauge_style(mut self, style: Style) -> Gauge<'a> { self.gauge_style = style; self } pub fn use_unicode(mut self, unicode: bool) -> Gauge<'a> { self.use_unicode = unicode; self } } impl<'a> Widget for Gauge<'a> { fn render(mut self, area: Rect, buf: &mut Buffer) { buf.set_style(area, self.style); let gauge_area = match self.block.take() { Some(b) => { let inner_area = b.inner(area); b.render(area, buf); inner_area } None => area, }; buf.set_style(gauge_area, self.gauge_style); if gauge_area.height < 1 { return; } // compute label value and its position // label is put at the center of the gauge_area let label = { let pct = f64::round(self.ratio * 100.0); self.label .unwrap_or_else(|| Span::from(format!("{}%", pct))) }; let clamped_label_width = gauge_area.width.min(label.width() as u16); let label_col = gauge_area.left() + (gauge_area.width - clamped_label_width) / 2; let label_row = gauge_area.top() + gauge_area.height / 2; // the gauge will be filled proportionally to the ratio let filled_width = f64::from(gauge_area.width) * self.ratio; let end = if self.use_unicode { gauge_area.left() + filled_width.floor() as u16 } else { gauge_area.left() + filled_width.round() as u16 }; for y in gauge_area.top()..gauge_area.bottom() { // render the filled area (left to end) for x in gauge_area.left()..end { // spaces are needed to apply the background styling buf.get_mut(x, y) .set_symbol(" ") .set_fg(self.gauge_style.bg.unwrap_or(Color::Reset)) .set_bg(self.gauge_style.fg.unwrap_or(Color::Reset)); } if self.use_unicode && self.ratio < 1.0 { buf.get_mut(end, y) .set_symbol(get_unicode_block(filled_width % 1.0)); } } // set the span buf.set_span(label_col, label_row, &label, clamped_label_width); } } fn get_unicode_block<'a>(frac: f64) -> &'a str { match (frac * 8.0).round() as u16 { 1 => symbols::block::ONE_EIGHTH, 2 => symbols::block::ONE_QUARTER, 3 => symbols::block::THREE_EIGHTHS, 4 => symbols::block::HALF, 5 => symbols::block::FIVE_EIGHTHS, 6 => symbols::block::THREE_QUARTERS, 7 => symbols::block::SEVEN_EIGHTHS, 8 => symbols::block::FULL, _ => " ", } } /// A compact widget to display a task progress over a single line. /// /// # Examples: /// /// ``` /// # use tui::widgets::{Widget, LineGauge, Block, Borders}; /// # use tui::style::{Style, Color, Modifier}; /// # use tui::symbols; /// LineGauge::default() /// .block(Block::default().borders(Borders::ALL).title("Progress")) /// .gauge_style(Style::default().fg(Color::White).bg(Color::Black).add_modifier(Modifier::BOLD)) /// .line_set(symbols::line::THICK) /// .ratio(0.4); /// ``` pub struct LineGauge<'a> { block: Option<Block<'a>>, ratio: f64, label: Option<Spans<'a>>, line_set: symbols::line::Set, style: Style, gauge_style: Style, } impl<'a> Default for LineGauge<'a> { fn default() -> Self { Self { block: None, ratio: 0.0, label: None, style: Style::default(), line_set: symbols::line::NORMAL, gauge_style: Style::default(), } } } impl<'a> LineGauge<'a> { pub fn block(mut self, block: Block<'a>) -> Self { self.block = Some(block); self } pub fn ratio(mut self, ratio: f64) -> Self { assert!( (0.0..=1.0).contains(&ratio), "Ratio should be between 0 and 1 inclusively." ); self.ratio = ratio; self } pub fn line_set(mut self, set: symbols::line::Set) -> Self { self.line_set = set; self } pub fn label<T>(mut self, label: T) -> Self where T: Into<Spans<'a>>, { self.label = Some(label.into()); self } pub fn style(mut self, style: Style) -> Self { self.style = style; self } pub fn gauge_style(mut self, style: Style) -> Self { self.gauge_style = style; self } } impl<'a> Widget for LineGauge<'a> { fn render(mut self, area: Rect, buf: &mut Buffer) { buf.set_style(area, self.style); let gauge_area = match self.block.take() { Some(b) => { let inner_area = b.inner(area); b.render(area, buf); inner_area }<|fim▁hole|> None => area, }; if gauge_area.height < 1 { return; } let ratio = self.ratio; let label = self .label .unwrap_or_else(move || Spans::from(format!("{:.0}%", ratio * 100.0))); let (col, row) = buf.set_spans( gauge_area.left(), gauge_area.top(), &label, gauge_area.width, ); let start = col + 1; if start >= gauge_area.right() { return; } let end = start + (f64::from(gauge_area.right().saturating_sub(start)) * self.ratio).floor() as u16; for col in start..end { buf.get_mut(col, row) .set_symbol(self.line_set.horizontal) .set_style(Style { fg: self.gauge_style.fg, bg: None, add_modifier: self.gauge_style.add_modifier, sub_modifier: self.gauge_style.sub_modifier, }); } for col in end..gauge_area.right() { buf.get_mut(col, row) .set_symbol(self.line_set.horizontal) .set_style(Style { fg: self.gauge_style.bg, bg: None, add_modifier: self.gauge_style.add_modifier, sub_modifier: self.gauge_style.sub_modifier, }); } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn gauge_invalid_percentage() { Gauge::default().percent(110); } #[test] #[should_panic] fn gauge_invalid_ratio_upper_bound() { Gauge::default().ratio(1.1); } #[test] #[should_panic] fn gauge_invalid_ratio_lower_bound() { Gauge::default().ratio(-0.5); } }<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import CodeClipboard from './CodeClipboard'; <|fim▁hole|><|fim▁end|>
export default CodeClipboard;
<|file_name|>Feedback.py<|end_file_name|><|fim▁begin|>from ..PulsePrimitives import * from ..Compiler import compile_to_hardware from ..PulseSequencePlotter import plot_pulse_files from .helpers import create_cal_seqs from itertools import product import operator from ..ControlFlow import *<|fim▁hole|>from typing import Iterable, Union, Tuple @qfunction def qreset(qubits: Channels.LogicalChannel, signVec: Tuple[bool], measDelay: Union[int,float], buf: Union[int,float], reg_size: int = None, TDM_map: Iterable[Union[int,bool]] = None) -> list: """ For each qubit, build the set of feedback actions to perform when receiving a zero or one in the comparison register Parameters ---------- qubits : Channels.LogicalChannel tuple A hashable (immutable) tuple of qubits to reset signVec : boolean tuple A hashable (immutable) tuple of binary values from the compairison register indicating the measured state of each qubit in the register before reset. measDelay : int/float Delay after measurement before performing the LOADCMP comparison with value in the register (seconds) buf : int/float Wait time between (seconds) reg_size : int, optional Size of the register in number of qubits, including those not reset. Default value is set to len(qubits). TDM_map : bit mask, optional Map each qubit to a TDM digital input. If True, arguments reset a subset of the qubit register (see Reset). Default: np.array(qN, qN-1, ..., q1) from MSB to LSB. Returns ------- seq : QGL.ControlFlow.Call QGL sequence with the qreset calls Examples -------- >>> qreset((q1, q2), (0,1), 2e-6, 2e-6); CALL(H:) """ if not reg_size: reg_size = len(qubits) TDM_map = np.arange(reg_size,0,-1) FbGates = [] for ct, q in enumerate(qubits): if signVec[ct] == 0: FbGates.append([gate(q) for gate in [Id, X]]) else: # inverted logic FbGates.append([gate(q) for gate in [X, Id]]) FbSeq = [reduce(operator.mul, x) for x in product(*FbGates)] # load register seq = [Id(qubits[0], measDelay), qwait(kind='CMP'), Id(qubits[0], buf)] # create a branch for each possible comparison value for ct in range(2**reg_size): # duplicate branches for the irrelevant results # if reg_size > len(TDM_map) meas_result = [(ct & TDM_bit)>0 for TDM_bit in 2**(np.array(TDM_map)-1)] branch_idx = sum([t*2**(len(qubits)-ind-1) for ind,t in enumerate((meas_result))]) seq += qif(ct, [FbSeq[branch_idx]]) return seq def Reset(qubits: Iterable[Channels.LogicalChannel], measDelay: Union[int,float]=1e-6, signVec: Tuple[bool] = None, doubleRound: bool = True, buf: Union[int,float] = 20e-9, showPlot: bool = False, measChans: Channels.LogicalChannel = None, add_cals: bool = True, calRepeats: int = 2, reg_size: int = None, TDM_map: Iterable[Union[int,bool]]=None) -> str: """ Preparation, simultanoeus reset, and measurement of an arbitrary number of qubits Parameters ---------- qubits : Channels.LogicalChannel tuple A hashable (immutable) tuple of qubits to reset measDelay : int/float, optional Delay after measurement before performing the LOADCMP compairison with value in the register (seconds) signVec : boolean tuple, optional conditions for feedback. Tuple of 0 (flip if signal is above threshold) and 1 (flip if below) for each qubit. Default = 0 for all qubits doubleRound : boolean, optional If true, do two rounds of feedback showPlot : boolean, optional Whether to plot measChans : LogicalChannel tuple, optional A hashable (immutable) tuple of qubits to measured. add_cals : boolean, optional Whether to append calibration pulses to the end of the sequence calRepeats : int, optional How many times to repeat calibration scalings (default 2) reg_size : int, optional Size of the register in number of qubits, including those not reset. Default value is set to len(qubits). TDM_map : bit mask, optional Map each qubit to a TDM digital input. If True, arguments reset a subset of the qubit register (see Reset). Default: np.array(qN, qN-1, ..., q1) from MSB to LSB. Returns ------- metafile : string Path to a json metafile with details about the sequences and paths to compiled machine files Examples -------- >>> Reset((q1, q2)); Compiled 12 sequences. >>> mf '/path/to/exp/exp-meta.json' """ if measChans is None: measChans = qubits if signVec == None: signVec = (0, ) * len(qubits) seqs = [prep + [qreset(qubits, signVec, measDelay, buf, reg_size=reg_size, TDM_map=TDM_map)] for prep in create_cal_seqs(qubits, 1)] measBlock = reduce(operator.mul, [MEAS(q) for q in qubits]) if doubleRound: for seq in seqs: seq += [measBlock] seq.append(qreset(qubits, signVec, measDelay, buf, reg_size=reg_size, TDM_map=TDM_map)) # add final measurement for seq in seqs: seq += [measBlock, Id(qubits[0], measDelay), qwait(kind='CMP')] if add_cals: seqs += create_cal_seqs(qubits, calRepeats, measChans=measChans, waitcmp=True) metafile = compile_to_hardware(seqs, 'Reset/Reset') if showPlot: plot_pulse_files(metafile) return metafile # do not make it a subroutine for now def BitFlip3(data_qs: Iterable[Channels.LogicalChannel], ancilla_qs: Iterable[Channels.LogicalChannel], theta: Union[int,float] = None, phi: Union[int,float] = None, nrounds: int = 1, meas_delay: Union[int,float] = 1e-6, add_cals: bool = False, calRepeats: int = 2) -> str: """ Encoding on 3-qubit bit-flip code, followed by n rounds of syndrome detection, and final correction using the n results. Parameters ---------- data_qs : Channels.LogicalChannel tuple A hashable (immutable) tuple of qubits of the 3 code qubits ancilla_qs : Channels.LogicalChannel tuple A hashable (immutable) tuple of qubits of the 2 syndrome qubits theta : int/float, optional Longitudinal rotation angle for the encoded state (radians). Default = None. phi : int/float, optional Azimuthal rotation angle for the encoded state (radians). Default = None. nrounds: int, optional Number of consecutive measurements measDelay : int/float, optional Delay between syndrome check rounds (seconds) add_cals : boolean, optional Whether to append calibration pulses to the end of the sequence calRepeats : int, optional How many times to repeat calibration scalings (default 2) Returns ------- metafile : string Path to a json metafile with details about the sequences and paths to compiled machine files Examples -------- >>> mf = BitFlip3((q1, q2, q3), (q4, q5)); Compiled 12 sequences. >>> mf '/path/to/exp/exp-meta.json' """ if len(data_qs) != 3 or len(ancilla_qs) != 2: raise Exception("Wrong number of qubits") seqs = [ DecodeSetRounds(1,0,nrounds), Invalidate(10, 2*nrounds), Invalidate(11, 0x1)] # encode single-qubit state into 3 qubits if theta and phi: seqs+=[Utheta(data_qs[1], theta, phi), CNOT(data_qs[1], data_qs[0]), CNOT(data_qs[1], data_qs[2])] # multiple rounds of syndrome measurements for n in range(nrounds): seqs+= [CNOT(data_qs[0],ancilla_qs[0])*CNOT(data_qs[1],ancilla_qs[1])], seqs+= [CNOT(data_qs[1], ancilla_qs[0])*CNOT(data_qs[2],ancilla_qs[1])], seqs+= [MEASA(ancilla_qs[0], maddr=(10, 2*n))* MEASA(ancilla_qs[1], maddr=(10, 2*n+1)), Id(ancilla_qs[0], meas_delay), MEAS(data_qs[0], amp=0)* MEAS(data_qs[1], amp=0)* MEAS(data_qs[2], amp=0)] # virtual msmt's just to keep the number of segments # uniform across digitizer channels seqs+=Decode(10, 11, 2*nrounds) seqs+=qwait("RAM",11) seqs+=[MEAS(data_qs[0])* MEAS(data_qs[1])* MEAS(data_qs[2])* MEAS(ancilla_qs[0], amp=0)* MEAS(ancilla_qs[1], amp=0)] # virtual msmt's # apply corrective pulses depending on the decoder result FbGates = [] for q in data_qs: FbGates.append([gate(q) for gate in [Id, X]]) FbSeq = [reduce(operator.mul, x) for x in product(*FbGates)] for k in range(8): seqs += qif(k, [FbSeq[k]]) if add_cals: seqs += create_cal_seqs(qubits, calRepeats) metafile = compile_to_hardware(seqs, 'BitFlip/BitFlip', tdm_seq=True) return metafile def MajorityVoteN(qubits: Iterable[Channels.LogicalChannel], nrounds: int, prep: Iterable[bool] = [], meas_delay: float = 1e-6, add_cals: bool = False, calRepeats: int = 2) -> str: """ Majority vote across multiple measurement results (same or different qubits) Parameters ---------- qubits : Channels.LogicalChannel tuple A hashable (immutable) tuple of qubits for majority vote nrounds: int Number of consecutive measurements prep : boolean iterable, optional Array of binary values mapping X(q) pulses to the list of qubits proivided. Ex: (q1,q2), prep=(1,0) -> would apply a pi pulse to q1 before the majority vote measurement. Default = [] measDelay : int/float, optional Delay between syndrome check rounds (seconds) add_cals : boolean, optional Whether to append calibration pulses to the end of the sequence calRepeats : int, optional How many times to repeat calibration scalings (default 2) Returns ------- metafile : string Path to a json metafile with details about the sequences and paths to compiled machine files Examples -------- >>> mf = MajorityVoteN((q1, q2, q3), 10); Compiled 1 sequences. o INVALIDATE(channel=None, addr=0x1, mask=0x0) o WRITEADDR(channel=None, addr=0x1, value=0xfffff) MAJORITYMASK(in_addr=1, out_addr=0) o INVALIDATE(channel=None, addr=0xa, mask=0xfffff) o INVALIDATE(channel=None, addr=0xb, mask=0x1) MAJORITY(in_addr=a, out_addr=b) >>> mf '/path/to/exp/exp-meta.json' """ nqubits = len(qubits) seqs = [MajorityMask(1, 0, nrounds*nqubits), Invalidate(10, nrounds*nqubits), Invalidate(11, 1)] if prep: seqs += [reduce(operator.mul, [X(q) for n,q in enumerate(qubits) if prep[n]])] for n in range(nrounds): seqs += [reduce(operator.mul, [MEASA(q, (10, nqubits*n+m)) for m,q in enumerate(qubits)]), Id(qubits[0],meas_delay)] seqs+=MajorityVote(10,11, nrounds*nqubits) seqs+=qwait("RAM", 11) seqs+=[Id(qubits[0],100e-9)] seqs+=qif(1,[X(qubits[0])]) # placeholder for any conditional operation seqs=[seqs] if add_cals: seqs += create_cal_seqs(qubits, calRepeats) metafile = compile_to_hardware(seqs, 'MajorityVote/MajorityVote', tdm_seq=True) return metafile<|fim▁end|>
from ..TdmInstructions import * from functools import reduce
<|file_name|>track_sampling.py<|end_file_name|><|fim▁begin|>""" Sampling along tracks --------------------- The :func:`pygmt.grdtrack` function samples a raster grid's value along specified<|fim▁hole|>:class:`pandas.DataFrame` table where the first two columns are x and y (or longitude and latitude). Note also that there is a ``newcolname`` parameter that will be used to name the new column of values sampled from the grid. Alternatively, a NetCDF file path can be passed to ``grid``. An ASCII file path can also be accepted for ``points``. To save an output ASCII file, a file name argument needs to be passed to the ``outfile`` parameter. """ import pygmt # Load sample grid and point datasets grid = pygmt.datasets.load_earth_relief() points = pygmt.datasets.load_ocean_ridge_points() # Sample the bathymetry along the world's ocean ridges at specified track points track = pygmt.grdtrack(points=points, grid=grid, newcolname="bathymetry") fig = pygmt.Figure() # Plot the earth relief grid on Cylindrical Stereographic projection, masking land areas fig.basemap(region="g", projection="Cyl_stere/150/-20/15c", frame=True) fig.grdimage(grid=grid, cmap="gray") fig.coast(land="#666666") # Plot the sampled bathymetry points using circles (c) of 0.15 cm size # Points are colored using elevation values (normalized for visual purposes) fig.plot( x=track.longitude, y=track.latitude, style="c0.15c", cmap="terra", color=(track.bathymetry - track.bathymetry.mean()) / track.bathymetry.std(), ) fig.show()<|fim▁end|>
points. We will need to input a 2D raster to ``grid`` which can be an :class:`xarray.DataArray`. The argument passed to the ``points`` parameter can be a
<|file_name|>move.hpp<|end_file_name|><|fim▁begin|>// Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // (C) Copyright 2007-8 Anthony Williams // (C) Copyright 2011-2012 Vicente J. Botet Escriba #ifndef BOOST_THREAD_MOVE_HPP #define BOOST_THREAD_MOVE_HPP #include <boost/thread/detail/config.hpp> #ifndef BOOST_NO_SFINAE #include <boost/core/enable_if.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/type_traits/decay.hpp> #include <boost/type_traits/conditional.hpp> #include <boost/type_traits/remove_extent.hpp> #include <boost/type_traits/is_array.hpp> #include <boost/type_traits/is_function.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/decay.hpp> #endif #include <boost/thread/detail/delete.hpp> #include <boost/move/utility.hpp> #include <boost/move/traits.hpp> #include <boost/config/abi_prefix.hpp> #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES #include <type_traits> #endif namespace boost { namespace detail { template <typename T> struct enable_move_utility_emulation_dummy_specialization; template<typename T> struct thread_move_t { T& t; explicit thread_move_t(T& t_): t(t_) {} T& operator*() const { return t; } T* operator->() const { return &t; } private: void operator=(thread_move_t&); }; } #if !defined BOOST_THREAD_USES_MOVE #ifndef BOOST_NO_SFINAE template<typename T> typename enable_if<boost::is_convertible<T&,boost::detail::thread_move_t<T> >, boost::detail::thread_move_t<T> >::type move(T& t) { return boost::detail::thread_move_t<T>(t); } #endif template<typename T> boost::detail::thread_move_t<T> move(boost::detail::thread_move_t<T> t) { return t; } #endif //#if !defined BOOST_THREAD_USES_MOVE } #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES #define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE) #define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE) #define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG #define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END #define BOOST_THREAD_RV(V) V #define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE #define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) #define BOOST_THREAD_DCL_MOVABLE(TYPE) #define BOOST_THREAD_DCL_MOVABLE_BEG(T) \ namespace detail { \ template <typename T> \ struct enable_move_utility_emulation_dummy_specialization< #define BOOST_THREAD_DCL_MOVABLE_END > \ : integral_constant<bool, false> \ {}; \ } #elif ! defined BOOST_NO_CXX11_RVALUE_REFERENCES && defined BOOST_MSVC #define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE) #define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE) #define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG #define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END #define BOOST_THREAD_RV(V) V #define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE #define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) #define BOOST_THREAD_DCL_MOVABLE(TYPE) #define BOOST_THREAD_DCL_MOVABLE_BEG(T) \ namespace detail { \ template <typename T> \ struct enable_move_utility_emulation_dummy_specialization< #define BOOST_THREAD_DCL_MOVABLE_END > \ : integral_constant<bool, false> \ {}; \ } #else #if defined BOOST_THREAD_USES_MOVE #define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE) #define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE)<|fim▁hole|>#define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG #define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END #define BOOST_THREAD_RV(V) V #define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) #define BOOST_THREAD_DCL_MOVABLE(TYPE) #define BOOST_THREAD_DCL_MOVABLE_BEG(T) \ namespace detail { \ template <typename T> \ struct enable_move_utility_emulation_dummy_specialization< #define BOOST_THREAD_DCL_MOVABLE_END > \ : integral_constant<bool, false> \ {}; \ } #else #define BOOST_THREAD_RV_REF(TYPE) boost::detail::thread_move_t< TYPE > #define BOOST_THREAD_RV_REF_BEG boost::detail::thread_move_t< #define BOOST_THREAD_RV_REF_END > #define BOOST_THREAD_RV(V) (*V) #define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) #define BOOST_THREAD_DCL_MOVABLE(TYPE) \ template <> \ struct enable_move_utility_emulation< TYPE > \ { \ static const bool value = false; \ }; #define BOOST_THREAD_DCL_MOVABLE_BEG(T) \ template <typename T> \ struct enable_move_utility_emulation< #define BOOST_THREAD_DCL_MOVABLE_END > \ { \ static const bool value = false; \ }; #endif namespace boost { namespace detail { template <typename T> BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type) make_rv_ref(T v) BOOST_NOEXCEPT { return (BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v); } // template <typename T> // BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type) // make_rv_ref(T &v) BOOST_NOEXCEPT // { // return (BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v); // } // template <typename T> // const BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type) // make_rv_ref(T const&v) BOOST_NOEXCEPT // { // return (const BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v); // } } } #define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE.move() //#define BOOST_THREAD_MAKE_RV_REF(RVALUE) boost::detail::make_rv_ref(RVALUE) #endif #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES #define BOOST_THREAD_MOVABLE(TYPE) #else #if defined BOOST_THREAD_USES_MOVE #define BOOST_THREAD_MOVABLE(TYPE) \ ::boost::rv<TYPE>& move() BOOST_NOEXCEPT \ { \ return *static_cast< ::boost::rv<TYPE>* >(this); \ } \ const ::boost::rv<TYPE>& move() const BOOST_NOEXCEPT \ { \ return *static_cast<const ::boost::rv<TYPE>* >(this); \ } \ operator ::boost::rv<TYPE>&() \ { \ return *static_cast< ::boost::rv<TYPE>* >(this); \ } \ operator const ::boost::rv<TYPE>&() const \ { \ return *static_cast<const ::boost::rv<TYPE>* >(this); \ }\ #else #define BOOST_THREAD_MOVABLE(TYPE) \ operator ::boost::detail::thread_move_t<TYPE>() BOOST_NOEXCEPT \ { \ return move(); \ } \ ::boost::detail::thread_move_t<TYPE> move() BOOST_NOEXCEPT \ { \ ::boost::detail::thread_move_t<TYPE> x(*this); \ return x; \ } \ #endif #endif #define BOOST_THREAD_MOVABLE_ONLY(TYPE) \ BOOST_THREAD_NO_COPYABLE(TYPE) \ BOOST_THREAD_MOVABLE(TYPE) \ #define BOOST_THREAD_COPYABLE_AND_MOVABLE(TYPE) \ BOOST_THREAD_MOVABLE(TYPE) \ namespace boost { namespace thread_detail { #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES template <class Tp> struct remove_reference : boost::remove_reference<Tp> {}; template <class Tp> struct decay : boost::decay<Tp> {}; #else template <class Tp> struct remove_reference { typedef Tp type; }; template <class Tp> struct remove_reference<Tp&> { typedef Tp type; }; template <class Tp> struct remove_reference< rv<Tp> > { typedef Tp type; }; template <class Tp> struct decay { private: typedef typename boost::move_detail::remove_rvalue_reference<Tp>::type Up0; typedef typename boost::remove_reference<Up0>::type Up; public: typedef typename conditional < is_array<Up>::value, typename remove_extent<Up>::type*, typename conditional < is_function<Up>::value, typename add_pointer<Up>::type, typename remove_cv<Up>::type >::type >::type type; }; #endif #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES template <class T> typename decay<T>::type decay_copy(T&& t) { return boost::forward<T>(t); } #else template <class T> typename decay<T>::type decay_copy(BOOST_THREAD_FWD_REF(T) t) { return boost::forward<T>(t); } #endif } } #include <boost/config/abi_suffix.hpp> #endif<|fim▁end|>
<|file_name|>mapparser.class.cpp<|end_file_name|><|fim▁begin|>// ************************************************************************** // // 24 Bomb // // By: rcargou <[email protected]> ::: :::::::: // // By: nmohamed <[email protected]> :+: :+: :+: // // By: adjivas <[email protected]> +:+ +:+ +:+ // // By: vjacquie <[email protected]> +#+ +:+ +#+ // // By: jmoiroux <[email protected]> +#+#+#+#+#+ +#+ // // Created: 2015/10/16 17:03:20 by rcargou #+# #+# // // Updated: 2015/10/27 14:00:02 by rcargou ### ########.fr // // // // ************************************************************************** // #include <mapparser.class.hpp> #include <entity.class.hpp> #include <wall.class.hpp> #include <bomb.class.hpp> #include <fire.class.hpp> #include <player.class.hpp> #include <enemy.class.hpp> #include <boss.class.hpp> #include <globject.class.hpp> #include <event.class.hpp> Entity *** Mapparser::map_from_file( char *map_path ) { if (NULL != main_event->map) Mapparser::free_old_map(); Entity *** tmp = Mapparser::map_alloc(); Entity * elem = NULL; std::fstream file; std::string line; std::string casemap; int i = 0, j = globject::mapY_size - 1, x = 0; Mapparser::valid_map(map_path); file.open(map_path , std::fstream::in); for (int x = 0; x < 3; x++) std::getline(file, line); while (j >= 0) { i = ((globject::mapX_size - 1) * 4 ); x = globject::mapX_size - 1; std::getline(file, line); while (i >= 0) { casemap += line[i]; casemap += line[i + 1]; casemap += line[i + 2]; elem = Mapparser::get_entity_from_map( casemap, (float)x, (float)j ); if (elem->type == PLAYER || elem->type == ENEMY || elem->type == BOSS) { tmp[j][x] = Factory::create_empty((int)x, (int)j); main_event->char_list.push_back(elem); } else tmp[j][x] = elem; casemap.clear(); i -= 4; x--; if ( i < 0 ) break; } j--; } main_event->w_log("Mapparser::map_from_file LOADED"); return tmp; } Entity * Mapparser::get_entity_from_map( std::string & casemap, float x, float y) { Entity * tmp = NULL; if ( g_mapcase.count(casemap) == 0) { main_event->w_error("Map file Case Syntax error/doesn't exist"); throw std::exception(); } else { switch (g_mapcase.at(casemap)) { case EMPTY: return static_cast<Entity*>( Factory::create_empty(x, y) ); case WALL_INDESTRUCTIBLE: return static_cast<Entity*>( Factory::create_wall(WALL_INDESTRUCTIBLE, x, y, WALL_INDESTRUCTIBLE) ); case WALL_HP_1: return static_cast<Entity*>( Factory::create_wall(WALL_HP_1, x, y, WALL_HP_1) ); case WALL_HP_2: return static_cast<Entity*>( Factory::create_wall(WALL_HP_2, x, y, WALL_HP_2) ); case WALL_HP_3: return static_cast<Entity*>( Factory::create_wall(WALL_HP_3, x, y, WALL_HP_3) ); case WALL_HP_4: return static_cast<Entity*>( Factory::create_wall(WALL_HP_4, x, y, WALL_HP_4) ); case ENEMY1: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY1) ); case ENEMY2: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY2) ); case ENEMY3: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY3) ); case ENEMY4: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY4) ); case ENEMY5: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY5) ); case BOSS_A: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_A, BOSS_A) ); case BOSS_B: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_B, BOSS_B) ); case BOSS_C: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_C) );<|fim▁hole|> case PLAYER4: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER4) ); case PLAYER5: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER5) ); case PLAYER6: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER6) ); case PLAYER7: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER7) ); case PLAYER8: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER8) ); case PLAYER9: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER9) ); case PLAYER10: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER10) ); case BONUS_POWER_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_POWER_UP) ); case BONUS_PLUS_ONE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_PLUS_ONE) ); case BONUS_KICK: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_KICK) ); case BONUS_CHANGE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_CHANGE) ); case BONUS_REMOTE_BOMB: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_REMOTE_BOMB) ); case BONUS_SPEED_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_SPEED_UP) ); default: return static_cast<Entity*>( Factory::create_empty(x, y) ); } } return tmp; } int Mapparser::valid_map( char const *map_path ) { std::fstream file; std::string line; int x = 0, y = 0, j = 0; if( access( map_path, F_OK ) < 0 ) { main_event->w_error("Mapparser::valid_map file access error"); throw std::exception(); } file.open(map_path , std::fstream::in); if (!file.is_open()) { main_event->w_error("Mapparser::valid_map file open error"); throw std::exception(); } std::getline(file, line); // y: 20 if (line.length() >= 4) x = std::stoi(&line[3]); else main_event->w_exception("map line 1 error"); std::getline(file, line); // x: 20 if (line.length() >= 4) y = std::stoi(&line[3]); else main_event->w_exception("map line 2 error"); std::getline(file, line); // <-- MAP --> j = 0; while ( std::getline(file, line) ) { if ((int)line.length() != (4 * x - 1) ) { main_event->w_exception("width doesn't correspond"); } if (j >= y - 1) break; j++; } if (j != y - 1) main_event->w_exception("Map height doesn't correspond"); file.close(); return 0; } Entity *** Mapparser::map_alloc() { // return map 2d without entity int y = 0; Entity *** new_map = NULL; // TO DELETE SI SEGFAULT // if (main_event->map != NULL) { // while (y < globject::mapY_size) { // std::free(main_event->map[y]); // main_event->map[y] = NULL; // y++; // } // std::free(main_event->map); // main_event->map = NULL; // } ///////////////////// new_map = (Entity ***)std::malloc(sizeof(Entity **) * globject::mapY_size); if (new_map == NULL) { main_event->w_error("Mapparser::map_alloc() new_map Allocation error"); throw std::exception(); } y = 0; while (y < globject::mapY_size) { new_map[y] = NULL; new_map[y] = (Entity **)std::malloc(sizeof(Entity *) * globject::mapX_size); if (new_map[y] == NULL) { main_event->w_error("Mapparser::map_alloc() new_map[y] Allocation error"); throw std::exception(); } y++; } return new_map; } void Mapparser::free_old_map() { int y = 0; while (y < globject::mapY_size) { if (NULL != main_event->map[y]) std::free( main_event->map[y]); y++; } if (NULL != main_event->map) std::free(main_event->map); main_event->map = NULL; } void Mapparser::get_error() const { if (NULL != Mapparser::error) std::cerr << Mapparser::error; } std::string * Mapparser::error = NULL; Mapparser::Mapparser() {} Mapparser::~Mapparser() {} Mapparser::Mapparser( Mapparser const & src ) { *this = src; } Mapparser & Mapparser::operator=( Mapparser const & rhs ) { if (this != &rhs) { this->error = rhs.error; } return *this; }<|fim▁end|>
case BOSS_D: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_D) ); case PLAYER1: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER1) ); case PLAYER2: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER2) ); case PLAYER3: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER3) );
<|file_name|>tarteaucitron.it.js<|end_file_name|><|fim▁begin|>/*global tarteaucitron */ tarteaucitron.lang = { "adblock": "Benvenuto! Questo sito ti permette di attivare i servizi di terzi di tua scelta.", "adblock_call": "Disabilita il tuo adblocker per iniziare la navigazione.", "reload": "Aggiorna la pagina", "alertBigScroll": "Continuando a scorrere,", "alertBigClick": "Continuando a navigare nel sito,", "alertBig": "autorizzi l’utilizzo dei cookies inviati da domini di terze parti", "alertBigPrivacy": "Questo sito fa uso di cookies e ti consente di decidere se accettarli o rifiutarli", "alertSmall": "Gestione dei servizi", "acceptAll": "Ok, accetta tutto", "personalize": "Personalizza", "close": "Chiudi", "all": "Preferenze per tutti i servizi", "info": "Tutela della privacy", "disclaimer": "Abilitando l'uso dei servizi di terze parti, accetti la ricezione dei cookies e l'uso delle tecnologie analitici necessarie al loro funzionamento.", "allow": "Consenti", "deny": "Blocca", "noCookie": "Questo servizio non invia nessun cookie", "useCookie": "Questo servizio puo' inviare", "useCookieCurrent": "Questo servizio ha inviato", "useNoCookie": "Questo servizio non ha inviato nessun cookie", "more": "Saperne di più", "source": "Vai al sito ufficiale", "credit": "Gestione dei cookies da tarteaucitron.js", "toggleInfoBox": "Show/hide informations about cookie storage", "title": "Cookies management panel", "cookieDetail": "Cookie detail for", "ourSite": "on our site", "newWindow": "(new window)", "allowAll": "Allow all cookies", "denyAll": "Deny all cookies", "fallback": "è disattivato", "ads": { "title": "Regie pubblicitarie", "details": "Le regie pubblicitarie producono redditi gestendo la commercializzazione degli spazi del sito dedicati alle campagne pubblicitarie" }, "analytic": { "title": "Misura del pubblico", "details": "I servizi di misura del pubblico permettono di raccogliere le statistiche utili al miglioramento del sito" }, "social": { "title": "Reti sociali", "details": "Le reti sociali permettono di migliorare l'aspetto conviviale del sito e di sviluppare la condivisione dei contenuti da parte degli utenti a fini promozionali." }, "video": { "title": "Video", "details": "I servizi di condivisione di video permettono di arricchire il sito di contenuti multimediali e di aumentare la sua visibilità" }, "comment": { "title": "Commenti",<|fim▁hole|> "support": { "title": "Supporto", "details": "I servizi di supporto ti consentono di contattare la team del sito e di contribuire al suo miglioramento" }, "api": { "title": "API", "details": "Le API permettono di implementare script diversi : geolocalizzazione, motori di ricerca, traduttori..." }, "other": { "title": "Altro", "details": "Servizi per visualizzare contenuti web." } };<|fim▁end|>
"details": "La gestione dei commenti utente aiuta a gestire la pubblicazione dei commenti e a lottare contro lo spamming" },
<|file_name|>primitive_reuse_peer.rs<|end_file_name|><|fim▁begin|>extern crate futures; extern crate tokio_io; use futures::future::ok; use std::cell::RefCell; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer}; use std::io::{Error as IoError, Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; use super::{once, ConstructParams, PeerConstructor, Specifier}; use futures::Future; use std::ops::DerefMut; #[derive(Debug)] pub struct Reuser(pub Rc<dyn Specifier>); impl Specifier for Reuser { fn construct(&self, p: ConstructParams) -> PeerConstructor { let send_zero_msg_on_disconnect = p.program_options.reuser_send_zero_msg_on_disconnect; let reuser = p.global(GlobalState::default).clone(); let mut reuser = reuser.clone(); let l2r = p.left_to_right.clone(); let inner = || self.0.construct(p).get_only_first_conn(l2r); once(connection_reuser( &mut reuser, inner, send_zero_msg_on_disconnect, )) } specifier_boilerplate!(singleconnect has_subspec globalstate); self_0_is_subspecifier!(...); } specifier_class!( name = ReuserClass, target = Reuser, prefixes = ["reuse-raw:", "raw-reuse:"], arg_handling = subspec, overlay = true, MessageBoundaryStatusDependsOnInnerType, SingleConnect, help = r#" Reuse subspecifier for serving multiple clients: unpredictable mode. [A] Better used with --unidirectional, otherwise replies get directed to random connected client. Example: Forward multiple parallel WebSocket connections to a single persistent TCP connection websocat -u ws-l:0.0.0.0:8800 reuse:tcp:127.0.0.1:4567 Example (unreliable): don't disconnect SSH when websocket reconnects websocat ws-l:[::]:8088 reuse:tcp:127.0.0.1:22 "# ); type PeerSlot = Rc<RefCell<Option<Peer>>>; #[derive(Default, Clone)] pub struct GlobalState(PeerSlot); #[derive(Clone)] struct PeerHandle(PeerSlot, bool); impl Read for PeerHandle { fn read(&mut self, b: &mut [u8]) -> Result<usize, IoError> { if let Some(ref mut x) = *self.0.borrow_mut().deref_mut() { x.0.read(b) } else { unreachable!() } } } impl AsyncRead for PeerHandle {} impl Write for PeerHandle { fn write(&mut self, b: &[u8]) -> Result<usize, IoError> { if let Some(ref mut x) = *self.0.borrow_mut().deref_mut() { x.1.write(b) } else { unreachable!() } }<|fim▁hole|> if let Some(ref mut x) = *self.0.borrow_mut().deref_mut() { x.1.flush() } else { unreachable!() } } } impl AsyncWrite for PeerHandle { fn shutdown(&mut self) -> futures::Poll<(), IoError> { if self.1 { let _ = self.write(b""); } if let Some(ref mut _x) = *self.0.borrow_mut().deref_mut() { // Ignore shutdown attempts Ok(futures::Async::Ready(())) //_x.1.shutdown() } else { unreachable!() } } } pub fn connection_reuser<F: FnOnce() -> BoxedNewPeerFuture>( s: &mut GlobalState, inner_peer: F, send_zero_msg_on_disconnect: bool, ) -> BoxedNewPeerFuture { let need_init = s.0.borrow().is_none(); let rc = s.0.clone(); if need_init { info!("Initializing"); Box::new(inner_peer().and_then(move |inner| { { let mut b = rc.borrow_mut(); let x: &mut Option<Peer> = b.deref_mut(); *x = Some(inner); } let ps: PeerSlot = rc.clone(); let ph1 = PeerHandle(ps, send_zero_msg_on_disconnect); let ph2 = ph1.clone(); let peer = Peer::new(ph1, ph2, None /* TODO */); ok(peer) })) as BoxedNewPeerFuture } else { info!("Reusing"); let ps: PeerSlot = rc.clone(); let ph1 = PeerHandle(ps, send_zero_msg_on_disconnect); let ph2 = ph1.clone(); let peer = Peer::new(ph1, ph2, None /* TODO */); Box::new(ok(peer)) as BoxedNewPeerFuture } }<|fim▁end|>
fn flush(&mut self) -> Result<(), IoError> {
<|file_name|>test_trt_convert_group_norm.py<|end_file_name|><|fim▁begin|><|fim▁hole|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from trt_layer_auto_scan_test import TrtLayerAutoScanTest, SkipReasons from program_config import TensorConfig, ProgramConfig import numpy as np import paddle.inference as paddle_infer from functools import partial from typing import Optional, List, Callable, Dict, Any, Set import unittest class TrtConvertGroupNormTest(TrtLayerAutoScanTest): def is_program_valid(self, program_config: ProgramConfig) -> bool: return True def sample_program_configs(self): def generate_input(attrs: List[Dict[str, Any]], batch): if attrs[0]['data_layout'] == 'NCHW': return np.random.random([batch, 32, 64, 64]).astype(np.float32) else: return np.random.random([batch, 64, 64, 32]).astype(np.float32) def generate_scale(): return np.random.randn(32).astype(np.float32) def generate_bias(): return np.random.randn(32).astype(np.float32) for batch in [1, 2, 4]: for group in [1, 4, 32]: for epsilon in [0.1, 0.7]: for data_layout in ['NCHW', 'NHWC']: for i in [0, 1]: dics = [{ "epsilon": epsilon, "groups": group, "data_layout": data_layout }, { "groups": group, "data_layout": data_layout }] ops_config = [{ "op_type": "group_norm", "op_inputs": { "X": ["input_data"], "Scale": ["scale_weight"], "Bias": ["bias_weight"] }, "op_outputs": { "Y": ["y_output"], "Mean": ["mean_output"], "Variance": ["variance_output"] }, "op_attrs": dics[i] }] ops = self.generate_op_config(ops_config) program_config = ProgramConfig( ops=ops, weights={ "scale_weight": TensorConfig( data_gen=partial(generate_scale)), "bias_weight": TensorConfig( data_gen=partial(generate_bias)) }, inputs={ "input_data": TensorConfig(data_gen=partial( generate_input, dics, batch)) }, outputs=["y_output"]) yield program_config def sample_predictor_configs( self, program_config) -> (paddle_infer.Config, List[int], float): def generate_dynamic_shape(attrs): self.dynamic_shape.min_input_shape = {"input_data": [1, 16, 32, 32]} self.dynamic_shape.max_input_shape = { "input_data": [4, 64, 128, 64] } self.dynamic_shape.opt_input_shape = {"input_data": [2, 32, 64, 64]} def clear_dynamic_shape(): self.dynamic_shape.max_input_shape = {} self.dynamic_shape.min_input_shape = {} self.dynamic_shape.opt_input_shape = {} def generate_trt_nodes_num(attrs, dynamic_shape): if len(attrs[0]) == 3: if dynamic_shape: return 1, 2 else: return 0, 3 else: return 0, 3 attrs = [ program_config.ops[i].attrs for i in range(len(program_config.ops)) ] # for static_shape clear_dynamic_shape() self.trt_param.precision = paddle_infer.PrecisionType.Float32 yield self.create_inference_config(), generate_trt_nodes_num( attrs, False), (1e-5, 1e-5) self.trt_param.precision = paddle_infer.PrecisionType.Half yield self.create_inference_config(), generate_trt_nodes_num( attrs, False), (1e-5, 1e-5) # for dynamic_shape generate_dynamic_shape(attrs) self.trt_param.precision = paddle_infer.PrecisionType.Float32 yield self.create_inference_config(), generate_trt_nodes_num( attrs, True), (1e-5, 1e-5) self.trt_param.precision = paddle_infer.PrecisionType.Half yield self.create_inference_config(), generate_trt_nodes_num( attrs, True), (1e-5, 1e-5) def add_skip_trt_case(self): def teller1(program_config, predictor_config): if len(self.dynamic_shape.min_input_shape) != 0: return True return False self.add_skip_case( teller1, SkipReasons.TRT_NOT_IMPLEMENTED, "The goup_norm plugin will check dim not -1 failed when dynamic fp16 mode." ) def test(self): self.add_skip_trt_case() self.run_test() if __name__ == "__main__": unittest.main()<|fim▁end|>
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
<|file_name|>test_effects_layer.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, unicode_literals import pytest import logging from psd_tools.psd.effects_layer import ( CommonStateInfo, ShadowInfo, InnerGlowInfo, OuterGlowInfo, BevelInfo, SolidFillInfo, ) from ..utils import check_write_read, check_read_write logger = logging.getLogger(__name__) @pytest.mark.parametrize( 'kls', [ CommonStateInfo, ShadowInfo,<|fim▁hole|> OuterGlowInfo, BevelInfo, SolidFillInfo, ] ) def test_effects_layer_empty_wr(kls): check_write_read(kls()) @pytest.mark.parametrize( 'fixture', [ ( b'\x00\x00\x00\x028BIMnorm\x0b\xf40262SC\x00\x00\xff\x01\x00\x00' b'\xf0\x89\xa7s\x94\xd1\x00\x00' ), ] ) def test_solid_fill_info(fixture): check_read_write(SolidFillInfo, fixture)<|fim▁end|>
InnerGlowInfo,
<|file_name|>CipherOutputStream.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided<|fim▁hole|> * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.crypto; import java.io.*; /** * A CipherOutputStream is composed of an OutputStream and a Cipher so * that write() methods first process the data before writing them out * to the underlying OutputStream. The cipher must be fully * initialized before being used by a CipherOutputStream. * * <p> For example, if the cipher is initialized for encryption, the * CipherOutputStream will attempt to encrypt data before writing out the * encrypted data. * * <p> This class adheres strictly to the semantics, especially the * failure semantics, of its ancestor classes * java.io.OutputStream and java.io.FilterOutputStream. This class * has exactly those methods specified in its ancestor classes, and * overrides them all. Moreover, this class catches all exceptions * that are not thrown by its ancestor classes. In particular, this * class catches BadPaddingException and other exceptions thrown by * failed integrity checks during decryption. These exceptions are not * re-thrown, so the client will not be informed that integrity checks * failed. Because of this behavior, this class may not be suitable * for use with decryption in an authenticated mode of operation (e.g. GCM) * if the application requires explicit notification when authentication * fails. Such an application can use the Cipher API directly as an * alternative to using this class. * * <p> It is crucial for a programmer using this class not to use * methods that are not defined or overriden in this class (such as a * new method or constructor that is later added to one of the super * classes), because the design and implementation of those methods * are unlikely to have considered security impact with regard to * CipherOutputStream. * * @author Li Gong * @see java.io.OutputStream * @see java.io.FilterOutputStream * @see javax.crypto.Cipher * @see javax.crypto.CipherInputStream * * @since 1.4 */ public class CipherOutputStream extends FilterOutputStream { // the cipher engine to use to process stream data private Cipher cipher; // the underlying output stream private OutputStream output; /* the buffer holding one byte of incoming data */ private byte[] ibuffer = new byte[1]; // the buffer holding data ready to be written out private byte[] obuffer; // stream status private boolean closed = false; /** * * Constructs a CipherOutputStream from an OutputStream and a * Cipher. * <br>Note: if the specified output stream or cipher is * null, a NullPointerException may be thrown later when * they are used. * * @param os the OutputStream object * @param c an initialized Cipher object */ public CipherOutputStream(OutputStream os, Cipher c) { super(os); output = os; cipher = c; }; /** * Constructs a CipherOutputStream from an OutputStream without * specifying a Cipher. This has the effect of constructing a * CipherOutputStream using a NullCipher. * <br>Note: if the specified output stream is null, a * NullPointerException may be thrown later when it is used. * * @param os the OutputStream object */ protected CipherOutputStream(OutputStream os) { super(os); output = os; cipher = new NullCipher(); } /** * Writes the specified byte to this output stream. * * @param b the <code>byte</code>. * @exception IOException if an I/O error occurs. * @since JCE1.2 */ public void write(int b) throws IOException { ibuffer[0] = (byte) b; obuffer = cipher.update(ibuffer, 0, 1); if (obuffer != null) { output.write(obuffer); obuffer = null; } }; /** * Writes <code>b.length</code> bytes from the specified byte array * to this output stream. * <p> * The <code>write</code> method of * <code>CipherOutputStream</code> calls the <code>write</code> * method of three arguments with the three arguments * <code>b</code>, <code>0</code>, and <code>b.length</code>. * * @param b the data. * @exception NullPointerException if <code>b</code> is null. * @exception IOException if an I/O error occurs. * @see javax.crypto.CipherOutputStream#write(byte[], int, int) * @since JCE1.2 */ public void write(byte b[]) throws IOException { write(b, 0, b.length); } /** * Writes <code>len</code> bytes from the specified byte array * starting at offset <code>off</code> to this output stream. * * @param b the data. * @param off the start offset in the data. * @param len the number of bytes to write. * @exception IOException if an I/O error occurs. * @since JCE1.2 */ public void write(byte b[], int off, int len) throws IOException { obuffer = cipher.update(b, off, len); if (obuffer != null) { output.write(obuffer); obuffer = null; } } /** * Flushes this output stream by forcing any buffered output bytes * that have already been processed by the encapsulated cipher object * to be written out. * * <p>Any bytes buffered by the encapsulated cipher * and waiting to be processed by it will not be written out. For example, * if the encapsulated cipher is a block cipher, and the total number of * bytes written using one of the <code>write</code> methods is less than * the cipher's block size, no bytes will be written out. * * @exception IOException if an I/O error occurs. * @since JCE1.2 */ public void flush() throws IOException { if (obuffer != null) { output.write(obuffer); obuffer = null; } output.flush(); } /** * Closes this output stream and releases any system resources * associated with this stream. * <p> * This method invokes the <code>doFinal</code> method of the encapsulated * cipher object, which causes any bytes buffered by the encapsulated * cipher to be processed. The result is written out by calling the * <code>flush</code> method of this output stream. * <p> * This method resets the encapsulated cipher object to its initial state * and calls the <code>close</code> method of the underlying output * stream. * * @exception IOException if an I/O error occurs. * @since JCE1.2 */ public void close() throws IOException { if (closed) { return; } closed = true; try { obuffer = cipher.doFinal(); } catch (IllegalBlockSizeException | BadPaddingException e) { obuffer = null; } try { flush(); } catch (IOException ignored) {} out.close(); } }<|fim▁end|>
* by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT
<|file_name|>ops.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains convenience wrappers for typical Neural Network TensorFlow layers. Additionally it maintains a collection with update_ops that need to be updated after the ops have been computed, for exmaple to update moving means and moving variances of batch_norm. Ops that have different behavior during training or eval have an is_training parameter. Additionally Ops that contain variables.variable have a trainable parameter, which control if the ops variables are trainable or not. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.python.training import moving_averages from inception.slim import losses from inception.slim import scopes from inception.slim import variables # Used to keep the update ops done by batch_norm. UPDATE_OPS_COLLECTION = '_update_ops_' @scopes.add_arg_scope def batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, moving_vars='moving_vars', activation=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): """Adds a Batch Normalization layer. Args: inputs: a tensor of size [batch_size, height, width, channels] or [batch_size, channels]. decay: decay for the moving average. center: If True, subtract beta. If False, beta is not created and ignored. scale: If True, multiply by gamma. If False, gamma is not used. When the next layer is linear (also e.g. ReLU), this can be disabled since the scaling can be done by the next layer. epsilon: small float added to variance to avoid dividing by zero. moving_vars: collection to store the moving_mean and moving_variance. activation: activation function. is_training: whether or not the model is in training mode. trainable: whether or not the variables should be trainable or not. restore: whether or not the variables should be marked for restore. scope: Optional scope for variable_scope. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. Returns: a tensor representing the output of the operation. """ inputs_shape = inputs.get_shape() with tf.variable_scope(scope, 'BatchNorm', [inputs], reuse=reuse): axis = list(range(len(inputs_shape) - 1)) params_shape = inputs_shape[-1:] # Allocate parameters for the beta and gamma of the normalization. beta, gamma = None, None if center: beta = variables.variable('beta', params_shape, initializer=tf.zeros_initializer(), trainable=trainable, restore=restore) if scale: gamma = variables.variable('gamma', params_shape, initializer=tf.ones_initializer(), trainable=trainable, restore=restore) # Create moving_mean and moving_variance add them to # GraphKeys.MOVING_AVERAGE_VARIABLES collections. moving_collections = [moving_vars, tf.GraphKeys.MOVING_AVERAGE_VARIABLES] moving_mean = variables.variable('moving_mean', params_shape, initializer=tf.zeros_initializer(), trainable=False, restore=restore,<|fim▁hole|> moving_variance = variables.variable('moving_variance', params_shape, initializer=tf.ones_initializer(), trainable=False, restore=restore, collections=moving_collections) if is_training: # Calculate the moments based on the individual batch. mean, variance = tf.nn.moments(inputs, axis) update_moving_mean = moving_averages.assign_moving_average( moving_mean, mean, decay) tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_mean) update_moving_variance = moving_averages.assign_moving_average( moving_variance, variance, decay) tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_variance) else: # Just use the moving_mean and moving_variance. mean = moving_mean variance = moving_variance # Normalize the activations. outputs = tf.nn.batch_normalization( inputs, mean, variance, beta, gamma, epsilon) outputs.set_shape(inputs.get_shape()) if activation: outputs = activation(outputs) return outputs def _two_element_tuple(int_or_tuple): """Converts `int_or_tuple` to height, width. Several of the functions that follow accept arguments as either a tuple of 2 integers or a single integer. A single integer indicates that the 2 values of the tuple are the same. This functions normalizes the input value by always returning a tuple. Args: int_or_tuple: A list of 2 ints, a single int or a tf.TensorShape. Returns: A tuple with 2 values. Raises: ValueError: If `int_or_tuple` it not well formed. """ if isinstance(int_or_tuple, (list, tuple)): if len(int_or_tuple) != 2: raise ValueError('Must be a list with 2 elements: %s' % int_or_tuple) return int(int_or_tuple[0]), int(int_or_tuple[1]) if isinstance(int_or_tuple, int): return int(int_or_tuple), int(int_or_tuple) if isinstance(int_or_tuple, tf.TensorShape): if len(int_or_tuple) == 2: return int_or_tuple[0], int_or_tuple[1] raise ValueError('Must be an int, a list with 2 elements or a TensorShape of ' 'length 2') @scopes.add_arg_scope def conv2d(inputs, num_filters_out, kernel_size, stride=1, padding='SAME', activation=tf.nn.relu, stddev=0.01, bias=0.0, weight_decay=0, batch_norm_params=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): """Adds a 2D convolution followed by an optional batch_norm layer. conv2d creates a variable called 'weights', representing the convolutional kernel, that is convolved with the input. If `batch_norm_params` is None, a second variable called 'biases' is added to the result of the convolution operation. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_filters_out: the number of output filters. kernel_size: a list of length 2: [kernel_height, kernel_width] of of the filters. Can be an int if both values are the same. stride: a list of length 2: [stride_height, stride_width]. Can be an int if both strides are the same. Note that presently both strides must have the same value. padding: one of 'VALID' or 'SAME'. activation: activation function. stddev: standard deviation of the truncated guassian weight distribution. bias: the initial value of the biases. weight_decay: the weight decay. batch_norm_params: parameters for the batch_norm. If is None don't use it. is_training: whether or not the model is in training mode. trainable: whether or not the variables should be trainable or not. restore: whether or not the variables should be marked for restore. scope: Optional scope for variable_scope. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. Returns: a tensor representing the output of the operation. """ with tf.variable_scope(scope, 'Conv', [inputs], reuse=reuse): kernel_h, kernel_w = _two_element_tuple(kernel_size) stride_h, stride_w = _two_element_tuple(stride) num_filters_in = inputs.get_shape()[-1] weights_shape = [kernel_h, kernel_w, num_filters_in, num_filters_out] weights_initializer = tf.truncated_normal_initializer(stddev=stddev) l2_regularizer = None if weight_decay and weight_decay > 0: l2_regularizer = losses.l2_regularizer(weight_decay) weights = variables.variable('weights', shape=weights_shape, initializer=weights_initializer, regularizer=l2_regularizer, trainable=trainable, restore=restore) conv = tf.nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1], padding=padding) if batch_norm_params is not None: with scopes.arg_scope([batch_norm], is_training=is_training, trainable=trainable, restore=restore): outputs = batch_norm(conv, **batch_norm_params) else: bias_shape = [num_filters_out,] bias_initializer = tf.constant_initializer(bias) biases = variables.variable('biases', shape=bias_shape, initializer=bias_initializer, trainable=trainable, restore=restore) outputs = tf.nn.bias_add(conv, biases) if activation: outputs = activation(outputs) return outputs @scopes.add_arg_scope def fc(inputs, num_units_out, activation=tf.nn.relu, stddev=0.01, bias=0.0, weight_decay=0, batch_norm_params=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): """Adds a fully connected layer followed by an optional batch_norm layer. FC creates a variable called 'weights', representing the fully connected weight matrix, that is multiplied by the input. If `batch_norm` is None, a second variable called 'biases' is added to the result of the initial vector-matrix multiplication. Args: inputs: a [B x N] tensor where B is the batch size and N is the number of input units in the layer. num_units_out: the number of output units in the layer. activation: activation function. stddev: the standard deviation for the weights. bias: the initial value of the biases. weight_decay: the weight decay. batch_norm_params: parameters for the batch_norm. If is None don't use it. is_training: whether or not the model is in training mode. trainable: whether or not the variables should be trainable or not. restore: whether or not the variables should be marked for restore. scope: Optional scope for variable_scope. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. Returns: the tensor variable representing the result of the series of operations. """ with tf.variable_scope(scope, 'FC', [inputs], reuse=reuse): num_units_in = inputs.get_shape()[1] weights_shape = [num_units_in, num_units_out] weights_initializer = tf.truncated_normal_initializer(stddev=stddev) l2_regularizer = None if weight_decay and weight_decay > 0: l2_regularizer = losses.l2_regularizer(weight_decay) weights = variables.variable('weights', shape=weights_shape, initializer=weights_initializer, regularizer=l2_regularizer, trainable=trainable, restore=restore) if batch_norm_params is not None: outputs = tf.matmul(inputs, weights) with scopes.arg_scope([batch_norm], is_training=is_training, trainable=trainable, restore=restore): outputs = batch_norm(outputs, **batch_norm_params) else: bias_shape = [num_units_out,] bias_initializer = tf.constant_initializer(bias) biases = variables.variable('biases', shape=bias_shape, initializer=bias_initializer, trainable=trainable, restore=restore) outputs = tf.nn.xw_plus_b(inputs, weights, biases) if activation: outputs = activation(outputs) return outputs def one_hot_encoding(labels, num_classes, scope=None): """Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels. """ with tf.name_scope(scope, 'OneHotEncoding', [labels]): batch_size = labels.get_shape()[0] indices = tf.expand_dims(tf.range(0, batch_size), 1) labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype) concated = tf.concat(axis=1, values=[indices, labels]) onehot_labels = tf.sparse_to_dense( concated, tf.stack([batch_size, num_classes]), 1.0, 0.0) onehot_labels.set_shape([batch_size, num_classes]) return onehot_labels @scopes.add_arg_scope def max_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None): """Adds a Max Pooling layer. It is assumed by the wrapper that the pooling is only done per image and not in depth or batch. Args: inputs: a tensor of size [batch_size, height, width, depth]. kernel_size: a list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same. stride: a list of length 2: [stride_height, stride_width]. Can be an int if both strides are the same. Note that presently both strides must have the same value. padding: the padding method, either 'VALID' or 'SAME'. scope: Optional scope for name_scope. Returns: a tensor representing the results of the pooling operation. Raises: ValueError: if 'kernel_size' is not a 2-D list """ with tf.name_scope(scope, 'MaxPool', [inputs]): kernel_h, kernel_w = _two_element_tuple(kernel_size) stride_h, stride_w = _two_element_tuple(stride) return tf.nn.max_pool(inputs, ksize=[1, kernel_h, kernel_w, 1], strides=[1, stride_h, stride_w, 1], padding=padding) @scopes.add_arg_scope def avg_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None): """Adds a Avg Pooling layer. It is assumed by the wrapper that the pooling is only done per image and not in depth or batch. Args: inputs: a tensor of size [batch_size, height, width, depth]. kernel_size: a list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same. stride: a list of length 2: [stride_height, stride_width]. Can be an int if both strides are the same. Note that presently both strides must have the same value. padding: the padding method, either 'VALID' or 'SAME'. scope: Optional scope for name_scope. Returns: a tensor representing the results of the pooling operation. """ with tf.name_scope(scope, 'AvgPool', [inputs]): kernel_h, kernel_w = _two_element_tuple(kernel_size) stride_h, stride_w = _two_element_tuple(stride) return tf.nn.avg_pool(inputs, ksize=[1, kernel_h, kernel_w, 1], strides=[1, stride_h, stride_w, 1], padding=padding) @scopes.add_arg_scope def dropout(inputs, keep_prob=0.5, is_training=True, scope=None): """Returns a dropout layer applied to the input. Args: inputs: the tensor to pass to the Dropout layer. keep_prob: the probability of keeping each input unit. is_training: whether or not the model is in training mode. If so, dropout is applied and values scaled. Otherwise, inputs is returned. scope: Optional scope for name_scope. Returns: a tensor representing the output of the operation. """ if is_training and keep_prob > 0: with tf.name_scope(scope, 'Dropout', [inputs]): return tf.nn.dropout(inputs, keep_prob) else: return inputs def flatten(inputs, scope=None): """Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raises: ValueError: if inputs.shape is wrong. """ if len(inputs.get_shape()) < 2: raise ValueError('Inputs must be have a least 2 dimensions') dims = inputs.get_shape()[1:] k = dims.num_elements() with tf.name_scope(scope, 'Flatten', [inputs]): return tf.reshape(inputs, [-1, k]) def repeat_op(repetitions, inputs, op, *args, **kwargs): """Build a sequential Tower starting from inputs by using an op repeatedly. It creates new scopes for each operation by increasing the counter. Example: given repeat_op(3, _, ops.conv2d, 64, [3, 3], scope='conv1') it will repeat the given op under the following variable_scopes: conv1/Conv conv1/Conv_1 conv1/Conv_2 Args: repetitions: number or repetitions. inputs: a tensor of size [batch_size, height, width, channels]. op: an operation. *args: args for the op. **kwargs: kwargs for the op. Returns: a tensor result of applying the operation op, num times. Raises: ValueError: if the op is unknown or wrong. """ scope = kwargs.pop('scope', None) with tf.variable_scope(scope, 'RepeatOp', [inputs]): tower = inputs for _ in range(repetitions): tower = op(tower, *args, **kwargs) return tower<|fim▁end|>
collections=moving_collections)
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::F9R1 { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct FB0R { bits: bool, } impl FB0R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB1R { bits: bool, } impl FB1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB2R { bits: bool, } impl FB2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB3R { bits: bool, } impl FB3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB4R { bits: bool, } impl FB4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB5R { bits: bool, } impl FB5R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB6R { bits: bool, } impl FB6R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB7R { bits: bool, } impl FB7R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB8R { bits: bool, } impl FB8R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB9R { bits: bool, } impl FB9R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB10R { bits: bool, } impl FB10R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB11R { bits: bool, } impl FB11R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB12R { bits: bool, } impl FB12R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB13R { bits: bool, } impl FB13R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB14R { bits: bool, } impl FB14R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB15R { bits: bool, } impl FB15R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB16R { bits: bool, } impl FB16R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB17R { bits: bool, } impl FB17R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB18R { bits: bool, } impl FB18R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB19R { bits: bool, } impl FB19R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB20R { bits: bool, } impl FB20R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB21R { bits: bool, } impl FB21R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB22R { bits: bool, } impl FB22R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB23R { bits: bool, } impl FB23R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB24R { bits: bool, } impl FB24R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB25R { bits: bool, } impl FB25R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB26R { bits: bool, } impl FB26R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB27R { bits: bool, } impl FB27R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB28R { bits: bool, } impl FB28R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB29R { bits: bool, } impl FB29R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB30R { bits: bool, } impl FB30R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct FB31R { bits: bool, } impl FB31R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _FB0W<'a> { w: &'a mut W, } impl<'a> _FB0W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB1W<'a> { w: &'a mut W, } impl<'a> _FB1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB2W<'a> { w: &'a mut W, } impl<'a> _FB2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB3W<'a> { w: &'a mut W, } impl<'a> _FB3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB4W<'a> { w: &'a mut W, } impl<'a> _FB4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB5W<'a> { w: &'a mut W, } impl<'a> _FB5W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB6W<'a> { w: &'a mut W, } impl<'a> _FB6W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB7W<'a> { w: &'a mut W, } impl<'a> _FB7W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB8W<'a> { w: &'a mut W, } impl<'a> _FB8W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB9W<'a> { w: &'a mut W, } impl<'a> _FB9W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB10W<'a> { w: &'a mut W, } impl<'a> _FB10W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB11W<'a> { w: &'a mut W, } impl<'a> _FB11W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB12W<'a> { w: &'a mut W, } impl<'a> _FB12W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB13W<'a> { w: &'a mut W, } impl<'a> _FB13W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 13; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB14W<'a> { w: &'a mut W, } impl<'a> _FB14W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB15W<'a> { w: &'a mut W, } impl<'a> _FB15W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB16W<'a> { w: &'a mut W, } impl<'a> _FB16W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB17W<'a> { w: &'a mut W, } impl<'a> _FB17W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB18W<'a> { w: &'a mut W, } impl<'a> _FB18W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB19W<'a> { w: &'a mut W, } impl<'a> _FB19W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB20W<'a> { w: &'a mut W, } impl<'a> _FB20W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB21W<'a> { w: &'a mut W, } impl<'a> _FB21W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 21; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB22W<'a> { w: &'a mut W, } impl<'a> _FB22W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB23W<'a> { w: &'a mut W, } impl<'a> _FB23W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB24W<'a> { w: &'a mut W, } impl<'a> _FB24W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB25W<'a> { w: &'a mut W, } impl<'a> _FB25W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB26W<'a> { w: &'a mut W, } impl<'a> _FB26W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 26; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB27W<'a> { w: &'a mut W, } impl<'a> _FB27W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 27; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB28W<'a> { w: &'a mut W, } impl<'a> _FB28W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB29W<'a> { w: &'a mut W, } impl<'a> _FB29W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 29; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB30W<'a> { w: &'a mut W, } impl<'a> _FB30W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FB31W<'a> { w: &'a mut W, } impl<'a> _FB31W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 31; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Filter bits"] #[inline(always)] pub fn fb0(&self) -> FB0R { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB0R { bits } } #[doc = "Bit 1 - Filter bits"] #[inline(always)] pub fn fb1(&self) -> FB1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB1R { bits } } #[doc = "Bit 2 - Filter bits"] #[inline(always)] pub fn fb2(&self) -> FB2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB2R { bits } } #[doc = "Bit 3 - Filter bits"] #[inline(always)] pub fn fb3(&self) -> FB3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB3R { bits } } #[doc = "Bit 4 - Filter bits"] #[inline(always)] pub fn fb4(&self) -> FB4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB4R { bits } } #[doc = "Bit 5 - Filter bits"] #[inline(always)] pub fn fb5(&self) -> FB5R { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB5R { bits } } #[doc = "Bit 6 - Filter bits"] #[inline(always)] pub fn fb6(&self) -> FB6R { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB6R { bits } } #[doc = "Bit 7 - Filter bits"] #[inline(always)] pub fn fb7(&self) -> FB7R { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB7R { bits } } #[doc = "Bit 8 - Filter bits"] #[inline(always)] pub fn fb8(&self) -> FB8R { let bits = { const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB8R { bits } } #[doc = "Bit 9 - Filter bits"] #[inline(always)] pub fn fb9(&self) -> FB9R { let bits = { const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB9R { bits } } #[doc = "Bit 10 - Filter bits"] #[inline(always)] pub fn fb10(&self) -> FB10R { let bits = { const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB10R { bits } } #[doc = "Bit 11 - Filter bits"] #[inline(always)] pub fn fb11(&self) -> FB11R { let bits = { const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB11R { bits } } #[doc = "Bit 12 - Filter bits"] #[inline(always)] pub fn fb12(&self) -> FB12R { let bits = { const MASK: bool = true; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB12R { bits } } #[doc = "Bit 13 - Filter bits"] #[inline(always)] pub fn fb13(&self) -> FB13R { let bits = { const MASK: bool = true; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB13R { bits } } #[doc = "Bit 14 - Filter bits"] #[inline(always)] pub fn fb14(&self) -> FB14R { let bits = { const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB14R { bits } } #[doc = "Bit 15 - Filter bits"] #[inline(always)] pub fn fb15(&self) -> FB15R { let bits = { const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB15R { bits } } #[doc = "Bit 16 - Filter bits"] #[inline(always)] pub fn fb16(&self) -> FB16R { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB16R { bits } } #[doc = "Bit 17 - Filter bits"] #[inline(always)] pub fn fb17(&self) -> FB17R { let bits = { const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB17R { bits } } #[doc = "Bit 18 - Filter bits"] #[inline(always)] pub fn fb18(&self) -> FB18R { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB18R { bits } } #[doc = "Bit 19 - Filter bits"] #[inline(always)] pub fn fb19(&self) -> FB19R { let bits = { const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB19R { bits } } #[doc = "Bit 20 - Filter bits"] #[inline(always)] pub fn fb20(&self) -> FB20R { let bits = { const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB20R { bits } } #[doc = "Bit 21 - Filter bits"] #[inline(always)] pub fn fb21(&self) -> FB21R { let bits = { const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB21R { bits } } #[doc = "Bit 22 - Filter bits"] #[inline(always)] pub fn fb22(&self) -> FB22R { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB22R { bits } } #[doc = "Bit 23 - Filter bits"] #[inline(always)] pub fn fb23(&self) -> FB23R { let bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB23R { bits } } #[doc = "Bit 24 - Filter bits"] #[inline(always)] pub fn fb24(&self) -> FB24R { let bits = { const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB24R { bits } } #[doc = "Bit 25 - Filter bits"] #[inline(always)] pub fn fb25(&self) -> FB25R { let bits = { const MASK: bool = true; const OFFSET: u8 = 25; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB25R { bits } } #[doc = "Bit 26 - Filter bits"] #[inline(always)] pub fn fb26(&self) -> FB26R { let bits = { const MASK: bool = true; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB26R { bits } } #[doc = "Bit 27 - Filter bits"] #[inline(always)] pub fn fb27(&self) -> FB27R { let bits = { const MASK: bool = true; const OFFSET: u8 = 27; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB27R { bits } } #[doc = "Bit 28 - Filter bits"] #[inline(always)] pub fn fb28(&self) -> FB28R { let bits = { const MASK: bool = true; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB28R { bits } } #[doc = "Bit 29 - Filter bits"] #[inline(always)] pub fn fb29(&self) -> FB29R { let bits = { const MASK: bool = true; const OFFSET: u8 = 29; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB29R { bits } } #[doc = "Bit 30 - Filter bits"] #[inline(always)] pub fn fb30(&self) -> FB30R { let bits = { const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB30R { bits } } #[doc = "Bit 31 - Filter bits"] #[inline(always)] pub fn fb31(&self) -> FB31R { let bits = { const MASK: bool = true; const OFFSET: u8 = 31; ((self.bits >> OFFSET) & MASK as u32) != 0 }; FB31R { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline(always)] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Filter bits"] #[inline(always)] pub fn fb0(&mut self) -> _FB0W { _FB0W { w: self } } #[doc = "Bit 1 - Filter bits"] #[inline(always)] pub fn fb1(&mut self) -> _FB1W { _FB1W { w: self } } #[doc = "Bit 2 - Filter bits"] #[inline(always)] pub fn fb2(&mut self) -> _FB2W { _FB2W { w: self } } #[doc = "Bit 3 - Filter bits"] #[inline(always)] pub fn fb3(&mut self) -> _FB3W { _FB3W { w: self } } #[doc = "Bit 4 - Filter bits"] #[inline(always)] pub fn fb4(&mut self) -> _FB4W { _FB4W { w: self } } #[doc = "Bit 5 - Filter bits"] #[inline(always)] pub fn fb5(&mut self) -> _FB5W { _FB5W { w: self } } #[doc = "Bit 6 - Filter bits"] #[inline(always)] pub fn fb6(&mut self) -> _FB6W { _FB6W { w: self } } #[doc = "Bit 7 - Filter bits"] #[inline(always)] pub fn fb7(&mut self) -> _FB7W { _FB7W { w: self } } #[doc = "Bit 8 - Filter bits"] #[inline(always)] pub fn fb8(&mut self) -> _FB8W { _FB8W { w: self } } #[doc = "Bit 9 - Filter bits"] #[inline(always)] pub fn fb9(&mut self) -> _FB9W { _FB9W { w: self } } #[doc = "Bit 10 - Filter bits"] #[inline(always)] pub fn fb10(&mut self) -> _FB10W { _FB10W { w: self } }<|fim▁hole|> pub fn fb11(&mut self) -> _FB11W { _FB11W { w: self } } #[doc = "Bit 12 - Filter bits"] #[inline(always)] pub fn fb12(&mut self) -> _FB12W { _FB12W { w: self } } #[doc = "Bit 13 - Filter bits"] #[inline(always)] pub fn fb13(&mut self) -> _FB13W { _FB13W { w: self } } #[doc = "Bit 14 - Filter bits"] #[inline(always)] pub fn fb14(&mut self) -> _FB14W { _FB14W { w: self } } #[doc = "Bit 15 - Filter bits"] #[inline(always)] pub fn fb15(&mut self) -> _FB15W { _FB15W { w: self } } #[doc = "Bit 16 - Filter bits"] #[inline(always)] pub fn fb16(&mut self) -> _FB16W { _FB16W { w: self } } #[doc = "Bit 17 - Filter bits"] #[inline(always)] pub fn fb17(&mut self) -> _FB17W { _FB17W { w: self } } #[doc = "Bit 18 - Filter bits"] #[inline(always)] pub fn fb18(&mut self) -> _FB18W { _FB18W { w: self } } #[doc = "Bit 19 - Filter bits"] #[inline(always)] pub fn fb19(&mut self) -> _FB19W { _FB19W { w: self } } #[doc = "Bit 20 - Filter bits"] #[inline(always)] pub fn fb20(&mut self) -> _FB20W { _FB20W { w: self } } #[doc = "Bit 21 - Filter bits"] #[inline(always)] pub fn fb21(&mut self) -> _FB21W { _FB21W { w: self } } #[doc = "Bit 22 - Filter bits"] #[inline(always)] pub fn fb22(&mut self) -> _FB22W { _FB22W { w: self } } #[doc = "Bit 23 - Filter bits"] #[inline(always)] pub fn fb23(&mut self) -> _FB23W { _FB23W { w: self } } #[doc = "Bit 24 - Filter bits"] #[inline(always)] pub fn fb24(&mut self) -> _FB24W { _FB24W { w: self } } #[doc = "Bit 25 - Filter bits"] #[inline(always)] pub fn fb25(&mut self) -> _FB25W { _FB25W { w: self } } #[doc = "Bit 26 - Filter bits"] #[inline(always)] pub fn fb26(&mut self) -> _FB26W { _FB26W { w: self } } #[doc = "Bit 27 - Filter bits"] #[inline(always)] pub fn fb27(&mut self) -> _FB27W { _FB27W { w: self } } #[doc = "Bit 28 - Filter bits"] #[inline(always)] pub fn fb28(&mut self) -> _FB28W { _FB28W { w: self } } #[doc = "Bit 29 - Filter bits"] #[inline(always)] pub fn fb29(&mut self) -> _FB29W { _FB29W { w: self } } #[doc = "Bit 30 - Filter bits"] #[inline(always)] pub fn fb30(&mut self) -> _FB30W { _FB30W { w: self } } #[doc = "Bit 31 - Filter bits"] #[inline(always)] pub fn fb31(&mut self) -> _FB31W { _FB31W { w: self } } }<|fim▁end|>
#[doc = "Bit 11 - Filter bits"] #[inline(always)]
<|file_name|>PreventListener.java<|end_file_name|><|fim▁begin|>/* * This file is part of FlexibleLogin * * The MIT License (MIT) * * Copyright (c) 2015-2018 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy<|fim▁hole|> * 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. */ package com.github.games647.flexiblelogin.listener.prevent; import com.flowpowered.math.vector.Vector3i; import com.github.games647.flexiblelogin.FlexibleLogin; import com.github.games647.flexiblelogin.PomData; import com.github.games647.flexiblelogin.config.Settings; import com.google.inject.Inject; import java.util.List; import java.util.Optional; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.InteractEntityEvent; import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.filter.type.Exclude; import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent.NumberPress; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; import org.spongepowered.api.event.item.inventory.InteractItemEvent; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.event.message.MessageChannelEvent; public class PreventListener extends AbstractPreventListener { private final CommandManager commandManager; @Inject PreventListener(FlexibleLogin plugin, Settings settings, CommandManager commandManager) { super(plugin, settings); this.commandManager = commandManager; } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerMove(MoveEntityEvent playerMoveEvent, @First Player player) { if (playerMoveEvent instanceof MoveEntityEvent.Teleport) { return; } Vector3i oldLocation = playerMoveEvent.getFromTransform().getPosition().toInt(); Vector3i newLocation = playerMoveEvent.getToTransform().getPosition().toInt(); if (oldLocation.getX() != newLocation.getX() || oldLocation.getZ() != newLocation.getZ()) { checkLoginStatus(playerMoveEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onChat(MessageChannelEvent.Chat chatEvent, @First Player player) { checkLoginStatus(chatEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onCommand(SendCommandEvent commandEvent, @First Player player) { String command = commandEvent.getCommand(); Optional<? extends CommandMapping> commandOpt = commandManager.get(command); if (commandOpt.isPresent()) { CommandMapping mapping = commandOpt.get(); command = mapping.getPrimaryAlias(); //do not blacklist our own commands if (commandManager.getOwner(mapping) .map(pc -> pc.getId().equals(PomData.ARTIFACT_ID)) .orElse(false)) { return; } } commandEvent.setResult(CommandResult.empty()); if (settings.getGeneral().isCommandOnlyProtection()) { List<String> protectedCommands = settings.getGeneral().getProtectedCommands(); if (protectedCommands.contains(command) && !plugin.getDatabase().isLoggedIn(player)) { player.sendMessage(settings.getText().getProtectedCommand()); commandEvent.setCancelled(true); } } else { checkLoginStatus(commandEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemDrop(DropItemEvent dropItemEvent, @First Player player) { checkLoginStatus(dropItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemPickup(ChangeInventoryEvent.Pickup pickupItemEvent, @Root Player player) { checkLoginStatus(pickupItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemConsume(UseItemStackEvent.Start itemConsumeEvent, @First Player player) { checkLoginStatus(itemConsumeEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemInteract(InteractItemEvent interactItemEvent, @First Player player) { checkLoginStatus(interactItemEvent, player); } // Ignore number press events, because Sponge before this commit // https://github.com/SpongePowered/SpongeForge/commit/f0605fb0bd62ca2f958425378776608c41f16cca // has a duplicate bug. Using this exclude we can ignore it, but still cancel the movement of the item // it appears to be fixed using SpongeForge 4005 (fixed) and 4004 with this change @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryChange(ChangeInventoryEvent changeInventoryEvent, @First Player player) { checkLoginStatus(changeInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryInteract(InteractInventoryEvent interactInventoryEvent, @First Player player) { checkLoginStatus(interactInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryClick(ClickInventoryEvent clickInventoryEvent, @First Player player) { checkLoginStatus(clickInventoryEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onBlockInteract(InteractBlockEvent interactBlockEvent, @First Player player) { checkLoginStatus(interactBlockEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractEntity(InteractEntityEvent interactEntityEvent, @First Player player) { checkLoginStatus(interactEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerDamage(DamageEntityEvent damageEntityEvent, @First Player player) { //player is damage source checkLoginStatus(damageEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onDamagePlayer(DamageEntityEvent damageEntityEvent, @Getter("getTargetEntity") Player player) { //player is damage target checkLoginStatus(damageEntityEvent, player); } }<|fim▁end|>
* 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
<|file_name|>labler.js<|end_file_name|><|fim▁begin|>const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); <|fim▁hole|> try { const labels = await recognition.getLabels(file.metadata.mediaLink); const metadata = { metadata: { labels: JSON.stringify(labels) } }; console.log(`Set metadata for file ${file.name}`); await storage.setMetadata(file, metadata); } catch (ex) { console.warn("Failed to set metadata for file ${file.name}", ex); } } } async function main(bucketName) { try { await labelPictures(bucketName); } catch (error) { console.error(error); } } if (process.argv.length < 3) { throw new Error("Please specify a bucket name"); } main(process.argv[2]);<|fim▁end|>
for (const file of fileNames) { console.log(`Retrieve labels for file ${file.name}`);
<|file_name|>pic.py<|end_file_name|><|fim▁begin|># _*_ coding: utf-8 _*_ # filename: pic.py import csv import numpy import matplotlib.pyplot as plt # 读取 house.csv 文件中价格和面积列 price, size = numpy.loadtxt('house.csv', delimiter='|', usecols=(1, 2), unpack=True) print price print size plt.figure() plt.subplot(211) # plt.title("price") plt.title("/ 10000RMB") plt.hist(price, bins=20) <|fim▁hole|> plt.figure(2) plt.title("price") plt.plot(price) plt.show() # 求价格和面积的平均值 price_mean = numpy.mean(price) size_mean = numpy.mean(size) # 求价格和面积的方差 price_var = numpy.var(price) size_var = numpy.var(size) print "价格的方差为:", price_var print "面积的方差为:", size_var<|fim▁end|>
plt.subplot(212) # plt.title("area") plt.xlabel("/ m**2") plt.hist(size, bins=20)
<|file_name|>strategy_test.go<|end_file_name|><|fim▁begin|>/* Copyright 2015 The Kubernetes Authors. <|fim▁hole|>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. */ package replicationcontroller import ( "strings" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/kubernetes/pkg/api/legacyscheme" apitesting "k8s.io/kubernetes/pkg/api/testing" api "k8s.io/kubernetes/pkg/apis/core" // install all api groups for testing _ "k8s.io/kubernetes/pkg/api/testapi" ) func TestControllerStrategy(t *testing.T) { ctx := genericapirequest.NewDefaultContext() if !Strategy.NamespaceScoped() { t.Errorf("ReplicationController must be namespace scoped") } if Strategy.AllowCreateOnUpdate() { t.Errorf("ReplicationController should not allow create on update") } validSelector := map[string]string{"a": "b"} validPodTemplate := api.PodTemplate{ Template: api.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: validSelector, }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}}, }, }, } rc := &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, Spec: api.ReplicationControllerSpec{ Selector: validSelector, Template: &validPodTemplate.Template, }, Status: api.ReplicationControllerStatus{ Replicas: 1, ObservedGeneration: int64(10), }, } Strategy.PrepareForCreate(ctx, rc) if rc.Status.Replicas != 0 { t.Error("ReplicationController should not allow setting status.replicas on create") } if rc.Status.ObservedGeneration != int64(0) { t.Error("ReplicationController should not allow setting status.observedGeneration on create") } errs := Strategy.Validate(ctx, rc) if len(errs) != 0 { t.Errorf("Unexpected error validating %v", errs) } invalidRc := &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{Name: "bar", ResourceVersion: "4"}, } Strategy.PrepareForUpdate(ctx, invalidRc, rc) errs = Strategy.ValidateUpdate(ctx, invalidRc, rc) if len(errs) == 0 { t.Errorf("Expected a validation error") } if invalidRc.ResourceVersion != "4" { t.Errorf("Incoming resource version on update should not be mutated") } } func TestControllerStatusStrategy(t *testing.T) { ctx := genericapirequest.NewDefaultContext() if !StatusStrategy.NamespaceScoped() { t.Errorf("ReplicationController must be namespace scoped") } if StatusStrategy.AllowCreateOnUpdate() { t.Errorf("ReplicationController should not allow create on update") } validSelector := map[string]string{"a": "b"} validPodTemplate := api.PodTemplate{ Template: api.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: validSelector, }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, }, }, } oldController := &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault, ResourceVersion: "10"}, Spec: api.ReplicationControllerSpec{ Replicas: 3, Selector: validSelector, Template: &validPodTemplate.Template, }, Status: api.ReplicationControllerStatus{ Replicas: 1, ObservedGeneration: int64(10), }, } newController := &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault, ResourceVersion: "9"}, Spec: api.ReplicationControllerSpec{ Replicas: 1, Selector: validSelector, Template: &validPodTemplate.Template, }, Status: api.ReplicationControllerStatus{ Replicas: 3, ObservedGeneration: int64(11), }, } StatusStrategy.PrepareForUpdate(ctx, newController, oldController) if newController.Status.Replicas != 3 { t.Errorf("Replication controller status updates should allow change of replicas: %v", newController.Status.Replicas) } if newController.Spec.Replicas != 3 { t.Errorf("PrepareForUpdate should have preferred spec") } errs := StatusStrategy.ValidateUpdate(ctx, newController, oldController) if len(errs) != 0 { t.Errorf("Unexpected error %v", errs) } } func TestSelectableFieldLabelConversions(t *testing.T) { apitesting.TestSelectableFieldLabelConversionsOfKind(t, legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion.String(), "ReplicationController", ControllerToSelectableFields(&api.ReplicationController{}), nil, ) } func TestValidateUpdate(t *testing.T) { ctx := genericapirequest.NewDefaultContext() validSelector := map[string]string{"a": "b"} validPodTemplate := api.PodTemplate{ Template: api.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: validSelector, }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, }, }, } oldController := &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault, ResourceVersion: "10", Annotations: make(map[string]string)}, Spec: api.ReplicationControllerSpec{ Replicas: 3, Selector: validSelector, Template: &validPodTemplate.Template, }, Status: api.ReplicationControllerStatus{ Replicas: 1, ObservedGeneration: int64(10), }, } // Conversion sets this annotation oldController.Annotations[api.NonConvertibleAnnotationPrefix+"/"+"spec.selector"] = "no way" // Deep-copy so we won't mutate both selectors. newController := oldController.DeepCopy() // Irrelevant (to the selector) update for the replication controller. newController.Spec.Replicas = 5 // If they didn't try to update the selector then we should not return any error. errs := Strategy.ValidateUpdate(ctx, newController, oldController) if len(errs) > 0 { t.Fatalf("unexpected errors: %v", errs) } // Update the selector - validation should return an error. newController.Spec.Selector["shiny"] = "newlabel" newController.Spec.Template.Labels["shiny"] = "newlabel" errs = Strategy.ValidateUpdate(ctx, newController, oldController) for _, err := range errs { t.Logf("%#v\n", err) } if len(errs) != 1 { t.Fatalf("expected a validation error") } if !strings.Contains(errs[0].Error(), "selector") { t.Fatalf("expected error related to the selector") } }<|fim▁end|>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
<|file_name|>index.js<|end_file_name|><|fim▁begin|>define(['underscore','backbone','aura'], function(_,Backbone,Aura) { console.log('loading index.js') var app=Aura({debug: { enable: true}}); app.components.addSource('aura', '../node_webkit/auraext'); app.components.addSource('kse', '../kse/aura_components'); <|fim▁hole|> .use('../node_webkit/auraext/aura-rangy') .use('../node_webkit/auraext/aura-toc') .start({ widgets: 'body' }).then(function() { console.log('Aura Started'); }) });<|fim▁end|>
app.use('../node_webkit/auraext/aura-backbone') .use('../node_webkit/auraext/aura-yadb') .use('../node_webkit/auraext/aura-yase')
<|file_name|>controls.ts<|end_file_name|><|fim▁begin|>// Copyright 2016 David Li, Michael Mauer, Andy Jiang // This file is part of Tell Me to Survive. // Tell Me to Survive is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Tell Me to Survive 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with Tell Me to Survive. If not, see <http://www.gnu.org/licenses/>. import PubSub = require("pubsub"); import {EditorContext, MAIN} from "model/editorcontext"; interface ControlsController extends _mithril.MithrilController { } export const Component: _mithril.MithrilComponent<ControlsController> = <any> { controller: function(): ControlsController { return {}; }, view: function(controller: ControlsController, args: { executing: _mithril.MithrilProperty<boolean>, doneExecuting: _mithril.MithrilProperty<boolean>, paused: _mithril.MithrilProperty<boolean>, speed: _mithril.MithrilProperty<number>, valid: boolean, memoryUsage: EditorContext, onrun?: () => void, onruninvalid?: () => void, onrunmemory?: () => void, onreset?: () => void, onabort?: () => void, onpause?: () => void, onstep?: () => void, }): _mithril.MithrilVirtualElement<ControlsController> { let buttons: _mithril.MithrilVirtualElement<ControlsController>[] = []; if (args.doneExecuting()) { buttons.push(m(<any> "button.reset", { onclick: function() { if (args.onreset) { args.onreset(); } }, }, "Reset")); } else if (!args.executing()) { let cssClass = args.valid ? ".run" : ".runInvalid"; let text = args.valid ? "Run" : "Invalid Code"; if (args.memoryUsage !== null) { cssClass = ".runMemory"; let overLimit = args.memoryUsage.className + "." + args.memoryUsage.method; if (args.memoryUsage.className === MAIN) { overLimit = "main"; } text = "Over Memory Limit: " + overLimit; } buttons.push(m(<any> ("button" + cssClass), { onclick: function() { if (!args.valid) { if (args.onruninvalid) { args.onruninvalid(); } } else if (args.memoryUsage !== null) { if (args.onrunmemory) { args.onrunmemory(); } } else if (args.onrun) { args.onrun(); } }, }, text)); } else { buttons.push(m(<any> "button.abort", { onclick: function() { if (args.onabort) {<|fim▁hole|> buttons.push(m(".speed-control", [ "Slow", m("input[type=range][min=0.5][max=2.0][step=0.1]", { value: args.speed(), onchange: function(event: any) { let value = parseFloat(event.target.value); args.speed(value); }, }), "Fast" ])); } return m("nav#gameControls", buttons); } }<|fim▁end|>
args.onabort(); } }, }, "Abort"));
<|file_name|>utils.go<|end_file_name|><|fim▁begin|>package zmq4 import ( "fmt" ) /* Send multi-part message on socket. Any `[]string' or `[][]byte' is split into separate `string's or `[]byte's Any other part that isn't a `string' or `[]byte' is converted to `string' with `fmt.Sprintf("%v", part)'. Returns total bytes sent. */ func (soc *Socket) SendMessage(parts ...interface{}) (total int, err error) { return soc.sendMessage(0, parts...) } /* Like SendMessage(), but adding the DONTWAIT flag. */ func (soc *Socket) SendMessageDontwait(parts ...interface{}) (total int, err error) { return soc.sendMessage(DONTWAIT, parts...) } func (soc *Socket) sendMessage(dontwait Flag, parts ...interface{}) (total int, err error) { var last int PARTS: for last = len(parts) - 1; last >= 0; last-- { switch t := parts[last].(type) { case []string: if len(t) > 0 { break PARTS } case [][]byte: if len(t) > 0 { break PARTS } default: break PARTS } } opt := SNDMORE | dontwait for i := 0; i <= last; i++ { if i == last { opt = dontwait } switch t := parts[i].(type) { case []string: opt = SNDMORE | dontwait n := len(t) - 1 for j, s := range t { if j == n && i == last { opt = dontwait } c, e := soc.Send(s, opt) if e == nil { total += c } else { return -1, e } } case [][]byte: opt = SNDMORE | dontwait n := len(t) - 1 for j, b := range t { if j == n && i == last { opt = dontwait } c, e := soc.SendBytes(b, opt) if e == nil { total += c } else { return -1, e } } case string: c, e := soc.Send(t, opt) if e == nil { total += c } else { return -1, e } case []byte: c, e := soc.SendBytes(t, opt) if e == nil { total += c } else { return -1, e } default: c, e := soc.Send(fmt.Sprintf("%v", t), opt) if e == nil { total += c } else { return -1, e } } } return } /* Receive parts as message from socket. Returns last non-nil error code. */ func (soc *Socket) RecvMessage(flags Flag) (msg []string, err error) { msg = make([]string, 0) for { s, e := soc.Recv(flags) if e == nil { msg = append(msg, s) } else { return msg[0:0], e } more, e := soc.GetRcvmore() if e == nil { if !more { break } } else { return msg[0:0], e } } return } /* Receive parts as message from socket. Returns last non-nil error code. */ func (soc *Socket) RecvMessageBytes(flags Flag) (msg [][]byte, err error) { msg = make([][]byte, 0) for { b, e := soc.RecvBytes(flags) if e == nil { msg = append(msg, b) } else { return msg[0:0], e } more, e := soc.GetRcvmore() if e == nil { if !more { break } } else { return msg[0:0], e } } return }<|fim▁hole|>Metadata is picked from the first message part. For details about metadata, see RecvWithMetadata(). Returns last non-nil error code. */ func (soc *Socket) RecvMessageWithMetadata(flags Flag, properties ...string) (msg []string, metadata map[string]string, err error) { b, p, err := soc.RecvMessageBytesWithMetadata(flags, properties...) m := make([]string, len(b)) for i, bt := range b { m[i] = string(bt) } return m, p, err } /* Receive parts as message from socket, including metadata. Metadata is picked from the first message part. For details about metadata, see RecvBytesWithMetadata(). Returns last non-nil error code. */ func (soc *Socket) RecvMessageBytesWithMetadata(flags Flag, properties ...string) (msg [][]byte, metadata map[string]string, err error) { bb := make([][]byte, 0) b, p, err := soc.RecvBytesWithMetadata(flags, properties...) if err != nil { return bb, p, err } for { bb = append(bb, b) var more bool more, err = soc.GetRcvmore() if err != nil || !more { break } b, err = soc.RecvBytes(flags) if err != nil { break } } return bb, p, err }<|fim▁end|>
/* Receive parts as message from socket, including metadata.
<|file_name|>frequency.rs<|end_file_name|><|fim▁begin|>use envelope; use pitch; /// Types for generating the frequency given some playhead position. pub trait Frequency { /// Return the frequency given some playhead percentage through the duration of the Synth. /// - 0.0 < perc < 1.0l fn hz_at_playhead(&self, perc: f64) -> f64; /// Return the frequency as a percentage. #[inline] fn freq_perc_at_playhead(&self, perc: f64) -> f64 { pitch::Hz(self.hz_at_playhead(perc) as f32).perc() } } /// Alias for the Envelope used. pub type Envelope = envelope::Envelope; /// A type that allows dynamically switching between constant and enveloped frequency. #[derive(Debug, Clone, PartialEq)] pub enum Dynamic { Envelope(Envelope), Hz(f64), } impl Dynamic { <|fim▁hole|> if let Dynamic::Envelope(_) = *self { true } else { false } } /// Convert the dynamic to its Envelope variant. pub fn to_env(&self) -> Dynamic { use std::iter::once; if let Dynamic::Hz(hz) = *self { let perc = pitch::Hz(hz as f32).perc(); return Dynamic::Envelope({ once(envelope::Point::new(0.0, perc, 0.0)) .chain(once(envelope::Point::new(1.0, perc, 0.0))) .collect() }) } self.clone() } /// Convert the dynamic to its Hz variant. pub fn to_hz(&self) -> Dynamic { if let Dynamic::Envelope(ref env) = *self { use pitch::{LetterOctave, Letter}; // Just convert the first point to the constant Hz. return match env.points.iter().nth(0) { Some(point) => Dynamic::Hz(pitch::Perc(point.y).hz() as f64), None => Dynamic::Hz(LetterOctave(Letter::C, 1).hz() as f64), } } self.clone() } } impl Frequency for f64 { #[inline] fn hz_at_playhead(&self, _perc: f64) -> f64 { *self } } impl Frequency for Envelope { #[inline] fn hz_at_playhead(&self, perc: f64) -> f64 { pitch::Perc(self.freq_perc_at_playhead(perc)).hz() as f64 } #[inline] fn freq_perc_at_playhead(&self, perc: f64) -> f64 { envelope::Trait::y(self, perc) .expect("The given playhead position is out of range (0.0..1.0).") } } impl Frequency for Dynamic { #[inline] fn hz_at_playhead(&self, perc: f64) -> f64 { match *self { Dynamic::Envelope(ref env) => env.hz_at_playhead(perc), Dynamic::Hz(hz) => hz, } } }<|fim▁end|>
/// Return whether or not the Dynamic is an Envelope. pub fn is_env(&self) -> bool {
<|file_name|>char_parameter.cpp<|end_file_name|><|fim▁begin|>// (C) Copyright Gennadiy Rozental 2005-2008. // Use, modification, and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 49312 $ // // Description : offline implementation of char parameter<|fim▁hole|>#define BOOST_RT_PARAM_INLINE #include <boost/test/utils/runtime/cla/char_parameter.ipp><|fim▁end|>
// ***************************************************************************
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import platform if platform.system() == 'Windows': from compat import * from puke.Error import * from puke.Task import * from puke.Tools import * from puke.ToolsExec import * from puke.FileList import * from puke.Sed import * from puke.Console import * from puke.Env import * from puke.Cache import * from puke.Require import * from puke.Yak import * from puke.VirtualEnv import * from puke.Std import * from puke.SSH import SSH import puke.System import puke.FileSystem import puke.Utils import requests as http VERSION = 0.1 __all__ = [ "main", "VERSION", "Error", "FileList", "Sed", "Std", "Env", "Require", "Load", "Yak", "VirtualEnv", "System", "FileSystem", "Utils", "combine", "sh", "minify", "jslint", "http", "jsdoc", "jsdoc3", "patch", "prompt", "deepcopy", "stats", "pack", "unpack", "hsizeof", "console", "SSH" ] import sys, logging, os, traceback import pkg_resources from optparse import OptionParser from colorama import * try: sys.path.insert(1, os.getcwd()) except: pass def run(): """ Main routine which should be called on startup """ # # Parse options # parser = OptionParser() parser.add_option("-c", "--clear", action="store_true", dest="clearcache", help="Spring time, clean all the vomit") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="don't print status messages to stdout") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="print more detailed status messages to stdout") parser.add_option("-t", "--tasks",action="store_true", dest="list_tasks", help="list tasks") parser.add_option("-l", "--log", dest="logfile", help="Write debug messages to given logfile") parser.add_option("-f", "--file", dest="file", help="Use the given build script") parser.add_option("-p", "--patch",action="store_true", dest="patch", help="Patch closure") parser.add_option("-i", "--info",action="store_true", dest="info", help="puke task --info show task informations") if sys.platform.lower() == "darwin": parser.add_option("-s", "--speak", action="store_true", dest="speak", help="puke speaks on fail/success") (options, args) = parser.parse_args() if hasattr(options, 'speak'): Console.SPEAK_ENABLED = True rLog = logging.getLogger('requests') rLog.setLevel(logging.WARNING) # # Configure logging # if options.logfile: logging.basicConfig(filename=options.logfile, level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") logging.getLogger().setLevel(logging.DEBUG) elif not logging.root.handlers: if options.verbose is True: logging.getLogger().setLevel(logging.DEBUG) rLog.setLevel(logging.DEBUG) elif options.verbose is False: logging.getLogger().setLevel(logging.WARN) else: logging.getLogger().setLevel(logging.INFO) # Define a Handler which writes INFO messages or higher to the sys.stderr consoleCfg = logging.StreamHandler() if options.verbose is True: consoleCfg.setLevel(logging.DEBUG) elif options.verbose is False: consoleCfg.setLevel(logging.WARN) else: consoleCfg.setLevel(logging.INFO) if os.environ.get("NOCOLOR"): consoleCfg.setFormatter(logging.Formatter( ' %(message)s' , '%H:%M:%S')) else: consoleCfg.setFormatter(logging.Formatter( ' %(message)s' + Style.RESET_ALL, '%H:%M:%S')) <|fim▁hole|> #Patch closure try: closure = pkg_resources.get_distribution('closure_linter').location closure_lock = os.path.join(closure, 'closure_linter', 'puke.lock') if options.patch or not os.path.isfile(closure_lock): closure = os.path.join(closure, 'closure_linter', 'ecmalintrules.py') try: handle = source = destination = None import shutil shutil.move( closure, closure+"~" ) destination= open( closure, "w" ) source= open( closure+"~", "r" ) content = source.read() content = content.replace('MAX_LINE_LENGTH = 80', 'MAX_LINE_LENGTH = 120') destination.write(content) source.close() destination.close() os.remove(closure+"~" ) handle = file(closure_lock, 'a') handle.close if options.patch: console.confirm('Patch successful') sys.exit(0) except Exception as e: console.warn(">>> you should consider running \"sudo puke --patch\"") if handle: handle.close() if source: source.close() if destination: destination.close() if options.patch: sys.exit(0) except Exception as e: console.error('Closure linter not found %s' % e) # # Handle .pukeignore # if os.path.isfile('.pukeignore'): try: f = open('.pukeignore', 'r') for line in f: FileList.addGlobalExclude(line.strip()) except Exception as e: console.warn('Puke ignore error : %s' % e) # # Find and execute build script # pukefiles = ["pukefile", "pukeFile", "pukefile", "pukefile.py", "pukeFile.py", "pukefile.py"] script = None if options.file: if os.path.isfile(options.file): script = options.file else: for name in pukefiles: if os.path.isfile(name): script = name if script is None: if options.file: raise PukeError("No generate file '%s' found!" % options.file) else: raise PukeError("No generate file found!") retval = execfile(script) # # Execute tasks # if options.list_tasks: console.confirm("Please choose from: ") printTasks() sys.exit(0) if options.clearcache: console.header("Spring time, cleaning all the vomit around ...") console.log("...") if Cache.clean(): console.confirm("You're good to go !\n") else: console.confirm("Your room is already tidy, good boy :-) \n") sys.exit(0) try: args = args.strip() except: pass if not args: if hasDefault(): executeTask('default') else: logging.error("No tasks to execute. Please choose from: ") printTasks() sys.exit(1) else: name = args.pop(0) if options.info: printHelp(name.strip()) else: executeTask(name.strip(), *args) def gettraceback(level = 0): trace = "" exception = "" exc_list = traceback.format_exception_only (sys.exc_type, sys.exc_value) reverse = -1 - level for entry in exc_list: exception += entry tb_list = traceback.format_tb(sys.exc_info()[2]) for entry in tb_list[reverse]: trace += entry return trace def main(): try: run() except Exception as error: console.fail("\n\n :puke: \n PUKE %s \n %s \n" % (error, gettraceback())) sys.exit(1) except KeyboardInterrupt: console.warn("\n\n :puke: \nBuild interrupted!\n") sys.exit(2) if Console.SPEAK_ENABLED and Console.SPEAK_MESSAGE_ON_SUCCESS: console.say(Console.SPEAK_MESSAGE_ON_SUCCESS) sys.exit(0)<|fim▁end|>
logging.getLogger().addHandler(consoleCfg)
<|file_name|>UncagingControlTemplate_pyqt5.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'acq4/analysis/old/UncagingControlTemplate.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_UncagingControlWidget(object): def setupUi(self, UncagingControlWidget): UncagingControlWidget.setObjectName("UncagingControlWidget") UncagingControlWidget.resize(442, 354) self.gridLayout_4 = QtWidgets.QGridLayout(UncagingControlWidget) self.gridLayout_4.setObjectName("gridLayout_4") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.label = QtWidgets.QLabel(UncagingControlWidget) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.thresholdSpin = QtWidgets.QDoubleSpinBox(UncagingControlWidget) self.thresholdSpin.setObjectName("thresholdSpin") self.gridLayout.addWidget(self.thresholdSpin, 0, 1, 1, 1) self.label_3 = QtWidgets.QLabel(UncagingControlWidget) self.label_3.setObjectName("label_3") self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1) self.directTimeSpin = QtWidgets.QDoubleSpinBox(UncagingControlWidget) self.directTimeSpin.setObjectName("directTimeSpin") self.gridLayout.addWidget(self.directTimeSpin, 1, 1, 1, 1) self.label_2 = QtWidgets.QLabel(UncagingControlWidget) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1) self.poststimTimeSpin = QtWidgets.QDoubleSpinBox(UncagingControlWidget) self.poststimTimeSpin.setObjectName("poststimTimeSpin") self.gridLayout.addWidget(self.poststimTimeSpin, 2, 1, 1, 1) self.gridLayout_4.addLayout(self.gridLayout, 0, 0, 1, 1) self.groupBox_4 = QtWidgets.QGroupBox(UncagingControlWidget) self.groupBox_4.setObjectName("groupBox_4") self.horizontalLayout = QtWidgets.QHBoxLayout(self.groupBox_4) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName("horizontalLayout") self.groupBox_2 = QtWidgets.QGroupBox(self.groupBox_4) self.groupBox_2.setTitle("") self.groupBox_2.setObjectName("groupBox_2") self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox_2) self.gridLayout_3.setObjectName("gridLayout_3") self.gradientRadio = QtWidgets.QRadioButton(self.groupBox_2) self.gradientRadio.setObjectName("gradientRadio") self.gridLayout_3.addWidget(self.gradientRadio, 0, 0, 1, 2) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label_4 = QtWidgets.QLabel(self.groupBox_2) self.label_4.setObjectName("label_4") self.horizontalLayout_2.addWidget(self.label_4) self.colorSpin1 = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.colorSpin1.setObjectName("colorSpin1") self.horizontalLayout_2.addWidget(self.colorSpin1) self.gridLayout_3.addLayout(self.horizontalLayout_2, 1, 0, 1, 2) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_5 = QtWidgets.QLabel(self.groupBox_2) self.label_5.setObjectName("label_5") self.horizontalLayout_3.addWidget(self.label_5) self.colorSpin3 = QtWidgets.QDoubleSpinBox(self.groupBox_2) self.colorSpin3.setMaximum(100.0) self.colorSpin3.setObjectName("colorSpin3") self.horizontalLayout_3.addWidget(self.colorSpin3) self.gridLayout_3.addLayout(self.horizontalLayout_3, 2, 0, 1, 2) self.gradientWidget = GradientWidget(self.groupBox_2) self.gradientWidget.setObjectName("gradientWidget") self.gridLayout_3.addWidget(self.gradientWidget, 3, 0, 2, 2) self.rgbRadio = QtWidgets.QRadioButton(self.groupBox_2) self.rgbRadio.setObjectName("rgbRadio") self.gridLayout_3.addWidget(self.rgbRadio, 5, 0, 1, 2) self.colorTracesCheck = QtWidgets.QCheckBox(self.groupBox_2) self.colorTracesCheck.setObjectName("colorTracesCheck") self.gridLayout_3.addWidget(self.colorTracesCheck, 7, 0, 1, 2) self.svgCheck = QtWidgets.QCheckBox(self.groupBox_2) self.svgCheck.setObjectName("svgCheck") self.gridLayout_3.addWidget(self.svgCheck, 8, 0, 1, 2) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.label_6 = QtWidgets.QLabel(self.groupBox_2) self.label_6.setObjectName("label_6") self.horizontalLayout_4.addWidget(self.label_6) self.lowClipSpin = QtWidgets.QSpinBox(self.groupBox_2) self.lowClipSpin.setObjectName("lowClipSpin") self.horizontalLayout_4.addWidget(self.lowClipSpin) self.highClipSpin = QtWidgets.QSpinBox(self.groupBox_2) self.highClipSpin.setObjectName("highClipSpin") self.horizontalLayout_4.addWidget(self.highClipSpin) self.gridLayout_3.addLayout(self.horizontalLayout_4, 9, 0, 1, 2) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.label_7 = QtWidgets.QLabel(self.groupBox_2) self.label_7.setObjectName("label_7") self.horizontalLayout_5.addWidget(self.label_7) self.downsampleSpin = QtWidgets.QSpinBox(self.groupBox_2) self.downsampleSpin.setObjectName("downsampleSpin") self.horizontalLayout_5.addWidget(self.downsampleSpin) self.gridLayout_3.addLayout(self.horizontalLayout_5, 10, 0, 1, 2) self.horizontalLayout.addWidget(self.groupBox_2) self.gridLayout_4.addWidget(self.groupBox_4, 0, 1, 2, 1) self.groupBox = QtWidgets.QGroupBox(UncagingControlWidget) self.groupBox.setObjectName("groupBox") self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.eventFindRadio = QtWidgets.QRadioButton(self.groupBox) self.eventFindRadio.setObjectName("eventFindRadio") self.gridLayout_2.addWidget(self.eventFindRadio, 0, 0, 1, 1) self.chargeTransferRadio = QtWidgets.QRadioButton(self.groupBox) self.chargeTransferRadio.setObjectName("chargeTransferRadio") self.gridLayout_2.addWidget(self.chargeTransferRadio, 1, 0, 1, 1) self.useSpontActCheck = QtWidgets.QCheckBox(self.groupBox) self.useSpontActCheck.setObjectName("useSpontActCheck") self.gridLayout_2.addWidget(self.useSpontActCheck, 2, 0, 1, 1) self.medianCheck = QtWidgets.QCheckBox(self.groupBox) self.medianCheck.setObjectName("medianCheck") self.gridLayout_2.addWidget(self.medianCheck, 3, 0, 1, 1) self.gridLayout_4.addWidget(self.groupBox, 1, 0, 1, 1) self.recolorBtn = QtWidgets.QPushButton(UncagingControlWidget) self.recolorBtn.setObjectName("recolorBtn") self.gridLayout_4.addWidget(self.recolorBtn, 2, 0, 1, 2) self.retranslateUi(UncagingControlWidget) Qt.QMetaObject.connectSlotsByName(UncagingControlWidget) def retranslateUi(self, UncagingControlWidget):<|fim▁hole|> _translate = Qt.QCoreApplication.translate UncagingControlWidget.setWindowTitle(_translate("UncagingControlWidget", "Form")) self.label.setText(_translate("UncagingControlWidget", "Noise Threshold")) self.label_3.setText(_translate("UncagingControlWidget", "Direct Time")) self.label_2.setText(_translate("UncagingControlWidget", "Post-Stim. Time")) self.groupBox_4.setTitle(_translate("UncagingControlWidget", "Coloring Scheme:")) self.gradientRadio.setText(_translate("UncagingControlWidget", "Gradient")) self.label_4.setText(_translate("UncagingControlWidget", "Low % Cutoff")) self.label_5.setText(_translate("UncagingControlWidget", "High % Cutoff")) self.rgbRadio.setText(_translate("UncagingControlWidget", "RGB")) self.colorTracesCheck.setText(_translate("UncagingControlWidget", "Color Traces by Laser Power")) self.svgCheck.setText(_translate("UncagingControlWidget", "Prepare for SVG")) self.label_6.setText(_translate("UncagingControlWidget", "Clip:")) self.label_7.setText(_translate("UncagingControlWidget", "Downsample:")) self.groupBox.setTitle(_translate("UncagingControlWidget", "Analysis Method:")) self.eventFindRadio.setText(_translate("UncagingControlWidget", "Event Finding")) self.chargeTransferRadio.setText(_translate("UncagingControlWidget", "Total Charge Transfer")) self.useSpontActCheck.setText(_translate("UncagingControlWidget", "Use Spont. Activity")) self.medianCheck.setText(_translate("UncagingControlWidget", "Use Median")) self.recolorBtn.setText(_translate("UncagingControlWidget", "Re-Color")) from acq4.pyqtgraph.GradientWidget import GradientWidget<|fim▁end|>
<|file_name|>test.py<|end_file_name|><|fim▁begin|># noinspection PyMethodMayBeStatic class TestDevice: def __init__(self, cf): self.type = cf.get('device_test_type', 'test') self.host = ('test', 80) self.mac = [1, 2, 3, 4, 5, 6] def auth(self): pass # RM2/RM4 def check_temperature(self): return 23.5 <|fim▁hole|> def check_humidity(self): return 56 def enter_learning(self): pass def check_data(self): payload = bytearray(5) payload[0] = 0xAA payload[1] = 0xBB payload[2] = 0xCC payload[3] = 0xDD payload[4] = 0xEE return payload def send_data(self, data): pass def check_sensors(self): return {'temperature': 23.5, 'humidity': 36, 'light': 'dim', 'air_quality': 'normal', 'noise': 'noisy'} def check_sensors_raw(self): return {'temperature': 23.5, 'humidity': 36, 'light': 1, 'air_quality': 3, 'noise': 2} def get_percentage(self): return 33 def open(self): pass def get_state(self): return {'pwr': 1, 'pwr1': 1, 'pwr2': 0, 'maxworktime': 60, 'maxworktime1': 60, 'maxworktime2': 0, 'idcbrightness': 50} def check_power(self): return {'s1': True, 's2': False, 's3': True, 's4': False}<|fim▁end|>
# RM4
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup uses a pluggable XML or HTML parser to parse a (possibly invalid) document into a tree representation. Beautiful Soup provides provides methods and Pythonic idioms that make it easy to navigate, search, and modify the parse tree. Beautiful Soup works with Python 2.6 and up. It works better if lxml and/or html5lib is installed. For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ """ __author__ = "Leonard Richardson ([email protected])" __version__ = "4.0.4" __copyright__ = "Copyright (c) 2004-2012 Leonard Richardson" __license__ = "MIT" __all__ = ['BeautifulSoup'] import re import warnings from .builder import builder_registry from .dammit import UnicodeDammit from .element import ( CData, Comment, DEFAULT_OUTPUT_ENCODING, Declaration, Doctype, NavigableString, PageElement, ProcessingInstruction, ResultSet, SoupStrainer, Tag, ) # The very first thing we do is give a useful error if someone is # running this code under Python 3 without converting it. syntax_error = u'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work. You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).' class BeautifulSoup(Tag): """ This class defines the basic interface called by the tree builders. These methods will be called by the parser: reset() feed(markup) The tree builder may call these methods from its feed() implementation: handle_starttag(name, attrs) # See note about return value handle_endtag(name) handle_data(data) # Appends to the current data node endData(containerClass=NavigableString) # Ends the current data node No matter how complicated the underlying parser is, you should be able to build a tree using 'start tag' events, 'end tag' events, 'data' events, and "done with data" events. If you encounter an empty-element tag (aka a self-closing tag, like HTML's <br> tag), call handle_starttag and then handle_endtag. """ ROOT_TAG_NAME = u'[document]' # If the end-user gives no indication which tree builder they # want, look for one with these features. DEFAULT_BUILDER_FEATURES = ['html', 'fast'] # Used when determining whether a text node is all whitespace and # can be replaced with a single space. A text node that contains # fancy Unicode spaces (usually non-breaking) should be left # alone. STRIP_ASCII_SPACES = {9: None, 10: None, 12: None, 13: None, 32: None, } def __init__(self, markup="", features=None, builder=None, parse_only=None, from_encoding=None, **kwargs): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser.""" if 'convertEntities' in kwargs: warnings.warn( "BS4 does not respect the convertEntities argument to the " "BeautifulSoup constructor. Entities are always converted " "to Unicode characters.") if 'markupMassage' in kwargs: del kwargs['markupMassage'] warnings.warn( "BS4 does not respect the markupMassage argument to the " "BeautifulSoup constructor. The tree builder is responsible " "for any necessary markup massage.") if 'smartQuotesTo' in kwargs: del kwargs['smartQuotesTo'] warnings.warn( "BS4 does not respect the smartQuotesTo argument to the " "BeautifulSoup constructor. Smart quotes are always converted " "to Unicode characters.") if 'selfClosingTags' in kwargs: del kwargs['selfClosingTags'] warnings.warn( "BS4 does not respect the selfClosingTags argument to the " "BeautifulSoup constructor. The tree builder is responsible " "for understanding self-closing tags.") if 'isHTML' in kwargs: del kwargs['isHTML'] warnings.warn( "BS4 does not respect the isHTML argument to the " "BeautifulSoup constructor. You can pass in features='html' " "or features='xml' to get a builder capable of handling " "one or the other.") def deprecated_argument(old_name, new_name): if old_name in kwargs: warnings.warn( 'The "%s" argument to the BeautifulSoup constructor ' 'has been renamed to "%s."' % (old_name, new_name)) value = kwargs[old_name] del kwargs[old_name] return value return None parse_only = parse_only or deprecated_argument( "parseOnlyThese", "parse_only") from_encoding = from_encoding or deprecated_argument( "fromEncoding", "from_encoding") if len(kwargs) > 0: arg = kwargs.keys().pop() raise TypeError( "__init__() got an unexpected keyword argument '%s'" % arg) if builder is None: if isinstance(features, basestring): features = [features] if features is None or len(features) == 0: features = self.DEFAULT_BUILDER_FEATURES builder_class = builder_registry.lookup(*features) if builder_class is None: raise ValueError( "Couldn't find a tree builder with the features you " "requested: %s. Do you need to install a parser library?" % ",".join(features)) builder = builder_class() self.builder = builder self.is_xml = builder.is_xml self.builder.soup = self self.parse_only = parse_only self.reset() if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() (self.markup, self.original_encoding, self.declared_html_encoding, self.contains_replacement_characters) = ( self.builder.prepare_markup(markup, from_encoding)) try: self._feed() except StopParsing: pass # Clear out the markup and remove the builder's circular # reference to this object. self.markup = None self.builder.soup = None def _feed(self): # Convert the document to Unicode. self.builder.reset() self.builder.feed(self.markup) # Close out any unfinished strings and close all the open tags. self.endData() while self.currentTag.name != self.ROOT_TAG_NAME: self.popTag() def reset(self): Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME) self.hidden = 1 self.builder.reset() self.currentData = [] self.currentTag = None self.tagStack = [] self.pushTag(self) def new_tag(self, name, namespace=None, nsprefix=None, **attrs): """Create a new tag associated with this soup.""" return Tag(None, self.builder, name, namespace, nsprefix, attrs) def new_string(self, s): """Create a new NavigableString associated with this soup.""" navigable = NavigableString(s) navigable.setup() return navigable def insert_before(self, successor): raise ValueError("BeautifulSoup objects don't support insert_before().") def insert_after(self, successor): raise ValueError("BeautifulSoup objects don't support insert_after().") def popTag(self): tag = self.tagStack.pop() #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag def pushTag(self, tag): #print "Push", tag.name if self.currentTag: self.currentTag.contents.append(tag) self.tagStack.append(tag) self.currentTag = self.tagStack[-1] def endData(self, containerClass=NavigableString): if self.currentData: currentData = u''.join(self.currentData) if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and not set([tag.name for tag in self.tagStack]).intersection( self.builder.preserve_whitespace_tags)):<|fim▁hole|> currentData = '\n' else: currentData = ' ' self.currentData = [] if self.parse_only and len(self.tagStack) <= 1 and \ (not self.parse_only.text or \ not self.parse_only.search(currentData)): return o = containerClass(currentData) self.object_was_parsed(o) def object_was_parsed(self, o): """Add an object to the parse tree.""" o.setup(self.currentTag, self.previous_element) if self.previous_element: self.previous_element.next_element = o self.previous_element = o self.currentTag.contents.append(o) def _popToTag(self, name, nsprefix=None, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name if name == self.ROOT_TAG_NAME: return numPops = 0 mostRecentTag = None for i in range(len(self.tagStack) - 1, 0, -1): if (name == self.tagStack[i].name and nsprefix == self.tagStack[i].nsprefix == nsprefix): numPops = len(self.tagStack) - i break if not inclusivePop: numPops = numPops - 1 for i in range(0, numPops): mostRecentTag = self.popTag() return mostRecentTag def handle_starttag(self, name, namespace, nsprefix, attrs): """Push a start tag on to the stack. If this method returns None, the tag was rejected by the SoupStrainer. You should proceed as if the tag had not occured in the document. For instance, if this was a self-closing tag, don't call handle_endtag. """ # print "Start tag %s: %s" % (name, attrs) self.endData() if (self.parse_only and len(self.tagStack) <= 1 and (self.parse_only.text or not self.parse_only.search_tag(name, attrs))): return None tag = Tag(self, self.builder, name, namespace, nsprefix, attrs, self.currentTag, self.previous_element) if tag is None: return tag if self.previous_element: self.previous_element.next_element = tag self.previous_element = tag self.pushTag(tag) return tag def handle_endtag(self, name, nsprefix=None): #print "End tag: " + name self.endData() self._popToTag(name, nsprefix) def handle_data(self, data): self.currentData.append(data) def decode(self, pretty_print=False, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Returns a string or Unicode representation of this document. To get Unicode, pass None for encoding.""" if self.is_xml: # Print the XML declaration encoding_part = '' if eventual_encoding != None: encoding_part = ' encoding="%s"' % eventual_encoding prefix = u'<?xml version="1.0"%s?>\n' % encoding_part else: prefix = u'' if not pretty_print: indent_level = None else: indent_level = 0 return prefix + super(BeautifulSoup, self).decode( indent_level, eventual_encoding, formatter) class BeautifulStoneSoup(BeautifulSoup): """Deprecated interface to an XML parser.""" def __init__(self, *args, **kwargs): kwargs['features'] = 'xml' warnings.warn( 'The BeautifulStoneSoup class is deprecated. Instead of using ' 'it, pass features="xml" into the BeautifulSoup constructor.') super(BeautifulStoneSoup, self).__init__(*args, **kwargs) class StopParsing(Exception): pass #By default, act as an HTML pretty-printer. if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin) print soup.prettify()<|fim▁end|>
if '\n' in currentData:
<|file_name|>cli.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals, division, absolute_import import re from argparse import ArgumentParser, ArgumentTypeError from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flexget import options from flexget.event import event from flexget.terminal import TerminalTable, TerminalTableError, table_parser, console from flexget.utils.database import Session from . import db def do_cli(manager, options): """Handle regexp-list cli""" action_map = { 'all': action_all, 'list': action_list, 'add': action_add, 'del': action_del, 'purge': action_purge, } action_map[options.regexp_action](options) def action_all(options): """ Show all regexp lists """ lists = db.get_regexp_lists() header = ['#', 'List Name'] table_data = [header] for regexp_list in lists: table_data.append([regexp_list.id, regexp_list.name]) table = TerminalTable(options.table_type, table_data) try: console(table.output) except TerminalTableError as e: console('ERROR: %s' % str(e)) def action_list(options): """List regexp list""" with Session() as session:<|fim▁hole|> console('Could not find regexp list with name {}'.format(options.list_name)) return header = ['Regexp'] table_data = [header] regexps = db.get_regexps_by_list_id( regexp_list.id, order_by='added', descending=True, session=session ) for regexp in regexps: regexp_row = [regexp.regexp or ''] table_data.append(regexp_row) try: table = TerminalTable(options.table_type, table_data) console(table.output) except TerminalTableError as e: console('ERROR: %s' % str(e)) def action_add(options): with Session() as session: regexp_list = db.get_list_by_exact_name(options.list_name) if not regexp_list: console('Could not find regexp list with name {}, creating'.format(options.list_name)) regexp_list = db.create_list(options.list_name, session=session) regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session) if not regexp: console("Adding regexp {} to list {}".format(options.regexp, regexp_list.name)) db.add_to_list_by_name(regexp_list.name, options.regexp, session=session) console( 'Successfully added regexp {} to regexp list {} '.format( options.regexp, regexp_list.name ) ) else: console("Regexp {} already exists in list {}".format(options.regexp, regexp_list.name)) def action_del(options): with Session() as session: regexp_list = db.get_list_by_exact_name(options.list_name) if not regexp_list: console('Could not find regexp list with name {}'.format(options.list_name)) return regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session) if regexp: console('Removing regexp {} from list {}'.format(options.regexp, options.list_name)) session.delete(regexp) else: console( 'Could not find regexp {} in list {}'.format( options.movie_title, options.list_name ) ) return def action_purge(options): with Session() as session: regexp_list = db.get_list_by_exact_name(options.list_name) if not regexp_list: console('Could not find regexp list with name {}'.format(options.list_name)) return console('Deleting list %s' % options.list_name) session.delete(regexp_list) def regexp_type(regexp): try: re.compile(regexp) return regexp except re.error as e: raise ArgumentTypeError(e) @event('options.register') def register_parser_arguments(): # Common option to be used in multiple subparsers regexp_parser = ArgumentParser(add_help=False) regexp_parser.add_argument('regexp', type=regexp_type, help="The regexp") list_name_parser = ArgumentParser(add_help=False) list_name_parser.add_argument( 'list_name', nargs='?', help='Name of regexp list to operate on', default='regexps' ) # Register subcommand parser = options.register_command('regexp-list', do_cli, help='View and manage regexp lists') # Set up our subparsers subparsers = parser.add_subparsers(title='actions', metavar='<action>', dest='regexp_action') subparsers.add_parser('all', parents=[table_parser], help='Shows all existing regexp lists') subparsers.add_parser( 'list', parents=[list_name_parser, table_parser], help='List regexp from a list' ) subparsers.add_parser( 'add', parents=[list_name_parser, regexp_parser], help='Add a regexp to a list' ) subparsers.add_parser( 'del', parents=[list_name_parser, regexp_parser], help='Remove a regexp from a list' ) subparsers.add_parser( 'purge', parents=[list_name_parser], help='Removes an entire list. Use with caution!' )<|fim▁end|>
regexp_list = db.get_list_by_exact_name(options.list_name) if not regexp_list:
<|file_name|>quickOutline.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./quickOutline'; import * as nls from 'vs/nls'; import { matchesFuzzy } from 'vs/base/common/filters'; import * as strings from 'vs/base/common/strings'; import { TPromise } from 'vs/base/common/winjs.base'; import { IContext, IHighlight, QuickOpenEntryGroup, QuickOpenModel } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; import { ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { SymbolInformation, DocumentSymbolProviderRegistry, symbolKindToCssClass } from 'vs/editor/common/modes'; import { BaseEditorQuickOpenAction, IDecorator } from './editorQuickOpen'; import { getDocumentSymbols, IOutline } from 'vs/editor/contrib/quickOpen/common/quickOpen'; import { editorAction, ServicesAccessor } from 'vs/editor/common/editorCommonExtensions'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { Range } from 'vs/editor/common/core/range'; let SCOPE_PREFIX = ':'; class SymbolEntry extends QuickOpenEntryGroup { private name: string; private type: string; private description: string; private range: Range; private editor: ICommonCodeEditor; private decorator: IDecorator; constructor(name: string, type: string, description: string, range: Range, highlights: IHighlight[], editor: ICommonCodeEditor, decorator: IDecorator) { super(); this.name = name; this.type = type; this.description = description; this.range = range; this.setHighlights(highlights); this.editor = editor; this.decorator = decorator; } public getLabel(): string { return this.name; } public getAriaLabel(): string { return nls.localize('entryAriaLabel', "{0}, symbols", this.name); } public getIcon(): string { return this.type; } public getDescription(): string { return this.description; } public getType(): string { return this.type; } public getRange(): Range { return this.range; } public run(mode: Mode, context: IContext): boolean { if (mode === Mode.OPEN) { return this.runOpen(context); } return this.runPreview(); } private runOpen(context: IContext): boolean { // Apply selection and focus let range = this.toSelection(); this.editor.setSelection(range); this.editor.revealRangeInCenter(range); this.editor.focus(); return true; } private runPreview(): boolean { // Select Outline Position let range = this.toSelection(); this.editor.revealRangeInCenter(range); // Decorate if possible this.decorator.decorateLine(this.range, this.editor); return false; } private toSelection(): Range { return new Range( this.range.startLineNumber, this.range.startColumn || 1, this.range.startLineNumber, this.range.startColumn || 1 );<|fim▁hole|>@editorAction export class QuickOutlineAction extends BaseEditorQuickOpenAction { constructor() { super(nls.localize('quickOutlineActionInput', "Type the name of an identifier you wish to navigate to"), { id: 'editor.action.quickOutline', label: nls.localize('QuickOutlineAction.label', "Go to Symbol..."), alias: 'Go to Symbol...', precondition: EditorContextKeys.hasDocumentSymbolProvider, kbOpts: { kbExpr: EditorContextKeys.focus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_O }, menuOpts: { group: 'navigation', order: 3 } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): TPromise<void> { let model = editor.getModel(); if (!DocumentSymbolProviderRegistry.has(model)) { return null; } // Resolve outline return getDocumentSymbols(model).then((result: IOutline) => { if (result.entries.length === 0) { return; } this._run(editor, result.entries); }); } private _run(editor: ICommonCodeEditor, result: SymbolInformation[]): void { this._show(this.getController(editor), { getModel: (value: string): QuickOpenModel => { return new QuickOpenModel(this.toQuickOpenEntries(editor, result, value)); }, getAutoFocus: (searchValue: string): IAutoFocus => { // Remove any type pattern (:) from search value as needed if (searchValue.indexOf(SCOPE_PREFIX) === 0) { searchValue = searchValue.substr(SCOPE_PREFIX.length); } return { autoFocusPrefixMatch: searchValue, autoFocusFirstEntry: !!searchValue }; } }); } private toQuickOpenEntries(editor: ICommonCodeEditor, flattened: SymbolInformation[], searchValue: string): SymbolEntry[] { const controller = this.getController(editor); let results: SymbolEntry[] = []; // Convert to Entries let normalizedSearchValue = searchValue; if (searchValue.indexOf(SCOPE_PREFIX) === 0) { normalizedSearchValue = normalizedSearchValue.substr(SCOPE_PREFIX.length); } for (let i = 0; i < flattened.length; i++) { let element = flattened[i]; let label = strings.trim(element.name); // Check for meatch let highlights = matchesFuzzy(normalizedSearchValue, label); if (highlights) { // Show parent scope as description let description: string = null; if (element.containerName) { description = element.containerName; } // Add results.push(new SymbolEntry(label, symbolKindToCssClass(element.kind), description, Range.lift(element.location.range), highlights, editor, controller)); } } // Sort properly if actually searching if (searchValue) { if (searchValue.indexOf(SCOPE_PREFIX) === 0) { results = results.sort(this.sortScoped.bind(this, searchValue.toLowerCase())); } else { results = results.sort(this.sortNormal.bind(this, searchValue.toLowerCase())); } } // Mark all type groups if (results.length > 0 && searchValue.indexOf(SCOPE_PREFIX) === 0) { let currentType: string = null; let currentResult: SymbolEntry = null; let typeCounter = 0; for (let i = 0; i < results.length; i++) { let result = results[i]; // Found new type if (currentType !== result.getType()) { // Update previous result with count if (currentResult) { currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter)); } currentType = result.getType(); currentResult = result; typeCounter = 1; result.setShowBorder(i > 0); } // Existing type, keep counting else { typeCounter++; } } // Update previous result with count if (currentResult) { currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter)); } } // Mark first entry as outline else if (results.length > 0) { results[0].setGroupLabel(nls.localize('symbols', "symbols ({0})", results.length)); } return results; } private typeToLabel(type: string, count: number): string { switch (type) { case 'module': return nls.localize('modules', "modules ({0})", count); case 'class': return nls.localize('class', "classes ({0})", count); case 'interface': return nls.localize('interface', "interfaces ({0})", count); case 'method': return nls.localize('method', "methods ({0})", count); case 'function': return nls.localize('function', "functions ({0})", count); case 'property': return nls.localize('property', "properties ({0})", count); case 'variable': return nls.localize('variable', "variables ({0})", count); case 'var': return nls.localize('variable2', "variables ({0})", count); case 'constructor': return nls.localize('_constructor', "constructors ({0})", count); case 'call': return nls.localize('call', "calls ({0})", count); } return type; } private sortNormal(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number { let elementAName = elementA.getLabel().toLowerCase(); let elementBName = elementB.getLabel().toLowerCase(); // Compare by name let r = elementAName.localeCompare(elementBName); if (r !== 0) { return r; } // If name identical sort by range instead let elementARange = elementA.getRange(); let elementBRange = elementB.getRange(); return elementARange.startLineNumber - elementBRange.startLineNumber; } private sortScoped(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number { // Remove scope char searchValue = searchValue.substr(SCOPE_PREFIX.length); // Sort by type first if scoped search let elementAType = elementA.getType(); let elementBType = elementB.getType(); let r = elementAType.localeCompare(elementBType); if (r !== 0) { return r; } // Special sort when searching in scoped mode if (searchValue) { let elementAName = elementA.getLabel().toLowerCase(); let elementBName = elementB.getLabel().toLowerCase(); // Compare by name let r = elementAName.localeCompare(elementBName); if (r !== 0) { return r; } } // Default to sort by range let elementARange = elementA.getRange(); let elementBRange = elementB.getRange(); return elementARange.startLineNumber - elementBRange.startLineNumber; } }<|fim▁end|>
} }
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models import Profile from cc.relate.forms import EndorseForm, AcknowledgementForm from cc.relate.models import Endorsement from cc.feed.models import FeedItem from cc.general.mail import send_notification from django.utils.translation import ugettext as _ MESSAGES = { 'endorsement_saved': _("Endorsement saved."), 'endorsement_deleted': _("Endorsement deleted."), 'acknowledgement_sent': _("Acknowledgement sent."), } @login_required @render() def endorse_user(request, recipient_username): recipient = get_object_or_404(Profile, user__username=recipient_username) if recipient == request.profile: raise Http404() try: endorsement = Endorsement.objects.get( endorser=request.profile, recipient=recipient) except Endorsement.DoesNotExist: endorsement = None if request.method == 'POST': if 'delete' in request.POST and endorsement: endorsement.delete() messages.info(request, MESSAGES['endorsement_deleted']) return HttpResponseRedirect( endorsement.recipient.get_absolute_url()) form = EndorseForm(request.POST, instance=endorsement, endorser=request.profile, recipient=recipient) if form.is_valid(): is_new = endorsement is None endorsement = form.save() if is_new: send_endorsement_notification(endorsement) messages.info(request, MESSAGES['endorsement_saved']) return HttpResponseRedirect(endorsement.get_absolute_url()) else: form = EndorseForm(instance=endorsement, endorser=request.profile, recipient=recipient) profile = recipient # For profile_base.html. return locals() def send_endorsement_notification(endorsement): subject = _("%s has endorsed you on Villages.cc") % endorsement.endorser send_notification(subject, endorsement.endorser, endorsement.recipient, 'endorsement_notification_email.txt', {'endorsement': endorsement}) @login_required @render() def endorsement(request, endorsement_id): endorsement = get_object_or_404(Endorsement, pk=endorsement_id) return locals() @login_required @render() def relationships(request): accounts = ripple.get_user_accounts(request.profile) return locals() @login_required @render() def relationship(request, partner_username): partner = get_object_or_404(Profile, user__username=partner_username) if partner == request.profile: raise Http404 # Can't have relationship with yourself. account = request.profile.account(partner) if account: entries = account.entries balance = account.balance else:<|fim▁hole|> entries = [] balance = 0 profile = partner # For profile_base.html. return locals() @login_required @render() def acknowledge_user(request, recipient_username): recipient = get_object_or_404(Profile, user__username=recipient_username) if recipient == request.profile: raise Http404 # TODO: Don't recompute max_amount on form submit? Cache, or put in form # as hidden field? max_amount = ripple.max_payment(request.profile, recipient) if request.method == 'POST': form = AcknowledgementForm(request.POST, max_ripple=max_amount) if form.is_valid(): acknowledgement = form.send_acknowledgement( request.profile, recipient) send_acknowledgement_notification(acknowledgement) messages.info(request, MESSAGES['acknowledgement_sent']) return HttpResponseRedirect(acknowledgement.get_absolute_url()) else: form = AcknowledgementForm(max_ripple=max_amount, initial=request.GET) can_ripple = max_amount > 0 profile = recipient # For profile_base.html. return locals() def send_acknowledgement_notification(acknowledgement): subject = _("%s has acknowledged you on Villages.cc") % ( acknowledgement.payer) send_notification(subject, acknowledgement.payer, acknowledgement.recipient, 'acknowledgement_notification_email.txt', {'acknowledgement': acknowledgement}) @login_required @render() def view_acknowledgement(request, payment_id): try: payment = ripple.get_payment(payment_id) except ripple.RipplePayment.DoesNotExist: raise Http404 entries = payment.entries_for_user(request.profile) if not entries: raise Http404 # Non-participants don't get to see anything. sent_entries = [] received_entries = [] for entry in entries: if entry.amount < 0: sent_entries.append(entry) else: received_entries.append(entry) return locals()<|fim▁end|>
<|file_name|>UploadingViewTest.java<|end_file_name|><|fim▁begin|>package eindberetning.it_minds.dk.eindberetningmobil_android.views; import android.widget.TextView;<|fim▁hole|>import eindberetning.it_minds.dk.eindberetningmobil_android.BaseTest; import eindberetning.it_minds.dk.eindberetningmobil_android.data.StaticData; import it_minds.dk.eindberetningmobil_android.R; import it_minds.dk.eindberetningmobil_android.views.UploadingView; public class UploadingViewTest extends BaseTest<UploadingView> { @Override public void runBeforeGetActivity() { getSettings().setProfile(StaticData.createSimpleProfile()); } public UploadingViewTest() { super(UploadingView.class); } @Test public void testLayout() { solo.waitForView(R.id.uploading_view_image); getActivity().runOnUiThread(new Runnable() { @Override public void run() { getActivity().updateStatusText("asd-swag"); } }); TextView view = (TextView) solo.getView(R.id.upload_view_status_text); assertEquals(view.getText(), "asd-swag"); } }<|fim▁end|>
import org.junit.Test;
<|file_name|>DisassociateEnvironmentOperationsRoleRequest.java<|end_file_name|><|fim▁begin|>/* * Copyright 2017-2022 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://aws.amazon.com/apache2.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. */ package com.amazonaws.services.elasticbeanstalk.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Request to disassociate the operations role from an environment. * </p> * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DisassociateEnvironmentOperationsRole" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DisassociateEnvironmentOperationsRoleRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the environment from which to disassociate the operations role. * </p> */ private String environmentName; /** * <p> * The name of the environment from which to disassociate the operations role. * </p> * * @param environmentName * The name of the environment from which to disassociate the operations role. */ public void setEnvironmentName(String environmentName) { this.environmentName = environmentName; } /** * <p> * The name of the environment from which to disassociate the operations role. * </p> * * @return The name of the environment from which to disassociate the operations role. */ public String getEnvironmentName() { return this.environmentName; } /** * <p> * The name of the environment from which to disassociate the operations role. * </p> * * @param environmentName * The name of the environment from which to disassociate the operations role. * @return Returns a reference to this object so that method calls can be chained together. */ public DisassociateEnvironmentOperationsRoleRequest withEnvironmentName(String environmentName) { setEnvironmentName(environmentName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEnvironmentName() != null) sb.append("EnvironmentName: ").append(getEnvironmentName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DisassociateEnvironmentOperationsRoleRequest == false) return false; DisassociateEnvironmentOperationsRoleRequest other = (DisassociateEnvironmentOperationsRoleRequest) obj; if (other.getEnvironmentName() == null ^ this.getEnvironmentName() == null)<|fim▁hole|> return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEnvironmentName() == null) ? 0 : getEnvironmentName().hashCode()); return hashCode; } @Override public DisassociateEnvironmentOperationsRoleRequest clone() { return (DisassociateEnvironmentOperationsRoleRequest) super.clone(); } }<|fim▁end|>
return false; if (other.getEnvironmentName() != null && other.getEnvironmentName().equals(this.getEnvironmentName()) == false) return false;
<|file_name|>test_color.py<|end_file_name|><|fim▁begin|><|fim▁hole|> class TestColor(TestCase): def test_is_string(self): c = n.color("w") self.assertTrue(isinstance(c, tuple))<|fim▁end|>
from unittest import TestCase import neuropsydia as n n.start(open_window=False)
<|file_name|>commit_sync_config_utils.rs<|end_file_name|><|fim▁begin|>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use metaconfig_types::{DefaultSmallToLargeCommitSyncPathAction, SmallRepoCommitSyncConfig}; use mononoke_types::MPath;<|fim▁hole|>use std::collections::HashMap; pub struct SmallRepoCommitSyncConfigDiff { pub default_action_change: Option<( DefaultSmallToLargeCommitSyncPathAction, DefaultSmallToLargeCommitSyncPathAction, )>, pub mapping_added: HashMap<MPath, MPath>, pub mapping_changed: HashMap<MPath, (MPath, MPath)>, pub mapping_removed: HashMap<MPath, MPath>, } pub fn diff_small_repo_commit_sync_configs( from: SmallRepoCommitSyncConfig, to: SmallRepoCommitSyncConfig, ) -> SmallRepoCommitSyncConfigDiff { let default_action_change = if from.default_action == to.default_action { None } else { Some((from.default_action, to.default_action)) }; let mut mapping_added = HashMap::new(); let mut mapping_changed = HashMap::new(); let mut mapping_removed = HashMap::new(); for (from_small, from_large) in &from.map { match to.map.get(from_small) { Some(to_large) if from_large != to_large => { mapping_changed.insert(from_small.clone(), (from_large.clone(), to_large.clone())); } Some(_to_large) => { // nothing has changed } None => { mapping_removed.insert(from_small.clone(), from_large.clone()); } }; } for (to_small, to_large) in &to.map { if !from.map.contains_key(to_small) { mapping_added.insert(to_small.clone(), to_large.clone()); } } SmallRepoCommitSyncConfigDiff { default_action_change, mapping_added, mapping_changed, mapping_removed, } }<|fim▁end|>
<|file_name|>integration_parameters.rs<|end_file_name|><|fim▁begin|>use na::{self, RealField}; /// Parameters for a time-step of the physics engine. #[derive(Clone)] pub struct IntegrationParameters<N: RealField> { /// The timestep (default: `1.0 / 60.0`) dt: N, /// The inverse of `dt`. inv_dt: N, /// If `true`, the world's `step` method will stop right after resolving exactly one CCD event (default: `false`). /// This allows the user to take action during a timestep, in-between two CCD events. pub return_after_ccd_substep: bool, /// The total elapsed time in the physics world. /// /// This is the accumulation of the `dt` of all the calls to `world.step()`. pub t: N, /// The Error Reduction Parameter in `[0, 1]` is the proportion of /// the positional error to be corrected at each time step (default: `0.2`). pub erp: N, /// Each cached impulse are multiplied by this coefficient in `[0, 1]` /// when they are re-used to initialize the solver (default `1.0`). pub warmstart_coeff: N, /// Contacts at points where the involved bodies have a relative /// velocity smaller than this threshold wont be affected by the restitution force (default: `1.0`). pub restitution_velocity_threshold: N, /// Ammount of penetration the engine wont attempt to correct (default: `0.001m`). pub allowed_linear_error: N, /// Ammount of angular drift of joint limits the engine wont /// attempt to correct (default: `0.001rad`). pub allowed_angular_error: N, /// Maximum linear correction during one step of the non-linear position solver (default: `0.2`). pub max_linear_correction: N, /// Maximum angular correction during one step of the non-linear position solver (default: `0.2`). pub max_angular_correction: N, /// Maximum nonlinear SOR-prox scaling parameter when the constraint /// correction direction is close to the kernel of the involved multibody's /// jacobian (default: `0.2`). pub max_stabilization_multiplier: N, /// Maximum number of iterations performed by the velocity constraints solver (default: `8`). pub max_velocity_iterations: usize, /// Maximum number of iterations performed by the position-based constraints solver (default: `3`). pub max_position_iterations: usize, /// Maximum number of iterations performed by the position-based constraints solver for CCD steps (default: `10`). /// /// This should be sufficiently high so all penetration get resolved. For example, if CCD cause your /// objects to stutter, that may be because the number of CCD position iterations is too low, causing /// them to remain stuck in a penetration configuration for a few frames. /// /// The highest this number, the highest its computational cost. pub max_ccd_position_iterations: usize, /// Maximum number of substeps performed by the solver (default: `1`). pub max_ccd_substeps: usize, /// Controls the number of Proximity::Intersecting events generated by a trigger during CCD resolution (default: `false`). /// /// If false, triggers will only generate one Proximity::Intersecting event during a step, even /// if another colliders repeatedly enters and leaves the triggers during multiple CCD substeps. /// /// If true, triggers will generate as many Proximity::Intersecting and Proximity::Disjoint/Proximity::WithinMargin /// events as the number of times a collider repeatedly enters and leaves the triggers during multiple CCD substeps. /// This is more computationally intensive. pub multiple_ccd_substep_sensor_events_enabled: bool, /// Whether penetration are taken into account in CCD resolution (default: `false`). /// /// If this is set to `false` two penetrating colliders will not be considered to have any time of impact /// while they are penetrating. This may end up allowing some tunelling, but will avoid stuttering effect /// when the constraints solver fails to completely separate two colliders after a CCD contact. /// /// If this is set to `true`, two penetrating colliders will be considered to have a time of impact /// equal to 0 until the constraints solver manages to separate them. This will prevent tunnelling /// almost completely, but may introduce stuttering effects when the constraints solver fails to completely /// seperate two colliders after a CCD contact. // FIXME: this is a very binary way of handling penetration. // We should provide a more flexible solution by letting the user choose some // minimal amount of movement applied to an object that get stuck. pub ccd_on_penetration_enabled: bool, } impl<N: RealField> IntegrationParameters<N> { /// Creates a set of integration parameters with the given values. pub fn new( dt: N, erp: N, warmstart_coeff: N, restitution_velocity_threshold: N, allowed_linear_error: N, allowed_angular_error: N, max_linear_correction: N, max_angular_correction: N, max_stabilization_multiplier: N, max_velocity_iterations: usize, max_position_iterations: usize, max_ccd_position_iterations: usize, max_ccd_substeps: usize, return_after_ccd_substep: bool, multiple_ccd_substep_sensor_events_enabled: bool, ccd_on_penetration_enabled: bool, ) -> Self { IntegrationParameters { t: N::zero(), dt, inv_dt: if dt == N::zero() { N::zero() } else { N::one() / dt }, erp, warmstart_coeff, restitution_velocity_threshold, allowed_linear_error, allowed_angular_error, max_linear_correction, max_angular_correction, max_stabilization_multiplier, max_velocity_iterations, max_position_iterations, max_ccd_position_iterations, max_ccd_substeps, return_after_ccd_substep, multiple_ccd_substep_sensor_events_enabled, ccd_on_penetration_enabled, } } /// The current time-stepping length. #[inline(always)] pub fn dt(&self) -> N { self.dt } /// The inverse of the time-stepping length. /// /// This is zero if `self.dt` is zero. #[inline(always)] pub fn inv_dt(&self) -> N { self.inv_dt } /// Sets the time-stepping length. /// /// This automatically recompute `self.inv_dt`. #[inline] pub fn set_dt(&mut self, dt: N) { assert!( dt >= N::zero(), "The time-stepping length cannot be negative."<|fim▁hole|> } else { self.inv_dt = N::one() / dt } } /// Sets the inverse time-stepping length (i.e. the frequency). /// /// This automatically recompute `self.dt`. #[inline] pub fn set_inv_dt(&mut self, inv_dt: N) { self.inv_dt = inv_dt; if inv_dt == N::zero() { self.dt = N::zero() } else { self.dt = N::one() / inv_dt } } } impl<N: RealField> Default for IntegrationParameters<N> { fn default() -> Self { Self::new( na::convert(1.0 / 60.0), na::convert(0.2), na::convert(1.0), na::convert(1.0), na::convert(0.001), na::convert(0.001), na::convert(0.2), na::convert(0.2), na::convert(0.2), 8, 3, 10, 1, false, false, false, ) } }<|fim▁end|>
); self.dt = dt; if dt == N::zero() { self.inv_dt = N::zero()
<|file_name|>functions4.go<|end_file_name|><|fim▁begin|>package main import "fmt" func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } func main() { x, y := split(22)<|fim▁hole|><|fim▁end|>
fmt.Println(x, y) }
<|file_name|>my-service.js<|end_file_name|><|fim▁begin|>'use strict'; <|fim▁hole|> return 'Welcome to Strapi 🚀'; }, });<|fim▁end|>
module.exports = ({ strapi }) => ({ getWelcomeMessage() {
<|file_name|>RunDGEN.py<|end_file_name|><|fim▁begin|>import re import os import itertools import time from string import upper import ete3 import copy import subprocess from collections import defaultdict from sys import platform from scipy import stats from ete3 import Tree from natsort import natsorted from Bio import AlignIO """ Functions: ~ Chabrielle Allen Travis Benedict Peter Dulworth """ def run_saved_dgen(stat_file,sequence_files,window_size=999999999999999999999999999999, window_offset=999999999999999999999999999999, verbose=False, alpha=0.01, plot=False, meta=False): """ Creates a network tree based on the species tree and the two leaves to be connected. Inputs: inheritance --- inputted tuple containing inheritance probability ex. (0.7, 0.3) species_tree --- generated or inputted file or newick string network_map --- inputted mapping of leaves where nodes will be added Output: network --- a newick string network with the added nodes. """ #decided to do a rename here alignments = sequence_files # read in dgen stat from file # (have to wait for file to exist sometimes) while not os.path.exists(stat_file): time.sleep(1) with(open(stat_file, "r")) as s: lines = s.readlines() taxa = eval(lines[0].split(None, 1)[1]) stat_species_tree = lines[1].split(None, 2)[2].replace("\n", "") stat_species_network = lines[2].split(None, 2)[2].replace("\n", "") outgroup = lines[3].split(None, 1)[1].replace("\n", "") invariants = [] for oneInvLine in range(4,len(lines)): this_line_invariant_group = eval(lines[oneInvLine].split(None, 6)[6]) invariants.append(this_line_invariant_group) #increase = eval(lines[1].split(None, 2)[2]) #decrease = eval(lines[2].split(None, 2)[2]) #increase_resized = increase #decrease_resized = decrease #overall_coefficient = 1 #patterns_to_coeff = {} # DONE READING IN STATISTIC FROM FILE, RUN THE STAT #window_size = 5000 #window_offset = 5000 #verbose = True #alpha = 0.01 #alignments.append(sequence_file) alignments_to_windows_to_DGEN = calculate_windows_to_DGEN(alignments, taxa, outgroup, invariants, window_size, window_offset, verbose, alpha) # the lazy way to do alignments to d using same function and not having to rewrite a nearly identical function alignments_to_DGEN = calculate_windows_to_DGEN(alignments, taxa, outgroup, invariants, 999999999999999999999999999999, 999999999999999999999999999999, verbose, alpha) for alignment in alignments: alignments_to_DGEN[alignment] = alignments_to_DGEN[alignment][0] # print stuff s = "" for alignment in alignments: if verbose: dgen2_dof, significant_dgen, dgen2_num_ignored, dgen2_chisq, l_pval_dgen = alignments_to_DGEN[alignment] s += "\n" s += alignment + ": " + "\n" s += "\n" s += "(format = degrees of freedom, is significant?, num. of sites ignored, chi squared value, DGEN p value)" s += "\n" s += "Windows to D value: " + str(alignments_to_windows_to_DGEN[alignment]) + "\n" s += "\n" s += "Final Overall DGEN p value: {0}".format(l_pval_dgen) + "\n" s += "Significant p value: {0}".format(significant_dgen) + "\n" s += "\n" s += "(Verbose) Number Of Sites Ignored: {0}".format(dgen2_num_ignored) + "\n" s += "(Verbose) Degrees Of Freedom: {0}".format(dgen2_dof) + "\n" s += "(Verbose) ChiSquared Value: {0}".format(dgen2_chisq) + "\n" s += "\n" s += "For easy plotting of DGEN values:" s += "\n" windowIndex = 0 for windowEntryIndex in alignments_to_windows_to_DGEN[alignment]: s += str(windowIndex) + "," + str(alignments_to_windows_to_DGEN[alignment][windowEntryIndex][4]) + "\n" windowIndex += 1 else: l_pval_dgen, significant_dgen = alignments_to_DGEN[alignment] s += "\n" s += alignment + ": " + "\n" s += "\n" s += "(format = DGEN p value, is significant?)" s += "\n" s += "Windows to D value: " + str(alignments_to_windows_to_DGEN[alignment]) + "\n" s += "\n" s += "Final Overall DGEN p value: {0}".format(l_pval_dgen) + "\n" s += "Significant p value: {0}".format(significant_dgen) + "\n" # finally do one more output of just window#,dgen val for easy plotting s += "\n" s += "For easy plotting of DGEN values:" s += "\n" windowIndex = 0 for windowEntryIndex in alignments_to_windows_to_DGEN[alignment]: s += str(windowIndex) + "," + str(alignments_to_windows_to_DGEN[alignment][windowEntryIndex][0]) + "\n" windowIndex += 1 print s if plot: plot_formatting((alignments_to_DGEN, alignments_to_windows_to_DGEN), plot, meta) return s def calculate_windows_to_DGEN(alignments, taxa_order, outgroup, list_of_tree_and_net_invariants, window_size, window_offset, verbose= False, alpha=0.01): """ Calculates the DGEN statistic for the given alignment Input: alignment --- a sequence alignment in phylip format taxa_order --- the desired order of the taxa patterns_of_interest --- a tuple containing the sets of patterns used for determining a statistic window_size --- the desired window size windw_offset --- the desired offset between windows Output: l_stat --- the L statistic value windows_to_l --- a mapping of window indices to L statistic values """ # create a map that will map from all the patterns we care about to their counts pattern_count_map = defaultdict(int) for aLine in list_of_tree_and_net_invariants: for aPatternGroup in aLine: # technically could skip the first one or just use the first one for aPattern in aPatternGroup: pattern_count_map[aPattern] = 0 # Separate the patterns of interest into their two terms #terms1 = patterns_of_interest[0] #terms2 = patterns_of_interest[1] alignments_to_windows_to_d = {} for alignment in alignments: sequence_list = [] taxon_list = [] with open(alignment) as f: # Create a list of each line in the file lines = f.readlines() # First line contains the number and length of the sequences first_line = lines[0].split() length_of_sequences = int(first_line[1]) for line in lines[1:]: # Add each sequence to a list sequence = line.split()[1] sequence_list.append(sequence) # Add each taxon to a list taxon = line.split()[0] taxon_list.append(taxon) i = 0 num_windows = 0 if window_size > length_of_sequences: num_windows = 1 window_size = length_of_sequences else: # Determine the total number of windows needed while i + window_size - 1 < length_of_sequences: i += window_offset num_windows += 1 site_idx = 0 windows_to_l = {} # Iterate over each window for window in range(num_windows): terms1_counts = defaultdict(int) terms2_counts = defaultdict(int) num_ignored = 0 # Iterate over the indices in each window for window_idx in range(window_size): # Map each taxa to the base at a given site taxa_to_site = {} # Create a set of the bases at a given site to determine if the site is biallelic bases = set([]) # Iterate over each sequence in the alignment for sequence, taxon in zip(sequence_list, taxon_list): # Map each taxon to the corresponding base at the site # Add upper function to handle both lowercase and uppercase sequences identically (wasnt working for undercase sequences) base = upper(sequence[site_idx]) taxa_to_site[taxon] = base bases.add(base) # there are too many non ACTG letters allowed in fasta files, so i will just make sure bases only has A C T G possibleBases = set([]) possibleBases.add("A") possibleBases.add("C") possibleBases.add("G") possibleBases.add("T") # Statistic can only be calculated where the nucleotides are known # this includes things like -'s, but also N's, and I will now exclude anything but ACTG # if len(bases) == 2 and "-" not in bases and "N" not in bases: if len(bases) == 2 and bases.issubset(possibleBases): # Create the pattern that each site has site_pattern = [] # The ancestral gene is always the same as the outgroup ancestral = taxa_to_site[outgroup] # Iterate over each taxon for taxon in taxa_order: nucleotide = taxa_to_site[taxon] # Determine if the correct derived/ancestral status of each nucleotide if nucleotide == ancestral: site_pattern.append("A") else: site_pattern.append("B") # Convert the site pattern to a string sites = pattern_string_generator([site_pattern]) if sites: site_string = sites[0] # If the site string is a pattern of interest add to its count for one of the terms # add to my new DGEN map if site_string in pattern_count_map: pattern_count_map[site_string] += 1 #elif "-" in bases or "N" in bases: #(more can happen now, i will just check not in subset of possible bases elif bases.issubset(possibleBases) == False: num_ignored += 1 #final catch all else for ignored sites (forgot to add back in check for non biallelic (they were ignored but not counted in verbose output. this line now properly counts them for verbose mode)) #includes also sites that only have all A's or whatever, basically anything non strictly biallelic else: num_ignored += 1 #should i add count here for sites that specifically violate biallelic as in 3 or 4 dif letters? (len(bases)>2)? # Increment the site index site_idx += 1 # create counts based on tree / net invariant groupings list_of_tree_and_net_invariants_counts = [] for aLine in list_of_tree_and_net_invariants: lineAdd = [] for aPatternGroup in aLine: # technically could skip the first one or just use the first one groupCount = 0 for aPattern in aPatternGroup: groupCount += pattern_count_map[aPattern] lineAdd.append(groupCount) list_of_tree_and_net_invariants_counts.append(lineAdd) #for debugging, how many sites are actually observed that go into the observed calculations? # calculate new version of chi squared test # chi squared = sum of (obs - exp)^2 / exp # obs is Na and exp is Nt * |Na| / |Nt| chiSquared = 0 dof = 0 cCardinality = 0 for invariantIndex in range(0,len(list_of_tree_and_net_invariants)): treeGroupSize = len(list_of_tree_and_net_invariants[invariantIndex][0]) treeGroupCount = list_of_tree_and_net_invariants_counts[invariantIndex][0] cCardinality += 1 for oneNetInvariant in range(1,len(list_of_tree_and_net_invariants[invariantIndex])): netGroupSize = len(list_of_tree_and_net_invariants[invariantIndex][oneNetInvariant]) netGroupCount = list_of_tree_and_net_invariants_counts[invariantIndex][oneNetInvariant] chiNumerator = (netGroupCount - (treeGroupCount * (netGroupSize / float(treeGroupSize)))) ** 2 # apparently 'python will return a float if at least one number in an equation is a float'. apparently this is not actually true as making just the first term here a float does not work chiDenominator = treeGroupCount * (netGroupSize / float(treeGroupSize)) if chiDenominator != 0: # handles the case where zero counts cause 0 in the denominator chiSquared += chiNumerator / float(chiDenominator) else: chiSquared = 0.0 dof += 1 #final dof is one less than this total (woops >.<) #dof = dof - 1 (not any more, totally changing the formulation now based on luays comments) #newest sum|Y| - |C| DoF calc. at this point in the code, dof stores the sum|Y| value #so i have made a new variable for |C| and i just take the difference dof = dof - cCardinality # determine if the chisquared is significant. ALSO NOTE - dispensing with the 'd value' and just looking at chiSq and pval # Verbose output if verbose: signif, chisq, pval = calculate_significance_custom_dof(chiSquared, dof, verbose, alpha) # The line below can be changed to add more information to the windows to L mapping #windows_to_l[window] = (l_stat, signif, num_ignored, chisq, pval) windows_to_l[window] = (dof, signif, num_ignored, chisq, pval) # Standard output else: signif, pval = calculate_significance_custom_dof(chiSquared, dof, verbose, alpha) windows_to_l[window] = (pval, signif) # Account for overlapping windows site_idx += (window_offset - window_size) alignments_to_windows_to_d[alignment] = windows_to_l return alignments_to_windows_to_d def Create_Network_Helper(species_tree, reticulations, inheritanceProb): """ leo - making a slightly more user friendly fucntion for this (dont need to input a tuple and maybe other things) Creates a network tree based on the species tree and the two leaves to be connected. Inputs: inheritance --- inputted single containing inheritance probability ex. (0.7, 0.3) species_tree --- generated or inputted file or newick string network_map --- inputted mapping of leaves where nodes will be added Output: network --- a newick string network with the added nodes. """ inheritance = (inheritanceProb, 1 - float(inheritanceProb)) #inheritance[0] = inheritanceProb #inheritance[1] = 1 - float(inheritanceProb) # check for a species tree file if os.path.isfile(species_tree): with open(species_tree) as f: network = f.readline() # check for a species tree string else: network = species_tree for i in range(len(reticulations)): # get taxa for the edge in the network start = reticulations[i][0] end = reticulations[i][1] # add nodes into tree in proper format #network = network.replace(start, '((' + start + ')#H' + str(i+1) + ':0::' + str(inheritance[0]) + ')') # one too many paranthesis here apparently network = network.replace(start, '(' + start + ')#H' + str(i + 1) + ':0::' + str(inheritance[0]) + '') # took a paranthesis off network = network.replace(end, '(#H' + str(i+1) + ':0::' + str(inheritance[1]) + ',' + end + ')') return network def generate_network_tree(inheritance, species_tree, reticulations): """ Creates a network tree based on the species tree and the two leaves to be connected. Inputs: inheritance --- inputted tuple containing inheritance probability ex. (0.7, 0.3) species_tree --- generated or inputted file or newick string network_map --- inputted mapping of leaves where nodes will be added Output: network --- a newick string network with the added nodes. """ # check for a species tree file if os.path.isfile(species_tree): with open(species_tree) as f: network = f.readline() # check for a species tree string else: network = species_tree for i in range(len(reticulations)): # get taxa for the edge in the network start = reticulations[i][0] end = reticulations[i][1] # add nodes into tree in proper format network = network.replace(start, '((' + start + ')#H' + str(i+1) + ':0::' + str(inheritance[0]) + ')') network = network.replace(end, '(#H' + str(i+1) + ':0::' + str(inheritance[1]) + ',' + end + ')') return network ##### Generate all unique trees functions def genDistinct(n): """ Generate all full binary trees with n leaves Input: n --- the number of leaves Output: dp[-1] --- the set of all full binary trees with n nodes """ leafnode = '(.)' dp = [] newset = set() newset.add(leafnode) dp.append(newset) for i in range(1, n): newset = set() for j in range(i): for leftchild in dp[j]: for rightchild in dp[i - j - 1]: newset.add('(' + '.' + leftchild + rightchild + ')') dp.append(newset) return dp[-1] def generate_all_trees(taxa): """ Create all trees given a set of taxa Inputs: taxa --- a set of the taxa to be used for leaf names Output: trees --- the set of all trees over the taxa """ # Regex pattern for identifying leaves next to a clade in newick string pattern = "([\)][a-zA-Z0-9_.-])" # Generate all distinct binary trees trees = genDistinct(len(taxa)) # Get all possible permutations of the taxa taxa_orders = itertools.permutations(taxa) taxa_orders = list(taxa_orders) all_trees = [] # Iterate over each tree in the set for tree in trees: # Reformat the tree tree = tree.replace('.', '') # Iterate over each permutation of taxa for taxa_perm in taxa_orders: # Create a copy of the tree bi_tree = tree # replace the leaves with taxons and reformat string for i in range(len(taxa_perm)): taxon = taxa_perm[i] + "," bi_tree = bi_tree.replace("()", taxon, 1) bi_tree = bi_tree.replace(",)", ")") # Find all instances of a ")" followed by a taxon and add a "," between clades = re.findall(pattern, bi_tree) for clade in clades: taxon = clade[1] bi_tree = bi_tree.replace(clade, ")," + taxon) bi_tree = bi_tree.replace(")(", "),(") bi_tree = bi_tree + ";" all_trees.append(bi_tree) return all_trees def generate_unique_trees(taxa, outgroup): """ Generate the set of unique trees over a set of taxa with an outgroup Inputs: taxa --- a list of taxa to be used as the leaves of trees outgroup --- the outgroup to root at Output: unique_newicks --- a set of all unique topologies over the given taxa """ # Create a set for unique trees unique_trees = set([]) unique_newicks = set([]) all_trees = generate_all_trees(taxa) # Iterate over each tree in all_trees for tree in all_trees: tree = Tree(tree) tree.set_outgroup(outgroup) is_unique = True # Iterate the unique trees for comparison for unique_tree in unique_trees: # Compute robinson-foulds distance rf_distance = tree.robinson_foulds(unique_tree)[0] # If rf distance is 0 the tree is not unique if rf_distance == 0: is_unique = False if is_unique: unique_trees.add(tree) # Iterate over the trees for tree in unique_trees: # Get newick strings from the tree objects tree = tree.write() # Get rid of branch lengths in the newick strings tree = branch_removal(tree) tree = outgroup_reformat(tree, outgroup) # Add the newick strings to the set of unique newick strings unique_newicks.add(tree) return unique_newicks ###### Statistics Calculations Functions def calculate_pgtst(species_tree, gene_tree): """ Calculate p(gt|st) or p(gt|sn) Input: species_tree --- a species tree or network in newick format gene_tree --- a gene tree in newick format Output: pgtst --- p(gt|st) or p(gt|sn) """ # Get the global path name to the jar file dir_path = os.path.dirname(os.path.realpath(__file__)) j = os.path.join(dir_path, "Unstable.jar") # Run PhyloNet p(g|S) jar file p = subprocess.Popen("java -jar {0} {1} {2}".format(j, species_tree, gene_tree), stdout=subprocess.PIPE, shell=True) # Read output and convert to float pgtst = float(p.stdout.readline()) return pgtst def calculate_newicks_to_stats(species_tree, species_network, unique_trees): """ Compute p(g|S) and p(g|N) for each g in unique_trees and map the tree newick string to those values Inputs: species_tree --- the species tree newick string for the taxa species_network --- the network newick string derived from adding a branch to the species tree between the interested taxa unique_trees --- the set of all unique topologies over n taxa outgroup --- the outgroup Output: trees_to_pgS--- a mapping of tree newick strings to their p(g|S) values trees_to_pgN--- a mapping of tree newick strings to their p(g|N) values """ trees_to_pgS = {} trees_to_pgN = {} if platform == 'darwin': # macs need single quotes for some reason species_tree = str(species_tree) species_tree = "'" + species_tree + "'" species_network = str(species_network) species_network = "'" + species_network + "'" # Iterate over the trees for tree in unique_trees: if platform == 'darwin': # macs need single quotes for some reason tree = "'" + tree + "'" p_of_g_given_s = calculate_pgtst(species_tree, tree) p_of_g_given_n = calculate_pgtst(species_network, tree) if platform == 'darwin': # remove the quotes from the tree before we add it to the mapping tree = tree[1:-1] trees_to_pgS[tree] = p_of_g_given_s trees_to_pgN[tree] = p_of_g_given_n return trees_to_pgS, trees_to_pgN ##### Site Pattern Functions def outgroup_reformat(newick, outgroup): """ Move the location of the outgroup in a newick string to be at the end of the string Inputs: newick --- a newick string to be reformatted outgroup --- the outgroup Output: newick --- the reformatted string """ # Replace the outgroup and comma with an empty string newick = newick.replace(outgroup + ",", "") newick = newick[:-2] + "," + outgroup + ");" return newick def pattern_inverter(patterns): """ Switches "A"s to "B"s and "B"s to "A" in a site pattern excluding the outgroup Inputs: patterns --- a list of site patterns Output: inverted --- a list of the inverted patterns """ inverted = [] # Iterate over the patterns for pattern in patterns: a_count = 0 b_count = 0 inverted_pattern = [] # Iterate over each site in the pattern for site in pattern: if site == "A": inverted_pattern.append("B") b_count += 1 elif site == "B": inverted_pattern.append("A") a_count += 1 if inverted_pattern[-1] != "A": # Change the last site to an "A" inverted_pattern[-1] = "A" b_count -= 1 a_count += 1 if a_count > 1 and b_count > 0: inverted.append(inverted_pattern) return inverted def pattern_string_generator(patterns): """ Creates a list of viable pattern strings that are easier to read Input: patterns --- a list of lists of individual characters e.g. [["A","B","B","A"],["B","A","B","A"]] Output: pattern_strings --- a list of lists of strings e.g. [["ABBA"],["BABA"]] """ # Convert the site pattern lists to strings pattern_strings = [] while patterns: a_count = 0 b_count = 0 pattern_str = "" pattern = patterns.pop() for site in pattern: if site == "A": b_count += 1 elif site == "B": a_count += 1 pattern_str += site if a_count > 0 and b_count > 0: pattern_strings.append(pattern_str) return pattern_strings def branch_removal(n): """ Remove the branch lengths from an inputted newick string Input: n --- a newick string Output: n --- the reformatted string """ float_pattern = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])" # Regular expressions for removing branch lengths and confidence values pattern2 = "([\:][\\d])" pattern3 = "([\)][\\d])" # Get rid of branch lengths in the newick strings n = (re.sub(float_pattern, '', n)) n = (re.sub(pattern2, '', n)).replace(":", "") n = (re.sub(pattern3, ')', n)) return n def site_pattern_generator(taxa_order, newick, outgroup): """ Generate the appropriate AB list patterns Inputs: taxa_order --- the desired order of the taxa newick --- the newick string to generate site patterns for outgroup --- the outgroup of the tree Output: finished_patterns --- the list of site patterns generated for the newick string """ # Create a tree object tree = ete3.Tree(newick, format=1) tree.ladderize(direction=1) tree.set_outgroup(outgroup) # Initialize containers for the final patterns and patterns being altered final_site_patterns = [] # Keep a count of clades in the tree that contain 2 leaves clade_count = 0 # Number of possible patterns is number of taxa - 2 + the number of clades num_patterns = len(taxa_order) - 2 # Initialize pattern to be a list of strings pattern = ["B" for x in range(len(taxa_order))] # Create list of nodes in order of appearance nodes = [] for node in tree.traverse("preorder"): # Add node name to list of nodes nodes.append(node.name) # If there are internal nodes at the second and third position travel over the tree in postorder if nodes[2] == "" and nodes[3] == "": nodes = [] for node in tree.traverse("postorder"): # Add node name to list of nodes nodes.append(node.name) # Keep track of visited leaves seen_leaves = [] # Iterate over the order that the nodes occur beginning at the root for node_idx in range(len(nodes)): node = nodes[node_idx] # If the node is the outgroup add A to the end of the pattern if node == outgroup: pattern[-1] = "A" # Add outgroup to the seen leaves seen_leaves.append(node) elif outgroup not in seen_leaves: pass # Else if the node is a leaf and is after the outgroup elif node != "" and seen_leaves[-1] == outgroup and outgroup in seen_leaves: # If the next node is a leaf a clade has been found if nodes[node_idx + 1] != "": node2 = nodes[node_idx + 1] # Get the indices of the leaves in the pattern pat_idx1 = taxa_order.index(node) pat_idx2 = taxa_order.index(node2) # Set those pattern indices to "A" pattern[pat_idx1] = "A" pattern[pat_idx2] = "A" clade_count += 1 final_site_patterns.append(pattern) seen_leaves.append(node) seen_leaves.append(node2) # Get the index that final clade occurs at end_idx = node_idx + 1 break # Otherwise there is no clade else: # Get the index of the leaf in the pattern pat_idx = taxa_order.index(node) # Set those pattern indices to "A" pattern[pat_idx] = "A" seen_leaves.append(node) # Get the index that final leaf occurs at end_idx = node_idx break num_patterns = num_patterns + clade_count # All patterns can be derived from the pattern with the most B's working_patterns = [pattern for x in range(num_patterns)] # Pop a pattern off of working patterns and add it to the final site patterns final_site_patterns.append(working_patterns.pop()) # Iterate over each pattern in working patterns and change them while working_patterns: # Get a pattern and copy it pattern = copy.deepcopy(working_patterns.pop()) # Iterate over the order that the nodes occur beginning at the last clade or leaf for node_idx in range(end_idx + 1, len(nodes)): # If the last clade is reached break if node_idx == len(nodes) - 1: if node != "": # Get the index of the leaf in the pattern pat_idx1 = taxa_order.index(node) # Set those pattern indices to "A" pattern[pat_idx1] = "A" # Get the index that final leaf occurs at end_idx = node_idx break else: break node = nodes[node_idx] # If the next node is a leaf a clade has been found if node != "" and nodes[node_idx + 1] != "": node2 = nodes[node_idx + 1] # Get the indices of the leaves in the pattern pat_idx1 = taxa_order.index(node) pat_idx2 = taxa_order.index(node2) # Set those pattern indices to "A" pattern[pat_idx1] = "A" pattern[pat_idx2] = "A" clade_count += 1 final_site_patterns.append(pattern) # Get the index that final clade occurs at end_idx = node_idx + 1 break # Else if the node is a leaf elif node != "": # Get the index of the leaf in the pattern pat_idx1 = taxa_order.index(node) # Set those pattern indices to "A" pattern[pat_idx1] = "A" # Get the index that final leaf occurs at end_idx = node_idx break # Add the altered pattern to the final site patterns final_site_patterns.append(pattern) # Update the working patterns to be the same as the most recent pattern working_patterns = [pattern for x in range(num_patterns - len(final_site_patterns))] # Create a list of patterns without duplicates finished_patterns = [] # Iterate over each pattern and determine which ones are duplicates for pattern in final_site_patterns: if pattern not in finished_patterns: finished_patterns.append(pattern) # If a site pattern only has a single B consider it as the inverse for pattern in finished_patterns: if b_count(pattern) == 1: finished_patterns.remove(pattern) new_pattern = pattern_inverter([pattern])[0] finished_patterns.append(new_pattern) # Always do calculation with the inverse patterns inverted_patterns = pattern_inverter(finished_patterns) # Iterate over the inverted patterns and add them to finished patterns for pattern in inverted_patterns: if pattern not in finished_patterns: finished_patterns.append(pattern) finished_patterns = pattern_string_generator(finished_patterns) inverted_patterns = pattern_string_generator(inverted_patterns) return finished_patterns, inverted_patterns def newicks_to_patterns_generator(taxa_order, newicks, outgroup): """ Generate the site patterns for each newick string and map the strings to their patterns Inputs: taxa_order --- the desired order of the taxa newicks --- a list of newick strings Output: newicks_to_patterns --- a mapping of newick strings to their site patterns """ newicks_to_patterns = {} inverse_to_counts = defaultdict(int) # Iterate over the newick strings for newick in newicks: # Get the total set of site patterns and the inverses all_patterns, inverses = site_pattern_generator(taxa_order, newick, outgroup) newicks_to_patterns[newick] = all_patterns # Count the number of times a site pattern appears as an inverse for pattern in inverses: inverse_to_counts[pattern] += 1 return newicks_to_patterns, inverse_to_counts ##### Interesting sites functions def calculate_pattern_probabilities(newicks_to_patterns, newicks_to_pgS, newicks_to_pgN): """ Creates a mapping of site patterns to their total p(g|S) values across all gene trees and a mapping of site patterns to their total p(g|N) values across all gene trees Inputs: newicks_to_patterns --- a mapping of tree newick strings to their site patterns newicks_to_pgS--- a mapping of tree newick strings to their p(g|S) values newicks_to_pgN--- a mapping of tree newick strings to their p(g|N) values Outputs: patterns_to_pgS --- a mapping of site patterns to their total p(g|S) value patterns_to_pgN --- a mapping of site patterns to their total p(g|N) value """ patterns_to_pgS = defaultdict(float) patterns_to_pgN = defaultdict(float) # Iterate over each newick string for newick in newicks_to_patterns: # Iterate over each site pattern of a tree for pattern in newicks_to_patterns[newick]: patterns_to_pgS[pattern] += newicks_to_pgS[newick] patterns_to_pgN[pattern] += newicks_to_pgN[newick] return patterns_to_pgS, patterns_to_pgN def determine_patterns(pattern_set, patterns_to_equality, patterns_to_pgN, patterns_to_pgS, use_inv): """ Determine which patterns are useful in determining introgression Inputs: pattern_set -- a set containing all patterns of interest patterns_to_equality --- a mapping of site patterns to site patterns with equivalent p(gt|st) patterns_to_pgN --- a mapping of site patterns to their total p(g|N) value for a network patterns_to_pgS --- a mapping of site patterns to their total p(g|st) Outputs: terms1 --- set of patterns to count whose probabilities increase under introgression terms2 --- set of patterns to count whose probabilities decrease under introgression """ terms1 = set([]) terms2 = set([]) # Iterate over each pattern to determine the terms of interest for pattern1 in pattern_set: pat1_prob = patterns_to_pgN[pattern1] if pattern1 in patterns_to_equality.keys(): for pattern2 in patterns_to_equality[pattern1]: pat2_prob = patterns_to_pgN[pattern2] # Issues with randomness when very small values are close but not technically equal if not approximately_equal(pat1_prob, pat2_prob): if pat1_prob > pat2_prob: terms1.add(pattern1) terms2.add(pattern2) elif pat1_prob < pat2_prob: terms1.add(pattern2) terms2.add(pattern1) terms1_resized, terms2_resized = resize_terms(terms1, terms2, patterns_to_pgS, use_inv) patterns_to_coefficients = scale_terms(terms1, terms2, patterns_to_pgS) return terms1, terms2, terms1_resized, terms2_resized, patterns_to_coefficients def resize_terms(terms1, terms2, patterns_to_pgS, use_inv): """ Resize the terms to ensure that the probabilities are the same on both sides. This is necessary to maintain the null hypothesis that D = 0 under no introgression. Inputs: terms1 --- a set of patterns to count and add to each other to determine introgression terms2 --- a set of other patterns to count and add to each other to determine introgression use_inv --- boolean for determining if inverse site patterns will be used patterns_to_pgS --- a mapping of site patterns to their p(gt|st) values<|fim▁hole|> Outputs: terms1 --- a set of patterns to count and add to each other to determine introgression terms2 --- a set of other patterns to count and add to each other to determine introgression """ terms1 = list(terms1) terms2 = list(terms2) # Create a mapping of pgtst to trees for each term pgtst_to_trees1 = defaultdict(set) pgtst_to_trees2 = defaultdict(set) for tree in terms1: # Round the probability to the 15th digit to prevent the randomness issues with small values prob = float(format(patterns_to_pgS[tree], '.15f')) pgtst_to_trees1[prob].add(tree) for tree in terms2: # Round the probability to the 15th digit to prevent the randomness issues with small values prob = float(format(patterns_to_pgS[tree], '.15f')) pgtst_to_trees2[prob].add(tree) # Balance terms terms1_prob_counts = defaultdict(int) terms2_prob_counts = defaultdict(int) # Round each probability and count the number of times it occurs for tree in terms1: prob = float(format(patterns_to_pgS[tree], '.15f')) terms1_prob_counts[prob] += 1 for tree in terms2: prob = float(format(patterns_to_pgS[tree], '.15f')) terms2_prob_counts[prob] += 1 # Iterate over each probability for prob in terms1_prob_counts: # Get the number of times each probability occurs count1, count2 = terms1_prob_counts[prob], terms2_prob_counts[prob] removed = set([]) # The number of site patterns to remove is the difference in counts num_remove = abs(count2 - count1) if use_inv: # If not using inverses remove the inverse along with the normal pattern num_remove = num_remove / 2 # If probabilities do not occur an equal number of times remove site patterns until they do if count1 > count2: for i in range(num_remove): # Get a pattern to remove and remove it from the possible removals r = sorted(list(pgtst_to_trees1[prob])).pop(0) pgtst_to_trees1[prob].remove(r) removed.add(r) terms1_remove = True if count1 < count2: for i in range(num_remove): # Get a pattern to remove and remove it from the possible removals r = sorted(list(pgtst_to_trees2[prob])).pop(0) pgtst_to_trees2[prob].remove(r) removed.add(r) terms1_remove = False if use_inv: # Remove site patterns and their inverses rm = set([]) inv_rm = pattern_inverter(removed) for pattern in inv_rm: rm.add(''.join(pattern)) removed = removed.union(rm) # Iterate over each pattern to be removed and remove it for pattern in removed: if terms1_remove: terms1.remove(pattern) else: terms2.remove(pattern) terms1, terms2 = tuple(terms1), tuple(terms2) return terms1, terms2 def scale_terms(terms1, terms2, patterns_to_pgS): """ Multiply the terms by a scalar to ensure that the probabilities are the same on both sides. This is necessary to maintain the null hypothesis that D = 0 under no introgression. Inputs: terms1 --- a set of patterns to count and add to each other to determine introgression terms2 --- a set of other patterns to count and add to each other to determine introgression patterns_to_pgS --- a mapping of site patterns to their p(gt|st) values Outputs: patterns_to_coefficient --- a mapping of site patterns to a coefficent to multiply their counts by """ terms1 = list(terms1) terms2 = list(terms2) # Create a mapping of pgtst to trees for each term pgtst_to_trees1 = defaultdict(set) pgtst_to_trees2 = defaultdict(set) patterns_to_coefficient = {} for tree in terms1: prob = float(format(patterns_to_pgS[tree], '.15f')) pgtst_to_trees1[prob].add(tree) for tree in terms2: prob = float(format(patterns_to_pgS[tree], '.15f')) pgtst_to_trees2[prob].add(tree) # Balance terms terms1_prob_counts = defaultdict(int) terms2_prob_counts = defaultdict(int) # Round each probability and count the number of times it occurs for tree in terms1: prob = float(format(patterns_to_pgS[tree], '.15f')) terms1_prob_counts[prob] += 1 for tree in terms2: prob = float(format(patterns_to_pgS[tree], '.15f')) terms2_prob_counts[prob] += 1 # Iterate over each probability for prob in terms1_prob_counts: # Get the number of times each probability occurs count1, count2 = terms1_prob_counts[prob], terms2_prob_counts[prob] # Get the patterns in the left set of terms corresponding the probability patterns1 = pgtst_to_trees1[prob] # Multiply each term in terms1 by count2 / count1 for pattern in patterns1: patterns_to_coefficient[pattern] = float(count2) / count1 return patterns_to_coefficient def generate_statistic_string(patterns_of_interest): """ Create a string representing the statistic for determining introgression like "(ABBA - BABA)/(ABBA + BABA)" Input: patterns_of_interest --- a tuple containing the sets of patterns used for determining a statistic Output: L_statistic --- a string representation of the statistic """ calculation = [] # Iterate over each set of patterns for pattern_set in patterns_of_interest: term = "(" # Combine each term with a "+" for pattern in sorted(pattern_set): term = term + pattern + " + " term = term[:-3] + ")" calculation.append(term) L_statistic = "({0} - {1}) / ({0} + {1})".format(calculation[0], calculation[1]) return L_statistic ##### Function for calculating statistic def calculate_significance_custom_dof(chiSqValue, dofValue, verbose, alpha): """ Determines statistical significance based on a chi-squared goodness of fit test Input: left --- the total count for site patterns in the left term of the statistic right --- the total count for site patterns in the right term of the statistic verbose --- a boolean corresponding to a verbose output alpha --- the significance level Output: significant --- a boolean corresponding to whether or not the result is statistically significant """ # Calculate the test statistic # if left + right > 0: # chisq = abs((left - right)**2 / float(left + right)) # else: # chisq = 0 # Calculate the p-value based on a chi square distribution with df = 1 # pval = 1 - stats.chi2.cdf(chisq, 1) chiSquaredDistVal = stats.chi2.cdf(chiSqValue, dofValue) pval = 1 - chiSquaredDistVal if pval < alpha: signif = True else: signif = False if verbose: return signif, chiSqValue, pval else: return signif, pval def calculate_significance(left, right, verbose, alpha): """ Determines statistical significance based on a chi-squared goodness of fit test Input: left --- the total count for site patterns in the left term of the statistic right --- the total count for site patterns in the right term of the statistic verbose --- a boolean corresponding to a verbose output alpha --- the significance level Output: significant --- a boolean corresponding to whether or not the result is statistically significant """ # Calculate the test statistic if left + right > 0: chisq = abs((left - right)**2 / float(left + right)) else: chisq = 0 # Calculate the p-value based on a chi square distribution with df = 1 pval = 1 - stats.chi2.cdf(chisq, 1) if pval < alpha: signif = True else: signif = False if verbose: return signif, chisq, pval else: return signif def calculate_L(alignments, taxa_order, outgroup, patterns_of_interest, verbose, alpha, patterns_of_interest_resized, overall_coefficient=1, patterns_to_coefficients={}): """ Calculates the L statistic for the given alignment Input: alignments --- a list of sequence alignment in phylip format taxa_order --- the desired order of the taxa patterns_of_interest --- a tuple containing the sets of patterns used for determining a statistic verbose --- a booolean if more output information is desired alpha --- the significance value patterns_of_interest_resized --- the patterns of interest after block resizing overall_coefficient --- the probability coefficient used to maintain the null hypothesis patterns _to_coefficients --- a mapping of site patterns to coefficients needed to maintain the null Output: l_stat --- the L statistic value significant --- a boolean denoting if the l_stat value is statistically significant """ # Separate the patterns of interest into their two terms terms1 = patterns_of_interest[0] terms2 = patterns_of_interest[1] # Do the same for the resized terms terms1_resized = patterns_of_interest_resized[0] terms2_resized = patterns_of_interest_resized[1] # Create a mapping for each generalized D type alignments_to_d_resized = {} alignments_to_d_pattern_coeff = {} alignments_to_d_ovr_coeff = {} for alignment in alignments: # Initialize these things for all files terms1_counts = defaultdict(int) terms2_counts = defaultdict(int) terms1_counts_resized = defaultdict(int) terms2_counts_resized = defaultdict(int) sequence_list = [] taxon_list = [] with open(alignment) as f: # Create a list of each line in the file lines = f.readlines() # First line contains the number and length of the sequences first_line = lines[0].split() length_of_sequences = int(first_line[1]) for line in lines[1:]: # Add each sequence to a list sequence = line.split()[1] sequence_list.append(sequence) # Add each taxon to a list taxon = line.split()[0] taxon_list.append(taxon) length_of_sequences = len(min(sequence_list, key=len)) num_ignored = 0 # Iterate over the site indices for site_idx in range(length_of_sequences): # Map each taxa to the base at a given site taxa_to_site = {} # Create a set of the bases at a given site to determine if the site is biallelic bases = set([]) # Iterate over each sequence in the alignment for sequence, taxon in zip(sequence_list, taxon_list): # Map each taxon to the corresponding base at the site base = sequence[site_idx] taxa_to_site[taxon] = base bases.add(base) # Statistic can only be calculated where the nucleotides are known if "-" not in bases and "N" not in bases and len(bases) == 2: # Create the pattern that each site has site_pattern = [] # The ancestral gene is always the same as the outgroup ancestral = taxa_to_site[outgroup] # Iterate over each taxon for taxon in taxa_order: nucleotide = taxa_to_site[taxon] # Determine if the correct derived/ancestral status of each nucleotide if nucleotide == ancestral: site_pattern.append("A") else: site_pattern.append("B") sites = pattern_string_generator([site_pattern]) if sites: site_string = sites[0] # If the site string is a pattern of interest add to its count for one of the terms if site_string in terms1: terms1_counts[site_string] += 1 if site_string in terms2: terms2_counts[site_string] += 1 if site_string in terms1_resized: terms1_counts_resized[site_string] += 1 if site_string in terms2_resized: terms2_counts_resized[site_string] += 1 elif "-" in bases or "N" in bases: num_ignored += 1 terms1_total = sum(terms1_counts.values()) terms2_total = sum(terms2_counts.values()) terms1_total_resized = sum(terms1_counts_resized.values()) terms2_total_resized = sum(terms2_counts_resized.values()) # Calculate the generalized d for the block resizing method numerator_resized = terms1_total_resized - terms2_total_resized denominator_resized = terms1_total_resized + terms2_total_resized if denominator_resized != 0: l_stat_resized = numerator_resized / float(denominator_resized) else: l_stat_resized = 0 # Calculate the generalized d for the total coefficient method numerator_ovr_coeff = (overall_coefficient * terms1_total) - terms2_total denominator_ovr_coeff = (overall_coefficient * terms1_total) + terms2_total if denominator_ovr_coeff != 0: l_stat_ovr_coeff = numerator_ovr_coeff / float(denominator_ovr_coeff) else: l_stat_ovr_coeff = 0 # Calculate the generalized d for the pattern coefficient method weighted_terms1_total, weighted_counts = weight_counts(terms1_counts, patterns_to_coefficients) numerator_pattern_coeff = weighted_terms1_total - terms2_total denominator_pattern_coeff = weighted_terms1_total + terms2_total if denominator_pattern_coeff != 0: l_stat_pattern_coeff = numerator_pattern_coeff / float(denominator_pattern_coeff) else: l_stat_pattern_coeff = 0 # Verbose output if verbose: significant, chisq, pval = calculate_significance(terms1_total_resized, terms2_total_resized, verbose, alpha) alignments_to_d_resized[ alignment] = l_stat_resized, significant, terms1_counts_resized, terms2_counts_resized, num_ignored, chisq, pval significant, chisq, pval = calculate_significance(weighted_terms1_total, terms2_total, verbose, alpha) alignments_to_d_pattern_coeff[ alignment] = l_stat_pattern_coeff, significant, weighted_counts, terms2_counts, num_ignored, chisq, pval significant, chisq, pval = calculate_significance(overall_coefficient * terms1_total, terms2_total, verbose, alpha) alignments_to_d_ovr_coeff[ alignment] = l_stat_ovr_coeff, significant, terms1_counts, terms2_counts, num_ignored, chisq, pval, overall_coefficient # Standard output else: significant = calculate_significance(terms1_total_resized, terms2_total_resized, verbose, alpha) alignments_to_d_resized[ alignment] = l_stat_resized, significant significant = calculate_significance(weighted_terms1_total, terms2_total, verbose, alpha) alignments_to_d_pattern_coeff[ alignment] = l_stat_pattern_coeff, significant significant = calculate_significance(overall_coefficient * terms1_total, terms2_total, verbose,alpha) alignments_to_d_ovr_coeff[ alignment] = l_stat_ovr_coeff, significant return alignments_to_d_resized, alignments_to_d_pattern_coeff, alignments_to_d_ovr_coeff def weight_counts(term_counts, patterns_to_coefficients): """ Inputs: term_counts --- a mapping of terms to their counts patterns_to_coefficients --- a mapping of site patterns to coefficients needed to maintain the null Output: weighted_total --- the total counts for the site patterns weighted """ # Create a mapping of patterns to their weighted counts weighted_counts = {} # Iterate over each pattern for pattern in term_counts: # Weight its count based on the coefficient if pattern in patterns_to_coefficients: coefficient = patterns_to_coefficients[pattern] else: coefficient = 1 count = term_counts[pattern] weighted_counts[pattern] = count * coefficient weighted_total = sum(weighted_counts.values()) return weighted_total, weighted_counts def calculate_windows_to_L(alignments, taxa_order, outgroup, patterns_of_interest, window_size, window_offset, verbose= False, alpha=0.01): """ Calculates the L statistic for the given alignment Input: alignment --- a sequence alignment in phylip format taxa_order --- the desired order of the taxa patterns_of_interest --- a tuple containing the sets of patterns used for determining a statistic window_size --- the desired window size windw_offset --- the desired offset between windows Output: l_stat --- the L statistic value windows_to_l --- a mapping of window indices to L statistic values """ # Separate the patterns of interest into their two terms terms1 = patterns_of_interest[0] terms2 = patterns_of_interest[1] alignments_to_windows_to_d = {} for alignment in alignments: sequence_list = [] taxon_list = [] with open(alignment) as f: # Create a list of each line in the file lines = f.readlines() # First line contains the number and length of the sequences first_line = lines[0].split() length_of_sequences = int(first_line[1]) for line in lines[1:]: # Add each sequence to a list sequence = line.split()[1] sequence_list.append(sequence) # Add each taxon to a list taxon = line.split()[0] taxon_list.append(taxon) i = 0 num_windows = 0 if window_size > length_of_sequences: num_windows = 1 window_size = length_of_sequences else: # Determine the total number of windows needed while i + window_size - 1 < length_of_sequences: i += window_offset num_windows += 1 site_idx = 0 windows_to_l = {} # Iterate over each window for window in range(num_windows): terms1_counts = defaultdict(int) terms2_counts = defaultdict(int) num_ignored = 0 # Iterate over the indices in each window for window_idx in range(window_size): # Map each taxa to the base at a given site taxa_to_site = {} # Create a set of the bases at a given site to determine if the site is biallelic bases = set([]) # Iterate over each sequence in the alignment for sequence, taxon in zip(sequence_list, taxon_list): # Map each taxon to the corresponding base at the site base = sequence[site_idx] taxa_to_site[taxon] = base bases.add(base) # Statistic can only be calculated where the nucleotides are known if "-" not in bases and len(bases) == 2: # Create the pattern that each site has site_pattern = [] # The ancestral gene is always the same as the outgroup ancestral = taxa_to_site[outgroup] # Iterate over each taxon for taxon in taxa_order: nucleotide = taxa_to_site[taxon] # Determine if the correct derived/ancestral status of each nucleotide if nucleotide == ancestral: site_pattern.append("A") else: site_pattern.append("B") # Convert the site pattern to a string sites = pattern_string_generator([site_pattern]) if sites: site_string = sites[0] # If the site string is a pattern of interest add to its count for one of the terms if site_string in terms1: terms1_counts[site_string] += 1 elif site_string in terms2: terms2_counts[site_string] += 1 elif "-" in bases or "N" in bases: num_ignored += 1 # Increment the site index site_idx += 1 terms1_total = sum(terms1_counts.values()) terms2_total = sum(terms2_counts.values()) numerator = terms1_total - terms2_total denominator = terms1_total + terms2_total if denominator != 0: l_stat = numerator / float(denominator) else: l_stat = 0 # Verbose output if verbose: signif, chisq, pval = calculate_significance(terms1_total, terms2_total, verbose, alpha) # The line below can be changed to add more information to the windows to L mapping windows_to_l[window] = (l_stat, signif, num_ignored, chisq, pval) # Standard output else: signif = calculate_significance(terms1_total, terms2_total, verbose, alpha) windows_to_l[window] = (l_stat, signif) # Account for overlapping windows site_idx += (window_offset - window_size) alignments_to_windows_to_d[alignment] = windows_to_l return alignments_to_windows_to_d ##### Functions for total ordering def branch_adjust(species_tree): """ Create all possible combinations of branch lengths for the given species tree Input: species_tree --- a newick string containing the overall species tree Output: adjusted_trees --- a set of trees with all combinations of branch lengths """ branch_lengths = [.5, 1.0, 2.0, 4.0] adjusted_trees = set([]) taxa = [] pattern = "((?<=\()[\w]+)|((?<=\,)[\w]+)" leaves = re.findall(pattern, species_tree) for leaf in leaves: if leaf[0] == '': taxa.append(leaf[1]) else: taxa.append(leaf[0]) for b in branch_lengths: new_t = species_tree for taxon in taxa: new_t = new_t.replace(taxon, "{0}:{1}".format(taxon, b)) new_t = new_t.replace("),", "):{0},".format(b)) adjusted_trees.add(new_t) return adjusted_trees, taxa def approximately_equal(x, y, tol=0.00000000000001): """ Determines if floats x and y are equal within a degree of uncertainty Inputs: x --- a float y --- a float tol --- an error tolerance """ return abs(x - y) <= tol def equality_sets(species_trees, network, taxa, outgroup, use_inv): """ Create mappings of site patterns to patterns with equivalent probabilities Input: species_tree --- a newick string containing the overall species tree without branch lengths Output: trees_to_equality --- a mapping of tree strings to a set of other trees with the same p(gt|st) trees_to_equality --- a mapping of tree strings to a set of other trees with the same p(gt|N) """ st_to_pattern_probs = {} st_to_pattern_probs_N = {} trees_to_equality = {} trees_to_equality_N = {} gene_trees = generate_unique_trees(taxa, outgroup) newick_patterns, inverses_to_counts = newicks_to_patterns_generator(taxa, gene_trees, outgroup) # If inverses are not desired remove them if not use_inv: newick_patterns = remove_inverse(newick_patterns, inverses_to_counts) for st in species_trees: ts_to_pgS, ts_to_pgN = calculate_newicks_to_stats(st, network, gene_trees) patterns_pgS, patterns_pgN = calculate_pattern_probabilities(newick_patterns, ts_to_pgS, ts_to_pgN) st_to_pattern_probs[st] = sorted(patterns_pgS.items(), key=lambda tup: tup[1], reverse=True) st_to_pattern_probs_N[st] = sorted(patterns_pgN.items(), key=lambda tup: tup[1], reverse=True) # Generate equality sets based on p(gt|st) for st in sorted(st_to_pattern_probs.keys()): gt_probs = st_to_pattern_probs[st] for i in range(len(gt_probs)): gt1, prob1 = gt_probs[i] equal_trees = set([]) for j in range(len(gt_probs)): gt2, prob2 = gt_probs[j] if approximately_equal(prob1, prob2): equal_trees.add(gt2) # Add the equality set to the mapping if tbe pattern is not already in the mapping and set is non empty if len(equal_trees) != 0: trees_to_equality[gt1] = equal_trees # Generate equality sets based on p(gt|N) for st in sorted(st_to_pattern_probs_N.keys()): gt_probs = st_to_pattern_probs_N[st] for i in range(len(gt_probs)): gt1, prob1 = gt_probs[i] equal_trees = set([]) for j in range(len(gt_probs)): gt2, prob2 = gt_probs[j] if approximately_equal(prob1, prob2): equal_trees.add(gt2) # Add the equality set to the mapping if tbe pattern is not already in the mapping and set is non empty if len(equal_trees) != 0: trees_to_equality_N[gt1] = equal_trees return trees_to_equality, trees_to_equality_N, patterns_pgS, patterns_pgN def set_of_interest(trees_to_equality, trees_to_equality_N): """ Inputs: trees_to_equality --- a mapping of tree strings to a set of other trees with the same p(gt|st) trees_to_equality_N --- a mapping of tree strings to a set of other trees with the same p(gt|N) Output: trees_of_interest --- a set of trees that changed equality under the species network """ trees_of_interest = set([]) for tree in trees_to_equality: if tree not in trees_to_equality_N: t_set = copy.deepcopy(trees_to_equality[tree]) t_set.add(tree) trees_of_interest = trees_of_interest.union(t_set) elif trees_to_equality[tree] != trees_to_equality_N[tree]: t_set = copy.deepcopy(trees_to_equality[tree]) t_set.add(tree) trees_of_interest = trees_of_interest.union(t_set) return trees_of_interest def concat_directory(directory_path): """ Concatenates all the alignments in a given directory and returns a single file. Input: directory_path --- a string path to the directory the use wants to use. Output: file_path --- a string path to the file that was created as a result of the concatenation. """ # filter out hidden files filenames = filter(lambda n: not n.startswith(".") , natsorted(os.listdir(directory_path))) # get the number of lines on each file with open(os.path.join(directory_path, filenames[0]), "r") as f: n = len(list(f)) # initialize a list with an empty string for each line output_file_list = [""] * n # Iterate over each folder in the given directory in numerical order for i in range(len(filenames)): # get full path of file input_file = os.path.join(directory_path, filenames[i]) # if its a fasta file -> convert to phylip if filenames[i].endswith(".fa") or filenames[i].endswith(".fasta"): input_handle = open(input_file, "rU") output_handle = open(input_file + ".phylip", "w") alignments = AlignIO.parse(input_handle, "fasta") AlignIO.write(alignments, output_handle, "phylip-sequential") output_handle.close() input_handle.close() input_file = input_file + ".phylip" # create a list of the input files lines with open(input_file, 'r') as f: input_file_list = [l.rstrip() for l in list(f)] for j in range(len(input_file_list)): # if this is the first file if i == 0: output_file_list[j] = input_file_list[j] else: if j == 0: num_bp = int(input_file_list[0].split(" ")[2]) total_bp = int(output_file_list[j].split(" ")[2]) + num_bp output_file_list[j] = " " + str(n - 1) + " " + str(total_bp) else: output_file_list[j] += input_file_list[j].split(" ")[-1] # write the contents of the output file list to a text file with open(os.path.abspath(directory_path) + "/concatFile.phylip.txt", "w") as o: for line in output_file_list: print >> o, line return os.path.abspath(directory_path) + "/concatFile.phylip.txt" def remove_inverse(newick_patterns, inverses_to_counts): """ Remove inverse site patterns Input: term --- a tuple of site patterns and their inverses Output: term --- the original tuple with site patterns removed """ # Create a ,mapping of each site pattern to its inverse patterns_to_inverse = {} d = set([]) for newick in newick_patterns: d = d.union(set(newick_patterns[newick])) #Map each pattern to its inverse for newick in newick_patterns: for pattern in newick_patterns[newick]: # Represent the pattern as a list pattern_lst = [x for x in pattern] # Create the inverse pattern inv_lst = pattern_inverter([pattern_lst])[0] inverse = ''.join(inv_lst) # If the pattern is not already in the mapping map it if pattern not in patterns_to_inverse.keys() and pattern not in patterns_to_inverse.values(): patterns_to_inverse[pattern] = inverse # Real inverses are the site patterns that appear as inverses more frequently real_inverses = [] # Iterate over all possible patterns for pat in patterns_to_inverse: possible_inv = patterns_to_inverse[pat] # If a pattern only has one B define it as the inverse if b_count(pat) == 1: real_inverses.append(pat) elif b_count(possible_inv) == 1: real_inverses.append(possible_inv) # If a pattern appears as an inverse more often than its "inverse" then it is an inverse elif inverses_to_counts[pat] > inverses_to_counts[possible_inv]: real_inverses.append(pat) # Otherwise the "inverse" is the true inverse else: real_inverses.append(possible_inv) # Remove all real inverse for newick in newick_patterns: inverses_removed = list(newick_patterns[newick]) for p in newick_patterns[newick]: if p in real_inverses: inverses_removed.remove(p) newick_patterns[newick] = inverses_removed return newick_patterns def b_count(pattern): """ Count the number of B's that occur in a site pattern Input: pattern --- a site pattern Output: num_b --- the number of B's in the site pattern """ num_b = 0 for char in pattern: if char == "B": num_b += 1 return num_b def calculate_total_term_prob(patterns_pgS, term): """ Calculate the total probability for a term """ term_prob = 0 for pattern in term: term_prob += patterns_pgS[pattern] return term_prob def calculate_generalized(alignments, species_tree=None, reticulations=None, outgroup=None, window_size=100000000000, window_offset=100000000000, verbose=False, alpha=0.01, use_inv=False, useDir=False, directory="", statistic=False, save=False, f="DGenStatistic_", plot=False, meta=False): """ Calculates the L statistic for the given alignment Input: alignment --- a sequence alignment in phylip format species_tree --- the inputted species tree over the given taxa reticulations --- a tuple containing two dictionaries mapping the start leaves to end leaves outgroup --- the desired root of the species tree window_size --- the desired window size window_offset --- the desired offset between windows verbose --- a boolean for determining if extra information will be printed alpha --- the significance level use_inv --- a boolean for using inverse site patterns or not useDir --- a boolean for determining if the user wants to input an entire directory of alignments or only a single alignment directory --- a string path to the directory the use wants to use. NOTE: only necessary if useDir=True. statistic --- a text file containing a saved statistic save --- a boolean corresponding to save a statistic or not, note that saving uses block resizing f --- the desired save statistic file name plot --- a boolean corresponding to using plot formatting for the output meta --- a string of metadata added to the plot formatting output Output: l_stat --- the generalized d statistic value """ # If the user does not have a specific statistic file to use if not statistic: st = re.sub("\:\d+\.\d+", "", species_tree) st = Tree(st) st.set_outgroup(outgroup) st.ladderize(direction=1) st = st.write() trees, taxa = branch_adjust(st) network = generate_network_tree((0.1, 0.9), list(trees)[0], reticulations) trees_to_equality, trees_to_equality_N, patterns_pgS, patterns_pgN = equality_sets(trees, network, taxa, outgroup, use_inv) trees_of_interest = set_of_interest(trees_to_equality, trees_to_equality_N) increase, decrease, increase_resized, decrease_resized, patterns_to_coeff = determine_patterns( trees_of_interest, trees_to_equality, patterns_pgN, patterns_pgS, use_inv) # Calculate the total probabilities for creating a coefficient inc_prob = calculate_total_term_prob(patterns_pgS, increase) dec_prob = calculate_total_term_prob(patterns_pgS, decrease) if inc_prob != 0: overall_coefficient = dec_prob / inc_prob else: overall_coefficient = 0 # If users want to save the statistic and speed up future runs if save: num = 0 file_name = f + ".txt" while os.path.exists(file_name): file_name = "DGenStatistic_{0}.txt".format(num) num += 1 with open(file_name, "w") as text_file: output_str = "Taxa: {0}\n".format(taxa) text_file.write(output_str) output_str = "Left Terms: {0}\n".format(increase_resized) text_file.write(output_str) output_str = "Right Terms: {0}\n".format(decrease_resized) text_file.write(output_str) output_str = "Statistic: {0}\n".format(generate_statistic_string((increase_resized, decrease_resized))) text_file.write(output_str) output_str = "Species Tree: {0}\n".format(species_tree) text_file.write(output_str) output_str = "Outgroup: {0}\n".format(outgroup) text_file.write(output_str) output_str = "Reticulations: {0}\n".format(reticulations) text_file.write(output_str) text_file.close() # Users can specify a previously generated statistic to use for alignment counting else: with(open(statistic, "r")) as s: lines = s.readlines() taxa = eval(lines[0].split(None, 1)[1]) increase = eval(lines[1].split(None, 2)[2]) decrease = eval(lines[2].split(None, 2)[2]) outgroup = lines[5].split(None, 1)[1].replace("\n", "") increase_resized = increase decrease_resized = decrease overall_coefficient = 1 patterns_to_coeff = {} if useDir: alignments = [concat_directory(directory)] alignments_to_d_resized, alignments_to_d_pattern_coeff, alignments_to_d_ovr_coeff = calculate_L( alignments, taxa, outgroup, (increase, decrease), verbose, alpha, (increase_resized, decrease_resized), overall_coefficient, patterns_to_coeff) alignments_to_windows_to_d = calculate_windows_to_L(alignments, taxa, outgroup, (increase_resized, decrease_resized), window_size, window_offset, verbose, alpha) s = "" n = "" # Create the output string if verbose and not statistic: s += "\n" s += "Probability of gene tree patterns: " + str(patterns_pgS) + "\n" s += "\n" s += "Probability of species network patterns:" + str(patterns_pgN) + "\n" s += "\n" s += "Patterns that were formerly equal with increasing probability: " + str(increase) + "\n" s += "Patterns that were formerly equal with decreasing probability: " + str(decrease) + "\n" s += "Total p(gt|st) for increasing site patterns: " + str(inc_prob) + "\n" s += "Total p(gt|st) for decreasing site patterns: " + str(dec_prob) + "\n" s += "\n" s += "Taxa order used for site patterns: " + str(taxa) + "\n" s += "Statistic without coefficient weighting: " + str(generate_statistic_string((increase, decrease))) + "\n" s += "\n" s += "Increasing patterns after block resizing: " + str(increase_resized) + "\n" s += "Decreasing patterns after block resizing: " + str(decrease_resized) + "\n" s += "Total p(gt|st) for resized increasing site patterns: " + str(calculate_total_term_prob(patterns_pgS, increase_resized)) + "\n" s += "Total p(gt|st) for resized decreasing site patterns: " + str(calculate_total_term_prob(patterns_pgS, decrease_resized)) + "\n" s += "Statistic using block resizing: " + str(generate_statistic_string((increase_resized, decrease_resized))) + "\n" s += "\n" s += "\n" s += "Information for each file: " + "\n" s += display_alignment_info(alignments_to_d_resized, alignments_to_d_pattern_coeff, alignments_to_d_ovr_coeff) print s elif verbose and statistic: s += "Taxa order used for site patterns: " + str(taxa) + "\n" s += "\n" s += "Patterns that were formerly equal with increasing probability: " + str(increase) + "\n" s += "Patterns that were formerly equal with decreasing probability: " + str(decrease) + "\n" s += "\n" s += "Statistic: " + str(generate_statistic_string((increase, decrease))) + "\n" s += "\n" s += "Information for each file: " + "\n" n += "Information for each file: " + "\n" for alignment in alignments_to_d_resized: l_stat, significant, left_counts, right_counts, num_ignored, chisq, pval = alignments_to_d_resized[alignment] s += alignment + ": " n += alignment + ": " + "\n" s += "\n" s += "Final Overall D value using Block Resizing Method: {0}".format(l_stat) + "\n" s += "Significant deviation from 0: {0}".format(significant) + "\n" s += "Overall Chi-Squared statistic: " + str(chisq) + "\n" s += "Overall p value: " + str(pval) + "\n" s += "Number of site ignored due to \"N\" or \"-\": {0}".format(num_ignored) + "\n" s += "\n" s += "Left term counts: " + "\n" for pattern in left_counts: s += pattern + ": {0}".format(left_counts[pattern]) + "\n" s += "\n" s += "Right term counts: " + "\n" for pattern in right_counts: s += pattern + ": {0}".format(right_counts[pattern]) + "\n" s += "\n" s += "Windows to D value: " + str(alignments_to_windows_to_d[alignment]) + "\n" s += "\n" s += "Final Overall D value {0}".format(l_stat) + "\n" s += "Significant deviation from 0: {0}".format(significant) + "\n" n += "Final Overall D value {0}".format(l_stat) + "\n" n += "Significant deviation from 0: {0}".format(significant) + "\n" print s else: for alignment in alignments_to_d_resized: l_stat_r, significant_r = alignments_to_d_resized[alignment] l_stat_pc, significant_pc = alignments_to_d_pattern_coeff[alignment] l_stat_oc, significant_oc = alignments_to_d_ovr_coeff[alignment] s += "\n" s += alignment + ": " + "\n" s += "\n" s += "Windows to D value: " + str(alignments_to_windows_to_d[alignment]) + "\n" s += "\n" s += "Final Overall D value using Block Resizing Method: {0}".format(l_stat_r) + "\n" s += "Significant deviation from 0: {0}".format(significant_r) + "\n" s += "\n" s += "Final Overall D value using Pattern Coefficient Method: {0}".format(l_stat_pc) + "\n" s += "Significant deviation from 0: {0}".format(significant_pc) + "\n" s += "\n" s += "Final Overall D value using Overall Coefficient Method: {0}".format(l_stat_oc) + "\n" s += "Significant deviation from 0: {0}".format(significant_oc) + "\n" print s if plot: plot_formatting((alignments_to_d_resized, alignments_to_windows_to_d), plot, meta) return alignments_to_d_resized, alignments_to_windows_to_d, n, s def display_alignment_info(alignments_to_d_resized, alignments_to_d_pattern_coeff, alignments_to_d_ovr_coeff): """ Print information for an alignment to D mapping Inputs: alignments_to_d_resized --- a mapping of alignment files to their D information using block resizing alignments_to_d_pattern_coeff --- a mapping of alignment files to their D information using pattern coefficient alignments_to_d_ovr_coeff --- --- a mapping of alignment files to their D information using overall coefficient Output: s --- the output string """ s = "" n = "" for alignment in alignments_to_d_resized: # Get the information for each alignment file l_stat, significant, left_counts_res, right_counts_res, num_ignored, chisq, pval = alignments_to_d_resized[alignment] output_resized = [("Final Overall D value using Block Resizing method: ", l_stat), ("Significant deviation from 0: ", significant), ("Overall p value: ", pval), ("Overall Chi-Squared statistic: ", chisq), ("", ""), ("Number of site ignored due to \"N\" or \"-\": ", num_ignored)] l_stat, significant, left_counts_pcoeff, right_counts, num_ignored, chisq, pval = alignments_to_d_pattern_coeff[alignment] output_pattern_coeff = [("Final Overall D value using Pattern Weighting method: ", l_stat), ("Significant deviation from 0: ", significant), ("Overall p value: ", pval), ("Overall Chi-Squared statistic: ", chisq), ("", ""), ("Number of site ignored due to \"N\" or \"-\": ", num_ignored)] l_stat, significant, left_counts_ocoeff, right_counts, num_ignored, chisq, pval, coeff = alignments_to_d_ovr_coeff[alignment] output_overall_coeff = [("Final Overall D value using Overall Weighting method: ", l_stat), ("Significant deviation from 0: ", significant), ("Overall p value: ", pval), ("Overall Chi-Squared statistic: ", chisq), ("", ""), ("Number of site ignored due to \"N\" or \"-\": ", num_ignored)] # Create the output string s += "\n" s += "\n" s += alignment + ": " s += "\n" n += "\n" + "\n" + alignment + ": " + "\n" # Print output for resizing method for output in output_resized: s += str(output[0]) + str(output[1]) + "\n" n += str(output[0]) + str(output[1]) + "\n" s += "Left term counts: " + "\n" for pattern in left_counts_res: s += pattern + ": {0}".format(left_counts_res[pattern]) + "\n" s += "\n" s += "Right term counts: " + "\n" for pattern in right_counts_res: s += pattern + ": {0}".format(right_counts_res[pattern]) + "\n" s += "\n" s += "\n" # Print output for pattern coefficient method for output in output_pattern_coeff: s += str(output[0]) + str(output[1]) + "\n" s += "Left term counts weighted by pattern probability: " + "\n" for pattern in left_counts_pcoeff: s += pattern + ": {0}".format(left_counts_pcoeff[pattern]) + "\n" s += "\n" s += "Right term counts: " + "\n" for pattern in right_counts: s += pattern + ": {0}".format(right_counts[pattern]) + "\n" s += "\n" s += "\n" # Print output for overall coefficient method for output in output_overall_coeff: s += str(output[0]) + str(output[1]) + "\n" s += "Overall Coefficient for weighting: {0}".format(coeff) + "\n" s += "Left term counts after weighting: " + "\n" for pattern in left_counts_ocoeff: s += pattern + ": {0}".format(left_counts_ocoeff[pattern] * coeff) + "\n" s += "\n" s += "Right term counts: " + "\n" for pattern in right_counts: s += pattern + ": {0}".format(right_counts[pattern]) + "\n" return s def plot_formatting(info_tuple, name, meta): """ Reformats and writes the dictionary output to a text file to make plotting it in Excel easy Input: info_tuple --- a tuple from the calculate_generalized output """ alignments_to_d, alignments_to_windows_to_d = info_tuple num = 0 file_name = "{0}_{1}.txt".format(name, num) while os.path.exists(file_name): num += 1 file_name = "{0}_{1}.txt".format(name, num) with open(file_name, "w") as text_file: for alignment in alignments_to_d: l_stat, significant = alignments_to_d[alignment][0], alignments_to_d[alignment][1] significant = str(significant).upper() windows_to_l = alignments_to_windows_to_d[alignment] output_str = "{0}, {1}, {2} \n".format(l_stat, meta, significant) text_file.write(output_str) text_file.close() if __name__ == '__main__': r = [('P3', 'P2')] species_tree = '(((P1,P2),P3),O);' # species_tree = '((P1,P2),(P3,O));' # species_tree = '(((P1,P2),(P3,P4)),O);' # DFOIL tree # species_tree = '((((P1,P2),P3),P4),O);' # Smallest asymmetrical tree # species_tree = '(((P1,P2),(P3,(P4,P5))),O);' # n = '((P2,(P1,P3)),O);' # n = '(((P1,P3),P2),O);' # n = '((P1,(P2,(P3,P4))),O);' # t = ["P1", "P2", "P3", "P4", "O"] # o = "O" # print site_pattern_generator(t, n, o, False) if platform == "darwin": alignments = ["/Users/Peter/PycharmProjects/ALPHA/exampleFiles/seqfile.txt"] else: alignments = ["C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim2\\seqfile.txt"] # alignments = ["C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim5\\seqfile", # "C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim7\\seqfile", # "C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim4\\seqfile", # "C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim6\\seqfile", # "C:\\Users\\travi\\Desktop\\dFoilStdPlusOneFar50kbp\\dFoilStdPlusOneFar50kbp\\sim8\\seqfile"] print calculate_generalized(alignments, species_tree, r, "O", 500000, 500000, alpha=0.01, verbose=False, use_inv=False) # alignments = ["C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames"] # # # species_tree, r = '((((P1,P4),P3),P2),O);', [('P3', 'P2'),('P1', 'P2')] # # # 3 to 2 # calculate_generalized( ['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P3', 'P2')], 50000, 50000, True, save=True, f='stat_6tax_sub_3to2.txt') # print "done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized( ['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P3', 'P2')], 50000, 50000, True, save=True, f='stat_inv_6tax_sub_3to2.txt', use_inv=True) # print "done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # # 4 to 3 # calculate_generalized( ['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P4', 'P3')], 50000, 50000, True, save=True, f='stat_6tax_sub_4to3.txt') # print "done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized( ['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P4', 'P3')], 50000, 50000, True, save=True, f='stat_inv_6tax_sub_4to3.txt', use_inv=True) # print "done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # # both # calculate_generalized(['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P3', 'P2'),('P4', 'P3')], 50000, 50000, True, save=True, f='stat_6tax_sub_3to2_4to3.txt') # print "done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized(['C:\\Users\\travi\\Desktop\\390 Errors\\seqfileNames'], '(((P5,P6),((P1,P2),P3)),P4);', [('P3', 'P2'),('P4', 'P3')], 50000, 50000, True, save=True, f='stat_inv_6tax_sub_3to2_4to3.txt', use_inv=True) # print "done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # species_tree, r = "(((P5,P6),((P1,P2),P3)),P4);", [('P3', 'P2')] # alignments = ["C:\\Users\\travi\\Desktop\\MosquitoConcat.phylip.txt"] # species_tree, r = '((C,G),(((A,Q),L),R));', [('Q', 'G')] # print calculate_generalized(alignments, 500000, 500000, statistic="C:\\Users\\travi\\Desktop\\stat_mosqSubset.txt", alpha=0.01, verbose=False, use_inv=False) # alignments = ["C:\\Users\\travi\\Desktop\\MosquitoConcat.phylip.txt"] # alignments = ["C:\\Users\\travi\\Desktop\\3L\\3L\\3L.41960870.634.fa.phylip"] # # calculate_generalized(alignments , '((C,G),(((A,Q),L),R));', [('Q', 'G')], 50000, 50000, True, save=True, f='stat_QuaToGam.txt') # print "Q to G done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized(alignments, '((C,G),(((A,Q),L),R));', [('Q', 'G')], 50000, 50000, True, save=True, f='stat_inv_QuaToGam.txt', use_inv=True) # print "Q to G done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # # next generate Q to R, the bottom right one in dingqiaos fig # calculate_generalized(alignments , '((C,G),(((A,Q),L),R));', [('Q', 'R')], 50000, 50000, True, save=True, f='stat_QuaToMer.txt') # print "Q to R done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized(alignments , '((C,G),(((A,Q),L),R));', [('Q', 'R')], 50000, 50000, True, save=True, f='stat_inv_QuaToMer.txt', use_inv=True) # print "Q to R done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # # last generate L to R, the top right one in dingqiaos fig # calculate_generalized(alignments, '((C,G),(((A,Q),L),R));', [('L', 'R')], 50000, 50000, True, save=True, f='stat_MelToMer.txt') # print "L to R done" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # # calculate_generalized(alignments , '((C,G),(((A,Q),L),R));', [('L', 'R')], 50000, 50000, True, save=True, f='stat_inv_MelToMer.txt', use_inv=True) # print "L to R done with inverses" # playsound.playsound("C:\\Users\\travi\\Downloads\\app-5.mp3") # print calculate_generalized(alignments, species_tree, r, 50000, 50000, alpha=0.01, statistic=False, save=False, # verbose=True, use_inv=False) # s = "C:\\Users\\travi\\Documents\\ALPHA\\CommandLineFiles\\DGenStatistic_85.txt" # print calculate_generalized(alignments, species_tree, r, 50000, 50000, alpha=0.01, statistic=s, # verbose=True, use_inv=False) # print calculate_generalized(alignments, species_tree, r, 50000, 50000, alpha=0.01, statistic=False, save=False, # verbose=True, use_inv=False) # print calculate_generalized(alignments, species_tree, r, 50000, 50000, alpha=0.01, statistic=False, save=False, # verbose=True, use_inv=False) # calculate_generalized(alignments, species_tree, r, 500000, 500000, True, 0.01, statistic=False, save=True, f="C:\\Users\\travi\\Documents\\ALPHA\\ABBABABATest2") # print calculate_generalized(alignments, species_tree, r, 50000, 50000, alpha=0.01, statistic="C:\\Users\\travi\\Documents\\ALPHA\\ABBABABATest2.txt", verbose=True) # # save_file = "C:\\Users\\travi\\Documents\\ALPHA\\CommandLineFiles\\DGenStatistic_11.txt" # plot_formatting(calculate_generalized(alignments, statistic=save_file, verbose=True)) # python -c"from CalculateGeneralizedDStatistic import *; plot_formatting(calculate_generalized('C:\\Users\\travi\\Desktop\\seqfileNamed', '(((P1,P2),(P3,P4)),O);', [('P1', 'P3')], 100000, 100000, True, 0.01), True)" # Uncomment this to speed up 6 taxa debugging # trees_of_interest = set(['BBABBA', 'ABBBAA', 'BABBBA', 'ABBABA', 'ABBBBA', 'AAABAA', 'ABAABA', 'BBBABA', 'BABABA', 'ABBAAA', # 'BAAABA', 'ABABAA', 'BABBAA', 'BAAAAA', 'BBBBAA', 'ABABBA', 'BAABBA', 'AABAAA', 'BAABAA', 'BABAAA', # 'ABAAAA', 'AAAABA']) # trees_to_equality = {'BBABBA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'ABBBAA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BABBBA': set(['BABBBA', 'ABAAAA', 'ABBBBA', 'BAAAAA']), # 'AABBAA': set(['AABABA', 'BBABAA', 'AABBAA', 'BBAABA']), # 'AAABAA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'BBBABA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'ABBAAA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'BBAABA': set(['AABABA', 'BBABAA', 'AABBAA', 'BBAABA']), # 'BABAAA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BAAAAA': set(['BABBBA', 'ABAAAA', 'ABBBBA', 'BAAAAA']), # 'AABABA': set(['AABABA', 'BBABAA', 'AABBAA', 'BBAABA']), # 'BBBBAA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'ABABBA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BAABAA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BABBAA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'AAAABA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'AABBBA': set(['BBAAAA', 'AABBBA']), # 'ABAABA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'ABBBBA': set(['BABBBA', 'ABAAAA', 'ABBBBA', 'BAAAAA']), 'BBBAAA': set(['AAABBA', 'BBBAAA']), # 'ABBABA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BBABAA': set(['AABABA', 'BBABAA', 'AABBAA', 'BBAABA']), 'AAABBA': set(['AAABBA', 'BBBAAA']), # 'BAAABA': set(['BABAAA', 'ABBBAA', 'ABBABA', 'ABABBA', 'BAABAA', 'BAAABA']), # 'BBAAAA': set(['BBAAAA', 'AABBBA']), # 'ABABAA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'BABABA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'BAABBA': set(['ABABAA', 'ABAABA', 'BABABA', 'BAABBA', 'ABBAAA', 'BABBAA']), # 'AABAAA': set(['BBABBA', 'AAABAA', 'BBBBAA', 'BBBABA', 'AABAAA', 'AAAABA']), # 'ABAAAA': set(['BABBBA', 'ABAAAA', 'ABBBBA', 'BAAAAA'])} # patterns_pgN = {'BBABBA': 0.032771235848126294, 'ABBBAA': 0.02098066450471356, 'BABBBA': 0.161652195191427, # 'AABBAA': 0.03153707911255491, 'AAABAA': 0.1777623151093396, 'BBBABA': 0.1777623151093396, # 'ABBAAA': 0.014809880826856624, 'BBAABA': 0.03153707911255491, 'BABAAA': 0.63719275136487, # 'BAAAAA': 0.016661115930213705, 'AABABA': 0.03153707911255492, 'BBBBAA': 0.1777623151093396, # 'ABABBA': 0.63719275136487, 'BAABAA': 0.02098066450471356, 'BABBAA': 0.15980096008806993, # 'AAAABA': 0.1777623151093396, 'AABBBA': 0.08944867415584207, 'ABAABA': 0.15980096008806993, # 'ABBBBA': 0.016661115930213705, 'BBBAAA': 0.2180376149041211, 'ABBABA': 0.02098066450471356, # 'BBABAA': 0.03153707911255492, 'AAABBA': 0.2180376149041211, 'BAAABA': 0.02098066450471356, # 'BBAAAA': 0.08944867415584207, 'ABABAA': 0.15980096008806996, 'BABABA': 0.15980096008806996, # 'BAABBA': 0.014809880826856624, 'AABAAA': 0.032771235848126294, 'ABAAAA': 0.161652195191427} # patterns_pgS = {'BBABBA': 0.11019080921752063, 'ABBBAA': 0.037037004438901525, 'BABBBA': 0.029411738819127668, # 'AABBAA': 0.10801216189758524, 'AAABAA': 0.11019080921752065, 'BBBABA': 0.11019080921752065, # 'ABBAAA': 0.026143767839224594, 'BBAABA': 0.10801216189758524, 'BABAAA': 0.03703700443890152, # 'BAAAAA': 0.029411738819127668, 'AABABA': 0.10801216189758527, 'BBBBAA': 0.11019080921752064, # 'ABABBA': 0.03703700443890152, 'BAABAA': 0.03703700443890151, 'BABBAA': 0.026143767839224594, # 'AAAABA': 0.11019080921752064, 'AABBBA': 0.38034805363207147, 'ABAABA': 0.026143767839224594, # 'ABBBBA': 0.029411738819127668, 'BBBAAA': 0.1303855768171189, 'ABBABA': 0.03703700443890151, # 'BBABAA': 0.10801216189758527, 'AAABBA': 0.1303855768171189, 'BAAABA': 0.037037004438901525, # 'BBAAAA': 0.38034805363207147, 'ABABAA': 0.026143767839224594, 'BABABA': 0.026143767839224594, # 'BAABBA': 0.026143767839224594, 'AABAAA': 0.11019080921752063, 'ABAAAA': 0.029411738819127668} # Debug for CL introgression file # trees_of_interest = set(['ABBBAA', 'ABAABA', 'AABBAA', 'BBBAAA', 'ABBABA', 'BBABAA', 'BABABA', 'AAABBA', 'BBAABA', 'BAAABA', 'ABABAA', # 'AABABA', 'ABABBA', 'BAABBA', 'ABBAAA', 'BAABAA', 'BABAAA', 'BABBAA']) # trees_to_equality = {'BBABBA': set(['BBABBA']), 'ABBBAA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA']), # 'BABBBA': set(['BABBBA']), 'AABBAA': set(['AABABA', 'AAABBA', 'AABBAA']), 'BBBABA': set(['BBBABA']), # 'ABBAAA': set(['ABABAA', 'ABBAAA', 'ABAABA']), 'BBAABA': set(['BBBAAA', 'BBABAA', 'BBAABA']), # 'BABAAA': set(['BABAAA', 'BAAABA', 'BAABAA']), 'AABABA': set(['AABABA', 'AAABBA', 'AABBAA']), # 'BBBBAA': set(['BBBBAA']), 'ABABBA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA']), # 'BAABAA': set(['BABAAA', 'BAAABA', 'BAABAA']), # 'BABBAA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA']), 'AABBBA': set(['AABBBA']), # 'ABAABA': set(['ABABAA', 'ABBAAA', 'ABAABA']), 'ABBBBA': set(['ABBBBA']), # 'BBBAAA': set(['BBBAAA', 'BBABAA', 'BBAABA']), # 'ABBABA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA']), # 'BBABAA': set(['BBBAAA', 'BBABAA', 'BBAABA']), 'AAABBA': set(['AABABA', 'AAABBA', 'AABBAA']), # 'BAAABA': set(['BABAAA', 'BAAABA', 'BAABAA']), 'BBAAAA': set(['BBAAAA']), # 'ABABAA': set(['ABABAA', 'ABBAAA', 'ABAABA']), # 'BABABA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA']), # 'BAABBA': set(['ABBBAA', 'ABBABA', 'ABABBA', 'BAABBA', 'BABABA', 'BABBAA'])} # patterns_pgN = {'BBABBA': 0.25178403007053934, 'ABBBAA': 0.00925617551678539, 'BABBBA': 0.14956960525299257, # 'AABBAA': 0.011432470392906461, 'BBBABA': 0.1888697257294821, 'ABBAAA': 0.006170783677856928, # 'BBAABA': 0.025366295434697986, 'BABAAA': 0.22118908909853413, 'AABABA': 0.011432470392906461, # 'BBBBAA': 0.2346987308343348, 'ABABBA': 0.11799948496269537, 'BAABAA': 0.0037024702067141564, # 'BABBAA': 0.1542472547779987, 'AABBBA': 0.02133876545521984, 'ABAABA': 0.042418553493160246, # 'ABBBBA': 0.011107410620142468, 'BBBAAA': 0.1703573746959113, 'ABBABA': 0.00925617551678539, # 'BBABAA': 0.025366295434697986, 'AAABBA': 0.04768024020820978, 'BAAABA': 0.0037024702067141564, # 'BBAAAA': 0.027867650083583044, 'ABABAA': 0.04241855349316025, 'BABABA': 0.15424725477799872, # 'BAABBA': 0.00925617551678539} # patterns_pgS = {'BBABBA': 0.09979995455763162, 'ABBBAA': 0.016339854899515373, 'BABBBA': 0.15058034441671714, # 'AABBAA': 0.03326665151921054, 'BBBABA': 0.12979863509693912, 'ABBAAA': 0.010893236599676915, # 'BBAABA': 0.09711892529790832, 'BABAAA': 0.006535941959806149, 'AABABA': 0.03326665151921054, # 'BBBBAA': 0.15979731563624658, 'ABABBA': 0.016339854899515373, 'BAABAA': 0.006535941959806149, # 'BABBAA': 0.016339854899515373, 'AABBBA': 0.0769241576983101, 'ABAABA': 0.010893236599676915, # 'ABBBBA': 0.019607825879418447, 'BBBAAA': 0.09711892529790833, 'ABBABA': 0.016339854899515373, # 'BBABAA': 0.09711892529790832, 'AAABBA': 0.03326665151921054, 'BAAABA': 0.006535941959806149, # 'BBAAAA': 0.12770454755739558, 'ABABAA': 0.010893236599676915, 'BABABA': 0.016339854899515373, # 'BAABBA': 0.016339854899515373}<|fim▁end|>
<|file_name|>eui48.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2008-2015, David P. D. Moss. All rights reserved. # # Released under the BSD license. See the LICENSE file for details. #----------------------------------------------------------------------------- """ IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re # Check whether we need to use fallback code or not. try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError from netaddr.strategy import \ valid_words as _valid_words, \ int_to_words as _int_to_words, \ words_to_int as _words_to_int, \ valid_bits as _valid_bits, \ bits_to_int as _bits_to_int, \ int_to_bits as _int_to_bits, \ valid_bin as _valid_bin, \ int_to_bin as _int_to_bin, \ bin_to_int as _bin_to_int from netaddr.compat import _is_str #: The width (in bits) of this address type. width = 48 #: The AF_* constant value of this address type. family = AF_LINK #: A friendly string name address type. family_name = 'MAC' #: The version of this address type. version = 48 #: The maximum integer value that can be represented by this address type. max_int = 2 ** width - 1 #----------------------------------------------------------------------------- # Dialect classes. #----------------------------------------------------------------------------- class mac_eui48(object): """A standard IEEE EUI-48 dialect class.""" #: The individual word size (in bits) of this address type. word_size = 8 #: The number of words in this address type. num_words = width // word_size #: The maximum integer value for an individual word in this address type. max_word = 2 ** word_size - 1 #: The separator character used between each word. word_sep = '-' #: The format string to be used when converting words to string values. word_fmt = '%.2X' #: The number base to be used when interpreting word values as integers. word_base = 16 class mac_unix(mac_eui48): """A UNIX-style MAC address dialect class.""" word_size = 8 num_words = width // word_size word_sep = ':' word_fmt = '%x' word_base = 16 class mac_unix_expanded(mac_unix): """A UNIX-style MAC address dialect class with leading zeroes.""" word_fmt = '%.2x' class mac_cisco(mac_eui48): """A Cisco 'triple hextet' MAC address dialect class.""" word_size = 16 num_words = width // word_size word_sep = '.' word_fmt = '%.4x' word_base = 16 class mac_bare(mac_eui48): """A bare (no delimiters) MAC address dialect class.""" word_size = 48 num_words = width // word_size word_sep = '' word_fmt = '%.12X' word_base = 16 class mac_pgsql(mac_eui48): """A PostgreSQL style (2 x 24-bit words) MAC address dialect class.""" word_size = 24 num_words = width // word_size word_sep = ':' word_fmt = '%.6x' word_base = 16 #: The default dialect to be used when not specified by the user. DEFAULT_DIALECT = mac_eui48 #----------------------------------------------------------------------------- #: Regular expressions to match all supported MAC address formats. RE_MAC_FORMATS = ( # 2 bytes x 6 (UNIX, Windows, EUI-48) '^' + ':'.join(['([0-9A-F]{1,2})'] * 6) + '$', '^' + '-'.join(['([0-9A-F]{1,2})'] * 6) + '$', # 4 bytes x 3 (Cisco) '^' + ':'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '-'.join(['([0-9A-F]{1,4})'] * 3) + '$',<|fim▁hole|> '^' + '\.'.join(['([0-9A-F]{1,4})'] * 3) + '$', # 6 bytes x 2 (PostgreSQL) '^' + '-'.join(['([0-9A-F]{5,6})'] * 2) + '$', '^' + ':'.join(['([0-9A-F]{5,6})'] * 2) + '$', # 12 bytes (bare, no delimiters) '^(' + ''.join(['[0-9A-F]'] * 12) + ')$', '^(' + ''.join(['[0-9A-F]'] * 11) + ')$', ) # For efficiency, each string regexp converted in place to its compiled # counterpart. RE_MAC_FORMATS = [_re.compile(_, _re.IGNORECASE) for _ in RE_MAC_FORMATS] def valid_str(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: ``True`` if MAC address string is valid, ``False`` otherwise. """ for regexp in RE_MAC_FORMATS: try: match_result = regexp.findall(addr) if len(match_result) != 0: return True except TypeError: pass return False def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0],) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % addr) else: raise TypeError('%r is not str() or unicode()!' % addr) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' \ % addr) return int_val def int_to_str(int_val, dialect=None): """ :param int_val: An unsigned integer. :param dialect: (optional) a Python class defining formatting options. :return: An IEEE EUI-48 (MAC) address string that is equivalent to unsigned integer formatted according to the dialect settings. """ if dialect is None: dialect = mac_eui48 words = int_to_words(int_val, dialect) tokens = [dialect.word_fmt % i for i in words] addr = dialect.word_sep.join(tokens) return addr def int_to_packed(int_val): """ :param int_val: the integer to be packed. :return: a packed string that is equivalent to value represented by an unsigned integer. """ return _struct.pack(">HI", int_val >> 32, int_val & 0xffffffff) def packed_to_int(packed_int): """ :param packed_int: a packed string containing an unsigned integer. It is assumed that string is packed in network byte order. :return: An unsigned integer equivalent to value of network address represented by packed binary string. """ words = list(_struct.unpack('>6B', packed_int)) int_val = 0 for i, num in enumerate(reversed(words)): word = num word = word << 8 * i int_val = int_val | word return int_val def valid_words(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_words(words, dialect.word_size, dialect.num_words) def int_to_words(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_words(int_val, dialect.word_size, dialect.num_words) def words_to_int(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _words_to_int(words, dialect.word_size, dialect.num_words) def valid_bits(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bits(bits, width, dialect.word_sep) def bits_to_int(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _bits_to_int(bits, width, dialect.word_sep) def int_to_bits(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_bits(int_val, dialect.word_size, dialect.num_words, dialect.word_sep) def valid_bin(bin_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bin(bin_val, width) def int_to_bin(int_val): return _int_to_bin(int_val, width) def bin_to_int(bin_val): return _bin_to_int(bin_val, width)<|fim▁end|>
<|file_name|>NonUniqueTaxonomyMap.java<|end_file_name|><|fim▁begin|>//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.core.clinical.domain.objects; /** * * @author John MacEnri * Generated. */ public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1003100071; private static final long serialVersionUID = 1003100071L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } private ims.domain.lookups.LookupInstance taxonomyName; private String taxonomyCode; private java.util.Date effectiveFrom; private java.util.Date effectiveTo; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public NonUniqueTaxonomyMap (Integer id, int ver) { super(id, ver); isComponentClass=true; } public NonUniqueTaxonomyMap () { super(); isComponentClass=true; } public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); isComponentClass=true; } public Class getRealDomainClass() { return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class; } public ims.domain.lookups.LookupInstance getTaxonomyName() { return taxonomyName; } public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) { this.taxonomyName = taxonomyName; } public String getTaxonomyCode() { return taxonomyCode; } public void setTaxonomyCode(String taxonomyCode) { if ( null != taxonomyCode && taxonomyCode.length() > 30 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+ taxonomyCode); } this.taxonomyCode = taxonomyCode; } public java.util.Date getEffectiveFrom() { return effectiveFrom; } public void setEffectiveFrom(java.util.Date effectiveFrom) { this.effectiveFrom = effectiveFrom; } public java.util.Date getEffectiveTo() { return effectiveTo; } public void setEffectiveTo(java.util.Date effectiveTo) { this.effectiveTo = effectiveTo; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*taxonomyName* :"); if (taxonomyName != null) auditStr.append(taxonomyName.getText()); auditStr.append("; "); auditStr.append("\r\n*taxonomyCode* :"); auditStr.append(taxonomyCode); auditStr.append("; "); auditStr.append("\r\n*effectiveFrom* :"); auditStr.append(effectiveFrom); auditStr.append("; "); auditStr.append("\r\n*effectiveTo* :"); auditStr.append(effectiveTo); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getTaxonomyName() != null) { sb.append("<taxonomyName>"); sb.append(this.getTaxonomyName().toXMLString()); sb.append("</taxonomyName>"); } if (this.getTaxonomyCode() != null) { sb.append("<taxonomyCode>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString())); sb.append("</taxonomyCode>"); } if (this.getEffectiveFrom() != null) { sb.append("<effectiveFrom>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveFrom>"); } if (this.getEffectiveTo() != null) { sb.append("<effectiveTo>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveTo>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap); } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!NonUniqueTaxonomyMap.class.getName().equals(className)) { Class clz = Class.forName(className); if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } NonUniqueTaxonomyMap ret = null; if (ret == null) { ret = new NonUniqueTaxonomyMap(); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("taxonomyName"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("taxonomyCode"); if(fldEl != null) { obj.setTaxonomyCode(new String(fldEl.getTextTrim())); } fldEl = el.element("effectiveFrom"); if(fldEl != null) { obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("effectiveTo"); if(fldEl != null) { obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ }; } /** equals */ public boolean equals(Object obj) { if (null == obj) { return false; } if(!(obj instanceof NonUniqueTaxonomyMap)) <|fim▁hole|> { return false; } NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj; if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&& (taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&& (effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&& (effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo))) return true; return super.equals(obj); } /** toString */ public String toString() { StringBuffer objStr = new StringBuffer(); if (taxonomyName != null) objStr.append(taxonomyName.getText() + "-"); objStr.append(taxonomyCode); return objStr.toString(); } /** hashcode */ public int hashCode() { int hash = 0; if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011; if (taxonomyCode!= null) hash += taxonomyCode.hashCode(); if (effectiveFrom!= null) hash += effectiveFrom.hashCode(); if (effectiveTo!= null) hash += effectiveTo.hashCode(); return hash; } public static class FieldNames { public static final String ID = "id"; public static final String TaxonomyName = "taxonomyName"; public static final String TaxonomyCode = "taxonomyCode"; public static final String EffectiveFrom = "effectiveFrom"; public static final String EffectiveTo = "effectiveTo"; } }<|fim▁end|>
<|file_name|>ListProcessingJobsResult.cpp<|end_file_name|><|fim▁begin|>/* * Copyright 2010-2017 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://aws.amazon.com/apache2.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. */ #include <aws/sagemaker/model/ListProcessingJobsResult.h><|fim▁hole|>#include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SageMaker::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListProcessingJobsResult::ListProcessingJobsResult() { } ListProcessingJobsResult::ListProcessingJobsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListProcessingJobsResult& ListProcessingJobsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ProcessingJobSummaries")) { Array<JsonView> processingJobSummariesJsonList = jsonValue.GetArray("ProcessingJobSummaries"); for(unsigned processingJobSummariesIndex = 0; processingJobSummariesIndex < processingJobSummariesJsonList.GetLength(); ++processingJobSummariesIndex) { m_processingJobSummaries.push_back(processingJobSummariesJsonList[processingJobSummariesIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }<|fim▁end|>
#include <aws/core/utils/json/JsonSerializer.h>
<|file_name|>regularizers.py<|end_file_name|><|fim▁begin|>import numpy as np from keras.datasets import mnist from keras.layers import Activation from keras.layers import Dense from keras.models import Sequential from keras.utils import np_utils np.random.seed(1337) nb_classes = 10 batch_size = 128 nb_epoch = 5 weighted_class = 9 standard_weight = 1 high_weight = 5<|fim▁hole|>def get_data(): # the data, shuffled and split between tran and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, 784)[:max_train_samples] X_test = X_test.reshape(10000, 784)[:max_test_samples] X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 # convert class vectors to binary class matrices y_train = y_train[:max_train_samples] y_test = y_test[:max_test_samples] Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) test_ids = np.where(y_test == np.array(weighted_class))[0] return (X_train, Y_train), (X_test, Y_test), test_ids def validate_regularizer(weight_reg=None, activity_reg=None): model = Sequential() model.add(Dense(50, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(10, W_regularizer=weight_reg, activity_regularizer=activity_reg)) model.add(Activation('softmax')) return model<|fim▁end|>
max_train_samples = 5000 max_test_samples = 1000
<|file_name|>plugin.js<|end_file_name|><|fim▁begin|>/* Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about) Dual licensed under the MIT or LGPL Version 2 licenses. */ (function() { OMEDITOR.plugins.add( 'templates', { requires : [ 'dialog' ], init : function( editor ) { OMEDITOR.dialog.add( 'templates', OMEDITOR.getUrl( this.path + 'dialogs/templates.js' ) ); editor.addCommand( 'templates', new OMEDITOR.dialogCommand( 'templates' ) ); editor.ui.addButton( 'Templates', { label : editor.lang.templates.button, command : 'templates' }); } }); var templates = {}, loadedTemplatesFiles = {}; OMEDITOR.addTemplates = function( name, definition )<|fim▁hole|> templates[ name ] = definition; }; OMEDITOR.getTemplates = function( name ) { return templates[ name ]; }; OMEDITOR.loadTemplates = function( templateFiles, callback ) { // Holds the templates files to be loaded. var toLoad = []; // Look for pending template files to get loaded. for ( var i = 0, count = templateFiles.length ; i < count ; i++ ) { if ( !loadedTemplatesFiles[ templateFiles[ i ] ] ) { toLoad.push( templateFiles[ i ] ); loadedTemplatesFiles[ templateFiles[ i ] ] = 1; } } if ( toLoad.length ) OMEDITOR.scriptLoader.load( toLoad, callback ); else setTimeout( callback, 0 ); }; })(); /** * The templates definition set to use. It accepts a list of names separated by * comma. It must match definitions loaded with the templates_files setting. * @type String * @default 'default' * @example * config.templates = 'my_templates'; */ /** * The list of templates definition files to load. * @type (String) Array * @default [ 'plugins/templates/templates/default.js' ] * @example * config.templates_files = * [ * '/editor_templates/site_default.js', * 'http://www.example.com/user_templates.js * ]; * */ OMEDITOR.config.templates_files = [ OMEDITOR.getUrl( '_source/' + // @Packager.RemoveLine 'plugins/templates/templates/default.js' ) ]; /** * Whether the "Replace actual contents" checkbox is checked by default in the * Templates dialog. * @type Boolean * @default true * @example * config.templates_replaceContent = false; */ OMEDITOR.config.templates_replaceContent = true;<|fim▁end|>
{
<|file_name|>tree.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use attr::{AttrSelectorOperation, NamespaceConstraint}; use matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus}; use parser::SelectorImpl; pub trait Element: Sized { type Impl: SelectorImpl; fn parent_element(&self) -> Option<Self>; /// The parent of a given pseudo-element, after matching a pseudo-element /// selector. /// /// This is guaranteed to be called in a pseudo-element. fn pseudo_element_originating_element(&self) -> Option<Self> { self.parent_element() } /// Skips non-element nodes fn first_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn last_child_element(&self) -> Option<Self>; /// Skips non-element nodes fn prev_sibling_element(&self) -> Option<Self>; /// Skips non-element nodes fn next_sibling_element(&self) -> Option<Self>; fn is_html_element_in_html_document(&self) -> bool; fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName; <|fim▁hole|> fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl; fn attr_matches(&self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName, operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>) -> bool; fn match_non_ts_pseudo_class<F>(&self, pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass, context: &mut MatchingContext, relevant_link: &RelevantLinkStatus, flags_setter: &mut F) -> bool where F: FnMut(&Self, ElementSelectorFlags); fn match_pseudo_element(&self, pe: &<Self::Impl as SelectorImpl>::PseudoElement, context: &mut MatchingContext) -> bool; /// Whether this element is a `link`. fn is_link(&self) -> bool; fn get_id(&self) -> Option<<Self::Impl as SelectorImpl>::Identifier>; fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName) -> bool; /// Returns whether this element matches `:empty`. /// /// That is, whether it does not contain any child element or any non-zero-length text node. /// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo fn is_empty(&self) -> bool; /// Returns whether this element matches `:root`, /// i.e. whether it is the root element of a document. /// /// Note: this can be false even if `.parent_element()` is `None` /// if the parent node is a `DocumentFragment`. fn is_root(&self) -> bool; }<|fim▁end|>
/// Empty string for no namespace
<|file_name|>test_despike.py<|end_file_name|><|fim▁begin|>import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks of spectra for testing purposes 'wavelist_speclist_generate' can be used as input to any other test function that needs access to the variables it returns! wave1, spec1 are a single chunk of 1d spectrum wavelist, speclist are lists of three chunks of 1d spectrum ''' wave1, spec1 = np.loadtxt(os.path.join(DATAPATH, 'spec1test.txt'), unpack=True) wave2, spec2 = np.loadtxt(os.path.join(DATAPATH, 'spec2test.txt'), unpack=True)<|fim▁hole|> return wave1, spec1, wavelist, speclist @pytest.mark.parametrize('filelist, cond', [ (FILELIST1, False), (FILELIST2, True), ]) def test_read_infiles(filelist, cond): ''' Test reading in both text and fits files Each resulting wavelength array should be sorted in ascending order ''' infilelist, wavelist, speclist = despike.read_infiles(DATAPATH, filelist, cond) assert len(infilelist) > 0 assert len(infilelist) == len(wavelist) assert len(wavelist) == len(speclist) for wave in wavelist: assert all(value >= 0 for value in wave) assert list(np.sort(wave)) == list(wave) assert all(np.equal(np.sort(wave), wave)) def test_simpledespike(wave_spec_generate): ''' spike condition is met at pixels 15, 16, 17 and 18 so indices 9 through 24, inclusive, should be removed ''' wave, spec = wave_spec_generate[0], wave_spec_generate[1] newwave, newspec = despike.simpledespike(wave, spec, delwindow=6, stdfactorup=0.7, stdfactordown=3, plot=False) assert len(newwave) == len(newspec) assert len(newwave) <= len(wave) assert len(newspec) <= len(spec) assert all(np.equal(np.hstack((wave[0:9], wave[25:])), newwave)) assert all(np.equal(np.hstack((spec[0:9], spec[25:])), newspec)) def test_despike_spectra(wave_spec_generate): ''' Test that new spectra are shorter than the original because the outliers are gone ''' wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3] newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False) assert len(newwavelist) == len(wavelist) assert len(newspeclist) == len(speclist)<|fim▁end|>
wave3, spec3 = np.loadtxt(os.path.join(DATAPATH, 'spec3test.txt'), unpack=True) wavelist = [wave1, wave2, wave3] speclist = [spec1, spec2, spec3]
<|file_name|>CreateUserOrgHierarchySample.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ package org.apache.directory.fortress.core.samples; import org.apache.directory.fortress.core.DelAdminMgr; import org.apache.directory.fortress.core.DelAdminMgrFactory; import org.apache.directory.fortress.core.SecurityException; import org.apache.directory.fortress.core.model.OrgUnit; import org.apache.directory.fortress.core.impl.TestUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CreateUserOrgHierarchySample JUnit Test. This test program will show how to build a simple User OrgUnit hierarchy which are * used to enable administrators to group Users by organizational structure. This system supports multiple * inheritance between OrgUnits and there are no limits on how deep a hierarchy can be. The OrgUnits require name and type. Optionally can * include a description. The User OrgUnit must be associated with Users and are used to provide Administratrive RBAC control * over who may perform User Role assigns and deassigns in directory. * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class CreateUserOrgHierarchySample extends TestCase { private static final String CLS_NM = CreateUserOrgHierarchySample.class.getName(); private static final Logger LOG = LoggerFactory.getLogger( CLS_NM ); // This constant will be added to index for creation of multiple nodes in directory. public static final String TEST_HIER_USERORG_PREFIX = "sampleHierUserOrg"; public static final String TEST_HIER_BASE_USERORG = "sampleHierUserOrg1"; public static final int TEST_NUMBER = 6; public static final String TEST_HIER_DESC_USERORG_PREFIX = "sampleHierUserOrgD"; public static final String TEST_HIER_ASC_USERORG_PREFIX = "sampleHierUserOrgA"; /** * Simple constructor kicks off JUnit test suite. * @param name */ public CreateUserOrgHierarchySample(String name) { super(name); } /** * Run the User OrgUnit test cases. * * @return Test */ public static Test suite() { TestSuite suite = new TestSuite(); if(!AllSamplesJUnitTest.isFirstRun()) { suite.addTest(new CreateUserOrgHierarchySample("testDeleteHierUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testDeleteDescendantUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testDeleteAscendantUserOrgs")); } suite.addTest(new CreateUserOrgHierarchySample("testCreateHierUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testCreateDescendantUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testCreateAscendantUserOrgs")); /* suite.addTest(new CreateUserOrgHierarchySample("testDeleteHierUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testCreateHierUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testDeleteDescendantUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testCreateDescendantUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testDeleteAscendantUserOrgs")); suite.addTest(new CreateUserOrgHierarchySample("testCreateAscendantUserOrgs")); */ return suite; } /** * Remove the simple hierarchical OrgUnits from the directory. Before removal call the API to move the relationship * between the parent and child OrgUnits. Once the relationship is removed the parent OrgUnit can be removed. * User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap. * <p> * <img src="./doc-files/HierUserOrgSimple.png" alt=""> */ public static void testDeleteHierUserOrgs() { String szLocation = ".testDeleteHierUserOrgs"; if(AllSamplesJUnitTest.isFirstRun()) { return; } try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext()); for (int i = 1; i < TEST_NUMBER; i++) { // The key that must be set to locate any OrgUnit is simply the name and type. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + i, OrgUnit.Type.USER); OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER); // Remove the relationship from the parent and child OrgUnit: delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit); // Remove the parent OrgUnit from directory: delAdminMgr.delete(parentOrgUnit); } // Remove the child OrgUnit from directory: delAdminMgr.delete(new OrgUnit(TEST_HIER_USERORG_PREFIX + TEST_NUMBER, OrgUnit.Type.USER)); LOG.info(szLocation + " success"); } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } /** * Add a simple OrgUnit hierarchy to ldap. The OrgUnits will named to include a name,'sampleHierUserOrg', appended with the * sequence of 1 - 6. 'sampleHierUserOrg1' is the root or highest level OrgUnit in the structure while sampleHierUserOrg6 is the lowest * most child. Fortress OrgUnits may have multiple parents which is demonstrated in testCreateAscendantUserOrgs sample. * <p> * <img src="./doc-files/HierUserOrgSimple.png" alt=""> */ public static void testCreateHierUserOrgs() { String szLocation = ".testCreateHierUserOrgs"; try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext()); // Instantiate the root OrgUnit entity. OrgUnit requires name and type before addition. OrgUnit baseOrgUnit = new OrgUnit(TEST_HIER_BASE_USERORG, OrgUnit.Type.USER); // Add the root OrgUnit entity to the directory. delAdminMgr.add(baseOrgUnit); // Create User OrgUnits, 'sampleHierUserOrg2' - 'sampleHierUserOrg6'. for (int i = 2; i < TEST_NUMBER + 1; i++) { // Instantiate the OrgUnit entity. OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + i, OrgUnit.Type.USER); // Add the OrgUnit entity to the directory. delAdminMgr.add(childOrgUnit); // Instantiate the parent OrgUnit. The key is the name and type. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + (i - 1), OrgUnit.Type.USER); // Add a relationship between the parent and child OrgUnits: delAdminMgr.addInheritance(parentOrgUnit, childOrgUnit); } LOG.info(szLocation + " success"); } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } /** * Demonstrate teardown of a parent to child relationship of one-to-many. Each child must first remove the inheritance * relationship with parent before being removed from ldap. The parent OrgUnit will be removed from ldap last. * User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap. * <p> * <img src="./doc-files/HierUserOrgDescendants.png" alt=""> */ public static void testDeleteDescendantUserOrgs() { String szLocation = ".testDeleteDescendantUserOrgs"; if(AllSamplesJUnitTest.isFirstRun()) { return; } try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext()); // This parent has many children. They must be deleted before parent itself can. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + 1, OrgUnit.Type.USER); // There are N User OrgUnits to process: for (int i = 2; i < TEST_NUMBER + 1; i++) { // Instantiate the child OrgUnit entity. The key is the name and type. OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + i, OrgUnit.Type.USER); // Remove the relationship from the parent and child OrgUnit: delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit); // Remove the child OrgUnit from directory: delAdminMgr.delete(childOrgUnit); } // Remove the parent OrgUnit from directory: delAdminMgr.delete(parentOrgUnit); LOG.info(szLocation + " success"); } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } /** * Demonstrate a parent to child OrgUnit structure of one-to-many. The parent OrgUnit must be created before * the call to addDescendant which will Add a new OrgUnit node and set a OrgUnit relationship with parent node. * <p> * <img src="./doc-files/HierUserOrgDescendants.png" alt=""> */ public static void testCreateDescendantUserOrgs() { String szLocation = ".testCreateDescendantUserOrgs"; try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());<|fim▁hole|> // Instantiate the parent User OrgUnit entity. This needs a name and type before it can be added to ldap. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + 1, OrgUnit.Type.USER); // This parent will have many children: delAdminMgr.add(parentOrgUnit); // Create User OrgUnits, 'sampleHierUserOrgD2' - 'sampleHierUserOrgD6'. for (int i = 1; i < TEST_NUMBER; i++) { // Now add relationship to the directory between parent and child User OrgUnits. OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER); // Now add child OrgUnit entity to directory and add relationship with existing parent OrgUnit. delAdminMgr.addDescendant(parentOrgUnit, childOrgUnit); } LOG.info(szLocation + " success"); } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } /** * This example demonstrates tear down of a child to parent represented as one-to-many. The parents must all * be removed from the child before the child can be removed. * User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap. * <p> * <img src="./doc-files/HierUserOrgAscendants.png" alt=""> */ public static void testDeleteAscendantUserOrgs() { String szLocation = ".testDeleteAscendantUserOrgs"; if(AllSamplesJUnitTest.isFirstRun()) { return; } try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext()); // This child OrgUnit has many parents: OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + 1, OrgUnit.Type.USER); for (int i = 2; i < TEST_NUMBER + 1; i++) { // Instantiate the parent. This needs a name and type before it can be used in operation. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + i, OrgUnit.Type.USER); // Remove the relationship between parent and child OrgUnits: delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit); // Remove the parent OrgUnit from directory: delAdminMgr.delete(parentOrgUnit); } // Remove the child OrgUnit from directory: delAdminMgr.delete(childOrgUnit); LOG.info(szLocation + " success"); } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } /** * Demonstrate a child to parent OrgUnit structure of one-to-many. To use this API, the child OrgUnit must be created before * the call to addAscendant which will Add a new OrgUnit node and set a OrgUnit relationship with child node. * <p> * <img src="./doc-files/HierUserOrgAscendants.png" alt=""> */ public static void testCreateAscendantUserOrgs() { String szLocation = ".testCreateAscendantUserOrgs"; try { // Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies. DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext()); // Instantiate the child OrgUnit. This needs a name and type. OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + 1, OrgUnit.Type.USER); // This child will have many parents: delAdminMgr.add(childOrgUnit); // Create OrgUnits, 'sampleHierUserOrgA2' - 'sampleHierUserOrgA6'. for (int i = 1; i < TEST_NUMBER; i++) { // Instantiate the parent OrgUnit. This needs a name and type before it can be added to ldap. OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER); // Now add parent OrgUnit entity to directory and add relationship with existing child OrgUnit. delAdminMgr.addAscendant(childOrgUnit, parentOrgUnit); } } catch (SecurityException ex) { LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex); fail(ex.getMessage()); } } }<|fim▁end|>
<|file_name|>589.async.js<|end_file_name|><|fim▁begin|>require.ensure([], function(require) { require("./73.async.js"); require("./147.async.js"); require("./294.async.js"); require("./588.async.js");<|fim▁hole|><|fim▁end|>
}); module.exports = 589;
<|file_name|>media_queries.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Servo's media-query device and expression representation. use app_units::Au; use cssparser::RGBA; use custom_properties::CssEnvironment; use euclid::{Size2D, TypedScale, TypedSize2D}; use media_queries::media_feature::{AllowsRanges, ParsingRequirements}; use media_queries::media_feature::{Evaluator, MediaFeatureDescription}; use media_queries::media_feature_expression::RangeOrOperator; use media_queries::MediaType; use properties::ComputedValues; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::viewport::ViewportConstraints; use style_traits::{CSSPixel, DevicePixel}; use values::computed::font::FontSize; use values::computed::CSSPixelLength; use values::KeyframesName; /// A device is a structure that represents the current media a given document /// is displayed in. /// /// This is the struct against which media queries are evaluated. #[derive(Debug, MallocSizeOf)] pub struct Device {<|fim▁hole|> /// The current device pixel ratio, from CSS pixels to device pixels. device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, /// The font size of the root element /// This is set when computing the style of the root /// element, and used for rem units in other elements /// /// When computing the style of the root element, there can't be any /// other style being computed at the same time, given we need the style of /// the parent to compute everything else. So it is correct to just use /// a relaxed atomic here. #[ignore_malloc_size_of = "Pure stack type"] root_font_size: AtomicIsize, /// Whether any styles computed in the document relied on the root font-size /// by using rem units. #[ignore_malloc_size_of = "Pure stack type"] used_root_font_size: AtomicBool, /// Whether any styles computed in the document relied on the viewport size. #[ignore_malloc_size_of = "Pure stack type"] used_viewport_units: AtomicBool, /// The CssEnvironment object responsible of getting CSS environment /// variables. environment: CssEnvironment, } impl Device { /// Trivially construct a new `Device`. pub fn new( media_type: MediaType, viewport_size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, ) -> Device { Device { media_type, viewport_size, device_pixel_ratio, // FIXME(bz): Seems dubious? root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize), used_root_font_size: AtomicBool::new(false), used_viewport_units: AtomicBool::new(false), environment: CssEnvironment, } } /// Get the relevant environment to resolve `env()` functions. #[inline] pub fn environment(&self) -> &CssEnvironment { &self.environment } /// Return the default computed values for this device. pub fn default_computed_values(&self) -> &ComputedValues { // FIXME(bz): This isn't really right, but it's no more wrong // than what we used to do. See // https://github.com/servo/servo/issues/14773 for fixing it properly. ComputedValues::initial_values() } /// Get the font size of the root element (for rem) pub fn root_font_size(&self) -> Au { self.used_root_font_size.store(true, Ordering::Relaxed); Au::new(self.root_font_size.load(Ordering::Relaxed) as i32) } /// Set the font size of the root element (for rem) pub fn set_root_font_size(&self, size: Au) { self.root_font_size .store(size.0 as isize, Ordering::Relaxed) } /// Sets the body text color for the "inherit color from body" quirk. /// /// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk> pub fn set_body_text_color(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. true } /// Returns whether we ever looked up the root font size of the Device. pub fn used_root_font_size(&self) -> bool { self.used_root_font_size.load(Ordering::Relaxed) } /// Returns the viewport size of the current device in app units, needed, /// among other things, to resolve viewport units. #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new( Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height), ) } /// Like the above, but records that we've used viewport units. pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.used_viewport_units.store(true, Ordering::Relaxed); self.au_viewport_size() } /// Whether viewport units were used since the last device change. pub fn used_viewport_units(&self) -> bool { self.used_viewport_units.load(Ordering::Relaxed) } /// Returns the device pixel ratio. pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { self.device_pixel_ratio } /// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self.media_type.clone() } /// Returns whether document colors are enabled. pub fn use_document_colors(&self) -> bool { true } /// Returns the default background color. pub fn default_background_color(&self) -> RGBA { RGBA::new(255, 255, 255, 255) } } /// https://drafts.csswg.org/mediaqueries-4/#width fn eval_width( device: &Device, value: Option<CSSPixelLength>, range_or_operator: Option<RangeOrOperator>, ) -> bool { RangeOrOperator::evaluate( range_or_operator, value.map(Au::from), device.au_viewport_size().width, ) } #[derive(Clone, Copy, Debug, FromPrimitive, Parse, ToCss)] #[repr(u8)] enum Scan { Progressive, Interlace, } /// https://drafts.csswg.org/mediaqueries-4/#scan fn eval_scan(_: &Device, _: Option<Scan>) -> bool { // Since we doesn't support the 'tv' media type, the 'scan' feature never // matches. false } lazy_static! { /// A list with all the media features that Servo supports. pub static ref MEDIA_FEATURES: [MediaFeatureDescription; 2] = [ feature!( atom!("width"), AllowsRanges::Yes, Evaluator::Length(eval_width), ParsingRequirements::empty(), ), feature!( atom!("scan"), AllowsRanges::No, keyword_evaluator!(eval_scan, Scan), ParsingRequirements::empty(), ), ]; }<|fim▁end|>
/// The current media type used by de device. media_type: MediaType, /// The current viewport size, in CSS pixels. viewport_size: TypedSize2D<f32, CSSPixel>,
<|file_name|>test_output_plots.py<|end_file_name|><|fim▁begin|>''' Tests of output_plots.py module ''' import pytest import os import numpy as np import matplotlib.image as mpimg from ogusa import utils, output_plots # Load in test results and parameters CUR_PATH = os.path.abspath(os.path.dirname(__file__)) base_ss = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'SS_vars_baseline.pkl')) base_tpi = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TPI_vars_baseline.pkl')) base_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_baseline.pkl')) base_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_baseline.pkl')) reform_ss = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'SS_vars_reform.pkl')) reform_tpi = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TPI_vars_reform.pkl')) reform_params = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'model_params_reform.pkl')) reform_taxfunctions = utils.safe_read_pickle( os.path.join(CUR_PATH, 'test_io_data', 'TxFuncEst_reform.pkl')) test_data = [(base_tpi, base_params, reform_tpi, reform_params, 'pct_diff', None, None),<|fim▁hole|> (base_tpi, base_params, reform_tpi, reform_params, 'cbo', None, None), (base_tpi, base_params, reform_tpi, reform_params, 'levels', None, None), (base_tpi, base_params, None, None, 'levels', None, None), (base_tpi, base_params, None, None, 'levels', [2040, 2060], None), (base_tpi, base_params, None, None, 'levels', None, 'Test plot title') ] @pytest.mark.parametrize( 'base_tpi,base_params,reform_tpi,reform_parms,plot_type,' + 'vertical_line_years,plot_title', test_data, ids=['Pct Diff', 'Diff', 'CBO', 'Levels w reform', 'Levels w/o reform', 'Vertical line included', 'Plot title included']) def test_plot_aggregates(base_tpi, base_params, reform_tpi, reform_parms, plot_type, vertical_line_years, plot_title): fig = output_plots.plot_aggregates( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, var_list=['Y', 'r'], plot_type=plot_type, num_years_to_plot=20, vertical_line_years=vertical_line_years, plot_title=plot_title) assert fig test_data = [(base_tpi, base_params, None, None, None, None), (base_tpi, base_params, reform_tpi, reform_params, None, None), (base_tpi, base_params, reform_tpi, reform_params, [2040, 2060], None), (base_tpi, base_params, None, None, None, 'Test plot title') ] def test_plot_aggregates_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.plot_aggregates( base_tpi, base_params, plot_type='levels', path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) test_data = [(base_tpi, base_params, None, None, None, None, 'levels'), (base_tpi, base_params, reform_tpi, reform_params, None, None, 'levels'), (base_tpi, base_params, reform_tpi, reform_params, None, None, 'diffs'), (base_tpi, base_params, reform_tpi, reform_params, [2040, 2060], None, 'levels'), (base_tpi, base_params, None, None, None, 'Test plot title', 'levels') ] @pytest.mark.parametrize( 'base_tpi,base_params,reform_tpi,reform_params,' + 'vertical_line_years,plot_title,plot_type', test_data, ids=['No reform', 'With reform', 'Differences', 'Vertical line included', 'Plot title included']) def test_plot_gdp_ratio(base_tpi, base_params, reform_tpi, reform_params, vertical_line_years, plot_title, plot_type): fig = output_plots.plot_gdp_ratio( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, plot_type=plot_type, vertical_line_years=vertical_line_years, plot_title=plot_title) assert fig def test_plot_gdp_ratio_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.plot_aggregates( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) def test_ability_bar(): fig = output_plots.ability_bar( base_tpi, base_params, reform_tpi, reform_params, plot_title=' Test Plot Title') assert fig def test_ability_bar_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.ability_bar( base_tpi, base_params, reform_tpi, reform_params, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) def test_ability_bar_ss(): fig = output_plots.ability_bar_ss( base_ss, base_params, reform_ss, reform_params, plot_title=' Test Plot Title') assert fig @pytest.mark.parametrize( 'by_j,plot_data', [(True, False), (False, False), (False, True)], ids=['By j', 'Not by j', 'Plot data']) def test_ss_profiles(by_j, plot_data): fig = output_plots.ss_profiles( base_ss, base_params, reform_ss, reform_params, by_j=by_j, plot_data=plot_data, plot_title=' Test Plot Title') assert fig def test_ss_profiles_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.ss_profiles( base_ss, base_params, reform_ss, reform_params, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) @pytest.mark.parametrize( 'by_j', [True, False], ids=['By j', 'Not by j']) def test_tpi_profiles(by_j): fig = output_plots.tpi_profiles( base_tpi, base_params, reform_tpi, reform_params, by_j=by_j, plot_title=' Test Plot Title') assert fig test_data = [(base_params, base_ss, None, None, 'levels', None), (base_params, base_ss, reform_params, reform_ss, 'levels', None), (base_params, base_ss, reform_params, reform_ss, 'diff', None), (base_params, base_ss, reform_params, reform_ss, 'pct_diff', None), (base_params, base_ss, reform_params, reform_ss, 'pct_diff', 'Test Plot Title') ] def test_tpi_profiles_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.tpi_profiles( base_tpi, base_params, reform_tpi, reform_params, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) @pytest.mark.parametrize( 'base_params,base_ss,reform_params,reform_ss,plot_type,plot_title', test_data, ids=['Levels', 'Levels w/ reform', 'Differences', 'Pct Diffs', 'Plot title included']) def test_ss_3Dplot(base_params, base_ss, reform_params, reform_ss, plot_type, plot_title): fig = output_plots.ss_3Dplot( base_params, base_ss, reform_params=reform_params, reform_ss=reform_ss, plot_type=plot_type, plot_title=plot_title) assert fig def test_ss_3Dplot_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.ss_3Dplot( base_params, base_ss, reform_params=reform_params, reform_ss=reform_ss, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) @pytest.mark.parametrize( 'base_tpi,base_params,reform_tpi, reform_params,ineq_measure,' + 'pctiles,plot_type', [(base_tpi, base_params, None, None, 'gini', None, 'levels'), (base_tpi, base_params, reform_tpi, reform_params, 'gini', None, 'levels'), (base_tpi, base_params, reform_tpi, reform_params, 'var_of_logs', None, 'diff'), (base_tpi, base_params, reform_tpi, reform_params, 'pct_ratio', (0.9, 0.1), 'levels'), (base_tpi, base_params, reform_tpi, reform_params, 'top_share', (0.01), 'pct_diff')], ids=['Just baseline', 'Baseline + Reform', 'Base + Refore, var logs, diff', 'Base + Refore, pct ratios', 'Base + Refore, top share, pct diff']) def test_inequality_plot(base_tpi, base_params, reform_tpi, reform_params, ineq_measure, pctiles, plot_type): fig = output_plots.inequality_plot( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, ineq_measure=ineq_measure, pctiles=pctiles, plot_type=plot_type) assert fig def test_inequality_plot_save_fig(tmpdir): path = os.path.join(tmpdir, 'test_plot.png') output_plots.inequality_plot( base_tpi, base_params, reform_tpi=reform_tpi, reform_params=reform_params, path=path) img = mpimg.imread(path) assert isinstance(img, np.ndarray) def test_plot_all(tmpdir): base_output_path = os.path.join(CUR_PATH, 'test_io_data', 'OUTPUT') reform_output_path = os.path.join(CUR_PATH, 'test_io_data', 'OUTPUT') output_plots.plot_all(base_output_path, reform_output_path, tmpdir) img1 = mpimg.imread(os.path.join(tmpdir, 'MacroAgg_PctChange.png')) img2 = mpimg.imread(os.path.join( tmpdir, 'SSLifecycleProfile_Cons_Reform.png')) img3 = mpimg.imread(os.path.join( tmpdir, 'SSLifecycleProfile_Save_Reform.png')) assert isinstance(img1, np.ndarray) assert isinstance(img2, np.ndarray) assert isinstance(img3, np.ndarray)<|fim▁end|>
(base_tpi, base_params, reform_tpi, reform_params, 'diff', None, None),
<|file_name|>cli.py<|end_file_name|><|fim▁begin|># Copyright 2014 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import sys import time from catkin_pkg.package import InvalidPackage from catkin_tools.argument_parsing import add_context_args from catkin_tools.argument_parsing import add_cmake_and_make_and_catkin_make_args from catkin_tools.common import format_time_delta from catkin_tools.common import is_tty from catkin_tools.common import log from catkin_tools.common import find_enclosing_package from catkin_tools.context import Context from catkin_tools.terminal_color import set_color from catkin_tools.metadata import get_metadata from catkin_tools.metadata import update_metadata from catkin_tools.resultspace import load_resultspace_environment from .color import clr<|fim▁hole|> from .build import build_isolated_workspace from .build import determine_packages_to_be_built from .build import topological_order_packages from .build import verify_start_with_option def prepare_arguments(parser): parser.description = "Build one or more packages in a catkin workspace.\ This invokes `CMake`, `make`, and optionally `make install` for either all\ or the specified packages in a catkin workspace.\ \ Arguments passed to this verb can temporarily override persistent options\ stored in the catkin profile config. If you want to save these options, use\ the --save-config argument. To see the current config, use the\ `catkin config` command." # Workspace / profile args add_context_args(parser) # Sub-commands add = parser.add_argument add('--dry-run', '-d', action='store_true', default=False, help='List the packages which will be built with the given arguments without building them.') # What packages to build pkg_group = parser.add_argument_group('Packages', 'Control which packages get built.') add = pkg_group.add_argument add('packages', metavar='PKGNAME', nargs='*', help='Workspace packages to build, package dependencies are built as well unless --no-deps is used. ' 'If no packages are given, then all the packages are built.') add('--this', dest='build_this', action='store_true', default=False, help='Build the package containing the current working directory.') add('--no-deps', action='store_true', default=False, help='Only build specified packages, not their dependencies.') start_with_group = pkg_group.add_mutually_exclusive_group() add = start_with_group.add_argument add('--start-with', metavar='PKGNAME', type=str, help='Build a given package and those which depend on it, skipping any before it.') add('--start-with-this', action='store_true', default=False, help='Similar to --start-with, starting with the package containing the current directory.') # Build options build_group = parser.add_argument_group('Build', 'Control the build behaiovr.') add = build_group.add_argument add('--force-cmake', action='store_true', default=None, help='Runs cmake explicitly for each catkin package.') add('--no-install-lock', action='store_true', default=None, help='Prevents serialization of the install steps, which is on by default to prevent file install collisions') config_group = parser.add_argument_group('Config', 'Parameters for the underlying buildsystem.') add = config_group.add_argument add('--save-config', action='store_true', default=False, help='Save any configuration options in this section for the next build invocation.') add_cmake_and_make_and_catkin_make_args(config_group) # Behavior behavior_group = parser.add_argument_group('Interface', 'The behavior of the command-line interface.') add = behavior_group.add_argument add('--force-color', action='store_true', default=False, help='Forces catkin build to ouput in color, even when the terminal does not appear to support it.') add('--verbose', '-v', action='store_true', default=False, help='Print output from commands in ordered blocks once the command finishes.') add('--interleave-output', '-i', action='store_true', default=False, help='Prevents ordering of command output when multiple commands are running at the same time.') add('--no-status', action='store_true', default=False, help='Suppresses status line, useful in situations where carriage return is not properly supported.') add('--no-notify', action='store_true', default=False, help='Suppresses system popup notification.') return parser def dry_run(context, packages, no_deps, start_with): # Print Summary log(context.summary()) # Find list of packages in the workspace packages_to_be_built, packages_to_be_built_deps, all_packages = determine_packages_to_be_built(packages, context) # Assert start_with package is in the workspace verify_start_with_option(start_with, packages, all_packages, packages_to_be_built + packages_to_be_built_deps) if not no_deps: # Extend packages to be built to include their deps packages_to_be_built.extend(packages_to_be_built_deps) # Also resort packages_to_be_built = topological_order_packages(dict(packages_to_be_built)) # Print packages log("Packages to be built:") max_name_len = str(max([len(pkg.name) for pth, pkg in packages_to_be_built])) prefix = clr('@{pf}' + ('------ ' if start_with else '- ') + '@|') for pkg_path, pkg in packages_to_be_built: build_type = get_build_type(pkg) if build_type == 'catkin' and 'metapackage' in [e.tagname for e in pkg.exports]: build_type = 'metapackage' if start_with and pkg.name == start_with: start_with = None log(clr("{prefix}@{cf}{name:<" + max_name_len + "}@| (@{yf}{build_type}@|)") .format(prefix=clr('@!@{kf}(skip)@| ') if start_with else prefix, name=pkg.name, build_type=build_type)) log("Total packages: " + str(len(packages_to_be_built))) def main(opts): # Context-aware args if opts.build_this or opts.start_with_this: # Determine the enclosing package try: this_package = find_enclosing_package() except InvalidPackage: pass # Handle context-based package building if opts.build_this: if this_package: opts.packages += [this_package] else: sys.exit("catkin build: --this was specified, but this directory is not contained by a catkin package.") # If --start--with was used without any packages and --this was specified, start with this package if opts.start_with_this: if this_package: opts.start_with = this_package else: sys.exit("catkin build: --this was specified, but this directory is not contained by a catkin package.") if opts.no_deps and not opts.packages: sys.exit("With --no-deps, you must specify packages to build.") if not opts.force_color and not is_tty(sys.stdout): set_color(False) # Load the context ctx = Context.Load(opts.workspace, opts.profile, opts) # Load the environment of the workspace to extend if ctx.extend_path is not None: try: load_resultspace_environment(ctx.extend_path) except IOError as exc: log(clr("@!@{rf}Error:@| Unable to extend workspace from \"%s\": %s" % (ctx.extend_path, exc.message))) return 1 # Display list and leave the filesystem untouched if opts.dry_run: dry_run(ctx, opts.packages, opts.no_deps, opts.start_with) return # Check if the context is valid before writing any metadata if not ctx.source_space_exists(): print("catkin build: error: Unable to find source space `%s`" % ctx.source_space_abs) return 1 # Always save the last context under the build verb update_metadata(ctx.workspace, ctx.profile, 'build', ctx.get_stored_dict()) build_metadata = get_metadata(ctx.workspace, ctx.profile, 'build') if build_metadata.get('needs_force', False): opts.force_cmake = True update_metadata(ctx.workspace, ctx.profile, 'build', {'needs_force': False}) # Save the context as the configuration if opts.save_config: Context.Save(ctx) start = time.time() try: return build_isolated_workspace( ctx, packages=opts.packages, start_with=opts.start_with, no_deps=opts.no_deps, jobs=opts.parallel_jobs, force_cmake=opts.force_cmake, force_color=opts.force_color, quiet=not opts.verbose, interleave_output=opts.interleave_output, no_status=opts.no_status, lock_install=not opts.no_install_lock, no_notify=opts.no_notify ) finally: log("[build] Runtime: {0}".format(format_time_delta(time.time() - start)))<|fim▁end|>
from .common import get_build_type
<|file_name|>script_settings.py<|end_file_name|><|fim▁begin|><|fim▁hole|>../../../../../../../share/pyshared/orca/scripts/apps/packagemanager/script_settings.py<|fim▁end|>
<|file_name|>DataDescription.tsx<|end_file_name|><|fim▁begin|>/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import {Typography, Popover, Input, Select, Checkbox} from 'antd'; import {DataInspectorSetValue} from './DataInspectorNode'; import {PureComponent} from 'react'; import styled from '@emotion/styled'; import {SketchPicker, CompactPicker} from 'react-color'; import React, {KeyboardEvent} from 'react'; import {HighlightContext} from '../Highlight'; import {parseColor} from '../../utils/parseColor'; import {TimelineDataDescription} from './TimelineDataDescription'; import {theme} from '../theme'; import {EditOutlined} from '@ant-design/icons'; import type {CheckboxChangeEvent} from 'antd/lib/checkbox'; const {Link} = Typography; // Based on FIG UI Core, TODO: does that still makes sense? export const presetColors = Object.values({ blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons green: '#42b72a', // Green - Confirmation, success, commerce and status red: '#FC3A4B', // Red - Badges, error states blueGray: '#5f6673', // Blue Grey slate: '#b9cad2', // Slate aluminum: '#a3cedf', // Aluminum seaFoam: '#54c7ec', // Sea Foam teal: '#6bcebb', // Teal lime: '#a3ce71', // Lime lemon: '#fcd872', // Lemon orange: '#f7923b', // Orange tomato: '#fb724b', // Tomato - Tometo? Tomato. cherry: '#f35369', // Cherry pink: '#ec7ebd', // Pink grape: '#8c72cb', // Grape }); export const NullValue = styled.span({ color: theme.semanticColors.nullValue, }); NullValue.displayName = 'DataDescription:NullValue'; const UndefinedValue = styled.span({ color: theme.semanticColors.nullValue, }); UndefinedValue.displayName = 'DataDescription:UndefinedValue'; export const StringValue = styled.span({ color: theme.semanticColors.stringValue, wordWrap: 'break-word', }); StringValue.displayName = 'DataDescription:StringValue'; const ColorValue = styled.span({ color: theme.semanticColors.colorValue, }); ColorValue.displayName = 'DataDescription:ColorValue'; const SymbolValue = styled.span({ color: theme.semanticColors.stringValue, }); SymbolValue.displayName = 'DataDescription:SymbolValue'; export const NumberValue = styled.span({ color: theme.semanticColors.numberValue, }); NumberValue.displayName = 'DataDescription:NumberValue'; export const BooleanValue = styled.span({ color: theme.semanticColors.booleanValue, }); BooleanValue.displayName = 'DataDescription:BooleanValue'; const ColorBox = styled.span<{color: string}>((props) => ({ backgroundColor: props.color, boxShadow: `inset 0 0 1px ${theme.black}`, display: 'inline-block', height: 12, marginRight: 4, verticalAlign: 'middle', width: 12, borderRadius: 4, })); ColorBox.displayName = 'DataDescription:ColorBox'; const FunctionKeyword = styled.span({ color: theme.semanticColors.nullValue, fontStyle: 'italic', }); FunctionKeyword.displayName = 'DataDescription:FunctionKeyword'; const FunctionName = styled.span({ fontStyle: 'italic', }); FunctionName.displayName = 'DataDescription:FunctionName'; const ColorPickerDescription = styled.div({ display: 'inline', position: 'relative', }); ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription'; const EmptyObjectValue = styled.span({ fontStyle: 'italic', }); EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue'; export type DataDescriptionType = | 'number' | 'string' | 'boolean' | 'undefined' | 'null' | 'object' | 'array' | 'date' | 'symbol' | 'function' | 'bigint' | 'text' // deprecated, please use string | 'enum' // unformatted string | 'color' | 'picker' // multiple choise item like an, eehhh, enum | 'timeline' | 'color_lite'; // color with limited palette, specific for fblite; type DataDescriptionProps = { path?: Array<string>; type: DataDescriptionType; value: any; extra?: any; setValue: DataInspectorSetValue | null | undefined; }; type DescriptionCommitOptions = { value: any; keep: boolean; clear: boolean; set: boolean; }; class NumberTextEditor extends PureComponent<{ commit: (opts: DescriptionCommitOptions) => void; type: DataDescriptionType; value: any; origValue: any; }> { onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const val = this.props.type === 'number' ? parseFloat(e.target.value) : e.target.value; this.props.commit({ clear: false, keep: true, value: val, set: false, }); }; onNumberTextInputKeyDown = (e: KeyboardEvent) => { if (e.key === 'Enter') { const val = this.props.type === 'number' ? parseFloat(this.props.value) : this.props.value; this.props.commit({clear: true, keep: true, value: val, set: true}); } else if (e.key === 'Escape') { this.props.commit({ clear: true,<|fim▁hole|> value: this.props.origValue, set: false, }); } }; onNumberTextRef = (ref: HTMLElement | undefined | null) => { if (ref) { ref.focus(); } }; onNumberTextBlur = () => { this.props.commit({ clear: true, keep: true, value: this.props.value, set: true, }); }; render() { const extraProps: any = {}; if (this.props.type === 'number') { // render as a HTML number input extraProps.type = 'number'; // step="any" allows any sort of float to be input, otherwise we're limited // to decimal extraProps.step = 'any'; } return ( <Input key="input" {...extraProps} size="small" onChange={this.onNumberTextInputChange} onKeyDown={this.onNumberTextInputKeyDown} ref={this.onNumberTextRef} onBlur={this.onNumberTextBlur} value={this.props.value} style={{fontSize: 11}} /> ); } } type DataDescriptionState = { editing: boolean; origValue: any; value: any; }; export class DataDescription extends PureComponent< DataDescriptionProps, DataDescriptionState > { constructor(props: DataDescriptionProps, context: Object) { super(props, context); this.state = { editing: false, origValue: '', value: '', }; } commit = (opts: DescriptionCommitOptions) => { const {path, setValue} = this.props; if (opts.keep && setValue && path) { const val = opts.value; this.setState({value: val}); if (opts.set) { setValue(path, val); } } if (opts.clear) { this.setState({ editing: false, origValue: '', value: '', }); } }; _renderEditing() { const {type, extra} = this.props; const {origValue, value} = this.state; if ( type === 'string' || type === 'text' || type === 'number' || type === 'enum' ) { return ( <NumberTextEditor type={type} value={value} origValue={origValue} commit={this.commit} /> ); } if (type === 'color') { return <ColorEditor value={value} commit={this.commit} />; } if (type === 'color_lite') { return ( <ColorEditor value={value} colorSet={extra.colorSet} commit={this.commit} /> ); } return null; } _hasEditUI() { const {type} = this.props; return ( type === 'string' || type === 'text' || type === 'number' || type === 'enum' || type === 'color' || type === 'color_lite' ); } onEditStart = () => { this.setState({ editing: this._hasEditUI(), origValue: this.props.value, value: this.props.value, }); }; render(): any { if (this.state.editing) { return this._renderEditing(); } else { return ( <DataDescriptionPreview type={this.props.type} value={this.props.value} extra={this.props.extra} editable={!!this.props.setValue} commit={this.commit} onEdit={this.onEditStart} /> ); } } } class ColorEditor extends PureComponent<{ value: any; colorSet?: Array<string | number>; commit: (opts: DescriptionCommitOptions) => void; }> { onBlur = (newVisibility: boolean) => { if (!newVisibility) { this.props.commit({ clear: true, keep: false, value: this.props.value, set: true, }); } }; onChange = ({ hex, rgb: {a, b, g, r}, }: { hex: string; rgb: {a: number; b: number; g: number; r: number}; }) => { const prev = this.props.value; let val; if (typeof prev === 'string') { if (a === 1) { // hex is fine and has an implicit 100% alpha val = hex; } else { // turn into a css rgba value val = `rgba(${r}, ${g}, ${b}, ${a})`; } } else if (typeof prev === 'number') { // compute RRGGBBAA value val = (Math.round(a * 255) & 0xff) << 24; val |= (r & 0xff) << 16; val |= (g & 0xff) << 8; val |= b & 0xff; const prevClear = ((prev >> 24) & 0xff) === 0; const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff); if (!onlyAlphaChanged && prevClear) { val = 0xff000000 | (val & 0x00ffffff); } } else { return; } this.props.commit({clear: false, keep: true, value: val, set: true}); }; onChangeLite = ({ rgb: {a, b, g, r}, }: { rgb: {a: number; b: number; g: number; r: number}; }) => { const prev = this.props.value; if (typeof prev !== 'number') { return; } // compute RRGGBBAA value let val = (Math.round(a * 255) & 0xff) << 24; val |= (r & 0xff) << 16; val |= (g & 0xff) << 8; val |= b & 0xff; this.props.commit({clear: false, keep: true, value: val, set: true}); }; render() { const colorInfo = parseColor(this.props.value); if (!colorInfo) { return null; } return ( <Popover trigger={'click'} onVisibleChange={this.onBlur} content={() => this.props.colorSet ? ( <CompactPicker color={colorInfo} colors={this.props.colorSet .filter((x) => x != 0) .map(parseColor) .map((rgba) => { if (!rgba) { return ''; } return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`; })} onChange={(color: { hex: string; hsl: { a?: number; h: number; l: number; s: number; }; rgb: {a?: number; b: number; g: number; r: number}; }) => { this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}}); }} /> ) : ( <SketchPicker color={colorInfo} presetColors={presetColors} onChange={(color: { hex: string; hsl: { a?: number; h: number; l: number; s: number; }; rgb: {a?: number; b: number; g: number; r: number}; }) => { this.onChange({ hex: color.hex, rgb: {...color.rgb, a: color.rgb.a || 1}, }); }} /> ) }> <ColorPickerDescription> <DataDescriptionPreview type="color" value={this.props.value} extra={this.props.colorSet} editable={false} commit={this.props.commit} /> </ColorPickerDescription> </Popover> ); } } class DataDescriptionPreview extends PureComponent<{ type: DataDescriptionType; value: any; extra?: any; editable: boolean; commit: (opts: DescriptionCommitOptions) => void; onEdit?: () => void; }> { onClick = () => { const {onEdit} = this.props; if (this.props.editable && onEdit) { onEdit(); } }; render() { const {type, value} = this.props; const description = ( <DataDescriptionContainer type={type} value={value} editable={this.props.editable} commit={this.props.commit} /> ); // booleans are always editable so don't require the onEditStart handler if (type === 'boolean') { return description; } return ( <span onClick={this.onClick} role="button" tabIndex={-1}> {description} </span> ); } } type Picker = { values: Set<string>; selected: string; }; class DataDescriptionContainer extends PureComponent<{ type: DataDescriptionType; value: any; editable: boolean; commit: (opts: DescriptionCommitOptions) => void; }> { static contextType = HighlightContext; // Replace with useHighlighter context!: React.ContextType<typeof HighlightContext>; onChangeCheckbox = (e: CheckboxChangeEvent) => { this.props.commit({ clear: true, keep: true, value: e.target.checked, set: true, }); }; render(): any { const {type, editable, value: val} = this.props; const highlighter = this.context; switch (type) { case 'timeline': { return ( <> <TimelineDataDescription canSetCurrent={editable} timeline={JSON.parse(val)} onClick={(id) => { this.props.commit({ value: id, keep: true, clear: false, set: true, }); }} /> </> ); } case 'number': return <NumberValue>{+val}</NumberValue>; case 'color': { const colorInfo = parseColor(val); if (typeof val === 'number' && val === 0) { return <UndefinedValue>(not set)</UndefinedValue>; } else if (colorInfo) { const {a, b, g, r} = colorInfo; return ( <> <ColorBox key="color-box" color={`rgba(${r}, ${g}, ${b}, ${a})`} /> <ColorValue key="value"> rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)}) </ColorValue> </> ); } else { return <span>Malformed color</span>; } } case 'color_lite': { const colorInfo = parseColor(val); if (typeof val === 'number' && val === 0) { return <UndefinedValue>(not set)</UndefinedValue>; } else if (colorInfo) { const {a, b, g, r} = colorInfo; return ( <> <ColorBox key="color-box" color={`rgba(${r}, ${g}, ${b}, ${a})`} /> <ColorValue key="value"> rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)}) </ColorValue> </> ); } else { return <span>Malformed color</span>; } } case 'picker': { const picker: Picker = JSON.parse(val); return ( <Select disabled={!this.props.editable} options={Array.from(picker.values).map((value) => ({ value, label: value, }))} value={picker.selected} onChange={(value: string) => this.props.commit({ value, keep: true, clear: false, set: true, }) } size="small" style={{fontSize: 11}} dropdownMatchSelectWidth={false} /> ); } case 'text': case 'string': const isUrl = val.startsWith('http://') || val.startsWith('https://'); if (isUrl) { return ( <> <Link href={val}>{highlighter.render(val)}</Link> {editable && ( <EditOutlined style={{ color: theme.disabledColor, cursor: 'pointer', marginLeft: 8, }} /> )} </> ); } else { return ( <StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue> ); } case 'enum': return <StringValue>{highlighter.render(val)}</StringValue>; case 'boolean': return editable ? ( <Checkbox checked={!!val} disabled={!editable} onChange={this.onChangeCheckbox} /> ) : ( <BooleanValue>{'' + val}</BooleanValue> ); case 'undefined': return <UndefinedValue>undefined</UndefinedValue>; case 'date': if (Object.prototype.toString.call(val) === '[object Date]') { return <span>{val.toString()}</span>; } else { return <span>{val}</span>; } case 'null': return <NullValue>null</NullValue>; // no description necessary as we'll typically wrap it in [] or {} which // already denotes the type case 'array': return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null; case 'object': return Object.keys(val ?? {}).length <= 0 ? ( <EmptyObjectValue>{'{}'}</EmptyObjectValue> ) : null; case 'function': return ( <span> <FunctionKeyword>function</FunctionKeyword> <FunctionName>&nbsp;{val.name}()</FunctionName> </span> ); case 'symbol': return <SymbolValue>Symbol()</SymbolValue>; default: return <span>Unknown type "{type}"</span>; } } }<|fim▁end|>
keep: false,
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|># 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. # ==============================================================================<|fim▁end|>
# coding=utf-8 # Copyright 2016 The TF-Slim Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>application.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import make_response from flask import request from flask import render_template from flask import redirect from flask import url_for import logging from logging.handlers import RotatingFileHandler app = Flask(__name__) @app.route('/') def index(): app.logger.info('index') username = request.cookies.get('username') if (username == None): return redirect(url_for('login')) else: return render_template('index.html', username=username) @app.route('/login', methods=['GET','POST']) def login(): app.logger.info('login') if request.method == 'POST': if validate_credentials(request.form['username'], request.form['password']):<|fim▁hole|> return resp else: return render_template('login.html', error='Invalid username or password') else: return render_template('login.html') @app.route('/logout') def logout(): app.logger.info('logout') resp = make_response(redirect(url_for('index'))) resp.set_cookie('username', '', expires=0) return resp def validate_credentials(username, password): return username == password if __name__ == '__main__': handler = RotatingFileHandler('todo.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.INFO) app.logger.addHandler(handler) app.run()<|fim▁end|>
resp = make_response(redirect(url_for('index'))) resp.set_cookie('username', request.form['username'])
<|file_name|>server.cc<|end_file_name|><|fim▁begin|>/* * ============================================================================ * Filename: server.hxx * Description: Server side implementation for flihabi network * Version: 1.0 * Created: 04/20/2015 06:21:00 PM * Revision: none * Compiler: gcc * Author: Rafael Gozlan * Organization: Flihabi * ============================================================================ */ #define _POSIX_SOURCE #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include <thread> #include <iostream> #include "blocking_queue.hh" #include "utils.hh" #include "server.hh" #include "broadcaster.hh" #include "listener.hh" #include "network.hh" // TODO: More free // PUBLIC METHODS Server::Server() : results_(), busy_(), todo_() { // Launch the server broadcaster and connection handler std::thread broadcaster(broadcastLoop); broadcaster.detach(); std::thread handle(Server::handler, this); handle.detach(); } Result *Server::getResult(int i) { Result *r = results_[i]; if (r != NULL) { results_[i] = NULL; busy_[i] = false; /* set busy to false so the emplacement is free*/ } return r; } int Server::execBytecode(std::string bytecode) { int i = getResultEmplacement(); TodoItem *t = new TodoItem(); t->id = i; t->bytecode = bytecode; todo_.push(t); return i; } // PRIVATE METHODS void Server::setResult(int i, Result *r) { results_[i] = r; } int Server::getResultEmplacement() { for (size_t i = 0; i < busy_.size(); i++) { if (!busy_[i]) { busy_[i] = true; return i; } } /* Add emplacement */ busy_.push_back(false); results_.push_back(NULL); return busy_.size() - 1; } /* Server slaves handling */ void Server::handler(Server *server) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, std::to_string(CONNECTION_PORT).c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "Handler: getaddrinfo: %s\n", gai_strerror(rv)); return; }<|fim▁hole|> // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Handler: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("Handler: setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Handler: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "Handler: failed to bind\n"); return; } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, 10) == -1) { perror("listen"); exit(1); } printf("Handler: waiting for connections...\n"); while (true) /* I love stuff like this */ { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("Handler: accept"); continue; } inet_ntop(their_addr.ss_family, Utils::get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("Handler: got connection from %s\n", s); int numbytes; char buf[100]; // Receiving connection msg if ((numbytes = recv(new_fd, buf, 100-1, 0)) == -1) { perror("Server: failed to recv the connection msg"); exit(1); } buf[numbytes] = '\0'; printf("Server: received '%s'\n",buf); if (std::string(buf) == CONNECTION_MSG) { std::thread client(Server::clientThread, server, new_fd); client.detach(); } } } void Server::clientThread(Server *s, int sockfd) { std::cout << "Client thread: sending Hello!" << std::endl; // Sending ACK if (send(sockfd, CONNECTION_MSG, strlen(CONNECTION_MSG), 0) == -1) perror("Client thread: failed sending Hello!"); while (true) /* client loop */ { TodoItem *t = NULL; while ((t = s->todo_.pop()) == NULL); // Try to get bytecode to exec std::cout << "Server thread opening task:\n"; /* const char *buffer = t->bytecode.c_str(); for (unsigned i = 0; i < t->bytecode.size(); i++) { if (buffer[i] <= '~' && buffer[i] >= ' ') printf("%c", buffer[i]); else printf("\\%02X", buffer[i]); } */ std::cout << "\n==\n"; // Sending Bytecode if (Utils::sendBytecode(sockfd, t->bytecode, t->bytecode.size()) == (uint64_t) -1) { perror("Client thread: failed sending bytecode"); s->todo_.push(t); break; } ssize_t nbytes; uint64_t len; if ((len = Utils::recvBytecodeLen(sockfd)) == (uint64_t) -1) { perror("Client thread: fail to get bytecode len"); s->todo_.push(t); break; } uint64_t len_aux = len; char *buf = (char*) malloc(len); char *aux = buf; // Receiving connection msg while (len > 0) { if (len < 4096) nbytes = recv(sockfd, aux, len, 0); else nbytes = recv(sockfd, aux, 4096, 0); if (nbytes == -1) { perror("Client thread: failed receiving bytecode"); s->todo_.push(t); break; } if (nbytes == 0) { std::cout << "Client thread: Connection seems to be reset." << std::endl; s->todo_.push(t); close(sockfd); break; } len -= nbytes; aux += nbytes; } if (nbytes == -1) { return; } if (nbytes == 0) { break; } // Setting result /* TODO: Test if r is persistant */ std::cout << "Server got returned bytecode\n"; Result *r = new Result(); r->value = std::string(buf, len_aux); s->setResult(t->id, r); free(buf); } }<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This crate provides the `regex!` macro. Its use is documented in the //! `regex` crate. #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(plugin_registrar, quote, rustc_private)] extern crate regex; extern crate regex_syntax; extern crate rustc_plugin; extern crate syntax; use std::collections::BTreeMap; use std::usize; use syntax::ast; use syntax::codemap; use syntax::ext::build::AstBuilder; use syntax::ext::base::{ExtCtxt, MacResult, MacEager, DummyResult}; use syntax::parse::token; use syntax::print::pprust; use syntax::fold::Folder; use syntax::ptr::P; use rustc_plugin::Registry; use regex::internal::{Compiler, EmptyLook, Inst, Program}; use regex_syntax::Expr; /// For the `regex!` syntax extension. Do not use. #[plugin_registrar] #[doc(hidden)] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("regex", native); } /// Generates specialized code for the Pike VM for a particular regular /// expression. /// /// There are two primary differences between the code generated here and the /// general code in vm.rs. /// /// 1. All heap allocation is removed. Sized vector types are used instead. /// Care must be taken to make sure that these vectors are not copied /// gratuitously. (If you're not sure, run the benchmarks. They will yell /// at you if you do.) /// 2. The main `match instruction { ... }` expressions are replaced with more /// direct `match pc { ... }`. The generators can be found in /// `step_insts` and `add_insts`. /// /// It is strongly recommended to read the dynamic implementation in vm.rs /// first before trying to understand the code generator. The implementation /// strategy is identical and vm.rs has comments and will be easier to follow. fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> { let regex = match parse(cx, tts) { Some(r) => r, // error is logged in 'parse' with cx.span_err None => return DummyResult::any(sp), }; // We use the largest possible size limit because this is happening at // compile time. We trust the programmer. let expr = match Expr::parse(&regex) { Ok(expr) => expr, Err(err) => { cx.span_err(sp, &err.to_string()); return DummyResult::any(sp) } }; let prog = match Compiler::new().size_limit(usize::MAX).compile(&[expr]) { Ok(re) => re, Err(err) => { cx.span_err(sp, &err.to_string()); return DummyResult::any(sp) } }; let names = prog.captures.iter().cloned().collect(); let mut gen = NfaGen { cx: &*cx, sp: sp, prog: prog, names: names, original: regex, }; MacEager::expr(gen.code()) } struct NfaGen<'a> { cx: &'a ExtCtxt<'a>, sp: codemap::Span, prog: Program, names: Vec<Option<String>>, original: String, } impl<'a> NfaGen<'a> { fn code(&mut self) -> P<ast::Expr> { // Most or all of the following things are used in the quasiquoted // expression returned. let num_cap_locs = 2 * self.prog.captures.len(); let num_insts = self.prog.len(); let cap_names = self.vec_expr(self.names.iter(), &mut |cx, name| match *name { Some(ref name) => { let name = &**name; quote_expr!(cx, Some($name)) } None => cx.expr_none(self.sp), } ); let capture_name_idx = { let mut capture_name_idx = BTreeMap::new(); for (i, name) in self.names.iter().enumerate() { if let Some(ref name) = *name { capture_name_idx.insert(name.to_owned(), i); } } self.vec_expr(capture_name_idx.iter(), &mut |cx, (name, group_idx)| quote_expr!(cx, ($name, $group_idx)) ) }; let is_anchored_start = self.prog.is_anchored_start; let step_insts = self.step_insts(); let add_insts = self.add_insts(); let regex = &*self.original; quote_expr!(self.cx, { // When `regex!` is bound to a name that is not used, we have to make sure // that dead_code warnings don't bubble up to the user from the generated // code. Therefore, we suppress them by allowing dead_code. The effect is that // the user is only warned about *their* unused variable/code, and not the // unused code generated by regex!. See #14185 for an example. #[allow(dead_code)] static CAPTURES: &'static [Option<&'static str>] = &$cap_names; #[allow(dead_code)] static CAPTURE_NAME_IDX: &'static [(&'static str, usize)] = &$capture_name_idx; #[allow(dead_code)] fn exec<'t>( mut caps: &mut [Option<usize>], input: &'t str, start: usize, ) -> bool { #![allow(unused_imports)] #![allow(unused_mut)] use regex::internal::{Char, CharInput, InputAt, Input, Inst}; let input = CharInput::new(input.as_bytes()); let at = input.at(start); return Nfa {<|fim▁hole|> ncaps: caps.len(), }.exec(&mut NfaThreads::new(), &mut caps, at); struct Nfa<'t> { input: CharInput<'t>, ncaps: usize, } impl<'t> Nfa<'t> { #[allow(unused_variables)] fn exec( &mut self, mut q: &mut NfaThreads, mut caps: &mut [Option<usize>], mut at: InputAt, ) -> bool { let mut matched = false; let (mut clist, mut nlist) = (&mut q.clist, &mut q.nlist); clist.empty(); nlist.empty(); 'LOOP: loop { if clist.size == 0 { if matched || (!at.is_start() && $is_anchored_start) { break; } // TODO: Prefix matching... Hmm. // Prefix matching now uses a DFA, so I think this is // going to require encoding that DFA statically. } if clist.size == 0 || (!$is_anchored_start && !matched) { self.add(clist, &mut caps, 0, at); } let at_next = self.input.at(at.next_pos()); for i in 0..clist.size { let pc = clist.pc(i); let tcaps = clist.caps(i); if self.step(nlist, caps, tcaps, pc, at, at_next) { matched = true; if caps.len() == 0 { break 'LOOP; } break; } } if at.char().is_none() { break; } at = at_next; ::std::mem::swap(&mut clist, &mut nlist); nlist.empty(); } matched } // Sometimes `nlist` is never used (for empty regexes). #[allow(unused_variables)] #[inline] fn step( &self, nlist: &mut Threads, caps: &mut [Option<usize>], thread_caps: &mut [Option<usize>], pc: usize, at: InputAt, at_next: InputAt, ) -> bool { $step_insts; false } fn add( &self, nlist: &mut Threads, thread_caps: &mut [Option<usize>], pc: usize, at: InputAt, ) { if nlist.contains(pc) { return; } let ti = nlist.add(pc); $add_insts } } struct NfaThreads { clist: Threads, nlist: Threads, } struct Threads { dense: [Thread; $num_insts], sparse: [usize; $num_insts], size: usize, } struct Thread { pc: usize, caps: [Option<usize>; $num_cap_locs], } impl NfaThreads { fn new() -> NfaThreads { NfaThreads { clist: Threads::new(), nlist: Threads::new(), } } fn swap(&mut self) { ::std::mem::swap(&mut self.clist, &mut self.nlist); } } impl Threads { fn new() -> Threads { Threads { // These unsafe blocks are used for performance reasons, as it // gives us a zero-cost initialization of a sparse set. The // trick is described in more detail here: // http://research.swtch.com/sparse // The idea here is to avoid initializing threads that never // need to be initialized, particularly for larger regexs with // a lot of instructions. dense: unsafe { ::std::mem::uninitialized() }, sparse: unsafe { ::std::mem::uninitialized() }, size: 0, } } #[inline] fn add(&mut self, pc: usize) -> usize { let i = self.size; self.dense[i].pc = pc; self.sparse[pc] = i; self.size += 1; i } #[inline] fn thread(&mut self, i: usize) -> &mut Thread { &mut self.dense[i] } #[inline] fn contains(&self, pc: usize) -> bool { let s = unsafe { ::std::ptr::read_volatile(&self.sparse[pc]) }; s < self.size && self.dense[s].pc == pc } #[inline] fn empty(&mut self) { self.size = 0; } #[inline] fn pc(&self, i: usize) -> usize { self.dense[i].pc } #[inline] fn caps<'r>(&'r mut self, i: usize) -> &'r mut [Option<usize>] { &mut self.dense[i].caps } } } ::regex::Regex(::regex::internal::_Regex::Plugin(::regex::internal::Plugin { original: $regex, names: &CAPTURES, groups: &CAPTURE_NAME_IDX, prog: exec, })) }) } // Generates code for the `add` method, which is responsible for adding // zero-width states to the next queue of states to visit. fn add_insts(&self) -> P<ast::Expr> { let arms = self.prog.iter().enumerate().map(|(pc, inst)| { let body = match *inst { Inst::EmptyLook(ref inst) => { let nextpc = inst.goto; match inst.look { EmptyLook::StartLine => { quote_expr!(self.cx, { let prev = self.input.previous_char(at); if prev.is_none() || prev == '\n' { self.add(nlist, thread_caps, $nextpc, at); } }) } EmptyLook::EndLine => { quote_expr!(self.cx, { if at.char().is_none() || at.char() == '\n' { self.add(nlist, thread_caps, $nextpc, at); } }) } EmptyLook::StartText => { quote_expr!(self.cx, { let prev = self.input.previous_char(at); if prev.is_none() { self.add(nlist, thread_caps, $nextpc, at); } }) } EmptyLook::EndText => { quote_expr!(self.cx, { if at.char().is_none() { self.add(nlist, thread_caps, $nextpc, at); } }) } EmptyLook::WordBoundary | EmptyLook::NotWordBoundary => { let m = if inst.look == EmptyLook::WordBoundary { quote_expr!(self.cx, { w1 ^ w2 }) } else { quote_expr!(self.cx, { !(w1 ^ w2) }) }; quote_expr!(self.cx, { let prev = self.input.previous_char(at); let w1 = prev.is_word_char(); let w2 = at.char().is_word_char(); if $m { self.add(nlist, thread_caps, $nextpc, at); } }) } EmptyLook::WordBoundaryAscii | EmptyLook::NotWordBoundaryAscii => { unreachable!() } } } Inst::Save(ref inst) => { let nextpc = inst.goto; let slot = inst.slot; quote_expr!(self.cx, { if $slot >= self.ncaps { self.add(nlist, thread_caps, $nextpc, at); } else { let old = thread_caps[$slot]; thread_caps[$slot] = Some(at.pos()); self.add(nlist, thread_caps, $nextpc, at); thread_caps[$slot] = old; } }) } Inst::Split(ref inst) => { let (x, y) = (inst.goto1, inst.goto2); quote_expr!(self.cx, { self.add(nlist, thread_caps, $x, at); self.add(nlist, thread_caps, $y, at); }) } // For Match, Char, Ranges _ => quote_expr!(self.cx, { let mut t = &mut nlist.thread(ti); for (slot, val) in t.caps.iter_mut().zip(thread_caps.iter()) { *slot = *val; } }), }; self.arm_inst(pc, body) }).collect::<Vec<ast::Arm>>(); self.match_insts(arms) } // Generates the code for the `step` method, which processes all states // in the current queue that consume a single character. fn step_insts(&self) -> P<ast::Expr> { let arms = self.prog.iter().enumerate().map(|(pc, inst)| { let body = match *inst { Inst::Match(_) => quote_expr!(self.cx, { for (slot, val) in caps.iter_mut().zip(thread_caps.iter()) { *slot = *val; } return true; }), Inst::Char(ref inst) => { let nextpc = inst.goto; let c = inst.c; quote_expr!(self.cx, { if $c == at.char() { self.add(nlist, thread_caps, $nextpc, at_next); } return false; }) } Inst::Ranges(ref inst) => { let match_class = self.match_class(&inst.ranges); let nextpc = inst.goto; quote_expr!(self.cx, { let mut c = at.char(); if let Some(c) = c.as_char() { if $match_class { self.add(nlist, thread_caps, $nextpc, at_next); } } return false; }) } // EmptyLook, Save, Jump, Split _ => quote_expr!(self.cx, { return false; }), }; self.arm_inst(pc, body) }).collect::<Vec<ast::Arm>>(); self.match_insts(arms) } // Translates a character class into a match expression. // This avoids a binary search (and is hopefully replaced by a jump // table). fn match_class(&self, ranges: &[(char, char)]) -> P<ast::Expr> { let mut arms = ranges.iter().map(|&(start, end)| { let pat = self.cx.pat( self.sp, ast::PatKind::Range( quote_expr!(self.cx, $start), quote_expr!(self.cx, $end))); self.cx.arm(self.sp, vec!(pat), quote_expr!(self.cx, true)) }).collect::<Vec<ast::Arm>>(); arms.push(self.wild_arm_expr(quote_expr!(self.cx, false))); let match_on = quote_expr!(self.cx, c); self.cx.expr_match(self.sp, match_on, arms) } // Generates code for checking a literal prefix of the search string. // The code is only generated if the regex *has* a literal prefix. // Otherwise, a no-op is returned. // fn check_prefix(&self) -> P<ast::Expr> { // if self.prog.prefixes.len() == 0 { // self.empty_block() // } else { // quote_expr!(self.cx, // if clist.size == 0 { // let haystack = &self.input.as_bytes()[self.ic..]; // match find_prefix(prefix_bytes, haystack) { // None => break, // Some(i) => { // self.ic += i; // next_ic = self.chars.set(self.ic); // } // } // } // ) // } // } // Builds a `match pc { ... }` expression from a list of arms, specifically // for matching the current program counter with an instruction. // A wild-card arm is automatically added that executes a no-op. It will // never be used, but is added to satisfy the compiler complaining about // non-exhaustive patterns. fn match_insts(&self, mut arms: Vec<ast::Arm>) -> P<ast::Expr> { arms.push(self.wild_arm_expr(self.empty_block())); self.cx.expr_match(self.sp, quote_expr!(self.cx, pc), arms) } fn empty_block(&self) -> P<ast::Expr> { quote_expr!(self.cx, {}) } // Creates a match arm for the instruction at `pc` with the expression // `body`. fn arm_inst(&self, pc: usize, body: P<ast::Expr>) -> ast::Arm { let pc_pat = self.cx.pat_lit(self.sp, quote_expr!(self.cx, $pc)); self.cx.arm(self.sp, vec!(pc_pat), body) } // Creates a wild-card match arm with the expression `body`. fn wild_arm_expr(&self, body: P<ast::Expr>) -> ast::Arm { ast::Arm { attrs: vec!(), pats: vec!(P(ast::Pat{ id: ast::DUMMY_NODE_ID, span: self.sp, node: ast::PatKind::Wild, })), guard: None, body: body, } } // Converts `xs` to a `[x1, x2, .., xN]` expression by calling `to_expr` // on each element in `xs`. fn vec_expr<T, It: Iterator<Item=T>>( &self, xs: It, to_expr: &mut FnMut(&ExtCtxt, T) -> P<ast::Expr>, ) -> P<ast::Expr> { let exprs = xs.map(|x| to_expr(self.cx, x)).collect(); self.cx.expr_vec(self.sp, exprs) } } /// Looks for a single string literal and returns it. /// Otherwise, logs an error with cx.span_err and returns None. fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<String> { let mut parser = cx.new_parser_from_tts(tts); if let Ok(expr) = parser.parse_expr() { let entry = cx.expander().fold_expr(expr); let regex = match entry.node { ast::ExprKind::Lit(ref lit) => { match lit.node { ast::LitKind::Str(ref s, _) => s.to_string(), _ => { cx.span_err(entry.span, &format!( "expected string literal but got `{}`", pprust::lit_to_string(&**lit))); return None } } } _ => { cx.span_err(entry.span, &format!( "expected string literal but got `{}`", pprust::expr_to_string(&*entry))); return None } }; if !parser.eat(&token::Eof) { cx.span_err(parser.span, "only one string literal allowed"); return None; } Some(regex) } else { cx.parse_sess().span_diagnostic.err("failure parsing token tree"); None } }<|fim▁end|>
input: input,
<|file_name|>products.server.controller.js<|end_file_name|><|fim▁begin|>'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Product = mongoose.model('Product'), multiparty = require('multiparty'), uuid = require('node-uuid'), fs = require('fs'), _ = require('lodash'); /** * Create a Product */ exports.create = function(req, res, next) { var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { var file = files.file[0]; var contentType = file.headers['content-type']; var tmpPath = file.path; var extIndex = tmpPath.lastIndexOf('.'); var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex); // uuid is for generating unique filenames. var fileName = uuid.v4() + extension; var destPath = '/home/blaze/Sites/github/yaltashop/uploads/' + fileName; //fs.rename(tmpPath, destPath, function(err) { if (err) { console.log('there was an error during saving file'); next(err); } var product = new Product(fields); file.name = file.originalFilename; product.photo.file = file; product.user = req.user; product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); //}); }); }; /** * Show the current Product */ exports.read = function(req, res) { res.jsonp(req.product); }; /** * Update a Product */ exports.update = function(req, res) { var product = req.product ; product = _.extend(product , req.body); product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * Delete an Product */ exports.delete = function(req, res) { var product = req.product ; product.remove(function(err) {<|fim▁hole|> return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * List of Products */ exports.list = function(req, res) { Product.find().sort('-created').populate('user', 'displayName').exec(function(err, products) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(products); } }); }; /** * Product middleware */ exports.productByID = function(req, res, next, id) { Product.findById(id).populate('user', 'displayName').exec(function(err, product) { if (err) return next(err); if (! product) return next(new Error('Failed to load Product ' + id)); req.product = product ; next(); }); }; /** * Product authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.product.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };<|fim▁end|>
if (err) {
<|file_name|>turtle.js<|end_file_name|><|fim▁begin|>var Turtle = function () { this.d = 0; this.x = 0; this.y = 0; this.rounding = false; this.invert = false; } Turtle.prototype.setX = function (val) { this.x = val; return this; } Turtle.prototype.setY = function (val) { this.y = val; return this; } Turtle.prototype.setDegree = function (deg) { this.d = deg; return this; } Turtle.prototype.setInvert = function (bool) { this.invert = bool; return this; } Turtle.prototype.setRounding = function (bool) { this.rounding = bool; return this; } Turtle.prototype.rt = function (degrees) { if (this.invert) { this.d += degrees; } else { this.d -= degrees; this.d += 360; // to ensure that the number is positive } this.d %= 360; return this; } Turtle.prototype.lt = function (degrees) { if (this.invert) { this.d -= degrees; this.d += 360; // to ensure that the number is positive } else { this.d += degrees; } this.d %= 360; return this; } Turtle.prototype.adj = function (degrees, hyp) { var adj = Math.cos(degrees * Math.PI / 180) * hyp; if (this.rounding) { return Math.round(adj); } else { return adj; } } Turtle.prototype.opp = function (degrees, hyp) { var opp = Math.sin(degrees * Math.PI / 180) * hyp; if (this.rounding) { return Math.round(opp); } else { return opp; } } Turtle.prototype.fd = function (magnitude) { if (this.d < 90) { // x == adjacent<|fim▁hole|> this.x += this.adj(this.d, magnitude); // y == opposite this.y += this.opp(this.d, magnitude); } else if (this.d < 180) { // x == -opposite this.x -= this.opp(this.d - 90, magnitude); // y == adjacent this.y += this.adj(this.d - 90, magnitude); } else if (this.d < 270) { // x == -adjacent this.x -= this.adj(this.d - 180, magnitude); // y == -opposite this.y -= this.opp(this.d - 180, magnitude); } else if (this.d < 360) { // x == opposite this.x += this.opp(this.d - 270, magnitude); // y == -adjacent this.y -= this.adj(this.d - 270, magnitude); } return this; } Turtle.prototype.bk = function (magnitude) { if (this.d < 90) { // x -= adjacent this.x -= this.adj(this.d, magnitude); // y -= opposite this.y -= this.opp(this.d, magnitude); } else if (this.d < 180) { // x == +opposite this.x += this.opp(this.d - 90, magnitude); // y == -adjacent this.y -= this.adj(this.d - 90, magnitude); } else if (this.d < 270) { // x == opposite this.x += this.adj(this.d - 180, magnitude); // y == adjacent this.y += this.opp(this.d - 180, magnitude); } else if (this.d < 360) { // x == -opposite this.x -= this.opp(this.d - 270, magnitude); // y == adjacent this.y += this.adj(this.d - 270, magnitude); } return this; }<|fim▁end|>
<|file_name|>u_char.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault; /// Returns the amount of bytes this character would need if encoded in /// UTF-8. #[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx.<|fim▁hole|> /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn is_alphabetic(self) -> bool { match self { 'a' ... 'z' | 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] fn is_lowercase(self) -> bool { match self { 'a' ... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { ' ' | '\x09' ... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0' ... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }<|fim▁end|>
#[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue'
<|file_name|>biotestflavor.py<|end_file_name|><|fim▁begin|>from fabric.api import * from fabric.contrib.files import * from cloudbio.flavor import Flavor from cloudbio.custom.shared import (_fetch_and_unpack) class BioTestFlavor(Flavor): """A Flavor for cross Bio* tests """ def __init__(self, env): Flavor.__init__(self,env) self.name = "Bio* cross-lang flavor" def rewrite_config_items(self, name, items): if name == "packages": # list.remove('screen') # list.append('test') return items elif name == "python": return [ 'biopython' ] elif name == "perl": return [ 'bioperl' ] elif name == "ruby": return [ 'bio' ] elif name == "custom": return [] else: return items def post_install(self):<|fim▁hole|> run('git pull') else: _fetch_and_unpack("git clone git://github.com/pjotrp/Scalability.git") # Now run a post installation routine (for the heck of it) run('./Scalability/scripts/hello.sh') env.logger.info("Load Cross-language tests") if exists('Cross-language-interfacing'): with cd('Cross-language-interfacing'): run('git pull') else: _fetch_and_unpack("git clone git://github.com/pjotrp/Cross-language-interfacing.git") # Special installs for the tests with cd('Cross-language-interfacing'): sudo('./scripts/install-packages-root.sh ') run('./scripts/install-packages.sh') run('./scripts/create_test_files.rb') env.flavor = BioTestFlavor(env)<|fim▁end|>
env.logger.info("Starting post-install") env.logger.info("Load Scalability tests") if exists('Scalability'): with cd('Scalability'):
<|file_name|>image.cpp<|end_file_name|><|fim▁begin|>// // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // 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. // #include "misc/debug.h" #include "misc/formats.h" #include "misc/object_tracker.h" #include "wrappers/buffer.h" #include "wrappers/command_buffer.h" #include "wrappers/command_pool.h" #include "wrappers/device.h" #include "wrappers/image.h" #include "wrappers/memory_block.h" #include "wrappers/physical_device.h" #include "wrappers/queue.h" #include "wrappers/swapchain.h" #include <math.h> /* Please see header for specification */ Anvil::Image::Image(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkSharingMode sharing_mode, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, bool use_full_mipmap_chain, bool is_mutable, Anvil::QueueFamilyBits queue_families, VkImageLayout post_create_image_layout, const std::vector<MipmapRawData>* opt_mipmaps_ptr) :m_alignment (0), m_depth (base_mipmap_depth), m_device_ptr (device_ptr), m_flags (0), m_format (format), m_has_transitioned_to_post_create_layout(false), m_height (base_mipmap_height), m_image (VK_NULL_HANDLE), m_image_owner (true), m_is_mutable (is_mutable), m_is_sparse (false), m_is_swapchain_image (false), m_memory_types (0), m_n_mipmaps (0), m_n_layers (n_layers), m_n_slices (0), m_post_create_layout (post_create_image_layout), m_queue_families (queue_families), m_residency_scope (Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED), m_sample_count (sample_count), m_sharing_mode (sharing_mode), m_storage_size (0), m_swapchain_memory_assigned (false), m_tiling (tiling), m_type (type), m_usage (static_cast<VkImageUsageFlagBits>(usage)), m_uses_full_mipmap_chain (use_full_mipmap_chain), m_width (base_mipmap_width), m_memory_owner (false) { if (opt_mipmaps_ptr != nullptr) { m_mipmaps_to_upload = *opt_mipmaps_ptr; } /* Register this instance */ Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_IMAGE, this); } /* Please see header for specification */ Anvil::Image::Image(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkSharingMode sharing_mode, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, Anvil::QueueFamilyBits queue_families, bool use_full_mipmap_chain, bool is_mutable, VkImageLayout post_create_image_layout, const std::vector<MipmapRawData>* mipmaps_ptr) :m_alignment (0), m_depth (base_mipmap_depth), m_device_ptr (device_ptr), m_flags (0), m_format (format), m_has_transitioned_to_post_create_layout(false), m_height (base_mipmap_height), m_image (VK_NULL_HANDLE), m_image_owner (true), m_is_mutable (is_mutable), m_is_sparse (false), m_is_swapchain_image (false), m_memory_owner (true), m_memory_types (0), m_n_layers (n_layers), m_n_mipmaps (0), m_n_slices (0), m_post_create_layout (post_create_image_layout), m_queue_families (queue_families), m_residency_scope (Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED), m_sample_count (sample_count), m_sharing_mode (sharing_mode), m_storage_size (0), m_swapchain_memory_assigned (false), m_tiling (tiling), m_type (type), m_usage (static_cast<VkImageUsageFlagBits>(usage)), m_uses_full_mipmap_chain (use_full_mipmap_chain), m_width (base_mipmap_width) { if (mipmaps_ptr != nullptr) { m_mipmaps_to_upload = *mipmaps_ptr; } /* Register this instance */ Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_IMAGE, this); } /* Please see header for specification */ Anvil::Image::Image(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImage image, VkFormat format, VkImageTiling tiling, VkSharingMode sharing_mode, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, uint32_t n_mipmaps, VkSampleCountFlagBits sample_count, uint32_t n_slices, bool is_mutable, Anvil::QueueFamilyBits queue_families, VkImageCreateFlags flags) :m_alignment (0), m_depth (base_mipmap_depth), m_device_ptr (device_ptr), m_flags (flags), m_format (format), m_has_transitioned_to_post_create_layout(true), m_height (base_mipmap_height), m_image (image), m_image_owner (false), m_is_mutable (is_mutable), m_is_sparse (false), m_is_swapchain_image (false), m_memory_owner (false), m_memory_types (UINT32_MAX), m_n_layers (n_layers), m_n_mipmaps (n_mipmaps), m_n_slices (n_slices), m_post_create_layout (VK_IMAGE_LAYOUT_UNDEFINED), m_queue_families (queue_families), m_residency_scope (Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED), m_sample_count (sample_count), m_sharing_mode (sharing_mode), m_storage_size (UINT64_MAX), m_swapchain_memory_assigned (false), m_tiling (tiling), m_type (VK_IMAGE_TYPE_MAX_ENUM), m_usage (static_cast<VkImageUsageFlagBits>(usage)), m_uses_full_mipmap_chain (false), m_width (base_mipmap_width) { /* Register this instance */ Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_IMAGE, this); } /** Please see header for specification */ Anvil::Image::Image(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, Anvil::QueueFamilyBits queue_families, VkSharingMode sharing_mode, bool use_full_mipmap_chain, bool is_mutable, Anvil::SparseResidencyScope residency_scope) :m_alignment (0), m_depth (base_mipmap_depth), m_device_ptr (device_ptr), m_flags (0), m_format (format), m_has_transitioned_to_post_create_layout(true), m_height (base_mipmap_height), m_image (VK_NULL_HANDLE), m_image_owner (true), m_is_mutable (is_mutable), m_is_sparse (true), m_is_swapchain_image (false), m_memory_owner (false), m_memory_types (UINT32_MAX), m_n_layers (n_layers), m_n_mipmaps (0), m_n_slices (0), m_post_create_layout (VK_IMAGE_LAYOUT_UNDEFINED), m_queue_families (queue_families), m_residency_scope (residency_scope), m_sample_count (sample_count), m_sharing_mode (sharing_mode), m_storage_size (UINT64_MAX), m_swapchain_memory_assigned (false), m_tiling (tiling), m_type (type), m_usage (static_cast<VkImageUsageFlagBits>(usage)), m_uses_full_mipmap_chain (use_full_mipmap_chain), m_width (base_mipmap_width) { /* Register this instance */ Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_IMAGE, this); } /** Please see header for specification */ std::shared_ptr<Anvil::Image> Anvil::Image::create_nonsparse(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, Anvil::QueueFamilyBits queue_families, VkSharingMode sharing_mode, bool use_full_mipmap_chain, bool is_mutable, VkImageLayout post_create_image_layout, const std::vector<MipmapRawData>* opt_mipmaps_ptr) { std::shared_ptr<Anvil::Image> result_ptr( new Image(device_ptr, type, format, tiling, sharing_mode, usage, base_mipmap_width, base_mipmap_height, base_mipmap_depth, n_layers, sample_count, use_full_mipmap_chain, is_mutable, queue_families, post_create_image_layout, opt_mipmaps_ptr) ); result_ptr->init(use_full_mipmap_chain, false, /* should_memory_backing_be_mappable - irrelevant */ false, /* should_memory_backing_be_coherent - irrelevant */ nullptr); /* start_image_layout_ptr - irrelevant */ return result_ptr; } /** Please see header for specification */ std::shared_ptr<Anvil::Image> Anvil::Image::create_nonsparse(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, Anvil::QueueFamilyBits queue_families, VkSharingMode sharing_mode, bool use_full_mipmap_chain, bool should_memory_backing_be_mappable, bool should_memory_backing_be_coherent, bool is_mutable, VkImageLayout post_create_image_layout, const std::vector<MipmapRawData>* mipmaps_ptr) { const VkImageLayout start_image_layout = (mipmaps_ptr != nullptr && mipmaps_ptr->size() > 0) ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED; std::shared_ptr<Anvil::Image> new_image_ptr( new Anvil::Image(device_ptr, type, format, tiling, sharing_mode, usage, base_mipmap_width, base_mipmap_height, base_mipmap_depth, n_layers, sample_count, queue_families, use_full_mipmap_chain, is_mutable, post_create_image_layout, mipmaps_ptr) ); new_image_ptr->init(use_full_mipmap_chain, should_memory_backing_be_mappable, should_memory_backing_be_coherent, &start_image_layout); return new_image_ptr; } /** Please see header for specification */ std::shared_ptr<Anvil::Image> Anvil::Image::create_nonsparse(std::weak_ptr<Anvil::BaseDevice> device_ptr, const VkSwapchainCreateInfoKHR& swapchain_create_info, VkImage image) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(device_ptr); std::shared_ptr<Anvil::Image> new_image_ptr( new Anvil::Image(device_ptr, image, swapchain_create_info.imageFormat, VK_IMAGE_TILING_OPTIMAL, swapchain_create_info.imageSharingMode, swapchain_create_info.imageUsage, swapchain_create_info.imageExtent.width, swapchain_create_info.imageExtent.height, 1, /* base_mipmap_depth */ swapchain_create_info.imageArrayLayers, 1, /* n_mipmaps */ VK_SAMPLE_COUNT_1_BIT, 1, /* n_slices */ true, /* is_mutable */ Anvil::QUEUE_FAMILY_TYPE_UNDEFINED, 0u) /* flags */ ); new_image_ptr->m_memory_types = 0; new_image_ptr->m_storage_size = 0; new_image_ptr->m_type = VK_IMAGE_TYPE_2D; new_image_ptr->m_is_swapchain_image = true; new_image_ptr->init_mipmap_props(); return new_image_ptr; } /** Please see header for specification */ std::shared_ptr<Anvil::Image> Anvil::Image::create_sparse(std::weak_ptr<Anvil::BaseDevice> device_ptr, VkImageType type, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, uint32_t base_mipmap_width, uint32_t base_mipmap_height, uint32_t base_mipmap_depth, uint32_t n_layers, VkSampleCountFlagBits sample_count, Anvil::QueueFamilyBits queue_families, VkSharingMode sharing_mode, bool use_full_mipmap_chain, bool is_mutable, Anvil::SparseResidencyScope residency_scope) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(device_ptr); const VkPhysicalDeviceFeatures& features (device_locked_ptr->get_physical_device_features() ); std::shared_ptr<Anvil::Image> result_ptr; /* Make sure requested functionality is supported by the device */ if (!features.sparseBinding) { anvil_assert(features.sparseBinding); goto end; } if (residency_scope != Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { /* For sparse residency, we need to verify the device can actually support the requested configuration */ std::vector<VkSparseImageFormatProperties> result_properties; device_locked_ptr->get_physical_device_sparse_image_format_properties(format, type, sample_count, usage, tiling, result_properties); if (result_properties.size() == 0) { goto end; } switch (type) { case VK_IMAGE_TYPE_1D: { /* Not supported in Vulkan 1.0 */ anvil_assert(false); goto end; } case VK_IMAGE_TYPE_2D: { if (!features.sparseResidencyImage2D) { anvil_assert(false); goto end; } break; } case VK_IMAGE_TYPE_3D: { if (!features.sparseResidencyImage3D) { anvil_assert(false); goto end; } break; } default: { anvil_assert(false); goto end; } } switch (sample_count) { case VK_SAMPLE_COUNT_1_BIT: { /* No validation required */ break; } case VK_SAMPLE_COUNT_2_BIT: { if (!features.sparseResidency2Samples) { anvil_assert(features.sparseResidency2Samples); goto end; } break; } case VK_SAMPLE_COUNT_4_BIT: { if (!features.sparseResidency4Samples) { anvil_assert(features.sparseResidency4Samples); goto end; } break; } case VK_SAMPLE_COUNT_8_BIT: { if (!features.sparseResidency8Samples) { anvil_assert(features.sparseResidency8Samples); goto end; } break; } case VK_SAMPLE_COUNT_16_BIT: { if (!features.sparseResidency4Samples) { anvil_assert(features.sparseResidency16Samples); goto end; } break; } default: { anvil_assert(false); goto end; } } } /* Spawn a new Image instance and initialize it */ result_ptr.reset( new Anvil::Image(device_ptr, type, format, tiling, usage, base_mipmap_width, base_mipmap_height, base_mipmap_depth, n_layers, sample_count, queue_families, sharing_mode, use_full_mipmap_chain, is_mutable, residency_scope) ); result_ptr->init(use_full_mipmap_chain, false, /* should_memory_backing_be_mappable - irrelevant */ false, /* should_memory_backing_be_coherent - irrelevant */ nullptr); /* start_image_layout - irrelevant */ end: return result_ptr; } /** Please see header for specification */ bool Anvil::Image::get_aspect_subresource_layout(VkImageAspectFlags aspect, uint32_t n_layer, uint32_t n_mip, VkSubresourceLayout* out_subresource_layout_ptr) const { auto aspect_iterator = m_aspects.find(static_cast<VkImageAspectFlagBits>(aspect) ); bool result = false; anvil_assert(m_tiling == VK_IMAGE_TILING_LINEAR); if (aspect_iterator != m_aspects.end() ) { auto layer_mip_iterator = aspect_iterator->second.find(LayerMipKey(n_layer, n_mip) ); if (layer_mip_iterator != aspect_iterator->second.end() ) { *out_subresource_layout_ptr = layer_mip_iterator->second; result = true; } } return result; } /** Private function which initializes the Image instance. * * For argument discussion, please see documentation of the constructors. **/ void Anvil::Image::init(bool use_full_mipmap_chain, bool memory_mappable, bool memory_coherent, const VkImageLayout* start_image_layout_ptr) { std::vector<VkImageAspectFlags> aspects_used; std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr); VkImageFormatProperties image_format_props; uint32_t max_dimension; uint32_t n_queue_family_indices = 0; uint32_t queue_family_indices[3]; VkResult result (VK_ERROR_INITIALIZATION_FAILED); bool result_bool(false); ANVIL_REDUNDANT_VARIABLE(result); ANVIL_REDUNDANT_VARIABLE(result_bool); if (m_memory_owner && !memory_mappable) { anvil_assert(!memory_coherent); } /* Determine the maximum dimension size. */ max_dimension = m_width; if (max_dimension < m_height) { max_dimension = m_height; } if (max_dimension < m_depth) { max_dimension = m_depth; } /* Form the queue family array */ Anvil::Utils::convert_queue_family_bits_to_family_indices(m_device_ptr, m_queue_families, queue_family_indices, &n_queue_family_indices); /* Is the requested texture size valid? */ result_bool = device_locked_ptr->get_physical_device_image_format_properties(m_format, m_type, m_tiling, m_usage, 0, /* flags */ image_format_props); anvil_assert(result_bool); anvil_assert(m_width >= 1 && m_height >= 1 && m_depth >= 1); anvil_assert(m_width <= (uint32_t) image_format_props.maxExtent.width); if (m_height > 1) { anvil_assert(m_height <= (uint32_t) image_format_props.maxExtent.height); } if (m_depth > 1) { anvil_assert(m_depth <= (uint32_t) image_format_props.maxExtent.depth); } anvil_assert(m_n_layers >= 1); if (m_n_layers > 1) { anvil_assert(m_n_layers <= (uint32_t) image_format_props.maxArrayLayers); } /* If multisample image is requested, make sure the number of samples is supported. */ anvil_assert(m_sample_count >= 1); if (m_sample_count > 1) { anvil_assert((image_format_props.sampleCounts & m_sample_count) != 0); } /* Create the image object */ VkImageCreateInfo image_create_info; VkImageCreateFlags image_flags = m_flags; if (m_type == VK_IMAGE_TYPE_2D && (m_n_layers % 6) == 0) { image_flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; } if (m_is_mutable) { image_flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; } if (m_is_sparse) { /* Convert residency scope to Vulkan image create flags */ switch (m_residency_scope) { case Anvil::SPARSE_RESIDENCY_SCOPE_ALIASED: image_flags |= VK_IMAGE_CREATE_SPARSE_ALIASED_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; case Anvil::SPARSE_RESIDENCY_SCOPE_NONALIASED: image_flags |= VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; case Anvil::SPARSE_RESIDENCY_SCOPE_NONE: image_flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; default: { anvil_assert(false); } } } image_create_info.arrayLayers = m_n_layers; image_create_info.extent.depth = m_depth; image_create_info.extent.height = m_height; image_create_info.extent.width = m_width; image_create_info.flags = image_flags; image_create_info.format = m_format; image_create_info.imageType = m_type; image_create_info.initialLayout = (start_image_layout_ptr != nullptr) ? *start_image_layout_ptr : (m_mipmaps_to_upload.size() > 0) ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED; image_create_info.mipLevels = (uint32_t) ((use_full_mipmap_chain) ? (1 + log2(max_dimension)) : 1); image_create_info.pNext = nullptr; image_create_info.pQueueFamilyIndices = queue_family_indices; image_create_info.queueFamilyIndexCount = n_queue_family_indices; image_create_info.samples = static_cast<VkSampleCountFlagBits>(m_sample_count); image_create_info.sharingMode = m_sharing_mode; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.tiling = m_tiling; image_create_info.usage = m_usage; result = vkCreateImage(device_locked_ptr->get_device_vk(), &image_create_info, nullptr, /* pAllocator */ &m_image); anvil_assert_vk_call_succeeded(result); m_n_mipmaps = image_create_info.mipLevels; m_n_slices = (m_type == VK_IMAGE_TYPE_3D) ? m_depth : 1; if (m_swapchain_ptr == nullptr) { /* Extract various image properties we're going to need later */ vkGetImageMemoryRequirements(device_locked_ptr->get_device_vk(), m_image, &m_memory_reqs); m_alignment = m_memory_reqs.alignment; m_memory_types = m_memory_reqs.memoryTypeBits; m_storage_size = m_memory_reqs.size; } else { m_alignment = UINT64_MAX; m_memory_types = 0; m_storage_size = 0; } /* Cache aspect subresource properties if we're dealing with a linear image */ if (m_tiling == VK_IMAGE_TILING_LINEAR) { Anvil::Formats::get_format_aspects(m_format, &aspects_used); for (const auto& current_aspect : aspects_used) { VkImageSubresource subresource; subresource.aspectMask = current_aspect; for (uint32_t n_layer = 0; n_layer < m_n_layers; ++n_layer) { subresource.arrayLayer = n_layer; for (uint32_t n_mip = 0; n_mip < m_n_mipmaps; ++n_mip) { VkSubresourceLayout subresource_layout; subresource.mipLevel = n_mip; vkGetImageSubresourceLayout(device_locked_ptr->get_device_vk(), m_image, &subresource, &subresource_layout); m_aspects[static_cast<VkImageAspectFlagBits>(current_aspect)][LayerMipKey(n_layer, n_mip)] = subresource_layout; } } } } /* Initialize mipmap props storage */ init_mipmap_props(); if (m_is_sparse && m_residency_scope != SPARSE_RESIDENCY_SCOPE_NONE) { uint32_t n_reqs = 0; std::vector<VkSparseImageMemoryRequirements> sparse_image_memory_reqs; anvil_assert(m_swapchain_ptr == nullptr); /* Retrieve image aspect properties. Since Vulkan lets a single props structure to refer to more than * just a single aspect, we first cache the exposed info in a vec and then distribute the information to * a map, whose key is allowed to consist of a single bit ( = individual aspect) only */ vkGetImageSparseMemoryRequirements(device_locked_ptr->get_device_vk(), m_image, &n_reqs, nullptr); anvil_assert(n_reqs >= 1); sparse_image_memory_reqs.resize(n_reqs); vkGetImageSparseMemoryRequirements(device_locked_ptr->get_device_vk(), m_image, &n_reqs, &sparse_image_memory_reqs[0]); for (const auto& image_memory_req : sparse_image_memory_reqs) { for (uint32_t n_bit = 0; (1u << n_bit) <= image_memory_req.formatProperties.aspectMask; ++n_bit) { VkImageAspectFlagBits aspect = static_cast<VkImageAspectFlagBits>(1 << n_bit); if ((image_memory_req.formatProperties.aspectMask & aspect) == 0) { continue; } anvil_assert(m_sparse_aspect_props.find(aspect) == m_sparse_aspect_props.end() ); m_sparse_aspect_props[aspect] = Anvil::SparseImageAspectProperties(image_memory_req); } } /* Continue by setting up storage for page occupancy data */ init_page_occupancy(sparse_image_memory_reqs); /* Finally, partially-resident images require metadata aspect to be bound memory before they can be * accessed. Allocate & associate a dedicated memory block to the image */ auto metadata_aspect_iterator = m_sparse_aspect_props.find(VK_IMAGE_ASPECT_METADATA_BIT); if (metadata_aspect_iterator != m_sparse_aspect_props.end() ) { Anvil::SparseMemoryBindInfoID metadata_binding_bind_info_id; Anvil::Utils::SparseMemoryBindingUpdateInfo metadata_binding_update; std::shared_ptr<Anvil::Queue> sparse_queue_ptr(device_locked_ptr->get_sparse_binding_queue(0) ); /* TODO: Right now, we only support cases where image uses only one metadata block, no matter how many * layers there are. */ anvil_assert((metadata_aspect_iterator->second.flags & VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT) != 0); /* Instantiate the memory block which is going to hold the metadata * * NOTE: We should use an instance-wide allocator, preferably resizable, for this. */ m_metadata_memory_block_ptr = Anvil::MemoryBlock::create(m_device_ptr, m_memory_reqs.memoryTypeBits, metadata_aspect_iterator->second.mip_tail_size, false, /* should_be_mappable */ false); /* should_be_coherent */ /* Set up bind info update structure. */ metadata_binding_bind_info_id = metadata_binding_update.add_bind_info(0, /* n_signal_semaphores */ nullptr, /* opt_signal_semaphores_ptr */ 0, /* n_wait_semaphores */ nullptr); /* opt_wait_semaphores_ptr */ metadata_binding_update.append_opaque_image_memory_update(metadata_binding_bind_info_id, shared_from_this(), metadata_aspect_iterator->second.mip_tail_offset, metadata_aspect_iterator->second.mip_tail_size, VK_SPARSE_MEMORY_BIND_METADATA_BIT, m_metadata_memory_block_ptr, 0); /* opt_memory_block_start_offset */ result_bool = sparse_queue_ptr->bind_sparse_memory(metadata_binding_update); anvil_assert(result_bool); } } else if (m_residency_scope == Anvil::SPARSE_RESIDENCY_SCOPE_NONE && m_is_sparse) { m_page_tracker_ptr.reset( new Anvil::PageTracker(m_storage_size, m_alignment) ); } if (m_memory_owner) { anvil_assert(!m_is_sparse); /* Allocate memory for the image */ auto memory_block_ptr = Anvil::MemoryBlock::create(m_device_ptr, m_memory_reqs.memoryTypeBits, m_memory_reqs.size, memory_mappable, memory_coherent); set_memory(memory_block_ptr); } } /** Initializes page occupancy data. Should only be used for sparse images. * * @param memory_reqs Image memory requirements. **/ void Anvil::Image::init_page_occupancy(const std::vector<VkSparseImageMemoryRequirements>& memory_reqs) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr); anvil_assert(m_residency_scope != Anvil::SPARSE_RESIDENCY_SCOPE_NONE && m_residency_scope != Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED); /* First, allocate space for an AspectPageOccupancyData instance for all aspects used by the image. * * Vulkan may interleave data of more than one aspect in one memory region, so we need to go the extra * mile to ensure the same AspectPageOccupancyData structure is assigned to such aspects. */ for (const auto& memory_req : memory_reqs) { std::shared_ptr<AspectPageOccupancyData> occupancy_data_ptr; for (uint32_t n_aspect_bit = 0; (1u << n_aspect_bit) <= memory_req.formatProperties.aspectMask; ++n_aspect_bit) { VkImageAspectFlagBits current_aspect = static_cast<VkImageAspectFlagBits>(1 << n_aspect_bit); if ((memory_req.formatProperties.aspectMask & current_aspect) == 0) { continue; } if (m_sparse_aspect_page_occupancy.find(current_aspect) != m_sparse_aspect_page_occupancy.end() ) { occupancy_data_ptr = m_sparse_aspect_page_occupancy.at(current_aspect); break; } } if (occupancy_data_ptr == nullptr) { occupancy_data_ptr.reset( new AspectPageOccupancyData() ); } for (uint32_t n_aspect_bit = 0; (1u << n_aspect_bit) <= memory_req.formatProperties.aspectMask; ++n_aspect_bit) { VkImageAspectFlagBits current_aspect = static_cast<VkImageAspectFlagBits>(1 << n_aspect_bit); if ((memory_req.formatProperties.aspectMask & current_aspect) == 0) { continue; } m_sparse_aspect_page_occupancy[current_aspect] = occupancy_data_ptr; } } /* Next, iterate over each aspect and initialize storage for the mip chain */ anvil_assert(m_memory_reqs.alignment != 0); for (auto occupancy_iterator = m_sparse_aspect_page_occupancy.begin(); occupancy_iterator != m_sparse_aspect_page_occupancy.end(); ++occupancy_iterator) { const VkImageAspectFlagBits& current_aspect = occupancy_iterator->first; decltype(m_sparse_aspect_props)::const_iterator current_aspect_props_iterator; std::shared_ptr<AspectPageOccupancyData> page_occupancy_ptr = occupancy_iterator->second; if (page_occupancy_ptr->layers.size() > 0) { /* Already initialized */ continue; } if (current_aspect == VK_IMAGE_ASPECT_METADATA_BIT) { /* Don't initialize per-layer occupancy data for metadata aspect */ continue; } current_aspect_props_iterator = m_sparse_aspect_props.find(current_aspect); anvil_assert(current_aspect_props_iterator != m_sparse_aspect_props.end() ); anvil_assert(current_aspect_props_iterator->second.granularity.width >= 1); anvil_assert(current_aspect_props_iterator->second.granularity.height >= 1); anvil_assert(current_aspect_props_iterator->second.granularity.depth >= 1); /* Initialize storage for layer data.. */ for (uint32_t n_layer = 0; n_layer < m_n_layers; ++n_layer) { page_occupancy_ptr->layers.push_back(AspectPageOccupancyLayerData() ); auto& current_layer = page_occupancy_ptr->layers.back(); /* Tail can be, but does not necessarily have to be a part of non-zero layers. Take this into account, * when determining how many pages we need to alloc space for it. */ if (current_aspect_props_iterator->second.mip_tail_size > 0) { const bool is_single_miptail = (current_aspect_props_iterator->second.flags & VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT) != 0; if ((is_single_miptail && n_layer == 0) || !is_single_miptail) { anvil_assert( (current_aspect_props_iterator->second.mip_tail_size % m_memory_reqs.alignment) == 0); current_layer.n_total_tail_pages = static_cast<uint32_t>(current_aspect_props_iterator->second.mip_tail_size / m_memory_reqs.alignment); current_layer.tail_occupancy.resize(1 + current_layer.n_total_tail_pages / (sizeof(PageOccupancyStatus) * 8 /* bits in byte */) ); } else { current_layer.n_total_tail_pages = 0; } } else { current_layer.n_total_tail_pages = 0; } for (const auto& current_mip : m_mipmaps) { AspectPageOccupancyLayerMipData mip_data(current_mip.width, current_mip.height, current_mip.depth, current_aspect_props_iterator->second.granularity.width, current_aspect_props_iterator->second.granularity.height, current_aspect_props_iterator->second.granularity.depth); anvil_assert(current_mip.width >= 1); anvil_assert(current_mip.height >= 1); anvil_assert(current_mip.depth >= 1); current_layer.mips.push_back(mip_data); } } } } /** Releases the Vulkan image object, as well as the memory object associated with the Image instance. */ Anvil::Image::~Image() { if (m_image != VK_NULL_HANDLE && m_image_owner) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr); vkDestroyImage(device_locked_ptr->get_device_vk(), m_image, nullptr /* pAllocator */); m_image = VK_NULL_HANDLE; } m_memory_block_ptr.reset(); /* Unregister the object */ Anvil::ObjectTracker::get()->unregister_object(Anvil::OBJECT_TYPE_IMAGE, this); } /* Please see header for specification */ bool Anvil::Image::get_image_mipmap_size(uint32_t n_mipmap, uint32_t* opt_out_width_ptr, uint32_t* opt_out_height_ptr, uint32_t* opt_out_depth_ptr) const { bool result = false; /* Is this a sensible mipmap index? */ if (m_mipmaps.size() <= n_mipmap) { goto end; } /* Return the result data.. */ if (opt_out_width_ptr != nullptr) { *opt_out_width_ptr = m_mipmaps[n_mipmap].width; } if (opt_out_height_ptr != nullptr) { *opt_out_height_ptr = m_mipmaps[n_mipmap].height; } if (opt_out_depth_ptr != nullptr) { *opt_out_depth_ptr = m_mipmaps[n_mipmap].depth; } /* All done */ result = true; end: return result; } /** Please see header for specification */ bool Anvil::Image::get_sparse_image_aspect_properties(const VkImageAspectFlagBits aspect, const Anvil::SparseImageAspectProperties** out_result_ptr_ptr) const { decltype(m_sparse_aspect_props)::const_iterator prop_iterator; bool result = false; if (!m_is_sparse) { anvil_assert(m_is_sparse); goto end; } if (m_residency_scope == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { anvil_assert(m_residency_scope != Anvil::SPARSE_RESIDENCY_SCOPE_NONE); goto end; } prop_iterator = m_sparse_aspect_props.find(aspect); if (prop_iterator == m_sparse_aspect_props.end() ) { anvil_assert(prop_iterator != m_sparse_aspect_props.end() ); goto end; } *out_result_ptr_ptr = &prop_iterator->second; result = true; end: return result; } /** Please see header for specification */ VkImageSubresourceRange Anvil::Image::get_subresource_range() const { VkImageSubresourceRange result; switch (m_format) { case VK_FORMAT_D16_UNORM: case VK_FORMAT_D32_SFLOAT: { result.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; break; } case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT_S8_UINT: { result.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; break; } case VK_FORMAT_S8_UINT: { result.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; break; } default: { result.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; break; } } result.baseArrayLayer = 0; result.baseMipLevel = 0; result.layerCount = m_n_layers; result.levelCount = m_n_mipmaps; return result; } /** Please see header for specification */ bool Anvil::Image::has_aspects(VkImageAspectFlags aspects) const { VkImageAspectFlags checked_aspects = 0; bool result = true; if (m_is_sparse) { for (uint32_t n_bit = 0; n_bit < sizeof(uint32_t) * 8 /* bits in byte */ && result; ++n_bit) { VkImageAspectFlagBits current_aspect = static_cast<VkImageAspectFlagBits>(1 << n_bit); if ((aspects & current_aspect) != 0 && m_sparse_aspect_props.find(current_aspect) == m_sparse_aspect_props.end() ) { result = false; } } } else { const Anvil::ComponentLayout component_layout = Anvil::Formats::get_format_component_layout(m_format); bool has_color_components = false; bool has_depth_components = false; bool has_stencil_components = false; switch (component_layout) { case COMPONENT_LAYOUT_ABGR: case COMPONENT_LAYOUT_ARGB: case COMPONENT_LAYOUT_BGR: case COMPONENT_LAYOUT_BGRA: case COMPONENT_LAYOUT_EBGR: case COMPONENT_LAYOUT_R: case COMPONENT_LAYOUT_RG: case COMPONENT_LAYOUT_RGB: case COMPONENT_LAYOUT_RGBA: { has_color_components = true; break; } case COMPONENT_LAYOUT_D: case COMPONENT_LAYOUT_XD: { has_depth_components = true; break; } case COMPONENT_LAYOUT_DS: { has_depth_components = true; has_stencil_components = true; break; } case COMPONENT_LAYOUT_S: { has_stencil_components = true; break; } default: { anvil_assert(false); } } if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) { result &= has_color_components; checked_aspects |= VK_IMAGE_ASPECT_COLOR_BIT; } if (result && (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) != 0) { result &= has_depth_components; checked_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; } if (result && (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) != 0) { result &= has_stencil_components; checked_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; } anvil_assert(!result || result && checked_aspects == aspects); } return result; } /** Fills the m_mipmaps vector with mipmap size data. */ void Anvil::Image::init_mipmap_props() { uint32_t current_mipmap_size[3] = { m_width, m_height, m_depth }; anvil_assert(m_n_mipmaps != 0); anvil_assert(m_mipmaps.size() == 0); for (uint32_t mipmap_level = 0; mipmap_level < m_n_mipmaps; ++mipmap_level) { m_mipmaps.push_back(Mipmap(current_mipmap_size[0], current_mipmap_size[1], current_mipmap_size[2]) ); current_mipmap_size[0] /= 2; current_mipmap_size[1] /= 2; current_mipmap_size[2] /= 2; if (current_mipmap_size[0] < 1) { current_mipmap_size[0] = 1; } if (current_mipmap_size[1] < 1) { current_mipmap_size[1] = 1; } if (current_mipmap_size[2] < 1) { current_mipmap_size[2] = 1; } } } /* Please see header for specification */ bool Anvil::Image::is_memory_bound_for_texel(VkImageAspectFlagBits aspect, uint32_t n_layer, uint32_t n_mip, uint32_t x, uint32_t y, uint32_t z) const { bool result = false; /* Sanity checks */ anvil_assert(m_is_sparse); anvil_assert(m_residency_scope == SPARSE_RESIDENCY_SCOPE_ALIASED || m_residency_scope == SPARSE_RESIDENCY_SCOPE_NONALIASED); anvil_assert(m_n_layers > n_layer); anvil_assert(m_n_mipmaps > n_mip); anvil_assert(m_sparse_aspect_page_occupancy.find(aspect) != m_sparse_aspect_page_occupancy.end() ); /* Retrieve the tile status */ const auto& aspect_data = m_sparse_aspect_props.at(aspect); const auto& layer_data = m_sparse_aspect_page_occupancy.at(aspect)->layers.at(n_layer); if (n_mip >= aspect_data.mip_tail_first_lod) { /* For tails, we only have enough info to work at layer granularity */ const VkDeviceSize layer_start_offset = aspect_data.mip_tail_offset + aspect_data.mip_tail_stride * n_layer; ANVIL_REDUNDANT_VARIABLE_CONST(layer_start_offset); /* TODO */ result = true; } else { const auto& mip_data = layer_data.mips.at(n_mip); const uint32_t tile_index = mip_data.get_texture_space_xyz_to_block_mapping_index(x, y, z); result = (mip_data.tile_to_block_mappings.at(tile_index) != nullptr); } return result; } /* Please see header for specification */ bool Anvil::Image::set_memory(std::shared_ptr<Anvil::MemoryBlock> memory_block_ptr) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr); const Anvil::DeviceType device_type (device_locked_ptr->get_type() ); VkResult result (VK_ERROR_INITIALIZATION_FAILED); /* Sanity checks */ anvil_assert(memory_block_ptr != nullptr); anvil_assert(!m_is_sparse); anvil_assert(m_mipmaps.size() > 0); anvil_assert(m_memory_block_ptr == nullptr); anvil_assert(m_swapchain_ptr == nullptr); /* Bind the memory object to the image object */ if (device_type == Anvil::DEVICE_TYPE_SINGLE_GPU) { result = vkBindImageMemory(device_locked_ptr->get_device_vk(), m_image, memory_block_ptr->get_memory(), memory_block_ptr->get_start_offset() ); } anvil_assert_vk_call_succeeded(result); if (is_vk_call_successful(result) ) { m_memory_block_ptr = memory_block_ptr; /* Fill the storage with mipmap contents, if mipmap data was specified at input */ if (m_mipmaps_to_upload.size() > 0) { upload_mipmaps(&m_mipmaps_to_upload, (m_tiling == VK_IMAGE_TILING_LINEAR) ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED, &m_post_create_layout); m_mipmaps_to_upload.clear(); } if (m_post_create_layout != VK_IMAGE_LAYOUT_PREINITIALIZED && m_post_create_layout != VK_IMAGE_LAYOUT_UNDEFINED) { const uint32_t n_mipmaps_to_upload = static_cast<uint32_t>(m_mipmaps_to_upload.size()); transition_to_post_create_image_layout((n_mipmaps_to_upload > 0) ? VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : 0u, (n_mipmaps_to_upload > 0) ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED); } } return is_vk_call_successful(result); } /** Updates page tracker (for non-resident images) OR tile-to-block mappings & tail page counteres, * as per the specified non-opaque image memory update properties. * * @param resource_offset Raw image data offset, from which the update has been performed * @param size Size of the updated region. * @param memory_block_ptr Memory block, bound to the specified region. * @param memory_block_start_offset Start offset relative to @param memory_block_ptr used for the update. **/ void Anvil::Image::set_memory_sparse(VkDeviceSize resource_offset, VkDeviceSize size, std::shared_ptr<Anvil::MemoryBlock> memory_block_ptr, VkDeviceSize memory_block_start_offset) { const bool is_unbinding = (memory_block_ptr == nullptr); /* Sanity checks */ anvil_assert(m_is_sparse); if (memory_block_ptr != nullptr) { anvil_assert(memory_block_ptr->get_size() <= memory_block_start_offset + size); } if (m_residency_scope == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { /* Non-resident image: underlying memory is viewed as an opaque linear region. */ m_page_tracker_ptr->set_binding(memory_block_ptr, memory_block_start_offset, resource_offset, size); } else { /* We can land here under two circumstances: * * 1) Application is about to bind the same memory backing to all tiles OR unbind all * memory backings at once, which means that the process of updating page occupancy data * is fairly straightforward. * * 2) Application wants to bind (or unbind) the same memory backing to all miptail tiles. * * 3) Anvil::Image has requested to bind memory to metadata aspect. We don't track this so the operation * is a nop. * * TODO: This is not going to work right for multi-aspect images. Current impl seems slippy * - re-verify. */ auto metadata_aspect_iterator = m_sparse_aspect_props.find(VK_IMAGE_ASPECT_METADATA_BIT); if (metadata_aspect_iterator != m_sparse_aspect_props.end() ) { /* Handle case 3) */ if (resource_offset == metadata_aspect_iterator->second.mip_tail_offset && size == metadata_aspect_iterator->second.mip_tail_size) { return; } else { /* TODO: We do not currently support cases where the application tries to bind its own memory * block to the metadata aspect. */ anvil_assert(resource_offset < metadata_aspect_iterator->second.mip_tail_offset); } } for (auto aspect_iterator = m_sparse_aspect_page_occupancy.begin(); aspect_iterator != m_sparse_aspect_page_occupancy.end(); ++aspect_iterator) { VkImageAspectFlagBits current_aspect = aspect_iterator->first; const SparseImageAspectProperties& current_aspect_props = m_sparse_aspect_props.at(current_aspect); auto occupancy_data_ptr = aspect_iterator->second; ANVIL_REDUNDANT_VARIABLE_CONST(current_aspect_props); anvil_assert(resource_offset == 0 || resource_offset == current_aspect_props.mip_tail_offset && size == current_aspect_props.mip_tail_size); for (auto& current_layer : occupancy_data_ptr->layers) { if (resource_offset == 0) { for (auto& current_mip : current_layer.mips) { const uint32_t n_mip_tiles = static_cast<uint32_t>(current_mip.tile_to_block_mappings.size() ); if (is_unbinding) { for (uint32_t n_mip_tile = 0; n_mip_tile < n_mip_tiles; ++n_mip_tile) { current_mip.tile_to_block_mappings.at(n_mip_tile).reset(); } } else { for (uint32_t n_mip_tile = 0; n_mip_tile < n_mip_tiles; ++n_mip_tile) { current_mip.tile_to_block_mappings.at(n_mip_tile) = memory_block_ptr; } } } } if (current_layer.n_total_tail_pages != 0) { memset(&current_layer.tail_occupancy[0], (!is_unbinding) ? ~0 : 0, current_layer.tail_occupancy.size() ); if (is_unbinding) { current_layer.tail_pages_per_binding[memory_block_ptr] = current_layer.n_total_tail_pages; } else { current_layer.tail_pages_per_binding.clear(); } } } } } } /** Updates page tracker (for non-resident images) OR tile-to-block mappings & tail page counteres, * as per the specified opaque image update properties. * * @param subresource Subresource specified for the update. * @param offset Offset specified for the update. * @param extent Extent specified for the update. * @param memory_block_ptr Memory block, bound to the specified region. * @param memory_block_start_offset Start offset relative to @param memory_block_ptr used for the update. **/ void Anvil::Image::set_memory_sparse(const VkImageSubresource& subresource, VkOffset3D offset, VkExtent3D extent, std::shared_ptr<Anvil::MemoryBlock> memory_block_ptr, VkDeviceSize memory_block_start_offset) { AspectPageOccupancyLayerData* aspect_layer_ptr; AspectPageOccupancyLayerMipData* aspect_layer_mip_ptr; decltype(m_sparse_aspect_page_occupancy)::iterator aspect_page_occupancy_iterator; decltype(m_sparse_aspect_props)::iterator aspect_props_iterator; anvil_assert(m_residency_scope == Anvil::SPARSE_RESIDENCY_SCOPE_ALIASED || m_residency_scope == Anvil::SPARSE_RESIDENCY_SCOPE_NONALIASED); ANVIL_REDUNDANT_ARGUMENT(memory_block_start_offset); if (subresource.aspectMask == VK_IMAGE_ASPECT_METADATA_BIT) { /* TODO: Metadata is a blob - cache it separately */ anvil_assert(false); return; } aspect_page_occupancy_iterator = m_sparse_aspect_page_occupancy.find(static_cast<VkImageAspectFlagBits>(subresource.aspectMask) ); aspect_props_iterator = m_sparse_aspect_props.find (static_cast<VkImageAspectFlagBits>(subresource.aspectMask) ); anvil_assert(aspect_page_occupancy_iterator != m_sparse_aspect_page_occupancy.end() ); anvil_assert(aspect_props_iterator != m_sparse_aspect_props.end() ); anvil_assert((offset.x % aspect_props_iterator->second.granularity.width) == 0 && (offset.y % aspect_props_iterator->second.granularity.height) == 0 && (offset.z % aspect_props_iterator->second.granularity.depth) == 0); anvil_assert((extent.width % aspect_props_iterator->second.granularity.width) == 0 && (extent.height % aspect_props_iterator->second.granularity.height) == 0 && (extent.depth % aspect_props_iterator->second.granularity.depth) == 0); anvil_assert(aspect_page_occupancy_iterator->second->layers.size() >= subresource.arrayLayer); aspect_layer_ptr = &aspect_page_occupancy_iterator->second->layers.at(subresource.arrayLayer); anvil_assert(aspect_layer_ptr->mips.size() > subresource.mipLevel); aspect_layer_mip_ptr = &aspect_layer_ptr->mips.at(subresource.mipLevel); const uint32_t extent_tile[] = { extent.width / aspect_props_iterator->second.granularity.width, extent.height / aspect_props_iterator->second.granularity.height, extent.depth / aspect_props_iterator->second.granularity.depth }; const uint32_t offset_tile[] = { offset.x / aspect_props_iterator->second.granularity.width, offset.y / aspect_props_iterator->second.granularity.height, offset.z / aspect_props_iterator->second.granularity.depth }; /* We're going to favor readability over performance in the loops below. */ for (uint32_t current_x_tile = offset_tile[0]; current_x_tile < offset_tile[0] + extent_tile[0]; ++current_x_tile) { for (uint32_t current_y_tile = offset_tile[1]; current_y_tile < offset_tile[1] + extent_tile[1]; ++current_y_tile) { for (uint32_t current_z_tile = offset_tile[2]; current_z_tile < offset_tile[2] + extent_tile[2]; ++current_z_tile) { const uint32_t tile_index = aspect_layer_mip_ptr->get_tile_space_xyz_to_block_mapping_index(current_x_tile, current_y_tile, current_z_tile); anvil_assert(aspect_layer_mip_ptr->tile_to_block_mappings.size() > tile_index); /* Assign the memory block (potentially null) to the tile */ aspect_layer_mip_ptr->tile_to_block_mappings.at(tile_index) = memory_block_ptr; } } } } /* Transitions the underlying Vulkan image to the layout stored in m_post_create_layout. * * @param source_access_mask All access types used to fill the image with data. * @param src_layout Layout to transition from. **/ void Anvil::Image::transition_to_post_create_image_layout(VkAccessFlags source_access_mask, VkImageLayout src_layout) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr (m_device_ptr); const Anvil::DeviceType device_type (device_locked_ptr->get_type() ); std::shared_ptr<Anvil::PrimaryCommandBuffer> transition_command_buffer_ptr; std::shared_ptr<Anvil::Queue> universal_queue_ptr; anvil_assert(!m_has_transitioned_to_post_create_layout); universal_queue_ptr = device_locked_ptr->get_universal_queue(0); transition_command_buffer_ptr = device_locked_ptr->get_command_pool (Anvil::QUEUE_FAMILY_TYPE_UNIVERSAL)->alloc_primary_level_command_buffer(); transition_command_buffer_ptr->start_recording(true, /* one_time_submit */ false); /* simultaneous_use_allowed */ { Anvil::ImageBarrier image_barrier(source_access_mask, Anvil::Utils::get_access_mask_from_image_layout(m_post_create_layout), false, src_layout, m_post_create_layout, (m_sharing_mode == VK_SHARING_MODE_CONCURRENT) ? VK_QUEUE_FAMILY_IGNORED : universal_queue_ptr->get_queue_family_index(), (m_sharing_mode == VK_SHARING_MODE_CONCURRENT) ? VK_QUEUE_FAMILY_IGNORED : universal_queue_ptr->get_queue_family_index(), shared_from_this(), get_subresource_range() ); transition_command_buffer_ptr->record_pipeline_barrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_FALSE, /* in_by_region */ 0, /* in_memory_barrier_count */ nullptr, /* in_memory_barrier_ptrs */ 0, /* in_buffer_memory_barrier_count */ nullptr, /* in_buffer_memory_barrier_ptrs */ 1, /* in_image_memory_barrier_count */ &image_barrier); } transition_command_buffer_ptr->stop_recording(); if (device_type == Anvil::DEVICE_TYPE_SINGLE_GPU) { universal_queue_ptr->submit_command_buffer(transition_command_buffer_ptr, true /* should_block */); } m_has_transitioned_to_post_create_layout = true; } /** Please see header for specification */ void Anvil::Image::upload_mipmaps(const std::vector<MipmapRawData>* mipmaps_ptr, VkImageLayout current_image_layout, VkImageLayout* out_new_image_layout_ptr) { std::shared_ptr<Anvil::BaseDevice> device_locked_ptr(m_device_ptr); std::map<VkImageAspectFlagBits, std::vector<const Anvil::MipmapRawData*> > image_aspect_to_mipmap_raw_data_map; VkImageAspectFlags image_aspects_touched (0); VkImageSubresourceRange image_subresource_range; uint32_t max_layer_index (UINT32_MAX); uint32_t max_mipmap_index (UINT32_MAX); uint32_t min_layer_index (UINT32_MAX); uint32_t min_mipmap_index (UINT32_MAX); /* Each image aspect needs to be modified separately. Iterate over the input vector and move MipmapRawData * to separate vectors corresponding to which aspect they need to update. */ for (auto mipmap_iterator = mipmaps_ptr->cbegin(); mipmap_iterator != mipmaps_ptr->cend(); ++mipmap_iterator) { image_aspect_to_mipmap_raw_data_map[mipmap_iterator->aspect].push_back(&(*mipmap_iterator)); } /* Determine the max/min layer & mipmap indices */ anvil_assert(mipmaps_ptr->size() > 0); for (auto mipmap_iterator = mipmaps_ptr->cbegin(); mipmap_iterator != mipmaps_ptr->cend(); ++mipmap_iterator) { image_aspects_touched |= mipmap_iterator->aspect; if (max_layer_index == UINT32_MAX || max_layer_index < mipmap_iterator->n_layer) {<|fim▁hole|> } if (max_mipmap_index == UINT32_MAX || max_mipmap_index < mipmap_iterator->n_mipmap) { max_mipmap_index = mipmap_iterator->n_mipmap; } if (min_layer_index == UINT32_MAX || min_layer_index > mipmap_iterator->n_layer) { min_layer_index = mipmap_iterator->n_layer; } if (min_mipmap_index == UINT32_MAX || min_mipmap_index > mipmap_iterator->n_mipmap) { min_mipmap_index = mipmap_iterator->n_mipmap; } } anvil_assert(max_layer_index < m_n_layers); anvil_assert(max_mipmap_index < m_n_mipmaps); /* Fill the buffer memory with data, according to the specified layout requirements, * if linear tiling is used. * * For optimal tiling, we need to copy the raw data to temporary buffer * and use vkCmdCopyBufferToImage() to let the driver rearrange the data as needed. */ image_subresource_range.aspectMask = image_aspects_touched; image_subresource_range.baseArrayLayer = min_layer_index; image_subresource_range.baseMipLevel = min_mipmap_index; image_subresource_range.layerCount = max_layer_index - min_layer_index + 1; image_subresource_range.levelCount = max_mipmap_index - min_mipmap_index + 1; if (m_tiling == VK_IMAGE_TILING_LINEAR) { /* TODO: Transition the subresource ranges, if necessary. */ anvil_assert(current_image_layout == VK_IMAGE_LAYOUT_PREINITIALIZED); for (auto aspect_to_mipmap_data_iterator = image_aspect_to_mipmap_raw_data_map.begin(); aspect_to_mipmap_data_iterator != image_aspect_to_mipmap_raw_data_map.end(); ++aspect_to_mipmap_data_iterator) { VkImageAspectFlagBits current_aspect = aspect_to_mipmap_data_iterator->first; const auto& mipmap_raw_data_items = aspect_to_mipmap_data_iterator->second; for (auto mipmap_raw_data_item_iterator = mipmap_raw_data_items.begin(); mipmap_raw_data_item_iterator != mipmap_raw_data_items.end(); ++mipmap_raw_data_item_iterator) { const unsigned char* current_mipmap_data_ptr = nullptr; uint32_t current_mipmap_height = 0; const auto& current_mipmap_raw_data_item_ptr = *mipmap_raw_data_item_iterator; uint32_t current_mipmap_slices = 0; uint32_t current_row_size = 0; uint32_t current_slice_size = 0; VkDeviceSize dst_slice_offset = 0; const unsigned char* src_slice_ptr = nullptr; VkImageSubresource image_subresource; VkSubresourceLayout image_subresource_layout; current_mipmap_data_ptr = (current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_ptr != nullptr) ? current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_ptr.get() : (current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_raw_ptr != nullptr) ? current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_raw_ptr : &(*current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_vec_ptr)[0]; image_subresource.arrayLayer = current_mipmap_raw_data_item_ptr->n_layer; image_subresource.aspectMask = current_aspect; image_subresource.mipLevel = current_mipmap_raw_data_item_ptr->n_mipmap; vkGetImageSubresourceLayout(device_locked_ptr->get_device_vk(), m_image, &image_subresource, &image_subresource_layout); /* Determine row size for the mipmap. * * NOTE: Current implementation can only handle power-of-two textures. */ anvil_assert(m_height == 1 || (m_height % 2) == 0); current_mipmap_height = m_height / (1 << current_mipmap_raw_data_item_ptr->n_mipmap); if (current_mipmap_height < 1) { current_mipmap_height = 1; } current_mipmap_slices = current_mipmap_raw_data_item_ptr->n_slices; current_row_size = current_mipmap_raw_data_item_ptr->row_size; current_slice_size = (current_row_size * current_mipmap_height); if (current_mipmap_slices < 1) { current_mipmap_slices = 1; } for (unsigned int n_slice = 0; n_slice < current_mipmap_slices; ++n_slice) { dst_slice_offset = image_subresource_layout.offset + image_subresource_layout.depthPitch * n_slice; src_slice_ptr = current_mipmap_data_ptr + current_slice_size * n_slice; for (unsigned int n_row = 0; n_row < current_mipmap_height; ++n_row, dst_slice_offset += image_subresource_layout.rowPitch) { m_memory_block_ptr->write(dst_slice_offset, current_row_size, src_slice_ptr + current_row_size * n_row); } } } } *out_new_image_layout_ptr = VK_IMAGE_LAYOUT_PREINITIALIZED; } else { anvil_assert(m_tiling == VK_IMAGE_TILING_OPTIMAL); std::shared_ptr<Anvil::Buffer> temp_buffer_ptr; std::shared_ptr<Anvil::PrimaryCommandBuffer> temp_cmdbuf_ptr; VkDeviceSize total_raw_mips_size = 0; std::shared_ptr<Anvil::Queue> universal_queue_ptr = device_locked_ptr->get_universal_queue(0); /* Count how much space all specified mipmaps take in raw format. */ for (auto mipmap_iterator = mipmaps_ptr->cbegin(); mipmap_iterator != mipmaps_ptr->cend(); ++mipmap_iterator) { total_raw_mips_size += mipmap_iterator->n_slices * mipmap_iterator->data_size; /* Mip offsets must be rounded up to 4 due to the following "Valid Usage" requirement of VkBufferImageCopy struct: * * "bufferOffset must be a multiple of 4" */ if ((total_raw_mips_size % 4) != 0) { total_raw_mips_size += (4 - (total_raw_mips_size % 4)); } } /* Merge data of all mips into one buffer, cache the offsets and push the merged data * to the buffer memory. */ std::vector<VkDeviceSize> mip_data_offsets; VkDeviceSize current_mip_offset = 0; std::unique_ptr<char> merged_mip_storage(new char[static_cast<uint32_t>(total_raw_mips_size)]); /* NOTE: The memcpy() call, as well as the way we implement copy op calls below, assume * POT resolution of the base mipmap */ anvil_assert(m_height < 2 || (m_height % 2) == 0); for (auto mipmap_iterator = mipmaps_ptr->cbegin(); mipmap_iterator != mipmaps_ptr->cend(); ++mipmap_iterator) { const auto& current_mipmap = *mipmap_iterator; const unsigned char* current_mipmap_data_ptr; current_mipmap_data_ptr = (mipmap_iterator->linear_tightly_packed_data_uchar_ptr != nullptr) ? mipmap_iterator->linear_tightly_packed_data_uchar_ptr.get() : (mipmap_iterator->linear_tightly_packed_data_uchar_raw_ptr != nullptr) ? mipmap_iterator->linear_tightly_packed_data_uchar_raw_ptr : &(*mipmap_iterator->linear_tightly_packed_data_uchar_vec_ptr)[0]; mip_data_offsets.push_back(current_mip_offset); memcpy(merged_mip_storage.get() + current_mip_offset, current_mipmap_data_ptr, current_mipmap.n_slices * current_mipmap.data_size); current_mip_offset += current_mipmap.n_slices * current_mipmap.data_size; /* Mip offset must be rounded up to 4 due to the following "Valid Usage" requirement of VkBufferImageCopy struct: * * "bufferOffset must be a multiple of 4" */ if ((current_mip_offset % 4) != 0) { current_mip_offset = Anvil::Utils::round_up(current_mip_offset, static_cast<VkDeviceSize>(4) ); } } temp_buffer_ptr = Anvil::Buffer::create_nonsparse(m_device_ptr, total_raw_mips_size, Anvil::QUEUE_FAMILY_GRAPHICS_BIT, VK_SHARING_MODE_EXCLUSIVE, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, false, /* should_be_mappable */ false, /* should_be_coherent */ merged_mip_storage.get() ); merged_mip_storage.reset(); /* Set up a command buffer we will use to copy the data to the image */ temp_cmdbuf_ptr = device_locked_ptr->get_command_pool(Anvil::QUEUE_FAMILY_TYPE_UNIVERSAL)->alloc_primary_level_command_buffer(); anvil_assert(temp_cmdbuf_ptr != nullptr); temp_cmdbuf_ptr->start_recording(true, /* one_time_submit */ false /* simultaneous_use_allowed */); { std::vector<VkBufferImageCopy> copy_regions; /* Transfer the image to the transfer_destination layout */ Anvil::ImageBarrier image_barrier(0, /* source_access_mask */ VK_ACCESS_TRANSFER_WRITE_BIT, false, current_image_layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, universal_queue_ptr->get_queue_family_index(), universal_queue_ptr->get_queue_family_index(), shared_from_this(), image_subresource_range); temp_cmdbuf_ptr->record_pipeline_barrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_FALSE, /* in_by_region */ 0, /* in_memory_barrier_count */ nullptr, /* in_memory_barrier_ptrs */ 0, /* in_buffer_memory_barrier_count */ nullptr, /* in_buffer_memory_barrier_ptrs */ 1, /* in_image_memory_barrier_count */ &image_barrier); /* Issue the buffer->image copy op */ copy_regions.reserve(mipmaps_ptr->size() ); for (auto mipmap_iterator = mipmaps_ptr->cbegin(); mipmap_iterator != mipmaps_ptr->cend(); ++mipmap_iterator) { VkBufferImageCopy current_copy_region; const auto& current_mipmap = *mipmap_iterator; current_copy_region.bufferImageHeight = m_height / (1 << current_mipmap.n_mipmap); current_copy_region.bufferOffset = mip_data_offsets[static_cast<uint32_t>(mipmap_iterator - mipmaps_ptr->cbegin()) ]; current_copy_region.bufferRowLength = 0; current_copy_region.imageOffset.x = 0; current_copy_region.imageOffset.y = 0; current_copy_region.imageOffset.z = 0; current_copy_region.imageSubresource.baseArrayLayer = current_mipmap.n_layer; current_copy_region.imageSubresource.layerCount = current_mipmap.n_layers; current_copy_region.imageSubresource.aspectMask = current_mipmap.aspect; current_copy_region.imageSubresource.mipLevel = current_mipmap.n_mipmap; current_copy_region.imageExtent.depth = current_mipmap.n_slices; current_copy_region.imageExtent.height = m_height / (1 << current_mipmap.n_mipmap); current_copy_region.imageExtent.width = m_width / (1 << current_mipmap.n_mipmap); if (current_copy_region.imageExtent.depth < 1) { current_copy_region.imageExtent.depth = 1; } if (current_copy_region.imageExtent.height < 1) { current_copy_region.imageExtent.height = 1; } if (current_copy_region.imageExtent.width < 1) { current_copy_region.imageExtent.width = 1; } copy_regions.push_back(current_copy_region); } temp_cmdbuf_ptr->record_copy_buffer_to_image(temp_buffer_ptr, shared_from_this(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<uint32_t>(copy_regions.size() ), &copy_regions[0]); } temp_cmdbuf_ptr->stop_recording(); /* Execute the command buffer */ universal_queue_ptr->submit_command_buffer(temp_cmdbuf_ptr, true /* should_block */); *out_new_image_layout_ptr = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; } }<|fim▁end|>
max_layer_index = mipmap_iterator->n_layer;
<|file_name|>anomaly_likelihood_region_test.py<|end_file_name|><|fim▁begin|># ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ----------------------------------------------------------------------<|fim▁hole|>import csv import numpy try: import capnp except ImportError: capnp = None if capnp: from nupic.regions.AnomalyLikelihoodRegion_capnp import\ AnomalyLikelihoodRegionProto from nupic.regions.anomaly_likelihood_region import AnomalyLikelihoodRegion from nupic.algorithms.anomaly_likelihood import AnomalyLikelihood from pkg_resources import resource_filename _INPUT_DATA_FILE = resource_filename( "nupic.datafiles", "extra/hotgym/hotgym-anomaly.csv" ) """ Unit tests for the anomaly likelihood region """ class AnomalyLikelihoodRegionTest(unittest.TestCase): """Tests for anomaly likelihood region""" def testParamterError(self): """ ensure historicWindowSize is greater than estimationSamples """ try: anomalyLikelihoodRegion = AnomalyLikelihoodRegion(estimationSamples=100, historicWindowSize=99) self.assertEqual(False, True, "Should have failed with ValueError") except ValueError: pass def testLikelihoodValues(self): """ test to see if the region keeps track of state correctly and produces the same likelihoods as the AnomalyLikelihood module """ anomalyLikelihoodRegion = AnomalyLikelihoodRegion() anomalyLikelihood = AnomalyLikelihood() inputs = AnomalyLikelihoodRegion.getSpec()['inputs'] outputs = AnomalyLikelihoodRegion.getSpec()['outputs'] with open (_INPUT_DATA_FILE) as f: reader = csv.reader(f) reader.next() for record in reader: consumption = float(record[1]) anomalyScore = float(record[2]) likelihood1 = anomalyLikelihood.anomalyProbability( consumption, anomalyScore) inputs['rawAnomalyScore'] = numpy.array([anomalyScore]) inputs['metricValue'] = numpy.array([consumption]) anomalyLikelihoodRegion.compute(inputs, outputs) likelihood2 = outputs['anomalyLikelihood'][0] self.assertEqual(likelihood1, likelihood2) @unittest.skipUnless( capnp, "pycapnp is not installed, skipping serialization test.") def testSerialization(self): """ test to ensure serialization preserves the state of the region correctly. """ anomalyLikelihoodRegion1 = AnomalyLikelihoodRegion() inputs = AnomalyLikelihoodRegion.getSpec()['inputs'] outputs = AnomalyLikelihoodRegion.getSpec()['outputs'] parameters = AnomalyLikelihoodRegion.getSpec()['parameters'] # Make sure to calculate distribution by passing the probation period learningPeriod = parameters['learningPeriod']['defaultValue'] reestimationPeriod = parameters['reestimationPeriod']['defaultValue'] probation = learningPeriod + reestimationPeriod for _ in xrange(0, probation + 1): inputs['rawAnomalyScore'] = numpy.array([random.random()]) inputs['metricValue'] = numpy.array([random.random()]) anomalyLikelihoodRegion1.compute(inputs, outputs) score1 = outputs['anomalyLikelihood'][0] proto1 = AnomalyLikelihoodRegionProto.new_message() anomalyLikelihoodRegion1.write(proto1) # Write the proto to a temp file and read it back into a new proto with tempfile.TemporaryFile() as f: proto1.write(f) f.seek(0) proto2 = AnomalyLikelihoodRegionProto.read(f) # # Load the deserialized proto anomalyLikelihoodRegion2 = AnomalyLikelihoodRegion.read(proto2) self.assertEqual(anomalyLikelihoodRegion1, anomalyLikelihoodRegion2) window = parameters['historicWindowSize']['defaultValue'] for _ in xrange(0, window + 1): inputs['rawAnomalyScore'] = numpy.array([random.random()]) inputs['metricValue'] = numpy.array([random.random()]) anomalyLikelihoodRegion1.compute(inputs, outputs) score1 = outputs['anomalyLikelihood'][0] anomalyLikelihoodRegion2.compute(inputs, outputs) score2 = outputs['anomalyLikelihood'][0] self.assertEqual(score1, score2) if __name__ == "__main__": unittest.main()<|fim▁end|>
import tempfile import unittest import random
<|file_name|>notification.js<|end_file_name|><|fim▁begin|>/** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ (function ($, require) { var exports = require('piwik/UI'); /** * Creates a new notifications. * * Example: * var UI = require('piwik/UI'); * var notification = new UI.Notification(); * notification.show('My Notification Message', {title: 'Low space', context: 'warning'}); */ var Notification = function () { this.$node = null; }; /** * Makes the notification visible.<|fim▁hole|> * @param {Object} [options] * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {bool} [options.animate=true] If enabled, the notification will be faded in. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} * @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar". * You can specify any other CSS selector to place the notifications * wherever you want. */ Notification.prototype.show = function (message, options) { checkMessage(message); options = checkOptions(options); var template = generateNotificationHtmlMarkup(options, message); this.$node = placeNotification(template, options); }; /** * Removes a previously shown notification having the given notification id. * * * @param {string} notificationId The id of a notification that was previously registered. */ Notification.prototype.remove = function (notificationId) { $('[piwik-notification][notification-id=' + notificationId + ']').remove(); }; Notification.prototype.scrollToNotification = function () { if (this.$node) { piwikHelper.lazyScrollTo(this.$node, 250); } }; /** * Shows a notification at a certain point with a quick upwards animation. * * TODO: if the materializecss version matomo uses is updated, should use their toasts. * * @type {Notification} * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} options * @param {string} options.placeat Where to place the notification. Required. * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} */ Notification.prototype.toast = function (message, options) { checkMessage(message); options = checkOptions(options); var $placeat = $(options.placeat); if (!$placeat.length) { throw new Error("A valid selector is required for the placeat option when using Notification.toast()."); } var $template = $(generateNotificationHtmlMarkup(options, message)).hide(); $('body').append($template); compileNotification($template); $template.css({ position: 'absolute', left: $placeat.offset().left, top: $placeat.offset().top }); setTimeout(function () { $template.animate( { top: $placeat.offset().top - $template.height() }, { duration: 300, start: function () { $template.show(); } } ); }); }; exports.Notification = Notification; function generateNotificationHtmlMarkup(options, message) { var attributeMapping = { id: 'notification-id', title: 'notification-title', context: 'context', type: 'type', noclear: 'noclear', class: 'class', toastLength: 'toast-length' }, html = '<div piwik-notification'; for (var key in attributeMapping) { if (attributeMapping.hasOwnProperty(key) && options[key] ) { html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, "&quot;") + '"'; } } html += '>' + message + '</div>'; return html; } function compileNotification($node) { angular.element(document).injector().invoke(function ($compile, $rootScope) { $compile($node)($rootScope.$new(true)); }); } function placeNotification(template, options) { var $notificationNode = $(template); // compile the template in angular compileNotification($notificationNode); if (options.style) { $notificationNode.css(options.style); } var notificationPosition = '#notificationContainer'; var method = 'append'; if (options.placeat) { notificationPosition = options.placeat; } else { // If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal var modalSelector = '.modal.open .modal-content'; var modalOpen = $(modalSelector); if (modalOpen.length) { notificationPosition = modalSelector; method = 'prepend'; } } $notificationNode = $notificationNode.hide(); $(notificationPosition)[method]($notificationNode); if (false === options.animate) { $notificationNode.show(); } else { $notificationNode.fadeIn(1000); } return $notificationNode; } function checkMessage(message) { if (!message) { throw new Error('No message given, cannot display notification'); } } function checkOptions(options) { if (options && !$.isPlainObject(options)) { throw new Error('Options has the wrong format, cannot display notification'); } else if (!options) { options = {}; } return options; } })(jQuery, require);<|fim▁end|>
* * @param {string} message The actual message that will be displayed. Must be set.
<|file_name|>locked_queue.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
#include "locked_queue.h"
<|file_name|>application_gateway_sku.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator.<|fim▁hole|># regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ApplicationGatewaySku(Model): """SKU of an application gateway. :param name: Name of an application gateway SKU. Possible values are: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', and 'WAF_Large'. Possible values include: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', 'WAF_Large' :type name: str or :class:`ApplicationGatewaySkuName <azure.mgmt.network.v2016_09_01.models.ApplicationGatewaySkuName>` :param tier: Tier of an application gateway. Possible values are: 'Standard' and 'WAF'. Possible values include: 'Standard', 'WAF' :type tier: str or :class:`ApplicationGatewayTier <azure.mgmt.network.v2016_09_01.models.ApplicationGatewayTier>` :param capacity: Capacity (instance count) of an application gateway. :type capacity: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(self, name=None, tier=None, capacity=None): self.name = name self.tier = tier self.capacity = capacity<|fim▁end|>
# Changes may cause incorrect behavior and will be lost if the code is
<|file_name|>Guild.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Guild.h" #include "AccountMgr.h" #include "Bag.h" #include "CalendarMgr.h" #include "CharacterCache.h" #include "Chat.h" #include "Config.h" #include "DatabaseEnv.h" #include "GameTime.h" #include "GuildMgr.h" #include "Language.h" #include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" #include "ScriptMgr.h" #include "SocialMgr.h" #include "World.h" #include "WorldSession.h" size_t const MAX_GUILD_BANK_TAB_TEXT_LEN = 500; uint32 const EMBLEM_PRICE = 10 * GOLD; // only used in logs char const* GetGuildEventString(GuildEvents event) { switch (event) { case GE_PROMOTION: return "Member promotion"; case GE_DEMOTION: return "Member demotion"; case GE_MOTD: return "Guild MOTD"; case GE_JOINED: return "Member joined"; case GE_LEFT: return "Member left"; case GE_REMOVED: return "Member removed"; case GE_LEADER_IS: return "Leader is"; case GE_LEADER_CHANGED: return "Leader changed"; case GE_DISBANDED: return "Guild disbanded"; case GE_TABARDCHANGE: return "Tabard change"; case GE_RANK_UPDATED: return "Rank updated"; case GE_RANK_DELETED: return "Rank deleted"; case GE_SIGNED_ON: return "Member signed on"; case GE_SIGNED_OFF: return "Member signed off"; case GE_GUILDBANKBAGSLOTS_CHANGED: return "Bank bag slots changed"; case GE_BANK_TAB_PURCHASED: return "Bank tab purchased"; case GE_BANK_TAB_UPDATED: return "Bank tab updated"; case GE_BANK_MONEY_SET: return "Bank money set"; case GE_BANK_TAB_AND_MONEY_UPDATED: return "Bank and money updated"; case GE_BANK_TEXT_CHANGED: return "Bank tab text changed"; default: break; } return "<None>"; } inline uint32 GetGuildBankTabPrice(uint8 tabId) { // these prices are in gold units, not copper static uint32 const tabPrices[GUILD_BANK_MAX_TABS] = { 100, 250, 500, 1000, 2500, 5000 }; ASSERT(tabId < GUILD_BANK_MAX_TABS); return tabPrices[tabId]; } void Guild::SendCommandResult(WorldSession* session, GuildCommandType type, GuildCommandError errCode, std::string const& param) { WorldPacket data(SMSG_GUILD_COMMAND_RESULT, 8 + param.size() + 1); data << uint32(type); data << param; data << uint32(errCode); session->SendPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_COMMAND_RESULT [%s]: Type: %u, code: %u, param: %s" , session->GetPlayerInfo().c_str(), type, errCode, param.c_str()); } void Guild::SendSaveEmblemResult(WorldSession* session, GuildEmblemError errCode) { WorldPacket data(MSG_SAVE_GUILD_EMBLEM, 4); data << uint32(errCode); session->SendPacket(&data); TC_LOG_DEBUG("guild", "MSG_SAVE_GUILD_EMBLEM [%s] Code: %u", session->GetPlayerInfo().c_str(), errCode); } // LogHolder Guild::LogHolder::~LogHolder() { // Cleanup for (auto itr = m_log.begin(); itr != m_log.end(); ++itr) delete (*itr); } // Adds event loaded from database to collection inline void Guild::LogHolder::LoadEvent(LogEntry* entry) { if (m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED)) m_nextGUID = entry->GetGUID(); m_log.push_front(entry); } // Adds new event happened in game. // If maximum number of events is reached, oldest event is removed from collection. inline void Guild::LogHolder::AddEvent(SQLTransaction& trans, LogEntry* entry) { // Check max records limit if (m_log.size() >= m_maxRecords) { LogEntry* oldEntry = m_log.front(); delete oldEntry; m_log.pop_front(); } // Add event to list m_log.push_back(entry); // Save to DB entry->SaveToDB(trans); } // Writes information about all events into packet. inline void Guild::LogHolder::WritePacket(WorldPacket& data) const { data << uint8(m_log.size()); for (auto itr = m_log.begin(); itr != m_log.end(); ++itr) (*itr)->WritePacket(data); } inline uint32 Guild::LogHolder::GetNextGUID() { // Next guid was not initialized. It means there are no records for this holder in DB yet. // Start from the beginning. if (m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED)) m_nextGUID = 0; else m_nextGUID = (m_nextGUID + 1) % m_maxRecords; return m_nextGUID; } Guild::LogEntry::LogEntry(ObjectGuid::LowType guildId, uint32 guid) : m_guildId(guildId), m_guid(guid), m_timestamp(GameTime::GetGameTime()) { } // EventLogEntry void Guild::EventLogEntry::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG); stmt->setUInt32(0, m_guildId); stmt->setUInt32(1, m_guid); trans->Append(stmt); uint8 index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, uint8(m_eventType)); stmt->setUInt32(++index, m_playerGuid1); stmt->setUInt32(++index, m_playerGuid2); stmt->setUInt8 (++index, m_newRank); stmt->setUInt64(++index, m_timestamp); trans->Append(stmt); } void Guild::EventLogEntry::WritePacket(WorldPacket& data) const { // Event type data << uint8(m_eventType); // Player 1 data << ObjectGuid(HighGuid::Player, m_playerGuid1); // Player 2 not for left/join guild events if (m_eventType != GUILD_EVENT_LOG_JOIN_GUILD && m_eventType != GUILD_EVENT_LOG_LEAVE_GUILD) data << ObjectGuid(HighGuid::Player, m_playerGuid2); // New Rank - only for promote/demote guild events if (m_eventType == GUILD_EVENT_LOG_PROMOTE_PLAYER || m_eventType == GUILD_EVENT_LOG_DEMOTE_PLAYER) data << uint8(m_newRank); // Event timestamp data << uint32(GameTime::GetGameTime() - m_timestamp); } // BankEventLogEntry void Guild::BankEventLogEntry::SaveToDB(SQLTransaction& trans) const { uint8 index = 0; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, m_bankTabId); trans->Append(stmt); index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, m_bankTabId); stmt->setUInt8 (++index, uint8(m_eventType)); stmt->setUInt32(++index, m_playerGuid); stmt->setUInt32(++index, m_itemOrMoney); stmt->setUInt16(++index, m_itemStackCount); stmt->setUInt8 (++index, m_destTabId); stmt->setUInt64(++index, m_timestamp); trans->Append(stmt); } void Guild::BankEventLogEntry::WritePacket(WorldPacket& data) const { data << uint8(m_eventType); data << ObjectGuid(HighGuid::Player, m_playerGuid); switch (m_eventType) { case GUILD_BANK_LOG_DEPOSIT_ITEM: case GUILD_BANK_LOG_WITHDRAW_ITEM: data << uint32(m_itemOrMoney); data << uint32(m_itemStackCount); break; case GUILD_BANK_LOG_MOVE_ITEM: case GUILD_BANK_LOG_MOVE_ITEM2: data << uint32(m_itemOrMoney); data << uint32(m_itemStackCount); data << uint8(m_destTabId); break; default: data << uint32(m_itemOrMoney); } data << uint32(GameTime::GetGameTime() - m_timestamp); } // RankInfo void Guild::RankInfo::LoadFromDB(Field* fields) { m_rankId = fields[1].GetUInt8(); m_name = fields[2].GetString(); m_rights = fields[3].GetUInt32(); m_bankMoneyPerDay = fields[4].GetUInt32(); if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights m_rights |= GR_RIGHT_ALL; } void Guild::RankInfo::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_RANK); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_rankId); stmt->setString(2, m_name); stmt->setUInt32(3, m_rights); stmt->setUInt32(4, m_bankMoneyPerDay); CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::RankInfo::CreateMissingTabsIfNeeded(uint8 tabs, SQLTransaction& trans, bool logOnCreate /* = false */) { for (uint8 i = 0; i < tabs; ++i) { GuildBankRightsAndSlots& rightsAndSlots = m_bankTabRightsAndSlots[i]; if (rightsAndSlots.GetTabId() == i) continue; rightsAndSlots.SetTabId(i); if (m_rankId == GR_GUILDMASTER) rightsAndSlots.SetGuildMasterValues(); if (logOnCreate) TC_LOG_ERROR("guild", "Guild %u has broken Tab %u for rank %u. Created default tab.", m_guildId, i, m_rankId); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); stmt->setUInt32(0, m_guildId); stmt->setUInt8(1, i); stmt->setUInt8(2, m_rankId); stmt->setUInt8(3, rightsAndSlots.GetRights()); stmt->setUInt32(4, rightsAndSlots.GetSlots()); trans->Append(stmt); } } void Guild::RankInfo::WritePacket(WorldPacket& data) const { data << uint32(m_rights); if (m_bankMoneyPerDay == GUILD_WITHDRAW_MONEY_UNLIMITED) data << uint32(GUILD_WITHDRAW_MONEY_UNLIMITED); else data << uint32(m_bankMoneyPerDay); for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; ++i) { data << uint32(m_bankTabRightsAndSlots[i].GetRights()); data << uint32(m_bankTabRightsAndSlots[i].GetSlots()); } } void Guild::RankInfo::SetName(std::string const& name) { if (m_name == name) return; m_name = name; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_NAME); stmt->setString(0, m_name); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetRights(uint32 rights) { if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights rights = GR_RIGHT_ALL; if (m_rights == rights) return; m_rights = rights; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_RIGHTS); stmt->setUInt32(0, m_rights); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetBankMoneyPerDay(uint32 money) { if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights money = uint32(GUILD_WITHDRAW_MONEY_UNLIMITED); if (m_bankMoneyPerDay == money) return; m_bankMoneyPerDay = money; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY); stmt->setUInt32(0, money); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetBankTabSlotsAndRights(GuildBankRightsAndSlots rightsAndSlots, bool saveToDB) { if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights rightsAndSlots.SetGuildMasterValues(); GuildBankRightsAndSlots& guildBR = m_bankTabRightsAndSlots[rightsAndSlots.GetTabId()]; guildBR = rightsAndSlots; if (saveToDB) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, guildBR.GetTabId()); stmt->setUInt8 (2, m_rankId); stmt->setUInt8 (3, guildBR.GetRights()); stmt->setUInt32(4, guildBR.GetSlots()); CharacterDatabase.Execute(stmt); } } // BankTab Guild::BankTab::BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId) { memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*)); } void Guild::BankTab::LoadFromDB(Field* fields) { m_name = fields[2].GetString(); m_icon = fields[3].GetString(); m_text = fields[4].GetString(); } bool Guild::BankTab::LoadItemFromDB(Field* fields) { uint8 slotId = fields[13].GetUInt8(); ObjectGuid::LowType itemGuid = fields[14].GetUInt32(); uint32 itemEntry = fields[15].GetUInt32(); if (slotId >= GUILD_BANK_MAX_SLOTS) { TC_LOG_ERROR("guild", "Invalid slot for item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry); return false; } ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry); if (!proto) { TC_LOG_ERROR("guild", "Unknown item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry); return false; } Item* pItem = NewItemOrBag(proto); if (!pItem->LoadFromDB(itemGuid, ObjectGuid::Empty, fields, itemEntry)) { TC_LOG_ERROR("guild", "Item (GUID %u, id: %u) not found in item_instance, deleting from guild bank!", itemGuid, itemEntry); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); CharacterDatabase.Execute(stmt); delete pItem; return false; } pItem->AddToWorld(); m_items[slotId] = pItem; return true; } // Deletes contents of the tab from the world (and from DB if necessary) void Guild::BankTab::Delete(SQLTransaction& trans, bool removeItemsFromDB) { for (uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId) { if (Item* pItem = m_items[slotId]) { pItem->RemoveFromWorld(); if (removeItemsFromDB) pItem->DeleteFromDB(trans); delete pItem; pItem = nullptr; } } } inline void Guild::BankTab::WritePacket(WorldPacket& data) const { uint8 count = 0; size_t pos = data.wpos(); data << uint8(0); for (uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId) if (WriteSlotPacket(data, slotId)) ++count; data.put<uint8>(pos, count); } // Writes information about contents of specified slot into packet. bool Guild::BankTab::WriteSlotPacket(WorldPacket& data, uint8 slotId, bool ignoreEmpty /* = true */) const { Item* pItem = GetItem(slotId); uint32 itemEntry = pItem ? pItem->GetEntry() : 0; if (!itemEntry && ignoreEmpty) return false; data << uint8(slotId); data << uint32(itemEntry); if (itemEntry) { data << uint32(0); // 3.3.0 (0x00018020, 0x00018000) if (uint32 random = pItem->GetItemRandomPropertyId()) { data << uint32(random); // Random item property id data << uint32(pItem->GetItemSuffixFactor()); // SuffixFactor } else data << uint32(0); data << uint32(pItem->GetCount()); // ITEM_FIELD_STACK_COUNT data << uint32(pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT)); // Permanent enchantment data << uint8(abs(pItem->GetSpellCharges())); // Spell charges uint8 enchCount = 0; size_t enchCountPos = data.wpos(); data << uint8(enchCount); // Number of enchantments for (uint32 socketSlot = SOCK_ENCHANTMENT_SLOT; socketSlot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++socketSlot) { if (uint32 enchId = pItem->GetEnchantmentId(EnchantmentSlot(socketSlot))) { data << uint8(socketSlot - SOCK_ENCHANTMENT_SLOT); data << uint32(enchId); ++enchCount; } } data.put<uint8>(enchCountPos, enchCount); } return true; } void Guild::BankTab::WriteInfoPacket(WorldPacket& data) const { data << m_name; data << m_icon; } void Guild::BankTab::SetInfo(std::string const& name, std::string const& icon) { if (m_name == name && m_icon == icon) return; m_name = name; m_icon = icon; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_INFO); stmt->setString(0, m_name); stmt->setString(1, m_icon); stmt->setUInt32(2, m_guildId); stmt->setUInt8 (3, m_tabId); CharacterDatabase.Execute(stmt); } void Guild::BankTab::SetText(std::string const& text) { if (m_text == text) return; m_text = text; utf8truncate(m_text, MAX_GUILD_BANK_TAB_TEXT_LEN); // DB and client size limitation PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT); stmt->setString(0, m_text); stmt->setUInt32(1, m_guildId); stmt->setUInt8 (2, m_tabId); CharacterDatabase.Execute(stmt); } // Sets/removes contents of specified slot. // If pItem == nullptr contents are removed. bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* item) { if (slotId >= GUILD_BANK_MAX_SLOTS) return false; m_items[slotId] = item; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); trans->Append(stmt); if (item) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); stmt->setUInt32(3, item->GetGUID().GetCounter()); trans->Append(stmt); item->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid::Empty); item->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid::Empty); item->FSetState(ITEM_NEW); item->SaveToDB(trans); // Not in inventory and can be saved standalone } return true; } void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const { WorldPacket data(MSG_QUERY_GUILD_BANK_TEXT, 1 + m_text.size() + 1); data << uint8(m_tabId); data << m_text; if (session) { TC_LOG_DEBUG("guild", "MSG_QUERY_GUILD_BANK_TEXT [%s]: Tabid: %u, Text: %s" , session->GetPlayerInfo().c_str(), m_tabId, m_text.c_str()); session->SendPacket(&data); } else { TC_LOG_DEBUG("guild", "MSG_QUERY_GUILD_BANK_TEXT [Broadcast]: Tabid: %u, Text: %s", m_tabId, m_text.c_str()); guild->BroadcastPacket(&data); } } // Member Guild::Member::Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) : m_guildId(guildId), m_guid(guid), m_zoneId(0), m_level(0), m_class(0), m_gender(0), m_flags(GUILDMEMBER_STATUS_NONE), m_logoutTime(GameTime::GetGameTime()), m_accountId(0), m_rankId(rankId) { memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32)); } void Guild::Member::SetStats(Player* player) { m_name = player->GetName(); m_level = player->GetLevel(); m_class = player->GetClass(); m_gender = player->GetNativeGender(); m_zoneId = player->GetZoneId(); m_accountId = player->GetSession()->GetAccountId(); } void Guild::Member::SetStats(std::string const& name, uint8 level, uint8 _class, uint8 gender, uint32 zoneId, uint32 accountId) { m_name = name; m_level = level; m_class = _class; m_gender = gender; m_zoneId = zoneId; m_accountId = accountId; } void Guild::Member::SetPublicNote(std::string const& publicNote) { if (m_publicNote == publicNote) return; m_publicNote = publicNote; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_PNOTE); stmt->setString(0, publicNote); stmt->setUInt32(1, m_guid.GetCounter()); CharacterDatabase.Execute(stmt); } void Guild::Member::SetOfficerNote(std::string const& officerNote) { if (m_officerNote == officerNote) return; m_officerNote = officerNote; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE); stmt->setString(0, officerNote); stmt->setUInt32(1, m_guid.GetCounter()); CharacterDatabase.Execute(stmt); } void Guild::Member::ChangeRank(SQLTransaction& trans, uint8 newRank) { m_rankId = newRank; // Update rank information in player's field, if he is online. if (Player* player = FindPlayer()) player->SetRank(newRank); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_RANK); stmt->setUInt8 (0, newRank); stmt->setUInt32(1, m_guid.GetCounter()); CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::Member::UpdateLogoutTime() { m_logoutTime = GameTime::GetGameTime(); } void Guild::Member::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER); stmt->setUInt32(0, m_guildId); stmt->setUInt32(1, m_guid.GetCounter()); stmt->setUInt8 (2, m_rankId); stmt->setString(3, m_publicNote); stmt->setString(4, m_officerNote); CharacterDatabase.ExecuteOrAppend(trans, stmt); } // Loads member's data from database. // If member has broken fields (level, class) returns false. // In this case member has to be removed from guild. bool Guild::Member::LoadFromDB(Field* fields) { m_publicNote = fields[3].GetString(); m_officerNote = fields[4].GetString(); for (uint8 i = 0; i <= GUILD_BANK_MAX_TABS; ++i) m_bankWithdraw[i] = fields[5 + i].GetUInt32(); SetStats(fields[12].GetString(), fields[13].GetUInt8(), // characters.level fields[14].GetUInt8(), // characters.class fields[15].GetUInt8(), // characters.gender fields[16].GetUInt16(), // characters.zone fields[17].GetUInt32()); // characters.account m_logoutTime = fields[18].GetUInt32(); // characters.logout_time if (!CheckStats()) return false; if (!m_zoneId) { TC_LOG_DEBUG("guild", "%s has broken zone-data", m_guid.ToString().c_str()); m_zoneId = Player::GetZoneIdFromDB(m_guid); } ResetFlags(); return true; } // Validate player fields. Returns false if corrupted fields are found. bool Guild::Member::CheckStats() const { if (m_level < 1) { TC_LOG_ERROR("guild", "%s has a broken data in field `characters`.`level`, deleting him from guild!", m_guid.ToString().c_str()); return false; } if (m_class < CLASS_WARRIOR || m_class >= MAX_CLASSES) { TC_LOG_ERROR("guild", "%s has a broken data in field `characters`.`class`, deleting him from guild!", m_guid.ToString().c_str()); return false; } return true; } void Guild::Member::WritePacket(WorldPacket& data, bool sendOfficerNote) const { data << uint64(m_guid) << uint8(m_flags) << m_name << uint32(m_rankId) << uint8(m_level) << uint8(m_class) << uint8(m_gender) << uint32(m_zoneId); if (!m_flags) data << float(float(GameTime::GetGameTime() - m_logoutTime) / DAY); data << m_publicNote; if (sendOfficerNote) data << m_officerNote; else data << ""; } Player* Guild::Member::FindPlayer() const { return ObjectAccessor::FindPlayer(m_guid); } Player* Guild::Member::FindConnectedPlayer() const { return ObjectAccessor::FindConnectedPlayer(m_guid); } // Decreases amount of money/slots left for today. // If (tabId == GUILD_BANK_MAX_TABS) decrease money amount. // Otherwise decrease remaining items amount for specified tab. void Guild::Member::UpdateBankWithdrawValue(SQLTransaction& trans, uint8 tabId, uint32 amount) { m_bankWithdraw[tabId] += amount; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW); stmt->setUInt32(0, m_guid.GetCounter()); for (uint8 i = 0; i <= GUILD_BANK_MAX_TABS;) { uint32 withdraw = m_bankWithdraw[i++]; stmt->setUInt32(i, withdraw); } CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::Member::ResetValues() { for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId) m_bankWithdraw[tabId] = 0; } // Get amount of money/slots left for today. // If (tabId == GUILD_BANK_MAX_TABS) return money amount. // Otherwise return remaining items amount for specified tab. int32 Guild::Member::GetBankWithdrawValue(uint8 tabId) const { // Guild master has unlimited amount. if (IsRank(GR_GUILDMASTER)) return static_cast<int32>(tabId == GUILD_BANK_MAX_TABS ? GUILD_WITHDRAW_MONEY_UNLIMITED : GUILD_WITHDRAW_SLOT_UNLIMITED); return m_bankWithdraw[tabId]; } // EmblemInfo void EmblemInfo::ReadPacket(WorldPacket& recv) { recv >> m_style >> m_color >> m_borderStyle >> m_borderColor >> m_backgroundColor; } void EmblemInfo::LoadFromDB(Field* fields) { m_style = fields[3].GetUInt8(); m_color = fields[4].GetUInt8(); m_borderStyle = fields[5].GetUInt8(); m_borderColor = fields[6].GetUInt8(); m_backgroundColor = fields[7].GetUInt8(); } void EmblemInfo::WritePacket(WorldPacket& data) const { data << uint32(m_style); data << uint32(m_color); data << uint32(m_borderStyle); data << uint32(m_borderColor); data << uint32(m_backgroundColor); } void EmblemInfo::SaveToDB(ObjectGuid::LowType guildId) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_EMBLEM_INFO); stmt->setUInt32(0, m_style); stmt->setUInt32(1, m_color); stmt->setUInt32(2, m_borderStyle); stmt->setUInt32(3, m_borderColor); stmt->setUInt32(4, m_backgroundColor); stmt->setUInt32(5, guildId); CharacterDatabase.Execute(stmt); } // MoveItemData Guild::MoveItemData::MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player), m_container(container), m_slotId(slotId), m_pItem(nullptr), m_pClonedItem(nullptr) { } Guild::MoveItemData::~MoveItemData() { } bool Guild::MoveItemData::CheckItem(uint32& splitedAmount) { ASSERT(m_pItem); if (splitedAmount > m_pItem->GetCount()) return false; if (splitedAmount == m_pItem->GetCount()) splitedAmount = 0; return true; } bool Guild::MoveItemData::CanStore(Item* pItem, bool swap, bool sendError) { m_vec.clear(); InventoryResult msg = CanStore(pItem, swap); if (sendError && msg != EQUIP_ERR_OK) m_pPlayer->SendEquipError(msg, pItem); return (msg == EQUIP_ERR_OK); } bool Guild::MoveItemData::CloneItem(uint32 count) { ASSERT(m_pItem); m_pClonedItem = m_pItem->CloneItem(count); if (!m_pClonedItem) { m_pPlayer->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, m_pItem); return false; } return true; } void Guild::MoveItemData::LogAction(MoveItemData* pFrom) const { ASSERT(pFrom->GetItem()); sScriptMgr->OnGuildItemMove(m_pGuild, m_pPlayer, pFrom->GetItem(), pFrom->IsBank(), pFrom->GetContainer(), pFrom->GetSlotId(), IsBank(), GetContainer(), GetSlotId()); } inline void Guild::MoveItemData::CopySlots(SlotIds& ids) const { for (auto itr = m_vec.begin(); itr != m_vec.end(); ++itr) ids.insert(uint8(itr->pos)); } // PlayerMoveItemData bool Guild::PlayerMoveItemData::InitItem() { m_pItem = m_pPlayer->GetItemByPos(m_container, m_slotId); if (m_pItem) { // Anti-WPE protection. Do not move non-empty bags to bank. if (m_pItem->IsNotEmptyBag()) { m_pPlayer->SendEquipError(EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS, m_pItem); m_pItem = nullptr; } // Bound items cannot be put into bank. else if (!m_pItem->CanBeTraded()) { m_pPlayer->SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, m_pItem); m_pItem = nullptr; } } return (m_pItem != nullptr); } void Guild::PlayerMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* /*pOther*/, uint32 splitedAmount) { if (splitedAmount) { m_pItem->SetCount(m_pItem->GetCount() - splitedAmount); m_pItem->SetState(ITEM_CHANGED, m_pPlayer); m_pPlayer->SaveInventoryAndGoldToDB(trans); } else { m_pPlayer->MoveItemFromInventory(m_container, m_slotId, true); m_pItem->DeleteFromInventoryDB(trans); m_pItem = nullptr; } } Item* Guild::PlayerMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem) { ASSERT(pItem); m_pPlayer->MoveItemToInventory(m_vec, pItem, true); m_pPlayer->SaveInventoryAndGoldToDB(trans); return pItem; } void Guild::PlayerMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const { ASSERT(pFrom); // Bank -> Char m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_WITHDRAW_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUID().GetCounter(), pFrom->GetItem()->GetEntry(), count); } inline InventoryResult Guild::PlayerMoveItemData::CanStore(Item* pItem, bool swap) { return m_pPlayer->CanStoreItem(m_container, m_slotId, m_vec, pItem, swap); } // BankMoveItemData bool Guild::BankMoveItemData::InitItem() { m_pItem = m_pGuild->_GetItem(m_container, m_slotId); return (m_pItem != nullptr); } bool Guild::BankMoveItemData::HasStoreRights(MoveItemData* pOther) const { ASSERT(pOther); // Do not check rights if item is being swapped within the same bank tab if (pOther->IsBank() && pOther->GetContainer() == m_container) return true; return m_pGuild->_MemberHasTabRights(m_pPlayer->GetGUID(), m_container, GUILD_BANK_RIGHT_DEPOSIT_ITEM); } bool Guild::BankMoveItemData::HasWithdrawRights(MoveItemData* pOther) const { ASSERT(pOther); // Do not check rights if item is being swapped within the same bank tab if (pOther->IsBank() && pOther->GetContainer() == m_container) return true; int32 slots = 0; if (Member const* member = m_pGuild->GetMember(m_pPlayer->GetGUID())) slots = m_pGuild->_GetMemberRemainingSlots(member, m_container); return slots != 0; } void Guild::BankMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* pOther, uint32 splitedAmount) { ASSERT(m_pItem); if (splitedAmount) { m_pItem->SetCount(m_pItem->GetCount() - splitedAmount); m_pItem->FSetState(ITEM_CHANGED); m_pItem->SaveToDB(trans); } else { m_pGuild->_RemoveItem(trans, m_container, m_slotId); m_pItem = nullptr; } // Decrease amount of player's remaining items (if item is moved to different tab or to player) if (!pOther->IsBank() || pOther->GetContainer() != m_container) m_pGuild->_UpdateMemberWithdrawSlots(trans, m_pPlayer->GetGUID(), m_container); } Item* Guild::BankMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem) { if (!pItem) return nullptr; BankTab* pTab = m_pGuild->GetBankTab(m_container); if (!pTab) return nullptr; Item* pLastItem = pItem; for (auto itr = m_vec.begin(); itr != m_vec.end(); ) { ItemPosCount pos(*itr); ++itr; ASSERT(pItem); TC_LOG_DEBUG("guild", "GUILD STORAGE: StoreItem tab = %u, slot = %u, item = %u, count = %u", m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); pLastItem = _StoreItem(trans, pTab, pItem, pos, itr != m_vec.end()); } return pLastItem; } void Guild::BankMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const { ASSERT(pFrom->GetItem()); if (pFrom->IsBank()) // Bank -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_MOVE_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUID().GetCounter(), pFrom->GetItem()->GetEntry(), count, m_container); else // Char -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_ITEM, m_container, m_pPlayer->GetGUID().GetCounter(), pFrom->GetItem()->GetEntry(), count); } void Guild::BankMoveItemData::LogAction(MoveItemData* pFrom) const { MoveItemData::LogAction(pFrom); if (!pFrom->IsBank() && m_pPlayer->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) /// @todo Move this to scripts { sLog->outCommand(m_pPlayer->GetSession()->GetAccountId(), "GM %s (Guid: %u) (Account: %u) deposit item: %s (Entry: %d Count: %u) to guild bank named: %s (Guild ID: %u)", m_pPlayer->GetName().c_str(), m_pPlayer->GetGUID().GetCounter(), m_pPlayer->GetSession()->GetAccountId(), pFrom->GetItem()->GetTemplate()->Name1.c_str(), pFrom->GetItem()->GetEntry(), pFrom->GetItem()->GetCount(), m_pGuild->GetName().c_str(), m_pGuild->GetId()); } } Item* Guild::BankMoveItemData::_StoreItem(SQLTransaction& trans, BankTab* pTab, Item* pItem, ItemPosCount& pos, bool clone) const { uint8 slotId = uint8(pos.pos); uint32 count = pos.count; if (Item* pItemDest = pTab->GetItem(slotId)) { pItemDest->SetCount(pItemDest->GetCount() + count); pItemDest->FSetState(ITEM_CHANGED); pItemDest->SaveToDB(trans); if (!clone) { pItem->RemoveFromWorld(); pItem->DeleteFromDB(trans); delete pItem; } return pItemDest; } if (clone) pItem = pItem->CloneItem(count); else pItem->SetCount(count); if (pItem && pTab->SetItem(trans, slotId, pItem)) return pItem; return nullptr; } // Tries to reserve space for source item. // If item in destination slot exists it must be the item of the same entry // and stack must have enough space to take at least one item. // Returns false if destination item specified and it cannot be used to reserve space. bool Guild::BankMoveItemData::_ReserveSpace(uint8 slotId, Item* pItem, Item* pItemDest, uint32& count) { uint32 requiredSpace = pItem->GetMaxStackCount(); if (pItemDest) { // Make sure source and destination items match and destination item has space for more stacks. if (pItemDest->GetEntry() != pItem->GetEntry() || pItemDest->GetCount() >= pItem->GetMaxStackCount()) return false; requiredSpace -= pItemDest->GetCount(); } // Let's not be greedy, reserve only required space requiredSpace = std::min(requiredSpace, count); // Reserve space ItemPosCount pos(slotId, requiredSpace); if (!pos.isContainedIn(m_vec)) { m_vec.push_back(pos); count -= requiredSpace; } return true; } void Guild::BankMoveItemData::CanStoreItemInTab(Item* pItem, uint8 skipSlotId, bool merge, uint32& count) { for (uint8 slotId = 0; (slotId < GUILD_BANK_MAX_SLOTS) && (count > 0); ++slotId) { // Skip slot already processed in CanStore (when destination slot was specified) if (slotId == skipSlotId) continue; Item* pItemDest = m_pGuild->_GetItem(m_container, slotId); if (pItemDest == pItem) pItemDest = nullptr; // If merge skip empty, if not merge skip non-empty if ((pItemDest != nullptr) != merge) continue; _ReserveSpace(slotId, pItem, pItemDest, count); } } InventoryResult Guild::BankMoveItemData::CanStore(Item* pItem, bool swap) { TC_LOG_DEBUG("guild", "GUILD STORAGE: CanStore() tab = %u, slot = %u, item = %u, count = %u", m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); uint32 count = pItem->GetCount(); // Soulbound items cannot be moved if (pItem->IsSoulBound()) return EQUIP_ERR_CANT_DROP_SOULBOUND; // Make sure destination bank tab exists if (m_container >= m_pGuild->_GetPurchasedTabsSize()) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // Slot explicitely specified. Check it. if (m_slotId != NULL_SLOT) { Item* pItemDest = m_pGuild->_GetItem(m_container, m_slotId); // Ignore swapped item (this slot will be empty after move) if ((pItemDest == pItem) || swap) pItemDest = nullptr; if (!_ReserveSpace(m_slotId, pItem, pItemDest, count)) return EQUIP_ERR_ITEM_CANT_STACK; if (count == 0) return EQUIP_ERR_OK; } // Slot was not specified or it has not enough space for all the items in stack // Search for stacks to merge with if (pItem->GetMaxStackCount() > 1) { CanStoreItemInTab(pItem, m_slotId, true, count); if (count == 0) return EQUIP_ERR_OK; } // Search free slot for item CanStoreItemInTab(pItem, m_slotId, false, count); if (count == 0) return EQUIP_ERR_OK; return EQUIP_ERR_BANK_FULL; } // Guild Guild::Guild(): m_id(0), m_leaderGuid(), m_createdDate(0), m_accountsNumber(0), m_bankMoney(0), m_eventLog(nullptr) { memset(&m_bankEventLog, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(LogHolder*)); } Guild::~Guild() { SQLTransaction temp(nullptr); _DeleteBankItems(temp); // Cleanup delete m_eventLog; m_eventLog = nullptr; for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId) { delete m_bankEventLog[tabId]; m_bankEventLog[tabId] = nullptr; } for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) { delete itr->second; itr->second = nullptr; } } // Creates new guild with default data and saves it to database. bool Guild::Create(Player* pLeader, std::string const& name) { // Check if guild with such name already exists if (sGuildMgr->GetGuildByName(name)) return false; WorldSession* pLeaderSession = pLeader->GetSession(); if (!pLeaderSession) return false; m_id = sGuildMgr->GenerateGuildId(); m_leaderGuid = pLeader->GetGUID(); m_name = name; m_info = ""; m_motd = "No message set."; m_bankMoney = 0; m_createdDate = GameTime::GetGameTime(); _CreateLogHolders(); TC_LOG_DEBUG("guild", "GUILD: creating guild [%s] for leader %s (%u)", name.c_str(), pLeader->GetName().c_str(), m_leaderGuid.GetCounter()); SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBERS); stmt->setUInt32(0, m_id); trans->Append(stmt); uint8 index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD); stmt->setUInt32( index, m_id); stmt->setString(++index, name); stmt->setUInt32(++index, m_leaderGuid.GetCounter()); stmt->setString(++index, m_info); stmt->setString(++index, m_motd); stmt->setUInt64(++index, uint32(m_createdDate)); stmt->setUInt32(++index, m_emblemInfo.GetStyle()); stmt->setUInt32(++index, m_emblemInfo.GetColor()); stmt->setUInt32(++index, m_emblemInfo.GetBorderStyle()); stmt->setUInt32(++index, m_emblemInfo.GetBorderColor()); stmt->setUInt32(++index, m_emblemInfo.GetBackgroundColor()); stmt->setUInt64(++index, m_bankMoney); trans->Append(stmt); _CreateDefaultGuildRanks(trans, pLeaderSession->GetSessionDbLocaleIndex()); // Create default ranks bool ret = AddMember(trans, m_leaderGuid, GR_GUILDMASTER); // Add guildmaster CharacterDatabase.CommitTransaction(trans); if (ret) sScriptMgr->OnGuildCreate(this, pLeader, name); return ret; } // Disbands guild and deletes all related data from database void Guild::Disband() { // Call scripts before guild data removed from database sScriptMgr->OnGuildDisband(this); _BroadcastEvent(GE_DISBANDED, ObjectGuid::Empty); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // Remove all members while (!m_members.empty()) { auto itr = m_members.begin(); DeleteMember(trans, itr->second->GetGUID(), true); } PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TABS); stmt->setUInt32(0, m_id); trans->Append(stmt); // Free bank tab used memory and delete items stored in them _DeleteBankItems(trans, true); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEMS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOGS); stmt->setUInt32(0, m_id); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); sGuildMgr->RemoveGuild(m_id); } void Guild::UpdateMemberData(Player* player, uint8 dataid, uint32 value) { if (Member* member = GetMember(player->GetGUID())) { switch (dataid) { case GUILD_MEMBER_DATA_ZONEID: member->SetZoneID(value); break; case GUILD_MEMBER_DATA_LEVEL: member->SetLevel(value); break; default: TC_LOG_ERROR("guild", "Guild::UpdateMemberData: Called with incorrect DATAID %u (value %u)", dataid, value); return; } //HandleRoster(); } } void Guild::OnPlayerStatusChange(Player* player, uint32 flag, bool state) { if (Member* member = GetMember(player->GetGUID())) { if (state) member->AddFlag(flag); else member->RemFlag(flag); } } bool Guild::SetName(std::string const& name) { if (m_name == name || name.empty() || name.length() > 24 || sObjectMgr->IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) return false; m_name = name; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_NAME); stmt->setString(0, m_name); stmt->setUInt32(1, GetId()); CharacterDatabase.Execute(stmt); return true; } void Guild::HandleRoster(WorldSession* session) { // Guess size WorldPacket data(SMSG_GUILD_ROSTER, (4 + m_motd.length() + 1 + m_info.length() + 1 + 4 + _GetRanksSize() * (4 + 4 + GUILD_BANK_MAX_TABS * (4 + 4)) + m_members.size() * 50)); data << uint32(m_members.size()); data << m_motd; data << m_info; data << uint32(_GetRanksSize()); for (auto ritr = m_ranks.begin(); ritr != m_ranks.end(); ++ritr) ritr->WritePacket(data); for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) itr->second->WritePacket(data, _HasRankRight(session->GetPlayer(), GR_RIGHT_VIEWOFFNOTE)); TC_LOG_DEBUG("guild", "SMSG_GUILD_ROSTER [%s]", session->GetPlayerInfo().c_str()); session->SendPacket(&data); } void Guild::HandleQuery(WorldSession* session) { WorldPacket data(SMSG_GUILD_QUERY_RESPONSE, 8 * 32 + 200); // Guess size data << uint32(m_id); data << m_name; // Rank name for (uint8 i = 0; i < GUILD_RANKS_MAX_COUNT; ++i) // Always show 10 ranks { if (i < _GetRanksSize()) data << m_ranks[i].GetName(); else data << uint8(0); // Empty string } m_emblemInfo.WritePacket(data); data << uint32(_GetRanksSize()); // Number of ranks used session->SendPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_QUERY_RESPONSE [%s]", session->GetPlayerInfo().c_str()); } void Guild::HandleSetMOTD(WorldSession* session, std::string const& motd) { if (m_motd == motd) return; // Player must have rights to set MOTD if (!_HasRankRight(session->GetPlayer(), GR_RIGHT_SETMOTD)) SendCommandResult(session, GUILD_COMMAND_EDIT_MOTD, ERR_GUILD_PERMISSIONS); else { m_motd = motd; sScriptMgr->OnGuildMOTDChanged(this, motd); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MOTD); stmt->setString(0, motd); stmt->setUInt32(1, m_id); CharacterDatabase.Execute(stmt); _BroadcastEvent(GE_MOTD, ObjectGuid::Empty, motd.c_str()); } } void Guild::HandleSetInfo(WorldSession* session, std::string const& info) { if (m_info == info) return; // Player must have rights to set guild's info if (_HasRankRight(session->GetPlayer(), GR_RIGHT_MODIFY_GUILD_INFO)) { m_info = info; sScriptMgr->OnGuildInfoChanged(this, info); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_INFO); stmt->setString(0, info); stmt->setUInt32(1, m_id); CharacterDatabase.Execute(stmt); } } void Guild::HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo) { Player* player = session->GetPlayer(); if (!_IsLeader(player)) SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTGUILDMASTER); // "Only guild leaders can create emblems." else if (!player->HasEnoughMoney(EMBLEM_PRICE)) SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTENOUGHMONEY); // "You can't afford to do that." else { player->ModifyMoney(-int32(EMBLEM_PRICE)); m_emblemInfo = emblemInfo; m_emblemInfo.SaveToDB(m_id); SendSaveEmblemResult(session, ERR_GUILDEMBLEM_SUCCESS); // "Guild Emblem saved." HandleQuery(session); } } void Guild::HandleSetLeader(WorldSession* session, std::string const& name) { Player* player = session->GetPlayer(); // Only leader can assign new leader if (!_IsLeader(player)) SendCommandResult(session, GUILD_COMMAND_CHANGE_LEADER, ERR_GUILD_PERMISSIONS); // Old leader must be a member of guild else if (Member* pOldLeader = GetMember(player->GetGUID())) { // New leader must be a member of guild if (Member* pNewLeader = GetMember(name)) { _SetLeaderGUID(pNewLeader); SQLTransaction trans(nullptr); pOldLeader->ChangeRank(trans, GR_OFFICER); _BroadcastEvent(GE_LEADER_CHANGED, ObjectGuid::Empty, player->GetName().c_str(), name.c_str()); } } } void Guild::HandleSetBankTabInfo(WorldSession* session, uint8 tabId, std::string const& name, std::string const& icon) { BankTab* tab = GetBankTab(tabId); if (!tab) { TC_LOG_ERROR("guild", "Guild::HandleSetBankTabInfo: Player %s trying to change bank tab info from unexisting tab %d.", session->GetPlayerInfo().c_str(), tabId); return; } tab->SetInfo(name, icon); _BroadcastEvent(GE_BANK_TAB_UPDATED, ObjectGuid::Empty, std::to_string(tabId).c_str(), name.c_str(), icon.c_str()); } void Guild::HandleSetMemberNote(WorldSession* session, std::string const& name, std::string const& note, bool officer) { // Player must have rights to set public/officer note if (!_HasRankRight(session->GetPlayer(), officer ? GR_RIGHT_EOFFNOTE : GR_RIGHT_EPNOTE)) SendCommandResult(session, GUILD_COMMAND_PUBLIC_NOTE, ERR_GUILD_PERMISSIONS); else if (Member* member = GetMember(name)) { if (officer) member->SetOfficerNote(note); else member->SetPublicNote(note); HandleRoster(session); } } void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec const& rightsAndSlots) { // Only leader can modify ranks if (!_IsLeader(session->GetPlayer())) SendCommandResult(session, GUILD_COMMAND_CHANGE_RANK, ERR_GUILD_PERMISSIONS); else if (RankInfo* rankInfo = GetRankInfo(rankId)) { TC_LOG_DEBUG("guild", "Changed RankName to '%s', rights to 0x%08X", name.c_str(), rights); rankInfo->SetName(name); rankInfo->SetRights(rights); _SetRankBankMoneyPerDay(rankId, moneyPerDay); for (auto itr = rightsAndSlots.begin(); itr != rightsAndSlots.end(); ++itr) _SetRankBankTabRightsAndSlots(rankId, *itr); _BroadcastEvent(GE_RANK_UPDATED, ObjectGuid::Empty, std::to_string(rankId).c_str(), name.c_str()); } } void Guild::HandleBuyBankTab(WorldSession* session, uint8 tabId) { Player* player = session->GetPlayer(); if (!player) return; Member const* member = GetMember(player->GetGUID()); if (!member) return; if (_GetPurchasedTabsSize() >= GUILD_BANK_MAX_TABS) return; if (tabId != _GetPurchasedTabsSize()) return; if (tabId >= GUILD_BANK_MAX_TABS) return; uint32 tabCost = GetGuildBankTabPrice(tabId) * GOLD; if (!player->HasEnoughMoney(tabCost)) // Should not happen, this is checked by client return; player->ModifyMoney(-int32(tabCost)); _CreateNewBankTab(); _BroadcastEvent(GE_BANK_TAB_PURCHASED, ObjectGuid::Empty); SendPermissions(session); /// Hack to force client to update permissions } void Guild::HandleInviteMember(WorldSession* session, std::string const& name) { Player* pInvitee = ObjectAccessor::FindPlayerByName(name); if (!pInvitee) { SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_PLAYER_NOT_FOUND_S, name); return; } Player* player = session->GetPlayer(); // Do not show invitations from ignored players if (pInvitee->GetSocial()->HasIgnore(player->GetGUID())) return; if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && pInvitee->GetTeam() != player->GetTeam()) { SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_NOT_ALLIED, name); return; } // Invited player cannot be in another guild if (pInvitee->GetGuildId()) { SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_ALREADY_IN_GUILD_S, name); return; } // Invited player cannot be invited if (pInvitee->GetGuildIdInvited()) { SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_ALREADY_INVITED_TO_GUILD_S, name); return; } // Inviting player must have rights to invite if (!_HasRankRight(player, GR_RIGHT_INVITE)) { SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_PERMISSIONS); return; } SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_COMMAND_SUCCESS, name); TC_LOG_DEBUG("guild", "Player %s invited %s to join his Guild", player->GetName().c_str(), name.c_str()); pInvitee->SetGuildIdInvited(m_id); _LogEvent(GUILD_EVENT_LOG_INVITE_PLAYER, player->GetGUID().GetCounter(), pInvitee->GetGUID().GetCounter()); WorldPacket data(SMSG_GUILD_INVITE, 8 + 10); // Guess size data << player->GetName(); data << m_name; pInvitee->SendDirectMessage(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str()); } void Guild::HandleAcceptMember(WorldSession* session) { Player* player = session->GetPlayer(); if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && player->GetTeam() != sCharacterCache->GetCharacterTeamByGuid(GetLeaderGUID())) return; SQLTransaction trans(nullptr); AddMember(trans, player->GetGUID()); } void Guild::HandleLeaveMember(WorldSession* session) { Player* player = session->GetPlayer(); bool disband = false; // If leader is leaving if (_IsLeader(player)) { if (m_members.size() > 1) // Leader cannot leave if he is not the last member SendCommandResult(session, GUILD_COMMAND_QUIT, ERR_GUILD_LEADER_LEAVE); else { // Guild is disbanded if leader leaves. Disband(); disband = true; } } else { SQLTransaction trans(nullptr); DeleteMember(trans, player->GetGUID(), false, false); _LogEvent(GUILD_EVENT_LOG_LEAVE_GUILD, player->GetGUID().GetCounter()); _BroadcastEvent(GE_LEFT, player->GetGUID(), player->GetName().c_str()); SendCommandResult(session, GUILD_COMMAND_QUIT, ERR_GUILD_COMMAND_SUCCESS, m_name); } sCalendarMgr->RemovePlayerGuildEventsAndSignups(player->GetGUID(), GetId()); if (disband) delete this; } void Guild::HandleRemoveMember(WorldSession* session, std::string const& name) { Player* player = session->GetPlayer(); // Player must have rights to remove members if (!_HasRankRight(player, GR_RIGHT_REMOVE)) SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_PERMISSIONS); else if (Member* member = GetMember(name)) { // Guild masters cannot be removed if (member->IsRank(GR_GUILDMASTER)) SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_LEADER_LEAVE); // Do not allow to remove player with the same rank or higher else { Member const* memberMe = GetMember(player->GetGUID()); if (!memberMe || member->IsRankNotLower(memberMe->GetRankId())) SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_RANK_TOO_HIGH_S, name); else { ObjectGuid guid = member->GetGUID(); // After call to DeleteMember pointer to member becomes invalid SQLTransaction trans(nullptr); DeleteMember(trans, guid, false, true); _LogEvent(GUILD_EVENT_LOG_UNINVITE_PLAYER, player->GetGUID().GetCounter(), guid.GetCounter()); _BroadcastEvent(GE_REMOVED, ObjectGuid::Empty, name.c_str(), player->GetName().c_str()); } } } } void Guild::HandleUpdateMemberRank(WorldSession* session, std::string const& name, bool demote) { Player* player = session->GetPlayer(); GuildCommandType type = demote ? GUILD_COMMAND_DEMOTE : GUILD_COMMAND_PROMOTE; // Player must have rights to promote if (!_HasRankRight(player, demote ? GR_RIGHT_DEMOTE : GR_RIGHT_PROMOTE)) SendCommandResult(session, type, ERR_GUILD_PERMISSIONS); // Promoted player must be a member of guild else if (Member* member = GetMember(name)) { // Player cannot promote himself if (member->IsSamePlayer(player->GetGUID())) { SendCommandResult(session, type, ERR_GUILD_NAME_INVALID); return; } Member const* memberMe = GetMember(player->GetGUID()); ASSERT(memberMe); uint8 rankId = memberMe->GetRankId(); if (demote) { // Player can demote only lower rank members if (member->IsRankNotLower(rankId)) { SendCommandResult(session, type, ERR_GUILD_RANK_TOO_HIGH_S, name); return; } // Lowest rank cannot be demoted if (member->GetRankId() >= _GetLowestRankId()) { SendCommandResult(session, type, ERR_GUILD_RANK_TOO_LOW_S, name); return; } } else { // Allow to promote only to lower rank than member's rank // member->GetRankId() + 1 is the highest rank that current player can promote to if (member->IsRankNotLower(rankId + 1)) { SendCommandResult(session, type, ERR_GUILD_RANK_TOO_HIGH_S, name); return; } } uint32 newRankId = member->GetRankId() + (demote ? 1 : -1); SQLTransaction trans(nullptr); member->ChangeRank(trans, newRankId); _LogEvent(demote ? GUILD_EVENT_LOG_DEMOTE_PLAYER : GUILD_EVENT_LOG_PROMOTE_PLAYER, player->GetGUID().GetCounter(), member->GetGUID().GetCounter(), newRankId); _BroadcastEvent(demote ? GE_DEMOTION : GE_PROMOTION, ObjectGuid::Empty, player->GetName().c_str(), name.c_str(), _GetRankName(newRankId).c_str()); } } void Guild::HandleAddNewRank(WorldSession* session, std::string const& name) { uint8 size = _GetRanksSize(); if (size >= GUILD_RANKS_MAX_COUNT) return; // Only leader can add new rank if (_IsLeader(session->GetPlayer())) { SQLTransaction trans(nullptr); if (_CreateRank(trans, name, GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK)) _BroadcastEvent(GE_RANK_UPDATED, ObjectGuid::Empty, std::to_string(size).c_str(), name.c_str()); } } void Guild::HandleRemoveLowestRank(WorldSession* session) { HandleRemoveRank(session, _GetLowestRankId()); } void Guild::HandleRemoveRank(WorldSession* session, uint8 rankId) { // Cannot remove rank if total count is minimum allowed by the client or is not leader if (_GetRanksSize() <= GUILD_RANKS_MIN_COUNT || rankId >= _GetRanksSize() || !_IsLeader(session->GetPlayer())) return; // Delete bank rights for rank PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK); stmt->setUInt32(0, m_id); stmt->setUInt8(1, rankId); CharacterDatabase.Execute(stmt); // Delete rank stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_LOWEST_RANK); stmt->setUInt32(0, m_id); stmt->setUInt8(1, rankId); CharacterDatabase.Execute(stmt); m_ranks.pop_back(); _BroadcastEvent(GE_RANK_DELETED, ObjectGuid::Empty, std::to_string(rankId).c_str()); } void Guild::HandleMemberDepositMoney(WorldSession* session, uint32 amount) { Player* player = session->GetPlayer(); // Call script after validation and before money transfer. sScriptMgr->OnGuildMemberDepositMoney(this, player, amount); SQLTransaction trans = CharacterDatabase.BeginTransaction(); _ModifyBankMoney(trans, amount, true); player->ModifyMoney(-int32(amount)); player->SaveGoldToDB(trans); _LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_MONEY, uint8(0), player->GetGUID().GetCounter(), amount); CharacterDatabase.CommitTransaction(trans); std::string aux = ByteArrayToHexStr(reinterpret_cast<uint8*>(&m_bankMoney), 8, true); _BroadcastEvent(GE_BANK_MONEY_SET, ObjectGuid::Empty, aux.c_str()); if (player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) { sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) deposit money (Amount: %u) to guild bank (Guild ID %u)", player->GetName().c_str(), player->GetSession()->GetAccountId(), amount, m_id); } } bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool repair) { //clamp amount to MAX_MONEY_AMOUNT, Players can't hold more than that anyway amount = std::min(amount, MAX_MONEY_AMOUNT); if (m_bankMoney < amount) // Not enough money in bank return false; Player* player = session->GetPlayer(); Member* member = GetMember(player->GetGUID()); if (!member) return false; if (uint32(_GetMemberRemainingMoney(member)) < amount) // Check if we have enough slot/money today return false; // Call script after validation and before money transfer. sScriptMgr->OnGuildMemberWitdrawMoney(this, player, amount, repair); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // Add money to player (if required) if (!repair) { if (!player->ModifyMoney(amount)) return false; player->SaveGoldToDB(trans); } // Update remaining money amount member->UpdateBankWithdrawValue(trans, GUILD_BANK_MAX_TABS, amount); // Remove money from bank _ModifyBankMoney(trans, amount, false); // Log guild bank event _LogBankEvent(trans, repair ? GUILD_BANK_LOG_REPAIR_MONEY : GUILD_BANK_LOG_WITHDRAW_MONEY, uint8(0), player->GetGUID().GetCounter(), amount); CharacterDatabase.CommitTransaction(trans); std::string aux = ByteArrayToHexStr(reinterpret_cast<uint8*>(&m_bankMoney), 8, true); _BroadcastEvent(GE_BANK_MONEY_SET, ObjectGuid::Empty, aux.c_str()); return true; } void Guild::HandleMemberLogout(WorldSession* session) { Player* player = session->GetPlayer(); if (Member* member = GetMember(player->GetGUID())) { member->SetStats(player); member->UpdateLogoutTime(); member->ResetFlags(); } _BroadcastEvent(GE_SIGNED_OFF, player->GetGUID(), player->GetName().c_str()); } void Guild::HandleDisband(WorldSession* session) { // Only leader can disband guild if (_IsLeader(session->GetPlayer())) { Disband(); TC_LOG_DEBUG("guild", "Guild Successfully Disbanded"); delete this; } } // Send data to client void Guild::SendInfo(WorldSession* session) const { WorldPacket data(SMSG_GUILD_INFO, m_name.size() + 4 + 4 + 4); data << m_name; data.AppendPackedTime(m_createdDate); // 3.x (prev. year + month + day) data << uint32(m_members.size()); // Number of members data << m_accountsNumber; // Number of accounts session->SendPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_INFO [%s]", session->GetPlayerInfo().c_str()); } void Guild::SendEventLog(WorldSession* session) const { WorldPacket data(MSG_GUILD_EVENT_LOG_QUERY, 1 + m_eventLog->GetSize() * (1 + 8 + 4)); m_eventLog->WritePacket(data); session->SendPacket(&data); TC_LOG_DEBUG("guild", "MSG_GUILD_EVENT_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); } void Guild::SendBankLog(WorldSession* session, uint8 tabId) const { // GUILD_BANK_MAX_TABS send by client for money log if (tabId < _GetPurchasedTabsSize() || tabId == GUILD_BANK_MAX_TABS) { LogHolder const* pLog = m_bankEventLog[tabId]; WorldPacket data(MSG_GUILD_BANK_LOG_QUERY, pLog->GetSize() * (4 * 4 + 1) + 1 + 1); data << uint8(tabId); pLog->WritePacket(data); session->SendPacket(&data); TC_LOG_DEBUG("guild", "MSG_GUILD_BANK_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); } } void Guild::SendBankTabData(WorldSession* session, uint8 tabId) const { if (tabId < _GetPurchasedTabsSize()) _SendBankContent(session, tabId); } void Guild::SendBankTabsInfo(WorldSession* session, bool sendAllSlots /*= false*/) const { _SendBankList(session, 0, sendAllSlots); } void Guild::SendBankTabText(WorldSession* session, uint8 tabId) const { if (BankTab const* tab = GetBankTab(tabId)) tab->SendText(this, session); } void Guild::SendPermissions(WorldSession* session) const { Member const* member = GetMember(session->GetPlayer()->GetGUID()); if (!member) return; uint8 rankId = member->GetRankId(); WorldPacket data(MSG_GUILD_PERMISSIONS, 4 * 15 + 1); data << uint32(rankId); data << uint32(_GetRankRights(rankId)); data << uint32(_GetMemberRemainingMoney(member)); data << uint8(_GetPurchasedTabsSize()); for (uint8 tabId = 0; tabId < GUILD_BANK_MAX_TABS; ++tabId) { data << uint32(_GetRankBankTabRights(rankId, tabId)); data << uint32(_GetMemberRemainingSlots(member, tabId)); } session->SendPacket(&data); TC_LOG_DEBUG("guild", "MSG_GUILD_PERMISSIONS [%s] Rank: %u", session->GetPlayerInfo().c_str(), rankId); } void Guild::SendMoneyInfo(WorldSession* session) const { Member const* member = GetMember(session->GetPlayer()->GetGUID()); if (!member) return; int32 amount = _GetMemberRemainingMoney(member); WorldPacket data(MSG_GUILD_BANK_MONEY_WITHDRAWN, 4); data << int32(amount); session->SendPacket(&data); TC_LOG_DEBUG("guild", "MSG_GUILD_BANK_MONEY_WITHDRAWN [%s] Money: %u", session->GetPlayerInfo().c_str(), amount); } void Guild::SendLoginInfo(WorldSession* session) { WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + m_motd.size() + 1); data << uint8(GE_MOTD); data << uint8(1); data << m_motd; session->SendPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_EVENT [%s] MOTD", session->GetPlayerInfo().c_str()); SendBankTabsInfo(session); Player* player = session->GetPlayer(); HandleRoster(session); _BroadcastEvent(GE_SIGNED_ON, player->GetGUID(), player->GetName().c_str()); if (Member* member = GetMember(player->GetGUID())) { member->SetStats(player); member->AddFlag(GUILDMEMBER_STATUS_ONLINE); } } // Loading methods bool Guild::LoadFromDB(Field* fields) { m_id = fields[0].GetUInt32(); m_name = fields[1].GetString(); m_leaderGuid = ObjectGuid(HighGuid::Player, fields[2].GetUInt32()); m_emblemInfo.LoadFromDB(fields); m_info = fields[8].GetString(); m_motd = fields[9].GetString(); m_createdDate = time_t(fields[10].GetUInt32()); m_bankMoney = fields[11].GetUInt64(); uint8 purchasedTabs = uint8(fields[12].GetUInt64()); if (purchasedTabs > GUILD_BANK_MAX_TABS) purchasedTabs = GUILD_BANK_MAX_TABS; m_bankTabs.resize(purchasedTabs); for (uint8 i = 0; i < purchasedTabs; ++i) m_bankTabs[i] = new BankTab(m_id, i); _CreateLogHolders(); return true; } void Guild::LoadRankFromDB(Field* fields) { RankInfo rankInfo(m_id); rankInfo.LoadFromDB(fields); m_ranks.push_back(rankInfo); } bool Guild::LoadMemberFromDB(Field* fields) { ObjectGuid::LowType lowguid = fields[1].GetUInt32(); ObjectGuid playerGuid(HighGuid::Player, lowguid); Member* member = new Member(m_id, playerGuid, fields[2].GetUInt8()); if (!member->LoadFromDB(fields)) { SQLTransaction trans(nullptr); _DeleteMemberFromDB(trans, lowguid); delete member; return false; } sCharacterCache->UpdateCharacterGuildId(playerGuid, GetId()); m_members[lowguid] = member; return true; } void Guild::LoadBankRightFromDB(Field* fields) { // tabId rights slots GuildBankRightsAndSlots rightsAndSlots(fields[1].GetUInt8(), fields[3].GetUInt8(), fields[4].GetUInt32()); // rankId _SetRankBankTabRightsAndSlots(fields[2].GetUInt8(), rightsAndSlots, false); } bool Guild::LoadEventLogFromDB(Field* fields) { if (m_eventLog->CanInsert()) { m_eventLog->LoadEvent(new EventLogEntry( m_id, // guild id fields[1].GetUInt32(), // guid time_t(fields[6].GetUInt32()), // timestamp GuildEventLogTypes(fields[2].GetUInt8()), // event type fields[3].GetUInt32(), // player guid 1 fields[4].GetUInt32(), // player guid 2 fields[5].GetUInt8())); // rank return true; } return false; } bool Guild::LoadBankEventLogFromDB(Field* fields) { uint8 dbTabId = fields[1].GetUInt8(); bool isMoneyTab = (dbTabId == GUILD_BANK_MONEY_LOGS_TAB); if (dbTabId < _GetPurchasedTabsSize() || isMoneyTab) { uint8 tabId = isMoneyTab ? uint8(GUILD_BANK_MAX_TABS) : dbTabId; LogHolder* pLog = m_bankEventLog[tabId]; if (pLog->CanInsert()) { ObjectGuid::LowType guid = fields[2].GetUInt32(); GuildBankEventLogTypes eventType = GuildBankEventLogTypes(fields[3].GetUInt8()); if (BankEventLogEntry::IsMoneyEvent(eventType)) { if (!isMoneyTab) { TC_LOG_ERROR("guild", "GuildBankEventLog ERROR: MoneyEvent(LogGuid: %u, Guild: %u) does not belong to money tab (%u), ignoring...", guid, m_id, dbTabId); return false; } } else if (isMoneyTab) { TC_LOG_ERROR("guild", "GuildBankEventLog ERROR: non-money event (LogGuid: %u, Guild: %u) belongs to money tab, ignoring...", guid, m_id); return false; } pLog->LoadEvent(new BankEventLogEntry( m_id, // guild id guid, // guid time_t(fields[8].GetUInt32()), // timestamp dbTabId, // tab id eventType, // event type fields[4].GetUInt32(), // player guid fields[5].GetUInt32(), // item or money fields[6].GetUInt16(), // itam stack count fields[7].GetUInt8())); // dest tab id } } return true; } void Guild::LoadBankTabFromDB(Field* fields) { uint8 tabId = fields[1].GetUInt8(); if (tabId >= _GetPurchasedTabsSize()) TC_LOG_ERROR("guild", "Invalid tab (tabId: %u) in guild bank, skipped.", tabId); else m_bankTabs[tabId]->LoadFromDB(fields); } bool Guild::LoadBankItemFromDB(Field* fields) { uint8 tabId = fields[12].GetUInt8(); if (tabId >= _GetPurchasedTabsSize()) { TC_LOG_ERROR("guild", "Invalid tab for item (GUID: %u, id: #%u) in guild bank, skipped.", fields[14].GetUInt32(), fields[15].GetUInt32()); return false; } return m_bankTabs[tabId]->LoadItemFromDB(fields); } // Validates guild data loaded from database. Returns false if guild should be deleted. bool Guild::Validate() { // Validate ranks data // GUILD RANKS represent a sequence starting from 0 = GUILD_MASTER (ALL PRIVILEGES) to max 9 (lowest privileges). // The lower rank id is considered higher rank - so promotion does rank-- and demotion does rank++ // Between ranks in sequence cannot be gaps - so 0, 1, 2, 4 is impossible // Min ranks count is 5 and max is 10. bool broken_ranks = false; uint8 ranks = _GetRanksSize(); SQLTransaction trans = CharacterDatabase.BeginTransaction(); if (ranks < GUILD_RANKS_MIN_COUNT || ranks > GUILD_RANKS_MAX_COUNT) { TC_LOG_ERROR("guild", "Guild %u has invalid number of ranks, creating new...", m_id); broken_ranks = true; } else { for (uint8 rankId = 0; rankId < ranks; ++rankId) { RankInfo* rankInfo = GetRankInfo(rankId); if (rankInfo->GetId() != rankId) { TC_LOG_ERROR("guild", "Guild %u has broken rank id %u, creating default set of ranks...", m_id, rankId); broken_ranks = true; } else rankInfo->CreateMissingTabsIfNeeded(_GetPurchasedTabsSize(), trans, true); } } if (broken_ranks) { m_ranks.clear(); _CreateDefaultGuildRanks(trans, DEFAULT_LOCALE); } // Validate members' data for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->GetRankId() > _GetRanksSize()) itr->second->ChangeRank(trans, _GetLowestRankId()); // Repair the structure of the guild. // If the guildmaster doesn't exist or isn't member of the guild // attempt to promote another member. Member* pLeader = GetMember(m_leaderGuid); if (!pLeader) { SQLTransaction dummy(nullptr); DeleteMember(dummy, m_leaderGuid); // If no more members left, disband guild if (m_members.empty()) { Disband(); return false; } } else if (!pLeader->IsRank(GR_GUILDMASTER)) _SetLeaderGUID(pLeader); // Check config if multiple guildmasters are allowed if (!sConfigMgr->GetBoolDefault("Guild.AllowMultipleGuildMaster", 0)) for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->GetRankId() == GR_GUILDMASTER && !itr->second->IsSamePlayer(m_leaderGuid)) itr->second->ChangeRank(trans, GR_OFFICER); if (trans->GetSize() > 0) CharacterDatabase.CommitTransaction(trans); _UpdateAccountsNumber(); return true; } // Broadcasts void Guild::BroadcastToGuild(WorldSession* session, bool officerOnly, std::string const& msg, uint32 language) const { if (session && session->GetPlayer() && _HasRankRight(session->GetPlayer(), officerOnly ? GR_RIGHT_OFFCHATSPEAK : GR_RIGHT_GCHATSPEAK)) { WorldPacket data; ChatHandler::BuildChatPacket(data, officerOnly ? CHAT_MSG_OFFICER : CHAT_MSG_GUILD, Language(language), session->GetPlayer(), nullptr, msg); for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (Player* player = itr->second->FindConnectedPlayer()) if (player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) && !player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUID())) player->SendDirectMessage(&data); } } void Guild::BroadcastPacketToRank(WorldPacket* packet, uint8 rankId) const { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->IsRank(rankId)) if (Player* player = itr->second->FindConnectedPlayer()) player->SendDirectMessage(packet); } void Guild::BroadcastPacket(WorldPacket* packet) const { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (Player* player = itr->second->FindPlayer()) player->SendDirectMessage(packet); } void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 maxLevel, uint32 minRank) { uint32 count = 0; WorldPacket data(SMSG_CALENDAR_FILTER_GUILD); data << uint32(count); // count placeholder for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) { // not sure if needed, maybe client checks it as well if (count >= CALENDAR_MAX_INVITES) { if (Player* player = session->GetPlayer()) sCalendarMgr->SendCalendarCommandResult(player->GetGUID(), CALENDAR_ERROR_INVITES_EXCEEDED); return; } Member* member = itr->second; uint32 level = sCharacterCache->GetCharacterLevelByGuid(member->GetGUID()); if (member->GetGUID() != session->GetPlayer()->GetGUID() && level >= minLevel && level <= maxLevel && member->IsRankNotLower(minRank)) { data.appendPackGUID(member->GetGUID().GetRawValue()); data << uint8(0); // unk ++count; } } data.put<uint32>(0, count); session->SendPacket(&data); } // Members handling bool Guild::AddMember(SQLTransaction& trans, ObjectGuid guid, uint8 rankId) { Player* player = ObjectAccessor::FindConnectedPlayer(guid); // Player cannot be in guild if (player) { if (player->GetGuildId() != 0) return false; } else if (sCharacterCache->GetCharacterGuildIdByGuid(guid) != 0) return false; // Remove all player signs from another petitions // This will be prevent attempt to join many guilds and corrupt guild data integrity Player::RemovePetitionsAndSigns(guid, GUILD_CHARTER_TYPE); ObjectGuid::LowType lowguid = guid.GetCounter(); // If rank was not passed, assign lowest possible rank if (rankId == GUILD_RANK_NONE) rankId = _GetLowestRankId(); Member* member = new Member(m_id, guid, rankId); std::string name; if (player) { m_members[lowguid] = member; player->SetInGuild(m_id); player->SetGuildIdInvited(0); player->SetRank(rankId); member->SetStats(player); SendLoginInfo(player->GetSession()); name = player->GetName(); } else { member->ResetFlags(); bool ok = false; // Player must exist PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD); stmt->setUInt32(0, lowguid); if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) { Field* fields = result->Fetch(); name = fields[0].GetString(); member->SetStats( name, fields[1].GetUInt8(), fields[2].GetUInt8(), fields[3].GetUInt8(), fields[4].GetUInt16(), fields[5].GetUInt32()); ok = member->CheckStats(); } if (!ok) { delete member; return false; } m_members[lowguid] = member; sCharacterCache->UpdateCharacterGuildId(guid, GetId()); } member->SaveToDB(trans); _UpdateAccountsNumber(); _LogEvent(GUILD_EVENT_LOG_JOIN_GUILD, lowguid); _BroadcastEvent(GE_JOINED, guid, name.c_str()); // Call scripts if member was succesfully added (and stored to database) sScriptMgr->OnGuildAddMember(this, player, rankId); return true; } void Guild::DeleteMember(SQLTransaction& trans, ObjectGuid guid, bool isDisbanding, bool isKicked, bool canDeleteGuild) { ObjectGuid::LowType lowguid = guid.GetCounter(); Player* player = ObjectAccessor::FindConnectedPlayer(guid); // Guild master can be deleted when loading guild and guid doesn't exist in characters table // or when he is removed from guild by gm command if (m_leaderGuid == guid && !isDisbanding) { Member* oldLeader = nullptr; Member* newLeader = nullptr; for (auto i = m_members.begin(); i != m_members.end(); ++i) { if (i->first == lowguid) oldLeader = i->second; else if (!newLeader || newLeader->GetRankId() > i->second->GetRankId()) newLeader = i->second; } if (!newLeader) { Disband(); if (canDeleteGuild) delete this; return; } _SetLeaderGUID(newLeader); // If player not online data in data field will be loaded from guild tabs no need to update it !! if (Player* newLeaderPlayer = newLeader->FindPlayer()) newLeaderPlayer->SetRank(GR_GUILDMASTER); // If leader does not exist (at guild loading with deleted leader) do not send broadcasts if (oldLeader) { _BroadcastEvent(GE_LEADER_CHANGED, ObjectGuid::Empty, oldLeader->GetName().c_str(), newLeader->GetName().c_str()); _BroadcastEvent(GE_LEFT, guid, oldLeader->GetName().c_str()); } } // Call script on remove before member is actually removed from guild (and database) sScriptMgr->OnGuildRemoveMember(this, player, isDisbanding, isKicked); if (Member* member = GetMember(guid)) delete member; m_members.erase(lowguid); // If player not online data in data field will be loaded from guild tabs no need to update it !! if (player) { player->SetInGuild(0); player->SetRank(0); } else sCharacterCache->UpdateCharacterGuildId(guid, 0); _DeleteMemberFromDB(trans, lowguid); if (!isDisbanding) _UpdateAccountsNumber(); } bool Guild::ChangeMemberRank(SQLTransaction& trans, ObjectGuid guid, uint8 newRank) { if (newRank <= _GetLowestRankId()) // Validate rank (allow only existing ranks) { if (Member* member = GetMember(guid)) { member->ChangeRank(trans, newRank); return true; } } return false; } // Bank (items move) void Guild::SwapItems(Player* player, uint8 tabId, uint8 slotId, uint8 destTabId, uint8 destSlotId, uint32 splitedAmount) { if (tabId >= _GetPurchasedTabsSize() || slotId >= GUILD_BANK_MAX_SLOTS || destTabId >= _GetPurchasedTabsSize() || destSlotId >= GUILD_BANK_MAX_SLOTS) return; if (tabId == destTabId && slotId == destSlotId) return; BankMoveItemData from(this, player, tabId, slotId); BankMoveItemData to(this, player, destTabId, destSlotId); _MoveItems(&from, &to, splitedAmount); } void Guild::SwapItemsWithInventory(Player* player, bool toChar, uint8 tabId, uint8 slotId, uint8 playerBag, uint8 playerSlotId, uint32 splitedAmount) { if ((slotId >= GUILD_BANK_MAX_SLOTS && slotId != NULL_SLOT) || tabId >= _GetPurchasedTabsSize()) return; BankMoveItemData bankData(this, player, tabId, slotId); PlayerMoveItemData charData(this, player, playerBag, playerSlotId); if (toChar) _MoveItems(&bankData, &charData, splitedAmount); else _MoveItems(&charData, &bankData, splitedAmount); } // Bank tabs void Guild::SetBankTabText(uint8 tabId, std::string const& text) { if (BankTab* pTab = GetBankTab(tabId)) { pTab->SetText(text); pTab->SendText(this, nullptr); } } bool Guild::_HasRankRight(Player* player, uint32 right) const { if (player) if (Member const* member = GetMember(player->GetGUID())) return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY; return false; } void Guild::_DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); stmt->setUInt32(0, lowguid); CharacterDatabase.ExecuteOrAppend(trans, stmt); } // Private methods void Guild::_CreateLogHolders() { m_eventLog = new LogHolder(sWorld->getIntConfig(CONFIG_GUILD_EVENT_LOG_COUNT)); for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId) m_bankEventLog[tabId] = new LogHolder(sWorld->getIntConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT)); } void Guild::_CreateNewBankTab() { uint8 tabId = _GetPurchasedTabsSize(); // Next free id m_bankTabs.push_back(new BankTab(m_id, tabId)); SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TAB); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, tabId); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_TAB); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, tabId); trans->Append(stmt); ++tabId; for (auto itr = m_ranks.begin(); itr != m_ranks.end(); ++itr) (*itr).CreateMissingTabsIfNeeded(tabId, trans, false); CharacterDatabase.CommitTransaction(trans); } void Guild::_CreateDefaultGuildRanks(SQLTransaction& trans, LocaleConstant loc) { ASSERT(trans); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS); stmt->setUInt32(0, m_id); trans->Append(stmt); _CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_MASTER, loc), GR_RIGHT_ALL); _CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_OFFICER, loc), GR_RIGHT_ALL); _CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_VETERAN, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); _CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_MEMBER, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); _CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_INITIATE, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); } bool Guild::_CreateRank(SQLTransaction& trans, std::string const& name, uint32 rights) { uint8 newRankId = _GetRanksSize(); if (newRankId >= GUILD_RANKS_MAX_COUNT) return false; // Ranks represent sequence 0, 1, 2, ... where 0 means guildmaster RankInfo info(m_id, newRankId, name, rights, 0); m_ranks.push_back(info); bool const isInTransaction = bool(trans); if (!isInTransaction) trans = CharacterDatabase.BeginTransaction(); info.CreateMissingTabsIfNeeded(_GetPurchasedTabsSize(), trans); info.SaveToDB(trans); if (!isInTransaction) CharacterDatabase.CommitTransaction(trans); return true; } // Updates the number of accounts that are in the guild // Player may have many characters in the guild, but with the same account void Guild::_UpdateAccountsNumber() { // We use a set to be sure each element will be unique std::set<uint32> accountsIdSet; for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) accountsIdSet.insert(itr->second->GetAccountId()); m_accountsNumber = accountsIdSet.size(); } // Detects if player is the guild master. // Check both leader guid and player's rank (otherwise multiple feature with // multiple guild masters won't work) bool Guild::_IsLeader(Player* player) const { if (player->GetGUID() == m_leaderGuid) return true; if (Member const* member = GetMember(player->GetGUID())) return member->IsRank(GR_GUILDMASTER); return false; } void Guild::_DeleteBankItems(SQLTransaction& trans, bool removeItemsFromDB) { for (uint8 tabId = 0; tabId < _GetPurchasedTabsSize(); ++tabId) { m_bankTabs[tabId]->Delete(trans, removeItemsFromDB); delete m_bankTabs[tabId]; m_bankTabs[tabId] = nullptr; } m_bankTabs.clear(); } bool Guild::_ModifyBankMoney(SQLTransaction& trans, uint64 amount, bool add) { if (add) m_bankMoney += amount; else { // Check if there is enough money in bank. if (m_bankMoney < amount) return false; m_bankMoney -= amount; } PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_MONEY); stmt->setUInt64(0, m_bankMoney); stmt->setUInt32(1, m_id); trans->Append(stmt); return true; } void Guild::_SetLeaderGUID(Member* pLeader) { if (!pLeader) return; SQLTransaction trans = CharacterDatabase.BeginTransaction(); m_leaderGuid = pLeader->GetGUID(); pLeader->ChangeRank(trans, GR_GUILDMASTER); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER); stmt->setUInt32(0, m_leaderGuid.GetCounter()); stmt->setUInt32(1, m_id); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); } void Guild::_SetRankBankMoneyPerDay(uint8 rankId, uint32 moneyPerDay) { if (RankInfo* rankInfo = GetRankInfo(rankId)) rankInfo->SetBankMoneyPerDay(moneyPerDay); } void Guild::_SetRankBankTabRightsAndSlots(uint8 rankId, GuildBankRightsAndSlots rightsAndSlots, bool saveToDB) { if (rightsAndSlots.GetTabId() >= _GetPurchasedTabsSize()) return; if (RankInfo* rankInfo = GetRankInfo(rankId)) rankInfo->SetBankTabSlotsAndRights(rightsAndSlots, saveToDB); } inline std::string Guild::_GetRankName(uint8 rankId) const { if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetName(); return "<unknown>"; } inline uint32 Guild::_GetRankRights(uint8 rankId) const { if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetRights(); return 0; } inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const { if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankMoneyPerDay(); return 0; } inline int32 Guild::_GetRankBankTabSlotsPerDay(uint8 rankId, uint8 tabId) const { if (tabId < _GetPurchasedTabsSize()) if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabSlotsPerDay(tabId); return 0; } inline int8 Guild::_GetRankBankTabRights(uint8 rankId, uint8 tabId) const { if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabRights(tabId); return 0; } inline int32 Guild::_GetMemberRemainingSlots(Member const* member, uint8 tabId) const { if (member) { uint8 rankId = member->GetRankId(); if (rankId == GR_GUILDMASTER) return static_cast<int32>(GUILD_WITHDRAW_SLOT_UNLIMITED); if ((_GetRankBankTabRights(rankId, tabId) & GUILD_BANK_RIGHT_VIEW_TAB) != 0) { int32 remaining = _GetRankBankTabSlotsPerDay(rankId, tabId) - member->GetBankWithdrawValue(tabId); if (remaining > 0) return remaining; } } return 0; } inline int32 Guild::_GetMemberRemainingMoney(Member const* member) const { if (member) { uint8 rankId = member->GetRankId(); if (rankId == GR_GUILDMASTER) return static_cast<int32>(GUILD_WITHDRAW_MONEY_UNLIMITED); if ((_GetRankRights(rankId) & (GR_RIGHT_WITHDRAW_REPAIR | GR_RIGHT_WITHDRAW_GOLD)) != 0) { int32 remaining = _GetRankBankMoneyPerDay(rankId) - member->GetBankWithdrawValue(GUILD_BANK_MAX_TABS); if (remaining > 0) return remaining; } } return 0; } inline void Guild::_UpdateMemberWithdrawSlots(SQLTransaction& trans, ObjectGuid guid, uint8 tabId) { if (Member* member = GetMember(guid)) { uint8 rankId = member->GetRankId(); if (rankId != GR_GUILDMASTER && member->GetBankWithdrawValue(tabId) < _GetRankBankTabSlotsPerDay(rankId, tabId)) member->UpdateBankWithdrawValue(trans, tabId, 1); } } inline bool Guild::_MemberHasTabRights(ObjectGuid guid, uint8 tabId, uint32 rights) const { if (Member const* member = GetMember(guid)) { // Leader always has full rights if (member->IsRank(GR_GUILDMASTER) || m_leaderGuid == guid) return true; return (_GetRankBankTabRights(member->GetRankId(), tabId) & rights) == rights; } return false; } // Add new event log record inline void Guild::_LogEvent(GuildEventLogTypes eventType, ObjectGuid::LowType playerGuid1, ObjectGuid::LowType playerGuid2, uint8 newRank) { SQLTransaction trans = CharacterDatabase.BeginTransaction(); m_eventLog->AddEvent(trans, new EventLogEntry(m_id, m_eventLog->GetNextGUID(), eventType, playerGuid1, playerGuid2, newRank)); CharacterDatabase.CommitTransaction(trans); sScriptMgr->OnGuildEvent(this, uint8(eventType), playerGuid1, playerGuid2, newRank); } // Add new bank event log record void Guild::_LogBankEvent(SQLTransaction& trans, GuildBankEventLogTypes eventType, uint8 tabId, ObjectGuid::LowType lowguid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId) { if (tabId > GUILD_BANK_MAX_TABS) return; // not logging moves within the same tab if (eventType == GUILD_BANK_LOG_MOVE_ITEM && tabId == destTabId) return; uint8 dbTabId = tabId; if (BankEventLogEntry::IsMoneyEvent(eventType)) { tabId = GUILD_BANK_MAX_TABS; dbTabId = GUILD_BANK_MONEY_LOGS_TAB; } LogHolder* pLog = m_bankEventLog[tabId]; pLog->AddEvent(trans, new BankEventLogEntry(m_id, pLog->GetNextGUID(), eventType, dbTabId, lowguid, itemOrMoney, itemStackCount, destTabId)); sScriptMgr->OnGuildBankEvent(this, uint8(eventType), tabId, lowguid, itemOrMoney, itemStackCount, destTabId); } inline Item* Guild::_GetItem(uint8 tabId, uint8 slotId) const { if (BankTab const* tab = GetBankTab(tabId)) return tab->GetItem(slotId); return nullptr; } inline void Guild::_RemoveItem(SQLTransaction& trans, uint8 tabId, uint8 slotId) { if (BankTab* pTab = GetBankTab(tabId)) pTab->SetItem(trans, slotId, nullptr); } void Guild::_MoveItems(MoveItemData* pSrc, MoveItemData* pDest, uint32 splitedAmount) { // 1. Initialize source item<|fim▁hole|> // 2. Check source item if (!pSrc->CheckItem(splitedAmount)) return; // Source item or splited amount is invalid /* if (pItemSrc->GetCount() == 0) { TC_LOG_FATAL("guild", "Guild::SwapItems: Player %s(GUIDLow: %u) tried to move item %u from tab %u slot %u to tab %u slot %u, but item %u has a stack of zero!", player->GetName(), player->GetGUID().GetCounter(), pItemSrc->GetEntry(), tabId, slotId, destTabId, destSlotId, pItemSrc->GetEntry()); //return; // Commented out for now, uncomment when it's verified that this causes a crash!! } // */ // 3. Check destination rights if (!pDest->HasStoreRights(pSrc)) return; // Player has no rights to store item in destination // 4. Check source withdraw rights if (!pSrc->HasWithdrawRights(pDest)) return; // Player has no rights to withdraw items from source // 5. Check split if (splitedAmount) { // 5.1. Clone source item if (!pSrc->CloneItem(splitedAmount)) return; // Item could not be cloned // 5.2. Move splited item to destination _DoItemsMove(pSrc, pDest, true, splitedAmount); } else // 6. No split { // 6.1. Try to merge items in destination (pDest->GetItem() == nullptr) if (!_DoItemsMove(pSrc, pDest, false)) // Item could not be merged { // 6.2. Try to swap items // 6.2.1. Initialize destination item if (!pDest->InitItem()) return; // 6.2.2. Check rights to store item in source (opposite direction) if (!pSrc->HasStoreRights(pDest)) return; // Player has no rights to store item in source (opposite direction) if (!pDest->HasWithdrawRights(pSrc)) return; // Player has no rights to withdraw item from destination (opposite direction) // 6.2.3. Swap items (pDest->GetItem() != nullptr) _DoItemsMove(pSrc, pDest, true); } } // 7. Send changes _SendBankContentUpdate(pSrc, pDest); } bool Guild::_DoItemsMove(MoveItemData* pSrc, MoveItemData* pDest, bool sendError, uint32 splitedAmount) { Item* pDestItem = pDest->GetItem(); bool swap = (pDestItem != nullptr); Item* pSrcItem = pSrc->GetItem(splitedAmount != 0); // 1. Can store source item in destination if (!pDest->CanStore(pSrcItem, swap, sendError)) return false; // 2. Can store destination item in source if (swap) if (!pSrc->CanStore(pDestItem, true, true)) return false; // GM LOG (@todo move to scripts) pDest->LogAction(pSrc); if (swap) pSrc->LogAction(pDest); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // 3. Log bank events pDest->LogBankEvent(trans, pSrc, pSrcItem->GetCount()); if (swap) pSrc->LogBankEvent(trans, pDest, pDestItem->GetCount()); // 4. Remove item from source pSrc->RemoveItem(trans, pDest, splitedAmount); // 5. Remove item from destination if (swap) pDest->RemoveItem(trans, pSrc); // 6. Store item in destination pDest->StoreItem(trans, pSrcItem); // 7. Store item in source if (swap) pSrc->StoreItem(trans, pDestItem); CharacterDatabase.CommitTransaction(trans); return true; } void Guild::_SendBankContent(WorldSession* session, uint8 tabId) const { ObjectGuid guid = session->GetPlayer()->GetGUID(); if (!_MemberHasTabRights(guid, tabId, GUILD_BANK_RIGHT_VIEW_TAB)) return; _SendBankList(session, tabId, true); } void Guild::_SendBankMoneyUpdate(WorldSession* session) const { _SendBankList(session); } void Guild::_SendBankContentUpdate(MoveItemData* pSrc, MoveItemData* pDest) const { ASSERT(pSrc->IsBank() || pDest->IsBank()); uint8 tabId = 0; SlotIds slots; if (pSrc->IsBank()) // B -> { tabId = pSrc->GetContainer(); slots.insert(pSrc->GetSlotId()); if (pDest->IsBank()) // B -> B { // Same tab - add destination slots to collection if (pDest->GetContainer() == pSrc->GetContainer()) pDest->CopySlots(slots); else // Different tabs - send second message { SlotIds destSlots; pDest->CopySlots(destSlots); _SendBankContentUpdate(pDest->GetContainer(), destSlots); } } } else if (pDest->IsBank()) // C -> B { tabId = pDest->GetContainer(); pDest->CopySlots(slots); } _SendBankContentUpdate(tabId, slots); } void Guild::_SendBankContentUpdate(uint8 tabId, SlotIds slots) const { _SendBankList(nullptr, tabId, false, &slots); } void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1, char const* param2, char const* param3) const { uint8 count = !param3 ? (!param2 ? (!param1 ? 0 : 1) : 2) : 3; WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + count + (8)); data << uint8(guildEvent); data << uint8(count); if (param3) data << param1 << param2 << param3; else if (param2) data << param1 << param2; else if (param1) data << param1; if (guid) data << uint64(guid); BroadcastPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_EVENT [Broadcast] Event: %s (%u)", GetGuildEventString(guildEvent), guildEvent); } void Guild::_SendBankList(WorldSession* session /* = nullptr*/, uint8 tabId /*= 0*/, bool sendAllSlots /*= false*/, SlotIds *slots /*= nullptr*/) const { WorldPacket data(SMSG_GUILD_BANK_LIST, 500); data << uint64(m_bankMoney); data << uint8(tabId); size_t rempos = data.wpos(); data << uint32(0); data << uint8(sendAllSlots); if (sendAllSlots && !tabId) { data << uint8(_GetPurchasedTabsSize()); // Number of tabs for (uint8 i = 0; i < _GetPurchasedTabsSize(); ++i) m_bankTabs[i]->WriteInfoPacket(data); } BankTab const* tab = GetBankTab(tabId); if (!tab) data << uint8(0); else if (sendAllSlots) tab->WritePacket(data); else if (slots && !slots->empty()) { data << uint8(slots->size()); for (auto itr = slots->begin(); itr != slots->end(); ++itr) tab->WriteSlotPacket(data, *itr, false); } else data << uint8(0); if (session) { int32 numSlots = 0; if (Member const* member = GetMember(session->GetPlayer()->GetGUID())) numSlots = _GetMemberRemainingSlots(member, tabId); data.put<uint32>(rempos, numSlots); session->SendPacket(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %d", session->GetPlayerInfo().c_str(), tabId, sendAllSlots, numSlots); } else /// @todo - Probably this is just sent to session + those that have sent CMSG_GUILD_BANKER_ACTIVATE { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) { if (!_MemberHasTabRights(itr->second->GetGUID(), tabId, GUILD_BANK_RIGHT_VIEW_TAB)) continue; Player* player = itr->second->FindPlayer(); if (!player) continue; uint32 numSlots = _GetMemberRemainingSlots(itr->second, tabId); data.put<uint32>(rempos, numSlots); player->SendDirectMessage(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %u" , player->GetName().c_str(), tabId, sendAllSlots, numSlots); } } } void Guild::ResetTimes() { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) itr->second->ResetValues(); _BroadcastEvent(GE_BANK_TAB_AND_MONEY_UPDATED, ObjectGuid::Empty); }<|fim▁end|>
if (!pSrc->InitItem()) return; // No source item
<|file_name|>secure_message_sign_verify_rsa.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 Cossack Labs Limited // // 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. use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; use libthemis_sys::{ themis_secure_message_sign, themis_secure_message_verify, THEMIS_BUFFER_TOO_SMALL, THEMIS_SUCCESS, }; use themis::{keygen::gen_rsa_key_pair, secure_message::SecureSign}; const KB: usize = 1024; const MB: usize = 1024 * KB; #[allow(clippy::identity_op)] const MESSAGE_SIZES: &[usize] = &[ 16, // UUID 32, // SymmetricKey 64, // cache line (and close to EcdsaPrivateKey) 256, // RsaPrivateKey 4 * KB, // memory page 16 * KB, 64 * KB, 1 * MB, // L2 cache 2 * MB, 4 * MB, ]; pub fn signing(c: &mut Criterion) { let (private, _) = gen_rsa_key_pair().split(); let private = private.as_ref(); // Allocate buffer large enough for maximum test let mut signature = vec![0; 10 * MB]; let mut group = c.benchmark_group("Secure Message signing - RSA"); for message_size in MESSAGE_SIZES { group.throughput(Throughput::Bytes(*message_size as u64)); group.bench_with_input( BenchmarkId::from_parameter(pretty(*message_size)), message_size, |b, &size| { let message = vec![0; size]; b.iter(|| { let mut signature_size = 0; let res = unsafe { themis_secure_message_sign( private.as_ptr(), private.len(), message.as_ptr(), message.len(), std::ptr::null_mut(), &mut signature_size, ) }; assert_eq!(res, THEMIS_BUFFER_TOO_SMALL as i32); assert!(signature_size <= signature.len()); let res = unsafe { themis_secure_message_sign( private.as_ptr(), private.len(), message.as_ptr(), message.len(), signature.as_mut_ptr(), &mut signature_size, ) }; assert_eq!(res, THEMIS_SUCCESS as i32); }); }, ); } group.finish(); } pub fn verification(c: &mut Criterion) { let key_pair = gen_rsa_key_pair(); let (private, public) = key_pair.split(); let public = public.as_ref(); let mut group = c.benchmark_group("Secure Message verification - RSA"); for message_size in MESSAGE_SIZES { group.throughput(Throughput::Bytes(*message_size as u64)); group.bench_with_input( BenchmarkId::from_parameter(pretty(*message_size)), message_size, |b, &size| { let message = vec![0; size]; let signature = SecureSign::new(private.clone()) .sign(&message) .expect("failed signing"); let mut received_message = vec![0; size]; b.iter(|| { let mut received_message_size = 0; let res = unsafe { themis_secure_message_verify( public.as_ptr(), public.len(), signature.as_ptr(), signature.len(), std::ptr::null_mut(), &mut received_message_size, ) }; assert_eq!(res, THEMIS_BUFFER_TOO_SMALL as i32); assert!(received_message_size == received_message.len()); let res = unsafe { themis_secure_message_verify( public.as_ptr(), public.len(), signature.as_ptr(), signature.len(), received_message.as_mut_ptr(), &mut received_message_size, ) }; assert_eq!(res, THEMIS_SUCCESS as i32); }); }, ); } group.finish(); } fn pretty(size: usize) -> String { if size >= MB { format!("{} MB", size / MB)<|fim▁hole|> } else if size >= KB { format!("{} KB", size / KB) } else { format!("{}", size) } } criterion_group!(benches, signing, verification); criterion_main!(benches);<|fim▁end|>
<|file_name|>cost.py<|end_file_name|><|fim▁begin|>from neon.transforms.cost import Cost class MulticlsSVMLoss(Cost): def __init__(self, delta=1.): self.delta = delta def __call__(self, y, t): T = self.be.empty_like(y) T[:] = self.be.max(y * t, axis=0) # T = self.be.array(self.be.max(y * t, axis=0).asnumpyarray(), y.shape[0], axis=0) margin = self.be.square(self.be.maximum(0, y - T + self.delta)) * 0.5 return self.be.sum(margin) / self.be.bsz def bprop(self, y, t): T = self.be.empty_like(y) T[:] = self.be.max(y * t, axis=0)<|fim▁hole|>class L1SVMLoss(Cost): def __init__(self, C=10): self.C = C def __call__(self, y, t): return self.C * self.be.sum(self.be.square(self.be.maximum(0, 1 - y * (t * 2 - 1)))) * 0.5 / y.shape[0] def bprop(self, y, t): return - self.C * (t * 2 - 1) * self.be.maximum(0, 1 - y * (t * 2 - 1)) / self.be.bsz / y.shape[0]<|fim▁end|>
return self.be.maximum(0, y - T + self.delta) / self.be.bsz
<|file_name|>TriggerConfig.tsx<|end_file_name|><|fim▁begin|>import React from "react"; import {Input} from "reactstrap"; interface TriggerConfigProps { allModuleTypes: string[]; setConfig: (value: any) => void; configValue: string; } const TriggerConfig: React.FC<TriggerConfigProps> = ({ configValue = "", setConfig, allModuleTypes, }) => { const [triggerType, setTriggerType] = React.useState( configValue.split(":")[0],<|fim▁hole|> ); const [triggerValue, setTriggerValue] = React.useState(() => { const value = configValue.split(":")[1]; if (triggerType === "Timer") return parseInt(value.replace(" Seconds", ""), 10); if (triggerType === "Remote Access Code") return value; return null; }); return ( <> <Input value={triggerType} type="select" onChange={e => { setTriggerType(e.target.value); setTriggerValue(null); setConfig(e.target.value); }} > <option>Manual</option> <option>Immediate</option> <option>Timer</option> <option>Remote Access Code</option> {allModuleTypes.includes("Scan Trigger") && ( <option>Scan Trigger</option> )} {allModuleTypes.includes("Proximity Trigger") && ( <option>Proximity Trigger</option> )} </Input> {triggerType === "Timer" && ( <label> Delay in Seconds <Input value={triggerValue as number | undefined} type="number" min="0" onChange={e => { setTriggerValue(e.target.value); setConfig(`${triggerType}: ${e.target.value} Seconds`); }} ></Input> </label> )} {triggerType === "Remote Access Code" && ( <label> Remote Access Code <Input value={triggerValue as string | undefined} type="text" onChange={e => { setTriggerValue(e.target.value); setConfig(`${triggerType}:${e.target.value}`); }} ></Input> </label> )} </> ); }; export default TriggerConfig;<|fim▁end|>