code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
var _ = require('underscore') module.exports = function (cdb) { (function () { var Layers = cdb.vis.Layers; /* * if we are using http and the tiles of base map need to be fetched from * https try to fix it */ var HTTPS_TO_HTTP = { 'https://dnv9my2eseobd.cloudfront.net/': 'http://a.tiles.mapbox.com/', 'https://maps.nlp.nokia.com/': 'http://maps.nlp.nokia.com/', 'https://tile.stamen.com/': 'http://tile.stamen.com/', "https://{s}.maps.nlp.nokia.com/": "http://{s}.maps.nlp.nokia.com/", "https://cartocdn_{s}.global.ssl.fastly.net/": "http://{s}.api.cartocdn.com/", "https://cartodb-basemaps-{s}.global.ssl.fastly.net/": "http://{s}.basemaps.cartocdn.com/" }; function transformToHTTP(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { if (tilesTemplate.indexOf(url) !== -1) { return tilesTemplate.replace(url, HTTPS_TO_HTTP[url]) } } return tilesTemplate; } function transformToHTTPS(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { var httpsUrl = HTTPS_TO_HTTP[url]; if (tilesTemplate.indexOf(httpsUrl) !== -1) { return tilesTemplate.replace(httpsUrl, url); } } return tilesTemplate; } Layers.register('tilejson', function (vis, data) { var url = data.tiles[0]; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } return new cdb.geo.TileLayer({ urlTemplate: url }); }); Layers.register('tiled', function (vis, data) { var url = data.urlTemplate; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } data.urlTemplate = url; return new cdb.geo.TileLayer(data); }); Layers.register('wms', function (vis, data) { return new cdb.geo.WMSLayer(data); }); Layers.register('gmapsbase', function (vis, data) { return new cdb.geo.GMapsBaseLayer(data); }); Layers.register('plain', function (vis, data) { return new cdb.geo.PlainLayer(data); }); Layers.register('background', function (vis, data) { return new cdb.geo.PlainLayer(data); }); function normalizeOptions(vis, data) { if (data.infowindow && data.infowindow.fields) { if (data.interactivity) { if (data.interactivity.indexOf('cartodb_id') === -1) { data.interactivity = data.interactivity + ",cartodb_id"; } } else { data.interactivity = 'cartodb_id'; } } // if https is forced if (vis.https) { data.tiler_protocol = 'https'; data.tiler_port = 443; data.sql_api_protocol = 'https'; data.sql_api_port = 443; } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; } var cartoLayer = function (vis, data) { normalizeOptions(vis, data); // if sublayers are included that means a layergroup should // be created if (data.sublayers) { data.type = 'layergroup'; return new cdb.geo.CartoDBGroupLayer(data); } return new cdb.geo.CartoDBLayer(data); }; Layers.register('cartodb', cartoLayer); Layers.register('carto', cartoLayer); Layers.register('layergroup', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBGroupLayer(data); }); Layers.register('namedmap', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBNamedMapLayer(data); }); Layers.register('torque', function (vis, data) { normalizeOptions(vis, data); // default is https if (vis.https) { if (data.sql_api_domain && data.sql_api_domain.indexOf('cartodb.com') !== -1) { data.sql_api_protocol = 'https'; data.sql_api_port = 443; data.tiler_protocol = 'https'; data.tiler_port = 443; } } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; return new cdb.geo.TorqueLayer(data); }); })(); }
Stonelinks/cartodb-lite
src/vis/layers.js
JavaScript
bsd-3-clause
5,195
/* ///////////////////////////////////////////////////////////////////////// * File: test/scratch/test.scratch.be.speech/test.scratch.be.speech.cpp * * Purpose: C++ example program for Pantheios. Demonstrates: * * - use of custom severity level information for tabbing output * - definition of a custom back-end that supports tabbed output * - use of pantheios::logputs() in bail-out conditions * * Created: 31st August 2006 * Updated: 27th January 2017 * * www: http://www.pantheios.org/ * * License: This source code is placed into the public domain 2006 * by Synesis Software Pty Ltd. There are no restrictions * whatsoever to your use of the software. * * This software is provided "as is", and any warranties, * express or implied, of any kind and for any purpose, are * disclaimed. * * ////////////////////////////////////////////////////////////////////// */ /* This inclusion required for suppressing warnings during NoX (No eXception-support) configurations. */ #include <pantheios/util/test/compiler_warnings_suppression.first_include.h> /* Pantheios header files */ #include <pantheios/pantheios.hpp> #include <pantheios/backend.h> #include <pantheios/implicit_link/core.h> #include <pantheios/implicit_link/fe.simple.h> #include <pantheios/implicit_link/be.lrsplit.h> #include <pantheios/implicit_link/bel.WindowsConsole.h> #include <pantheios/implicit_link/bec.speech.WithCallback.h> #include <pantheios/backends/bec.speech.h> /* Standard C/C++ header files */ #include <exception> // for std::exception #include <string> // for std::string #include <stdio.h> // for fprintf() #include <stdlib.h> // for exit codes #include <string.h> // for memset() #include <pantheios/util/test/compiler_warnings_suppression.last_include.h> /* ////////////////////////////////////////////////////////////////////// */ // Define the fe.simple process identity, so that it links when using fe.simple PANTHEIOS_EXTERN PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("test.scratch.speech"); /* ////////////////////////////////////////////////////////////////////// */ //PANTHEIOS_BE_DEFINE_BE_FUNCTIONS(speech) PANTHEIOS_BE_DEFINE_BER_FUNCTIONS(speech) PANTHEIOS_CALL(void) pantheios_be_speech_getAppInit(int backEndId, pan_be_speech_init_t* init) /* throw() */ { // init->flags |= PANTHEIOS_BE_SPEECH_F_SYNCHRONOUS; // init->flags |= PANTHEIOS_BE_SPEECH_F_PURGE_BEFORE_SPEAK; // init->flags |= PANTHEIOS_BE_SPEECH_F_SPEAK_PUNCTUATION; // init->flags |= PANTHEIOS_BE_SPEECH_F_SYNCHRONOUS_ON_CRITICAL; } /* ////////////////////////////////////////////////////////////////////// */ int main() { DWORD shortPause = 1250; try { // pantheios::log(pantheios::notice, "Hello"); // ::Sleep(shortPause); // pantheios::log(pantheios::notice(2), "Hello"); // ::Sleep(shortPause); // pantheios::log(pantheios::notice(2), "Hello, boys. This is your daddy, telling you to turn around and eat your dinner. Now!"); // ::Sleep(shortPause); short s = SHRT_MIN; unsigned short us = USHRT_MAX; int i = INT_MIN; unsigned int ui = UINT_MAX; long l = LONG_MIN; unsigned long ul = ULONG_MAX; #if 0 // Log a short in decimal; Output: "s: [-32768]" pantheios::log_NOTICE("s: [", pantheios::integer(s), "]"); ::Sleep(shortPause); // Log a unsigned short as hexadecimal; Output: "us: [ffff]" pantheios::log_NOTICE("us: [", pantheios::integer(us, pantheios::fmt::hex), "]"); ::Sleep(shortPause); // Log an int, into a width of 20; Output: "i: [-2147483648 ]" pantheios::log_NOTICE("i: [", pantheios::integer(i, -20), "]"); ::Sleep(shortPause); // Log an unsigned int as hexadecimal with 0x prefix; Output: "ui: [0xffffffff]" pantheios::log_NOTICE("ui: [", pantheios::integer(ui, pantheios::fmt::hex | pantheios::fmt::zeroXPrefix), "]"); ::Sleep(shortPause); // Log a long; Output: "l: [ -2147483648]" pantheios::log_NOTICE("l: [", pantheios::integer(l, 20), "]"); ::Sleep(shortPause); // Log an unsigned long; Output: "ul: [4294967295]" pantheios::log_NOTICE("ul: [", pantheios::integer(ul), "]"); ::Sleep(shortPause); #else /* ? 0 */ pantheios::log_NOTICE("Hi!"); ::Sleep(shortPause); pantheios::log_NOTICE("This is your logger, calling."); ::Sleep(shortPause); pantheios::log_NOTICE("Here come some diagnostic logging statements ..."); ::Sleep(shortPause); #endif /* 0 */ pantheios::log_DEBUG("just being pedantic"); ::Sleep(shortPause); pantheios::log_INFORMATIONAL("you can ignore this"); ::Sleep(shortPause); pantheios::log_NOTICE("this is noteworthy"); ::Sleep(shortPause); pantheios::log_WARNING("there may be a problem"); ::Sleep(shortPause); pantheios::log_ERROR("there is a problem"); ::Sleep(shortPause); pantheios::log_CRITICAL("there is a serious problem"); ::Sleep(shortPause); pantheios::log_ALERT("there is a very serious problem"); ::Sleep(shortPause); pantheios::log_EMERGENCY("aargh! I'm operating in contradiction to my design!"); ::Sleep(90000); return EXIT_SUCCESS; } catch(std::bad_alloc &) { pantheios::log_CRITICAL("out of memory"); } catch(std::exception &x) { pantheios::log_ALERT("Exception: ", x); } catch(...) { pantheios::logputs(pantheios::emergency, "Unexpected unknown error"); } return EXIT_FAILURE; } /* ////////////////////////////////////////////////////////////////////// */
synesissoftware/Pantheios
test/scratch/test.scratch.be.speech/test.scratch.be.speech.cpp
C++
bsd-3-clause
6,112
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group 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. * *//*! * \file * \brief Image Tests *//*--------------------------------------------------------------------*/ #include "vktImageTests.hpp" #include "vktImageLoadStoreTests.hpp" #include "vktImageMultisampleLoadStoreTests.hpp" #include "vktImageMutableTests.hpp" #include "vktImageQualifiersTests.hpp" #include "vktImageSizeTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktImageAtomicOperationTests.hpp" #include "vktImageCompressionTranscodingSupport.hpp" #include "vktImageTranscodingSupportTests.hpp" #include "vktImageAstcDecodeModeTests.hpp" #include "vktImageMisalignedCubeTests.hpp" namespace vkt { namespace image { namespace { void createChildren (tcu::TestCaseGroup* imageTests) { tcu::TestContext& testCtx = imageTests->getTestContext(); imageTests->addChild(createImageStoreTests(testCtx)); imageTests->addChild(createImageLoadStoreTests(testCtx)); imageTests->addChild(createImageMultisampleLoadStoreTests(testCtx)); imageTests->addChild(createImageMutableTests(testCtx)); imageTests->addChild(createSwapchainImageMutableTests(testCtx)); imageTests->addChild(createImageFormatReinterpretTests(testCtx)); imageTests->addChild(createImageQualifiersTests(testCtx)); imageTests->addChild(createImageSizeTests(testCtx)); imageTests->addChild(createImageAtomicOperationTests(testCtx)); imageTests->addChild(createImageCompressionTranscodingTests(testCtx)); imageTests->addChild(createImageTranscodingSupportTests(testCtx)); imageTests->addChild(createImageExtendOperandsTests(testCtx)); imageTests->addChild(createImageAstcDecodeModeTests(testCtx)); imageTests->addChild(createMisalignedCubeTests(testCtx)); imageTests->addChild(createImageLoadStoreLodAMDTests(testCtx)); } } // anonymous tcu::TestCaseGroup* createTests (tcu::TestContext& testCtx) { return createTestGroup(testCtx, "image", "Image tests", createChildren); } } // image } // vkt
endlessm/chromium-browser
third_party/angle/third_party/VK-GL-CTS/src/external/vulkancts/modules/vulkan/image/vktImageTests.cpp
C++
bsd-3-clause
2,630
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ package antlr type IntStream interface { Consume() LA(int) int Mark() int Release(marker int) Index() int Seek(index int) Size() int GetSourceName() string }
chandler14362/antlr4
runtime/Go/antlr/int_stream.go
GO
bsd-3-clause
365
/* Copyright (C) 2014 Parrot SA Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Parrot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ARDiscoveryService.java * * Created on: * Author: */ package com.parrot.arsdk.ardiscovery; import android.os.Parcel; import android.os.Parcelable; import com.parrot.arsdk.arsal.ARSALPrint; public class ARDiscoveryDeviceService implements Parcelable { /** * */ private static String TAG = "ARDiscoveryDevice"; private String name; /**< Name of the device */ private int productID; /**< Specific product ID */ private ARDISCOVERY_NETWORK_TYPE_ENUM networkType; private Object device; /**< can by ARDiscoveryDeviceNetService or ARDiscoveryDeviceBLEService or ARDiscoveryDeviceUsbService*/ public static final Parcelable.Creator<ARDiscoveryDeviceService> CREATOR = new Parcelable.Creator<ARDiscoveryDeviceService>() { @Override public ARDiscoveryDeviceService createFromParcel(Parcel source) { return new ARDiscoveryDeviceService(source); } @Override public ARDiscoveryDeviceService[] newArray(int size) { return new ARDiscoveryDeviceService[size]; } }; public ARDiscoveryDeviceService () { name = ""; setDevice(null); productID = 0; networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN; } public ARDiscoveryDeviceService (String name, Object device, int productID) { this.name = name; this.setDevice(device); this.productID = productID; } // Parcelling part public ARDiscoveryDeviceService(Parcel in) { this.name = in.readString(); this.productID = in.readInt(); this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.getFromValue(in.readInt()); switch(this.networkType) { case ARDISCOVERY_NETWORK_TYPE_NET: this.device = in.readParcelable(ARDiscoveryDeviceNetService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_BLE: this.device = in.readParcelable(ARDiscoveryDeviceBLEService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_USBMUX: this.device = in.readParcelable(ARDiscoveryDeviceUsbService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_UNKNOWN: default: this.device = null; break; } } @Override public boolean equals(Object other) { boolean isEqual = true; if ( (other == null) || !(other instanceof ARDiscoveryDeviceService) ) { isEqual = false; } else if (other == this) { isEqual = true; } else { /* check */ ARDiscoveryDeviceService otherDevice = (ARDiscoveryDeviceService) other; if (this.getDevice() != otherDevice.getDevice()) { if((this.getDevice() != null) && (otherDevice.getDevice() != null)) { /* check if the devices are of same class */ if (this.networkType == otherDevice.networkType) { switch (this.networkType) { case ARDISCOVERY_NETWORK_TYPE_NET: /* if it is a NetDevice */ ARDiscoveryDeviceNetService deviceNetService = (ARDiscoveryDeviceNetService) this.getDevice(); ARDiscoveryDeviceNetService otherDeviceNetService = (ARDiscoveryDeviceNetService) otherDevice.getDevice(); if (!deviceNetService.equals(otherDeviceNetService)) { isEqual = false; } break; case ARDISCOVERY_NETWORK_TYPE_BLE: /* if it is a BLEDevice */ ARDiscoveryDeviceBLEService deviceBLEService = (ARDiscoveryDeviceBLEService) this.getDevice(); ARDiscoveryDeviceBLEService otherDeviceBLEService = (ARDiscoveryDeviceBLEService) otherDevice.getDevice(); if (!deviceBLEService.equals(otherDeviceBLEService)) { isEqual = false; } break; case ARDISCOVERY_NETWORK_TYPE_USBMUX: /* if it is a BLEDevice */ ARDiscoveryDeviceUsbService deviceUsbService = (ARDiscoveryDeviceUsbService) this.getDevice(); ARDiscoveryDeviceUsbService otherDeviceUsbService = (ARDiscoveryDeviceUsbService) otherDevice.getDevice(); if (!deviceUsbService.equals(otherDeviceUsbService)) { isEqual = false; } break; } } else { isEqual = false; } } else { isEqual = false; } } else { isEqual = false; } } return isEqual; } public String getName () { return name; } public void setName (String name) { this.name = name; } public Object getDevice () { return device; } public void setDevice (Object device) { this.device = device; if (device instanceof ARDiscoveryDeviceNetService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_NET; } else if (device instanceof ARDiscoveryDeviceBLEService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_BLE; } else if (device instanceof ARDiscoveryDeviceUsbService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_USBMUX; } else { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN; } } public ARDISCOVERY_NETWORK_TYPE_ENUM getNetworkType() { return networkType; } public int getProductID () { return productID; } public void setProductID (int productID) { this.productID = productID; } @Override public int describeContents() { return 0; } @Override public String toString() { return "name="+name+", productID="+productID+", networkType="+networkType; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeInt(this.productID); dest.writeInt(this.networkType.getValue()); if(this.networkType != ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN) { dest.writeParcelable((Parcelable) this.device, flags); } } };
Parrot-Developers/libARDiscovery
JNI/java/com/parrot/arsdk/ardiscovery/ARDiscoveryDeviceService.java
Java
bsd-3-clause
8,864
from django_nose.tools import assert_false, assert_true from pontoon.base.tests import TestCase from pontoon.base.utils import extension_in class UtilsTests(TestCase): def test_extension_in(self): assert_true(extension_in('filename.txt', ['bat', 'txt'])) assert_true(extension_in('filename.biff', ['biff'])) assert_true(extension_in('filename.tar.gz', ['gz'])) assert_false(extension_in('filename.txt', ['png', 'jpg'])) assert_false(extension_in('.dotfile', ['bat', 'txt'])) # Unintuitive, but that's how splitext works. assert_false(extension_in('filename.tar.gz', ['tar.gz']))
yfdyh000/pontoon
pontoon/base/tests/test_utils.py
Python
bsd-3-clause
644
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Universe/Lua/LuaNode.h> #include <Universe/Lua/LuaConstants.h> #include <Universe/Particles/PartEffectAttractor.h> #include <Universe/Particles/PartEffectForce.h> namespace Universe { //----------------------------------------------------------------------------- Ptr<NodeEmitter> LuaNode::getNodeEmitter(lua_State* L) const { if(_pNode->getNodeType() != NODE_EMITTER) badNodeType(L, NODE_EMITTER); else return LM_DEBUG_PTR_CAST<NodeEmitter>(_pNode); return null; } //----------------------------------------------------------------------------- int LuaNode::setPeriod(lua_State* L) { LM_LUA_FUNC_START(L); if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); pStorm->setPeriod(luat_tofloat(L, 1), luat_tofloat(L, 2)); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->setPeriod(luat_tofloat(L, 1), luat_tofloat(L, 2)); } return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::setStickyParticles(lua_State* L) { LM_LUA_FUNC_START(L); Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->setStickyParticles(luat_toboolean(L, 1)); return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::setGenerationTime(lua_State* L) { LM_LUA_FUNC_START(L); if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); pStorm->setGenerationTime(luat_tofloat(L, 1), luat_tofloat(L, 2)); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->setGenerationTime(luat_tofloat(L, 1), luat_tofloat(L, 2)); } return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::killAtEnd(lua_State* L) { LM_LUA_FUNC_START(L); if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); pStorm->killAtEnd(luat_toboolean(L, 1)); } else if(_pNode->getNodeType() == NODE_SOUND) { Ptr<NodeSoundSource> pSound(getNodeSoundSource(L)); pSound->killAtEnd(luat_toboolean(L, 1)); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->killAtEnd(luat_toboolean(L, 1)); } return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::getPeriod(lua_State* L) { LM_LUA_FUNC_START(L); float p1, p2; if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); pStorm->getPeriod(p1, p2); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->getPeriod(p1, p2); } lua_pushnumber(L, p1); lua_pushnumber(L, p2); return 2; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::getGenerationTime(lua_State* L) { LM_LUA_FUNC_START(L); double p1, p2; if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); pStorm->getGenerationTime(p1, p2); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->getGenerationTime(p1, p2); } lua_pushnumber(L, p1); lua_pushnumber(L, p2); return 2; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::getStickyParticles(lua_State* L) { LM_LUA_FUNC_START(L); Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); luat_pushboolean(L, pEmitter->getStickyParticles()); return 1; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::getKillAtEnd(lua_State* L) { LM_LUA_FUNC_START(L); if(_pNode->getNodeType() == NODE_STORM) { Ptr<NodeStorm> pStorm(getNodeStorm(L)); luat_pushboolean(L, pStorm->killAtEnd()); } else if (_pNode->getNodeType() == NODE_SOUND) { Ptr<NodeSoundSource> pNode(getNodeSoundSource(L)); lua_pushboolean(L, pNode->killAtEnd()); } else { Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); luat_pushboolean(L, pEmitter->killAtEnd()); } return 1; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::addAttractor(lua_State* L) { LM_LUA_FUNC_START(L); Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); Ptr<Universe::PartEffectAttractor> pAttractor(new Universe::PartEffectAttractor(luat_tovec3f(L, 1), luat_tofloat(L, 2))); pEmitter->addEffect(pAttractor); return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::addForce(lua_State* L) { LM_LUA_FUNC_START(L); Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); Ptr<Universe::PartEffectForce> pForce(new Universe::PartEffectForce(luat_tovec3f(L, 1), luat_tofloat(L, 2))); pEmitter->addEffect(pForce); return 0; LM_LUA_FUNC_END(L); } //----------------------------------------------------------------------------- int LuaNode::removeEffect(lua_State* L) { LM_LUA_FUNC_START(L); Ptr<NodeEmitter> pEmitter(getNodeEmitter(L)); pEmitter->removeEffects(luat_toeffect(L,1)); return 0; LM_LUA_FUNC_END(L); } }
benkaraban/anima-games-engine
Sources/Modules/Universe/Lua/LuaNodeEmitter.cpp
C++
bsd-3-clause
7,373
module.exports = function Clock() { // TODO }
MantarayAR/paugme-pack-circuits
src/circuit-components/active-components/clock.js
JavaScript
bsd-3-clause
47
/* * * Copyright (C) 2001-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmpstat * * Author: Marco Eichelberg * * Purpose: * classes: DVSignatureHandler * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmpstat/dvsighdl.h" #include "dcmtk/dcmdata/dcdeftag.h" #include "dcmtk/dcmsign/dcsignat.h" #include "dcmtk/dcmdata/dcobject.h" #include "dcmtk/dcmdata/dcsequen.h" #include "dcmtk/dcmdata/dcvrat.h" #include "dcmtk/dcmdata/dcitem.h" #include "dcmtk/dcmpstat/dvpscf.h" #include "dcmtk/dcmsign/sicert.h" #include "dcmtk/dcmsign/sitypes.h" #include "dcmtk/dcmsign/sinullpr.h" #include "dcmtk/dcmsign/siprivat.h" #include "dcmtk/dcmsign/siripemd.h" #include "dcmtk/ofstd/ofstream.h" #ifdef WITH_OPENSSL BEGIN_EXTERN_C #include <openssl/x509.h> END_EXTERN_C /// the signature profile class we're using with DICOMscope class DVSignatureHandlerSignatureProfile: public SiNullProfile { public: /// default constructor DVSignatureHandlerSignatureProfile(DcmAttributeTag& at) : SiNullProfile() , notToSign(at) , vmNotToSign(notToSign.getVM()) { } /// destructor virtual ~DVSignatureHandlerSignatureProfile() { } /** checks whether the given tag is in the list of tags not to sign * @param tag tag to check * @return true if in list, false otherwise */ OFBool tagInList(const DcmTagKey& tag) const { DcmAttributeTag tempList(notToSign); // required because getTagVal() is not const DcmTagKey tagkey; for (unsigned long n=0; n<vmNotToSign; n++) { if ((EC_Normal == tempList.getTagVal(tagkey, n)) && (tag == tagkey)) return OFTrue; } return OFFalse; } /** checks whether an attribute with the given tag must not be signed * for the current security profile. * @param key tag key to be checked * @return true if attribute must not be signed, false otherwise. */ virtual OFBool attributeForbidden(const DcmTagKey& key) const { return tagInList(key); } private: /// list of attributes not to sign DcmAttributeTag& notToSign; /// number of entries in notToSign unsigned long vmNotToSign; }; #endif DVSignatureHandler::DVSignatureHandler(DVConfiguration& cfg) : htmlSR("<html><head><title>Structured Report</title></head><body>No structured report is currently active.</body></html>\n") , htmlImage("<html><head><title>Image</title></head><body>No image is currently active.</body></html>\n") , htmlPState("<html><head><title>Presentation State</title></head><body>No presentation state is currently active.</body></html>\n") , htmlOverview() , correctSignaturesSR(0) , corruptSignaturesSR(0) , untrustSignaturesSR(0) , correctSignaturesImage(0) , corruptSignaturesImage(0) , untrustSignaturesImage(0) , correctSignaturesPState(0) , corruptSignaturesPState(0) , untrustSignaturesPState(0) #ifdef WITH_OPENSSL , certVerifier() #endif , config(cfg) { #ifdef WITH_OPENSSL int fileFormat = config.getTLSPEMFormat() ? X509_FILETYPE_PEM : X509_FILETYPE_ASN1; const char *tlsCACertificateFolder = config.getTLSCACertificateFolder(); if (tlsCACertificateFolder) certVerifier.addTrustedCertificateDir(tlsCACertificateFolder, fileFormat); #endif updateSignatureValidationOverview(); } DVSignatureHandler::~DVSignatureHandler() { } void DVSignatureHandler::replaceString(DVPSObjectType objtype, const char *str) { switch (objtype) { case DVPSS_structuredReport: if (str) htmlSR=str; else htmlSR.clear(); break; case DVPSS_image: if (str) htmlImage=str; else htmlImage.clear(); break; case DVPSS_presentationState: if (str) htmlPState=str; else htmlPState.clear(); break; } } void DVSignatureHandler::printSignatureItemPosition(DcmStack& stack, STD_NAMESPACE ostream& os) { DcmObject *elem = NULL; DcmSequenceOfItems *sq = NULL; unsigned long sqCard=0; const char *tagname = NULL; unsigned long m=0; char buf[20]; OFBool printed = OFFalse; if (stack.card() > 2) { // signature is located within a sequence for (unsigned long l=stack.card()-2; l>0; --l) // loop over all elements except the stack top and bottom { elem = stack.elem(l); if (elem) { if ((elem->ident() == EVR_item) && sq) { sqCard = sq->card(); for (m=0; m<sqCard; m++) { if (sq->getItem(m) == elem) { sprintf(buf, "[%lu]", m); os << buf; printed = OFTrue; } } } else { if (printed) os << ". "; sq = (DcmSequenceOfItems *)elem; DcmTag currentTag(elem->getTag()); tagname = currentTag.getTagName(); if (tagname) os << tagname; else { sprintf(buf, "(%04x,%04x)", elem->getTag().getGroup(), elem->getTag().getElement()); os << buf; printed = OFTrue; } if (elem->ident() == EVR_SQ) sq = (DcmSequenceOfItems *)elem; else sq = NULL; } } } } else { // signature is located in the main dataset os << "Main Dataset"; } } #ifdef WITH_OPENSSL void DVSignatureHandler::updateDigitalSignatureInformation(DcmItem& dataset, DVPSObjectType objtype, OFBool /* onRead */) #else void DVSignatureHandler::updateDigitalSignatureInformation(DcmItem& /*dataset*/, DVPSObjectType objtype, OFBool /* onRead */) #endif { OFOStringStream os; unsigned long counter = 0; unsigned long corrupt_counter = 0; unsigned long untrustworthy_counter = 0; const char *htmlHead = NULL; const char *htmlFoot = "</body></html>\n\n"; switch (objtype) { case DVPSS_structuredReport: htmlHead = "<html>\n<head><title>Structured Report</title></head><body>\n"; break; case DVPSS_image: htmlHead = "<html>\n<head><title>Image</title></head><body>\n"; break; case DVPSS_presentationState: htmlHead = "<html>\n<head><title>Presentation State</title></head><body>\n"; break; } os << htmlHead; #ifdef WITH_OPENSSL DcmStack stack; OFString aString; DcmAttributeTag at(DCM_DataElementsSigned); DcmTag tag; unsigned long numSignatures = 0; unsigned long l=0; Uint16 macID = 0; DcmTagKey tagkey; const char *tagName = NULL; OFBool nextline; const char *htmlEndl = "</td></tr>\n"; const char *htmlVfyOK = "<tr><td colspan=\"4\" bgcolor=\"#50ff50\">"; const char *htmlVfyCA = "<tr><td colspan=\"4\" bgcolor=\"yellow\">"; const char *htmlVfyErr = "<tr><td colspan=\"4\" bgcolor=\"#FF5050\">"; const char *htmlLine1 = "<tr><td width=\"20\" nowrap>&nbsp;</td><td colspan=\"2\" nowrap>"; const char *htmlLine2 = "<tr><td colspan=\"3\" nowrap>&nbsp;</td><td>"; const char *htmlLine3 = "<tr><td colspan=\"2\" nowrap>&nbsp;</td><td nowrap>"; const char *htmlLine4 = "<tr><td width=\"20\" nowrap>&nbsp;</td><td width=\"20\" nowrap>&nbsp;</td><td>"; const char *htmlNext = "</td><td>"; const char *htmlTableOK = "<table cellspacing=\"0\" bgcolor=\"#D0FFD0\">\n"; const char *htmlTableCA = "<table cellspacing=\"0\" bgcolor=\"#FFF8DC\">\n"; const char *htmlTableErr = "<table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n"; const char *htmlTableE = "</table><p>\n\n"; DcmItem *sigItem = DcmSignature::findFirstSignatureItem(dataset, stack); OFCondition sicond = EC_Normal; DcmSignature signer; while (sigItem) { signer.attach(sigItem); numSignatures = signer.numberOfSignatures(); for (l=0; l<numSignatures; l++) { if (EC_Normal == signer.selectSignature(l)) { ++counter; sicond = signer.verifyCurrent(); SiCertificate *cert = signer.getCurrentCertificate(); if ((sicond == EC_Normal) && cert) { sicond = certVerifier.verifyCertificate(*cert); } if (sicond == EC_Normal) os << htmlTableOK << htmlVfyOK; else if (sicond == SI_EC_VerificationFailed_NoTrust) os << htmlTableCA << htmlVfyCA; else os << htmlTableErr << htmlVfyErr; os << "<b>Signature #" << counter << " UID="; if (EC_Normal == signer.getCurrentSignatureUID(aString)) os << aString.c_str(); else os << "(unknown)"; os << "</b>" << htmlEndl; os << htmlLine1 << "Location" << htmlNext; printSignatureItemPosition(stack, os); os << htmlEndl; os << htmlLine1 << "MAC ID" << htmlNext; if (EC_Normal == signer.getCurrentMacID(macID)) os << macID; else os << "(unknown)"; os << htmlEndl; os << htmlLine1 << "MAC algorithm" << htmlNext; if (EC_Normal == signer.getCurrentMacName(aString)) os << aString.c_str(); else os << "(unknown)"; os << htmlEndl; os << htmlLine1 << "MAC calculation xfer syntax" << htmlNext; if (EC_Normal == signer.getCurrentMacXferSyntaxName(aString)) os << aString.c_str(); else os << "(unknown)"; os << htmlEndl; os << htmlLine1 << "Data elements signed" << htmlNext; nextline = OFFalse; if (EC_Normal == signer.getCurrentDataElementsSigned(at)) { unsigned long atVM = at.getVM(); for (unsigned long n=0; n<atVM; n++) { if (EC_Normal == at.getTagVal(tagkey, n)) { if (nextline) os << htmlLine2; else nextline=OFTrue; os << tagkey << " "; tag = tagkey; tagName = tag.getTagName(); if (tagName) os << tagName; os << htmlEndl; } } } else os << "all elements" << htmlEndl; os << htmlLine1 << "Signature date/time" << htmlNext; if (EC_Normal == signer.getCurrentSignatureDateTime(aString)) os << aString.c_str(); else os << "(unknown)"; os << htmlEndl << htmlLine1 << "Certificate of signer" << htmlNext; if ((cert == NULL)||(cert->getKeyType()==EKT_none)) os << "none" << htmlEndl; else { os << "X.509v" << cert->getX509Version() << htmlEndl; cert->getCertSubjectName(aString); os << htmlLine3 << "Subject" << htmlNext << aString.c_str() << htmlEndl; cert->getCertIssuerName(aString); os << htmlLine3 << "Issued by" << htmlNext << aString.c_str() << htmlEndl << htmlLine3 << "Serial no." << htmlNext << cert->getCertSerialNo() << htmlEndl << htmlLine3 << "Validity" << htmlNext << "not before "; cert->getCertValidityNotBefore(aString); os << aString.c_str() << ", not after "; cert->getCertValidityNotAfter(aString); os << aString.c_str() << htmlEndl << htmlLine4 << "Public key" << htmlNext; switch (cert->getKeyType()) { case EKT_RSA: os << "RSA, " << cert->getCertKeyBits() << " bits" << htmlEndl; break; case EKT_DSA: os << "DSA, " << cert->getCertKeyBits() << " bits" << htmlEndl; break; case EKT_DH: os << "DH, " << cert->getCertKeyBits() << " bits" << htmlEndl; break; case EKT_none: // should never happen os << "none" << htmlEndl; break; } } if (sicond.good()) { os << htmlVfyOK << "<b>Verification: OK</b>" << htmlEndl; } else if (sicond == SI_EC_VerificationFailed_NoTrust) { untrustworthy_counter++; os << htmlVfyCA << "<b>Verification: Signature is valid but certificate could not be verified: " << certVerifier.lastError() << "</b>" << htmlEndl ; } else { corrupt_counter++; os << htmlVfyErr << "<b>Verification: "; os << sicond.text() << "</b>" << htmlEndl; } os << htmlTableE; } } signer.detach(); sigItem = DcmSignature::findNextSignatureItem(dataset, stack); } #endif switch (objtype) { case DVPSS_structuredReport: if (counter == 0) os << "The current structured report does not contain any digital signature." << OFendl; corruptSignaturesSR = corrupt_counter; untrustSignaturesSR = untrustworthy_counter; correctSignaturesSR = counter - corrupt_counter - untrustworthy_counter; break; case DVPSS_image: if (counter == 0) os << "The current image does not contain any digital signature." << OFendl; corruptSignaturesImage = corrupt_counter; untrustSignaturesImage = untrustworthy_counter; correctSignaturesImage = counter - corrupt_counter - untrustworthy_counter; break; case DVPSS_presentationState: if (counter == 0) os << "The current presentation state does not contain any digital signature." << OFendl; corruptSignaturesPState = corrupt_counter; untrustSignaturesPState = untrustworthy_counter; correctSignaturesPState = counter - corrupt_counter - untrustworthy_counter; break; } os << htmlFoot << OFStringStream_ends; OFSTRINGSTREAM_GETSTR(os, newText) replaceString(objtype, newText); // copies newText into OFString OFSTRINGSTREAM_FREESTR(newText) updateSignatureValidationOverview(); return; } void DVSignatureHandler::disableDigitalSignatureInformation(DVPSObjectType objtype) { switch (objtype) { case DVPSS_structuredReport: htmlSR = "<html><head><title>Structured Report</title></head><body>The current structured report does not contain any digital signature.</body></html>\n"; corruptSignaturesSR = 0; untrustSignaturesSR = 0; correctSignaturesSR = 0; break; case DVPSS_image: corruptSignaturesImage = 0; untrustSignaturesImage = 0; correctSignaturesImage = 0; htmlImage = "<html><head><title>Image</title></head><body>The current image does not contain any digital signature.</body></html>\n"; break; case DVPSS_presentationState: corruptSignaturesPState = 0; untrustSignaturesPState = 0; correctSignaturesPState = 0; htmlPState = "<html><head><title>Presentation State</title></head><body>The current presentation state does not contain any digital signature.</body></html>\n"; break; } updateSignatureValidationOverview(); } void DVSignatureHandler::disableImageAndPState() { corruptSignaturesImage = 0; untrustSignaturesImage = 0; correctSignaturesImage = 0; htmlImage = "<html><head><title>Image</title></head><body>No image is currently active.</body></html>\n"; corruptSignaturesPState = 0; untrustSignaturesPState = 0; correctSignaturesPState = 0; htmlPState = "<html><head><title>Presentation State</title></head><body>No presentation state is currently active.</body></html>\n"; updateSignatureValidationOverview(); return; } DVPSSignatureStatus DVSignatureHandler::getCurrentSignatureStatus(DVPSObjectType objtype) const { switch (objtype) { case DVPSS_structuredReport: if ((correctSignaturesSR + corruptSignaturesSR + untrustSignaturesSR) == 0) return DVPSW_unsigned; if ((corruptSignaturesSR + untrustSignaturesSR) == 0) return DVPSW_signed_OK; if (corruptSignaturesSR == 0) return DVPSW_signed_unknownCA; break; case DVPSS_image: if ((correctSignaturesImage + corruptSignaturesImage + untrustSignaturesImage) == 0) return DVPSW_unsigned; if ((corruptSignaturesImage + untrustSignaturesImage) == 0) return DVPSW_signed_OK; if (corruptSignaturesImage == 0) return DVPSW_signed_unknownCA; break; case DVPSS_presentationState: if ((correctSignaturesPState + corruptSignaturesPState + untrustSignaturesPState) == 0) return DVPSW_unsigned; if ((corruptSignaturesPState + untrustSignaturesPState) == 0) return DVPSW_signed_OK; if (corruptSignaturesPState == 0) return DVPSW_signed_unknownCA; break; } return DVPSW_signed_corrupt; } DVPSSignatureStatus DVSignatureHandler::getCombinedImagePStateSignatureStatus() const { DVPSSignatureStatus statImage = getCurrentSignatureStatus(DVPSS_image); DVPSSignatureStatus statPState = getCurrentSignatureStatus(DVPSS_presentationState); if ((statImage == DVPSW_signed_corrupt)||(statPState == DVPSW_signed_corrupt)) return DVPSW_signed_corrupt; if ((statImage == DVPSW_signed_unknownCA)||(statPState == DVPSW_signed_unknownCA)) return DVPSW_signed_unknownCA; if ((statImage == DVPSW_signed_OK)&&(statPState == DVPSW_signed_OK)) return DVPSW_signed_OK; return DVPSW_unsigned; } const char *DVSignatureHandler::getCurrentSignatureValidationHTML(DVPSObjectType objtype) const { const char *result = ""; switch (objtype) { case DVPSS_structuredReport: result = htmlSR.c_str(); break; case DVPSS_image: result = htmlImage.c_str(); break; case DVPSS_presentationState: result = htmlPState.c_str(); break; } return result; } void DVSignatureHandler::updateSignatureValidationOverview() { const char *htmlHead = "<html>\n<head><title>Overview</title></head><body>\n"; const char *htmlFoot = "</body></html>\n\n"; const char *htmlEndl = "</td></tr>\n"; const char *htmlTitle = "<tr><td colspan=\"3\">"; const char *htmlVfyUns = "<tr><td colspan=\"3\" bgcolor=\"#A0A0A0\">"; const char *htmlVfySig = "<tr><td colspan=\"3\" bgcolor=\"#50ff50\">"; const char *htmlVfyCA = "<tr><td colspan=\"3\" bgcolor=\"yellow\">"; const char *htmlVfyErr = "<tr><td colspan=\"3\" bgcolor=\"#FF5050\">"; const char *htmlLine1 = "<tr><td width=\"20\" nowrap>&nbsp;</td><td nowrap>"; const char *htmlNext = "</td><td>"; const char *htmlTableUns = "<p><table cellspacing=\"0\" bgcolor=\"#E0E0E0\">\n"; const char *htmlTableSig = "<p><table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n"; const char *htmlTableCA = "<p><table cellspacing=\"0\" bgcolor=\"#FFF8DC\">\n"; const char *htmlTableErr = "<p><table cellspacing=\"0\" bgcolor=\"#FFD0D0\">\n"; const char *htmlTableE = "</table></p>\n\n"; OFOStringStream os; DVPSSignatureStatus status; os << htmlHead; // Structured Report status = getCurrentSignatureStatus(DVPSS_structuredReport); switch (status) { case DVPSW_unsigned: os << htmlTableUns; break; case DVPSW_signed_OK: os << htmlTableSig; break; case DVPSW_signed_unknownCA: os << htmlVfyCA; break; case DVPSW_signed_corrupt: os << htmlTableErr; break; } os << htmlTitle << "<b>Structured Report</b>"<< htmlEndl; os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesSR << htmlEndl; os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesSR << htmlEndl; os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesSR << htmlEndl; switch (status) { case DVPSW_unsigned: os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl; break; case DVPSW_signed_OK: os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl; break; case DVPSW_signed_unknownCA: os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl; break; case DVPSW_signed_corrupt: os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl; break; } os << htmlTableE; // Image status = getCurrentSignatureStatus(DVPSS_image); switch (status) { case DVPSW_unsigned: os << htmlTableUns; break; case DVPSW_signed_OK: os << htmlTableSig; break; case DVPSW_signed_unknownCA: os << htmlTableCA; break; case DVPSW_signed_corrupt: os << htmlTableErr; break; } os << htmlTitle << "<b>Image</b>"<< htmlEndl; os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesImage << htmlEndl; os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesImage << htmlEndl; os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesImage << htmlEndl; switch (status) { case DVPSW_unsigned: os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl; break; case DVPSW_signed_OK: os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl; break; case DVPSW_signed_unknownCA: os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl; break; case DVPSW_signed_corrupt: os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl; break; } os << htmlTableE; // Presentation State status = getCurrentSignatureStatus(DVPSS_presentationState); switch (status) { case DVPSW_unsigned: os << htmlTableUns; break; case DVPSW_signed_OK: os << htmlTableSig; break; case DVPSW_signed_unknownCA: os << htmlTableCA; break; case DVPSW_signed_corrupt: os << htmlTableErr; break; } os << htmlTitle << "<b>Presentation State</b>"<< htmlEndl; os << htmlLine1 << "Number of correct signatures" << htmlNext << correctSignaturesPState << htmlEndl; os << htmlLine1 << "Number of corrupt signatures" << htmlNext << corruptSignaturesPState << htmlEndl; os << htmlLine1 << "Number of untrusted signatures" << htmlNext << untrustSignaturesPState << htmlEndl; switch (status) { case DVPSW_unsigned: os << htmlVfyUns << "<b>Status: unsigned</b>" << htmlEndl; break; case DVPSW_signed_OK: os << htmlVfySig << "<b>Status: signed</b>" << htmlEndl; break; case DVPSW_signed_unknownCA: os << htmlVfyCA << "<b>Status: signed but untrustworthy: certificate could not be verified</b>" << htmlEndl; break; case DVPSW_signed_corrupt: os << htmlVfyErr << "<b>Status: contains corrupt signatures</b>" << htmlEndl; break; } os << htmlTableE; os << htmlFoot << OFStringStream_ends; OFSTRINGSTREAM_GETSTR(os, newText) htmlOverview = newText; OFSTRINGSTREAM_FREESTR(newText) return; } const char *DVSignatureHandler::getCurrentSignatureValidationOverview() const { return htmlOverview.c_str(); } unsigned long DVSignatureHandler::getNumberOfCorrectSignatures(DVPSObjectType objtype) const { unsigned long result = 0; switch (objtype) { case DVPSS_structuredReport: result = correctSignaturesSR; break; case DVPSS_image: result = correctSignaturesImage; break; case DVPSS_presentationState: result = correctSignaturesPState; break; } return result; } unsigned long DVSignatureHandler::getNumberOfUntrustworthySignatures(DVPSObjectType objtype) const { unsigned long result = 0; switch (objtype) { case DVPSS_structuredReport: result = untrustSignaturesSR; break; case DVPSS_image: result = untrustSignaturesImage; break; case DVPSS_presentationState: result = untrustSignaturesPState; break; } return result; } unsigned long DVSignatureHandler::getNumberOfCorruptSignatures(DVPSObjectType objtype) const { unsigned long result = 0; switch (objtype) { case DVPSS_structuredReport: result = corruptSignaturesSR; break; case DVPSS_image: result = corruptSignaturesImage; break; case DVPSS_presentationState: result = corruptSignaturesPState; break; } return result; } #ifdef WITH_OPENSSL OFBool DVSignatureHandler::attributesSigned(DcmItem& item, DcmAttributeTag& tagList) const { DcmStack stack; DcmAttributeTag at(DCM_DataElementsSigned); DcmTagKey tagkey; DcmSignature signer; unsigned long numSignatures; unsigned long l; DVSignatureHandlerSignatureProfile sigProfile(tagList); DcmItem *sigItem = DcmSignature::findFirstSignatureItem(item, stack); while (sigItem) { if (sigItem == &item) { // signatures on main level - check attributes signed signer.attach(sigItem); numSignatures = signer.numberOfSignatures(); for (l=0; l<numSignatures; l++) { if (EC_Normal == signer.selectSignature(l)) { // printSignatureItemPosition(stack, os); if (EC_Normal == signer.getCurrentDataElementsSigned(at)) { unsigned long atVM = at.getVM(); for (unsigned long n=0; n<atVM; n++) { if (EC_Normal == at.getTagVal(tagkey, n)) { if (sigProfile.tagInList(tagkey)) return OFTrue; // one of the elements in tagList is signed } } } else return OFTrue; // all elements are signed } } signer.detach(); } else { // signatures on lower level - check whether attribute on main level is in list unsigned long scard = stack.card(); if (scard > 1) // should always be true { DcmObject *obj = stack.elem(scard-2); if (obj) // should always be true { if (sigProfile.tagInList(obj->getTag())) return OFTrue; // one of the elements in tagList contains a signature } } } sigItem = DcmSignature::findNextSignatureItem(item, stack); } return OFFalse; } #else OFBool DVSignatureHandler::attributesSigned(DcmItem& /* item */, DcmAttributeTag& /* tagList */) const { return OFFalse; } #endif #ifdef WITH_OPENSSL OFCondition DVSignatureHandler::createSignature( DcmItem& mainDataset, const DcmStack& itemStack, DcmAttributeTag& attributesNotToSignInMainDataset, const char *userID, const char *passwd) { if (userID == NULL) return EC_IllegalCall; // get user settings int fileformat = config.getTLSPEMFormat() ? X509_FILETYPE_PEM : X509_FILETYPE_ASN1; const char *userDir = config.getUserCertificateFolder(); const char *userKey = config.getUserPrivateKey(userID); if (userKey == NULL) return EC_IllegalCall; const char *userCert = config.getUserCertificate(userID); if (userCert == NULL) return EC_IllegalCall; // load private key SiPrivateKey key; OFString filename; if (userDir) { filename = userDir; filename += PATH_SEPARATOR; } filename += userKey; if (passwd) key.setPrivateKeyPasswd(passwd); OFCondition sicond = key.loadPrivateKey(filename.c_str(), fileformat); if (sicond != EC_Normal) return EC_IllegalCall; // unable to load private key // load certificate SiCertificate cert; filename.clear(); if (userDir) { filename = userDir; filename += PATH_SEPARATOR; } filename += userCert; sicond = cert.loadCertificate(filename.c_str(), fileformat); if (sicond != EC_Normal) return EC_IllegalCall; // unable to load certificate if (! key.matchesCertificate(cert)) return EC_IllegalCall; // private key does not match certificate DcmSignature signer; SiRIPEMD160 mac; SiNullProfile nullProfile; DVSignatureHandlerSignatureProfile mainProfile(attributesNotToSignInMainDataset); DcmObject *current; DcmItem *currentItem; DcmStack workStack(itemStack); while (! workStack.empty()) { current = workStack.pop(); if ((current->ident() != EVR_dataset) && (current->ident() != EVR_item)) return EC_IllegalCall; // wrong type on stack currentItem = (DcmItem *)current; signer.attach(currentItem); if (currentItem == &mainDataset) { // we're creating a signature in the main dataset // we have to establish an explicit tag list, otherwise the profile does not work! DcmAttributeTag tagList(DCM_DataElementsSigned); unsigned long numAttributes = currentItem->card(); for (unsigned long l=0; l<numAttributes; l++) { tagList.putTagVal(currentItem->getElement(l)->getTag(),l); } sicond = signer.createSignature(key, cert, mac, mainProfile, EXS_LittleEndianExplicit, &tagList); if (sicond != EC_Normal) return EC_IllegalCall; // error while creating signature } else { // we're creating a signature in a sequence item sicond = signer.createSignature(key, cert, mac, nullProfile, EXS_LittleEndianExplicit); if (sicond != EC_Normal) return EC_IllegalCall; // error while creating signature } signer.detach(); } return EC_Normal; } #else OFCondition DVSignatureHandler::createSignature( DcmItem& /* mainDataset */, const DcmStack& /* itemStack */, DcmAttributeTag& /* attributesNotToSignInMainDataset */, const char * /* userID */, const char * /* passwd */) { return EC_IllegalCall; } #endif
NCIP/annotation-and-image-markup
AIMToolkit_v4.0.0_rv44/source/dcmtk-3.6.1_20121102/dcmpstat/libsrc/dvsighdl.cc
C++
bsd-3-clause
28,925
/** * View abstract class * * @author Mautilus s.r.o. * @class View * @abstract * @mixins Events * @mixins Deferrable */ function View() { Events.call(this); Deferrable.call(this); this.construct.apply(this, arguments); }; View.prototype.__proto__ = Events.prototype; View.prototype.__proto__.__proto__ = Deferrable.prototype; /** * Construct object * * @constructor * @param {String} [parent=null] Another View instance this view belongs to * @param {Object} [attributes={}] Object attrs */ View.prototype.construct = function(parent, attributes) { if (typeof attributes === 'undefined' && parent && !parent.construct) { // parent is not provided, but attributes are attributes = $.extend(true, {}, parent); parent = null; } /** * @property {Object} parent Parent snippet or scene */ this.parent = parent; this.reset(attributes); this.$el = this.create(); if (this.id) { this.$el.attr('id', this.id); } if (this.cls) { this.$el.addClass(this.cls); } this.init.apply(this, arguments); this.bindEvents(); }; /** * Destruct object * * @private */ View.prototype.desctruct = function() { this.deinit.apply(this, arguments); this.destroy(); }; /** * Set focus to the scene * * @template */ View.prototype.focus = function() { }; /** * Reset properties * * @param {Object} [attributes] Object attrs */ View.prototype.reset = function(attributes) { this.isVisible = false; this.isActive = false; if (attributes) { this.setAttributes(attributes); } }; /** * Set object properties, functions and attributes that start with '_' are not allowed * * @param {Object} attributes */ View.prototype.setAttributes = function(attributes) { for (var i in attributes) { if (typeof attributes[i] !== 'undefined' && typeof attributes[i] !== 'function' && typeof this[i] !== 'fucntion' && i.substr(0, 1) !== '_') { this[i] = attributes[i]; } } }; /** * Bind listeners to the `key` event and some others */ View.prototype.bindEvents = function() { if (this.parent) { this.parent.on('key', this._onKey, this); this.parent.on('click', this._onClick, this); this.parent.on('scroll', this._onScroll, this); this.parent.on('focus', this._onFocus, this); } else { Control.on('key', this._onKey, this); Mouse.on('click', this._onClick, this); Mouse.on('scroll', this._onScroll, this); Focus.on('focus', this._onFocus, this); } I18n.on('langchange', this._onLangChange, this); }; /** * Un-bind all default listeners */ View.prototype.unbindEvents = function() { if (this.parent) { this.parent.off('key', this._onKey, this); this.parent.off('click', this._onClick, this); this.parent.off('scroll', this._onScroll, this); this.parent.off('focus', this._onFocus, this); } else { Control.off('key', this._onKey, this); Mouse.off('click', this._onClick, this); Mouse.off('scroll', this._onScroll, this); Focus.off('focus', this._onFocus, this); } I18n.off('langchange', this._onLangChange, this); }; /** * Create scene's element, is called when scene is being constructed * * @template * @returns {Object} Element, jQuery collection */ View.prototype.create = function() { return $('<div />'); }; /** * Remove scene's elements when scene is hiding * * @template */ View.prototype.remove = function() { }; /** * Remove or hide scene's element, is called when scene is being destructed * * @template * @return {Boolean/Promise} Return FALSE when you don't want to hide this scene, Promise may be also returned */ View.prototype.destroy = function() { }; /** * Initialise scene * * @template */ View.prototype.init = function() { }; /** * De-initialise scene * * @template */ View.prototype.deinit = function() { }; /** * Activate and focus scene when its shown * * @template * @return {Boolean/Promise} Return FALSE when you don't want to show this scene, Promise may be also returned */ View.prototype.activate = function() { }; /** * Deactivate scene when its hidden * * @template * @return {Boolean} Return FALSE when you don't want to destroy this scene when its hidden */ View.prototype.deactivate = function() { }; /** * This method is called when and 'activate' method fails * * @template * @return {Boolean} If TRUE is returned, router will call goBack (default action) */ View.prototype.revert = function() { return true; }; /** * Render snippet * * @template * @return {Promise} */ View.prototype.render = function() { }; /** * Render snippet into specified target element * * @param {Object} target jQuery collection or HTMLElement */ View.prototype.renderTo = function(target) { var p; this.$el.appendTo(target); p = this.render(); if (p instanceof Promise) { p.done(function() { this.show(); }, this); } else { this.show(); } return p; }; /** * Display scene's element and set `this.isVisible` to TRUE */ View.prototype.show = function() { var args = arguments; return this.when(function(promise) { var activated; if (this.onBeforeShow() === false) { promise.reject(); return false; } this.$el.show(); this.isVisible = true; this.isActive = false; this.onShow(); this.trigger('show'); promise.fail(function() { this.hide(); }, this); activated = this.activate.apply(this, args); if (activated instanceof Promise) { activated.then(function(status) { this.isActive = status; if (status) { promise.resolve(); } else { promise.reject(); } }, this); } else if (activated !== false) { this.isActive = true; promise.resolve(); } else { this.isActive = false; promise.reject(); } }, this); }; /** * Fired before the view is being shown and before `activate` method * * @template * @return {Boolean} */ View.prototype.onBeforeShow = function() { }; /** * Fired when this view is displayed * * @template */ View.prototype.onShow = function() { }; /** * Hide scene's element and set `this.isVisible` to FALSE */ View.prototype.hide = function() { return this.when(function(promise) { var deactivated; promise.done(function() { this.onBeforeHide(); this.$el.hide(); this.isVisible = false; this.onHide(); this.trigger('hide'); }, this); deactivated = this.deactivate(); if (deactivated instanceof Promise) { deactivated.then(function(status) { if (status) { this.isActive = false; promise.resolve(); } else { promise.reject(); } }, this); } else if (deactivated !== false) { this.isActive = false; promise.resolve(); } else { promise.reject(); } }, this); }; /** * Fired before the view is being hidden but after `deactivate` method (no return value) * * @template */ View.prototype.onBeforeHide = function() { }; /** * Fired when this view is hidden * * @template */ View.prototype.onHide = function() { }; /** * Test if this scene has focus (or any snippet inside this scene) * * @returns {Boolean} */ View.prototype.hasFocus = function() { return Focus.isIn(this.$el); }; /** * @private */ View.prototype._onKey = function(keyCode, ev, stop) { if (!this.isVisible || !this.hasFocus()) { return; } if (this.trigger('beforekey', keyCode, ev) === false) { return false; } if (this.onKey(keyCode, ev, stop) === false) { return false; } if (Control.isArrow(keyCode) && this.navigate(Control.getArrow(keyCode), stop) === false) { return false; } if (keyCode === Control.key.ENTER && this.onEnter(Focus.focused, ev, stop) === false) { return false; } else if (keyCode === Control.key.RETURN && this.onReturn(Focus.focused, ev, stop) === false) { return false; } if (this.trigger('key', keyCode, ev) === false) { return false; } }; /** * Handles keyDown events * * @template * @param {Number} keyCode * @param {Event} event * @param {Function} stop * @returns {Boolean} */ View.prototype.onKey = function(keyCode, ev, stop) { }; /** * Handles ENTER event * * @template * @param {Object} $el Target element, jQuery collection * @param {Event} event * @returns {Boolean} */ View.prototype.onEnter = function($el, event) { }; /** * Handles RETURN event * * @template * @param {Object} $el Target element, jQuery collection * @param {Event} event * @returns {Boolean} */ View.prototype.onReturn = function($el, event) { }; /** * @private */ View.prototype._onClick = function($el, event) { if (!$el.belongsTo(this.$el)) { return; } if (this.onClick.apply(this, arguments) === false) { return false; } return this.trigger('click', $el, event); }; /** * Handles Click event * * @param {Object} $el Target element, jQuery collection * @param {Event} event Mouse event * @returns {Boolean} */ View.prototype.onClick = function($el, event) { }; /** * @private */ View.prototype._onScroll = function($el, delta, event) { if (!$el.belongsTo(this.$el)) { return; } if (this.onScroll.apply(this, arguments) === false) { return false; } return this.trigger('scroll', $el, delta, event); }; /** * Handles Scroll event when this scene is visible * * @param {Object} $el Target element, jQuery collection * @param {Number} delta, 1 or -1 * @param {Event} event Mouse event * @returns {Boolean} */ View.prototype.onScroll = function($el, delta, event) { }; /** * @private */ View.prototype._onFocus = function($el) { if (!$el.belongsTo(this.$el)) { return; } if (this.onFocus.apply(this, arguments) === false) { return false; } return this.trigger('focus', $el); }; /** * Handles Focus event * * @template * @param {Object} $el Target element, jQuery collection * @returns {Boolean} */ View.prototype.onFocus = function($el) { }; /** * @private */ View.prototype._onLangChange = function() { if (this.onLangChange.apply(this, arguments) === false) { return false; } this.trigger('langchange'); }; /** * When app language is changed * * @template * @returns {Boolean} */ View.prototype.onLangChange = function() { }; /** * Navigate in 4-way direction * * @template * @param {String} direction Possible values: 'left', 'right', 'up', 'down' * @param {Function} stop * @return {Boolean} Return FALSE to prevent event from bubeling */ View.prototype.navigate = function(direction, stop) { }; /** * Get all focusable elements inside this snippet. This takes currentyl focused * element and calculates new one. If the new sibling is not exits, new focus * is getting from the start / end of collection - cyclic. * * Is the same like getFocusable, but you can specify parent and also you can * walkthrough all elements in cyclic. * * @param {Number} direction left is equal to -1, right to 1 * @param {Object} parent jquery object. All focusable elements belongs only to this parent. * @returns {Object} jQuery collection */ View.prototype.getCircleFocusable = function(direction, parent) { var els = $('.focusable', parent || this.$el).not('.disabled').filter(':visible'), focusedIndex = Focus.focused ? els.index(Focus.focused) : -1; if (focusedIndex !== -1) { focusedIndex += direction; if (focusedIndex === -1) return els.eq(els.length - 1); else if (focusedIndex > els.length - 1) return els.eq(0); else return els.eq(focusedIndex); } }; /** * Get all focusable elements inside this scene * * @param {Number} [index] If specified, then returns only one element at the specified position * @param {Boolean} [fromCurrentlyFocused=false] If TRUE, than elements before focused element are cut off * @param {Object} [$el=this.$el] Limit search for just this specified element, jQuery collection * @param {String} [selector=.focusable] * @returns {Object} jQuery collection */ View.prototype.getFocusable = function(index, fromCurrentlyFocused, $el, selector) { var els, focusedIndex, _index = index; if (!selector) { selector = '.focusable'; } els = $(selector, $el || this.$el).filter(':visible').not('.disabled'); if (fromCurrentlyFocused) { if(typeof fromCurrentlyFocused === 'boolean'){ focusedIndex = Focus.focused ? els.index(Focus.focused) : -1; } else { focusedIndex = els.index(fromCurrentlyFocused); } if (typeof index !== 'undefined' && _index < 0) { els = els.slice(0, (focusedIndex >= 0 ? focusedIndex : 1)); //_index += els.length; } else { els = els.slice(focusedIndex >= 0 ? focusedIndex : 0); } } if (typeof _index !== 'undefined') { return els.eq(_index >> 0); } return els; }; /** * Convert View into string * * @returns {String} */ View.prototype.toString = function() { this.render(); return this.$el[0].outerHTML; };
wdoganowski/inio-tvapp
framework/view.js
JavaScript
bsd-3-clause
12,630
'use strict'; describe('Registry', function() { describe('create()', function() { it('name', function() { let blot = Registry.create('bold'); expect(blot instanceof BoldBlot).toBe(true); expect(blot.statics.blotName).toBe('bold'); }); it('node', function() { let node = document.createElement('strong'); let blot = Registry.create(node); expect(blot instanceof BoldBlot).toBe(true); expect(blot.statics.blotName).toBe('bold'); }); it('block', function() { let blot = Registry.create(Registry.Scope.BLOCK_BLOT); expect(blot instanceof BlockBlot).toBe(true); expect(blot.statics.blotName).toBe('block'); }); it('inline', function() { let blot = Registry.create(Registry.Scope.INLINE_BLOT); expect(blot instanceof InlineBlot).toBe(true); expect(blot.statics.blotName).toBe('inline'); }); it('string index', function() { let blot = Registry.create('header', '2'); expect(blot instanceof HeaderBlot).toBe(true); expect(blot.formats()).toEqual({ header: 'h2' }); }); it('invalid', function() { expect(function() { Registry.create(BoldBlot); }).toThrowError(/\[Parchment\]/); }); }); describe('register()', function() { it('invalid', function() { expect(function() { Registry.register({}); }).toThrowError(/\[Parchment\]/); }); it('abstract', function() { expect(function() { Registry.register(ShadowBlot); }).toThrowError(/\[Parchment\]/); }); }); describe('find()', function() { it('exact', function() { let blockNode = document.createElement('p'); blockNode.innerHTML = '<span>01</span><em>23<strong>45</strong></em>'; let blockBlot = Registry.create(blockNode); expect(Registry.find(document.body)).toBeFalsy(); expect(Registry.find(blockNode)).toBe(blockBlot); expect(Registry.find(blockNode.querySelector('span'))).toBe(blockBlot.children.head); expect(Registry.find(blockNode.querySelector('em'))).toBe(blockBlot.children.tail); expect(Registry.find(blockNode.querySelector('strong'))).toBe( blockBlot.children.tail.children.tail, ); let text01 = blockBlot.children.head.children.head; let text23 = blockBlot.children.tail.children.head; let text45 = blockBlot.children.tail.children.tail.children.head; expect(Registry.find(text01.domNode)).toBe(text01); expect(Registry.find(text23.domNode)).toBe(text23); expect(Registry.find(text45.domNode)).toBe(text45); }); it('bubble', function() { let blockBlot = Registry.create('block'); let textNode = document.createTextNode('Test'); blockBlot.domNode.appendChild(textNode); expect(Registry.find(textNode)).toBeFalsy(); expect(Registry.find(textNode, true)).toEqual(blockBlot); }); it('detached parent', function() { let blockNode = document.createElement('p'); blockNode.appendChild(document.createTextNode('Test')); expect(Registry.find(blockNode.firstChild)).toBeFalsy(); expect(Registry.find(blockNode.firstChild, true)).toBeFalsy(); }); }); describe('query()', function() { it('class', function() { let node = document.createElement('em'); node.setAttribute('class', 'author-blot'); expect(Registry.query(node)).toBe(AuthorBlot); }); it('type mismatch', function() { let match = Registry.query('italic', Registry.Scope.ATTRIBUTE); expect(match).toBeFalsy(); }); it('level mismatch for blot', function() { let match = Registry.query('italic', Registry.Scope.BLOCK); expect(match).toBeFalsy(); }); it('level mismatch for attribute', function() { let match = Registry.query('color', Registry.Scope.BLOCK); expect(match).toBeFalsy(); }); it('either level', function() { let match = Registry.query('italic', Registry.Scope.BLOCK | Registry.Scope.INLINE); expect(match).toBe(ItalicBlot); }); it('level and type match', function() { let match = Registry.query('italic', Registry.Scope.INLINE & Registry.Scope.BLOT); expect(match).toBe(ItalicBlot); }); it('level match and type mismatch', function() { let match = Registry.query('italic', Registry.Scope.INLINE & Registry.Scope.ATTRIBUTE); expect(match).toBeFalsy(); }); it('type match and level mismatch', function() { let match = Registry.query('italic', Registry.Scope.BLOCK & Registry.Scope.BLOT); expect(match).toBeFalsy(); }); }); });
quilljs/parchment
test/unit/registry.js
JavaScript
bsd-3-clause
4,631
/*-------------------------------------------------------- * Copyright (c) 2011, The Dojo Foundation * This software is distributed under the "Simplified BSD license", * the text of which is available at http://www.winktoolkit.org/licence.txt * or see the "license.txt" file for more details. *--------------------------------------------------------*/ /** * @fileOverview Implements an image opener. Creates an "image opener" with a 3D rendering * * @author Jerome GIRAUD */ /** * The event is fired when someone clicks on the image * * @name wink.ui.xyz.Opener#/opener/events/click * @event * @param {object} param The parameters object * @param {integer} param.openerId uId of the opener */ define(['../../../../_amd/core', '../../../../math/_geometric/js/geometric', '../../../../fx/_xyz/js/3dfx'], function(wink) { /** * @class Implements an image opener. Creates an "image opener" with a 3D rendering. * Define the image you want to see as the opener's background. Use the "getDomNode" method to insert the opener into the page. * * @param {object} properties The properties object * @param {string} properties.image The URL of the image to display * @param {integer} properties.height The height of the opener (should be the same as the image height) * @param {integer} properties.width The width of the opener (should be the same as the image width) * @param {integer} [properties.panelHeight=20] The height of each panel. The image is divided into X panels * @param {integer} [properties.panelsAngle=140] The winding angle of the opener * @param {integer} [properties.openerXAngle=10] The angle between the opener and the page on the X-axis * @param {integer} [properties.openerYAngle=15] The angle between the opener and the page on the Y-axis * @param {integer} [properties.duration=500] The opening duration in milliseconds * * @requires wink.math._geometric * @requires wink.math._matrix * @requires wink.fx._xyz * * @example * * var properties = * { * 'image': './img/wink.png', * 'height': 185, * 'width': 185, * 'panelsAngle': 200, * 'panelHeight': 5, * 'openerXAngle': 5, * 'openerYAngle': -50, * 'duration': 300 * } * * opener = new wink.ui.xyz.Opener(properties); * wink.byId('content').appendChild(opener.getDomNode()); * * @compatibility iOS2, iOS3, iOS4, iOS5, iOS6, Android 3.0, Android 3.1, Android 4.0, Android 4.1.2, BlackBerry 7, BB10 * * @see <a href="WINK_ROOT_URL/ui/xyz/opener/test/test_opener_1.html" target="_blank">Test page</a> * @see <a href="WINK_ROOT_URL/ui/xyz/opener/test/test_opener_2.html" target="_blank">Test page</a> */ wink.ui.xyz.Opener = function(properties) { /** * Unique identifier * * @property uId * @type integer */ this.uId = wink.getUId(); /** * True if the image is "opened", false otherwise * * @property opened * @type boolean */ this.opened = false; /** * The URL of the opener image * * @property image * @type string */ this.image = null; /** * The height of the opener * * @property height * @type integer */ this.height = 0; /** * The width of the opener * * @property width * @type integer */ this.width = 0; /** * The height of each panel * * @property panelHeight * @type integer */ this.panelHeight = 20; /** * The winding angle of the opener * * @property panelsAngle * @type integer */ this.panelsAngle = 140; /** * The angle between the opener and the page on the X-axis * * @property openerXAngle * @type integer */ this.openerXAngle = 10; /** * The angle between the opener and the page on the Y-axis * * @property the angle between the opener and the page on the Y-axis * @type integer */ this.openerYAngle = 15; /** * the opening duration in milliseconds * * @property duration * @type integer */ this.duration = 500; this._nbPanels = 0; this._panelAngle = 0; this._panelsList = []; this._domNode = null; this._panelsNode = null; this._contentNode = null; wink.mixin(this, properties); if ( this._validateProperties() === false )return; this._initProperties(); this._initDom(); this._initListeners(); }; wink.ui.xyz.Opener.prototype = { /** * @returns {HTMLElement} The dom node containing the Opener */ getDomNode: function() { return this._domNode; }, /** * Opens the image */ open: function() { wink.fx.initComposedTransform(this._panelsNode, false); wink.fx.setTransformPart(this._panelsNode, 1, { type: 'rotate', x: 0, y: 1, z: 0, angle: this.openerYAngle }); wink.fx.setTransformPart(this._panelsNode, 2, { type: 'rotate', x: 1, y: 0, z: 0, angle: this.openerXAngle }); wink.fx.applyComposedTransform(this._panelsNode); this._domNode.style['height'] = '0px'; var l = this._panelsList.length; for ( var i = l-1; i > 0; i-- ) { this._panelsList[i].open(); } this.opened = true; }, /** * Closes the image */ close: function() { wink.fx.setTransformPart(this._panelsNode, 1, { type: 'rotate', x: 0, y: 1, z: 0, angle: 0 }); wink.fx.setTransformPart(this._panelsNode, 2, { type: 'rotate', x: 1, y: 0, z: 0, angle: 0 }); wink.fx.applyComposedTransform(this._panelsNode); this._domNode.style['height'] = 'auto'; var l = this._panelsList.length; for ( var i = l-1; i > 0; i-- ) { this._panelsList[i].close(); } this.opened = false; }, /** * Toggles the image display */ toggle: function() { if ( this.opened ) { this.close(); } else { this.open(); } }, /** * Handles the click events */ _handleClick: function() { this.toggle(); wink.publish('/opener/events/click', {'openerId': this.uId}); }, /** * Validate the properties of the component * @returns {boolean} True if the properties are valid, false otherwise */ _validateProperties: function() { // Check duration if ( !wink.isInteger(this.duration) ) { wink.log('[Opener] The property duration must be an integer'); return false; } // Check opener X angle if ( !wink.isInteger(this.openerXAngle) ) { wink.log('[Opener] The property openerXAngle must be an integer'); return false; } // Check opener Y angle if ( !wink.isInteger(this.openerYAngle) ) { wink.log('[Opener] The property openerYAngle must be an integer'); return false; } // Check panel angle if ( !wink.isInteger(this.panelsAngle) ) { wink.log('[Opener] The property panelsAngle must be an integer'); return false; } // Check panelHeight if ( !wink.isInteger(this.panelHeight) ) { wink.log('[Opener] The property panelHeight must be an integer'); return false; } // Check height if ( !wink.isInteger(this.height) ) { wink.log('[Opener] The property height must be an integer'); return false; } // Check width if ( !wink.isInteger(this.width) ) { wink.log('[Opener] The property width must be an integer'); return false; } // Check image if ( !wink.isSet(this.image) ) { wink.log('[Opener] The property image must be set'); return false; } return true; }, /** * Initialize the 'click' listener */ _initListeners: function() { wink.subscribe('/opener_panel/events/click', {context: this, method: '_handleClick'}); }, /** * Initialize the Opener properties */ _initProperties: function() { this._nbPanels = Math.ceil(this.height / this.panelHeight); this._panelAngle = this.panelsAngle / this._nbPanels; }, /** * Initialize the Opener DOM nodes */ _initDom: function() { this._domNode = document.createElement('div'); this._domNode.className = 'op_container'; wink.fx.apply(this._domNode, { height: this.height + 'px', width: this.width + 'px' }); this._panelsNode = document.createElement('div'); this._panelsNode.className = 'op_panels'; wink.fx.apply(this._panelsNode, {'transform-origin': '100% 0', 'transform-style': 'preserve-3d'}); for ( var i=0; i<this._nbPanels; i++ ) { var panel = new wink.ui.xyz.Opener.Panel({index: i, image: this.image, height: this.panelHeight, angle: this._panelAngle}); this._panelsList.push(panel); this._panelsNode.appendChild(panel.getDomNode()); wink.fx.applyTransformTransition(panel.getDomNode(), this.duration + 'ms', '0ms', 'linear'); } this._domNode.appendChild(this._panelsNode); wink.fx.applyTransformTransition(this._panelsNode, this.duration + 'ms', '0ms', 'linear'); } }; /** * @class Implements an image opener panel. Should only be instantiated by the Opener itself * * @param {object} properties The properties object * @param {integer} properties.index The position of the panel in the panels list * @param {string} properties.image The URL of the image to display * @param {integer} properties.height The height of the panel * @param {integer} properties.angle The opening angle of the panel * */ wink.ui.xyz.Opener.Panel = function(properties) { /** * Unique identifier * * @property uId * @type integer */ this.uId = wink.getUId(); /** * The position of the panel * * @property index * @type integer */ this.index = null; /** * The URL of the image to display * * @property image * @type string */ this.image = null; /** * The height of the panel * * @property height * @type integer */ this.height = 0; /** * The opening angle of the panel * * @property angle * @type integer */ this.angle = 0; this._y = 0; this._z = 0; this._domNode = null; wink.mixin(this, properties); this._initProperties(); this._initDom(); }; /** * The event is fired when someone clicks on the panel * * @name wink.ui.xyz.Opener#/opener_panel/events/click * @event * @param {object} param The parameters object * @param {integer} param.panelId uId of the panel */ wink.ui.xyz.Opener.Panel.prototype = { /** * @returns {HTMLElement} The component main dom node */ getDomNode: function() { return this._domNode; }, /** * Opens the image */ open: function() { wink.fx.initComposedTransform(this._domNode, false); wink.fx.setTransformPart(this._domNode, 1, { type: 'rotate', x: 1, y: 0, z: 0, angle: (this.angle*(this.index)) }); wink.fx.setTransformPart(this._domNode, 2, { type: 'translate', x: 0, y: this._y, z: this._z }); wink.fx.applyComposedTransform(this._domNode); }, /** * Closes the image */ close: function() { wink.fx.setTransformPart(this._domNode, 1, { type: 'rotate', x: 1, y: 0, z: 0, angle: 0 }); wink.fx.setTransformPart(this._domNode, 2, { type: 'translate', x: 0, y: (this.index * this.height), z: 0 }); wink.fx.applyComposedTransform(this._domNode); }, /** * Initialize the Panel properties */ _initProperties: function() { for ( var i=0; i<this.index; i++ ) { this._y += Math.cos(wink.math.degToRad(this.angle*i))*this.height; this._z += Math.sin(wink.math.degToRad(this.angle*i))*this.height; } }, /** * Initialize the Panel DOM node */ _initDom: function() { this._domNode = document.createElement('div'); this._domNode.className = 'op_panel'; wink.fx.apply(this._domNode, { height: (this.height + 2) + 'px', 'transform-origin': '0 0', backgroundImage: 'url(' + this.image + ')', backgroundRepeat: 'no-repeat', backgroundPositionX: '0', backgroundPositionY: -this.index*this.height + 'px' }); this._domNode.onclick = function() { wink.publish('/opener_panel/events/click', {'panelId': this.uId}); }; wink.fx.translate(this._domNode, 0, this.index*this.height); } }; return wink.ui.xyz.Opener; });
winktoolkit/wink
ui/xyz/opener/js/opener.js
JavaScript
bsd-3-clause
12,838
<?php namespace app\models; use Yii; /** * This is the model class for table "{{%vacancy}}". * * @property integer $id * @property string $date * @property integer $firm_id * @property integer $profession_id * @property string $salary * @property string $note * @property integer $workplace_id * @property integer $rec_status_id * @property integer $user_id * @property string $dc * * @property Resume[] $resumes * @property Profession $profession * @property Workplace $workplace * @property User $user * @property RecStatus $recStatus * @property Firm $firm */ class Vacancy extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%vacancy}}'; } /** * @inheritdoc */ public function rules() { return [ [['note', 'date'], 'filter', 'filter' => 'trim'], [['note', 'date', 'user_id'], 'default'], [['rec_status_id'], 'default', 'value' => 1], [['user_id'], 'default', 'value' => Yii::$app->user->id], [['date'], 'default', 'value' => Yii::$app->formatter->asDate(time())], [['firm_id', 'profession_id', 'workplace_id'], 'required'], [['date'], 'date', 'format' => 'dd.mm.yyyy'], [['note'], 'string'], [['firm_id', 'profession_id', 'workplace_id', 'rec_status_id', 'user_id'], 'integer'], [['dc'], 'safe'], [['salary'], 'number'], ]; } /** * @inheritdoc */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { $this->date = $this->date ? Yii::$app->formatter->asDate($this->date,'php:Y-m-d') : null; return true; } else { return false; } } /** * @inheritdoc */ public function afterFind() { $this->date = $this->date ? Yii::$app->formatter->asDate($this->date) : null; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'date' => Yii::t('app', 'Дата'), 'firm_id' => Yii::t('app', 'Фирма-работодатель'), 'profession_id' => Yii::t('app', 'Должность'), 'salary' => Yii::t('app', 'Зарплата'), 'note' => Yii::t('app', 'Описание'), 'workplace_id' => Yii::t('app', 'Рабочее место'), 'rec_status_id' => Yii::t('app', 'Состояние записи'), 'user_id' => Yii::t('app', 'Кем добавлена запись'), 'dc' => Yii::t('app', 'Когда добавлена запись'), ]; } /** * @return \yii\db\ActiveQuery */ public function getResumes() { return $this->hasMany(Resume::className(), ['vacancy_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getProfession() { return $this->hasOne(Profession::className(), ['id' => 'profession_id']); } /** * @return \yii\db\ActiveQuery */ public function getWorkplace() { return $this->hasOne(Workplace::className(), ['id' => 'workplace_id']); } /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); } /** * @return \yii\db\ActiveQuery */ public function getRecStatus() { return $this->hasOne(RecStatus::className(), ['id' => 'rec_status_id']); } /** * @return \yii\db\ActiveQuery */ public function getFirm() { return $this->hasOne(Firm::className(), ['id' => 'firm_id']); } /** * @inheritdoc * @return \app\models\queries\VacancyQuery the active query used by this AR class. */ public static function find() { return new \app\models\queries\VacancyQuery(get_called_class()); } }
slavam/placement
models/Vacancy.php
PHP
bsd-3-clause
4,058
package org.broadinstitute.hellbender.tools.funcotator.dataSources.gencode; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.tools.funcotator.vcfOutput.VcfOutputRenderer; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; /** * * Unit test class for the {@link GencodeFuncotation} class. * Created by jonn on 9/1/17. */ public class GencodeFuncotationUnitTest extends GATKBaseTest { //================================================================================================================== // Helper Methods: private static GencodeFuncotation createGencodeFuncotation(final String hugoSymbol, final String ncbiBuild, final String chromosome, final int start, final int end, final GencodeFuncotation.VariantClassification variantClassification, final GencodeFuncotation.VariantClassification secondaryVariantClassification, final GencodeFuncotation.VariantType variantType, final String refAllele, final String tumorSeqAllele2, final String genomeChange, final String annotationTranscript, final String transcriptStrand, final Integer transcriptExon, final Integer transcriptPos, final String cDnaChange, final String codonChange, final String proteinChange, final Double gcContent, final String referenceContext, final List<String> otherTranscripts) { final GencodeFuncotation gencodeFuncotation = new GencodeFuncotation(); gencodeFuncotation.setVersion("TEST_VERSION"); gencodeFuncotation.setDataSourceName(GencodeFuncotationFactory.DEFAULT_NAME); gencodeFuncotation.setHugoSymbol( hugoSymbol ); gencodeFuncotation.setNcbiBuild( ncbiBuild ); gencodeFuncotation.setChromosome( chromosome ); gencodeFuncotation.setStart( start ); gencodeFuncotation.setEnd( end ); gencodeFuncotation.setVariantClassification( variantClassification ); gencodeFuncotation.setSecondaryVariantClassification(secondaryVariantClassification); gencodeFuncotation.setVariantType( variantType ); gencodeFuncotation.setRefAllele( refAllele ); gencodeFuncotation.setTumorSeqAllele2( tumorSeqAllele2 ); gencodeFuncotation.setGenomeChange( genomeChange ); gencodeFuncotation.setAnnotationTranscript( annotationTranscript ); gencodeFuncotation.setTranscriptStrand( transcriptStrand ); gencodeFuncotation.setTranscriptExonNumber( transcriptExon ); gencodeFuncotation.setTranscriptPos( transcriptPos ); gencodeFuncotation.setcDnaChange( cDnaChange ); gencodeFuncotation.setCodonChange( codonChange ); gencodeFuncotation.setProteinChange( proteinChange ); gencodeFuncotation.setGcContent( gcContent ); gencodeFuncotation.setReferenceContext( referenceContext ); gencodeFuncotation.setOtherTranscripts( otherTranscripts ); return gencodeFuncotation; } private static GencodeFuncotation setFuncotationFieldOverride( final GencodeFuncotation gencodeFuncotation, final String field, final String overrideValue) { final GencodeFuncotation otherGencodeFuncotation = new GencodeFuncotation(gencodeFuncotation); otherGencodeFuncotation.setFieldSerializationOverrideValue( field, overrideValue ); return otherGencodeFuncotation; } //================================================================================================================== // Data Providers: @DataProvider Object[][] provideForTestGetFieldNames() { //final GencodeFuncotation gencodeFuncotation, final LinkedHashSet<String> expected return new Object[][] { { createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, null, Arrays.asList("ONE", "TWO", "THREE")), new LinkedHashSet<>( Arrays.asList("Gencode_TEST_VERSION_hugoSymbol", "Gencode_TEST_VERSION_ncbiBuild", "Gencode_TEST_VERSION_chromosome", "Gencode_TEST_VERSION_start", "Gencode_TEST_VERSION_end", "Gencode_TEST_VERSION_variantClassification", "Gencode_TEST_VERSION_secondaryVariantClassification", "Gencode_TEST_VERSION_variantType", "Gencode_TEST_VERSION_refAllele", "Gencode_TEST_VERSION_tumorSeqAllele1", "Gencode_TEST_VERSION_tumorSeqAllele2", "Gencode_TEST_VERSION_genomeChange", "Gencode_TEST_VERSION_annotationTranscript", "Gencode_TEST_VERSION_transcriptStrand", "Gencode_TEST_VERSION_transcriptExon", "Gencode_TEST_VERSION_transcriptPos", "Gencode_TEST_VERSION_cDnaChange", "Gencode_TEST_VERSION_codonChange", "Gencode_TEST_VERSION_proteinChange", "Gencode_TEST_VERSION_gcContent", "Gencode_TEST_VERSION_referenceContext", "Gencode_TEST_VERSION_otherTranscripts") ) }, }; } @DataProvider Object[][] provideForTestGetField() { //final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected final GencodeFuncotation gencodeFuncotation = createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, "ATGCGCAT", Arrays.asList("ONE", "TWO", "THREE")); return new Object[][] { { gencodeFuncotation, "Gencode_TEST_VERSION_hugoSymbol", "TESTGENE" }, { gencodeFuncotation, "hugoSymbol", "TESTGENE" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_hugoSymbol", "GARBAGEDAY"), "hugoSymbol", "GARBAGEDAY" }, { gencodeFuncotation, "ncbiBuild", "BUILD1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_ncbiBuild", "OVERRIDE"), "ncbiBuild", "OVERRIDE" }, { gencodeFuncotation, "chromosome", "chr1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_chromosome", "OVERRIDE"), "chromosome", "OVERRIDE" }, { gencodeFuncotation, "start", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_start", "OVERRIDE"), "start", "OVERRIDE" }, { gencodeFuncotation, "end", "100" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_end", "OVERRIDE"), "end", "OVERRIDE" }, { gencodeFuncotation, "variantClassification", GencodeFuncotation.VariantClassification.NONSENSE.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_variantClassification", "OVERRIDE"), "variantClassification", "OVERRIDE" }, { gencodeFuncotation, "secondaryVariantClassification", GencodeFuncotation.VariantClassification.INTRON.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_secondaryVariantClassification", "OVERRIDE"), "secondaryVariantClassification", "OVERRIDE" }, { gencodeFuncotation, "variantType", GencodeFuncotation.VariantType.SNP.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_variantType", "OVERRIDE"), "variantType", "OVERRIDE" }, { gencodeFuncotation, "refAllele", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_refAllele", "OVERRIDE"), "refAllele", "OVERRIDE" }, { gencodeFuncotation, "tumorSeqAllele1", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_tumorSeqAllele1", "OVERRIDE"), "tumorSeqAllele1", "OVERRIDE" }, { gencodeFuncotation, "tumorSeqAllele2", "T" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_tumorSeqAllele2", "OVERRIDE"), "tumorSeqAllele2", "OVERRIDE" }, { gencodeFuncotation, "genomeChange", "big_%20_changes" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_genomeChange", "OVERRIDE"), "genomeChange", "OVERRIDE" }, { gencodeFuncotation, "annotationTranscript", "T1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_annotationTranscript", "OVERRIDE"), "annotationTranscript", "OVERRIDE" }, { gencodeFuncotation, "transcriptStrand", "3'" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptStrand", "OVERRIDE"), "transcriptStrand", "OVERRIDE" }, { gencodeFuncotation, "transcriptExon", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptExon", "OVERRIDE"), "transcriptExon", "OVERRIDE" }, { gencodeFuncotation, "transcriptPos", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptPos", "OVERRIDE"), "transcriptPos", "OVERRIDE" }, { gencodeFuncotation, "cDnaChange", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_cDnaChange", "OVERRIDE"), "cDnaChange", "OVERRIDE" }, { gencodeFuncotation, "codonChange", "ATC" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_codonChange", "OVERRIDE"), "codonChange", "OVERRIDE" }, { gencodeFuncotation, "proteinChange", "Lys" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_proteinChange", "OVERRIDE"), "proteinChange", "OVERRIDE" }, { gencodeFuncotation, "gcContent", "1.0" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_gcContent", "OVERRIDE"), "gcContent", "OVERRIDE" }, { gencodeFuncotation, "referenceContext", "ATGCGCAT" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_referenceContext", "OVERRIDE"), "referenceContext", "OVERRIDE" }, { gencodeFuncotation, "otherTranscripts", "ONE" + VcfOutputRenderer.OTHER_TRANSCRIPT_DELIMITER + "TWO" + VcfOutputRenderer.OTHER_TRANSCRIPT_DELIMITER + "THREE" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_otherTranscripts", "OVERRIDE"), "otherTranscripts", "OVERRIDE" } }; } @DataProvider Object[][] provideForTestGetFieldFail() { //final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected final GencodeFuncotation gencodeFuncotation = createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, "ATGCGCAT", Arrays.asList("ONE", "TWO", "THREE")); return new Object[][] { { gencodeFuncotation, "TESTFIELD_OMICRON" }, { gencodeFuncotation, "hugoSymmbol" }, { gencodeFuncotation, "GENCODE_hugoSymbol" }, }; } //================================================================================================================== // Tests: @Test(dataProvider = "provideForTestGetFieldNames") public void testGetFieldNames(final GencodeFuncotation gencodeFuncotation, final LinkedHashSet<String> expected) { Assert.assertEquals(gencodeFuncotation.getFieldNames(), expected); } @Test(dataProvider = "provideForTestGetField") public void testGetField(final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected) { Assert.assertEquals(gencodeFuncotation.getField(fieldName), expected); } @Test(dataProvider = "provideForTestGetFieldFail", expectedExceptions = GATKException.class) public void testGetFieldFail(final GencodeFuncotation gencodeFuncotation, final String fieldName) { gencodeFuncotation.getField(fieldName); } }
magicDGS/gatk
src/test/java/org/broadinstitute/hellbender/tools/funcotator/dataSources/gencode/GencodeFuncotationUnitTest.java
Java
bsd-3-clause
18,552
//------------------------------------------------------------------------------------- // Copyright (c) 2014, Anthilla S.r.l. (http://www.anthilla.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Anthilla S.r.l. nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL ANTHILLA S.R.L. BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // 20141110 //------------------------------------------------------------------------------------- using System.IO; using antdlib; using antdlib.Certificate; using antdlib.Log; using antdlib.MountPoint; using antdlib.Terminal; using Antd.Helpers; using Nancy; using Nancy.Security; namespace Antd.Modules { public class DomainControllerModule : CoreModule { private readonly string[] _directories = { "/etc/samba", "/usr/lib64/python2.7/site-packages/samba", "/var/cache/samba", "/var/lib/samba", "/var/lock/samba", "/var/log/samba" }; public DomainControllerModule() { this.RequiresAuthentication(); Post["/dc/setup"] = x => { foreach (var dir in _directories) { var mntDir = Mount.GetDirsPath(dir); Terminal.Execute($"mkdir -p {mntDir}"); Terminal.Execute($"cp /mnt/livecd{dir} {mntDir}"); Mount.Dir(dir); } var domainName = (string)Request.Form.DomainName; var domainRealmname = (string)Request.Form.DomainRealmname; var domainHostname = (string)Request.Form.DomainHostname; var domainHostip = (string)Request.Form.DomainHostip; var domainAdminPassword = (string)Request.Form.DomainAdminPassword; if (string.IsNullOrEmpty(domainName) || string.IsNullOrEmpty(domainRealmname) || string.IsNullOrEmpty(domainHostname) || string.IsNullOrEmpty(domainHostip) || string.IsNullOrEmpty(domainAdminPassword)) { return Response.AsText("error: a value is missing. go back."); } Terminal.Execute($"samba-tool domain provision --option=\"interfaces = lo br0\" --option=\"bind interfaces only = yes\" --use-rfc2307 --domain={domainName} --realm={domainRealmname} --host-name={domainHostname} --host-ip={domainHostip} --adminpass={domainAdminPassword} --dns-backend=SAMBA_INTERNAL --server-role=dc"); ConsoleLogger.Log($"domain {domainName} created"); if (!Mount.IsAlreadyMounted("/etc/hosts")) { Mount.File("/etc/hosts"); } Terminal.Execute("echo 127.0.0.1 localhost.localdomain localhost > /etc/hosts"); Terminal.Execute($"echo {domainHostip} {domainHostname}.{domainRealmname} {domainHostname} >> /etc/hosts"); if (!Mount.IsAlreadyMounted("/etc/resolv.conf")) { Mount.File("/etc/resolv.conf"); } Terminal.Execute(!File.Exists("/etc/resolv.conf") ? $"echo nameserver {domainHostip} > /etc/resolv.conf" : $"echo nameserver {domainHostip} >> /etc/resolv.conf"); Terminal.Execute($"echo search {domainRealmname} >> /etc/resolv.conf"); Terminal.Execute($"echo domain {domainRealmname} >> /etc/resolv.conf"); const string sambaRealConf = "/etc/samba/smb.conf"; var sambaConf = $"{Parameter.Resources}/smb.conf.template"; const string workgroup = "$workgroup$"; const string realm = "$realm$"; const string netbiosName = "$netbiosName$"; const string netlogonPath = "$netlogonPath$"; var lowerRealm = domainRealmname.ToLower(); var sambaCnfText = File.ReadAllText(sambaConf) .Replace(workgroup, domainName.ToUpper()) .Replace(realm, domainRealmname.ToUpper()) .Replace(netbiosName, domainHostname.ToUpper()) .Replace(netlogonPath, $"/var/lib/samba/sysvol/{lowerRealm}/scripts"); if (File.Exists(sambaRealConf)) { File.Delete(sambaRealConf); } File.WriteAllText(sambaRealConf, sambaCnfText); Terminal.Execute("systemctl restart samba"); Terminal.Execute("mkdir -p /var/lib/samba/private"); var krbConf = $"{Parameter.Resources}/krb5.conf.template"; const string realmAlt = "$realmalt$"; var krbCnfText = File.ReadAllText(krbConf) .Replace(realmAlt, lowerRealm) .Replace(realm, domainRealmname.ToUpper()); const string krbRealConf = "/etc/krb5.conf"; if (File.Exists(krbRealConf)) { File.Delete(krbRealConf); } File.WriteAllText(krbRealConf, krbCnfText); const string krbRealConfSamba = "/var/lib/samba/private/krb5.conf"; if (File.Exists(krbRealConfSamba)) { File.Delete(krbRealConfSamba); } File.WriteAllText(krbRealConfSamba, krbCnfText); ConsoleLogger.Log($"{domainName} references updated"); return Response.AsRedirect("/"); }; Post["/dc/adduser"] = x => { var domainName = (string)Request.Form.DomainName; var username = (string)Request.Form.Username; var userPassword = (string)Request.Form.UserPassword; if (string.IsNullOrEmpty(domainName) || string.IsNullOrEmpty(userPassword) || string.IsNullOrEmpty(username)) { return Response.AsText("error: a value is missing. go back."); } Terminal.Execute($"samba-tool user create {username} --password={userPassword} --username={username} --mail-address={username}@{domainName} --given-name={username}"); return Response.AsRedirect("/"); }; Post["/dc/cert"] = x => { var domControllerGuid = (string)Request.Form.DomainControllerGuid; var domDnsName = (string)Request.Form.DomainDnsName; var domCrlDistributionPoint = (string)Request.Form.DomainCrlDistributionPoint; var domCaCountry = (string)Request.Form.DomainCaCountry; var domCaProvince = (string)Request.Form.DomainCaProvince; var domCaLocality = (string)Request.Form.DomainCaLocality; var domCaOrganization = (string)Request.Form.DomainCaOrganization; var domCaOrganizationalUnit = (string)Request.Form.DomainCaOrganizationalUnit; var domCaCommonName = (string)Request.Form.DomainCaCommonName; var domCaEmail = (string)Request.Form.DomainCaEmail; var domCaPassphrase = (string)Request.Form.DomainCaPassphrase; CertificateAuthority.DomainControllerCertificate.Create(domCrlDistributionPoint, domControllerGuid, domDnsName, domCaCountry, domCaProvince, domCaLocality, domCaOrganization, domCaOrganizationalUnit, domCaCommonName, domCaEmail, domCaPassphrase); return Response.AsRedirect("/"); }; Post["/sc/cert"] = x => { var userPrincipalName = (string)Request.Form.UserPrincipalName; var domainCrlDistributionPoint = (string)Request.Form.DomainCrlDistributionPoint; var smartCardCaCountry = (string)Request.Form.SmartCardCaCountry; var smartCardCaProvince = (string)Request.Form.SmartCardCaProvince; var smartCardCaLocality = (string)Request.Form.SmartCardCaLocality; var smartCardCaOrganization = (string)Request.Form.SmartCardCaOrganization; var smartCardCaOrganizationalUnit = (string)Request.Form.SmartCardCaOrganizationalUnit; var smartCardCaPassphrase = (string)Request.Form.SmartCardCaPassphrase; CertificateAuthority.SmartCardCertificate.Create(domainCrlDistributionPoint, userPrincipalName, smartCardCaCountry, smartCardCaProvince, smartCardCaLocality, smartCardCaOrganization, smartCardCaOrganizationalUnit, smartCardCaPassphrase); return Response.AsRedirect("/"); }; Post["/ca/cert"] = x => { var certAssignment = (string)Request.Form.CertAssignment.Value; var certCountry = (string)Request.Form.CertCountry; var certProvince = (string)Request.Form.CertProvince; var certLocality = (string)Request.Form.CertLocality; var certOrganization = (string)Request.Form.CertOrganization; var certOrganizationalUnit = (string)Request.Form.CertOrganizationalUnit; var certCommonName = (string)Request.Form.CertCommonName; var certEmailAddress = (string)Request.Form.CertEmailAddress; var certPassphrase = (string)Request.Form.CertPassphrase; var certKeyLength = (string)Request.Form.CertKeyLength; var certUserAssignedGuid = (string)Request.Form.CertUserAssignedGuid; var certServiceAssignedGuid = (string)Request.Form.CertServiceAssignedGuid; var certServiceAssignedName = (string)Request.Form.CertServiceAssignedName; CertificateAuthority.Certificate.Create(certCountry, certProvince, certLocality, certOrganization, certOrganizationalUnit, certCommonName, certEmailAddress, certPassphrase, CertificateAssignmentType.Detect(certAssignment), certKeyLength, certUserAssignedGuid, certServiceAssignedGuid, certServiceAssignedName); return Response.AsRedirect("/"); }; } } }
Heather/Antd
Antd/Modules/DomainControllerModule.cs
C#
bsd-3-clause
11,376
module ServiceVersionsHelper def service_operation_responses_markup(service_version, verb, path) service_operation_responses_content_markup( service_version.operation(verb, path)['responses'], json_pointer_path('/paths', path, verb, 'responses'), service_version.spec_with_resolved_refs['references'] ) end def service_operation_parameters_markup(service_version, verb, path, location) path_parameters = service_version.path_parameters(path, location) operation_parameters = service_version.operation_parameters(verb, path, location) join_markup(path_parameters.map do |index, parameter| service_parameter_markup( location, parameter, json_pointer_path('/paths', path, 'parameters', index.to_s), service_version.spec_with_resolved_refs['references'] ) end) + join_markup(operation_parameters.map do |index, parameter| service_parameter_markup( location, parameter, json_pointer_path('/paths', path, verb, 'parameters', index.to_s), service_version.spec_with_resolved_refs['references'] ) end) end def service_operation_parameters_form(service_version, verb, path, location) path_parameters = service_version.path_parameters(path, location) operation_parameters = service_version.operation_parameters(verb, path, location) join_markup(path_parameters.map do |index, parameter| service_parameter_form( location, parameter, json_pointer_path('/paths', path, 'parameters', index.to_s), '/', service_version.spec_with_resolved_refs['references'] ) end) + join_markup(operation_parameters.map do |index, parameter| service_parameter_form( location, parameter, json_pointer_path('/paths', path, verb, 'parameters', index.to_s), '/', service_version.spec_with_resolved_refs['references'] ) end) end def css_class_for_http_verb(verb) { 'get' => 'info', 'post' => 'success', 'put' => 'warning', 'delete' => 'danger' }[verb] || '' end def service_operation_responses_content_markup(responses, json_pointer, references) join_markup(responses.map do |name, response| content_tag(:h3, name) + content_tag(:p, response['description']) + response_schema_object_markup( response['schema'], json_pointer_path(json_pointer, 'schema'), references ) + response_headers_markup( response['headers'], json_pointer_path(json_pointer, 'headers'), references ) + response_example_markup(response['examples']) end) end def response_example_markup(example) if example.present? content_tag(:div, class: 'box-code-example') do content_tag(:code, class: 'json') do preserve(JSON.pretty_generate example) end end else '' end end def response_headers_markup(headers, json_pointer, references) if headers.present? content_tag(:div, class: 'schema-panel-set detail') do join_markup(headers.map do |name, header| schema_object_property_markup( name, header, false, json_pointer_path(json_pointer, name), references ) end) end end end def response_schema_object_markup(schema, json_pointer, references) if schema.present? content_tag(:div, class: 'schema-panel-set detail') do case schema["type"] when "object" schema_object_spec_markup(schema, json_pointer, references) else schema_object_property_markup( '', schema, false, json_pointer, references ) end end else return '' end end def parameter_section_name(location) { 'body' => 'Body', 'query' => 'URL: Query', 'header' => 'Header', 'path' => 'URL: Path', 'formData' => 'Body (form data)' }[location] end def service_parameter_markup(location, parameter, json_pointer, references) if location == 'body' if parameter['schema']['description'].blank? parameter['schema'].merge!('description' => parameter['description']) end schema_object_property_markup(parameter['name'], parameter['schema'], parameter['required'], json_pointer_path(json_pointer, 'schema'), references) else schema_object_property_markup(parameter['name'], parameter, parameter['required'], json_pointer, references) end end def display_service_alert_msg(status) { 'rejected' => { 'title' => t(:version_rejected), 'msg' => t(:version_rejected_msg), }, 'proposed' => { 'title' => t(:service_pending_approval), 'msg' => '' } }[status] || '' end def service_parameter_form(location, parameter, json_pointer, target_json_pointer, references) if location == 'body' if parameter['schema']['description'].blank? parameter['schema'].merge!('description' => parameter['description']) end schema_object_property_form(parameter['name'], parameter['schema'], parameter['required'], json_pointer_path(json_pointer, 'schema'), target_json_pointer, references) else schema_object_property_form(parameter['name'], parameter, parameter['required'], json_pointer, json_pointer_path(target_json_pointer, parameter['name']), references) end end def schema_object_property_form(name, property_definition, required, json_pointer, target_json_pointer, references) if property_definition["type"] == "object" schema_object_complex_property_form( name, property_definition, required, json_pointer, target_json_pointer, references ) elsif property_definition["type"] == "array" schema_object_array_property_form( name, property_definition, required, json_pointer, target_json_pointer, references ) else schema_object_primitive_property_form( name, property_definition, required, json_pointer, target_json_pointer, references ) end end def dynamic_component_structure_form(field_name, s_name_markup, property_definition, required, json_pointer, target_json_pointer, references) s_type_and_format = s(property_definition['type']) || '' if property_definition.has_key?('format') s_type_and_format += "(#{s(property_definition['format'])})" end content_tag(:div, nil, class: "panel-group", data: {pointer: json_pointer, target: target_json_pointer }) do content_tag(:div, nil, class: "panel panel-schema") do editable_css = %w(object array).include?(property_definition['type']) ? '' : 'editable ' content_tag(:div, nil, class: "panel-heading #{editable_css}clearfix") do content_tag(:div, nil, class: "panel-title " + (required ? "required" : "")) do content_tag(:div, nil, class: "col-md-6") do s_name_markup end + content_tag(:div, nil, class: "col-md-6 text-right") do form_primitive_specifics(property_definition, field_name, required) end end end + content_tag(:div, nil, class: "panel-collapse collapse") do yield if block_given? end end end end def form_primitive_specifics(primitive, name, required) if primitive['enum'] options = {'data-type' => primitive['type'], include_blank: !required} select_tag(name, options_for_select(primitive['enum']), options) else case s(primitive['type']) when "string" string_primitive_form(primitive, name, required) when "integer" integer_primitive_form(primitive, name, required) when "number" number_primitive_form(primitive, name, required) when "boolean" boolean_primitive_form(primitive, name, required) else "".html_safe end end end def string_primitive_form(primitive, name, required) options = { placeholder: "[ingresa texto]", required: required, maxlength: primitive['maxLength'], pattern: primitive['pattern'], data: { minLength: primitive['minLength'] } } if primitive['format'].present? case s(primitive['format']) when 'password' password_field_tag(name, primitive['default'].to_s, options) when 'date-time' datetime_local_field_tag(name, primitive['default'].to_s, options) when 'date' date_field_tag(name, primitive['default'].to_s, options) else text_field_tag(name, primitive['default'].to_s, options) end else text_field_tag(name, primitive['default'].to_s, options) end end def integer_primitive_form(primitive, name, required) options = { placeholder: '[ingresa número]', required: required, data: {type: 'integer'} } numeric_primitive_form(primitive, name, options) end def number_primitive_form(primitive, name, required) options = {step: 'any', placeholder: '[ingresa número]', required: required, data: {type: 'number'}} numeric_primitive_form(primitive, name, options) end def numeric_primitive_form(primitive, name, options) options[:max] = primitive['maximum'] options[:min] = primitive['minimum'] options[:data] = { exclusiveMaximum: primitive['exclusiveMaximum'], exclusiveMinimum: primitive['exclusiveMinimum'], multipleOf: primitive['multipleOf'] } number_field_tag(name, primitive['default'].to_s, options) end def boolean_primitive_form(primitive, name, required) check_box_tag(name, "true", primitive['default'] == 'true', required: required) end def schema_object_primitive_property_form(name, primitive_property_definition, required, json_pointer, target_json_pointer, references) css_class = "name" css_class.concat(" anonymous") if name.empty? s_name_markup = content_tag(:span, s(name), class: css_class) dynamic_component_structure_form( name, s_name_markup, primitive_property_definition, required, json_pointer, target_json_pointer, references ) end def schema_object_complex_property_form(name, property_definition, required, json_pointer, target_json_pointer, references) s_name_markup = content_tag(:a, nil, data: {toggle: "collapse-next"}) do content_tag(:span, s(name), class: "name") end dynamic_component_structure_form( name, s_name_markup, property_definition, required, json_pointer, target_json_pointer, references ) do content_tag(:div, nil, class: "panel-body") do schema_object_spec_form(property_definition, json_pointer, target_json_pointer, references) end end end def schema_object_array_property_form(name, property_definition, required, json_pointer, target_json_pointer, references) s_name_markup = content_tag(:a, nil, data: {toggle: "collapse-next"}) do content_tag(:span, s(name), class: "name") end dynamic_component_structure_form( name, s_name_markup, property_definition, required, json_pointer, target_json_pointer, references ) do schema_object_array_property_initial_inputs_form( 0, property_definition, json_pointer, target_json_pointer, references, is_template: true ) + ( if required schema_object_array_property_initial_inputs_form( 0, property_definition, json_pointer, target_json_pointer, references, is_template: false) else "".html_safe end ) + content_tag(:div, class: 'text-right') do content_tag(:a, "Agregar Elemento", class: "btn add-element", data: {context: target_json_pointer}) end end end def schema_object_array_property_initial_inputs_form(index, property_definition, json_pointer, target_json_pointer, references, is_template: true) content_tag(:div, nil, class: "panel-body #{is_template ? 'clonable' : 'clone'}") do schema_object_property_form( "[#{index}]".html_safe, property_definition["items"], false, json_pointer_path(json_pointer, "items"), json_pointer_path(target_json_pointer, index.to_s), references ) end end def schema_object_spec_form(schema_object, json_pointer, target_json_pointer, references) properties = schema_object['properties'] || {} join_markup(properties.map do |name, property_definition| required = ( schema_object.has_key?("required") && schema_object["required"].include?(name) ) schema_object_property_form( name, property_definition, required, json_pointer_path(json_pointer, 'properties', name), json_pointer_path(target_json_pointer, name), references ) end) end end
continuum/APIO
app/helpers/service_versions_helper.rb
Ruby
bsd-3-clause
12,888
from django.conf.urls import patterns, include, url from django.views.generic import TemplateView home = TemplateView.as_view(template_name='home.html') urlpatterns = patterns( '', url(r'^filter/', include('demoproject.filter.urls')), # An informative homepage. url(r'', home, name='home') )
jgsogo/django-generic-filters
demo/demoproject/urls.py
Python
bsd-3-clause
312
<?php /** * * Descripcion: Clase que gestiona la relación dirección-empresa * * @category * @package Models * @subpackage */ class ProveedoresDireccion extends ActiveRecord { /** * Método para definir las relaciones y validaciones */ protected function initialize() { $this->belongs_to('proveedores'); $this->belongs_to('direcciones'); } /** * Método que retorna los recursos asignados a un perfil de usuario * @param int $perfil Identificador el perfil del usuario * @return array object ActieRecord */ public function getProveedoresDireccion($proveedores) { $proveedores = Filter::get($proveedores,'numeric'); $columnas = 'proveedores_direccion.*, direcciones.nombre_dir, direcciones.calle, direcciones.num_esterior, direcciones.colonia, direcciones.codigo_postal'; $join = 'INNER JOIN direcciones ON direcciones.id = proveedores_direccion.direcciones_id'; $condicion = "proveedores_direccion.proveedores_id = '$proveedores'"; // $order = 'recurso.modulo ASC, recurso.controlador ASC, recurso.recurso_at ASC'; return $this->find("columns: $columnas", "join: $join", "conditions: $condicion"); } }
lsomohano/dbkm-sipyme
default/app/models/config/proveedores_direccion.php
PHP
bsd-3-clause
1,329
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; import net.sourceforge.pmd.lang.java.ast.ASTArguments; import net.sourceforge.pmd.lang.java.ast.ASTArrayDimsAndInits; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; /** * 1. Note all private constructors. * 2. Note all instantiations from outside of the class by way of the private * constructor. * 3. Flag instantiations. * <p/> * <p/> * Parameter types can not be matched because they can come as exposed members * of classes. In this case we have no way to know what the type is. We can * make a best effort though which can filter some? * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * @author David Konecny (david.konecny@) * @author Romain PELISSE, belaran@gmail.com, patch bug#1807370 */ public class AccessorClassGenerationRule extends AbstractJavaRule { private List<ClassData> classDataList = new ArrayList<ClassData>(); private int classID = -1; private String packageName; public Object visit(ASTEnumDeclaration node, Object data) { return data; // just skip Enums } public Object visit(ASTCompilationUnit node, Object data) { classDataList.clear(); packageName = node.getScope().getEnclosingSourceFileScope().getPackageName(); return super.visit(node, data); } private static class ClassData { private String className; private List<ASTConstructorDeclaration> privateConstructors; private List<AllocData> instantiations; /** * List of outer class names that exist above this class */ private List<String> classQualifyingNames; public ClassData(String className) { this.className = className; this.privateConstructors = new ArrayList<ASTConstructorDeclaration>(); this.instantiations = new ArrayList<AllocData>(); this.classQualifyingNames = new ArrayList<String>(); } public void addInstantiation(AllocData ad) { instantiations.add(ad); } public Iterator<AllocData> getInstantiationIterator() { return instantiations.iterator(); } public void addConstructor(ASTConstructorDeclaration cd) { privateConstructors.add(cd); } public Iterator<ASTConstructorDeclaration> getPrivateConstructorIterator() { return privateConstructors.iterator(); } public String getClassName() { return className; } public void addClassQualifyingName(String name) { classQualifyingNames.add(name); } public List<String> getClassQualifyingNamesList() { return classQualifyingNames; } } private static class AllocData { private String name; private int argumentCount; private ASTAllocationExpression allocationExpression; private boolean isArray; public AllocData(ASTAllocationExpression node, String aPackageName, List<String> classQualifyingNames) { if (node.jjtGetChild(1) instanceof ASTArguments) { ASTArguments aa = (ASTArguments) node.jjtGetChild(1); argumentCount = aa.getArgumentCount(); //Get name and strip off all superfluous data //strip off package name if it is current package if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) { throw new RuntimeException("BUG: Expected a ASTClassOrInterfaceType, got a " + node.jjtGetChild(0).getClass()); } ASTClassOrInterfaceType an = (ASTClassOrInterfaceType) node.jjtGetChild(0); name = stripString(aPackageName + '.', an.getImage()); //strip off outer class names //try OuterClass, then try OuterClass.InnerClass, then try OuterClass.InnerClass.InnerClass2, etc... String findName = ""; for (ListIterator<String> li = classQualifyingNames.listIterator(classQualifyingNames.size()); li.hasPrevious();) { String aName = li.previous(); findName = aName + '.' + findName; if (name.startsWith(findName)) { //strip off name and exit name = name.substring(findName.length()); break; } } } else if (node.jjtGetChild(1) instanceof ASTArrayDimsAndInits) { //this is incomplete because I dont need it. // child 0 could be primitive or object (ASTName or ASTPrimitiveType) isArray = true; } allocationExpression = node; } public String getName() { return name; } public int getArgumentCount() { return argumentCount; } public ASTAllocationExpression getASTAllocationExpression() { return allocationExpression; } public boolean isArray() { return isArray; } } /** * Outer interface visitation */ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level interface String interfaceName = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(interfaceName); //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } else { String interfaceName = node.getImage(); classDataList.clear(); setClassID(0); classDataList.add(getClassID(), new ClassData(interfaceName)); Object o = super.visit(node, data); if (o != null) { processRule(o); } else { processRule(data); } setClassID(-1); return o; } } else if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level class String className = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(className); // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (formerID == -1 || formerID >= classDataList.size()) { return null; } //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } // outer classes if ( ! node.isStatic() ) { // See bug# 1807370 String className = node.getImage(); classDataList.clear(); setClassID(0);//first class classDataList.add(getClassID(), new ClassData(className)); } Object o = super.visit(node, data); if (o != null && ! node.isStatic() ) { // See bug# 1807370 processRule(o); } else { processRule(data); } setClassID(-1); return o; } /** * Store all target constructors */ public Object visit(ASTConstructorDeclaration node, Object data) { if (node.isPrivate()) { getCurrentClassData().addConstructor(node); } return super.visit(node, data); } public Object visit(ASTAllocationExpression node, Object data) { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID == -1 || getCurrentClassData() == null) { return data; } AllocData ad = new AllocData(node, packageName, getCurrentClassData().getClassQualifyingNamesList()); if (!ad.isArray()) { getCurrentClassData().addInstantiation(ad); } return super.visit(node, data); } private void processRule(Object ctx) { //check constructors of outerIterator against allocations of innerIterator for (ClassData outerDataSet : classDataList) { for (Iterator<ASTConstructorDeclaration> constructors = outerDataSet.getPrivateConstructorIterator(); constructors.hasNext();) { ASTConstructorDeclaration cd = constructors.next(); for (ClassData innerDataSet : classDataList) { if (outerDataSet == innerDataSet) { continue; } for (Iterator<AllocData> allocations = innerDataSet.getInstantiationIterator(); allocations.hasNext();) { AllocData ad = allocations.next(); //if the constructor matches the instantiation //flag the instantiation as a generator of an extra class if (outerDataSet.getClassName().equals(ad.getName()) && (cd.getParameterCount() == ad.getArgumentCount())) { addViolation(ctx, ad.getASTAllocationExpression()); } } } } } } private ClassData getCurrentClassData() { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID >= classDataList.size()) { return null; } return classDataList.get(classID); } private void setClassID(int id) { classID = id; } private int getClassID() { return classID; } //remove = Fire. //value = someFire.Fighter // 0123456789012345 //index = 4 //remove.size() = 5 //value.substring(0,4) = some //value.substring(4 + remove.size()) = Fighter //return "someFighter" // TODO move this into StringUtil private static String stripString(String remove, String value) { String returnValue; int index = value.indexOf(remove); if (index != -1) { //if the package name can start anywhere but 0 please inform the author because this will break returnValue = value.substring(0, index) + value.substring(index + remove.length()); } else { returnValue = value; } return returnValue; } }
daejunpark/jsaf
third_party/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/design/AccessorClassGenerationRule.java
Java
bsd-3-clause
12,208
package buffer import ( "errors" "sync" "github.com/flynn/flynn/pkg/syslog/rfc5424" ) // Buffer is a linked list that holds rfc5424.Messages. The Buffer's entire // contents can be read at once. Reading elements out of the buffer does not // clear them; messages merely get removed from the buffer when they are // replaced by new messages. // // A Buffer also offers the ability to subscribe to new incoming messages. type Buffer struct { mu sync.RWMutex // protects all of the following: head *message tail *message length int capacity int subs map[chan<- *rfc5424.Message]struct{} donec chan struct{} } type message struct { next *message prev *message rfc5424.Message } const DefaultCapacity = 10000 // NewBuffer returns an empty allocated Buffer with DefaultCapacity. func NewBuffer() *Buffer { return newBuffer(DefaultCapacity) } func newBuffer(capacity int) *Buffer { return &Buffer{ capacity: capacity, subs: make(map[chan<- *rfc5424.Message]struct{}), donec: make(chan struct{}), } } // Add adds an element to the Buffer. If the Buffer is already full, it removes // an existing message. func (b *Buffer) Add(m *rfc5424.Message) error { b.mu.Lock() defer b.mu.Unlock() if b.length == -1 { return errors.New("buffer closed") } if b.head == nil { b.head = &message{Message: *m} b.tail = b.head } else { // iterate from newest to oldest through messages to find position // to insert new message for other := b.tail; other != nil; other = other.prev { if m.Timestamp.Before(other.Timestamp) { if other.prev == nil { // insert before other at head other.prev = &message{Message: *m, next: other} b.head = other.prev break } else { continue } } msg := &message{Message: *m, prev: other} if other.next != nil { // insert between other and other.next other.next.prev = msg msg.next = other.next } else { // insert at tail b.tail = msg } other.next = msg break } } if b.length < b.capacity { // buffer not yet full b.length++ } else { // at capacity, remove head b.head = b.head.next b.head.prev = nil } for msgc := range b.subs { select { case msgc <- m: default: // chan is full, drop this message to it } } return nil } func (b *Buffer) Close() { b.mu.Lock() defer b.mu.Unlock() b.head = nil b.tail = nil b.length = -1 close(b.donec) } // Read returns a copied slice with the contents of the Buffer. It does not // modify the underlying buffer in any way. You are free to modify the // returned slice without affecting Buffer, though modifying the individual // elements in the result will also modify those elements in the Buffer. func (b *Buffer) Read() []*rfc5424.Message { b.mu.RLock() defer b.mu.RUnlock() return b.read() } // ReadAndSubscribe returns all buffered messages just like Read, and also // returns a channel that will stream new messages as they arrive. func (b *Buffer) ReadAndSubscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) []*rfc5424.Message { b.mu.RLock() defer b.mu.RUnlock() b.subscribe(msgc, donec) return b.read() } // Subscribe returns a channel that sends all future messages added to the // Buffer. The returned channel is buffered, and any attempts to send new // messages to the channel will drop messages if the channel is full. // // The caller closes the donec channel to stop receiving messages. func (b *Buffer) Subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) { b.mu.RLock() defer b.mu.RUnlock() b.subscribe(msgc, donec) } // _read expects b.mu to already be locked func (b *Buffer) read() []*rfc5424.Message { if b.length == -1 { return nil } buf := make([]*rfc5424.Message, 0, b.length) msg := b.head for msg != nil { buf = append(buf, &msg.Message) msg = msg.next } return buf } // _subscribe assumes b.mu is already locked func (b *Buffer) subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) { b.subs[msgc] = struct{}{} go func() { select { case <-donec: case <-b.donec: } b.mu.RLock() defer b.mu.RUnlock() delete(b.subs, msgc) close(msgc) }() }
rikur/flynn
logaggregator/buffer/buffer.go
GO
bsd-3-clause
4,180
// // Copyright 2016, Yahoo Inc. // Copyrights licensed under the New BSD License. // See the accompanying LICENSE file for terms. // package github.com.jminusminus.core.stream; public class Readable { // Jmm Readable wraps https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html protected java.io.InputStream stream; Readable(String str) { try { this.stream = new InputStream(str.getBytes("utf8")); } catch (Exception e) { System.out.println(e); } } Readable(String str, String encoding) { try { this.stream = new InputStream(str.getBytes(encoding)); } catch (Exception e) { System.out.println(e); } } Readable(byte[] b) { this.stream = new InputStream(b); } Readable(java.io.InputStream stream) { this.stream = stream; } // Returns an estimate of the number of bytes that can be read (or skipped over) from this // input stream without blocking by the next invocation of a method for this input stream. public int available() { try { return this.stream.available(); } catch (Exception e) { System.out.println(e); } return -1; } // Closes this input stream and releases any system resources associated with the stream. public boolean close() { try { this.stream.close(); return true; } catch (Exception e) { System.out.println(e); } return false; } // Marks the current position in this input stream. public void mark(int readlimit){ this.stream.mark(readlimit); } // Repositions this stream to the position at the time the mark method was last called on this input stream. public boolean reset() { try { this.stream.reset(); return true; } catch (Exception e) { System.out.println(e); } return false; } // public String read(int size, String encoding) { return ""; } // public byte[] read(int size) { return new byte[size]; } // public String readTo(String str, String encoding) { return ""; } // public byte[] readTo(int code) { return new byte[0]; } // public byte[] readTo(byte code) { return new byte[0]; } // public void pipe(Writable destination) { } }
jminusminus/core
stream/Readable.java
Java
bsd-3-clause
2,510
<?php namespace EvaUser\Validator; use Eva\Validator\AbstractValidator; use Eva\Validator\ValidationResult; class EmailExist extends AbstractValidator { function __invoke($value, $options = []) { $result = new ValidationResult(); $result->setValue($value); /** @var \EvaUser\Entity\User $user */ $user = $this->getEntityManager()->get('EvaUser\Entity\User')->findOneBy(['emailAddress' => $value]); if (!$user) { $result->setErrorMessage('Пользователь с такой электронной почтной не найден'); } return $result; } }
augustmedia/eva-user
src/Validator/EmailExist.php
PHP
bsd-3-clause
643
// Copyright 2013 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. #include "content/renderer/input/input_handler_proxy.h" #include "base/auto_reset.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/common/input/did_overscroll_params.h" #include "content/common/input/web_input_event_traits.h" #include "content/public/common/content_switches.h" #include "content/renderer/input/input_handler_proxy_client.h" #include "content/renderer/input/input_scroll_elasticity_controller.h" #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/events/latency_info.h" #include "ui/gfx/geometry/point_conversions.h" using blink::WebFloatPoint; using blink::WebFloatSize; using blink::WebGestureEvent; using blink::WebInputEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; using blink::WebPoint; using blink::WebTouchEvent; using blink::WebTouchPoint; namespace { // Maximum time between a fling event's timestamp and the first |Animate| call // for the fling curve to use the fling timestamp as the initial animation time. // Two frames allows a minor delay between event creation and the first animate. const double kMaxSecondsFromFlingTimestampToFirstAnimate = 2. / 60.; // Threshold for determining whether a fling scroll delta should have caused the // client to scroll. const float kScrollEpsilon = 0.1f; // Minimum fling velocity required for the active fling and new fling for the // two to accumulate. const double kMinBoostFlingSpeedSquare = 350. * 350.; // Minimum velocity for the active touch scroll to preserve (boost) an active // fling for which cancellation has been deferred. const double kMinBoostTouchScrollSpeedSquare = 150 * 150.; // Timeout window after which the active fling will be cancelled if no scrolls // or flings of sufficient velocity relative to the current fling are received. // The default value on Android native views is 40ms, but we use a slightly // increased value to accomodate small IPC message delays. const double kFlingBoostTimeoutDelaySeconds = 0.045; gfx::Vector2dF ToClientScrollIncrement(const WebFloatSize& increment) { return gfx::Vector2dF(-increment.width, -increment.height); } double InSecondsF(const base::TimeTicks& time) { return (time - base::TimeTicks()).InSecondsF(); } bool ShouldSuppressScrollForFlingBoosting( const gfx::Vector2dF& current_fling_velocity, const WebGestureEvent& scroll_update_event, double time_since_last_boost_event) { DCHECK_EQ(WebInputEvent::GestureScrollUpdate, scroll_update_event.type); gfx::Vector2dF dx(scroll_update_event.data.scrollUpdate.deltaX, scroll_update_event.data.scrollUpdate.deltaY); if (gfx::DotProduct(current_fling_velocity, dx) <= 0) return false; if (time_since_last_boost_event < 0.001) return true; // TODO(jdduke): Use |scroll_update_event.data.scrollUpdate.velocity{X,Y}|. // The scroll must be of sufficient velocity to maintain the active fling. const gfx::Vector2dF scroll_velocity = gfx::ScaleVector2d(dx, 1. / time_since_last_boost_event); if (scroll_velocity.LengthSquared() < kMinBoostTouchScrollSpeedSquare) return false; return true; } bool ShouldBoostFling(const gfx::Vector2dF& current_fling_velocity, const WebGestureEvent& fling_start_event) { DCHECK_EQ(WebInputEvent::GestureFlingStart, fling_start_event.type); gfx::Vector2dF new_fling_velocity( fling_start_event.data.flingStart.velocityX, fling_start_event.data.flingStart.velocityY); if (gfx::DotProduct(current_fling_velocity, new_fling_velocity) <= 0) return false; if (current_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare) return false; if (new_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare) return false; return true; } WebGestureEvent ObtainGestureScrollBegin(const WebGestureEvent& event) { WebGestureEvent scroll_begin_event = event; scroll_begin_event.type = WebInputEvent::GestureScrollBegin; scroll_begin_event.data.scrollBegin.deltaXHint = 0; scroll_begin_event.data.scrollBegin.deltaYHint = 0; return scroll_begin_event; } void ReportInputEventLatencyUma(const WebInputEvent& event, const ui::LatencyInfo& latency_info) { if (!(event.type == WebInputEvent::GestureScrollBegin || event.type == WebInputEvent::GestureScrollUpdate || event.type == WebInputEvent::GesturePinchBegin || event.type == WebInputEvent::GesturePinchUpdate || event.type == WebInputEvent::GestureFlingStart)) { return; } ui::LatencyInfo::LatencyMap::const_iterator it = latency_info.latency_components().find(std::make_pair( ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0)); if (it == latency_info.latency_components().end()) return; base::TimeDelta delta = base::TimeTicks::Now() - it->second.event_time; for (size_t i = 0; i < it->second.event_count; ++i) { switch (event.type) { case blink::WebInputEvent::GestureScrollBegin: UMA_HISTOGRAM_CUSTOM_COUNTS( "Event.Latency.RendererImpl.GestureScrollBegin", delta.InMicroseconds(), 1, 1000000, 100); break; case blink::WebInputEvent::GestureScrollUpdate: UMA_HISTOGRAM_CUSTOM_COUNTS( // So named for historical reasons. "Event.Latency.RendererImpl.GestureScroll2", delta.InMicroseconds(), 1, 1000000, 100); break; case blink::WebInputEvent::GesturePinchBegin: UMA_HISTOGRAM_CUSTOM_COUNTS( "Event.Latency.RendererImpl.GesturePinchBegin", delta.InMicroseconds(), 1, 1000000, 100); break; case blink::WebInputEvent::GesturePinchUpdate: UMA_HISTOGRAM_CUSTOM_COUNTS( "Event.Latency.RendererImpl.GesturePinchUpdate", delta.InMicroseconds(), 1, 1000000, 100); break; case blink::WebInputEvent::GestureFlingStart: UMA_HISTOGRAM_CUSTOM_COUNTS( "Event.Latency.RendererImpl.GestureFlingStart", delta.InMicroseconds(), 1, 1000000, 100); break; default: NOTREACHED(); break; } } } } // namespace namespace content { InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler, InputHandlerProxyClient* client) : client_(client), input_handler_(input_handler), deferred_fling_cancel_time_seconds_(0), #ifndef NDEBUG expect_scroll_update_end_(false), #endif gesture_scroll_on_impl_thread_(false), gesture_pinch_on_impl_thread_(false), fling_may_be_active_on_main_thread_(false), disallow_horizontal_fling_scroll_(false), disallow_vertical_fling_scroll_(false), has_fling_animation_started_(false), uma_latency_reporting_enabled_(base::TimeTicks::IsHighResolution()) { DCHECK(client); input_handler_->BindToClient(this); smooth_scroll_enabled_ = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSmoothScrolling); cc::ScrollElasticityHelper* scroll_elasticity_helper = input_handler_->CreateScrollElasticityHelper(); if (scroll_elasticity_helper) { scroll_elasticity_controller_.reset( new InputScrollElasticityController(scroll_elasticity_helper)); } } InputHandlerProxy::~InputHandlerProxy() {} void InputHandlerProxy::WillShutdown() { scroll_elasticity_controller_.reset(); input_handler_ = NULL; client_->WillShutdown(); } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleInputEventWithLatencyInfo( const WebInputEvent& event, ui::LatencyInfo* latency_info) { DCHECK(input_handler_); if (uma_latency_reporting_enabled_) ReportInputEventLatencyUma(event, *latency_info); TRACE_EVENT_FLOW_STEP0("input,benchmark", "LatencyInfo.Flow", TRACE_ID_DONT_MANGLE(latency_info->trace_id()), "HandleInputEventImpl"); scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor = input_handler_->CreateLatencyInfoSwapPromiseMonitor(latency_info); InputHandlerProxy::EventDisposition disposition = HandleInputEvent(event); return disposition; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleInputEvent( const WebInputEvent& event) { DCHECK(input_handler_); TRACE_EVENT1("input,benchmark", "InputHandlerProxy::HandleInputEvent", "type", WebInputEventTraits::GetName(event.type)); if (FilterInputEventForFlingBoosting(event)) return DID_HANDLE; switch (event.type) { case WebInputEvent::MouseWheel: return HandleMouseWheel(static_cast<const WebMouseWheelEvent&>(event)); case WebInputEvent::GestureScrollBegin: return HandleGestureScrollBegin( static_cast<const WebGestureEvent&>(event)); case WebInputEvent::GestureScrollUpdate: return HandleGestureScrollUpdate( static_cast<const WebGestureEvent&>(event)); case WebInputEvent::GestureScrollEnd: return HandleGestureScrollEnd(static_cast<const WebGestureEvent&>(event)); case WebInputEvent::GesturePinchBegin: { DCHECK(!gesture_pinch_on_impl_thread_); const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(event); if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad && input_handler_->HaveWheelEventHandlersAt( gfx::Point(gesture_event.x, gesture_event.y))) { return DID_NOT_HANDLE; } else { input_handler_->PinchGestureBegin(); gesture_pinch_on_impl_thread_ = true; return DID_HANDLE; } } case WebInputEvent::GesturePinchEnd: if (gesture_pinch_on_impl_thread_) { gesture_pinch_on_impl_thread_ = false; input_handler_->PinchGestureEnd(); return DID_HANDLE; } else { return DID_NOT_HANDLE; } case WebInputEvent::GesturePinchUpdate: { if (gesture_pinch_on_impl_thread_) { const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(event); if (gesture_event.data.pinchUpdate.zoomDisabled) return DROP_EVENT; input_handler_->PinchGestureUpdate( gesture_event.data.pinchUpdate.scale, gfx::Point(gesture_event.x, gesture_event.y)); return DID_HANDLE; } else { return DID_NOT_HANDLE; } } case WebInputEvent::GestureFlingStart: return HandleGestureFlingStart( *static_cast<const WebGestureEvent*>(&event)); case WebInputEvent::GestureFlingCancel: if (CancelCurrentFling()) return DID_HANDLE; else if (!fling_may_be_active_on_main_thread_) return DROP_EVENT; return DID_NOT_HANDLE; case WebInputEvent::TouchStart: return HandleTouchStart(static_cast<const WebTouchEvent&>(event)); case WebInputEvent::MouseMove: { const WebMouseEvent& mouse_event = static_cast<const WebMouseEvent&>(event); // TODO(tony): Ignore when mouse buttons are down? // TODO(davemoore): This should never happen, but bug #326635 showed some // surprising crashes. CHECK(input_handler_); input_handler_->MouseMoveAt(gfx::Point(mouse_event.x, mouse_event.y)); return DID_NOT_HANDLE; } default: if (WebInputEvent::isKeyboardEventType(event.type)) { // Only call |CancelCurrentFling()| if a fling was active, as it will // otherwise disrupt an in-progress touch scroll. if (fling_curve_) CancelCurrentFling(); } break; } return DID_NOT_HANDLE; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleMouseWheel( const WebMouseWheelEvent& wheel_event) { InputHandlerProxy::EventDisposition result = DID_NOT_HANDLE; cc::InputHandlerScrollResult scroll_result; // TODO(ccameron): The rail information should be pushed down into // InputHandler. gfx::Vector2dF scroll_delta( wheel_event.railsMode != WebInputEvent::RailsModeVertical ? -wheel_event.deltaX : 0, wheel_event.railsMode != WebInputEvent::RailsModeHorizontal ? -wheel_event.deltaY : 0); if (wheel_event.scrollByPage) { // TODO(jamesr): We don't properly handle scroll by page in the compositor // thread, so punt it to the main thread. http://crbug.com/236639 result = DID_NOT_HANDLE; } else if (!wheel_event.canScroll) { // Wheel events with |canScroll| == false will not trigger scrolling, // only event handlers. Forward to the main thread. result = DID_NOT_HANDLE; } else if (smooth_scroll_enabled_) { cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollAnimated(gfx::Point(wheel_event.x, wheel_event.y), scroll_delta); switch (scroll_status) { case cc::InputHandler::SCROLL_STARTED: result = DID_HANDLE; break; case cc::InputHandler::SCROLL_IGNORED: result = DROP_EVENT; default: result = DID_NOT_HANDLE; break; } } else { cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin( gfx::Point(wheel_event.x, wheel_event.y), cc::InputHandler::WHEEL); switch (scroll_status) { case cc::InputHandler::SCROLL_STARTED: { TRACE_EVENT_INSTANT2("input", "InputHandlerProxy::handle_input wheel scroll", TRACE_EVENT_SCOPE_THREAD, "deltaX", scroll_delta.x(), "deltaY", scroll_delta.y()); gfx::Point scroll_point(wheel_event.x, wheel_event.y); scroll_result = input_handler_->ScrollBy(scroll_point, scroll_delta); HandleOverscroll(scroll_point, scroll_result); input_handler_->ScrollEnd(); result = scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT; break; } case cc::InputHandler::SCROLL_IGNORED: // TODO(jamesr): This should be DROP_EVENT, but in cases where we fail // to properly sync scrollability it's safer to send the event to the // main thread. Change back to DROP_EVENT once we have synchronization // bugs sorted out. result = DID_NOT_HANDLE; break; case cc::InputHandler::SCROLL_UNKNOWN: case cc::InputHandler::SCROLL_ON_MAIN_THREAD: result = DID_NOT_HANDLE; break; case cc::InputHandler::ScrollStatusCount: NOTREACHED(); break; } } // Send the event and its disposition to the elasticity controller to update // the over-scroll animation. If the event is to be handled on the main // thread, the event and its disposition will be sent to the elasticity // controller after being handled on the main thread. if (scroll_elasticity_controller_ && result != DID_NOT_HANDLE) { // Note that the call to the elasticity controller is made asynchronously, // to minimize divergence between main thread and impl thread event // handling paths. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&InputScrollElasticityController::ObserveWheelEventAndResult, scroll_elasticity_controller_->GetWeakPtr(), wheel_event, scroll_result)); } return result; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollBegin( const WebGestureEvent& gesture_event) { if (gesture_scroll_on_impl_thread_) CancelCurrentFling(); #ifndef NDEBUG DCHECK(!expect_scroll_update_end_); expect_scroll_update_end_ = true; #endif cc::InputHandler::ScrollStatus scroll_status; if (gesture_event.data.scrollBegin.targetViewport) { scroll_status = input_handler_->RootScrollBegin(cc::InputHandler::GESTURE); } else { scroll_status = input_handler_->ScrollBegin( gfx::Point(gesture_event.x, gesture_event.y), cc::InputHandler::GESTURE); } UMA_HISTOGRAM_ENUMERATION("Renderer4.CompositorScrollHitTestResult", scroll_status, cc::InputHandler::ScrollStatusCount); switch (scroll_status) { case cc::InputHandler::SCROLL_STARTED: TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::handle_input gesture scroll", TRACE_EVENT_SCOPE_THREAD); gesture_scroll_on_impl_thread_ = true; return DID_HANDLE; case cc::InputHandler::SCROLL_UNKNOWN: case cc::InputHandler::SCROLL_ON_MAIN_THREAD: return DID_NOT_HANDLE; case cc::InputHandler::SCROLL_IGNORED: return DROP_EVENT; case cc::InputHandler::ScrollStatusCount: NOTREACHED(); break; } return DID_NOT_HANDLE; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollUpdate( const WebGestureEvent& gesture_event) { #ifndef NDEBUG DCHECK(expect_scroll_update_end_); #endif if (!gesture_scroll_on_impl_thread_ && !gesture_pinch_on_impl_thread_) return DID_NOT_HANDLE; gfx::Point scroll_point(gesture_event.x, gesture_event.y); gfx::Vector2dF scroll_delta(-gesture_event.data.scrollUpdate.deltaX, -gesture_event.data.scrollUpdate.deltaY); cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy( scroll_point, scroll_delta); HandleOverscroll(scroll_point, scroll_result); return scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollEnd( const WebGestureEvent& gesture_event) { #ifndef NDEBUG DCHECK(expect_scroll_update_end_); expect_scroll_update_end_ = false; #endif input_handler_->ScrollEnd(); if (!gesture_scroll_on_impl_thread_) return DID_NOT_HANDLE; gesture_scroll_on_impl_thread_ = false; return DID_HANDLE; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureFlingStart( const WebGestureEvent& gesture_event) { cc::InputHandler::ScrollStatus scroll_status; if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) { if (gesture_event.data.flingStart.targetViewport) { scroll_status = input_handler_->RootScrollBegin( cc::InputHandler::NON_BUBBLING_GESTURE); } else { scroll_status = input_handler_->ScrollBegin( gfx::Point(gesture_event.x, gesture_event.y), cc::InputHandler::NON_BUBBLING_GESTURE); } } else { if (!gesture_scroll_on_impl_thread_) scroll_status = cc::InputHandler::SCROLL_ON_MAIN_THREAD; else scroll_status = input_handler_->FlingScrollBegin(); } #ifndef NDEBUG expect_scroll_update_end_ = false; #endif switch (scroll_status) { case cc::InputHandler::SCROLL_STARTED: { if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) input_handler_->ScrollEnd(); const float vx = gesture_event.data.flingStart.velocityX; const float vy = gesture_event.data.flingStart.velocityY; current_fling_velocity_ = gfx::Vector2dF(vx, vy); DCHECK(!current_fling_velocity_.IsZero()); fling_curve_.reset(client_->CreateFlingAnimationCurve( gesture_event.sourceDevice, WebFloatPoint(vx, vy), blink::WebSize())); disallow_horizontal_fling_scroll_ = !vx; disallow_vertical_fling_scroll_ = !vy; TRACE_EVENT_ASYNC_BEGIN2("input", "InputHandlerProxy::HandleGestureFling::started", this, "vx", vx, "vy", vy); // Note that the timestamp will only be used to kickstart the animation if // its sufficiently close to the timestamp of the first call |Animate()|. has_fling_animation_started_ = false; fling_parameters_.startTime = gesture_event.timeStampSeconds; fling_parameters_.delta = WebFloatPoint(vx, vy); fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y); fling_parameters_.globalPoint = WebPoint(gesture_event.globalX, gesture_event.globalY); fling_parameters_.modifiers = gesture_event.modifiers; fling_parameters_.sourceDevice = gesture_event.sourceDevice; input_handler_->SetNeedsAnimateInput(); return DID_HANDLE; } case cc::InputHandler::SCROLL_UNKNOWN: case cc::InputHandler::SCROLL_ON_MAIN_THREAD: { TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::HandleGestureFling::" "scroll_on_main_thread", TRACE_EVENT_SCOPE_THREAD); gesture_scroll_on_impl_thread_ = false; fling_may_be_active_on_main_thread_ = true; return DID_NOT_HANDLE; } case cc::InputHandler::SCROLL_IGNORED: { TRACE_EVENT_INSTANT0( "input", "InputHandlerProxy::HandleGestureFling::ignored", TRACE_EVENT_SCOPE_THREAD); gesture_scroll_on_impl_thread_ = false; if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) { // We still pass the curve to the main thread if there's nothing // scrollable, in case something // registers a handler before the curve is over. return DID_NOT_HANDLE; } return DROP_EVENT; } case cc::InputHandler::ScrollStatusCount: NOTREACHED(); break; } return DID_NOT_HANDLE; } InputHandlerProxy::EventDisposition InputHandlerProxy::HandleTouchStart( const blink::WebTouchEvent& touch_event) { for (size_t i = 0; i < touch_event.touchesLength; ++i) { if (touch_event.touches[i].state != WebTouchPoint::StatePressed) continue; if (input_handler_->DoTouchEventsBlockScrollAt( gfx::Point(touch_event.touches[i].position.x, touch_event.touches[i].position.y))) { // TODO(rbyers): We should consider still sending the touch events to // main asynchronously (crbug.com/455539). return DID_NOT_HANDLE; } } return DROP_EVENT; } bool InputHandlerProxy::FilterInputEventForFlingBoosting( const WebInputEvent& event) { if (!WebInputEvent::isGestureEventType(event.type)) return false; if (!fling_curve_) { DCHECK(!deferred_fling_cancel_time_seconds_); return false; } const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(event); if (gesture_event.type == WebInputEvent::GestureFlingCancel) { if (gesture_event.data.flingCancel.preventBoosting) return false; if (current_fling_velocity_.LengthSquared() < kMinBoostFlingSpeedSquare) return false; TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::FlingBoostStart", TRACE_EVENT_SCOPE_THREAD); deferred_fling_cancel_time_seconds_ = event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds; return true; } // A fling is either inactive or is "free spinning", i.e., has yet to be // interrupted by a touch gesture, in which case there is nothing to filter. if (!deferred_fling_cancel_time_seconds_) return false; // Gestures from a different source should immediately interrupt the fling. if (gesture_event.sourceDevice != fling_parameters_.sourceDevice) { CancelCurrentFling(); return false; } switch (gesture_event.type) { case WebInputEvent::GestureTapCancel: case WebInputEvent::GestureTapDown: return false; case WebInputEvent::GestureScrollBegin: if (!input_handler_->IsCurrentlyScrollingLayerAt( gfx::Point(gesture_event.x, gesture_event.y), fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchpad ? cc::InputHandler::NON_BUBBLING_GESTURE : cc::InputHandler::GESTURE)) { CancelCurrentFling(); return false; } // TODO(jdduke): Use |gesture_event.data.scrollBegin.delta{X,Y}Hint| to // determine if the ScrollBegin should immediately cancel the fling. ExtendBoostedFlingTimeout(gesture_event); return true; case WebInputEvent::GestureScrollUpdate: { const double time_since_last_boost_event = event.timeStampSeconds - last_fling_boost_event_.timeStampSeconds; if (ShouldSuppressScrollForFlingBoosting(current_fling_velocity_, gesture_event, time_since_last_boost_event)) { ExtendBoostedFlingTimeout(gesture_event); return true; } CancelCurrentFling(); return false; } case WebInputEvent::GestureScrollEnd: // Clear the last fling boost event *prior* to fling cancellation, // preventing insertion of a synthetic GestureScrollBegin. last_fling_boost_event_ = WebGestureEvent(); CancelCurrentFling(); return true; case WebInputEvent::GestureFlingStart: { DCHECK_EQ(fling_parameters_.sourceDevice, gesture_event.sourceDevice); bool fling_boosted = fling_parameters_.modifiers == gesture_event.modifiers && ShouldBoostFling(current_fling_velocity_, gesture_event); gfx::Vector2dF new_fling_velocity( gesture_event.data.flingStart.velocityX, gesture_event.data.flingStart.velocityY); DCHECK(!new_fling_velocity.IsZero()); if (fling_boosted) current_fling_velocity_ += new_fling_velocity; else current_fling_velocity_ = new_fling_velocity; WebFloatPoint velocity(current_fling_velocity_.x(), current_fling_velocity_.y()); deferred_fling_cancel_time_seconds_ = 0; disallow_horizontal_fling_scroll_ = !velocity.x; disallow_vertical_fling_scroll_ = !velocity.y; last_fling_boost_event_ = WebGestureEvent(); fling_curve_.reset(client_->CreateFlingAnimationCurve( gesture_event.sourceDevice, velocity, blink::WebSize())); fling_parameters_.startTime = gesture_event.timeStampSeconds; fling_parameters_.delta = velocity; fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y); fling_parameters_.globalPoint = WebPoint(gesture_event.globalX, gesture_event.globalY); TRACE_EVENT_INSTANT2("input", fling_boosted ? "InputHandlerProxy::FlingBoosted" : "InputHandlerProxy::FlingReplaced", TRACE_EVENT_SCOPE_THREAD, "vx", current_fling_velocity_.x(), "vy", current_fling_velocity_.y()); // The client expects balanced calls between a consumed GestureFlingStart // and |DidStopFlinging()|. TODO(jdduke): Provide a count parameter to // |DidStopFlinging()| and only send after the accumulated fling ends. client_->DidStopFlinging(); return true; } default: // All other types of gestures (taps, presses, etc...) will complete the // deferred fling cancellation. CancelCurrentFling(); return false; } } void InputHandlerProxy::ExtendBoostedFlingTimeout( const blink::WebGestureEvent& event) { TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::ExtendBoostedFlingTimeout", TRACE_EVENT_SCOPE_THREAD); deferred_fling_cancel_time_seconds_ = event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds; last_fling_boost_event_ = event; } void InputHandlerProxy::Animate(base::TimeTicks time) { if (scroll_elasticity_controller_) scroll_elasticity_controller_->Animate(time); if (!fling_curve_) return; double monotonic_time_sec = InSecondsF(time); if (deferred_fling_cancel_time_seconds_ && monotonic_time_sec > deferred_fling_cancel_time_seconds_) { CancelCurrentFling(); return; } client_->DidAnimateForInput(); if (!has_fling_animation_started_) { has_fling_animation_started_ = true; // Guard against invalid, future or sufficiently stale start times, as there // are no guarantees fling event and animation timestamps are compatible. if (!fling_parameters_.startTime || monotonic_time_sec <= fling_parameters_.startTime || monotonic_time_sec >= fling_parameters_.startTime + kMaxSecondsFromFlingTimestampToFirstAnimate) { fling_parameters_.startTime = monotonic_time_sec; input_handler_->SetNeedsAnimateInput(); return; } } bool fling_is_active = fling_curve_->apply(monotonic_time_sec - fling_parameters_.startTime, this); if (disallow_vertical_fling_scroll_ && disallow_horizontal_fling_scroll_) fling_is_active = false; if (fling_is_active) { input_handler_->SetNeedsAnimateInput(); } else { TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::animate::flingOver", TRACE_EVENT_SCOPE_THREAD); CancelCurrentFling(); } } void InputHandlerProxy::MainThreadHasStoppedFlinging() { fling_may_be_active_on_main_thread_ = false; client_->DidStopFlinging(); } void InputHandlerProxy::ReconcileElasticOverscrollAndRootScroll() { if (scroll_elasticity_controller_) scroll_elasticity_controller_->ReconcileStretchAndScroll(); } void InputHandlerProxy::HandleOverscroll( const gfx::Point& causal_event_viewport_point, const cc::InputHandlerScrollResult& scroll_result) { DCHECK(client_); if (!scroll_result.did_overscroll_root) return; TRACE_EVENT2("input", "InputHandlerProxy::DidOverscroll", "dx", scroll_result.unused_scroll_delta.x(), "dy", scroll_result.unused_scroll_delta.y()); DidOverscrollParams params; params.accumulated_overscroll = scroll_result.accumulated_root_overscroll; params.latest_overscroll_delta = scroll_result.unused_scroll_delta; params.current_fling_velocity = ToClientScrollIncrement(current_fling_velocity_); params.causal_event_viewport_point = causal_event_viewport_point; if (fling_curve_) { static const int kFlingOverscrollThreshold = 1; disallow_horizontal_fling_scroll_ |= std::abs(params.accumulated_overscroll.x()) >= kFlingOverscrollThreshold; disallow_vertical_fling_scroll_ |= std::abs(params.accumulated_overscroll.y()) >= kFlingOverscrollThreshold; } client_->DidOverscroll(params); } bool InputHandlerProxy::CancelCurrentFling() { if (CancelCurrentFlingWithoutNotifyingClient()) { client_->DidStopFlinging(); return true; } return false; } bool InputHandlerProxy::CancelCurrentFlingWithoutNotifyingClient() { bool had_fling_animation = fling_curve_; if (had_fling_animation && fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchscreen) { input_handler_->ScrollEnd(); TRACE_EVENT_ASYNC_END0( "input", "InputHandlerProxy::HandleGestureFling::started", this); } TRACE_EVENT_INSTANT1("input", "InputHandlerProxy::CancelCurrentFling", TRACE_EVENT_SCOPE_THREAD, "had_fling_animation", had_fling_animation); fling_curve_.reset(); has_fling_animation_started_ = false; gesture_scroll_on_impl_thread_ = false; current_fling_velocity_ = gfx::Vector2dF(); fling_parameters_ = blink::WebActiveWheelFlingParameters(); if (deferred_fling_cancel_time_seconds_) { deferred_fling_cancel_time_seconds_ = 0; WebGestureEvent last_fling_boost_event = last_fling_boost_event_; last_fling_boost_event_ = WebGestureEvent(); if (last_fling_boost_event.type == WebInputEvent::GestureScrollBegin || last_fling_boost_event.type == WebInputEvent::GestureScrollUpdate) { // Synthesize a GestureScrollBegin, as the original was suppressed. HandleInputEvent(ObtainGestureScrollBegin(last_fling_boost_event)); } } return had_fling_animation; } bool InputHandlerProxy::TouchpadFlingScroll( const WebFloatSize& increment) { WebMouseWheelEvent synthetic_wheel; synthetic_wheel.type = WebInputEvent::MouseWheel; synthetic_wheel.deltaX = increment.width; synthetic_wheel.deltaY = increment.height; synthetic_wheel.hasPreciseScrollingDeltas = true; synthetic_wheel.x = fling_parameters_.point.x; synthetic_wheel.y = fling_parameters_.point.y; synthetic_wheel.globalX = fling_parameters_.globalPoint.x; synthetic_wheel.globalY = fling_parameters_.globalPoint.y; synthetic_wheel.modifiers = fling_parameters_.modifiers; InputHandlerProxy::EventDisposition disposition = HandleInputEvent(synthetic_wheel); switch (disposition) { case DID_HANDLE: return true; case DROP_EVENT: break; case DID_NOT_HANDLE: TRACE_EVENT_INSTANT0("input", "InputHandlerProxy::scrollBy::AbortFling", TRACE_EVENT_SCOPE_THREAD); // If we got a DID_NOT_HANDLE, that means we need to deliver wheels on the // main thread. In this case we need to schedule a commit and transfer the // fling curve over to the main thread and run the rest of the wheels from // there. This can happen when flinging a page that contains a scrollable // subarea that we can't scroll on the thread if the fling starts outside // the subarea but then is flung "under" the pointer. client_->TransferActiveWheelFlingAnimation(fling_parameters_); fling_may_be_active_on_main_thread_ = true; CancelCurrentFlingWithoutNotifyingClient(); break; } return false; } bool InputHandlerProxy::scrollBy(const WebFloatSize& increment, const WebFloatSize& velocity) { WebFloatSize clipped_increment; WebFloatSize clipped_velocity; if (!disallow_horizontal_fling_scroll_) { clipped_increment.width = increment.width; clipped_velocity.width = velocity.width; } if (!disallow_vertical_fling_scroll_) { clipped_increment.height = increment.height; clipped_velocity.height = velocity.height; } current_fling_velocity_ = clipped_velocity; // Early out if the increment is zero, but avoid early terimination if the // velocity is still non-zero. if (clipped_increment == WebFloatSize()) return clipped_velocity != WebFloatSize(); TRACE_EVENT2("input", "InputHandlerProxy::scrollBy", "x", clipped_increment.width, "y", clipped_increment.height); bool did_scroll = false; switch (fling_parameters_.sourceDevice) { case blink::WebGestureDeviceTouchpad: did_scroll = TouchpadFlingScroll(clipped_increment); break; case blink::WebGestureDeviceTouchscreen: { clipped_increment = ToClientScrollIncrement(clipped_increment); cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy( fling_parameters_.point, clipped_increment); HandleOverscroll(fling_parameters_.point, scroll_result); did_scroll = scroll_result.did_scroll; } break; } if (did_scroll) { fling_parameters_.cumulativeScroll.width += clipped_increment.width; fling_parameters_.cumulativeScroll.height += clipped_increment.height; } // It's possible the provided |increment| is sufficiently small as to not // trigger a scroll, e.g., with a trivial time delta between fling updates. // Return true in this case to prevent early fling termination. if (std::abs(clipped_increment.width) < kScrollEpsilon && std::abs(clipped_increment.height) < kScrollEpsilon) return true; return did_scroll; } } // namespace content
Just-D/chromium-1
content/renderer/input/input_handler_proxy.cc
C++
bsd-3-clause
36,271
<?php namespace common\models; use common\models\base\BusWay as BaseBusWay; use Yii; /** * This is the model class for table "bus_way". */ class BusWay extends BaseBusWay { /** * @inheritdoc */ public function rules() { return array_replace_recursive(parent::rules(), [ [['name', 'bus_info_id', 'bus_route_id'], 'required'], [['name'], 'string'], [['bus_info_id', 'active','b_reverse', 'ended', 'bus_route_id', 'created_by', 'updated_by', 'lock'], 'integer'], [['date_begin', 'date_end', 'date_add', 'date_edit', 'reverse_date_begin','reverse_date_end'], 'safe'], [['price'], 'number'], [['path_time'], 'string', 'max' => 45], [['lock'], 'default', 'value' => '0'], [['lock'], 'mootensai\components\OptimisticLockValidator'] ]); } /** * @inheritdoc */ public function attributeHints() { return [ //'id' => Yii::t('app', 'ID'), 'name' => Yii::t('app', 'Name'), 'bus_info_id' => Yii::t('app', 'Bus Info ID'), 'date_begin' => Yii::t('app', 'Date Begin'), 'date_end' => Yii::t('app', 'Date End'), 'bus_route_id' => Yii::t('app', 'Bus Route ID'), 'path_time' => Yii::t('app', 'Path Time'), 'price' => Yii::t('app', 'Price'), 'date_add' => Yii::t('app', 'Date Add'), 'date_edit' => Yii::t('app', 'Date Edit'), 'lock' => Yii::t('app', 'Lock'), //'stop' => Yii::t('app', 'Stop'), ]; } }
tkirsan4ik/yii2_region
common/models/BusWay.php
PHP
bsd-3-clause
1,697
import datetime import time from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models import Q from django.db.models.signals import pre_save from django.contrib.contenttypes.fields import GenericRelation from django.contrib.auth.models import User from tidings.models import NotificationsMixin from kitsune import forums from kitsune.access.utils import has_perm, perm_is_defined_on from kitsune.flagit.models import FlaggedObject from kitsune.sumo.templatetags.jinja_helpers import urlparams, wiki_to_html from kitsune.sumo.urlresolvers import reverse from kitsune.sumo.models import ModelBase from kitsune.search.models import ( SearchMappingType, SearchMixin, register_for_indexing, register_mapping_type) def _last_post_from(posts, exclude_post=None): """Return the most recent post in the given set, excluding the given post. If there are none, return None. """ if exclude_post: posts = posts.exclude(id=exclude_post.id) posts = posts.order_by('-created') try: return posts[0] except IndexError: return None class ThreadLockedError(Exception): """Trying to create a post in a locked thread.""" class Forum(NotificationsMixin, ModelBase): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True) description = models.TextField(null=True) last_post = models.ForeignKey('Post', related_name='last_post_in_forum', null=True, on_delete=models.SET_NULL) # Dictates the order in which forums are displayed in the forum list. display_order = models.IntegerField(default=1, db_index=True) # Whether or not this forum is visible in the forum list. is_listed = models.BooleanField(default=True, db_index=True) class Meta(object): ordering = ['display_order', 'id'] permissions = ( ('view_in_forum', 'Can view restricted forums'), ('post_in_forum', 'Can post in restricted forums')) def __unicode__(self): return self.name def get_absolute_url(self): return reverse('forums.threads', kwargs={'forum_slug': self.slug}) def allows_viewing_by(self, user): """Return whether a user can view me, my threads, and their posts.""" return (self._allows_public_viewing() or has_perm(user, 'forums_forum.view_in_forum', self)) def _allows_public_viewing(self): """Return whether I am a world-readable forum. If a django-authority permission relates to me, I am considered non- public. (We assume that you attached a permission to me in order to assign it to some users or groups.) Considered adding a Public flag to this model, but we didn't want it to show up on form and thus be accidentally flippable by readers of the Admin forum, who are all privileged enough to do so. """ return not perm_is_defined_on('forums_forum.view_in_forum', self) def allows_posting_by(self, user): """Return whether a user can make threads and posts in me.""" return (self._allows_public_posting() or has_perm(user, 'forums_forum.post_in_forum', self)) def _allows_public_posting(self): """Return whether I am a world-writable forum.""" return not perm_is_defined_on('forums_forum.post_in_forum', self) def update_last_post(self, exclude_thread=None, exclude_post=None): """Set my last post to the newest, excluding given thread and post.""" posts = Post.objects.filter(thread__forum=self) if exclude_thread: posts = posts.exclude(thread=exclude_thread) self.last_post = _last_post_from(posts, exclude_post=exclude_post) @classmethod def authorized_forums_for_user(cls, user): """Returns the forums this user is authorized to view""" return [f for f in Forum.objects.all() if f.allows_viewing_by(user)] class Thread(NotificationsMixin, ModelBase, SearchMixin): title = models.CharField(max_length=255) forum = models.ForeignKey('Forum') created = models.DateTimeField(default=datetime.datetime.now, db_index=True) creator = models.ForeignKey(User) last_post = models.ForeignKey('Post', related_name='last_post_in', null=True, on_delete=models.SET_NULL) replies = models.IntegerField(default=0) is_locked = models.BooleanField(default=False) is_sticky = models.BooleanField(default=False, db_index=True) class Meta: ordering = ['-is_sticky', '-last_post__created'] def __setattr__(self, attr, val): """Notice when the forum field changes. A property won't do here, because it usurps the "forum" name and prevents us from using lookups like Thread.objects.filter(forum=f). """ if attr == 'forum' and not hasattr(self, '_old_forum'): try: self._old_forum = self.forum except ObjectDoesNotExist: pass super(Thread, self).__setattr__(attr, val) @property def last_page(self): """Returns the page number for the last post.""" return self.replies / forums.POSTS_PER_PAGE + 1 def __unicode__(self): return self.title def delete(self, *args, **kwargs): """Override delete method to update parent forum info.""" forum = Forum.objects.get(pk=self.forum.id) if forum.last_post and forum.last_post.thread_id == self.id: forum.update_last_post(exclude_thread=self) forum.save() super(Thread, self).delete(*args, **kwargs) def new_post(self, author, content): """Create a new post, if the thread is unlocked.""" if self.is_locked: raise ThreadLockedError return self.post_set.create(author=author, content=content) def get_absolute_url(self): return reverse('forums.posts', args=[self.forum.slug, self.id]) def get_last_post_url(self): query = {'last': self.last_post_id} page = self.last_page if page > 1: query['page'] = page url = reverse('forums.posts', args=[self.forum.slug, self.id]) return urlparams(url, hash='post-%s' % self.last_post_id, **query) def save(self, *args, **kwargs): super(Thread, self).save(*args, **kwargs) old_forum = getattr(self, '_old_forum', None) new_forum = self.forum if old_forum and old_forum != new_forum: old_forum.update_last_post(exclude_thread=self) old_forum.save() new_forum.update_last_post() new_forum.save() del self._old_forum def update_last_post(self, exclude_post=None): """Set my last post to the newest, excluding the given post.""" last = _last_post_from(self.post_set, exclude_post=exclude_post) self.last_post = last # If self.last_post is None, and this was called from Post.delete, # then Post.delete will erase the thread, as well. @classmethod def get_mapping_type(cls): return ThreadMappingType @register_mapping_type class ThreadMappingType(SearchMappingType): seconds_ago_filter = 'last_post__created__gte' @classmethod def search(cls): return super(ThreadMappingType, cls).search().order_by('created') @classmethod def get_model(cls): return Thread @classmethod def get_query_fields(cls): return ['post_title', 'post_content'] @classmethod def get_mapping(cls): return { 'properties': { 'id': {'type': 'long'}, 'model': {'type': 'string', 'index': 'not_analyzed'}, 'url': {'type': 'string', 'index': 'not_analyzed'}, 'indexed_on': {'type': 'integer'}, 'created': {'type': 'integer'}, 'updated': {'type': 'integer'}, 'post_forum_id': {'type': 'integer'}, 'post_title': {'type': 'string', 'analyzer': 'snowball'}, 'post_is_sticky': {'type': 'boolean'}, 'post_is_locked': {'type': 'boolean'}, 'post_author_id': {'type': 'integer'}, 'post_author_ord': {'type': 'string', 'index': 'not_analyzed'}, 'post_content': {'type': 'string', 'analyzer': 'snowball', 'store': 'yes', 'term_vector': 'with_positions_offsets'}, 'post_replies': {'type': 'integer'} } } @classmethod def extract_document(cls, obj_id, obj=None): """Extracts interesting thing from a Thread and its Posts""" if obj is None: model = cls.get_model() obj = model.objects.select_related('last_post').get(pk=obj_id) d = {} d['id'] = obj.id d['model'] = cls.get_mapping_type_name() d['url'] = obj.get_absolute_url() d['indexed_on'] = int(time.time()) # TODO: Sphinx stores created and updated as seconds since the # epoch, so we convert them to that format here so that the # search view works correctly. When we ditch Sphinx, we should # see if it's faster to filter on ints or whether we should # switch them to dates. d['created'] = int(time.mktime(obj.created.timetuple())) if obj.last_post is not None: d['updated'] = int(time.mktime(obj.last_post.created.timetuple())) else: d['updated'] = None d['post_forum_id'] = obj.forum.id d['post_title'] = obj.title d['post_is_sticky'] = obj.is_sticky d['post_is_locked'] = obj.is_locked d['post_replies'] = obj.replies author_ids = set() author_ords = set() content = [] posts = Post.objects.filter( thread_id=obj.id).select_related('author') for post in posts: author_ids.add(post.author.id) author_ords.add(post.author.username) content.append(post.content) d['post_author_id'] = list(author_ids) d['post_author_ord'] = list(author_ords) d['post_content'] = content return d register_for_indexing('forums', Thread) class Post(ModelBase): thread = models.ForeignKey('Thread') content = models.TextField() author = models.ForeignKey(User) created = models.DateTimeField(default=datetime.datetime.now, db_index=True) updated = models.DateTimeField(default=datetime.datetime.now, db_index=True) updated_by = models.ForeignKey(User, related_name='post_last_updated_by', null=True) flags = GenericRelation(FlaggedObject) class Meta: ordering = ['created'] def __unicode__(self): return self.content[:50] def save(self, *args, **kwargs): """ Override save method to update parent thread info and take care of created and updated. """ new = self.id is None if not new: self.updated = datetime.datetime.now() super(Post, self).save(*args, **kwargs) if new: self.thread.replies = self.thread.post_set.count() - 1 self.thread.last_post = self self.thread.save() self.thread.forum.last_post = self self.thread.forum.save() def delete(self, *args, **kwargs): """Override delete method to update parent thread info.""" thread = Thread.objects.get(pk=self.thread.id) if thread.last_post_id and thread.last_post_id == self.id: thread.update_last_post(exclude_post=self) thread.replies = thread.post_set.count() - 2 thread.save() forum = Forum.objects.get(pk=thread.forum.id) if forum.last_post_id and forum.last_post_id == self.id: forum.update_last_post(exclude_post=self) forum.save() super(Post, self).delete(*args, **kwargs) # If I was the last post in the thread, delete the thread. if thread.last_post is None: thread.delete() @property def page(self): """Get the page of the thread on which this post is found.""" t = self.thread earlier = t.post_set.filter(created__lte=self.created).count() - 1 if earlier < 1: return 1 return earlier / forums.POSTS_PER_PAGE + 1 def get_absolute_url(self): query = {} if self.page > 1: query = {'page': self.page} url_ = self.thread.get_absolute_url() return urlparams(url_, hash='post-%s' % self.id, **query) @property def content_parsed(self): return wiki_to_html(self.content) register_for_indexing('forums', Post, instance_to_indexee=lambda p: p.thread) def user_pre_save(sender, instance, **kw): """When a user's username is changed, we must reindex the threads they participated in. """ if instance.id: user = User.objects.get(id=instance.id) if user.username != instance.username: threads = ( Thread.objects .filter( Q(creator=instance) | Q(post__author=instance)) .only('id') .distinct()) for t in threads: t.index_later() pre_save.connect( user_pre_save, sender=User, dispatch_uid='forums_user_pre_save')
anushbmx/kitsune
kitsune/forums/models.py
Python
bsd-3-clause
13,732
<?php /** * Created by PhpStorm. * User: David Cocom * Date: 03/02/2016 * Time: 10:58 AM */ use yii\helpers\Html; ?> <div class="row"> <p> Enmarcado en el Programa Institucional Prioritario de Gestión del Medio Ambiente, el Sistema de Gestión Ambiental tiene como alcance inicial las actividades, procesos e instalaciones de las siguientes dependencias: </p> <div class="col-lg-6 col-lg-offset-1 wow fadeInUp"> <?=Html::img('images/alcance_del_programa.png')?> </div> <div class="wow fadeInRight col-lg-4 border-rounded"> <strong>Nota:</strong> Las Facultades del CCSEAH se integrarán al Sistema de Gestión Ambiental conforme sus instalaciones se ubiquen dentro del Campus. </BR></BR> LAS DEMÁS DEPENDENCIAS SE IRÁN INTEGRANDO AL SISTEMA DE MANERA PAULATINA, SIN EMBARGO, TODAS LAS ACCIONES DEL PROGRAMA SE INCLUYEN EN TODA LA UNIVERSIDAD. </div> </div>
davcocom/SGA
views/site/sga/scope.php
PHP
bsd-3-clause
947
package org.gearman; import org.gearman.JobServerPoolAbstract.ConnectionController; import org.gearman.core.GearmanConnection; import org.gearman.core.GearmanPacket; import org.gearman.core.GearmanPacket.Magic; import org.gearman.util.ByteArray; /** * The {@link GearmanJob} implementation for the {@link GearmanFunction} object. It provides * the underlying implementation in sending data back to the client. * * @author isaiah.v */ class WorkerJob extends GearmanJob { private final static byte[] DEFAULT_UID = new byte[]{0}; protected WorkerJob(final String function,final byte[] jobData,final ConnectionController<?,?> conn,final ByteArray jobHandle) { super(function, jobData, DEFAULT_UID); super.setConnection(conn, jobHandle); } @Override public synchronized final void callbackData(final byte[] data) { if(this.isComplete()) throw new IllegalStateException("Job has completed"); final GearmanConnection<?> conn = super.getConnection(); final ByteArray jobHandle = super.getJobHandle(); assert conn!=null; assert jobHandle!=null; conn.sendPacket(GearmanPacket.createWORK_DATA(Magic.REQ, jobHandle.getBytes(), data), null /*TODO*/); } @Override public synchronized final void callbackWarning(final byte[] warning) { if(this.isComplete()) throw new IllegalStateException("Job has completed"); final GearmanConnection<?> conn = super.getConnection(); final ByteArray jobHandle = super.getJobHandle(); assert conn!=null; assert jobHandle!=null; conn.sendPacket(GearmanPacket.createWORK_WARNING(Magic.REQ, jobHandle.getBytes(), warning), null /*TODO*/); } /* @Override public synchronized final void callbackException(final byte[] exception) { if(this.isComplete()) throw new IllegalStateException("Job has completed"); final GearmanConnection<?> conn = super.getConnection(); final byte[] jobHandle = super.getJobHandle(); assert conn!=null; assert jobHandle!=null; conn.sendPacket(GearmanPacket.createWORK_EXCEPTION(Magic.REQ, jobHandle, exception),null ,null); //TODO } */ @Override public void callbackStatus(long numerator, long denominator) { if(this.isComplete()) throw new IllegalStateException("Job has completed"); final GearmanConnection<?> conn = super.getConnection(); final ByteArray jobHandle = super.getJobHandle(); assert conn!=null; assert jobHandle!=null; conn.sendPacket(GearmanPacket.createWORK_STATUS(Magic.REQ, jobHandle.getBytes(), numerator, denominator), null /*TODO*/); } @Override protected synchronized void onComplete(GearmanJobResult result) { final GearmanConnection<?> conn = super.getConnection(); final ByteArray jobHandle = super.getJobHandle(); assert conn!=null; assert jobHandle!=null; if(result.isSuccessful()) { conn.sendPacket(GearmanPacket.createWORK_COMPLETE(Magic.REQ, jobHandle.getBytes(), result.getData()),null /*TODO*/); } else { conn.sendPacket(GearmanPacket.createWORK_FAIL(Magic.REQ, jobHandle.getBytes()),null /*TODO*/); } } }
fwix/java-gearman
src/org/gearman/WorkerJob.java
Java
bsd-3-clause
3,036
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 type CustomResourceDefinitionExpansion interface{}
gravitational/monitoring-app
watcher/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/generated_expansion.go
GO
apache-2.0
681
// Copyright (c) 2015-2021 The btcsuite developers // Copyright (c) 2015-2021 The Decred developers package btcec import ( secp "github.com/decred/dcrd/dcrec/secp256k1/v4" ) // JacobianPoint is an element of the group formed by the secp256k1 curve in // Jacobian projective coordinates and thus represents a point on the curve. type JacobianPoint = secp.JacobianPoint // MakeJacobianPoint returns a Jacobian point with the provided X, Y, and Z // coordinates. func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint { return secp.MakeJacobianPoint(x, y, z) } // AddNonConst adds the passed Jacobian points together and stores the result // in the provided result param in *non-constant* time. func AddNonConst(p1, p2, result *JacobianPoint) { secp.AddNonConst(p1, p2, result) } // DecompressY attempts to calculate the Y coordinate for the given X // coordinate such that the result pair is a point on the secp256k1 curve. It // adjusts Y based on the desired oddness and returns whether or not it was // successful since not all X coordinates are valid. // // The magnitude of the provided X coordinate field val must be a max of 8 for // a correct result. The resulting Y field val will have a max magnitude of 2. func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool { return secp.DecompressY(x, odd, resultY) } // DoubleNonConst doubles the passed Jacobian point and stores the result in // the provided result parameter in *non-constant* time. // // NOTE: The point must be normalized for this function to return the correct // result. The resulting point will be normalized. func DoubleNonConst(p, result *JacobianPoint) { secp.DoubleNonConst(p, result) } // ScalarBaseMultNonConst multiplies k*G where G is the base point of the group // and k is a big endian integer. The result is stored in Jacobian coordinates // (x1, y1, z1). // // NOTE: The resulting point will be normalized. func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) { secp.ScalarBaseMultNonConst(k, result) } // ScalarMultNonConst multiplies k*P where k is a big endian integer modulo the // curve order and P is a point in Jacobian projective coordinates and stores // the result in the provided Jacobian point. // // NOTE: The point must be normalized for this function to return the correct // result. The resulting point will be normalized. func ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) { secp.ScalarMultNonConst(k, point, result) }
btcsuite/btcd
btcec/curve.go
GO
isc
2,476
/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _GOBBY_APPLICATIONACTIONS_HPP_ #define _GOBBY_APPLICATIONACTIONS_HPP_ #include <giomm/actionmap.h> namespace Gobby { class ApplicationActions { public: ApplicationActions(Gio::ActionMap& map); const Glib::RefPtr<Gio::SimpleAction> quit; const Glib::RefPtr<Gio::SimpleAction> preferences; const Glib::RefPtr<Gio::SimpleAction> help; const Glib::RefPtr<Gio::SimpleAction> about; }; } #endif // _GOBBY_APPLICATIONACTIONS_HPP_
dagopoot/gobby
code/core/applicationactions.hpp
C++
isc
1,288
#!/usr/bin/env python import dockci.commands from dockci.server import APP, app_init, MANAGER if __name__ == "__main__": app_init() MANAGER.run()
sprucedev/DockCI
manage.py
Python
isc
157
import os, logging from PIL import Image from sqlalchemy.orm.session import object_session from sqlalchemy.orm.util import identity_key from iktomi.unstable.utils.image_resizers import ResizeFit from iktomi.utils import cached_property from ..files import TransientFile, PersistentFile from .files import FileEventHandlers, FileProperty logger = logging.getLogger(__name__) class ImageFile(PersistentFile): def _get_properties(self, properties=['width', 'height']): if 'width' in properties or 'height' in properties: image = Image.open(self.path) self.width, self.height = image.size @cached_property def width(self): self._get_properties(['width']) return self.width @cached_property def height(self): self._get_properties(['height']) return self.height class ImageEventHandlers(FileEventHandlers): def _2persistent(self, target, transient): # XXX move this method to file_manager # XXX Do this check or not? image = Image.open(transient.path) assert image.format in Image.SAVE and image.format != 'bmp',\ 'Unsupported image format' if self.prop.image_sizes: session = object_session(target) persistent_name = getattr(target, self.prop.attribute_name) pn, ext = os.path.splitext(persistent_name) image_crop = self.prop.resize(image, self.prop.image_sizes) if self.prop.force_rgb and image_crop.mode not in ['RGB', 'RGBA']: image_crop = image_crop.convert('RGB') if ext == '.gif': image_crop.format = 'jpeg' ext = '.jpeg' if self.prop.enhancements: for enhance, factor in self.prop.enhancements: image_crop = enhance(image_crop).enhance(factor) if self.prop.filter: image_crop = image_crop.filter(self.prop.filter) if not ext: # set extension if it is not set ext = '.' + image.format.lower() if pn + ext != persistent_name: persistent_name = pn + ext # XXX hack? setattr(target, self.prop.attribute_name, persistent_name) image_attr = getattr(target.__class__, self.prop.key) file_manager = persistent = session.find_file_manager(image_attr) persistent = file_manager.get_persistent(persistent_name, self.prop.persistent_cls) transient = session.find_file_manager(image_attr).new_transient(ext) kw = dict(quality=self.prop.quality) if self.prop.optimize: kw = dict(kw, optimize=True) image_crop.save(transient.path, **kw) session.find_file_manager(image_attr).store(transient, persistent) return persistent else: # Attention! This method can accept PersistentFile. # In this case one shold NEVER been deleted or rewritten. assert isinstance(transient, TransientFile), repr(transient) return FileEventHandlers._2persistent(self, target, transient) def before_update(self, mapper, connection, target): FileEventHandlers.before_update(self, mapper, connection, target) self._fill_img(mapper, connection, target) def before_insert(self, mapper, connection, target): FileEventHandlers.before_insert(self, mapper, connection, target) self._fill_img(mapper, connection, target) def _fill_img(self, mapper, connection, target): if self.prop.fill_from: # XXX Looks hacky value = getattr(target, self.prop.key) if value is None: base = getattr(target, self.prop.fill_from) if base is None: return if not os.path.isfile(base.path): logger.warn('Original file is absent %s %s %s', identity_key(instance=target), self.prop.fill_from, base.path) return ext = os.path.splitext(base.name)[1] session = object_session(target) image_attr = getattr(target.__class__, self.prop.key) name = session.find_file_manager(image_attr).new_file_name( self.prop.name_template, target, ext, '') setattr(target, self.prop.attribute_name, name) persistent = self._2persistent(target, base) setattr(target, self.prop.key, persistent) class ImageProperty(FileProperty): event_cls = ImageEventHandlers def _set_options(self, options): # XXX rename image_sizes? options = dict(options) self.image_sizes = options.pop('image_sizes', None) self.resize = options.pop('resize', None) or ResizeFit() # XXX implement self.fill_from = options.pop('fill_from', None) self.filter = options.pop('filter', None) self.enhancements = options.pop('enhancements', []) self.force_rgb = self.enhancements or \ self.filter or \ options.pop('force_rgb', True) self.quality = options.pop('quality', 85) self.optimize = options.pop('optimize', False) assert self.fill_from is None or self.image_sizes is not None options.setdefault('persistent_cls', ImageFile) FileProperty._set_options(self, options)
Lehych/iktomi
iktomi/unstable/db/sqla/images.py
Python
mit
5,666
module VegaServer::IncomingMessages module Relayable include VegaServer::Storageable attr_reader :payload def initialize(websocket, payload) @websocket = websocket @payload = payload @peer_id = @payload[:peer_id] end def handle VegaServer::OutgoingMessages.send_message(peer_websocket, message) end private def peer_websocket pool[@peer_id] end def client_id pool.inverted_pool[@websocket] end def message outgoing_message_class.new(client_id, read_relayable) end def outgoing_message_class raise NotImplementedError end def read_relayable raise NotImplementedError end end end
zuzmo/vega_server_ruby
lib/vega_server/incoming_messages/relayable.rb
Ruby
mit
721
t = int(raw_input()) MOD = 10**9 + 7 def modexp(a,b): res = 1 while b: if b&1: res *= a res %= MOD a = (a*a)%MOD b /= 2 return res fn = [1 for _ in xrange(100001)] ifn = [1 for _ in xrange(100001)] for i in range(1,100000): fn[i] = fn[i-1] * i fn[i] %= MOD ifn[i] = modexp(fn[i],MOD-2) def nCr(n,k): return fn[n] * ifn[k] * ifn[n-k] for ti in range(t): n = int(raw_input()) a = map(int,raw_input().split()) ans = 0 for i in range(n): if i%2==0: ans += nCr(n-1,i)%MOD * a[i]%MOD else: ans -= nCr(n-1,i)%MOD * a[i]%MOD ans %= MOD print ans
ManrajGrover/CodeSprint_India_2014
Qualification_Round_2/Editorials/array_simp_2.py
Python
mit
683
/** * Created by fengyuanzemin on 17/2/15. */ import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions'; import * as mutations from './mutations'; Vue.use(Vuex); const state = { isShow: false, msg: '出错了', isBig: true, token: localStorage.getItem('f-token'), init: false }; export default new Vuex.Store({ state, actions, mutations });
fengyuanzemin/graduation
frontend/src/store/index.js
JavaScript
mit
389
/*global describe, it, expect, require*/ const nodeToBox = require('../../../src/core/layout/node-to-box'); describe('nodeToBox', function () { 'use strict'; it('should convert node to a box', function () { expect(nodeToBox({x: 10, styles: ['blue'], y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['blue'], top: 20, width: 30, height: 40, level: 2}); }); it('should append default styles if not provided', function () { expect(nodeToBox({x: 10, y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['default'], top: 20, width: 30, height: 40, level: 2}); }); it('should return falsy for undefined', function () { expect(nodeToBox()).toBeFalsy(); }); it('should return falsy for falsy', function () { expect(nodeToBox(false)).toBeFalsy(); }); });
mindmup/mapjs
specs/core/layout/node-to-box-spec.js
JavaScript
mit
802
package migrate import ( "reflect" "testing" "github.com/influxdata/influxdb/v2/pkg/slices" ) func Test_sortShardDirs(t *testing.T) { input := []shardMapping{ {path: "/influxdb/data/db0/autogen/0"}, {path: "/influxdb/data/db0/rp0/10"}, {path: "/influxdb/data/db0/autogen/10"}, {path: "/influxdb/data/db0/autogen/2"}, {path: "/influxdb/data/db0/autogen/43"}, {path: "/influxdb/data/apple/rp1/99"}, {path: "/influxdb/data/apple/rp2/0"}, {path: "/influxdb/data/db0/autogen/33"}, } expected := []shardMapping{ {path: "/influxdb/data/apple/rp1/99"}, {path: "/influxdb/data/apple/rp2/0"}, {path: "/influxdb/data/db0/autogen/0"}, {path: "/influxdb/data/db0/autogen/2"}, {path: "/influxdb/data/db0/autogen/10"}, {path: "/influxdb/data/db0/autogen/33"}, {path: "/influxdb/data/db0/autogen/43"}, {path: "/influxdb/data/db0/rp0/10"}, } if err := sortShardDirs(input); err != nil { t.Fatal(err) } if got, exp := input, expected; !reflect.DeepEqual(got, exp) { t.Fatalf("got %v, expected %v", got, expected) } input = append(input, shardMapping{path: "/influxdb/data/db0/rp0/badformat"}) if err := sortShardDirs(input); err == nil { t.Fatal("expected error, got <nil>") } } var sep = tsmKeyFieldSeparator1x func Test_sort1xTSMKeys(t *testing.T) { cases := []struct { input [][]byte expected [][]byte }{ { input: slices.StringsToBytes( "cpu"+sep+"a", "cpu"+sep+"b", "cpu"+sep+"c", "disk"+sep+"a", ), expected: slices.StringsToBytes( "cpu"+sep+"a", "cpu"+sep+"b", "cpu"+sep+"c", "disk"+sep+"a", ), }, { input: slices.StringsToBytes( "cpu"+sep+"c", "cpu,region=east"+sep+"b", "cpu,region=east,server=a"+sep+"a", ), expected: slices.StringsToBytes( "cpu,region=east,server=a"+sep+"a", "cpu,region=east"+sep+"b", "cpu"+sep+"c", ), }, { input: slices.StringsToBytes( "cpu"+sep+"c", "cpu,region=east"+sep+"b", "cpu,region=east,server=a"+sep+"a", ), expected: slices.StringsToBytes( "cpu,region=east,server=a"+sep+"a", "cpu,region=east"+sep+"b", "cpu"+sep+"c", ), }, { input: slices.StringsToBytes( "\xc1\xbd\xd5)x!\a#H\xd4\xf3ç\xde\v\x14,\x00=m0,tag0=value1#!~#v0", "\xc1\xbd\xd5)x!\a#H\xd4\xf3ç\xde\v\x14,\x00=m0,tag0=value19,tag1=value999,tag2=value9,tag3=value0#!~#v0", ), expected: slices.StringsToBytes( "\xc1\xbd\xd5)x!\a#H\xd4\xf3ç\xde\v\x14,\x00=m0,tag0=value1"+sep+"v0", "\xc1\xbd\xd5)x!\a#H\xd4\xf3ç\xde\v\x14,\x00=m0,tag0=value19,tag1=value999,tag2=value9,tag3=value0"+sep+"v0", ), }, } for _, tc := range cases { sort1xTSMKeys(tc.input) if got, exp := tc.input, tc.expected; !reflect.DeepEqual(got, exp) { t.Errorf("got %s, expected %s", got, exp) } } }
nooproblem/influxdb
tsdb/migrate/migrate_test.go
GO
mit
2,793
namespace Merchello.Tests.IntegrationTests.ObjectResolution { using Merchello.Core.EntityCollections; using Merchello.Core.EntityCollections.Providers; using Merchello.Tests.Base.TestHelpers; using Merchello.Web.Models.ContentEditing.Collections; using NUnit.Framework; [TestFixture] public class EntityCollectionResolution : MerchelloAllInTestBase { /// <summary> /// Test shows a key can be resolved from the attribute based on the type of provider /// </summary> [Test] public void Can_Resolve_StaticProductCollectionProviders_Key() { //// Arrange var expected = Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey; var resolver = EntityCollectionProviderResolver.Current; //// Act var key = resolver.GetProviderKey<StaticProductCollectionProvider>(); //// Assert Assert.AreEqual(expected, key); } [Test] public void Can_Resolve_StaticInvoiceCollectionProvider_Key() { //// Arrange var expected = Core.Constants.ProviderKeys.EntityCollection.StaticInvoiceCollectionProviderKey; var resolver = EntityCollectionProviderResolver.Current; //// Act var key = resolver.GetProviderKey<StaticInvoiceCollectionProvider>(); //// Assert Assert.AreEqual(expected, key); } [Test] public void Can_Resolve_StaticCustomerCollectionProvider_Key() { //// Arrange var expected = Core.Constants.ProviderKeys.EntityCollection.StaticCustomerCollectionProviderKey; var resolver = EntityCollectionProviderResolver.Current; //// Act var key = resolver.GetProviderKey<StaticCustomerCollectionProvider>(); //// Assert Assert.AreEqual(expected, key); } [Test] public void Can_Resolve_StaticEntityCollectionCollectionProvider_Key() { //// Arrange var expected = Core.Constants.ProviderKeys.EntityCollection.StaticEntityCollectionCollectionProvider; var resolver = EntityCollectionProviderResolver.Current; //// Act var key = resolver.GetProviderKey<StaticEntityCollectionCollectionProvider>(); //// Assert Assert.AreEqual(expected, key); } [Test] public void Can_Map_EntityCollectionProviderAttribute_To_EntityCollectionProviderDisplay() { //// Arrange var att = EntityCollectionProviderResolver.Current.GetProviderAttribute<StaticProductCollectionProvider>(); //// Act var display = att.ToEntityCollectionProviderDisplay(); //// Assert Assert.NotNull(display); } } }
MindfireTechnology/Merchello
test/Merchello.Tests.IntegrationTests/ObjectResolution/EntityCollectionResolution.cs
C#
mit
2,917
package com.pie.tlatoani.WebSocket; import com.pie.tlatoani.Core.Skript.MundoPropertyExpression; import com.pie.tlatoani.Core.Static.OptionalUtil; import mundosk_libraries.java_websocket.WebSocket; /** * Created by Tlatoani on 9/3/17. */ public class ExprWebSocketID extends MundoPropertyExpression<WebSocket, String> { @Override public String convert(WebSocket webSocket) { return OptionalUtil.cast(webSocket, SkriptWebSocketClient.class).map(client -> client.functionality.id).orElse(null); } }
TlatoaniHJ/MundoSK
src/com/pie/tlatoani/WebSocket/ExprWebSocketID.java
Java
mit
522
require 'cucumber/formatter/console' require 'cucumber/formatter/io' require 'fileutils' begin require 'rubygems' require 'prawn/core' require "prawn/layout" rescue LoadError => e e.message << "\nYou need the prawn gem. Please do 'gem install prawn'" raise e end module Cucumber module Formatter BLACK = '000000' GREY = '999999' class Pdf include FileUtils include Console include Io attr_writer :indent def initialize(step_mother, path_or_io, options) @step_mother = step_mother @file = ensure_file(path_or_io, "pdf") if(options[:dry_run]) @status_colors = { :passed => BLACK, :skipped => BLACK, :undefined => BLACK, :failed => BLACK, :putsd => GREY} else @status_colors = { :passed => '055902', :skipped => GREY, :undefined => 'F27405', :failed => '730202', :putsd => GREY} end @pdf = Prawn::Document.new @scrap = Prawn::Document.new @doc = @scrap @options = options @exceptions = [] @indent = 0 @buffer = [] load_cover_page_image @pdf.text "\n\n\nCucumber features", :align => :center, :size => 32 @pdf.draw_text "Generated: #{Time.now.strftime("%Y-%m-%d %H:%M")}", :size => 10, :at => [0, 24] @pdf.draw_text "$ cucumber #{ARGV.join(" ")}", :size => 10, :at => [0,10] unless options[:dry_run] @pdf.bounding_box [450,100] , :width => 100 do @pdf.text 'Legend', :size => 10 @status_colors.each do |k,v| @pdf.fill_color v @pdf.text k.to_s, :size => 10 @pdf.fill_color BLACK end end end end def load_cover_page_image() if (!load_image("features/support/logo.png")) load_image("features/support/logo.jpg") end end def load_image(image_path) begin @pdf.image open(image_path, "rb"), :position => :center, :width => 500 true rescue Errno::ENOENT false end end def puts(message) @pdf.fill_color(@status_colors[:putsd]) @pdf.text message, :size => 10 @pdf.fill_color BLACK end def after_features(features) @pdf.render_file(@file.path) puts "\ndone" end def feature_name(keyword, name) @pdf.start_new_page names = name.split("\n") @pdf.fill_color GREY @pdf.text(keyword, :align => :center) @pdf.fill_color BLACK names.each_with_index do |nameline, i| case i when 0 @pdf.text(nameline.strip, :size => 30, :align => :center ) @pdf.text("\n") else @pdf.text(nameline.strip, :size => 12) end end @pdf.move_down(30) end def after_feature_element(feature_element) flush end def after_feature(feature) flush end def feature_element_name(keyword, name) names = name.empty? ? [name] : name.split("\n") print "." STDOUT.flush keep_with do @doc.move_down(20) @doc.fill_color GREY @doc.text("#{keyword}", :size => 8) @doc.fill_color BLACK @doc.text("#{names[0]}", :size => 16) names[1..-1].each { |s| @doc.text(s, :size => 12) } @doc.text("\n") end end def step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background) @hide_this_step = false if exception if @exceptions.include?(exception) @hide_this_step = true return end @exceptions << exception end if status != :failed && @in_background ^ background @hide_this_step = true return end end def step_name(keyword, step_match, status, source_indent, background) return if @hide_this_step line = "#{keyword} #{step_match.format_args("%s")}" colorize(line, status) end def before_background(background) @in_background = true end def after_background(background) @in_background = nil end def before_multiline_arg(table) return if @hide_this_step if(table.kind_of? Cucumber::Ast::Table) keep_with do print_table(table, ['ffffff', 'f0f0f0']) end end end #using row_color hack to highlight each row correctly def before_outline_table(table) return if @hide_this_step row_colors = table.example_rows.map { |r| @status_colors[r.status] unless r.status == :skipped} keep_with do print_table(table, row_colors) end end def before_doc_string(string) return if @hide_this_step s = %{"""\n#{string}\n"""}.indent(10) s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l} s.each do |line| keep_with { @doc.text(line, :size => 8) } end end def tag_name(tag_name) return if @hide_this_step tag = format_string(tag_name, :tag).indent(@indent) # TODO should we render tags at all? skipped for now. difficult to place due to page breaks end def background_name(keyword, name, file_colon_line, source_indent) feature_element_name(keyword, name) end def examples_name(keyword, name) feature_element_name(keyword, name) end def scenario_name(keyword, name, file_colon_line, source_indent) feature_element_name(keyword, name) end private def colorize(text, status) keep_with do @doc.fill_color(@status_colors[status] || BLACK) @doc.text(text) @doc.fill_color(BLACK) end end def keep_with(&block) @buffer << block end def render(doc) @doc = doc @buffer.each do |proc| proc.call end end # This method does a 'test' rendering on a blank page, to see the rendered height of the buffer # if that too high for the space left on the age in the real document, we do a page break. # This obviously doesn't work if a scenario is longer than a whole page (God forbid) def flush @scrap.start_new_page oldy = @scrap.y render @scrap height = (oldy - @scrap.y) + 36 # whops magic number if ((@pdf.y - height) < @pdf.bounds.bottom) @pdf.start_new_page end render @pdf @pdf.move_down(20) @buffer = [] end def print_table(table, row_colors) @doc.table(table.rows, :headers => table.headers, :position => :center, :row_colors => row_colors) end end end end
jarib/cucumber
lib/cucumber/formatter/pdf.rb
Ruby
mit
6,890
//= require redactor-rails/plugins/clips //= require redactor-rails/plugins/fontcolor //= require redactor-rails/plugins/fontfamily //= require redactor-rails/plugins/fontsize //= require redactor-rails/plugins/fullscreen //= require redactor-rails/plugins/table //= require redactor-rails/plugins/textdirection //= require redactor-rails/plugins/video
lawrrn/redactor
vendor/assets/javascripts/redactor-rails/plugins.js
JavaScript
mit
353
import { Serializer } from "./jsonobject"; import { Question } from "./question"; import { Base, SurveyError, ISurveyImpl } from "./base"; import { ItemValue } from "./itemvalue"; import { Helpers, HashTable } from "./helpers"; import { surveyLocalization } from "./surveyStrings"; import { OtherEmptyError } from "./error"; import { ChoicesRestfull } from "./choicesRestfull"; import { LocalizableString } from "./localizablestring"; import { ConditionRunner } from "./conditions"; import { settings } from "./settings"; /** * It is a base class for checkbox, dropdown and radiogroup questions. */ export class QuestionSelectBase extends Question { public visibleChoicesChangedCallback: () => void; private filteredChoicesValue: Array<ItemValue> = null; private conditionChoicesVisibleIfRunner: ConditionRunner; private conditionChoicesEnableIfRunner: ConditionRunner; private commentValue: string; private prevCommentValue: string; private otherItemValue: ItemValue = new ItemValue("other"); private choicesFromUrl: Array<ItemValue> = null; private cachedValueForUrlRequests: any = null; private isChoicesLoaded: boolean = false; private enableOnLoadingChoices: boolean = false; constructor(name: string) { super(name); var self = this; this.createItemValues("choices"); this.registerFunctionOnPropertyValueChanged("choices", function () { if (!self.filterItems()) { self.onVisibleChoicesChanged(); } }); this.registerFunctionOnPropertyValueChanged( "hideIfChoicesEmpty", function () { self.updateVisibilityBasedOnChoices(); } ); this.createNewArray("visibleChoices"); this.setPropertyValue("choicesByUrl", this.createRestfull()); this.choicesByUrl.owner = this; this.choicesByUrl.loadingOwner = this; var locOtherText = this.createLocalizableString("otherText", this, true); this.createLocalizableString("otherErrorText", this, true); this.otherItemValue.locOwner = this; this.otherItemValue.setLocText(locOtherText); locOtherText.onGetTextCallback = function (text) { return !!text ? text : surveyLocalization.getString("otherItemText"); }; this.choicesByUrl.beforeSendRequestCallback = function () { self.onBeforeSendRequest(); }; this.choicesByUrl.getResultCallback = function (items: Array<ItemValue>) { self.onLoadChoicesFromUrl(items); }; this.choicesByUrl.updateResultCallback = function ( items: Array<ItemValue>, serverResult: any ): Array<ItemValue> { if (self.survey) { return self.survey.updateChoicesFromServer(self, items, serverResult); } return items; }; this.createLocalizableString("otherPlaceHolder", this); } public getType(): string { return "selectbase"; } public supportGoNextPageError() { return !this.isOtherSelected || !!this.comment; } isLayoutTypeSupported(layoutType: string): boolean { return true; } /** * Returns the other item. By using this property, you may change programmatically it's value and text. * @see hasOther */ public get otherItem(): ItemValue { return this.otherItemValue; } /** * Returns true if a user select the 'other' item. */ public get isOtherSelected(): boolean { return this.hasOther && this.getHasOther(this.renderedValue); } /** * An expression that returns true or false. It runs against each choices item and if for this item it returns true, then the item is visible otherwise the item becomes invisible. Please use {item} to get the current item value in the expression. * @see visibleIf * @see choicesEnableIf */ public get choicesVisibleIf(): string { return this.getPropertyValue("choicesVisibleIf", ""); } public set choicesVisibleIf(val: string) { this.setPropertyValue("choicesVisibleIf", val); this.filterItems(); } /** * An expression that returns true or false. It runs against each choices item and if for this item it returns true, then the item is enabled otherwise the item becomes disabled. Please use {item} to get the current item value in the expression. * @see choicesVisibleIf */ public get choicesEnableIf(): string { return this.getPropertyValue("choicesEnableIf", ""); } public set choicesEnableIf(val: string) { this.setPropertyValue("choicesEnableIf", val); this.filterItems(); } public runCondition(values: HashTable<any>, properties: HashTable<any>) { super.runCondition(values, properties); this.runItemsEnableCondition(values, properties); this.runItemsCondition(values, properties); } protected isTextValue(): boolean { return true; //for comments and others } private isSettingDefaultValue: boolean = false; protected setDefaultValue() { this.isSettingDefaultValue = !this.isValueEmpty(this.defaultValue) && this.hasUnknownValue(this.defaultValue); super.setDefaultValue(); this.isSettingDefaultValue = false; } protected getIsMultipleValue(): boolean { return false; } protected convertDefaultValue(val: any): any { if (val == null || val == undefined) return val; if (this.getIsMultipleValue()) { if (!Array.isArray(val)) return [val]; } else { if (Array.isArray(val) && val.length > 0) return val[0]; } return val; } protected filterItems(): boolean { if ( this.isLoadingFromJson || !this.data || this.areInvisibleElementsShowing ) return false; var values = this.getDataFilteredValues(); var properties = this.getDataFilteredProperties(); this.runItemsEnableCondition(values, properties); return this.runItemsCondition(values, properties); } protected runItemsCondition( values: HashTable<any>, properties: HashTable<any> ): boolean { this.setConditionalChoicesRunner(); var hasChanges = this.runConditionsForItems(values, properties); if ( !!this.filteredChoicesValue && this.filteredChoicesValue.length === this.activeChoices.length ) { this.filteredChoicesValue = null; } if (hasChanges) { this.onVisibleChoicesChanged(); this.clearIncorrectValues(); } return hasChanges; } protected runItemsEnableCondition( values: HashTable<any>, properties: HashTable<any> ): any { this.setConditionalEnableChoicesRunner(); var hasChanged = ItemValue.runEnabledConditionsForItems( this.activeChoices, this.conditionChoicesEnableIfRunner, values, properties, (item: ItemValue): boolean => { return this.onEnableItemCallBack(item); } ); if (hasChanged) { this.clearDisabledValues(); } this.onAfterRunItemsEnableCondition(); } protected onAfterRunItemsEnableCondition() {} protected onEnableItemCallBack(item: ItemValue): boolean { return true; } private setConditionalChoicesRunner() { if (this.choicesVisibleIf) { if (!this.conditionChoicesVisibleIfRunner) { this.conditionChoicesVisibleIfRunner = new ConditionRunner( this.choicesVisibleIf ); } this.conditionChoicesVisibleIfRunner.expression = this.choicesVisibleIf; } else { this.conditionChoicesVisibleIfRunner = null; } } private setConditionalEnableChoicesRunner() { if (this.choicesEnableIf) { if (!this.conditionChoicesEnableIfRunner) { this.conditionChoicesEnableIfRunner = new ConditionRunner( this.choicesEnableIf ); } this.conditionChoicesEnableIfRunner.expression = this.choicesEnableIf; } else { this.conditionChoicesEnableIfRunner = null; } } private runConditionsForItems( values: HashTable<any>, properties: HashTable<any> ): boolean { this.filteredChoicesValue = []; return ItemValue.runConditionsForItems( this.activeChoices, this.filteredChoices, this.areInvisibleElementsShowing ? null : this.conditionChoicesVisibleIfRunner, values, properties, !this.survey || !this.survey.areInvisibleElementsShowing ); } protected getHasOther(val: any): boolean { return val === this.otherItem.value; } get validatedValue(): any { return this.rendredValueToDataCore(this.value); } protected createRestfull(): ChoicesRestfull { return new ChoicesRestfull(); } protected getQuestionComment(): string { if (!!this.commentValue) return this.commentValue; if (this.hasComment || this.getStoreOthersAsComment()) return super.getQuestionComment(); return this.commentValue; } private isSettingComment: boolean = false; protected setQuestionComment(newValue: string) { if (this.hasComment || this.getStoreOthersAsComment()) super.setQuestionComment(newValue); else { if (!this.isSettingComment && newValue != this.commentValue) { this.isSettingComment = true; this.commentValue = newValue; if (this.isOtherSelected && !this.isRenderedValueSetting) { this.value = this.rendredValueToData(this.renderedValue); } this.isSettingComment = false; } } } public get renderedValue(): any { return this.getPropertyValue("renderedValue", null); } public set renderedValue(val: any) { this.setPropertyValue("renderedValue", val); this.value = this.rendredValueToData(val); } protected setQuestionValue(newValue: any, updateIsAnswered: boolean = true) { if ( this.isLoadingFromJson || Helpers.isTwoValueEquals(this.value, newValue) ) return; super.setQuestionValue(newValue, updateIsAnswered); this.setPropertyValue("renderedValue", this.rendredValueFromData(newValue)); if (this.hasComment) return; var isOtherSel = this.isOtherSelected; if (isOtherSel && !!this.prevCommentValue) { var oldComment = this.prevCommentValue; this.prevCommentValue = ""; this.comment = oldComment; } if (!isOtherSel && !!this.comment) { if (this.getStoreOthersAsComment()) { this.prevCommentValue = this.comment; } this.comment = ""; } } protected setNewValue(newValue: any) { newValue = this.valueFromData(newValue); if ( (!this.choicesByUrl.isRunning && !this.choicesByUrl.isWaitingForParameters) || !this.isValueEmpty(newValue) ) { this.cachedValueForUrlRequests = newValue; } super.setNewValue(newValue); } protected valueFromData(val: any): any { let choiceitem = ItemValue.getItemByValue(this.activeChoices, val); if (!!choiceitem) { return choiceitem.value; } return super.valueFromData(val); } protected rendredValueFromData(val: any): any { if (this.getStoreOthersAsComment()) return val; return this.renderedValueFromDataCore(val); } protected rendredValueToData(val: any): any { if (this.getStoreOthersAsComment()) return val; return this.rendredValueToDataCore(val); } protected renderedValueFromDataCore(val: any): any { if (!this.hasUnknownValue(val, true)) return this.valueFromData(val); this.comment = val; return this.otherItem.value; } protected rendredValueToDataCore(val: any): any { if (val == this.otherItem.value && this.getQuestionComment()) { val = this.getQuestionComment(); } return val; } protected hasUnknownValue(val: any, includeOther: boolean = false): boolean { if (Helpers.isValueEmpty(val)) return false; if (includeOther && val == this.otherItem.value) return false; return ItemValue.getItemByValue(this.filteredChoices, val) == null; } protected isValueDisabled(val: any): boolean { var itemValue = ItemValue.getItemByValue(this.filteredChoices, val); return !!itemValue && !itemValue.isEnabled; } /** * If the clearIncorrectValuesCallback is set, it is used to clear incorrect values instead of default behaviour. */ public clearIncorrectValuesCallback: () => void; /** * Use this property to fill the choices from a restful service. * @see choices */ public get choicesByUrl(): ChoicesRestfull { return this.getPropertyValue("choicesByUrl"); } /** * The list of items. Every item has value and text. If text is empty, the value is rendered. The item text supports markdown. * @see choicesByUrl */ public get choices(): Array<any> { return this.getPropertyValue("choices"); } public set choices(newValue: Array<any>) { this.setPropertyValue("choices", newValue); } /** * Set this property to true to hide the question if there is no visible choices. */ public get hideIfChoicesEmpty(): boolean { return this.getPropertyValue("hideIfChoicesEmpty", false); } public set hideIfChoicesEmpty(val: boolean) { this.setPropertyValue("hideIfChoicesEmpty", val); } public get keepIncorrectValues(): boolean { return this.getPropertyValue("keepIncorrectValues", false); } public set keepIncorrectValues(val: boolean) { this.setPropertyValue("keepIncorrectValues", val); } /** * Please use survey.storeOthersAsComment to change the behavior on the survey level. This property is depricated and invisible in Survey Creator. * By default the entered text in the others input in the checkbox/radiogroup/dropdown are stored as "question name " + "-Comment". The value itself is "question name": "others". Set this property to false, to store the entered text directly in the "question name" key. * Possible values are: "default", true, false * @see SurveyModel.storeOthersAsComment */ public get storeOthersAsComment(): any { return this.getPropertyValue("storeOthersAsComment", "default"); } public set storeOthersAsComment(val: any) { this.setPropertyValue("storeOthersAsComment", val); } protected hasOtherChanged() { this.onVisibleChoicesChanged(); } /** * Use this property to render items in a specific order: "asc", "desc", "random". Default value is "none". */ public get choicesOrder(): string { return this.getPropertyValue("choicesOrder"); } public set choicesOrder(val: string) { val = val.toLowerCase(); if (val == this.choicesOrder) return; this.setPropertyValue("choicesOrder", val); this.onVisibleChoicesChanged(); } /** * Use this property to set the different text for other item. */ public get otherText(): string { return this.getLocalizableStringText( "otherText", surveyLocalization.getString("otherItemText") ); } public set otherText(val: string) { this.setLocalizableStringText("otherText", val); this.onVisibleChoicesChanged(); } get locOtherText(): LocalizableString { return this.getLocalizableString("otherText"); } /** * Use this property to set the place holder text for other or comment field . */ public get otherPlaceHolder(): string { return this.getLocalizableStringText("otherPlaceHolder"); } public set otherPlaceHolder(val: string) { this.setLocalizableStringText("otherPlaceHolder", val); } get locOtherPlaceHolder(): LocalizableString { return this.getLocalizableString("otherPlaceHolder"); } /** * The text that shows when the other item is choosed by the other input is empty. */ public get otherErrorText(): string { return this.getLocalizableStringText( "otherErrorText", surveyLocalization.getString("otherRequiredError") ); } public set otherErrorText(val: string) { this.setLocalizableStringText("otherErrorText", val); } get locOtherErrorText(): LocalizableString { return this.getLocalizableString("otherErrorText"); } /** * The list of items as they will be rendered. If needed items are sorted and the other item is added. * @see hasOther * @see choicesOrder * @see enabledChoices */ public get visibleChoices(): Array<ItemValue> { return this.getPropertyValue("visibleChoices", []); } /** * The list of enabled items as they will be rendered. The disabled items are not included * @see hasOther * @see choicesOrder * @see visibleChoices */ public get enabledChoices(): Array<ItemValue> { var res = []; var items = this.visibleChoices; for (var i = 0; i < items.length; i++) { if (items[i].isEnabled) res.push(items[i]); } return res; } protected updateVisibleChoices() { if (this.isLoadingFromJson) return; var newValue = new Array<ItemValue>(); var calcValue = this.calcVisibleChoices(); if (!calcValue) calcValue = []; for (var i = 0; i < calcValue.length; i++) { newValue.push(calcValue[i]); } this.setPropertyValue("visibleChoices", newValue); } private calcVisibleChoices(): Array<ItemValue> { if (this.canUseFilteredChoices()) return this.filteredChoices; var res = this.sortVisibleChoices(this.filteredChoices.slice()); this.addToVisibleChoices(res); return res; } protected canUseFilteredChoices(): boolean { return !this.hasOther && this.choicesOrder == "none"; } protected addToVisibleChoices(items: Array<ItemValue>) { if (this.hasOther) { items.push(this.otherItem); } } public getPlainData( options: { includeEmpty?: boolean; includeQuestionTypes?: boolean; calculations?: Array<{ propertyName: string; }>; } = { includeEmpty: true, includeQuestionTypes: false, } ) { var questionPlainData = super.getPlainData(options); if (!!questionPlainData) { var values = Array.isArray(this.value) ? this.value : [this.value]; questionPlainData.isNode = true; questionPlainData.data = (questionPlainData.data || []).concat( values.map((dataValue, index) => { var choice = ItemValue.getItemByValue(this.visibleChoices, dataValue); var choiceDataItem = <any>{ name: index, title: "Choice", value: dataValue, displayValue: this.getChoicesDisplayValue( this.visibleChoices, dataValue ), getString: (val: any) => typeof val === "object" ? JSON.stringify(val) : val, isNode: false, }; if (!!choice) { (options.calculations || []).forEach((calculation) => { choiceDataItem[calculation.propertyName] = choice[calculation.propertyName]; }); } if (this.isOtherSelected && this.otherItemValue === choice) { choiceDataItem.isOther = true; choiceDataItem.displayValue = this.comment; } return choiceDataItem; }) ); } return questionPlainData; } /** * Returns the text for the current value. If the value is null then returns empty string. If 'other' is selected then returns the text for other value. */ protected getDisplayValueCore(keysAsText: boolean, value: any): any { return this.getChoicesDisplayValue(this.visibleChoices, value); } protected getChoicesDisplayValue(items: ItemValue[], val: any): any { if (val == this.otherItemValue.value) return this.comment ? this.comment : this.locOtherText.textOrHtml; var str = ItemValue.getTextOrHtmlByValue(items, val); return str == "" && val ? val : str; } private get filteredChoices(): Array<ItemValue> { return this.filteredChoicesValue ? this.filteredChoicesValue : this.activeChoices; } protected get activeChoices(): Array<ItemValue> { return this.choicesFromUrl ? this.choicesFromUrl : this.getChoices(); } protected getChoices(): Array<ItemValue> { return this.choices; } public supportComment(): boolean { return true; } public supportOther(): boolean { return true; } protected onCheckForErrors( errors: Array<SurveyError>, isOnValueChanged: boolean ) { super.onCheckForErrors(errors, isOnValueChanged); if (!this.hasOther || !this.isOtherSelected || this.comment) return; errors.push(new OtherEmptyError(this.otherErrorText, this)); } public setSurveyImpl(value: ISurveyImpl) { super.setSurveyImpl(value); this.runChoicesByUrl(); } protected getStoreOthersAsComment() { if (this.isSettingDefaultValue) return false; return ( this.storeOthersAsComment === true || (this.storeOthersAsComment == "default" && (this.survey != null ? this.survey.storeOthersAsComment : true)) || (!this.choicesByUrl.isEmpty && !this.choicesFromUrl) ); } onSurveyLoad() { super.onSurveyLoad(); this.runChoicesByUrl(); this.onVisibleChoicesChanged(); } onAnyValueChanged(name: string) { super.onAnyValueChanged(name); if (name != this.getValueName()) { this.runChoicesByUrl(); } } updateValueFromSurvey(newValue: any) { var newComment = ""; if ( this.hasOther && this.getStoreOthersAsComment() && this.hasUnknownValue(newValue) && !this.getHasOther(newValue) ) { newComment = this.getCommentFromValue(newValue); newValue = this.setOtherValueIntoValue(newValue); } super.updateValueFromSurvey(newValue); if (!!newComment) { this.setNewComment(newComment); } } protected getCommentFromValue(newValue: any): string { return newValue; } protected setOtherValueIntoValue(newValue: any): any { return this.otherItem.value; } private isRunningChoices: boolean = false; private runChoicesByUrl() { if (!this.choicesByUrl || this.isLoadingFromJson || this.isRunningChoices) return; var processor = this.surveyImpl ? this.surveyImpl.getTextProcessor() : this.textProcessor; if (!processor) processor = this.survey; if (!processor) return; this.isReadyValue = this.isChoicesLoaded || this.choicesByUrl.isEmpty; this.isRunningChoices = true; this.choicesByUrl.run(processor); this.isRunningChoices = false; } private isFirstLoadChoicesFromUrl = true; protected onBeforeSendRequest() { if (settings.disableOnGettingChoicesFromWeb === true && !this.isReadOnly) { this.enableOnLoadingChoices = true; this.readOnly = true; } } protected onLoadChoicesFromUrl(array: Array<ItemValue>) { if (this.enableOnLoadingChoices) { this.readOnly = false; } if (!this.isReadOnly) { var errors = []; if (this.choicesByUrl && this.choicesByUrl.error) { errors.push(this.choicesByUrl.error); } this.errors = errors; } var newChoices = null; var checkCachedValuesOnExisting = true; if ( this.isFirstLoadChoicesFromUrl && !this.cachedValueForUrlRequests && this.defaultValue ) { this.cachedValueForUrlRequests = this.defaultValue; checkCachedValuesOnExisting = false; } if (this.isValueEmpty(this.cachedValueForUrlRequests)) { this.cachedValueForUrlRequests = this.value; } this.isFirstLoadChoicesFromUrl = false; var cachedValues = this.createCachedValueForUrlRequests( this.cachedValueForUrlRequests, checkCachedValuesOnExisting ); if (array && array.length > 0) { newChoices = new Array<ItemValue>(); ItemValue.setData(newChoices, array); } this.choicesFromUrl = newChoices; this.filterItems(); this.onVisibleChoicesChanged(); if (newChoices) { var newValue = this.updateCachedValueForUrlRequests( cachedValues, newChoices ); if (!!newValue && !this.isReadOnly) { var hasChanged = !Helpers.isTwoValueEquals(this.value, newValue.value); try { if (!Helpers.isValueEmpty(newValue.value)) { this.allowNotifyValueChanged = false; this.locNotificationInData = true; this.value = undefined; this.locNotificationInData = false; } this.allowNotifyValueChanged = hasChanged; this.value = newValue.value; } finally { this.allowNotifyValueChanged = true; } } } this.choicesLoaded(); } private createCachedValueForUrlRequests( val: any, checkOnExisting: boolean ): any { if (this.isValueEmpty(val)) return null; if (Array.isArray(val)) { var res = []; for (var i = 0; i < val.length; i++) { res.push(this.createCachedValueForUrlRequests(val[i], true)); } return res; } var isExists = checkOnExisting ? !this.hasUnknownValue(val) : true; return { value: val, isExists: isExists }; } private updateCachedValueForUrlRequests( val: any, newChoices: Array<ItemValue> ): any { if (this.isValueEmpty(val)) return null; if (Array.isArray(val)) { var res = []; for (var i = 0; i < val.length; i++) { var updatedValue = this.updateCachedValueForUrlRequests( val[i], newChoices ); if (updatedValue && !this.isValueEmpty(updatedValue.value)) { var newValue = updatedValue.value; var item = ItemValue.getItemByValue(newChoices, updatedValue.value); if (!!item) { newValue = item.value; } res.push(newValue); } } return { value: res }; } var value = val.isExists && this.hasUnknownValue(val.value) ? null : val.value; var item = ItemValue.getItemByValue(newChoices, value); if (!!item) { value = item.value; } return { value: value }; } protected onVisibleChoicesChanged() { if (this.isLoadingFromJson) return; this.updateVisibleChoices(); this.updateVisibilityBasedOnChoices(); if (!!this.visibleChoicesChangedCallback) this.visibleChoicesChangedCallback(); } private updateVisibilityBasedOnChoices() { if (this.hideIfChoicesEmpty) { this.visible = !this.filteredChoices || this.filteredChoices.length > 0; } } private sortVisibleChoices(array: Array<ItemValue>): Array<ItemValue> { var order = this.choicesOrder.toLowerCase(); if (order == "asc") return this.sortArray(array, 1); if (order == "desc") return this.sortArray(array, -1); if (order == "random") return this.randomizeArray(array); return array; } private sortArray(array: Array<ItemValue>, mult: number): Array<ItemValue> { return array.sort(function (a, b) { if (a.calculatedText < b.calculatedText) return -1 * mult; if (a.calculatedText > b.calculatedText) return 1 * mult; return 0; }); } private randomizeArray(array: Array<ItemValue>): Array<ItemValue> { return Helpers.randomizeArray<ItemValue>(array); } public clearIncorrectValues() { if (this.keepIncorrectValues) return; if ( !!this.survey && this.survey.questionCountByValueName(this.getValueName()) > 1 ) return; if (!!this.choicesByUrl && !this.choicesByUrl.isEmpty) return; if (this.clearIncorrectValuesCallback) { this.clearIncorrectValuesCallback(); } else { this.clearIncorrectValuesCore(); } } public clearValueIfInvisible() { super.clearValueIfInvisible(); this.clearIncorrectValues(); } /** * Returns true if item is selected * @param item checkbox or radio item value */ public isItemSelected(item: ItemValue): boolean { return item.value === this.value; } private clearDisabledValues() { if (!this.survey || !this.survey.clearValueOnDisableItems) return; this.clearDisabledValuesCore(); } protected clearIncorrectValuesCore() { var val = this.value; if (this.canClearValueAnUnknow(val)) { this.clearValue(); } } protected canClearValueAnUnknow(val: any): boolean { if (!this.getStoreOthersAsComment() && this.isOtherSelected) return false; return this.hasUnknownValue(val, true); } protected clearDisabledValuesCore() { if (this.isValueDisabled(this.value)) { this.clearValue(); } } clearUnusedValues() { super.clearUnusedValues(); if (!this.isOtherSelected && !this.hasComment) { this.comment = ""; } } getColumnClass() { var columnClass = this.cssClasses.column; if (this.hasColumns) { columnClass += " sv-q-column-" + this.colCount; } return columnClass; } getLabelClass(item: ItemValue) { var labelClass = this.cssClasses.label; if (this.isItemSelected(item)) { labelClass += " " + this.cssClasses.labelChecked; } return labelClass; } getControlLabelClass(item: ItemValue) { var controlLabelClass = this.cssClasses.controlLabel; if (this.isItemSelected(item)) { controlLabelClass += " " + this.cssClasses.controlLabelChecked; } return controlLabelClass; } get columns() { var columns = []; var colCount = this.colCount; if (this.hasColumns && this.visibleChoices.length > 0) { if (settings.showItemsInOrder == "column") { var prevIndex = 0; var leftElementsCount = this.visibleChoices.length % colCount; for (var i = 0; i < colCount; i++) { var column = []; for ( var j = prevIndex; j < prevIndex + Math.floor(this.visibleChoices.length / colCount); j++ ) { column.push(this.visibleChoices[j]); } if (leftElementsCount > 0) { leftElementsCount--; column.push(this.visibleChoices[j]); j++; } prevIndex = j; columns.push(column); } } else { for (var i = 0; i < colCount; i++) { var column = []; for (var j = i; j < this.visibleChoices.length; j += colCount) { column.push(this.visibleChoices[j]); } columns.push(column); } } } return columns; } get hasColumns() { return this.colCount > 1; } public choicesLoaded(): void { this.isChoicesLoaded = true; let oldIsReady: boolean = this.isReadyValue; this.isReadyValue = true; this.onReadyChanged && this.onReadyChanged.fire(this, { question: this, isReady: true, oldIsReady: oldIsReady, }); } } /** * A base class for checkbox and radiogroup questions. It introduced a colCount property. */ export class QuestionCheckboxBase extends QuestionSelectBase { colCountChangedCallback: () => void; constructor(public name: string) { super(name); } /** * The number of columns for radiogroup and checkbox questions. Items are rendred in one line if the value is 0. */ public get colCount(): number { return this.getPropertyValue("colCount", this.isFlowLayout ? 0 : 1); } public set colCount(value: number) { if (value < 0 || value > 5 || this.isFlowLayout) return; this.setPropertyValue("colCount", value); this.fireCallback(this.colCountChangedCallback); } getItemIndex(item: any) { return this.visibleChoices.indexOf(item); } protected onParentChanged() { super.onParentChanged(); if (this.isFlowLayout) { this.setPropertyValue("colCount", null); } } } Serializer.addClass( "selectbase", [ { name: "hasComment:switch", layout: "row" }, { name: "commentText", dependsOn: "hasComment", visibleIf: function (obj: any) { return obj.hasComment; }, serializationProperty: "locCommentText", layout: "row", }, { name: "choices:itemvalue[]", baseValue: function () { return surveyLocalization.getString("choices_Item"); }, }, { name: "choicesOrder", default: "none", choices: ["none", "asc", "desc", "random"], }, { name: "choicesByUrl:restfull", className: "ChoicesRestfull", onGetValue: function (obj: any) { return obj.choicesByUrl.getData(); }, onSetValue: function (obj: any, value: any) { obj.choicesByUrl.setData(value); }, }, "hideIfChoicesEmpty:boolean", "choicesVisibleIf:condition", "choicesEnableIf:condition", "hasOther:boolean", { name: "otherPlaceHolder", serializationProperty: "locOtherPlaceHolder", dependsOn: "hasOther", visibleIf: function (obj: any) { return obj.hasOther; }, }, { name: "otherText", serializationProperty: "locOtherText", dependsOn: "hasOther", visibleIf: function (obj: any) { return obj.hasOther; }, }, { name: "otherErrorText", serializationProperty: "locOtherErrorText", dependsOn: "hasOther", visibleIf: function (obj: any) { return obj.hasOther; }, }, { name: "storeOthersAsComment", default: "default", choices: ["default", true, false], visible: false, }, ], null, "question" ); Serializer.addClass( "checkboxbase", [ { name: "colCount:number", default: 1, choices: [0, 1, 2, 3, 4, 5], layout: "row", }, ], null, "selectbase" );
surveyjs/surveyjs
src/question_baseselect.ts
TypeScript
mit
33,102
require "jarvis/error" describe ::Jarvis::Error do it "subclasses StandardError" do expect(subject).to be_kind_of(StandardError) end end
ph/jarvis
spec/jarvis/error_spec.rb
Ruby
mit
146
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SinglePlayer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("SinglePlayer")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0904ed7a-6158-4176-b2ed-a0404d9063f9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Reddit-Mud/RMUD
SinglePlayer/Properties/AssemblyInfo.cs
C#
mit
1,430
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PingYourPackage.Domain.Entities { public static class ShipmentTypeRepositoryExtensions { public static ShipmentType GetSingleByName( this IEntityRepository<ShipmentType> shipmentTypeRepository, string name) { return shipmentTypeRepository .FindBy(x => x.Name == name).FirstOrDefault(); } } }
niknhattan/PingYourPackage
PingYourPackage.Domain/Entities/Extentions/ShipmentTypeRepositoryExtensions.cs
C#
mit
513
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// A class contains methods which capture requirements related with Cell Sub-request. /// </summary> public sealed partial class MsfsshttpAdapterCapture { /// <summary> /// Capture requirements related with Cell Sub-request. /// </summary> /// <param name="cellSubResponse">Containing the CellSubResponse information</param> /// <param name="site">Instance of ITestSite</param> public static void ValidateCellSubResponse(CellSubResponseType cellSubResponse, ITestSite site) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R553 site.CaptureRequirement( "MS-FSSHTTP", 553, @"[In CellSubResponseType][CellSubResponseType schema is:] <xs:complexType name=""CellSubResponseType""> <xs:complexContent> <xs:extension base=""tns:SubResponseType""> <xs:sequence> <xs:element name=""SubResponseData"" type=""tns:CellSubResponseDataType"" minOccurs=""0"" maxOccurs=""1"" /> <xs:element name=""SubResponseStreamInvalid"" minOccurs=""0"" maxOccurs=""1"" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType>"); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R951 site.CaptureRequirementIfAreEqual<Type>( typeof(CellSubResponseType), cellSubResponse.GetType(), "MS-FSSHTTP", 951, @"[In Cell Subrequest][The protocol client sends a cell SubRequest message, which is of type CellSubRequestType,] The protocol server responds with a cell SubResponse message, which is of type CellSubResponseType as specified in section 2.3.1.4."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1687 site.CaptureRequirementIfAreEqual<Type>( typeof(CellSubResponseType), cellSubResponse.GetType(), "MS-FSSHTTP", 1687, @"[In SubResponseElementGenericType] Depending on the Type attribute specified in the SubRequest element, the SubResponseElementGenericType MUST take one of the forms: CellSubResponseType."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R274 site.CaptureRequirementIfAreEqual<Type>( typeof(CellSubResponseType), cellSubResponse.GetType(), "MS-FSSHTTP", 274, @"[In SubResponseType] The SubResponseElementGenericType takes one of the following forms: CellSubResponseType."); ErrorCodeType errorCode; site.Assert.IsTrue(Enum.TryParse<ErrorCodeType>(cellSubResponse.ErrorCode, true, out errorCode), "Fail to convert the error code string {0} to the Enum type ErrorCodeType", cellSubResponse.ErrorCode); if (cellSubResponse.ErrorCode != null) { ValidateCellRequestErrorCodeTypes(errorCode, site); } if (errorCode == ErrorCodeType.Success) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R263 site.Log.Add( LogEntryKind.Debug, "For requirement MS-FSSHTTP_R263, the SubResponseData value should not be NULL when the cell sub-request succeeds, the actual SubResponseData value is: {0}", cellSubResponse.SubResponseData != null ? cellSubResponse.SubResponseData.ToString() : "NULL"); site.CaptureRequirementIfIsNotNull( cellSubResponse.SubResponseData, "MS-FSSHTTP", 263, @"[In SubResponseElementGenericType][The SubResponseData element MUST be sent as part of the SubResponse element in a cell storage service response message if the ErrorCode attribute that is part of the SubResponse element is set to a value of ""Success"" and one of the following conditions is true:] The Type attribute that is specified in the SubRequest element is set to a value of ""Cell""."); } // Verify requirements related with its base type : SubResponseType ValidateSubResponseType(cellSubResponse as SubResponseType, site); // Verify requirements related with CellSubResponseDataType if (cellSubResponse.SubResponseData != null) { ValidateCellSubResponseDataType(cellSubResponse.SubResponseData, site); } } /// <summary> /// Capture requirements related with CellSubResponseDataType. /// </summary> /// <param name="cellSubResponseData">The cellSubResponseData</param> /// <param name="site">Instance of ITestSite</param> private static void ValidateCellSubResponseDataType(CellSubResponseDataType cellSubResponseData, ITestSite site) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1391 // The SubResponseData of CellSubResponse is of type CellSubResponseDataType, so if cellSubResponse.SubResponseData is not null, then MS-FSSHTTP_R1391 can be captured. site.CaptureRequirementIfAreEqual<Type>( typeof(CellSubResponseDataType), cellSubResponseData.GetType(), "MS-FSSHTTP", 1391, @"[In SubResponseDataGenericType][SubResponseDataGenericType MUST take one of the forms described in the following table] CellSubResponseDataType: Type definition for cell subresponse data."); if (cellSubResponseData.LockTypeSpecified) { // Verified LockTypes ValidateLockTypes(site); } // Verify requirements related with CellSubResponseDataOptionalAttributes if (cellSubResponseData.Etag != null || cellSubResponseData.LastModifiedTime != null || cellSubResponseData.CreateTime != null || cellSubResponseData.ModifiedBy != null || cellSubResponseData.CoalesceErrorMessage != null) { ValidateCellSubResponseDataOptionalAttributes(cellSubResponseData, site); } } /// <summary> /// Capture requirements related with CellSubResponseDataOptionalAttributes. /// </summary> /// <param name="cellSubResponseData">The cellSubResponseData</param> /// <param name="site">Instance of ITestSite</param> private static void ValidateCellSubResponseDataOptionalAttributes(CellSubResponseDataType cellSubResponseData, ITestSite site) { if (cellSubResponseData.ModifiedBy != null) { // Verify requirements related with UserNameTypes ValidateUserNameTypes(site); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1465 site.CaptureRequirement( "MS-FSSHTTP", 1465, @"[In CellSubResponseDataOptionalAttributes] The CellSubResponseDataOptionalAttributes attribute group contains attributes that is used in SubResponseData elements associated with a SubResponse for a cell subrequest."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1497 site.CaptureRequirement( "MS-FSSHTTP", 1497, @"[In SubResponseDataOptionalAttributes] CellSubResponseDataOptionalAttributes: An attribute group that specifies attributes that MUST be used for SubResponseData elements associated with a subresponse for a cell subrequest."); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R839 site.CaptureRequirement( "MS-FSSHTTP", 839, @"[In CellSubResponseDataOptionalAttributes] The definition of the CellSubResponseDataOptionalAttributes attribute group is as follows: <xs:attributeGroup name=""CellSubResponseDataOptionalAttributes""> <xs:attribute name=""Etag"" type=""xs:string"" use=""optional"" /> <xs:attribute name=""CreateTime"" type=""xs:integer"" use=""optional""/> <xs:attribute name=""LastModifiedTime"" type=""xs:integer"" use=""optional""/> <xs:attribute name=""ModifiedBy"" type=""tns:UserNameType"" use=""optional"" /> <xs:attribute name=""CoalesceErrorMessage"" type=""xs:string"" use=""optional""/> <xs:attribute name=""CoalesceHResult"" type=""xs:integer"" use=""optional""/> <xs:attribute name=""ContainsHotboxData"" type=""tns:TRUEFALSE"" use=""optional""/> <xs:attribute name=""HaveOnlyDemotionChanges"" type=""tns:TRUEFALSE"" use=""optional""/> </xs:attributeGroup>"); } /// <summary> /// Capture requirements related with CellRequestErrorCodeTypes. /// </summary> /// <param name="cellRequestErrorCode">A cellRequestErrorCode</param> /// <param name="site">Instance of ITestSite</param> private static void ValidateCellRequestErrorCodeTypes(ErrorCodeType cellRequestErrorCode, ITestSite site) { if (cellRequestErrorCode == ErrorCodeType.CellRequestFail || cellRequestErrorCode == ErrorCodeType.IRMDocLibarysOnlySupportWebDAV) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R772 site.CaptureRequirement( "MS-FSSHTTP", 772, @"[In CellRequestErrorCodeTypes][CellRequestErrorCodeTypes schema is:] <xs:simpleType name=""CellRequestErrorCodeTypes""> <xs:restriction base=""xs:string""> <!--cell request fail--> <xs:enumeration value=""CellRequestFail""/> <!--cell request etag not matching--> <xs:enumeration value=""IRMDocLibarysOnlySupportWebDAV""/> </xs:restriction> </xs:simpleType>"); // If the validation succeed, then the requirement MS-FSSHTTP_R773 can be captured. site.CaptureRequirement( "MS-FSSHTTP", 773, @"[In CellRequestErrorCodeTypes] The value of CellRequestErrorCodeTypes MUST be one of the following: [CellRequestFail, IRMDocLibarysOnlySupportWebDAV]"); } } } }
XinwLi/Interop-TestSuites-1
FileSyncandWOPI/Source/SharedTestSuite/SharedAdapter/CaptureCode/FSSHTTP/MsfsshttpCellSubRequestCapture.cs
C#
mit
11,228
<?php /** * LICENSE: 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. * * PHP version 5 * * @category Microsoft * @package WindowsAzure\Blob\Models * @author Azure PHP SDK <azurephpsdk@microsoft.com> * @copyright 2012 Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://github.com/windowsazure/azure-sdk-for-php */ namespace WindowsAzure\Blob\Models; use WindowsAzure\Common\Internal\Validate; /** * Optional parameters for listPageBlobRanges wrapper * * @category Microsoft * @package WindowsAzure\Blob\Models * @author Azure PHP SDK <azurephpsdk@microsoft.com> * @copyright 2012 Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @version Release: 0.4.2_2016-04 * @link https://github.com/windowsazure/azure-sdk-for-php */ class ListPageBlobRangesOptions extends BlobServiceOptions { /** * @var string */ private $_leaseId; /** * @var string */ private $_snapshot; /** * @var integer */ private $_rangeStart; /** * @var integer */ private $_rangeEnd; /** * @var AccessCondition */ private $_accessCondition; /** * Gets lease Id for the blob * * @return string */ public function getLeaseId() { return $this->_leaseId; } /** * Sets lease Id for the blob * * @param string $leaseId the blob lease id. * * @return none */ public function setLeaseId($leaseId) { $this->_leaseId = $leaseId; } /** * Gets blob snapshot. * * @return string. */ public function getSnapshot() { return $this->_snapshot; } /** * Sets blob snapshot. * * @param string $snapshot value. * * @return none. */ public function setSnapshot($snapshot) { $this->_snapshot = $snapshot; } /** * Gets rangeStart * * @return integer */ public function getRangeStart() { return $this->_rangeStart; } /** * Sets rangeStart * * @param integer $rangeStart the blob lease id. * * @return none */ public function setRangeStart($rangeStart) { Validate::isInteger($rangeStart, 'rangeStart'); $this->_rangeStart = $rangeStart; } /** * Gets rangeEnd * * @return integer */ public function getRangeEnd() { return $this->_rangeEnd; } /** * Sets rangeEnd * * @param integer $rangeEnd range end value in bytes * * @return none */ public function setRangeEnd($rangeEnd) { Validate::isInteger($rangeEnd, 'rangeEnd'); $this->_rangeEnd = $rangeEnd; } /** * Gets access condition * * @return AccessCondition */ public function getAccessCondition() { return $this->_accessCondition; } /** * Sets access condition * * @param AccessCondition $accessCondition value to use. * * @return none. */ public function setAccessCondition($accessCondition) { $this->_accessCondition = $accessCondition; } }
rollandwalsh/third-rail
plugins/backwpup/vendor/microsoft/windowsazure/WindowsAzure/Blob/Models/ListPageBlobRangesOptions.php
PHP
mit
3,871
import webpack from "webpack" import { spawn } from "child_process" import appRootDir from "app-root-dir" import path from "path" import { createNotification } from "./util" import HotServerManager from "./HotServerManager" import HotClientManager from "./HotClientManager" import ConfigFactory from "../webpack/ConfigFactory" import StatusPlugin from "../webpack/plugins/Status" function safeDisposer(manager) { return manager ? manager.dispose() : Promise.resolve() } /* eslint-disable arrow-body-style, no-console */ function createCompiler({ name, start, done }) { try { const webpackConfig = ConfigFactory({ target: name === "server" ? "node" : "web", mode: "development" }) // Offering a special status handling until Webpack offers a proper `done()` callback // See also: https://github.com/webpack/webpack/issues/4243 webpackConfig.plugins.push(new StatusPlugin({ name, start, done })) return webpack(webpackConfig) } catch (error) { createNotification({ title: "development", level: "error", message: "Webpack config is invalid, please check the console for more information.", notify: true }) console.error(error) throw error } } export default class HotController { constructor() { this.hotClientManager = null this.hotServerManager = null this.clientIsBuilding = false this.serverIsBuilding = false this.timeout = 0 const createClientManager = () => { return new Promise((resolve) => { const compiler = createCompiler({ name: "client", start: () => { this.clientIsBuilding = true createNotification({ title: "Hot Client", level: "info", message: "Building new bundle..." }) }, done: () => { this.clientIsBuilding = false createNotification({ title: "Hot Client", level: "info", message: "Bundle is ready.", notify: true }) resolve(compiler) } }) this.hotClientCompiler = compiler this.hotClientManager = new HotClientManager(compiler) }) } const createServerManager = () => { return new Promise((resolve) => { const compiler = createCompiler({ name: "server", start: () => { this.serverIsBuilding = true createNotification({ title: "Hot Server", level: "info", message: "Building new bundle..." }) }, done: () => { this.serverIsBuilding = false createNotification({ title: "Hot Server", level: "info", message: "Bundle is ready.", notify: true }) this.tryStartServer() resolve(compiler) } }) this.compiledServer = path.resolve( appRootDir.get(), compiler.options.output.path, `${Object.keys(compiler.options.entry)[0]}.js`, ) this.hotServerCompiler = compiler this.hotServerManager = new HotServerManager(compiler, this.hotClientCompiler) }) } createClientManager().then(createServerManager).catch((error) => { console.error("Error during build:", error) }) } tryStartServer = () => { if (this.clientIsBuilding) { if (this.serverTryTimeout) { clearTimeout(this.serverTryTimeout) } this.serverTryTimeout = setTimeout(this.tryStartServer, this.timeout) this.timeout += 100 return } this.startServer() this.timeout = 0 } startServer = () => { if (this.server) { this.server.kill() this.server = null createNotification({ title: "Hot Server", level: "info", message: "Restarting server..." }) } const newServer = spawn("node", [ "--inspect", this.compiledServer, "--colors" ], { stdio: [ process.stdin, process.stdout, "pipe" ] }) createNotification({ title: "Hot Server", level: "info", message: "Server running with latest changes.", notify: true }) newServer.stderr.on("data", (data) => { createNotification({ title: "Hot Server", level: "error", message: "Error in server execution, check the console for more info." }) process.stderr.write("\n") process.stderr.write(data) process.stderr.write("\n") }) this.server = newServer } dispose() { // First the hot client server. Then dispose the hot node server. return safeDisposer(this.hotClientManager).then(() => safeDisposer(this.hotServerManager)).catch((error) => { console.error(error) }) } }
sebastian-software/edgestack
src/hotdev/HotController.js
JavaScript
mit
4,927
<?php namespace Affiliate\AffiliateManagementBundle\Entity; use Doctrine\ORM\EntityRepository; /** * AdminPayReqRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class AdminPayReqRepository extends EntityRepository { }
tobhanugupta/web-services
src/Affiliate/AffiliateManagementBundle/Entity/AdminPayReqRepository.php
PHP
mit
289
<?php /* * This file is part of the HWIOAuthBundle package. * * (c) Hardware.Info <opensource@hardware.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner; use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * OdnoklassnikiResourceOwner. * * @author Sergey Polischook <spolischook@gmail.com> */ class OdnoklassnikiResourceOwner extends GenericOAuth2ResourceOwner { /** * {@inheritdoc} */ protected $paths = array( 'identifier' => 'uid', 'nickname' => 'username', 'realname' => 'name', 'email' => 'email', 'firstname' => 'first_name', 'lastname' => 'last_name', ); /** * {@inheritdoc} */ public function getUserInformation(array $accessToken, array $extraParameters = array()) { $parameters = array( 'access_token' => $accessToken['access_token'], 'application_key' => $this->options['application_key'], ); if ($this->options['fields']) { $parameters['fields'] = $this->options['fields']; $parameters['sig'] = md5(sprintf( 'application_key=%sfields=%smethod=users.getCurrentUser%s', $this->options['application_key'], $this->options['fields'], md5($accessToken['access_token'].$this->options['client_secret']) )); } else { $parameters['sig'] = md5(sprintf( 'application_key=%smethod=users.getCurrentUser%s', $this->options['application_key'], md5($accessToken['access_token'].$this->options['client_secret']) )); } $url = $this->normalizeUrl($this->options['infos_url'], $parameters); $content = $this->doGetUserInformationRequest($url)->getContent(); $response = $this->getUserResponse(); $response->setResponse($content); $response->setResourceOwner($this); $response->setOAuthToken(new OAuthToken($accessToken)); return $response; } /** * {@inheritdoc} */ protected function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults(array( 'authorization_url' => 'https://connect.ok.ru/oauth/authorize', 'access_token_url' => 'https://api.ok.ru/oauth/token.do', 'infos_url' => 'https://api.ok.ru/fb.do?method=users.getCurrentUser', 'application_key' => null, 'fields' => null, )); $fieldsNormalizer = function (Options $options, $value) { if (!$value) { return null; } return is_array($value) ? implode(',', $value) : $value; }; // Symfony <2.6 BC if (method_exists($resolver, 'setNormalizer')) { $resolver->setNormalizer('fields', $fieldsNormalizer); } else { $resolver->setNormalizers(array( 'fields' => $fieldsNormalizer, )); } } }
Tiriel/Quantified
vendor/hwi/oauth-bundle/OAuth/ResourceOwner/OdnoklassnikiResourceOwner.php
PHP
mit
3,326
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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 "../../../mocks/dispatch_syscall_bf_intrinsic_op.hpp" #include <bsl/ut.hpp> /// <!-- description --> /// @brief Main function for this unit test. If a call to bsl::ut_check() fails /// the application will fast fail. If all calls to bsl::ut_check() pass, this /// function will successfully return with bsl::exit_success. /// /// <!-- inputs/outputs --> /// @return Always returns bsl::exit_success. /// [[nodiscard]] auto main() noexcept -> bsl::exit_code { bsl::enable_color(); bsl::ut_scenario{"verify noexcept"} = []() noexcept { bsl::ut_then{} = []() noexcept { static_assert(noexcept(mk::dispatch_syscall_bf_intrinsic_op({}, {}))); }; }; return bsl::ut_success(); }
Bareflank/hypervisor
kernel/tests/mocks/dispatch_syscall_bf_intrinsic_op/requirements.cpp
C++
mit
1,953
/** * 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. */ package com.microsoft.azure.management.kusto.v2019_05_15.implementation; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The list Kusto database principals operation response. */ public class DatabasePrincipalListResultInner { /** * The list of Kusto database principals. */ @JsonProperty(value = "value") private List<DatabasePrincipalInner> value; /** * Get the list of Kusto database principals. * * @return the value value */ public List<DatabasePrincipalInner> value() { return this.value; } /** * Set the list of Kusto database principals. * * @param value the value value to set * @return the DatabasePrincipalListResultInner object itself. */ public DatabasePrincipalListResultInner withValue(List<DatabasePrincipalInner> value) { this.value = value; return this; } }
selvasingh/azure-sdk-for-java
sdk/kusto/mgmt-v2019_05_15/src/main/java/com/microsoft/azure/management/kusto/v2019_05_15/implementation/DatabasePrincipalListResultInner.java
Java
mit
1,165
from __future__ import absolute_import from jinja2 import Markup from rstblog.programs import RSTProgram import typogrify class TypogrifyRSTProgram(RSTProgram): def get_fragments(self): if self._fragment_cache is not None: return self._fragment_cache with self.context.open_source_file() as f: self.get_header(f) rv = self.context.render_rst(f.read().decode('utf-8')) rv['fragment'] = Markup(typogrify.typogrify(rv['fragment'])) self._fragment_cache = rv return rv def setup(builder): builder.programs['rst'] = TypogrifyRSTProgram
ericam/sidesaddle
modules/typogrify.py
Python
mit
620
/*------------------------------------------------------------------------*/ /* */ /* LISTIMP.H */ /* */ /* Copyright Borland International 1991, 1992 */ /* All Rights Reserved */ /* */ /*------------------------------------------------------------------------*/ #if !defined( __LISTIMP_H ) #define __LISTIMP_H #if !defined( __DEFS_H ) #include <_defs.h> #endif // __DEFS_H #if !defined( __MEMMGR_H ) #include <MemMgr.h> #endif // __MEMMGR_H #pragma option -Vo- #if defined( __BCOPT__ ) && !defined( _ALLOW_po ) #pragma option -po- #endif /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_ListElement */ /* */ /* Node for templates BI_ListImp<T> and BI_IListImp<T> */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_ListImp; template <class T> class _CLASSTYPE BI_ListBlockInitializer { protected: BI_ListBlockInitializer() { PRECONDITION( count != UINT_MAX ); if( count++ == 0 ) BI_ListElement<T>::mgr = new MemBlocks( sizeof(BI_ListElement<T>), 20 ); } ~BI_ListBlockInitializer() { PRECONDITION( count != 0 ); if( --count == 0 ) { delete BI_ListElement<T>::mgr; BI_ListElement<T>::mgr = 0; } } static unsigned count; }; template <class T> unsigned BI_ListBlockInitializer<T>::count = 0; template <class T> class _CLASSTYPE BI_ListElement { public: BI_ListElement( T t, BI_ListElement<T> _FAR *p ) : data(t) { next = p->next; p->next = this; } BI_ListElement(); BI_ListElement<T> _FAR *next; T data; void _FAR *operator new( size_t sz ); void operator delete( void _FAR * ); private: friend class BI_ListBlockInitializer<T>; static MemBlocks *mgr; }; template <class T> MemBlocks *BI_ListElement<T>::mgr = 0; inline BI_ListElement<void _FAR *>::BI_ListElement() { next = 0; data = 0; } template <class T> inline BI_ListElement<T>::BI_ListElement() { next = 0; } template <class T> void _FAR *BI_ListElement<T>::operator new( size_t sz ) { PRECONDITION( mgr != 0 ); return mgr->allocate( sz ); } template <class T> void BI_ListElement<T>::operator delete( void _FAR *b ) { PRECONDITION( mgr != 0 ); mgr->free( b ); } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_ListImp */ /* */ /* Implements a list of objects of type T. Assumes that */ /* T has meaningful copy semantics and a default constructor. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_ListIteratorImp; template <class T> class _CLASSTYPE BI_ListImp : private BI_ListBlockInitializer<T> { public: friend class BI_ListIteratorImp<T>; BI_ListImp() { initList(); } ~BI_ListImp() { flush(); } T peekHead() const { return head.next->data; } void add( T ); void detach( T, int = 0 ); void flush( int del = 0 ); int isEmpty() const { return head.next == &tail; } void forEach( void (_FAR *)(T _FAR &, void _FAR *), void _FAR * ); T _FAR *firstThat( int (_FAR *)(const T _FAR &, void _FAR *), void _FAR * ) const; T _FAR *lastThat( int (_FAR *)(const T _FAR &, void _FAR *), void _FAR * ) const; protected: BI_ListElement<T> head, tail; virtual BI_ListElement<T> _FAR *findDetach( T t ) { return findPred(t); } virtual BI_ListElement<T> _FAR *findPred( T ); private: virtual void removeData( BI_ListElement<T> _FAR * ) { } void initList(); }; template <class T> void BI_ListImp<T>::initList() { head.next = &tail; tail.next = &tail; } template <class T> void BI_ListImp<T>::add( T toAdd ) { new BI_ListElement<T>( toAdd, &head ); } template <class T> BI_ListElement<T> _FAR *BI_ListImp<T>::findPred( T t ) { tail.data = t; BI_ListElement<T> _FAR *cursor = &head; while( !(t == cursor->next->data) ) cursor = cursor->next; return cursor; } template <class T> void BI_ListImp<T>::detach( T toDetach, int del ) { BI_ListElement<T> _FAR *pred = findDetach( toDetach ); BI_ListElement<T> _FAR *item = pred->next; if( item != &tail ) { pred->next = pred->next->next; if( del != 0 ) removeData( item ); delete item; } } template <class T> void BI_ListImp<T>::flush( int del ) { BI_ListElement<T> _FAR *current = head.next; while( current != &tail ) { BI_ListElement<T> _FAR *temp = current; current = current->next; if( del != 0 ) removeData( temp ); delete temp; } initList(); } template <class T> void BI_ListImp<T>::forEach( void (_FAR *f)(T _FAR &, void _FAR *), void _FAR *args ) { BI_ListElement<T> _FAR *cur = head.next; while( cur->next != cur ) { f( cur->data, args ); cur = cur->next; } } template <class T> T _FAR *BI_ListImp<T>::firstThat( int (_FAR *cond)(const T _FAR &, void _FAR *), void _FAR *args ) const { BI_ListElement<T> _FAR *cur = head.next; while( cur->next != cur ) if( cond( cur->data, args ) != 0 ) return &(cur->data); else cur = cur->next; return 0; } template <class T> T _FAR *BI_ListImp<T>::lastThat( int (_FAR *cond)(const T _FAR &, void _FAR *), void _FAR *args ) const { T _FAR *res = 0; BI_ListElement<T> _FAR *cur = head.next; while( cur->next != cur ) { if( cond( cur->data, args ) != 0 ) res = &(cur->data); cur = cur->next; } return res; } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_SListImp */ /* */ /* Implements a sorted list of objects of type T. Assumes that */ /* T has meaningful copy semantics, a meaningful < operator, and a */ /* default constructor. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_SListImp : public BI_ListImp<T> { public: void add( T ); protected: virtual BI_ListElement<T> _FAR *findDetach( T t ); virtual BI_ListElement<T> _FAR *findPred( T ); }; template <class T> void BI_SListImp<T>::add( T t ) { new BI_ListElement<T>( t, findPred(t) ); } template <class T> BI_ListElement<T> _FAR *BI_SListImp<T>::findDetach( T t ) { BI_ListElement<T> _FAR *res = findPred(t); if( res->next->data == t ) return res; else return &tail; } template <class T> BI_ListElement<T> _FAR *BI_SListImp<T>::findPred( T t ) { tail.data = t; BI_ListElement<T> _FAR *cursor = &head; while( cursor->next->data < t ) cursor = cursor->next; return cursor; } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_ListIteratorImp */ /* */ /* Implements a list iterator. This iterator works with any direct */ /* list. For indirect lists, see BI_IListIteratorImp. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_ListIteratorImp { public: BI_ListIteratorImp( const BI_ListImp<T> _FAR &l ) { list = &l; cur = list->head.next; } operator int() { return cur != &(list->tail); } T current() { return cur->data; } T operator ++ ( int ) { BI_ListElement<T> _FAR *temp = cur; cur = cur->next; return temp->data; } T operator ++ () { cur = cur->next; return cur->data; } void restart() { cur = list->head.next; } private: const BI_ListImp<T> _FAR *list; BI_ListElement<T> _FAR *cur; }; /*------------------------------------------------------------------------*/ /* */ /* template <class T, class Vect> class BI_InternalIListImp */ /* */ /* Implements a list of pointers to objects of type T. */ /* This is implemented through the form of BI_ListImp specified by List. */ /* Since pointers always have meaningful copy semantics, this class */ /* can handle any type of object. */ /* */ /*------------------------------------------------------------------------*/ template <class T, class List> class _CLASSTYPE BI_InternalIListImp : public List { public: T _FAR *peekHead() const { return (T _FAR *)List::peekHead(); } void add( T _FAR *t ) { List::add( t ); } void detach( T _FAR *t, int del = 0 ) { List::detach( t, del ); } void forEach( void (_FAR *)(T _FAR &, void _FAR *), void _FAR * ); T _FAR *firstThat( int (_FAR *)(const T _FAR &, void _FAR *), void _FAR * ) const; T _FAR *lastThat( int (_FAR *)(const T _FAR &, void _FAR *), void _FAR * ) const; protected: virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * ) = 0; private: virtual void removeData( BI_ListElement<void _FAR *> _FAR *block ) { delete (T _FAR *)(block->data); } }; template <class T, class List> void BI_InternalIListImp<T, List>::forEach( void (_FAR *f)(T _FAR &, void _FAR *), void _FAR *args ) { BI_ListElement<void _FAR *> _FAR *cur = head.next; while( cur->next != cur ) { f( *(T _FAR *)cur->data, args ); cur = cur->next; } } template <class T, class List> T _FAR *BI_InternalIListImp<T, List>::firstThat( int (_FAR *cond)(const T _FAR &, void _FAR *), void _FAR *args ) const { BI_ListElement<void _FAR *> _FAR *cur = head.next; while( cur->next != cur ) if( cond( *(T _FAR *)(cur->data), args ) != 0 ) return (T _FAR *)cur->data; else cur = cur->next; return 0; } template <class T, class List> T _FAR *BI_InternalIListImp<T, List>::lastThat( int (_FAR *cond)(const T _FAR &, void _FAR *), void _FAR *args ) const { T _FAR *res = 0; BI_ListElement<void _FAR *> _FAR *cur = head.next; while( cur->next != cur ) { if( cond( *(T _FAR *)(cur->data), args ) != 0 ) res = (T _FAR *)(cur->data); cur = cur->next; } return res; } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_IListImp */ /* */ /* Implements a list of pointers to objects of type T. */ /* This is implemented through the template BI_InternalIListImp. Since */ /* pointers always have meaningful copy semantics, this class */ /* can handle any type of object. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_IListImp : public BI_InternalIListImp<T, BI_ListImp<void _FAR *> > { protected: virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * ); }; template <class T> BI_ListElement<void _FAR *> _FAR *BI_IListImp<T>::findPred( void _FAR *t ) { tail.data = t; BI_ListElement<void _FAR *> _FAR *cursor = &head; while( !(*(T _FAR *)t == *(T _FAR *)(cursor->next->data)) ) cursor = cursor->next; return cursor; } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_ISListImp */ /* */ /* Implements a sorted list of pointers to objects of type T. */ /* This is implemented through the template BI_InternalIListImp. Since */ /* pointers always have meaningful copy semantics, this class */ /* can handle any type of object. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_ISListImp : public BI_InternalIListImp<T, BI_SListImp<void _FAR *> > { protected: virtual BI_ListElement<void _FAR *> _FAR *findDetach( void _FAR * ); virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * ); }; template <class T> BI_ListElement<void _FAR *> _FAR *BI_ISListImp<T>::findDetach( void _FAR *t ) { BI_ListElement<void _FAR *> _FAR *res = findPred(t); if( *(T _FAR *)(res->next->data) == *(T _FAR *)t ) return res; else return &tail; } template <class T> BI_ListElement<void _FAR *> _FAR *BI_ISListImp<T>::findPred( void _FAR *t ) { tail.data = t; BI_ListElement<void _FAR *> _FAR *cursor = &head; while( *(T _FAR *)(cursor->next->data) < *(T _FAR *)t ) cursor = cursor->next; return cursor; } /*------------------------------------------------------------------------*/ /* */ /* template <class T> class BI_IListIteratorImp */ /* */ /* Implements a list iterator. This iterator works with any indirect */ /* list. For direct lists, see BI_ListIteratorImp. */ /* */ /*------------------------------------------------------------------------*/ template <class T> class _CLASSTYPE BI_IListIteratorImp : public BI_ListIteratorImp<void _FAR *> { public: BI_IListIteratorImp( const BI_ListImp<void _FAR *> _FAR &l ) : BI_ListIteratorImp<void _FAR *>(l) {} T _FAR *current() { return (T _FAR *)BI_ListIteratorImp<void _FAR *>::current(); } T _FAR *operator ++ (int) { return (T _FAR *)BI_ListIteratorImp<void _FAR *>::operator ++ (1); } T _FAR *operator ++ () { return (T _FAR *)BI_ListIteratorImp<void _FAR *>::operator ++ (); } }; #if defined( __BCOPT__ ) && !defined( _ALLOW_po ) #pragma option -po. #endif #pragma option -Vo. #endif // __LISTIMP_H
gandrewstone/GameMaker
tools/BORLANDC/CLASSLIB/INCLUDE/LISTIMP.H
C++
mit
17,753
# encoding: utf-8 module FFaker module PhoneNumberKR extend ModuleUtils extend self HOME_PHONE_PREFIXES = %w(02 031 032 033 041 042 043 044 049 051 052 053 054 055 061 062 063 064).freeze MOBILE_PHONE_PREFIXES = %w(010 011 016 019).freeze def phone_number case rand(2) when 0 then home_work_phone_number when 1 then mobile_phone_number end end def home_work_phone_number FFaker.numerify("#{HOME_PHONE_PREFIXES.sample} #### ####") end def mobile_phone_number FFaker.numerify("#{MOBILE_PHONE_PREFIXES.sample} #### ####") end def contry_code '+82' end def international_mobile_phone_number number = mobile_phone_number number[0] = "#{contry_code} " number end def international_home_work_phone_number number = home_work_phone_number number[0] = "#{contry_code} " number end def international_phone_number case rand(2) when 0 then international_mobile_phone_number when 1 then international_home_work_phone_number end end end end
44uk/ffaker
lib/ffaker/phone_number_kr.rb
Ruby
mit
1,119
package ar.com.javacuriosities.ws.gen.service.jaxws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "getIpAddressResponse", namespace = "http://service.gen.ws.javacuriosities.com.ar/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getIpAddressResponse", namespace = "http://service.gen.ws.javacuriosities.com.ar/") public class GetIpAddressResponse { @XmlElement(name = "return", namespace = "") private String _return; /** * * @return * returns String */ public String getReturn() { return this._return; } /** * * @param _return * the value for the _return property */ public void setReturn(String _return) { this._return = _return; } }
ldebello/javacuriosities
JavaEE/JavaWebServices/JAX-WS/WSGenBasics/src/main/java/ar/com/javacuriosities/ws/gen/service/jaxws/GetIpAddressResponse.java
Java
mit
962
<header class="main-header"> <!-- Logo --> <a href="<?php echo admin_template_url();?>index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">You have 4 messages</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <!-- start message --> <a href="#"> <div class="pull-left"> <img src="<?php echo admin_template_url();?>dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <h4> Support Team <small><i class="fa fa-clock-o"></i> 5 mins</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <!-- end message --> <li> <a href="#"> <div class="pull-left"> <img src="<?php echo admin_template_url();?>dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> AdminLTE Design Team <small><i class="fa fa-clock-o"></i> 2 hours</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="<?php echo admin_template_url();?>dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Developers <small><i class="fa fa-clock-o"></i> Today</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="<?php echo admin_template_url();?>dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Sales Department <small><i class="fa fa-clock-o"></i> Yesterday</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="<?php echo admin_template_url();?>dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> Reviewers <small><i class="fa fa-clock-o"></i> 2 days</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> </ul> </li> <li class="footer"><a href="#">See All Messages</a></li> </ul> </li> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> <li> <a href="#"> <i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems </a> </li> <li> <a href="#"> <i class="fa fa-users text-red"></i> 5 new members joined </a> </li> <li> <a href="#"> <i class="fa fa-shopping-cart text-green"></i> 25 sales made </a> </li> <li> <a href="#"> <i class="fa fa-user text-red"></i> You changed your username </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- Tasks: style can be found in dropdown.less --> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <!-- Task item --> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress progress-xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li> <!-- Task item --> <a href="#"> <h3> Create a nice theme <small class="pull-right">40%</small> </h3> <div class="progress progress-xs"> <div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li> <!-- Task item --> <a href="#"> <h3> Some task I need to do <small class="pull-right">60%</small> </h3> <div class="progress progress-xs"> <div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">60% Complete</span> </div> </div> </a> </li> <!-- end task item --> <li> <!-- Task item --> <a href="#"> <h3> Make beautiful transitions <small class="pull-right">80%</small> </h3> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">80% Complete</span> </div> </div> </a> </li> <!-- end task item --> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="<?php echo admin_template_url();?>dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <span class="hidden-xs">Alexander Pierce</span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="<?php echo admin_template_url();?>dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> Alexander Pierce - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="row"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </div> <!-- /.row --> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header>
Bathe0603it/ThemeShop
application/views/admincp/layout/lay-bin/header.php
PHP
mit
14,886
"use strict"; exports.__esModule = true; // istanbul ignore next var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; })(); // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj["default"] = obj;return newObj; } } // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } // istanbul ignore next function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _convertSourceMap = require("convert-source-map"); var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); var _modules = require("../modules"); var _modules2 = _interopRequireDefault(_modules); var _optionsOptionManager = require("./options/option-manager"); var _optionsOptionManager2 = _interopRequireDefault(_optionsOptionManager); var _pluginManager = require("./plugin-manager"); var _pluginManager2 = _interopRequireDefault(_pluginManager); var _shebangRegex = require("shebang-regex"); var _shebangRegex2 = _interopRequireDefault(_shebangRegex); var _traversalPath = require("../../traversal/path"); var _traversalPath2 = _interopRequireDefault(_traversalPath); var _lodashLangIsFunction = require("lodash/lang/isFunction"); var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction); var _sourceMap = require("source-map"); var _sourceMap2 = _interopRequireDefault(_sourceMap); var _generation = require("../../generation"); var _generation2 = _interopRequireDefault(_generation); var _helpersCodeFrame = require("../../helpers/code-frame"); var _helpersCodeFrame2 = _interopRequireDefault(_helpersCodeFrame); var _lodashObjectDefaults = require("lodash/object/defaults"); var _lodashObjectDefaults2 = _interopRequireDefault(_lodashObjectDefaults); var _lodashCollectionIncludes = require("lodash/collection/includes"); var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes); var _traversal = require("../../traversal"); var _traversal2 = _interopRequireDefault(_traversal); var _tryResolve = require("try-resolve"); var _tryResolve2 = _interopRequireDefault(_tryResolve); var _logger = require("./logger"); var _logger2 = _interopRequireDefault(_logger); var _plugin = require("../plugin"); var _plugin2 = _interopRequireDefault(_plugin); var _helpersParse = require("../../helpers/parse"); var _helpersParse2 = _interopRequireDefault(_helpersParse); var _traversalHub = require("../../traversal/hub"); var _traversalHub2 = _interopRequireDefault(_traversalHub); var _util = require("../../util"); var util = _interopRequireWildcard(_util); var _path = require("path"); var _path2 = _interopRequireDefault(_path); var _types = require("../../types"); var t = _interopRequireWildcard(_types); /** * [Please add a description.] */ var File = (function () { function File(opts, pipeline) { if (opts === undefined) opts = {}; _classCallCheck(this, File); this.transformerDependencies = {}; this.dynamicImportTypes = {}; this.dynamicImportIds = {}; this.dynamicImports = []; this.declarations = {}; this.usedHelpers = {}; this.dynamicData = {}; this.data = {}; this.ast = {}; this.metadata = { modules: { imports: [], exports: { exported: [], specifiers: [] } } }; this.hub = new _traversalHub2["default"](this); this.pipeline = pipeline; this.log = new _logger2["default"](this, opts.filename || "unknown"); this.opts = this.initOptions(opts); this.buildTransformers(); } /** * [Please add a description.] */ File.prototype.initOptions = function initOptions(opts) { opts = new _optionsOptionManager2["default"](this.log, this.pipeline).init(opts); if (opts.inputSourceMap) { opts.sourceMaps = true; } if (opts.moduleId) { opts.moduleIds = true; } opts.basename = _path2["default"].basename(opts.filename, _path2["default"].extname(opts.filename)); opts.ignore = util.arrayify(opts.ignore, util.regexify); if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); _lodashObjectDefaults2["default"](opts, { moduleRoot: opts.sourceRoot }); _lodashObjectDefaults2["default"](opts, { sourceRoot: opts.moduleRoot }); _lodashObjectDefaults2["default"](opts, { filenameRelative: opts.filename }); _lodashObjectDefaults2["default"](opts, { sourceFileName: opts.filenameRelative, sourceMapTarget: opts.filenameRelative }); // if (opts.externalHelpers) { this.set("helpersNamespace", t.identifier("babelHelpers")); } return opts; }; /** * [Please add a description.] */ File.prototype.isLoose = function isLoose(key) { return _lodashCollectionIncludes2["default"](this.opts.loose, key); }; /** * [Please add a description.] */ File.prototype.buildTransformers = function buildTransformers() { var file = this; var transformers = this.transformers = {}; var secondaryStack = []; var stack = []; // build internal transformers for (var key in this.pipeline.transformers) { var transformer = this.pipeline.transformers[key]; var pass = transformers[key] = transformer.buildPass(file); if (pass.canTransform()) { stack.push(pass); if (transformer.metadata.secondPass) { secondaryStack.push(pass); } if (transformer.manipulateOptions) { transformer.manipulateOptions(file.opts, file); } } } // init plugins! var beforePlugins = []; var afterPlugins = []; var pluginManager = new _pluginManager2["default"]({ file: this, transformers: this.transformers, before: beforePlugins, after: afterPlugins }); for (var i = 0; i < file.opts.plugins.length; i++) { pluginManager.add(file.opts.plugins[i]); } stack = beforePlugins.concat(stack, afterPlugins); // build transformer stack this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack); // build dependency graph var _arr = stack; for (var _i = 0; _i < _arr.length; _i++) { var pass = _arr[_i];var _arr2 = pass.plugin.dependencies; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var dep = _arr2[_i2]; this.transformerDependencies[dep] = pass.key; } } // collapse stack categories this.transformerStack = this.collapseStack(stack); }; /** * [Please add a description.] */ File.prototype.collapseStack = function collapseStack(_stack) { var stack = []; var ignore = []; var _arr3 = _stack; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var pass = _arr3[_i3]; // been merged if (ignore.indexOf(pass) >= 0) continue; var group = pass.plugin.metadata.group; // can't merge if (!pass.canTransform() || !group) { stack.push(pass); continue; } var mergeStack = []; var _arr4 = _stack; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var _pass = _arr4[_i4]; if (_pass.plugin.metadata.group === group) { mergeStack.push(_pass); ignore.push(_pass); } } var visitors = []; var _arr5 = mergeStack; for (var _i5 = 0; _i5 < _arr5.length; _i5++) { var _pass2 = _arr5[_i5]; visitors.push(_pass2.plugin.visitor); } var visitor = _traversal2["default"].visitors.merge(visitors); var mergePlugin = new _plugin2["default"](group, { visitor: visitor }); stack.push(mergePlugin.buildPass(this)); } return stack; }; /** * [Please add a description.] */ File.prototype.set = function set(key, val) { return this.data[key] = val; }; /** * [Please add a description.] */ File.prototype.setDynamic = function setDynamic(key, fn) { this.dynamicData[key] = fn; }; /** * [Please add a description.] */ File.prototype.get = function get(key) { var data = this.data[key]; if (data) { return data; } else { var dynamic = this.dynamicData[key]; if (dynamic) { return this.set(key, dynamic()); } } }; /** * [Please add a description.] */ File.prototype.resolveModuleSource = function resolveModuleSource(source) { var resolveModuleSource = this.opts.resolveModuleSource; if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); return source; }; /** * [Please add a description.] */ File.prototype.addImport = function addImport(source, name, type) { name = name || source; var id = this.dynamicImportIds[name]; if (!id) { source = this.resolveModuleSource(source); id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name); var specifiers = [t.importDefaultSpecifier(id)]; var declar = t.importDeclaration(specifiers, t.literal(source)); declar._blockHoist = 3; if (type) { var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || []; modules.push(declar); } if (this.transformers["es6.modules"].canTransform()) { this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope); this.moduleFormatter.hasLocalImports = true; } else { this.dynamicImports.push(declar); } } return id; }; /** * [Please add a description.] */ File.prototype.attachAuxiliaryComment = function attachAuxiliaryComment(node) { var beforeComment = this.opts.auxiliaryCommentBefore; if (beforeComment) { node.leadingComments = node.leadingComments || []; node.leadingComments.push({ type: "CommentLine", value: " " + beforeComment }); } var afterComment = this.opts.auxiliaryCommentAfter; if (afterComment) { node.trailingComments = node.trailingComments || []; node.trailingComments.push({ type: "CommentLine", value: " " + afterComment }); } return node; }; /** * [Please add a description.] */ File.prototype.addHelper = function addHelper(name) { var isSolo = _lodashCollectionIncludes2["default"](File.soloHelpers, name); if (!isSolo && !_lodashCollectionIncludes2["default"](File.helpers, name)) { throw new ReferenceError("Unknown helper " + name); } var declar = this.declarations[name]; if (declar) return declar; this.usedHelpers[name] = true; if (!isSolo) { var generator = this.get("helperGenerator"); var runtime = this.get("helpersNamespace"); if (generator) { return generator(name); } else if (runtime) { var id = t.identifier(t.toIdentifier(name)); return t.memberExpression(runtime, id); } } var ref = util.template("helper-" + name); var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); if (t.isFunctionExpression(ref) && !ref.id) { ref.body._compact = true; ref._generated = true; ref.id = uid; ref.type = "FunctionDeclaration"; this.attachAuxiliaryComment(ref); this.path.unshiftContainer("body", ref); } else { ref._compact = true; this.scope.push({ id: uid, init: ref, unique: true }); } return uid; }; File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { // Generate a unique name based on the string literals so we dedupe // identical strings used in the program. var stringIds = raw.elements.map(function (string) { return string.value; }); var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); var declar = this.declarations[name]; if (declar) return declar; var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); var helperId = this.addHelper(helperName); var init = t.callExpression(helperId, [strings, raw]); init._compact = true; this.scope.push({ id: uid, init: init, _blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers }); return uid; }; /** * [Please add a description.] */ File.prototype.errorWithNode = function errorWithNode(node, msg) { var Error = arguments.length <= 2 || arguments[2] === undefined ? SyntaxError : arguments[2]; var err; var loc = node && (node.loc || node._loc); if (loc) { err = new Error("Line " + loc.start.line + ": " + msg); err.loc = loc.start; } else { // todo: find errors with nodes inside to at least point to something err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it."); } return err; }; /** * [Please add a description.] */ File.prototype.mergeSourceMap = function mergeSourceMap(map) { var opts = this.opts; var inputMap = opts.inputSourceMap; if (inputMap) { map.sources[0] = inputMap.file; var inputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(inputMap); var outputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(map); var outputMapGenerator = _sourceMap2["default"].SourceMapGenerator.fromSourceMap(outputMapConsumer); outputMapGenerator.applySourceMap(inputMapConsumer); var mergedMap = outputMapGenerator.toJSON(); mergedMap.sources = inputMap.sources; mergedMap.file = inputMap.file; return mergedMap; } return map; }; /** * [Please add a description.] */ File.prototype.getModuleFormatter = function getModuleFormatter(type) { if (_lodashLangIsFunction2["default"](type) || !_modules2["default"][type]) { this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead."); } var ModuleFormatter = _lodashLangIsFunction2["default"](type) ? type : _modules2["default"][type]; if (!ModuleFormatter) { var loc = _tryResolve2["default"].relative(type); if (loc) ModuleFormatter = require(loc); } if (!ModuleFormatter) { throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type)); } return new ModuleFormatter(this); }; /** * [Please add a description.] */ File.prototype.parse = function parse(code) { var opts = this.opts; // var parseOpts = { highlightCode: opts.highlightCode, nonStandard: opts.nonStandard, sourceType: opts.sourceType, filename: opts.filename, plugins: {} }; var features = parseOpts.features = {}; for (var key in this.transformers) { var transformer = this.transformers[key]; features[key] = transformer.canTransform(); } parseOpts.looseModules = this.isLoose("es6.modules"); parseOpts.strictMode = features.strict; this.log.debug("Parse start"); var ast = _helpersParse2["default"](code, parseOpts); this.log.debug("Parse stop"); return ast; }; /** * [Please add a description.] */ File.prototype._addAst = function _addAst(ast) { this.path = _traversalPath2["default"].get({ hub: this.hub, parentPath: null, parent: ast, container: ast, key: "program" }).setContext(); this.scope = this.path.scope; this.ast = ast; }; /** * [Please add a description.] */ File.prototype.addAst = function addAst(ast) { this.log.debug("Start set AST"); this._addAst(ast); this.log.debug("End set AST"); this.log.debug("Start module formatter init"); var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules); if (modFormatter.init && this.transformers["es6.modules"].canTransform()) { modFormatter.init(); } this.log.debug("End module formatter init"); }; /** * [Please add a description.] */ File.prototype.transform = function transform() { this.call("pre"); var _arr6 = this.transformerStack; for (var _i6 = 0; _i6 < _arr6.length; _i6++) { var pass = _arr6[_i6]; pass.transform(); } this.call("post"); return this.generate(); }; /** * [Please add a description.] */ File.prototype.wrap = function wrap(code, callback) { code = code + ""; try { if (this.shouldIgnore()) { return this.makeResult({ code: code, ignored: true }); } else { return callback(); } } catch (err) { if (err._babel) { throw err; } else { err._babel = true; } var message = err.message = this.opts.filename + ": " + err.message; var loc = err.loc; if (loc) { err.codeFrame = _helpersCodeFrame2["default"](code, loc.line, loc.column + 1, this.opts); message += "\n" + err.codeFrame; } if (process.browser) { // chrome has it's own pretty stringifier which doesn't use the stack property // https://github.com/babel/babel/issues/2175 err.message = message; } if (err.stack) { var newStack = err.stack.replace(err.message, message); try { err.stack = newStack; } catch (e) { // `err.stack` may be a readonly property in some environments } } throw err; } }; /** * [Please add a description.] */ File.prototype.addCode = function addCode(code) { code = (code || "") + ""; code = this.parseInputSourceMap(code); this.code = code; }; /** * [Please add a description.] */ File.prototype.parseCode = function parseCode() { this.parseShebang(); var ast = this.parse(this.code); this.addAst(ast); }; /** * [Please add a description.] */ File.prototype.shouldIgnore = function shouldIgnore() { var opts = this.opts; return util.shouldIgnore(opts.filename, opts.ignore, opts.only); }; /** * [Please add a description.] */ File.prototype.call = function call(key) { var _arr7 = this.uncollapsedTransformerStack; for (var _i7 = 0; _i7 < _arr7.length; _i7++) { var pass = _arr7[_i7]; var fn = pass.plugin[key]; if (fn) fn(this); } }; /** * [Please add a description.] */ File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { var opts = this.opts; if (opts.inputSourceMap !== false) { var inputMap = _convertSourceMap2["default"].fromSource(code); if (inputMap) { opts.inputSourceMap = inputMap.toObject(); code = _convertSourceMap2["default"].removeComments(code); } } return code; }; /** * [Please add a description.] */ File.prototype.parseShebang = function parseShebang() { var shebangMatch = _shebangRegex2["default"].exec(this.code); if (shebangMatch) { this.shebang = shebangMatch[0]; this.code = this.code.replace(_shebangRegex2["default"], ""); } }; /** * [Please add a description.] */ File.prototype.makeResult = function makeResult(_ref) { var code = _ref.code; var _ref$map = _ref.map; var map = _ref$map === undefined ? null : _ref$map; var ast = _ref.ast; var ignored = _ref.ignored; var result = { metadata: null, ignored: !!ignored, code: null, ast: null, map: map }; if (this.opts.code) { result.code = code; } if (this.opts.ast) { result.ast = ast; } if (this.opts.metadata) { result.metadata = this.metadata; result.metadata.usedHelpers = Object.keys(this.usedHelpers); } return result; }; /** * [Please add a description.] */ File.prototype.generate = function generate() { var opts = this.opts; var ast = this.ast; var result = { ast: ast }; if (!opts.code) return this.makeResult(result); this.log.debug("Generation start"); var _result = _generation2["default"](ast, opts, this.code); result.code = _result.code; result.map = _result.map; this.log.debug("Generation end"); if (this.shebang) { // add back shebang result.code = this.shebang + "\n" + result.code; } if (result.map) { result.map = this.mergeSourceMap(result.map); } if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { result.code += "\n" + _convertSourceMap2["default"].fromObject(result.map).toComment(); } if (opts.sourceMaps === "inline") { result.map = null; } return this.makeResult(result); }; _createClass(File, null, [{ key: "helpers", /** * [Please add a description.] */ value: ["inherits", "defaults", "create-class", "create-decorated-class", "create-decorated-object", "define-decorated-property-descriptor", "tagged-template-literal", "tagged-template-literal-loose", "to-array", "to-consumable-array", "sliced-to-array", "sliced-to-array-loose", "object-without-properties", "has-own", "slice", "bind", "define-property", "async-to-generator", "interop-export-wildcard", "interop-require-wildcard", "interop-require-default", "typeof", "extends", "get", "set", "new-arrow-check", "class-call-check", "object-destructuring-empty", "temporal-undefined", "temporal-assert-defined", "self-global", "typeof-react-element", "default-props", "instanceof", // legacy "interop-require"], /** * [Please add a description.] */ enumerable: true }, { key: "soloHelpers", value: [], enumerable: true }]); return File; })(); exports["default"] = File; module.exports = exports["default"]; //# sourceMappingURL=index-compiled.js.map
patelsan/fetchpipe
node_modules/babel-core/lib/transformation/file/index-compiled.js
JavaScript
mit
22,758
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {LanguageService} from '../../language_service'; import {getExternalFiles} from '../../ts_plugin'; import {APP_COMPONENT, setup} from './mock_host'; describe('getExternalFiles()', () => { it('should return all typecheck files', () => { const {project, tsLS} = setup(); let externalFiles = getExternalFiles(project); // Initially there are no external files because Ivy compiler hasn't done // a global analysis expect(externalFiles).toEqual([]); // Trigger global analysis const ngLS = new LanguageService(project, tsLS, {}); ngLS.getSemanticDiagnostics(APP_COMPONENT); // Now that global analysis is run, we should have all the typecheck files externalFiles = getExternalFiles(project); expect(externalFiles.length).toBe(1); expect(externalFiles[0].endsWith('app.component.ngtypecheck.ts')).toBeTrue(); }); });
alxhub/angular
packages/language-service/ivy/test/legacy/ts_plugin_spec.ts
TypeScript
mit
1,076
module AASM::Core class State attr_reader :name, :state_machine, :options def initialize(name, klass, state_machine, options={}) @name = name @klass = klass @state_machine = state_machine update(options) end def ==(state) if state.is_a? Symbol name == state else name == state.name end end def <=>(state) if state.is_a? Symbol name <=> state else name <=> state.name end end def to_s name.to_s end def fire_callbacks(action, record, *args) action = @options[action] catch :halt_aasm_chain do action.is_a?(Array) ? action.each {|a| _fire_callbacks(a, record, args)} : _fire_callbacks(action, record, args) end end def display_name @display_name ||= begin if Module.const_defined?(:I18n) localized_name else name.to_s.gsub(/_/, ' ').capitalize end end end def localized_name AASM::Localizer.new.human_state_name(@klass, self) end alias human_name localized_name def for_select [display_name, name.to_s] end private def update(options = {}) if options.key?(:display) then @display_name = options.delete(:display) end @options = options self end def _fire_callbacks(action, record, args) case action when Symbol, String arity = record.__send__(:method, action.to_sym).arity record.__send__(action, *(arity < 0 ? args : args[0...arity])) when Proc arity = action.arity action.call(record, *(arity < 0 ? args : args[0...arity])) end end end end # AASM
HoyaBoya/aasm
lib/aasm/core/state.rb
Ruby
mit
1,776
<?php /** * TOP API: taobao.fenxiao.dealer.requisitionorder.refuse request * * @author auto create * @since 1.0, 2013-09-13 16:51:03 */ class Taobao_Request_FenxiaoDealerRequisitionorderRefuseRequest { /** * 采购申请/经销采购单编号 **/ private $dealerOrderId; /** * 驳回原因(1:价格不合理;2:采购数量不合理;3:其他原因) **/ private $reason; /** * 驳回详细原因,字数范围5-200字 **/ private $reasonDetail; private $apiParas = array(); public function setDealerOrderId($dealerOrderId) { $this->dealerOrderId = $dealerOrderId; $this->apiParas["dealer_order_id"] = $dealerOrderId; } public function getDealerOrderId() { return $this->dealerOrderId; } public function setReason($reason) { $this->reason = $reason; $this->apiParas["reason"] = $reason; } public function getReason() { return $this->reason; } public function setReasonDetail($reasonDetail) { $this->reasonDetail = $reasonDetail; $this->apiParas["reason_detail"] = $reasonDetail; } public function getReasonDetail() { return $this->reasonDetail; } public function getApiMethodName() { return "taobao.fenxiao.dealer.requisitionorder.refuse"; } public function getApiParas() { return $this->apiParas; } public function check() { Taobao_RequestCheckUtil::checkNotNull($this->dealerOrderId, "dealerOrderId"); Taobao_RequestCheckUtil::checkNotNull($this->reason, "reason"); Taobao_RequestCheckUtil::checkNotNull($this->reasonDetail, "reasonDetail"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
musicsnap/LearnCode
php/code/yaf/application/library/Taobao/Request/FenxiaoDealerRequisitionorderRefuseRequest.php
PHP
mit
1,658
namespace Hjson { /// <summary>Defines the known json types.</summary> /// <remarks>There is no null type as the primitive will be null instead of the JsonPrimitive containing null.</remarks> public enum JsonType { /// <summary>Json value of type string.</summary> String, /// <summary>Json value of type number.</summary> Number, /// <summary>Json value of type object.</summary> Object, /// <summary>Json value of type array.</summary> Array, /// <summary>Json value of type boolean.</summary> Boolean, /// <summary>Json value of an unknown type.</summary> Unknown, } }
laktak/hjson-cs
Hjson/JsonType.cs
C#
mit
630
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.annotation; import org.fest.assertions.Assertions; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.MockUtil; import org.mockito.runners.MockitoJUnitRunner; import org.mockitousage.examples.use.ArticleCalculator; import org.mockitousage.examples.use.ArticleDatabase; import org.mockitousage.examples.use.ArticleManager; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MockInjectionUsingConstructorTest { private MockUtil mockUtil = new MockUtil(); @Mock private ArticleCalculator calculator; @Mock private ArticleDatabase database; @InjectMocks private ArticleManager articleManager; @Spy @InjectMocks private ArticleManager spiedArticleManager; @InjectMocks private ArticleVisitor should_be_initialized_several_times; @Test public void shouldNotFailWhenNotInitialized() { assertNotNull(articleManager); } @Test(expected = IllegalArgumentException.class) public void innerMockShouldRaiseAnExceptionThatChangesOuterMockBehavior() { when(calculator.countArticles("new")).thenThrow(new IllegalArgumentException()); articleManager.updateArticleCounters("new"); } @Test public void mockJustWorks() { articleManager.updateArticleCounters("new"); } @Test public void constructor_is_called_for_each_test() throws Exception { int minimum_number_of_test_before = 3; Assertions.assertThat(articleVisitorInstantiationCount).isGreaterThan(minimum_number_of_test_before); Assertions.assertThat(articleVisitorMockInjectedInstances.size()).isGreaterThan(minimum_number_of_test_before); } @Test public void objects_created_with_constructor_initialization_can_be_spied() throws Exception { assertFalse(mockUtil.isMock(articleManager)); assertTrue(mockUtil.isMock(spiedArticleManager)); } @Test public void should_report_failure_only_when_object_initialization_throws_exception() throws Exception { try { MockitoAnnotations.initMocks(new ATest()); fail(); } catch (MockitoException e) { Assertions.assertThat(e.getMessage()).contains("failingConstructor").contains("constructor").contains("threw an exception"); Assertions.assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); } } private static int articleVisitorInstantiationCount = 0; private static Set<Object> articleVisitorMockInjectedInstances = new HashSet<Object>(); private static class ArticleVisitor { public ArticleVisitor(ArticleCalculator calculator) { articleVisitorInstantiationCount++; articleVisitorMockInjectedInstances.add(calculator); } } private static class FailingConstructor { FailingConstructor(Set set) { throw new IllegalStateException("always fail"); } } @Ignore("don't run this code in the test runner") private static class ATest { @Mock Set set; @InjectMocks FailingConstructor failingConstructor; } }
CyanogenMod/android_external_mockito
test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java
Java
mit
3,568
<TS language="ca" version="2.0"> <context> <name>AboutDialog</name> <message> <source>About Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>&lt;b&gt;Pesetacoin Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <source>The Pesetacoin Core developers</source> <translation type="unfinished"/> </message> <message> <source>(%1-bit)</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Double-click to edit address or label</source> <translation>Doble click per editar l&apos;adreça o l&apos;etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una nova adrça</translation> </message> <message> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia la selecció actual al porta-retalls del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <source>&amp;Delete</source> <translation>&amp;Eliminar</translation> </message> <message> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <source>Very sending addresses</source> <translation type="unfinished"/> </message> <message> <source>Much receiving addresses</source> <translation type="unfinished"/> </message> <message> <source>These are your Pesetacoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <source>These are your Pesetacoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Fitxer separat per comes (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Adreça</translation> </message> <message> <source>(no label)</source> <translation>(sense etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <source>Enter passphrase</source> <translation>Introduïu la frase-contrasenya</translation> </message> <message> <source>New passphrase</source> <translation>Nova frase-contrasenya</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repetiu la nova frase-contrasenya</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduïu la nova frase-contrasenya per a la cartera.&lt;br/&gt;Empreu una frase-contrasenya de &lt;b&gt;10 o més caràcters aleatoris&lt;b/&gt;, o &lt;b&gt;vuit o més paraules&lt;b/&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Encriptar cartera</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Cal que introduïu la frase-contrasenya de la cartera per a desbloquejar-la.</translation> </message> <message> <source>Unlock wallet</source> <translation>Desbloquejar cartera</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Cal que introduïu la frase-contrasenya de la cartera per a desencriptar-la.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Desencriptar cartera</translation> </message> <message> <source>Change passphrase</source> <translation>Canviar frase-contrasenya</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introduïu l&apos;antiga i la nova frase-contrasenya per a la cartera.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Confirmeu l&apos;encriptació de cartera</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PESETACOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <source>Wallet encrypted</source> <translation>Cartera encriptada</translation> </message> <message> <source>Pesetacoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your pesetacoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <source>Wallet encryption failed</source> <translation>L&apos;encriptació de cartera ha fallat</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>L&apos;encriptació de cartera ha fallat degut a un error intern. La vostra cartera no ha estat encriptada.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Les frases-contrasenya no concorden.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>El desbloqueig de cartera ha fallat</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La frase-contrasenya per a la desencriptació de cartera és incorrecta.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>La desencriptació de cartera ha fallat</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronitzant amb la xarxa...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Visió general</translation> </message> <message> <source>Node</source> <translation type="unfinished"/> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar visió general de la cartera</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaccions</translation> </message> <message> <source>Browse transaction history</source> <translation>Exploreu l&apos;historial de transaccions</translation> </message> <message> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <source>Quit application</source> <translation>Sortir de l&apos;aplicació</translation> </message> <message> <source>Show information about Pesetacoin</source> <translation>Informació sobre Pesetacoin</translation> </message> <message> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opcions...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <source>Very &amp;sending addresses...</source> <translation type="unfinished"/> </message> <message> <source>Much &amp;receiving addresses...</source> <translation type="unfinished"/> </message> <message> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <source>Send coins to a Pesetacoin address</source> <translation type="unfinished"/> </message> <message> <source>Modify configuration options for Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Canviar frase-contrasenya per a l&apos;escriptació de la cartera</translation> </message> <message> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin</source> <translation type="unfinished"/> </message> <message> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <source>Sign messages with your Pesetacoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <source>Verify messages to ensure they were signed with specified Pesetacoin addresses</source> <translation type="unfinished"/> </message> <message> <source>&amp;File</source> <translation>&amp;Fitxer</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuració</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ajuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barra d&apos;eines</translation> </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <source>Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>Request payments (generates QR codes and pesetacoin: URIs)</source> <translation type="unfinished"/> </message> <message> <source>&amp;About Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Open a pesetacoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <source>Show the Pesetacoin Core help message to get a list with possible command-line options</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n active connection(s) to Pesetacoin network</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n year(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <source>Warning</source> <translation type="unfinished"/> </message> <message> <source>Information</source> <translation type="unfinished"/> </message> <message> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <source>Catching up...</source> <translation>Actualitzant...</translation> </message> <message> <source>Sent transaction</source> <translation>Transacció enviada</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacció entrant</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>La cartera està &lt;b&gt;encriptada&lt;b/&gt; i &lt;b&gt;desbloquejada&lt;b/&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>La cartera està &lt;b&gt;encriptada&lt;b/&gt; i &lt;b&gt;bloquejada&lt;b/&gt;</translation> </message> <message> <source>A fatal error occurred. Pesetacoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <source>List mode</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>Label</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Adreça</translation> </message> <message> <source>Date</source> <translation type="unfinished"/> </message> <message> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <source>Priority</source> <translation type="unfinished"/> </message> <message> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <source>highest</source> <translation type="unfinished"/> </message> <message> <source>higher</source> <translation type="unfinished"/> </message> <message> <source>high</source> <translation type="unfinished"/> </message> <message> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <source>medium</source> <translation type="unfinished"/> </message> <message> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <source>low</source> <translation type="unfinished"/> </message> <message> <source>lower</source> <translation type="unfinished"/> </message> <message> <source>lowest</source> <translation type="unfinished"/> </message> <message> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Dust</source> <translation type="unfinished"/> </message> <message> <source>yes</source> <translation type="unfinished"/> </message> <message> <source>no</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(sense etiqueta)</translation> </message> <message> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar adreça</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Address</source> <translation>&amp;Adreça</translation> </message> <message> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <source>The entered address &quot;%1&quot; is not a valid Pesetacoin address.</source> <translation type="unfinished"/> </message> <message> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <source>name</source> <translation type="unfinished"/> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Pesetacoin Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>version</source> <translation type="unfinished"/> </message> <message> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <source>UI options</source> <translation type="unfinished"/> </message> <message> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation type="unfinished"/> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <source>Welcome to Pesetacoin Core.</source> <translation type="unfinished"/> </message> <message> <source>As this is the first time the program is launched, you can choose where Pesetacoin Core will store its data.</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin Core will download and store a copy of the Pesetacoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin</source> <translation type="unfinished"/> </message> <message> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <source>URI:</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation type="unfinished"/> </message> <message> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <source>Automatically start Pesetacoin Core after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Start Pesetacoin Core on system login</source> <translation type="unfinished"/> </message> <message> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <source>MB</source> <translation type="unfinished"/> </message> <message> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <source>Connect to the Pesetacoin network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation type="unfinished"/> </message> <message> <source>W&amp;allet</source> <translation type="unfinished"/> </message> <message> <source>Expert</source> <translation type="unfinished"/> </message> <message> <source>Enable coin &amp;control features</source> <translation type="unfinished"/> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation type="unfinished"/> </message> <message> <source>Automatically open the Pesetacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Pesetacoin Core.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <source>Whether to show Pesetacoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <source>default</source> <translation type="unfinished"/> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation type="unfinished"/> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Pesetacoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <source>Available:</source> <translation type="unfinished"/> </message> <message> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <source>Pending:</source> <translation type="unfinished"/> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <source>Total:</source> <translation type="unfinished"/> </message> <message> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <source>URI can not be parsed! This can be caused by an invalid Pesetacoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <source>Cannot start pesetacoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <source>Pesetacoin</source> <translation type="unfinished"/> </message> <message> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source> <translation type="unfinished"/> </message> <message> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin Core did&apos;t yet exit safely...</source> <translation type="unfinished"/> </message> <message> <source>Enter a Pesetacoin address (e.g. LGfR55WPULK6S7eoeEGYW5CLSUFWWZiH5Q)</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation type="unfinished"/> </message> <message> <source>N/A</source> <translation type="unfinished"/> </message> <message> <source>Client version</source> <translation type="unfinished"/> </message> <message> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <source>General</source> <translation type="unfinished"/> </message> <message> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <source>Network</source> <translation type="unfinished"/> </message> <message> <source>Name</source> <translation type="unfinished"/> </message> <message> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <source>Totals</source> <translation type="unfinished"/> </message> <message> <source>In:</source> <translation type="unfinished"/> </message> <message> <source>Out:</source> <translation type="unfinished"/> </message> <message> <source>Build date</source> <translation type="unfinished"/> </message> <message> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <source>Open the Pesetacoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <source>Welcome to the Pesetacoin RPC console.</source> <translation type="unfinished"/> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Pesetacoin network.</source> <translation type="unfinished"/> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation type="unfinished"/> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear</source> <translation type="unfinished"/> </message> <message> <source>Requested payments history</source> <translation type="unfinished"/> </message> <message> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <source>Show</source> <translation type="unfinished"/> </message> <message> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <source>Remove</source> <translation type="unfinished"/> </message> <message> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <source>Copy message</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <source>URI</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Adreça</translation> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation type="unfinished"/> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(sense etiqueta)</translation> </message> <message> <source>(no message)</source> <translation type="unfinished"/> </message> <message> <source>(no amount)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <source>or</source> <translation type="unfinished"/> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <source>Warning: Invalid Pesetacoin address</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(sense etiqueta)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <source>The address to send the payment to (e.g. LGfR55WPULK6S7eoeEGYW5CLSUFWWZiH5Q)</source> <translation type="unfinished"/> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <source>Message:</source> <translation type="unfinished"/> </message> <message> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <source>A message that was attached to the pesetacoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Pesetacoin network.</source> <translation type="unfinished"/> </message> <message> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <source>Memo:</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Pesetacoin Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <source>The address to sign the message with (e.g. LGfR55WPULK6S7eoeEGYW5CLSUFWWZiH5Q)</source> <translation type="unfinished"/> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <source>Signature</source> <translation type="unfinished"/> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <source>Sign the message to prove you own this Pesetacoin address</source> <translation type="unfinished"/> </message> <message> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <source>The address the message was signed with (e.g. LGfR55WPULK6S7eoeEGYW5CLSUFWWZiH5Q)</source> <translation type="unfinished"/> </message> <message> <source>Verify the message to ensure it was signed with the specified Pesetacoin address</source> <translation type="unfinished"/> </message> <message> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <source>Enter a Pesetacoin address (e.g. LGfR55WPULK6S7eoeEGYW5CLSUFWWZiH5Q)</source> <translation type="unfinished"/> </message> <message> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <source>Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>The Pesetacoin Core developers</source> <translation type="unfinished"/> </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>Date</source> <translation type="unfinished"/> </message> <message> <source>Source</source> <translation type="unfinished"/> </message> <message> <source>Generated</source> <translation type="unfinished"/> </message> <message> <source>From</source> <translation type="unfinished"/> </message> <message> <source>To</source> <translation type="unfinished"/> </message> <message> <source>own address</source> <translation type="unfinished"/> </message> <message> <source>label</source> <translation type="unfinished"/> </message> <message> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <source>Debit</source> <translation type="unfinished"/> </message> <message> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <source>Message</source> <translation type="unfinished"/> </message> <message> <source>Comment</source> <translation type="unfinished"/> </message> <message> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>true</source> <translation type="unfinished"/> </message> <message> <source>false</source> <translation type="unfinished"/> </message> <message> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation type="unfinished"/> </message> <message> <source>Type</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>Adreça</translation> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform/><numerusform/></translation> </message> <message> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <source>Offline</source> <translation type="unfinished"/> </message> <message> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <source>Received with</source> <translation type="unfinished"/> </message> <message> <source>Received from</source> <translation type="unfinished"/> </message> <message> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <source>Mined</source> <translation type="unfinished"/> </message> <message> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation type="unfinished"/> </message> <message> <source>Today</source> <translation type="unfinished"/> </message> <message> <source>This week</source> <translation type="unfinished"/> </message> <message> <source>This month</source> <translation type="unfinished"/> </message> <message> <source>Last month</source> <translation type="unfinished"/> </message> <message> <source>This year</source> <translation type="unfinished"/> </message> <message> <source>Range...</source> <translation type="unfinished"/> </message> <message> <source>Received with</source> <translation type="unfinished"/> </message> <message> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <source>Mined</source> <translation type="unfinished"/> </message> <message> <source>Other</source> <translation type="unfinished"/> </message> <message> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Fitxer separat per comes (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <source>Date</source> <translation type="unfinished"/> </message> <message> <source>Type</source> <translation type="unfinished"/> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Adreça</translation> </message> <message> <source>Amount</source> <translation type="unfinished"/> </message> <message> <source>ID</source> <translation type="unfinished"/> </message> <message> <source>Range:</source> <translation type="unfinished"/> </message> <message> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <source>List commands</source> <translation type="unfinished"/> </message> <message> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <source>Options:</source> <translation type="unfinished"/> </message> <message> <source>Specify configuration file (default: pesetacoin.conf)</source> <translation type="unfinished"/> </message> <message> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin Core RPC client version</source> <translation type="unfinished"/> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Pesetacoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:15)</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %d)</source> <translation type="unfinished"/> </message> <message> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source> <translation type="unfinished"/> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation type="unfinished"/> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source> <translation type="unfinished"/> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <source>Unable to bind to %s on this computer. Pesetacoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Pesetacoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <source>(default: 1)</source> <translation type="unfinished"/> </message> <message> <source>(default: wallet.dat)</source> <translation type="unfinished"/> </message> <message> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <source>Pesetacoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source> <translation type="unfinished"/> </message> <message> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <source>Connection options:</source> <translation type="unfinished"/> </message> <message> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <source>Debugging/Testing options:</source> <translation type="unfinished"/> </message> <message> <source>Disable safemode, override a real safe mode event (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <source>Fees smaller than this are considered zero fee (for relaying) (default:</source> <translation type="unfinished"/> </message> <message> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <source>Force safe mode (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <source>Importing...</source> <translation type="unfinished"/> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Usage (deprecated, use pesetacoin-cli):</source> <translation type="unfinished"/> </message> <message> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <source>Cannot obtain a lock on data directory %s. Pesetacoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Information</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: 50000)</source> <translation type="unfinished"/> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <source>Print block on startup, if found in block index</source> <translation type="unfinished"/> </message> <message> <source>Print block tree on startup (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <source>RPC server options:</source> <translation type="unfinished"/> </message> <message> <source>Randomly drop 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Randomly fuzz 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Run a thread to flush wallet periodically (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <source>Send command to Pesetacoin Core</source> <translation type="unfinished"/> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation type="unfinished"/> </message> <message> <source>Show benchmark information (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <source>Start Pesetacoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>System error: </source> <translation type="unfinished"/> </message> <message> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Warning</source> <translation type="unfinished"/> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <source>Zapping all transactions from wallet...</source> <translation type="unfinished"/> </message> <message> <source>on startup</source> <translation type="unfinished"/> </message> <message> <source>version</source> <translation type="unfinished"/> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <source>This help message</source> <translation type="unfinished"/> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Pesetacoin</source> <translation type="unfinished"/> </message> <message> <source>Wallet needed to be rewritten: restart Pesetacoin to complete</source> <translation type="unfinished"/> </message> <message> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <source>Error</source> <translation type="unfinished"/> </message> <message> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
FundacionPesetacoin/Pesetacoin-0.9.1-Oficial
src/qt/locale/bitcoin_ca.ts
TypeScript
mit
111,007
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SyncDisabled = props => <SvgIcon {...props}> <path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z" /> </SvgIcon>; SyncDisabled = pure(SyncDisabled); SyncDisabled.muiName = 'SvgIcon'; export default SyncDisabled;
AndriusBil/material-ui
packages/material-ui-icons/src/SyncDisabled.js
JavaScript
mit
728
//Copyright (C) 2014 Tom Deseyn //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. //This library 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 //Lesser General Public License for more details. //You should have received a copy of the GNU Lesser General Public //License along with this library; if not, write to the Free Software //Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading; using System.Threading.Tasks; using NetworkInterfaceInformation = System.Net.NetworkInformation.NetworkInterface; namespace Tmds.Sdp { public class NetworkInterface { public string Name { get { return Information.Name; } } public string Description { get { return Information.Description; } } public string Id { get { return Information.Id; } } public int IPv4Index { get; private set; } public int IPv6Index { get; private set; } public override bool Equals(object obj) { NetworkInterface networkInterface = obj as NetworkInterface; if (networkInterface == null) { return false; } return Index.Equals(networkInterface.Index); } public override int GetHashCode() { return Index.GetHashCode(); } internal NetworkInterface(NetworkInterfaceInformation info) { Information = info; IPv4Index = -1; IPv6Index = -1; if (info.Supports(NetworkInterfaceComponent.IPv4)) { IPv4Index = info.GetIPProperties().GetIPv4Properties().Index; } if (info.Supports(NetworkInterfaceComponent.IPv6)) { IPv6Index = info.GetIPProperties().GetIPv6Properties().Index; } Index = Interlocked.Increment(ref NextIndex); } internal int Index { get; private set; } internal NetworkInterfaceInformation Information { get; private set; } static private int NextIndex = 1; } }
bbc/sdp-test
src/Tmds.Sdp/Tmds/Sdp/NetworkInterface.cs
C#
mit
2,546
// Generated by CoffeeScript 1.6.3 (function() { var Stl, stl_parser; stl_parser = require('../parser/stl_parser'); Stl = (function() { function Stl() {} return Stl; })(); Stl.PovRay = (function() { function PovRay() {} PovRay.prototype._povHeaders = function(name) { return "#declare " + name + " = mesh {\n"; }; PovRay.prototype._povFooters = function() { return "}"; }; PovRay.prototype.convertFile = function(filePath, callback, progressCb) { var output, _this = this; output = ""; return stl_parser.parseFile(filePath, function(err, polygons, name) { var unique_name; if (err != null) { callback(err); return; } unique_name = '__' + name + '__'; output += _this._povFooters(); return callback(null, output, unique_name); }, function(err, polygon, name) { var povPolygon, unique_name; unique_name = '__' + name + '__'; if (output.length === 0) { output += _this._povHeaders(unique_name); } povPolygon = _this.convertPolygon(polygon); output += povPolygon; if (progressCb != null) { return progressCb(err, povPolygon, unique_name); } }); }; PovRay.prototype.convertPolygon = function(polygon) { var idx, output, vertex, _i, _len, _ref; output = ""; output += " triangle {\n"; _ref = polygon.verticies; for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { vertex = _ref[idx]; output += " <" + vertex[0] + ", " + (-vertex[1]) + ", " + vertex[2] + ">"; if (idx !== (polygon.verticies.length - 1)) { output += ",\n"; } } output += " }\n"; return output; }; return PovRay; })(); module.exports = new Stl.PovRay(); }).call(this);
cubehero/stljs
lib/to/povray.js
JavaScript
mit
1,910
class UsersController < ApplicationController # before_action :set_user, only: [:guchi, :jiman, :inori, :index, :show, :edit, :update, :destroy] before_action :logged_in_user, only: [:guchi, :jiman, :inori, :index, :show, :edit, :update, :destroy] def list @msg = 'Users cont. list アクション' @user = User.find(params[:id]) end def guchi @msg = 'Users cont. guchi アクション' @user = User.find(params[:id]) @micropost = Micropost.new end def guchi_feedback @msg = 'Users cont. guchi_feedback アクション' end def jiman @msg = 'Users cont. jiman アクション' @user = User.find(params[:id]) @micropost = Micropost.new end def jiman_feedback @msg = 'Users cont. jiman_feedback アクション' end def inori @msg = 'Users cont. inori アクション' @user = User.find(params[:id]) @micropost = Micropost.new end def inori_feedback @msg = 'Users cont. inori_feedback アクション' end def index @msg = 'Users cont. index アクション' @user = User.find(params[:id]) end def show @msg = 'Users cont. show アクション' @user = User.find(params[:id]) @microposts = @user.microposts.find(params[:id]) end def edit @msg = 'Users cont. edit アクション' @user = User.find(params[:id]) end def new @msg = 'Users cont. new アクション' @user = User.new end def create @user = User.new(user_params) if @user.save log_in @user flash[:success] = "Welcome to the SressShedder App!" redirect_to @user # Handle a successful save. else render 'new' end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) @micropost = Micropost.find(params[:id]) end def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end # beforeフィルター # 正しいユーザーかどうかを確認 def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end end
chubachi-pt-2017/StressShredder
app/controllers/users_controller.rb
Ruby
mit
2,255
ace.define("ace/snippets/apache_conf",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "apache_conf"; }); (function() { ace.require(["ace/snippets/apache_conf"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
NPellet/jsGraph
web/site/js/ace-builds/src-noconflict/snippets/apache_conf.js
JavaScript
mit
519
// @flow var React = require('react') var {assign} = require('lodash') import {Source, emptySource} from './model/source' import {displayIf, Colors} from './style' // but get the images at 2x resolution so they can be retina yo // or just get the photos at that ratio // 200x320 x2 // 150x240 // 100x160 // Blank Image - http://i.imgur.com/bMwt85W.jpg type Size = { Width: number; Height: number; } export var CoverSize = { Width: 150, Height: 240, Ratio: 1.6 } export var CoverThumb = { Width: 50, Height: 80, } export function coverStyle(url:string, size:Size = CoverSize):Object { // otherwise it forgets about the cover. Wait until the image is ready if (!url) { return {} } return { background: 'url('+url+') no-repeat center center', backgroundSize: 'cover', width: size.Width, height: size.Height } } export class CoverOverlay extends React.Component { render():React.Element { var style = assign( displayIf(this.props.show !== false), OverlayStyle, CoverTextStyle, this.props.style ) return <div style={style}> {this.props.children} </div> } } export class Cover extends React.Component { props: { src: string; size?: Size; children: Array<React.Element>; }; render():React.Element { var size = this.props.size || CoverSize return <div style={assign(coverStyle(this.props.src, size), {position: 'relative'})}> {this.props.children} </div> } } export class SourceCover extends React.Component { render():React.Element { var source:Source = this.props.source || emptySource() var showTitle:bool = source.imageMissingTitle return <Cover src={source.imageUrl}> <CoverOverlay show={showTitle}>{source.name}</CoverOverlay> </Cover> } } // I could specify it in terms of percentages instead? // that's a good idea. // so do I want 2 or 3 across? // definitely 3 :) export var OverlayStyle = { padding: 10, color: Colors.light, textAlign: 'center', position: 'absolute', bottom: 0, fontSize: 18, backgroundColor: 'rgba(0, 0, 0, 0.5)', width: CoverSize.Width } export var CoverTextStyle = { fontSize: 18, }
seanhess/serials
web/app/cover.js
JavaScript
mit
2,205
define([ 'jquery', 'underscore', 'backbone', 'views/AdminView', 'authentication', 'models/Beach' ], function ( $, _, Backbone, AdminView, Authentication, BeachModel) { var AdminRouter = Backbone.Router.extend({ routes: { 'admin' : 'index' }, index: function () { Authentication.authorize(function () { $('#content').html("<p style='display: block; font-size: 15%; text-align: center; line-height: 100vh; margin: 0;'>LOADING</p>"); beaches = new BeachModel.Collection(); beaches.fetch( { success: function( collection, response, options) { var adminView = new AdminView({ collection: collection }); $('#content').html(adminView.el); }, failure: function( collection, response, options) { $('#content').html("An error has occured."); } }); }, true); }, }); return AdminRouter; });
alex-driedger/Nurdles
clients/web/js/routers/AdminRouter.js
JavaScript
mit
1,209
from datetime import datetime, timedelta from time import sleep from random import uniform class SleepSchedule(object): """Pauses the execution of the bot every day for some time Simulates the user going to sleep every day for some time, the sleep time and the duration is changed every day by a random offset defined in the config file Example Config: "sleep_schedule": [ { "time": "12:00", "duration": "5:30", "time_random_offset": "00:30", "duration_random_offset": "00:30", "wake_up_at_location": "" }, { "time": "17:45", "duration": "3:00", "time_random_offset": "01:00", "duration_random_offset": "00:30", "wake_up_at_location": "" } ] time: (HH:MM) local time that the bot should sleep duration: (HH:MM) the duration of sleep time_random_offset: (HH:MM) random offset of time that the sleep will start for this example the possible start time is 11:30-12:30 duration_random_offset: (HH:MM) random offset of duration of sleep for this example the possible duration is 5:00-6:00 wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up *Note that an empty string ("") will not change the location*. """ LOG_INTERVAL_SECONDS = 600 SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now def __init__(self, bot, config): self.bot = bot self._process_config(config) self._schedule_next_sleep() self._calculate_current_sleep() def work(self): if self._should_sleep_now(): self._sleep() wake_up_at_location = self._wake_up_at_location self._schedule_next_sleep() if wake_up_at_location: if hasattr(self.bot, 'api'): # Check if api is already initialized self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2]) else: self.bot.wake_location = wake_up_at_location if hasattr(self.bot, 'api'): self.bot.login() # Same here def _process_config(self, config): self.entries = [] for entry in config: prepared = {} prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M') # Using datetime for easier stripping of timedeltas raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M') duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds()) raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M') time_random_offset = int( timedelta( hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds()) raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M') duration_random_offset = int( timedelta( hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds()) raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else '' if raw_wake_up_at_location: try: wake_up_at_location = raw_wake_up_at_location.split(',',2) lat=float(wake_up_at_location[0]) lng=float(wake_up_at_location[1]) if len(wake_up_at_location) == 3: alt=float(wake_up_at_location[2]) else: alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max) except ValueError: raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it... prepared['wake_up_at_location'] = [lat, lng, alt] prepared['duration'] = duration prepared['time_random_offset'] = time_random_offset prepared['duration_random_offset'] = duration_random_offset self.entries.append(prepared) def _schedule_next_sleep(self): self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule() self.bot.event_manager.emit( 'next_sleep', sender=self, formatted="Next sleep at {time}", data={ 'time': str(self._next_sleep) } ) def _calculate_current_sleep(self): self._current_sleep = self._next_sleep - timedelta(days=1) current_duration = self._next_duration self._current_end = self._current_sleep + timedelta(seconds = current_duration) def _should_sleep_now(self): if datetime.now() >= self._next_sleep: return True if datetime.now() >= self._current_sleep and datetime.now() < self._current_end: self._next_duration = (self._current_end - datetime.now()).total_seconds() return True return False def _get_next_sleep_schedule(self): now = datetime.now() + self.SCHEDULING_MARGIN times = [] for index in range(len(self.entries)): next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute) next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset'])) # If sleep time is passed add one day if next_time <= now: next_time += timedelta(days=1) times.append(next_time) diffs = {} for index in range(len(self.entries)): diff = (times[index]-now).total_seconds() if diff >= 0: diffs[index] = diff closest = min(diffs.iterkeys(), key=lambda x: diffs[x]) next_time = times[closest] next_duration = self._get_next_duration(self.entries[closest]) location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else '' return next_time, next_duration, location def _get_next_duration(self, entry): duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset']) return duration def _get_random_offset(self, max_offset): offset = uniform(-max_offset, max_offset) return int(offset) def _sleep(self): sleep_to_go = self._next_duration sleep_m, sleep_s = divmod(sleep_to_go, 60) sleep_h, sleep_m = divmod(sleep_m, 60) sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s) now = datetime.now() wake = str(now + timedelta(seconds=sleep_to_go)) self.bot.event_manager.emit( 'bot_sleep', sender=self, formatted="Sleeping for {time_hms}, wake at {wake}", data={ 'time_hms': sleep_hms, 'wake': wake } ) while sleep_to_go > 0: if sleep_to_go < self.LOG_INTERVAL_SECONDS: sleep(sleep_to_go) sleep_to_go = 0 else: sleep(self.LOG_INTERVAL_SECONDS) sleep_to_go -= self.LOG_INTERVAL_SECONDS
bbiiggppiigg/PokemonGo-Bot
pokemongo_bot/sleep_schedule.py
Python
mit
7,614
<style type="text/css"> </style> <div id="footer-large"> <div id="footer" role="contentinfo clearfix" class="non-burger-footer" style="position: relative;"> <div class="content-asset"> <footer id="siteFooter" class="y-shop footerOverlay"> <?php include('contact-bottom.php'); ?> <div class="footerStickyElms bottomSticky"> <div class="signup-10"> <div class=""> <div> <div class="signup10-inn"> <div> <div> <div id="footer-scroll-4" class="footer-scroll"> <div id="footer-tab_4" class="container-fluid site-footer-tab sticky-dcode"> <div class="row"> <div class="col-xs-12"> <div class="row"> <div class="col-xs-12 "> <a class="close close_signup_popup" data-target="4">X</a> <span class="content-head content-head-open">SIGN-UP for exclusive promotions & news + GET 10% off on your order</span> </div> </div> <div class="row signup_close_popup"> <div class="col-lg-offset-1 "> <form id="frmDCode1" name="frmDCode1" class="d-code1"> <div class="col-lg-4 col-md-4 dcode-email1"> <div class="dcode-wrapper"> <input id="dCodeEmail1" required name="email" placeholder="Your email address" type="email"/> <div class="dcode-message1"></div> </div> <div class="example"> <input type="radio" class="radio" name="gender" id="ex1_b" value="Male" checked="checked" /> <label for="ex1_b">MENS</label> <input type="radio" class="radio" name="gender" id="ex1_a" value="Female"> <label for="ex1_a" style="margin-right:0;">WOMENS</label> </div> </div> <div class="col-lg-2 col-md-3"> <input id="submit" type="button" value="Sign-Up" class="btn-d-code1" alt="Subscribe" /> </div> <!-- <div class="col-lg-1 col-md-2 footer-more"> <a href="<?=base_url();?>info/myaccount_and_newsletter" class="more"> <span class="learn-more-text">READ MORE</span> </a> </div> --> </form> </div> </div> <p>&nbsp;</p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footerTabContainer" style="border-top:1px solid #e6e6e6 !important"> <div class="tabFooter" data-footer="tabInfoShopping"> <div class="wrapperElementTab wrapperElementTabcustomer"> <div class="titleTabFooter closeSecondLevelMenu titleTabFootercustomer" data-target="1" id="customer_care" > <span class="icon icon-arrow-big-mainTab"></span> Customer Care </div> <ul class="tabFooterContent customerFooterContent no-mobile" > <li class="footerColumn ccareAccordionElement"> <div class="columnTitle accordion"> Shipping &amp; Returns <span class="icon icon-arrow-little-secondTab"></span> </div> <ul> <li> <a href="<?=base_url();?>member/login_popup" class="user-footer-login"> My Order </a> </li> <li> <a href="<?=base_url();?>info/shipping_info"> Shipping </a> </li> <li> <a href="<?=base_url();?>info/returns"> Returns </a> </li> </ul> </li> <li class="footerColumn ccareAccordionElement"> <div class="columnTitle accordion"> Customer Care <span class="icon icon-arrow-little-secondTab"></span> </div> <ul> <li> <a href="<?=base_url();?>info/shoppingsite"> Shopping </a> </li> <li> <a href="<?=base_url();?>info/payment"> Payment </a> </li> <li> <a href="<?=base_url();?>info/contact_us"> Contact Us </a> </li> </ul> </li> <li class="footerColumn ccareAccordionElement"> <div class="columnTitle accordion"> Legal Area <span class="icon icon-arrow-little-secondTab"></span> </div> <ul> <li> <a class="" href="#">Terms and conditions of Sale</a> </li> <li> <a class="" href="<?=base_url();?>info/policy">Privacy Policy</a> </li> <li> <a class="" href="<?=base_url();?>info/termsandconditions">Terms and Conditions for Order</a> </li> </ul> </li> <span class="icon icon-close close_icon_footer"></span> </ul> </div> </div> <div class="tabFooter" data-footer="tabWorldDiesel"> <div class="wrapperElementTab"> <div class="titleTabFooter closeSecondLevelMenu" id="worlddiesel"> <span class="icon icon-arrow-big-mainTab"></span> <a href="http://www.diesel.com/store-locator"> Store Locator</a> </div> <!--<ul class="tabFooterContent worldFooterContent"> <li > <div class="columnTitle"> <a href="<?=base_url();?>magazine/dieselworld"> </a> </div> </li> <span class="icon icon-close close_icon_footer"></span> <li class="footerColumn "> <ul> <li> <a href="<?=base_url();?>info/diesel"> About Diesel </a> </li> </ul> </li> <li class="footerColumn"> <ul> <li> <a href="#" target="_blank"> Diesel is part of OTB </a> </li> </ul> </li> </ul>--> </div> </div> <div class="tabFooter" data-footer="tabSocial"> <div class="wrapperElementTab"> <div class="titleTabFooter" id="followUs"> <span class="icon icon-arrow-big-mainTab closeSecondLevelMenu"></span> <span class="socialElement"> Follow us </span> </div> <ul class="tabFooterContent followFooterContent"> <li class="footerColumn"> <div class="columnTitle"> Connect with Diesel <span class="subtitle"> Like us and we will love you </span> </div> <ul class="followUs " > <a href="https://www.facebook.com/Diesel" target="_blank"> <li title="Facebook " class="facebook"> <span class="icon"></span> <span class="text">Facebook</span> </li> </a> <a href="https://twitter.com/diesel" target="_blank"> <li data-ytos-mdl="{&quot;socialType&quot;: &quot;twitter&quot;}" class="twitter" title="Twitter"> <span class="icon"></span> <span class="text">Twitter</span> </li> </a> <a href="https://plus.google.com/+Diesel/posts" class="google" target="_blank"> <li data-ytos-mdl="{&quot;socialType&quot;: &quot;googleplus&quot;}" class="googleplus" title="GooglePlus"> <span class="icon"></span> <span class="text">Google Plus</span> </li> </a> <a href="http://instagram.com/diesel" target="_blank"> <li data-ytos-mdl="{&quot;socialType&quot;: &quot;instagram&quot;}" class="instagram" title="Instagram"> <span class="icon"></span> <span class="text">Instagram</span> </li> </a> <!--<li data-ytos-mdl="{&quot;socialType&quot;: &quot;youtube&quot;}" class="youtube" title="Youtube"> <a href="http://www.youtube.com/user/DieselPlanet" target="_blank"> <span class="icon"></span> <span class="text">YouTube</span> </a> </li> <li data-ytos-mdl="{&quot;socialType&quot;: &quot;pinterest&quot;}" class="pinterest" title="Pinterest"> <a href="http://www.pinterest.com/diesel/" target="_blank"> <span class="icon"></span> <span class="text">Pinterest</span> </a> </li> <li data-ytos-mdl="{&quot;socialType&quot;: &quot;tumblr&quot;}" class="tumblr" title="Tumblr"> <a href="http://dieselreboot.tumblr.com/" class="tumbler" target="_blank"> <span class="icon"></span> <span class="text">Tumblr</span> </a> </li>--> </ul> </li> <li><span class="icon icon-close close_icon_footer"></span></li> </ul> </div> </div> <div class="tabFooter" data-footer="tabSubscribe"> <div class="titleTabFooter"> <span class="icon icon-arrow-big-mainTab closeSecondLevelMenu"></span> <a id="fancy_subscribe" href="javascript:void(0);" class="newsletterLink"><span class="icon"></span> <span class="text">Newsletter</span> <span class="value"></span> </a> </div> <div class="tabFooterContent"> <span class="icon icon-close"></span> </div> </div> </div> </div> <div id="copyright"> Mandana Holdings Pty Ltd, 30 Tullamarine Park Road, Tullamarine VIC Australia 3043. </div> </footer> </div> <!-- End content-asset --> </div> <?php if($view_file_name == 'cart_view') { ?> </div> <?php } ?> <!-- fancybox script starts --> <!--<script type="text/javascript" src="<?=base_url();?>fancybox/lib/jquery-1.10.1.min.js"></script>--> <script type="text/javascript" src="<?=base_url();?>fancybox/jquery.fancybox.js?v=2.1.5"></script> <link rel="stylesheet" type="text/css" href="<?=base_url();?>fancybox/jquery.fancybox.css?v=2.1.5" media="screen" /> <!--<script type="text/javascript" src="<?=base_url();?>fancybox/jquery.cookie.js"></script>--> <script type="text/javascript"> $(document).ready(function() { $('.fancybox').fancybox({ 'padding': 0, 'closeBtn': true }); $('#fancy_subscribe').click(function() { $('.titleTabFooter').removeClass("stickyOpen"); $(".tabFooterContent").removeClass("contentStickyOpen"); var viewportWidth = $(window).width(); if (viewportWidth > 767) { $(".tabFooterContent").hide(); } $('a#fancy_subscribe').attr("href", "<?=base_url();?>newsletter/signup"); $('a#fancy_subscribe').attr("class", "fancybox fancybox.iframe"); }); }); </script> <!-- fancybox script ends --> <script src="<?=base_url();?>js/new_footer.js" type="text/javascript"></script> <!-- Can Not Remove --> <script src="<?=base_url()?>js/custom.js" type="text/javascript"></script> <script src="<?=base_url()?>js/isotope.min.js" type="text/javascript"></script> <!-- Used in Magazine page for tile design --> <script src="<?=base_url()?>js/packery-mode.pkgd.js" type="text/javascript"></script> <script src="<?=base_url()?>js/imagesloaded.pkgd.min.js" type="text/javascript"></script> <script src="<?=base_url()?>js/persist-all-min.js" type="text/javascript"></script> <!-- used in Men's/Women's landing page menu dropdown and for footer loading --> <script src="<?=base_url()?>js/diesel.plugins.min.js" type="text/javascript"></script><!-- used in footer loading --> <script src="<?=base_url()?>js/carousel.min.js" type="text/javascript"></script> <!-- used in home page carousel --> <script src="<?=base_url()?>js/hammer.min.js" type="text/javascript"></script> <!-- Used for mobile friendly smooth touching--> <script src="<?=base_url()?>js/jquery.bxslider.js" type="text/javascript"></script> <!-- used in product detail slider --> <!-- <script src="<?=base_url()?>js/jquery.mousewheel.js" type="text/javascript"></script> --> <script src="<?=base_url()?>js/jquery.jscrollpane.min.js" type="text/javascript"></script> <!-- used in product detail slider --> <script src="<?=base_url()?>js/jquery.stellar.min.js" type="text/javascript"></script> <!-- for parallax backgrounds --> <script src="<?=base_url()?>js/backgroundVideo.min.js" type="text/javascript"></script> <!-- used in background video for homepage --> <script src="<?=base_url()?>js/jquery.tooltipster.js" type="text/javascript"></script> <!-- used for mouse hover tooltip --> <script src="<?=base_url()?>js/jquery.inViewport.js" type="text/javascript"></script> <!-- jQuery plugin that adds a CSS class to selected elements when they have been scrolled into the viewport for the first time. --> <script src="<?=base_url()?>js/scoped.js" type="text/javascript"></script><!-- Used in Magazine page for tile design --> <!--<script src="<?=base_url()?>js/utag.js" type="text/javascript"></script>--><!-- Used for mini cart product scroller --> <!--<script type="text/javascript" src="<?=base_url();?>js/igdrta.js"></script>--> <script src="<?=base_url();?>js/responsive.js"></script> <script type="text/javascript"> (function(app) { app.isMobileUserAgent = false; app.zoomViewerEnabled = true; app.carouselDelay = 7000; app.bonusProductsCount = 0 app.constants = { "AVAIL_STATUS_IN_STOCK": "IN_STOCK", "AVAIL_STATUS_PREORDER": "PREORDER", "AVAIL_STATUS_BACKORDER": "BACKORDER", "AVAIL_STATUS_NOT_AVAILABLE": "NOT_AVAILABLE", "PI_METHOD_GIFT_CERTIFICATE": "GIFT_CERTIFICATE" }; app.resources = { "SHIP_QualifiesFor": "This shipment qualifies for", "CC_LOAD_ERROR": "Couldn't load credit card!", "REG_ADDR_ERROR": "Couldn't Load Address", "BONUS_PRODUCT": "Bonus Product", "BONUS_PRODUCTS": "Bonus Product(s)", "SELECT_BONUS_PRODUCTS": "Select {0} Bonus Product(s)", "SELECT_BONUS_PRODUCT": "Select", "BONUS_PRODUCT_MAX": "The maximum number of bonus products have been selected. Please remove one in order to add additional bonus products.", "SIMPLE_SEARCH": "What are you looking for?", "SUBSCRIBE_EMAIL_DEFAULT": "Email Address", "CURRENCY_SYMBOL": "$", "MISSINGVAL": "Please Enter {0}", "SERVER_ERROR": "Server connection failed!", "MISSING_LIB": "jQuery is undefined.", "BAD_RESPONSE": "Bad response, Parser error", "INVALID_PHONE": "Please specify a valid phone number.", "INVALID_EMAIL": "Please enter a valid email address.", "INVALID_ZIPCODE": "Please enter a valid Zip Code", "INVALID_DOB": "Please enter valid date of birth", "REMOVE": "REMOVE", "QTY": "Quantity", "EMPTY_IMG_ALT": "REMOVE", "COMPARE_BUTTON_LABEL": "Compare Items", "COMPARE_CONFIRMATION": "This will remove the first product added to compare. Is that OK?", "COMPARE_REMOVE_FAIL": "Unable to remove item from list", "COMPARE_ADD_FAIL": "Unable to add item to list", "ADD_TO_CART_FAIL": "Unable to add item '{0}' to cart", "REGISTRY_SEARCH_ADVANCED_CLOSE": "Close Advanced Search", "GIFT_CERT_INVALID": "Invalid Gift Certificate Code", "GIFT_CERT_BALANCE": "Your current gift certificate balance is ", "GIFT_CERT_AMOUNT_INVALID": "Gift Certificate can only be purchased with a minimum of $5 and maximum of $5000", "GIFT_CERT_MISSING": "Please enter a gift certificate code.", "COUPON_CODE_MISSING": "Please Enter a Coupon Code", "COOKIES_DISABLED": "Your browser currently is not set to accept Cookies. Please turn it on or check if you have another program set to block cookies.", "BML_AGREE_TO_TERMS": "You must agree to the terms and conditions", "CHAR_LIMIT_MSG": "You have {0} characters left out of {1}", "CONFIRM_DELETE": "Are you sure you want to remove this {0}?", "TITLE_GIFTREGISTRY": "gift registry", "TITLE_ADDRESS": "address", "TITLE_CREDITCARD": "credit card", "SERVER_CONNECTION_ERROR": "Server connection failed!", "IN_STOCK_DATE": "The expected in-stock date is {0}.", "INIFINITESCROLL": "Show All", "HazmatPOBoxWarning": "Your order cannot be shipped to Alaska, Hawaii, US Territories, P.O. Boxes or APO/FPO addresses as it contains hazardous materials. Please change the shipping address to continue. If you need additional assistance please contact customer service by calling 877.344.8342 between the hours of 8:00 a.m. ET to 12:00 a.m. ET, 7-days per week, other than from 5:00 p.m. on December 24 to 8:00 a.m. on December 26. ", "SUBSCRIPTION_SUCCESS": "Newsletter successfully subscribed", "SUBSCRIPTION_FAILED": "Subscription unsuccessful", "IN_STOCK": "In Stock", "QTY_IN_STOCK": "{0} Item(s) In Stock", "PREORDER": "Pre-Order", "QTY_PREORDER": "{0} item(s) are available for pre-order.", "REMAIN_PREORDER": "The remaining items are available for pre-order.", "BACKORDER": "Back Order", "QTY_BACKORDER": "Back Order {0} item(s)", "REMAIN_BACKORDER": "The remaining items are available on back order.", "NOT_AVAILABLE": "Out of stock ", "REMAIN_NOT_AVAILABLE": "The remaining items are currently not available. Please adjust the quantity." }; app.urls = { "newsletterSubscription": "/on/demandware.store/Sites-DieselUS-Site/default/Account-SubscriptionForm" }; app.newUrls = { }; app.clientcache = { "LISTING_INFINITE_SCROLL": true, "LISTING_REFINE_SORT": true }; app.newsletterSignUp = true app.enableShipToStore = true; }(window.app = window.app || {})); </script> <script type="text/javascript" src="<?php echo base_url();?>js/addthis_widget.js#pubid=addthis"></script> <!-- Can Not Remove --> <script src="<?php echo base_url();?>js/app.js" type="text/javascript"></script> <!-- Can Not Remove --> <script src="<?php echo base_url();?>js/common.js" type="text/javascript"></script> <!-- Can Not Remove --> <!-- Can Not Remove --> <script src="<?php echo base_url();?>js/diesel.app.js" type="text/javascript"></script> <!-- Can Not Remove --> <script type="text/javascript"> $('.image_not_available').bxSlider({ mode: 'horizontal', preventDefaultSwipeY: false, }); $('#frmDCode1 #submit').on('click',function(){ var email_id = $('#frmDCode1 #dCodeEmail1').val(); var url = "<?=base_url('newsletter/footer_newsletter_signup');?>"; if(email_id != ''){ $.ajax({ url : url, async : false, cache : false, type :'post', data:{email:email_id}, success:function(result){ $('.dcode-message1').html(result); }, error:function(){} }); } else { $('#frmDCode1 #dCodeEmail1').addClass('error invalidinput'); } return false; }); </script> <?php if($view_file_name == 'register_view') { ?> <script> app.page.setContext({ "title": "My Account", "type": "MyAccount", "ns": "account" }); </script> <?php } elseif($view_file_name == 'cart_view') { ?> <script> app.page.setContext({ "title": "Cart", "type": "Cart", "ns": "cart" }); </script> <?php } else { ?> <script>// if removed product detail size drop dwn stops. app.page.setContext({ "title": "", "type": "product", "ns": "product" }); </script> <?php } ?> <?php if($view_file_name != 'cart_view') { ?> </div> <?php } ?> <!-- Google Code for Remarketing Tag --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 882205304; var google_custom_params = window.google_tag_params; var google_remarketing_only = true; /* ]]> */ </script> <!--<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script>--> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/882205304/?value=0&amp;guid=ON&amp;script=0"/> </div> </noscript> <?php if(ENVIRONMENT == 'production' && $view_file_name == 'success') { ?> <!-- Google Code for Website Conversion Conversion Page --> <script type="text/javascript"> / <![CDATA[ / var google_conversion_id = 882205304; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "YN_HCKOZ1GgQ-MTVpAM"; var google_remarketing_only = false; / ]]> / </script> <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/882205304/?label=YN_HCKOZ1GgQ-MTVpAM&amp;guid=ON&amp;script=0"/> </div> </noscript> <?php } ?> </body> </html>
sygcom/diesel_2016
application/views/includes/footer_2016_09_29.php
PHP
mit
28,077
const labels = { collectionFilterLabels: { edit: { name: 'Event name', event_type: 'Type of event', address_country: 'Country', uk_region: 'UK Region', organiser: 'Organiser', start_date_after: 'From', start_date_before: 'To', }, }, } module.exports = labels
uktrade/data-hub-fe-beta2
src/apps/events/labels.js
JavaScript
mit
314
/****************************************************************************** * $Id: gdaldrivermanager.cpp 27121 2014-04-03 22:08:55Z rouault $ * * Project: GDAL Core * Purpose: Implementation of GDALDriverManager class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1998, Frank Warmerdam * Copyright (c) 2009-2013, Even Rouault <even dot rouault at mines-paris dot org> * * 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 "gdal_priv.h" #include "cpl_string.h" #include "cpl_multiproc.h" #include "ogr_srs_api.h" #include "cpl_multiproc.h" #include "gdal_pam.h" #include "gdal_alg_priv.h" #ifdef _MSC_VER # ifdef MSVC_USE_VLD # include <wchar.h> # include <vld.h> # endif #endif CPL_CVSID("$Id: gdaldrivermanager.cpp 27121 2014-04-03 22:08:55Z rouault $"); static const char *pszUpdatableINST_DATA = "__INST_DATA_TARGET: "; /************************************************************************/ /* ==================================================================== */ /* GDALDriverManager */ /* ==================================================================== */ /************************************************************************/ static volatile GDALDriverManager *poDM = NULL; static void *hDMMutex = NULL; void** GDALGetphDMMutex() { return &hDMMutex; } /************************************************************************/ /* GetGDALDriverManager() */ /* */ /* A freestanding function to get the only instance of the */ /* GDALDriverManager. */ /************************************************************************/ /** * \brief Fetch the global GDAL driver manager. * * This function fetches the pointer to the singleton global driver manager. * If the driver manager doesn't exist it is automatically created. * * @return pointer to the global driver manager. This should not be able * to fail. */ GDALDriverManager * GetGDALDriverManager() { if( poDM == NULL ) { CPLMutexHolderD( &hDMMutex ); if( poDM == NULL ) poDM = new GDALDriverManager(); } CPLAssert( NULL != poDM ); return const_cast<GDALDriverManager *>( poDM ); } /************************************************************************/ /* GDALDriverManager() */ /************************************************************************/ GDALDriverManager::GDALDriverManager() { nDrivers = 0; papoDrivers = NULL; pszHome = CPLStrdup(""); CPLAssert( poDM == NULL ); /* -------------------------------------------------------------------- */ /* We want to push a location to search for data files */ /* supporting GDAL/OGR such as EPSG csv files, S-57 definition */ /* files, and so forth. The static pszUpdateableINST_DATA */ /* string can be updated within the shared library or */ /* executable during an install to point installed data */ /* directory. If it isn't burned in here then we use the */ /* INST_DATA macro (setup at configure time) if */ /* available. Otherwise we don't push anything and we hope */ /* other mechanisms such as environment variables will have */ /* been employed. */ /* -------------------------------------------------------------------- */ if( CPLGetConfigOption( "GDAL_DATA", NULL ) != NULL ) { // this one is picked up automatically by finder initialization. } else if( pszUpdatableINST_DATA[19] != ' ' ) { CPLPushFinderLocation( pszUpdatableINST_DATA + 19 ); } else { #ifdef INST_DATA CPLPushFinderLocation( INST_DATA ); #endif } } /************************************************************************/ /* ~GDALDriverManager() */ /************************************************************************/ void GDALDatasetPoolPreventDestroy(); /* keep that in sync with gdalproxypool.cpp */ void GDALDatasetPoolForceDestroy(); /* keep that in sync with gdalproxypool.cpp */ GDALDriverManager::~GDALDriverManager() { /* -------------------------------------------------------------------- */ /* Cleanup any open datasets. */ /* -------------------------------------------------------------------- */ int i, nDSCount; GDALDataset **papoDSList; /* First begin by requesting each reamining dataset to drop any reference */ /* to other datasets */ int bHasDroppedRef; /* We have to prevent the destroying of the dataset pool during this first */ /* phase, otherwise it cause crashes with a VRT B referencing a VRT A, and if */ /* CloseDependentDatasets() is called first on VRT A. */ /* If we didn't do this nasty trick, due to the refCountOfDisableRefCount */ /* mechanism that cheats the real refcount of the dataset pool, we might */ /* destroy the dataset pool too early, leading the VRT A to */ /* destroy itself indirectly ... Ok, I am aware this explanation does */ /* not make any sense unless you try it under a debugger ... */ /* When people just manipulate "top-level" dataset handles, we luckily */ /* don't need this horrible hack, but GetOpenDatasets() expose "low-level" */ /* datasets, which defeat some "design" of the proxy pool */ GDALDatasetPoolPreventDestroy(); do { papoDSList = GDALDataset::GetOpenDatasets(&nDSCount); /* If a dataset has dropped a reference, the list might have become */ /* invalid, so go out of the loop and try again with the new valid */ /* list */ bHasDroppedRef = FALSE; for(i=0;i<nDSCount && !bHasDroppedRef;i++) { //CPLDebug("GDAL", "Call CloseDependentDatasets() on %s", // papoDSList[i]->GetDescription() ); bHasDroppedRef = papoDSList[i]->CloseDependentDatasets(); } } while(bHasDroppedRef); /* Now let's destroy the dataset pool. Nobody shoud use it afterwards */ /* if people have well released their dependent datasets above */ GDALDatasetPoolForceDestroy(); /* Now close the stand-alone datasets */ papoDSList = GDALDataset::GetOpenDatasets(&nDSCount); for(i=0;i<nDSCount;i++) { CPLDebug( "GDAL", "force close of %s (%p) in GDALDriverManager cleanup.", papoDSList[i]->GetDescription(), papoDSList[i] ); /* Destroy with delete operator rather than GDALClose() to force deletion of */ /* datasets with multiple reference count */ /* We could also iterate while GetOpenDatasets() returns a non NULL list */ delete papoDSList[i]; } /* -------------------------------------------------------------------- */ /* Destroy the existing drivers. */ /* -------------------------------------------------------------------- */ while( GetDriverCount() > 0 ) { GDALDriver *poDriver = GetDriver(0); DeregisterDriver(poDriver); delete poDriver; } delete GDALGetAPIPROXYDriver(); /* -------------------------------------------------------------------- */ /* Cleanup local memory. */ /* -------------------------------------------------------------------- */ VSIFree( papoDrivers ); VSIFree( pszHome ); /* -------------------------------------------------------------------- */ /* Cleanup any Proxy related memory. */ /* -------------------------------------------------------------------- */ PamCleanProxyDB(); /* -------------------------------------------------------------------- */ /* Blow away all the finder hints paths. We really shouldn't */ /* be doing all of them, but it is currently hard to keep track */ /* of those that actually belong to us. */ /* -------------------------------------------------------------------- */ CPLFinderClean(); CPLFreeConfig(); CPLCleanupSharedFileMutex(); /* -------------------------------------------------------------------- */ /* Cleanup any memory allocated by the OGRSpatialReference */ /* related subsystem. */ /* -------------------------------------------------------------------- */ OSRCleanup(); /* -------------------------------------------------------------------- */ /* Cleanup VSIFileManager. */ /* -------------------------------------------------------------------- */ VSICleanupFileManager(); /* -------------------------------------------------------------------- */ /* Cleanup thread local storage ... I hope the program is all */ /* done with GDAL/OGR! */ /* -------------------------------------------------------------------- */ CPLCleanupTLS(); /* -------------------------------------------------------------------- */ /* Cleanup our mutex. */ /* -------------------------------------------------------------------- */ if( hDMMutex ) { CPLDestroyMutex( hDMMutex ); hDMMutex = NULL; } /* -------------------------------------------------------------------- */ /* Cleanup dataset list mutex */ /* -------------------------------------------------------------------- */ if ( *GDALGetphDLMutex() != NULL ) { CPLDestroyMutex( *GDALGetphDLMutex() ); *GDALGetphDLMutex() = NULL; } /* -------------------------------------------------------------------- */ /* Cleanup raster block mutex */ /* -------------------------------------------------------------------- */ GDALRasterBlock::DestroyRBMutex(); /* -------------------------------------------------------------------- */ /* Cleanup gdaltransformer.cpp mutex */ /* -------------------------------------------------------------------- */ GDALCleanupTransformDeserializerMutex(); /* -------------------------------------------------------------------- */ /* Cleanup cpl_error.cpp mutex */ /* -------------------------------------------------------------------- */ CPLCleanupErrorMutex(); /* -------------------------------------------------------------------- */ /* Cleanup CPLsetlocale mutex */ /* -------------------------------------------------------------------- */ CPLCleanupSetlocaleMutex(); /* -------------------------------------------------------------------- */ /* Cleanup the master CPL mutex, which governs the creation */ /* of all other mutexes. */ /* -------------------------------------------------------------------- */ CPLCleanupMasterMutex(); /* -------------------------------------------------------------------- */ /* Ensure the global driver manager pointer is NULLed out. */ /* -------------------------------------------------------------------- */ if( poDM == this ) poDM = NULL; } /************************************************************************/ /* GetDriverCount() */ /************************************************************************/ /** * \brief Fetch the number of registered drivers. * * This C analog to this is GDALGetDriverCount(). * * @return the number of registered drivers. */ int GDALDriverManager::GetDriverCount() { return( nDrivers ); } /************************************************************************/ /* GDALGetDriverCount() */ /************************************************************************/ /** * \brief Fetch the number of registered drivers. * * @see GDALDriverManager::GetDriverCount() */ int CPL_STDCALL GDALGetDriverCount() { return GetGDALDriverManager()->GetDriverCount(); } /************************************************************************/ /* GetDriver() */ /************************************************************************/ /** * \brief Fetch driver by index. * * This C analog to this is GDALGetDriver(). * * @param iDriver the driver index from 0 to GetDriverCount()-1. * * @return the driver identified by the index or NULL if the index is invalid */ GDALDriver * GDALDriverManager::GetDriver( int iDriver ) { CPLMutexHolderD( &hDMMutex ); if( iDriver < 0 || iDriver >= nDrivers ) return NULL; else return papoDrivers[iDriver]; } /************************************************************************/ /* GDALGetDriver() */ /************************************************************************/ /** * \brief Fetch driver by index. * * @see GDALDriverManager::GetDriver() */ GDALDriverH CPL_STDCALL GDALGetDriver( int iDriver ) { return (GDALDriverH) GetGDALDriverManager()->GetDriver(iDriver); } /************************************************************************/ /* RegisterDriver() */ /************************************************************************/ /** * \brief Register a driver for use. * * The C analog is GDALRegisterDriver(). * * Normally this method is used by format specific C callable registration * entry points such as GDALRegister_GTiff() rather than being called * directly by application level code. * * If this driver (based on the object pointer, not short name) is already * registered, then no change is made, and the index of the existing driver * is returned. Otherwise the driver list is extended, and the new driver * is added at the end. * * @param poDriver the driver to register. * * @return the index of the new installed driver. */ int GDALDriverManager::RegisterDriver( GDALDriver * poDriver ) { CPLMutexHolderD( &hDMMutex ); /* -------------------------------------------------------------------- */ /* If it is already registered, just return the existing */ /* index. */ /* -------------------------------------------------------------------- */ if( GetDriverByName( poDriver->GetDescription() ) != NULL ) { int i; for( i = 0; i < nDrivers; i++ ) { if( papoDrivers[i] == poDriver ) { return i; } } CPLAssert( FALSE ); } /* -------------------------------------------------------------------- */ /* Otherwise grow the list to hold the new entry. */ /* -------------------------------------------------------------------- */ papoDrivers = (GDALDriver **) VSIRealloc(papoDrivers, sizeof(GDALDriver *) * (nDrivers+1)); papoDrivers[nDrivers] = poDriver; nDrivers++; if( poDriver->pfnCreate != NULL ) poDriver->SetMetadataItem( GDAL_DCAP_CREATE, "YES" ); if( poDriver->pfnCreateCopy != NULL ) poDriver->SetMetadataItem( GDAL_DCAP_CREATECOPY, "YES" ); int iResult = nDrivers - 1; return iResult; } /************************************************************************/ /* GDALRegisterDriver() */ /************************************************************************/ /** * \brief Register a driver for use. * * @see GDALDriverManager::GetRegisterDriver() */ int CPL_STDCALL GDALRegisterDriver( GDALDriverH hDriver ) { VALIDATE_POINTER1( hDriver, "GDALRegisterDriver", 0 ); return GetGDALDriverManager()->RegisterDriver( (GDALDriver *) hDriver ); } /************************************************************************/ /* DeregisterDriver() */ /************************************************************************/ /** * \brief Deregister the passed driver. * * If the driver isn't found no change is made. * * The C analog is GDALDeregisterDriver(). * * @param poDriver the driver to deregister. */ void GDALDriverManager::DeregisterDriver( GDALDriver * poDriver ) { int i; CPLMutexHolderD( &hDMMutex ); for( i = 0; i < nDrivers; i++ ) { if( papoDrivers[i] == poDriver ) break; } if( i == nDrivers ) return; while( i < nDrivers-1 ) { papoDrivers[i] = papoDrivers[i+1]; i++; } nDrivers--; } /************************************************************************/ /* GDALDeregisterDriver() */ /************************************************************************/ /** * \brief Deregister the passed driver. * * @see GDALDriverManager::GetDeregisterDriver() */ void CPL_STDCALL GDALDeregisterDriver( GDALDriverH hDriver ) { VALIDATE_POINTER0( hDriver, "GDALDeregisterDriver" ); GetGDALDriverManager()->DeregisterDriver( (GDALDriver *) hDriver ); } /************************************************************************/ /* GetDriverByName() */ /************************************************************************/ /** * \brief Fetch a driver based on the short name. * * The C analog is the GDALGetDriverByName() function. * * @param pszName the short name, such as GTiff, being searched for. * * @return the identified driver, or NULL if no match is found. */ GDALDriver * GDALDriverManager::GetDriverByName( const char * pszName ) { int i; CPLMutexHolderD( &hDMMutex ); for( i = 0; i < nDrivers; i++ ) { if( EQUAL(papoDrivers[i]->GetDescription(), pszName) ) return papoDrivers[i]; } return NULL; } /************************************************************************/ /* GDALGetDriverByName() */ /************************************************************************/ /** * \brief Fetch a driver based on the short name. * * @see GDALDriverManager::GetDriverByName() */ GDALDriverH CPL_STDCALL GDALGetDriverByName( const char * pszName ) { VALIDATE_POINTER1( pszName, "GDALGetDriverByName", NULL ); return( GetGDALDriverManager()->GetDriverByName( pszName ) ); } /************************************************************************/ /* GetHome() */ /************************************************************************/ const char *GDALDriverManager::GetHome() { return pszHome; } /************************************************************************/ /* SetHome() */ /************************************************************************/ void GDALDriverManager::SetHome( const char * pszNewHome ) { CPLMutexHolderD( &hDMMutex ); CPLFree( pszHome ); pszHome = CPLStrdup(pszNewHome); } /************************************************************************/ /* AutoSkipDrivers() */ /************************************************************************/ /** * \brief This method unload undesirable drivers. * * All drivers specified in the space delimited list in the GDAL_SKIP * environment variable) will be deregistered and destroyed. This method * should normally be called after registration of standard drivers to allow * the user a way of unloading undesired drivers. The GDALAllRegister() * function already invokes AutoSkipDrivers() at the end, so if that functions * is called, it should not be necessary to call this method from application * code. */ void GDALDriverManager::AutoSkipDrivers() { if( CPLGetConfigOption( "GDAL_SKIP", NULL ) == NULL ) return; char **papszList = CSLTokenizeString( CPLGetConfigOption("GDAL_SKIP","") ); for( int i = 0; i < CSLCount(papszList); i++ ) { GDALDriver *poDriver = GetDriverByName( papszList[i] ); if( poDriver == NULL ) CPLError( CE_Warning, CPLE_AppDefined, "Unable to find driver %s to unload from GDAL_SKIP environment variable.", papszList[i] ); else { CPLDebug( "GDAL", "AutoSkipDriver(%s)", papszList[i] ); DeregisterDriver( poDriver ); delete poDriver; } } CSLDestroy( papszList ); } /************************************************************************/ /* AutoLoadDrivers() */ /************************************************************************/ /** * \brief Auto-load GDAL drivers from shared libraries. * * This function will automatically load drivers from shared libraries. It * searches the "driver path" for .so (or .dll) files that start with the * prefix "gdal_X.so". It then tries to load them and then tries to call a * function within them called GDALRegister_X() where the 'X' is the same as * the remainder of the shared library basename ('X' is case sensitive), or * failing that to call GDALRegisterMe(). * * There are a few rules for the driver path. If the GDAL_DRIVER_PATH * environment variable it set, it is taken to be a list of directories to * search separated by colons on UNIX, or semi-colons on Windows. Otherwise * the /usr/local/lib/gdalplugins directory, and (if known) the * lib/gdalplugins subdirectory of the gdal home directory are searched on * UNIX and $(BINDIR)\gdalplugins on Windows. * * Auto loading can be completely disabled by setting the GDAL_DRIVER_PATH * config option to "disable". */ void GDALDriverManager::AutoLoadDrivers() { char **papszSearchPath = NULL; const char *pszGDAL_DRIVER_PATH = CPLGetConfigOption( "GDAL_DRIVER_PATH", NULL ); /* -------------------------------------------------------------------- */ /* Allow applications to completely disable this search by */ /* setting the driver path to the special string "disable". */ /* -------------------------------------------------------------------- */ if( pszGDAL_DRIVER_PATH != NULL && EQUAL(pszGDAL_DRIVER_PATH,"disable")) { CPLDebug( "GDAL", "GDALDriverManager::AutoLoadDrivers() disabled." ); return; } /* -------------------------------------------------------------------- */ /* Where should we look for stuff? */ /* -------------------------------------------------------------------- */ if( pszGDAL_DRIVER_PATH != NULL ) { #ifdef WIN32 papszSearchPath = CSLTokenizeStringComplex( pszGDAL_DRIVER_PATH, ";", TRUE, FALSE ); #else papszSearchPath = CSLTokenizeStringComplex( pszGDAL_DRIVER_PATH, ":", TRUE, FALSE ); #endif } else { #ifdef GDAL_PREFIX papszSearchPath = CSLAddString( papszSearchPath, #ifdef MACOSX_FRAMEWORK GDAL_PREFIX "/PlugIns"); #else GDAL_PREFIX "/lib/gdalplugins" ); #endif #else char szExecPath[1024]; if( CPLGetExecPath( szExecPath, sizeof(szExecPath) ) ) { char szPluginDir[sizeof(szExecPath)+50]; strcpy( szPluginDir, CPLGetDirname( szExecPath ) ); strcat( szPluginDir, "\\gdalplugins" ); papszSearchPath = CSLAddString( papszSearchPath, szPluginDir ); } else { papszSearchPath = CSLAddString( papszSearchPath, "/usr/local/lib/gdalplugins" ); } #endif #ifdef MACOSX_FRAMEWORK #define num2str(x) str(x) #define str(x) #x papszSearchPath = CSLAddString( papszSearchPath, "/Library/Application Support/GDAL/" num2str(GDAL_VERSION_MAJOR) "." num2str(GDAL_VERSION_MINOR) "/PlugIns" ); #endif if( strlen(GetHome()) > 0 ) { papszSearchPath = CSLAddString( papszSearchPath, CPLFormFilename( GetHome(), #ifdef MACOSX_FRAMEWORK "/Library/Application Support/GDAL/" num2str(GDAL_VERSION_MAJOR) "." num2str(GDAL_VERSION_MINOR) "/PlugIns", NULL ) ); #else "lib/gdalplugins", NULL ) ); #endif } } /* -------------------------------------------------------------------- */ /* Format the ABI version specific subdirectory to look in. */ /* -------------------------------------------------------------------- */ CPLString osABIVersion; osABIVersion.Printf( "%d.%d", GDAL_VERSION_MAJOR, GDAL_VERSION_MINOR ); /* -------------------------------------------------------------------- */ /* Scan each directory looking for files starting with gdal_ */ /* -------------------------------------------------------------------- */ for( int iDir = 0; iDir < CSLCount(papszSearchPath); iDir++ ) { char **papszFiles = NULL; VSIStatBufL sStatBuf; CPLString osABISpecificDir = CPLFormFilename( papszSearchPath[iDir], osABIVersion, NULL ); if( VSIStatL( osABISpecificDir, &sStatBuf ) != 0 ) osABISpecificDir = papszSearchPath[iDir]; papszFiles = CPLReadDir( osABISpecificDir ); for( int iFile = 0; iFile < CSLCount(papszFiles); iFile++ ) { char *pszFuncName; const char *pszFilename; const char *pszExtension = CPLGetExtension( papszFiles[iFile] ); void *pRegister; if( !EQUALN(papszFiles[iFile],"gdal_",5) ) continue; if( !EQUAL(pszExtension,"dll") && !EQUAL(pszExtension,"so") && !EQUAL(pszExtension,"dylib") ) continue; pszFuncName = (char *) CPLCalloc(strlen(papszFiles[iFile])+20,1); sprintf( pszFuncName, "GDALRegister_%s", CPLGetBasename(papszFiles[iFile]) + 5 ); pszFilename = CPLFormFilename( osABISpecificDir, papszFiles[iFile], NULL ); CPLErrorReset(); CPLPushErrorHandler(CPLQuietErrorHandler); pRegister = CPLGetSymbol( pszFilename, pszFuncName ); CPLPopErrorHandler(); if( pRegister == NULL ) { CPLString osLastErrorMsg(CPLGetLastErrorMsg()); strcpy( pszFuncName, "GDALRegisterMe" ); pRegister = CPLGetSymbol( pszFilename, pszFuncName ); if( pRegister == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "%s", osLastErrorMsg.c_str() ); } } if( pRegister != NULL ) { CPLDebug( "GDAL", "Auto register %s using %s.", pszFilename, pszFuncName ); ((void (*)()) pRegister)(); } CPLFree( pszFuncName ); } CSLDestroy( papszFiles ); } CSLDestroy( papszSearchPath ); } /************************************************************************/ /* GDALDestroyDriverManager() */ /************************************************************************/ /** * \brief Destroy the driver manager. * * Incidently unloads all managed drivers. * * NOTE: This function is not thread safe. It should not be called while * other threads are actively using GDAL. */ void CPL_STDCALL GDALDestroyDriverManager( void ) { // THREADSAFETY: We would like to lock the mutex here, but it // needs to be reacquired within the destructor during driver // deregistration. if( poDM != NULL ) delete poDM; }
tilemapjp/OSGeo.GDAL.Xamarin
gdal-1.11.0/gcore/gdaldrivermanager.cpp
C++
mit
30,311
/** * 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. */ package com.microsoft.azure.management.network.v2019_08_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.network.v2019_08_01.implementation.ProbeInner; import com.microsoft.azure.arm.model.Indexable; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.network.v2019_08_01.implementation.NetworkManager; import java.util.List; import com.microsoft.azure.SubResource; /** * Type representing Probe. */ public interface Probe extends HasInner<ProbeInner>, Indexable, Refreshable<Probe>, HasManager<NetworkManager> { /** * @return the etag value. */ String etag(); /** * @return the id value. */ String id(); /** * @return the intervalInSeconds value. */ Integer intervalInSeconds(); /** * @return the loadBalancingRules value. */ List<SubResource> loadBalancingRules(); /** * @return the name value. */ String name(); /** * @return the numberOfProbes value. */ Integer numberOfProbes(); /** * @return the port value. */ int port(); /** * @return the protocol value. */ ProbeProtocol protocol(); /** * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * @return the requestPath value. */ String requestPath(); /** * @return the type value. */ String type(); }
navalev/azure-sdk-for-java
sdk/network/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/network/v2019_08_01/Probe.java
Java
mit
1,770
/* * MIT License * * Copyright (c) 2016 BotMill.io * * 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. */ package co.aurasphere.botmill.fb; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import co.aurasphere.botmill.core.BotDefinition; import co.aurasphere.botmill.core.base.BotMillServlet; import co.aurasphere.botmill.fb.internal.util.json.FbBotMillJsonUtils; import co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkConstants; import co.aurasphere.botmill.fb.model.incoming.MessageEnvelope; import co.aurasphere.botmill.fb.model.incoming.MessengerCallback; import co.aurasphere.botmill.fb.model.incoming.MessengerCallbackEntry; import co.aurasphere.botmill.fb.model.incoming.handler.IncomingToOutgoingMessageHandler; /** * Main Servlet for FbBotMill framework. This servlet requires an init-param * containing the fully qualified name of a class implementing * {@link BotDefinition} in which the initial configuration is done. If not such * class is found or can't be loaded, a ServletException is thrown during * initialization. * * The FbBotMillServlet supports GET requests only for the Subscribing phase and * POST requests for all the Facebook callbacks. For more information about how * the communication is handled, check the documentation for {@link #doGet}, * {@link #doPost(HttpServletRequest, HttpServletResponse)} and Facebook's * documentation with the link below. * * @author Donato Rimenti * @author Alvin Reyes * * @see <a href= * "https://developers.facebook.com/docs/messenger-platform/quickstart"> * Facebook Subscription info</a> * */ public class FbBotMillServlet extends BotMillServlet { /** * The logger. */ private static final Logger logger = LoggerFactory .getLogger(FbBotMillServlet.class); /** * The serial version UID. */ private static final long serialVersionUID = 1L; /** * Specifies how to handle a GET request. GET requests are used by Facebook * only during the WebHook registration. During this phase, the * FbBotMillServlet checks that the * {@link FbBotMillNetworkConstants#HUB_MODE_PARAMETER} value received * equals to {@link FbBotMillNetworkConstants#HUB_MODE_SUBSCRIBE} and that * the {@link FbBotMillNetworkConstants#HUB_VERIFY_TOKEN_PARAMETER} value * received equals to the {@link FbBotMillContext#getValidationToken()}. If * that's true, then the FbBotMillServlet will reply sending back the value * of the {@link FbBotMillNetworkConstants#HUB_CHALLENGE_PARAMETER} * received, in order to confirm the registration, otherwise it will return * an error 403. * * @param req * the req * @param resp * the resp * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override @SuppressWarnings("unchecked") protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Retrieves GET parameters. String validationToken = FbBotMillContext.getInstance() .getValidationToken(); Map<String, String[]> parameters = req.getParameterMap(); String hubMode = safeUnwrapGetParameters(parameters .get(FbBotMillNetworkConstants.HUB_MODE_PARAMETER)); String hubToken = safeUnwrapGetParameters(parameters .get(FbBotMillNetworkConstants.HUB_VERIFY_TOKEN_PARAMETER)); String hubChallenge = safeUnwrapGetParameters(parameters .get(FbBotMillNetworkConstants.HUB_CHALLENGE_PARAMETER)); // Checks parameters and responds according to that. if (hubMode.equals(FbBotMillNetworkConstants.HUB_MODE_SUBSCRIBE) && hubToken.equals(validationToken)) { logger.info("Subscription OK."); resp.setStatus(200); resp.setContentType("text/plain"); resp.getWriter().write(hubChallenge); } else { logger.warn("GET received is not a subscription or wrong validation token. Ensure you have set the correct validation token using FbBotMillContext.getInstance().setup(String, String)."); resp.sendError(403); } } /** * Specifies how to handle a POST request. It parses the request as a * {@link MessengerCallback} object. If the request is not a * MessengerCallback, then the FbBotMillServlet logs an error and does * nothing, otherwise it will forward the request to all registered bots in * order to let them process the callbacks. * * @param req * the req * @param resp * the resp * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.trace("POST received!"); MessengerCallback callback = new MessengerCallback(); // Extrapolates and logs the JSON for debugging. String json = readerToString(req.getReader()); logger.debug("JSON input: " + json); // Parses the request as a MessengerCallback. try { callback = FbBotMillJsonUtils.fromJson(json, MessengerCallback.class); } catch (Exception e) { logger.error("Error during MessengerCallback parsing: ", e); return; } // If the received POST is a MessengerCallback, it forwards the last // envelope of all the callbacks received to the registered bots. if (callback != null) { List<MessengerCallbackEntry> callbackEntries = callback.getEntry(); if (callbackEntries != null) { for (MessengerCallbackEntry entry : callbackEntries) { List<MessageEnvelope> envelopes = entry.getMessaging(); if (envelopes != null) { MessageEnvelope lastEnvelope = envelopes.get(envelopes.size() - 1); IncomingToOutgoingMessageHandler.getInstance().process(lastEnvelope); } } } } // Always set to ok. resp.setStatus(HttpServletResponse.SC_OK); } /** * Method which returns the first String in a String array if present or the * empty String otherwise. Used to unwrap the GET arguments from an * {@link HttpServletRequest#getParameterMap()} which returns a String array * for each GET parameter. * * @param parameter * the String array to unwrap. * @return the first String of the array if found or the empty String * otherwise. */ private static String safeUnwrapGetParameters(String[] parameter) { if (parameter == null || parameter[0] == null) { return ""; } return parameter[0]; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "FbBotMillServlet []"; } }
Aurasphere/facebot
src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java
Java
mit
8,084
import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1
IvanMalison/okcupyd
tests/search_test.py
Python
mit
7,482
(function ($) { var smileys = [ ":(", ":)", ":O", ":D", ":p", ":*", ":-)", ":-(", ":-O", ":-D" ], extras = { "<3": true, "&lt;3": true }, smileParts = { "O": "middle-mouth", "D": "middle-mouth", "d": "middle-mouth", "p": "low-mouth", "*": "high-mouth", "-": "nose" }, oppositeSmileParts = { "p": "d", ")": "(", "(": ")" }, reverseSmileys = []; for (var i = 0; i < smileys.length; i++) { var reverse = ""; for (var j = smileys[i].length - 1; j >= 0; j--) { var character = smileys[i][j]; if (character in oppositeSmileParts) { reverse += oppositeSmileParts[smileys[i][j]]; } else { reverse += smileys[i][j]; } } reverseSmileys.push(reverse); } function toggleSmiley() { $(this).toggleClass("active"); } function prepareSmileys(html) { for (var extra in extras) { html = checkForSmiley(html, extra, extras[extra]); } for (var i = smileys.length - 1; i >= 0; i--) { html = checkForSmiley(html, smileys[i], false); } for (var i = reverseSmileys.length - 1; i >= 0; i--) { html = checkForSmiley(html, reverseSmileys[i], true); } return html; } function checkForSmiley(html, smiley, isReverse) { var index = html.indexOf(smiley), replace = null; while (index >= 0) { if (replace === null) { replace = prepareSmiley(smiley, isReverse); } html = replaceString(html, replace, index, index + smiley.length); index = html.indexOf(smiley, index + replace.length); } return html; } function prepareSmiley(smiley, isReverse) { var html = '<span class="smiley-wrapper"><span class="smiley' + (isReverse ? ' smiley-reverse' : '') + '">'; for (var i = 0; i < smiley.length; i++) { if (smiley[i] in smileParts) { html += '<span class="' + smileParts[smiley[i]] + '">' + smiley[i] + '</span>'; } else { html += smiley[i]; } }; html += '</span></span>'; return html; } function replaceString(string, replace, from, to) { return string.substring(0, from) + replace + string.substring(to); } function fixSmiles($el) { var smiles = prepareSmileys($el.html()); $el.html(smiles); } $(document).on("click", ".smiley", toggleSmiley); $.fn.smilify = function() { var $els = $(this).each(function () { fixSmiles($(this)); }); setTimeout(function () { $els.find(".smiley").each(toggleSmiley); }, 20); return this; }; }(jQuery));
daltonrowe/daltonrowe.github.io
smileys/js/smileys.js
JavaScript
mit
2,469
<?php namespace Concrete\Tests\Form\Service; use Concrete\Core\Http\Request; use Core; use PHPUnit_Framework_TestCase; class FormTest extends PHPUnit_Framework_TestCase { /** * @var \Concrete\Core\Form\Service\Form */ protected static $formHelper; /** * @var \Concrete\Core\Http\Request */ protected static $request; public static function setUpBeforeClass() { self::$request = new Request(); self::$formHelper = Core::make('helper/form', ['request' => self::$request]); self::$formHelper->setRequest(self::$request); } public function providerTestCreateElements() { return [ // submit [ 'submit', ['Key', 'Value'], '<input type="submit" class="btn ccm-input-submit" id="Key" name="Key" value="Value" />', ], [ 'submit', ['Key[]', 'Value'], '<input type="submit" class="btn ccm-input-submit" id="Key[]" name="Key[]" value="Value" />', ], [ 'submit', ['Key', 'Value', ['class' => 'MY-CLASS']], '<input type="submit" class="MY-CLASS btn ccm-input-submit" id="Key" name="Key" value="Value" />', ], [ 'submit', ['Key', 'Value', [], 'MY-CLASS'], '<input type="submit" class="btn ccm-input-submit MY-CLASS" id="Key" name="Key" value="Value" />', ], // button [ 'button', ['Key', 'Value'], '<input type="button" class="btn ccm-input-button" id="Key" name="Key" value="Value" />', ], [ 'button', ['Key[]', 'Value'], '<input type="button" class="btn ccm-input-button" id="Key[]" name="Key[]" value="Value" />', ], [ 'button', ['Key', 'Value', ['class' => 'MY-CLASS']], '<input type="button" class="MY-CLASS btn ccm-input-button" id="Key" name="Key" value="Value" />', ], [ 'button', ['Key', 'Value', [], 'MY-CLASS'], '<input type="button" class="btn ccm-input-button MY-CLASS" id="Key" name="Key" value="Value" />', ], // label [ 'label', ['ForKey', '<b>label</b>'], '<label for="ForKey" class="control-label"><b>label</b></label>', ], [ 'label', ['ForKey[]', 'text'], '<label for="ForKey[]" class="control-label">text</label>', ], [ 'label', ['ForKey', 'text', []], '<label for="ForKey" class="control-label">text</label>', ], [ 'label', ['ForKey', 'text', ['class' => 'MY-CLASS']], '<label for="ForKey" class="MY-CLASS control-label">text</label>', ], // file [ 'file', ['Key'], '<input type="file" id="Key" name="Key" value="" class="form-control" />', ], [ 'file', ['Key[]'], '<input type="file" id="Key[]" name="Key[]" value="" class="form-control" />', ], [ 'file', ['Key', []], '<input type="file" id="Key" name="Key" value="" class="form-control" />', ], [ 'file', ['Key', ['class' => 'MY-CLASS']], '<input type="file" id="Key" name="Key" value="" class="MY-CLASS form-control" />', ], // hidden [ 'hidden', ['Key'], '<input type="hidden" id="Key" name="Key" value="" />', ], [ 'hidden', ['Key', null], '<input type="hidden" id="Key" name="Key" value="" />', ], [ 'hidden', ['Key', null, ['class' => 'MY-CLASS']], '<input type="hidden" id="Key" name="Key" class="MY-CLASS" value="" />', ], [ 'hidden', ['Key', ''], '<input type="hidden" id="Key" name="Key" value="" />', ], [ 'hidden', ['Key', '', ['class' => 'MY-CLASS']], '<input type="hidden" id="Key" name="Key" class="MY-CLASS" value="" />', ], [ 'hidden', ['Key', 'Field value'], '<input type="hidden" id="Key" name="Key" value="Field value" />', ], [ 'hidden', ['Key', 'Field value', ['class' => 'MY-CLASS', 'data-my-data' => 'My value']], '<input type="hidden" id="Key" name="Key" class="MY-CLASS" data-my-data="My value" value="Field value" />', ], [ 'hidden', ['Key', false], '<input type="hidden" id="Key" name="Key" value="" />', ], [ 'hidden', ['Key', 1], '<input type="hidden" id="Key" name="Key" value="1" />', ], [ 'hidden', ['Key', 'Original value'], '<input type="hidden" id="Key" name="Key" value="Original value" />', ], [ 'hidden', ['Key', 'Original value'], '<input type="hidden" id="Key" name="Key" value="" />', ['Key' => ''], ], [ 'hidden', ['Key[]'], '<input type="hidden" id="Key[]" name="Key[]" value="" />', ], [ 'hidden', ['Key', 'Original value'], '<input type="hidden" id="Key" name="Key" value="Received value" />', ['Key' => 'Received value'], ], [ 'hidden', ['Key[subkey1][subkey2]', 'Original value'], '<input type="hidden" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" />', ['Key' => 'Received value'], ], [ 'hidden', ['Key[subkey1][subkey2]', 'Original value'], '<input type="hidden" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" />', ['Key' => ['subkey1' => 'Received value']], ], [ 'hidden', ['Key[subkey1][subkey2]', 'Original value'], '<input type="hidden" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Received value" />', ['Key' => ['subkey1' => ['subkey2' => 'Received value']]], ], [ 'hidden', ['Key[subkey1][subkey2]', 'Original value'], '<input type="hidden" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" />', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'Received value']]]], ], // checkbox [ 'checkbox', ['Key', 'Value'], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key', 'Value', false], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key', 'Value', null], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key', 'Value', 0], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key', 'Value', '0'], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key', 'Value', true], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" checked="checked" />', ], [ 'checkbox', ['Key', 'Value', '1'], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" checked="checked" />', ], [ 'checkbox', ['Key', 'Value', true], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ['OtherField' => 'Other value'], ], [ 'checkbox', ['Key', 'Value', false], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" checked="checked" />', ['Key' => 'Value'], ], [ 'checkbox', ['Key', 'Value', false], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ['Key' => ''], ], [ 'checkbox', ['Key', 'Value', false], '<input type="checkbox" id="Key" name="Key" class="ccm-input-checkbox" value="Value" />', ['Key' => 'Wrong value'], ], [ 'checkbox', ['Key[]', 'Value'], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" />', ], [ 'checkbox', ['Key[]', 'Value', true], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" checked="checked" />', ], [ 'checkbox', ['Key[]', 'Value', true], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" />', ['OtherField' => 'Other value'], ], [ 'checkbox', ['Key[]', 'Value', false], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" checked="checked" />', ['Key' => 'Value'], ], [ 'checkbox', ['Key[]', 'Value', false], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" />', ['Key' => 'Other value'], ], [ 'checkbox', ['Key[]', 'Value', false], '<input type="checkbox" id="Key_Value" name="Key[]" class="ccm-input-checkbox" value="Value" checked="checked" />', ['Key' => ['Look', 'for', 'Value', 'in', 'this', 'array']], ], [ 'checkbox', ['Key[subkey1][subkey2]', 'Value', false], '<input type="checkbox" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="ccm-input-checkbox" value="Value" />', ['Key' => 'Value'], ], [ 'checkbox', ['Key[subkey1][subkey2]', 'Value', false], '<input type="checkbox" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="ccm-input-checkbox" value="Value" />', ['Key' => ['subkey1' => 'Value']], ], [ 'checkbox', ['Key[subkey1][subkey2]', 'Value', false], '<input type="checkbox" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="ccm-input-checkbox" value="Value" checked="checked" />', ['Key' => ['subkey1' => ['subkey2' => 'Value']]], ], [ 'checkbox', ['Key[subkey1][subkey2]', 'Value', false], '<input type="checkbox" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="ccm-input-checkbox" value="Value" checked="checked" />', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'Value']]]], ], [ 'checkbox', ['Key[subkey1][subkey2]', 'Value', false], '<input type="checkbox" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="ccm-input-checkbox" value="Value" />', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'Other value']]]], ], // textarea [ 'textarea', ['Key'], '<textarea id="Key" name="Key" class="form-control"></textarea>', ], [ 'textarea', ['Key', 'Value'], '<textarea id="Key" name="Key" class="form-control">Value</textarea>', ], [ 'textarea', ['Key', ['class' => 'MY-CLASS']], '<textarea id="Key" name="Key" class="MY-CLASS form-control"></textarea>', ], [ 'textarea', ['Key', '', ['class' => 'MY-CLASS']], '<textarea id="Key" name="Key" class="MY-CLASS form-control"></textarea>', ], [ 'textarea', ['Key', 'Value', ['class' => 'MY-CLASS']], '<textarea id="Key" name="Key" class="MY-CLASS form-control">Value</textarea>', ], [ 'textarea', ['Key', 'Original value'], '<textarea id="Key" name="Key" class="form-control"></textarea>', ['Key' => ''], ], [ 'textarea', ['Key', 'Original value'], '<textarea id="Key" name="Key" class="form-control">Received value</textarea>', ['Key' => 'Received value'], ], [ 'textarea', ['Key[subkey1][subkey2]', 'Original value'], '<textarea id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="form-control">Original value</textarea>', ['Key' => 'Received value'], ], [ 'textarea', ['Key[subkey1][subkey2]', 'Original value'], '<textarea id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="form-control">Original value</textarea>', ['Key' => ['subkey1' => 'Received value']], ], [ 'textarea', ['Key[subkey1][subkey2]', 'Original value'], '<textarea id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="form-control">Received value</textarea>', ['Key' => ['subkey1' => ['subkey2' => 'Received value']]], ], [ 'textarea', ['Key[subkey1][subkey2]', 'Original value'], '<textarea id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" class="form-control">Original value</textarea>', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'Received value']]]], ], // radio [ 'radio', ['Key', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" />', ], [ 'radio', ['Key', 'Value', 'Incorrect value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" />', ], [ 'radio', ['Key', 'Value', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" checked="checked" />', ], [ 'radio', ['Key', 'Value', ['class' => 'MY-CLASS', 'data-custom' => 'My custom data']], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="MY-CLASS ccm-input-radio" data-custom="My custom data" />', ], [ 'radio', ['Key', 'Value', 'Value', ['class' => 'MY-CLASS']], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="MY-CLASS ccm-input-radio" checked="checked" />', ], [ 'radio', ['Key', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" />', ['Key' => ''], ], [ 'radio', ['Key', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" />', ['Key' => 'Invalid value'], ], [ 'radio', ['Key', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" checked="checked" />', ['Key' => 'Value'], ], [ 'radio', ['Key', 'Value'], '<input type="radio" id="Key**UNIQUENUMBER**" name="Key" value="Value" class="ccm-input-radio" />', ['OtherKey' => 'OtherValue'], ], [ 'radio', ['Key[subkey1][subkey2]', 'Value'], '<input type="radio" id="Key[subkey1][subkey2]**UNIQUENUMBER**" name="Key[subkey1][subkey2]" value="Value" class="ccm-input-radio" checked="checked" />', ['Key' => ['subkey1' => ['subkey2' => 'Value']]], ], // inputType (text, number, email, telephone, url, search, password) [ 'text', ['Key'], '<input type="text" id="Key" name="Key" value="" class="form-control ccm-input-text" />', ], [ 'number', ['Key'], '<input type="number" id="Key" name="Key" value="" class="form-control ccm-input-number" />', ], [ 'email', ['Key'], '<input type="email" id="Key" name="Key" value="" class="form-control ccm-input-email" />', ], [ 'telephone', ['Key'], '<input type="tel" id="Key" name="Key" value="" class="form-control ccm-input-tel" />', ], [ 'url', ['Key'], '<input type="url" id="Key" name="Key" value="" class="form-control ccm-input-url" />', ], [ 'search', ['Key'], '<input type="search" id="Key" name="Key" value="" class="form-control ccm-input-search" />', ], [ 'password', ['Key'], '<input type="password" id="Key" name="Key" value="" class="form-control ccm-input-password" />', ], [ 'text', ['Key', null], '<input type="text" id="Key" name="Key" value="" class="form-control ccm-input-text" />', ], [ 'text', ['Key', false], '<input type="text" id="Key" name="Key" value="" class="form-control ccm-input-text" />', ], [ 'text', ['Key', 'Value'], '<input type="text" id="Key" name="Key" value="Value" class="form-control ccm-input-text" />', ], [ 'text', ['Key', ['data-mine' => 'MY DATA', 'class' => 'MY-CLASS']], '<input type="text" id="Key" name="Key" value="" data-mine="MY DATA" class="MY-CLASS form-control ccm-input-text" />', ], [ 'text', ['Key', 'Value', ['class' => 'MY-CLASS']], '<input type="text" id="Key" name="Key" value="Value" class="MY-CLASS form-control ccm-input-text" />', ], [ 'text', ['Key', 'Value'], '<input type="text" id="Key" name="Key" value="Received value" class="form-control ccm-input-text" />', ['Key' => 'Received value'], ], [ 'text', ['Key', 'Value'], '<input type="text" id="Key" name="Key" value="Value" class="form-control ccm-input-text" />', ['OtherKey' => 'Other value'], ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" class="form-control ccm-input-text" />', ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" class="form-control ccm-input-text" />', ['OtherKey' => 'Other value'], ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" class="form-control ccm-input-text" />', ['Key' => 'Received value'], ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" class="form-control ccm-input-text" />', ['Key' => ['subkey1' => 'Received value']], ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Received value" class="form-control ccm-input-text" />', ['Key' => ['subkey1' => ['subkey2' => 'Received value']]], ], [ 'text', ['Key[subkey1][subkey2]', 'Original value'], '<input type="text" id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" value="Original value" class="form-control ccm-input-text" />', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'Received value']]]], ], // select [ 'select', ['Key', null], '<select id="Key" name="Key" class="form-control"></select>', ], [ 'select', ['Key', false], '<select id="Key" name="Key" class="form-control"></select>', ], [ 'select', ['Key', ''], '<select id="Key" name="Key" class="form-control"></select>', ], [ 'select', ['Key', []], '<select id="Key" name="Key" class="form-control"></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], ['class' => 'MY-CLASS', 'data-mine' => 'MY DATA']], '<select id="Key" name="Key" class="MY-CLASS form-control" data-mine="MY DATA"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two', ['class' => 'MY-CLASS', 'data-mine' => 'MY DATA']], '<select id="Key" name="Key" class="MY-CLASS form-control" data-mine="MY DATA" ccm-passed-value="Two"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Invalid'], '<select id="Key" name="Key" ccm-passed-value="Invalid" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ['OtherField' => 'OtherValue'], ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ['Key' => ''], ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key" ccm-passed-value="Two" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => 'One'], ], [ 'select', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ['Key' => 'Invalid'], ], [ 'select', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => 'One'], ], [ 'select', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => ['subkey1' => 'One']], ], [ 'select', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" ccm-passed-value="Two" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => ['subkey1' => ['subkey2' => 'One']]], ], [ 'select', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2]" ccm-passed-value="Two" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'One']]]], ], // selectMultiple [ 'selectMultiple', ['Key', null], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"></select>', ], [ 'selectMultiple', ['Key', []], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], false], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], null], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], []], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], false, ['data-mine' => 'MY DATA', 'class' => 'MY-CLASS']], '<select id="Key" name="Key[]" multiple="multiple" data-mine="MY DATA" class="MY-CLASS form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], ['Two']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], ['Invalid']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], ['Two', 'One']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two" selected="selected">Second</option></select>', ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => 'One'], ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ['Key' => []], ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => ['One']], ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => ['One']], ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second']], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => ['One', 'Two']], ], [ 'selectMultiple', ['Key', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key" name="Key[]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => ['One', 'Two']], ], [ 'selectMultiple', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2][]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => ['One']], ], [ 'selectMultiple', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2][]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two" selected="selected">Second</option></select>', ['Key' => ['subkey1' => ['One']]], ], [ 'selectMultiple', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2][]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => ['subkey1' => ['subkey2' => ['One']]]], ], [ 'selectMultiple', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2][]" multiple="multiple" class="form-control"><option value="One" selected="selected">First</option><option value="Two">Second</option></select>', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => 'One']]]], ], [ 'selectMultiple', ['Key[subkey1][subkey2]', ['One' => 'First', 'Two' => 'Second'], 'Two'], '<select id="Key[subkey1][subkey2]" name="Key[subkey1][subkey2][]" multiple="multiple" class="form-control"><option value="One">First</option><option value="Two">Second</option></select>', ['Key' => ['subkey1' => ['subkey2' => ['subkey3' => ['One']]]]], ], ]; } /** * @dataProvider providerTestCreateElements * * @param mixed $method * @param array $args * @param mixed $expected * @param array $post */ public function testCreateElements($method, array $args, $expected, array $post = []) { if (empty($post)) { self::$request->initialize(); } else { self::$request->initialize([], $post, [], [], [], ['REQUEST_METHOD' => 'POST']); } $calculated = call_user_func_array([static::$formHelper, $method], $args); if (strpos($expected, '**UNIQUENUMBER**') === false) { $this->assertSame($expected, $calculated); } else { $chunks = explode('**UNIQUENUMBER**', $expected); array_walk($chunks, function (&$chunk, $index) { $chunk = preg_quote($chunk, '/'); }); $rx = '/^' . implode('\d+', $chunks) . '$/'; $this->assertRegExp($rx, $calculated); } } }
triplei/concrete5-8
tests/tests/Form/Service/FormTest.php
PHP
mit
37,375
/* * jQuery UI 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ (function($) { var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "1.7.2", // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function(module, option, set) { var proto = $.ui[module].prototype; for(var i in set) { proto.plugins[i] = proto.plugins[i] || []; proto.plugins[i].push([option, set[i]]); } }, call: function(instance, name, args) { var set = instance.plugins[name]; if(!set || !instance.element[0].parentNode) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b); }, hasScroll: function(el, a) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ($(el).css('overflow') == 'hidden') { return false; } var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', has = false; if (el[scroll] > 0) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[scroll] = 1; has = (el[scroll] > 0); el[scroll] = 0; return has; }, isOverAxis: function(x, reference, size) { //Determines when x coordinate is over "b" element axis return (x > reference) && (x < (reference + size)); }, isOver: function(y, x, top, left, height, width) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, scrollParent: function() { var scrollParent; if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; } }); //Additional selectors $.extend($.expr[':'], { data: function(elem, i, match) { return !!$.data(elem, match[3]); }, focusable: function(element) { var nodeName = element.nodeName.toLowerCase(), tabIndex = $.attr(element, 'tabindex'); return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : 'a' == nodeName || 'area' == nodeName ? element.href || !isNaN(tabIndex) : !isNaN(tabIndex)) // the element and all of its ancestors must be visible // the browser may report that the area is hidden && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; }, tabbable: function(element) { var tabIndex = $.attr(element, 'tabindex'); return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))._init()); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { if (event.target == element) { return self._setData(key, value); } }) .bind('getData.' + name, function(event, key) { if (event.target == element) { return self._getData(key); } }) .bind('remove', function() { return self.destroy(); }); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _getData: function(key) { return this.options[key]; }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var callback = this.options[type], eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = $.Event(event); event.type = eventName; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if (event.originalEvent) { for (var i = $.event.props.length, prop; i;) { prop = $.event.props[--i]; event[prop] = event.originalEvent[prop]; } } this.element.trigger(event, data); return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false || event.isDefaultPrevented()); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; event.stopImmediatePropagation(); return false; } }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart // TODO: figure out why we have to use originalEvent event.originalEvent = event.originalEvent || {}; if (event.originalEvent.mouseHandled) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed ($.browser.safari || event.preventDefault()); event.originalEvent.mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (event.target == this._mouseDownEvent.target); this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery); /* * jQuery UI Tabs 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Tabs * * Depends: * ui.core.js */ (function($) { $.widget("ui.tabs", { _init: function() { if (this.options.deselectable !== undefined) { this.options.collapsible = this.options.deselectable; } this._tabify(true); }, _setData: function(key, value) { if (key == 'selected') { if (this.options.collapsible && value == this.options.selected) { return; } this.select(value); } else { this.options[key] = value; if (key == 'deselectable') { this.options.collapsible = value; } this._tabify(); } }, _tabId: function(a) { return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') || this.options.idPrefix + $.data(a); }, _sanitizeSelector: function(hash) { return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":" }, _cookie: function() { var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0])); return $.cookie.apply(null, [cookie].concat($.makeArray(arguments))); }, _ui: function(tab, panel) { return { tab: tab, panel: panel, index: this.anchors.index(tab) }; }, _cleanup: function() { // restore all former loading tabs labels this.lis.filter('.ui-state-processing').removeClass('ui-state-processing') .find('span:data(label.tabs)') .each(function() { var el = $(this); el.html(el.data('label.tabs')).removeData('label.tabs'); }); }, _tabify: function(init) { this.list = this.element.children('ul:first'); this.lis = $('li:has(a[href])', this.list); this.anchors = this.lis.map(function() { return $('a', this)[0]; }); this.panels = $([]); var self = this, o = this.options; var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash this.anchors.each(function(i, a) { var href = $(a).attr('href'); // For dynamically created HTML that contains a hash as href IE < 8 expands // such href to the full page url with hash and then misinterprets tab as ajax. // Same consideration applies for an added tab with a fragment identifier // since a[href=#fragment-identifier] does unexpectedly not match. // Thus normalize href attribute... var hrefBase = href.split('#')[0], baseEl; if (hrefBase && (hrefBase === location.toString().split('#')[0] || (baseEl = $('base')[0]) && hrefBase === baseEl.href)) { href = a.hash; a.href = href; } // inline tab if (fragmentId.test(href)) { self.panels = self.panels.add(self._sanitizeSelector(href)); } // remote tab else if (href != '#') { // prevent loading the page itself if href is just "#" $.data(a, 'href.tabs', href); // required for restore on destroy // TODO until #3808 is fixed strip fragment identifier from url // (IE fails to load from such url) $.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data var id = self._tabId(a); a.href = '#' + id; var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom') .insertAfter(self.panels[i - 1] || self.list); $panel.data('destroy.tabs', true); } self.panels = self.panels.add($panel); } // invalid tab href else { o.disabled.push(i); } }); // initialization from scratch if (init) { // attach necessary classes for styling this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all'); this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.lis.addClass('ui-state-default ui-corner-top'); this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom'); // Selected tab // use "selected" option or try to retrieve: // 1. from fragment identifier in url // 2. from cookie // 3. from selected class attribute on <li> if (o.selected === undefined) { if (location.hash) { this.anchors.each(function(i, a) { if (a.hash == location.hash) { o.selected = i; return false; // break } }); } if (typeof o.selected != 'number' && o.cookie) { o.selected = parseInt(self._cookie(), 10); } if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } o.selected = o.selected || 0; } else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release o.selected = -1; } // sanity check - default to first tab... o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0; // Take disabling tabs via class attribute from HTML // into account and update option properly. // A selected tab cannot become disabled. o.disabled = $.unique(o.disabled.concat( $.map(this.lis.filter('.ui-state-disabled'), function(n, i) { return self.lis.index(n); } ) )).sort(); if ($.inArray(o.selected, o.disabled) != -1) { o.disabled.splice($.inArray(o.selected, o.disabled), 1); } // highlight selected tab this.panels.addClass('ui-tabs-hide'); this.lis.removeClass('ui-tabs-selected ui-state-active'); if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list this.panels.eq(o.selected).removeClass('ui-tabs-hide'); this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active'); // seems to be expected behavior that the show callback is fired self.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected])); }); this.load(o.selected); } // clean up to avoid memory leaks in certain versions of IE 6 $(window).bind('unload', function() { self.lis.add(self.anchors).unbind('.tabs'); self.lis = self.anchors = self.panels = null; }); } // update selected after add/remove else { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } // update collapsible this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible'); // set or update cookie after init and add/remove respectively if (o.cookie) { this._cookie(o.selected, o.cookie); } // disable tabs for (var i = 0, li; (li = this.lis[i]); i++) { $(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled'); } // reset cache if switching from cached to not cached if (o.cache === false) { this.anchors.removeData('cache.tabs'); } // remove all handlers before, tabify may run on existing tabs after add or option change this.lis.add(this.anchors).unbind('.tabs'); if (o.event != 'mouseover') { var addState = function(state, el) { if (el.is(':not(.ui-state-disabled)')) { el.addClass('ui-state-' + state); } }; var removeState = function(state, el) { el.removeClass('ui-state-' + state); }; this.lis.bind('mouseover.tabs', function() { addState('hover', $(this)); }); this.lis.bind('mouseout.tabs', function() { removeState('hover', $(this)); }); this.anchors.bind('focus.tabs', function() { addState('focus', $(this).closest('li')); }); this.anchors.bind('blur.tabs', function() { removeState('focus', $(this).closest('li')); }); } // set up animations var hideFx, showFx; if (o.fx) { if ($.isArray(o.fx)) { hideFx = o.fx[0]; showFx = o.fx[1]; } else { hideFx = showFx = o.fx; } } // Reset certain styles left over from animation // and prevent IE's ClearType bug... function resetStyle($el, fx) { $el.css({ display: '' }); if ($.browser.msie && fx.opacity) { $el[0].style.removeAttribute('filter'); } } // Show a tab... var showTab = showFx ? function(clicked, $show) { $(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active'); $show.hide().removeClass('ui-tabs-hide') // avoid flicker that way .animate(showFx, showFx.duration || 'normal', function() { resetStyle($show, showFx); self._trigger('show', null, self._ui(clicked, $show[0])); }); } : function(clicked, $show) { $(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active'); $show.removeClass('ui-tabs-hide'); self._trigger('show', null, self._ui(clicked, $show[0])); }; // Hide a tab, $show is optional... var hideTab = hideFx ? function(clicked, $hide) { $hide.animate(hideFx, hideFx.duration || 'normal', function() { self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default'); $hide.addClass('ui-tabs-hide'); resetStyle($hide, hideFx); self.element.dequeue("tabs"); }); } : function(clicked, $hide, $show) { self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default'); $hide.addClass('ui-tabs-hide'); self.element.dequeue("tabs"); }; // attach tab event handler, unbind to avoid duplicates from former tabifying... this.anchors.bind(o.event + '.tabs', function() { var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'), $show = $(self._sanitizeSelector(this.hash)); // If tab is already selected and not collapsible or tab disabled or // or is already loading or click callback returns false stop here. // Check if click handler returns false last so that it is not executed // for a disabled or loading tab! if (($li.hasClass('ui-tabs-selected') && !o.collapsible) || $li.hasClass('ui-state-disabled') || $li.hasClass('ui-state-processing') || self._trigger('select', null, self._ui(this, $show[0])) === false) { this.blur(); return false; } o.selected = self.anchors.index(this); self.abort(); // if tab may be closed if (o.collapsible) { if ($li.hasClass('ui-tabs-selected')) { o.selected = -1; if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { hideTab(el, $hide); }).dequeue("tabs"); this.blur(); return false; } else if (!$hide.length) { if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 this.blur(); return false; } } if (o.cookie) { self._cookie(o.selected, o.cookie); } // show new tab if ($show.length) { if ($hide.length) { self.element.queue("tabs", function() { hideTab(el, $hide); }); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); } else { throw 'jQuery UI Tabs: Mismatching fragment identifier.'; } // Prevent IE from keeping other link focussed when using the back button // and remove dotted border from clicked link. This is controlled via CSS // in modern browsers; blur() removes focus from address bar in Firefox // which can become a usability and annoying problem with tabs('rotate'). if ($.browser.msie) { this.blur(); } }); // disable click in any case this.anchors.bind('click.tabs', function(){return false;}); }, destroy: function() { var o = this.options; this.abort(); this.element.unbind('.tabs') .removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible') .removeData('tabs'); this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.anchors.each(function() { var href = $.data(this, 'href.tabs'); if (href) { this.href = href; } var $this = $(this).unbind('.tabs'); $.each(['href', 'load', 'cache'], function(i, prefix) { $this.removeData(prefix + '.tabs'); }); }); this.lis.unbind('.tabs').add(this.panels).each(function() { if ($.data(this, 'destroy.tabs')) { $(this).remove(); } else { $(this).removeClass([ 'ui-state-default', 'ui-corner-top', 'ui-tabs-selected', 'ui-state-active', 'ui-state-hover', 'ui-state-focus', 'ui-state-disabled', 'ui-tabs-panel', 'ui-widget-content', 'ui-corner-bottom', 'ui-tabs-hide' ].join(' ')); } }); if (o.cookie) { this._cookie(null, o.cookie); } }, add: function(url, label, index) { if (index === undefined) { index = this.anchors.length; // append by default } var self = this, o = this.options, $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)), id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]); $li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true); // try to find an existing element before creating a new one var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true); } $panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide'); if (index >= this.lis.length) { $li.appendTo(this.list); $panel.appendTo(this.list[0].parentNode); } else { $li.insertBefore(this.lis[index]); $panel.insertBefore(this.panels[index]); } o.disabled = $.map(o.disabled, function(n, i) { return n >= index ? ++n : n; }); this._tabify(); if (this.anchors.length == 1) { // after tabify $li.addClass('ui-tabs-selected ui-state-active'); $panel.removeClass('ui-tabs-hide'); this.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[0], self.panels[0])); }); this.load(0); } // callback this._trigger('add', null, this._ui(this.anchors[index], this.panels[index])); }, remove: function(index) { var o = this.options, $li = this.lis.eq(index).remove(), $panel = this.panels.eq(index).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) { this.select(index + (index + 1 < this.anchors.length ? 1 : -1)); } o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }), function(n, i) { return n >= index ? --n : n; }); this._tabify(); // callback this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0])); }, enable: function(index) { var o = this.options; if ($.inArray(index, o.disabled) == -1) { return; } this.lis.eq(index).removeClass('ui-state-disabled'); o.disabled = $.grep(o.disabled, function(n, i) { return n != index; }); // callback this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index])); }, disable: function(index) { var self = this, o = this.options; if (index != o.selected) { // cannot disable already selected tab this.lis.eq(index).addClass('ui-state-disabled'); o.disabled.push(index); o.disabled.sort(); // callback this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index])); } }, select: function(index) { if (typeof index == 'string') { index = this.anchors.index(this.anchors.filter('[href$=' + index + ']')); } else if (index === null) { // usage of null is deprecated, TODO remove in next release index = -1; } if (index == -1 && this.options.collapsible) { index = this.options.selected; } this.anchors.eq(index).trigger(this.options.event + '.tabs'); }, load: function(index) { var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs'); this.abort(); // not remote or from cache if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) { this.element.dequeue("tabs"); return; } // load remote from here on this.lis.eq(index).addClass('ui-state-processing'); if (o.spinner) { var span = $('span', a); span.data('label.tabs', span.html()).html(o.spinner); } this.xhr = $.ajax($.extend({}, o.ajaxOptions, { url: url, success: function(r, s) { $(self._sanitizeSelector(a.hash)).html(r); // take care of tab labels self._cleanup(); if (o.cache) { $.data(a, 'cache.tabs', true); // if loaded once do not load them again } // callbacks self._trigger('load', null, self._ui(self.anchors[index], self.panels[index])); try { o.ajaxOptions.success(r, s); } catch (e) {} // last, so that load event is fired before show... self.element.dequeue("tabs"); } })); }, abort: function() { // stop possibly running animations this.element.queue([]); this.panels.stop(false, true); // terminate pending requests from other tabs if (this.xhr) { this.xhr.abort(); delete this.xhr; } // take care of tab labels this._cleanup(); }, url: function(index, url) { this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url); }, length: function() { return this.anchors.length; } }); $.extend($.ui.tabs, { version: '1.7.2', getter: 'length', defaults: { ajaxOptions: null, cache: false, cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } collapsible: false, disabled: [], event: 'click', fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 } idPrefix: 'ui-tabs-', panelTemplate: '<div></div>', spinner: '<em>Loading&#8230;</em>', tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>' } }); /* * Tabs Extensions */ /* * Rotate */ $.extend($.ui.tabs.prototype, { rotation: null, rotate: function(ms, continuing) { var self = this, o = this.options; var rotate = self._rotate || (self._rotate = function(e) { clearTimeout(self.rotation); self.rotation = setTimeout(function() { var t = o.selected; self.select( ++t < self.anchors.length ? t : 0 ); }, ms); if (e) { e.stopPropagation(); } }); var stop = self._unrotate || (self._unrotate = !continuing ? function(e) { if (e.clientX) { // in case of a true click self.rotate(null); } } : function(e) { t = o.selected; rotate(); }); // start rotation if (ms) { this.element.bind('tabsshow', rotate); this.anchors.bind(o.event + '.tabs', stop); rotate(); } // stop rotation else { clearTimeout(self.rotation); this.element.unbind('tabsshow', rotate); this.anchors.unbind(o.event + '.tabs', stop); delete this._rotate; delete this._unrotate; } } }); })(jQuery);
nazar/wasters
public/javascripts/jquery/ui/tabs.js
JavaScript
mit
32,986
//@flow var x = 42; x = "true"; var y = 42; if (x) { y = "hello world"; } (42: string); // should still have some errors!
mroch/flow
tests/constrain_writes_dir/excluded/test.js
JavaScript
mit
127
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let BeachAccess = props => <SvgIcon {...props}> <path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z" /> </SvgIcon>; BeachAccess = pure(BeachAccess); BeachAccess.muiName = 'SvgIcon'; export default BeachAccess;
AndriusBil/material-ui
packages/material-ui-icons/src/BeachAccess.js
JavaScript
mit
579
/* A proxy for observing object state changes. var obj={person:'Eddie',age:22}; _o.onUpdate(obj,{ age:function(value){ if(value>this.oldValue) console.log('Happy birthday, Peter!') }, person:function(value){ console.log(this.oldValue+' is now '+value); } }); _o(obj).person='Peter'; //> Eddie is now Peter _o(obj).age++; //> Happy birthday, Peter! */ !function(){ 'use strict'; var tl=function(i,ln,ms){ return function(ms,f){ i++; if(f()) ln='info',ms='Test '+i+' passed: '+ms; else ln='error',ms='Test '+i+' failed: '+ms; console[ln](ms)}}(0); var cl=function(){ console.log.apply(console,arguments)}; var observingProxy=function(targetStack,proxyStack,changeStack,handlerStack,timeoutStack){ function getDeepPropertyDescriptors(o) { var ns; if(o){ ns=getDeepPropertyDescriptors(Object.getPrototypeOf(o))||[]; Array.prototype.push.apply(ns, Object.getOwnPropertyNames(o) .filter(function(k){ return isNaN(parseInt(k))}) .map(function(k){ return {name:k,descriptor:Object.getOwnPropertyDescriptor(o,k)}})); } return ns; } function newProxy(t) { var p={},ns=getDeepPropertyDescriptors(t); for(var i=ns.length;i--;){ delete ns[i].descriptor.value; delete ns[i].descriptor.writable; ns[i].descriptor.get=propertyGetter.bind({target:t,name:ns[i].name}); ns[i].descriptor.set=propertySetter.bind({target:t,name:ns[i].name}); try{ Object.defineProperty(p,ns[i].name,ns[i].descriptor); } catch(e){} } return p; } function notifyObservers(target) { var targetInd=targetIndex(target); if(changeStack[targetInd].length){ for(var l=0;l<handlerStack[targetInd].length;l++) handlerStack[targetInd][l].call({},changeStack[targetInd]); changeStack[targetInd]=[]; } } function propertyGetter() { var r=this.target[this.name]; if(Array.isArray(this.target)&&['pop','push','shift','splice','unshift']. indexOf(this.name)>-1) r=function(){ var res=this.target[this.name].apply(this.target,arguments), targetInd=targetIndex(this.target); changeStack[targetInd].push(({ 'pop':{object:this.target,type:'splice',index:this.target.length-1, removed:[res],addedCount:0}, 'push':{object:this.target,type:'splice',index:this.target.length-1, removed:[],addedCount:1}, 'shift':{object:this.target,type:'splice',index:0,removed:[res], addedCount:0}, 'splice':{object:this.target,type:'splice',index:arguments[0], removed:res,addedCount:Array.prototype.slice.call(arguments,2).length}, 'unshift':{object:this.target,type:'splice',index:0,removed:[], addedCount:1} })[this.name]); clearTimeout(timeoutStack[targetInd]); timeoutStack[targetInd]=setTimeout(function(){ notifyObservers(this.target)}.bind(this)); }.bind(this); return r; } function propertySetter(userVal) { var val=this.target[this.name], targetInd=targetIndex(this.target); if(val!==userVal){ this.target[this.name]=userVal; changeStack[targetInd].push( {name:this.name,object:this.target,type:'update',oldValue:val}); clearTimeout(timeoutStack[targetInd]); timeoutStack[targetInd]=setTimeout(function(){ notifyObservers(this.target)}.bind(this)); } } function targetIndex(t) { var i=targetStack.indexOf(t); if(i===-1&&t){ i=targetStack.push(t)-1; proxyStack.push(newProxy(t)); changeStack.push([]); handlerStack.push([]); timeoutStack.push(0); } return i; } if(this.test_o) tl('getDeepPropertyDescriptors',function(){ return getDeepPropertyDescriptors([1,2,3]).reduce(function(hasPush,item){ return hasPush||item.name==='push'; },false)}); if(this.test_o) tl('Property getter',function(){ var s={p1:1}; return newProxy(s).p1===s.p1}); if(this.test_o) tl('Property setter',function(){ var s={p1:1}; newProxy(s).p1=2; return s.p1===2}); if(this.test_o) tl('Array splice',function(){ var s=[]; newProxy(s).push(1); return s.length===1}); return { addChangeHandler:function(target,changeHandler,callOnInit){ var targetInd=targetIndex(target); handlerStack[targetInd].indexOf(changeHandler)===-1&& handlerStack[targetInd].push(changeHandler); if(callOnInit){ var changes=Array.isArray(target) ?target.map(function(_,index){ return {object:target,type:'splice',index:index,removed:[], addedCount:1}}) :Object.getOwnPropertyNames(target).map(function(key){ return {name:key,object:target,type:'update',oldValue:target[key]} }); changeHandler.call({},changes); } }, getProxy:function(target){ return proxyStack[targetIndex(target)]||target; }, removeChangeHandler:function(target,changeHandler){ var targetInd=targetIndex(target),rmInd; if((rmInd=handlerStack[targetInd].indexOf(changeHandler))>-1) handlerStack[targetInd].splice(rmInd,1); else if(!changeHandler) handlerStack[targetInd]=[]; clearTimeout(timeoutStack[targetInd]); } } }.bind(this)([],[],[],[],[]); function _o(target) { return observingProxy.getProxy(target); } _o.observe=function(target,changeHandler,callOnInit){ if(!target) throw 'Observing proxy error: cannot _o.observe '+target+' object'; return observingProxy.addChangeHandler.apply(observingProxy,arguments); }; _o.unobserve=function(target,changeHandler){ if(!target) throw 'Observing proxy error: cannot _o.unobserve '+target+' object'; return observingProxy.removeChangeHandler.apply(observingProxy,arguments); }; _o.onUpdate=function(target,onChangeCollection,callOnInit){ var onPropertyChange; if(typeof onChangeCollection==='string'){ onChangeCollection={}; onChangeCollection[arguments[1]]=arguments[2]; callOnInit=arguments[3]; } callOnInit=callOnInit===undefined&&true||callOnInit; if(target) observingProxy.addChangeHandler(target,onPropertyChange=function(changes){ for(var key in onChangeCollection) for(var i=changes.length;i--;) if(changes[i].name===key&&changes[i].type==='update'){ onChangeCollection[key].call(changes[i],changes[i].object[changes[i].name]); break; } },callOnInit); return{ destroy:function(){ observingProxy.removeChangeHandler(target,onPropertyChange); }, report:function(){ if(!target) throw 'Observing proxy error: cannot _o.onUpdate '+target+' object'; }, restore:function(){ observingProxy.addChangeHandler(target,onPropertyChange,callOnInit); } }; }; if(typeof Object.defineProperty!=='function') throw 'Object.defineProperty is not a function'; if(this.exports&&this.module) this.module.exports=_o; else if(this.define&&this.define.amd) this.define(function(){return _o}); else this._o=_o; if(this.test_o) tl('getProxy',function(){ var s={p1:1}; return observingProxy.getProxy(s).p1===s.p1}); if(this.test_o) !function(){ var u; var s={p1:1}; observingProxy.addChangeHandler(s,function(changes){ clearTimeout(u); tl('addChangeHandler',function(){return true}); }); observingProxy.getProxy(s).p1=101; u=setTimeout(function(){ tl('addChangeHandler',function(){return false}); }); }(); if(this.test_o) !function(){ var u; var f=function(){ clearTimeout(u); tl('removeChangeHandler',function(){return false}); }; var s={p1:1}; observingProxy.addChangeHandler(s,f); observingProxy.removeChangeHandler(s,f); observingProxy.getProxy(s).p1=2; u=setTimeout(function(){ tl('removeChangeHandler',function(){return true}); }); }(); if(this.test_o) !function(){ var s={p1:1}; var u=setTimeout(function(){ tl('callOnInit',function(){return false}); }); observingProxy.addChangeHandler(s,function(changes){ clearTimeout(u); tl('callOnInit',function(){return true}); },true); }(); if(this.test_o) !function(){ var s={p1:0},proxy=observingProxy.getProxy(s),n=0; observingProxy.addChangeHandler(s,function(ch){ n++; }); for(var i=10;i--;) proxy.p1++; setTimeout(function(){ tl('Delayed notify',function(){return n===1}); }) }(); if(this.test_o) !function(){ var s={p1:1}; _o.onUpdate(s,'p1',function(value){ if(value===2){ clearTimeout(u); tl('onUpdateHandler',function(){return value===2}); } }); observingProxy.getProxy(s).p1=2; var u=setTimeout(function(){ tl('onUpdateHandler',function(){return false}); }); }(); if(this.test_o) !function(){ var s={p1:1},proxy=observingProxy.getProxy(s),i=0; var observer=_o.onUpdate(s,'p1',function(value){ i++; }); setTimeout(function(){ proxy.p1=2; setTimeout(function(){ observer.destroy(); proxy.p1=3; setTimeout(function(){ observer.restore(); proxy.p1=4; setTimeout(function(){ tl('onUpdateHandler destructor',function(){return i==4}); }); }); }); }); }(); }.bind(this)()
ytiurin/observingproxy
observing-proxy.js
JavaScript
mit
9,561
#define WINDOWS_PHONE #define SILVERLIGHT /* Copyright (C) 2008-2011, Bit Miracle * http://www.bitmiracle.com * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * */ /* * This file contains the JPEG system-independent memory management * routines. */ /* * About virtual array management: * * Full-image-sized buffers are handled as "virtual" arrays. The array is still accessed a strip at a * time, but the memory manager must save the whole array for repeated * accesses. * * The Access method is responsible for making a specific strip area accessible. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace BitMiracle.LibJpeg.Classic { /// <summary> /// JPEG virtual array. /// </summary> /// <typeparam name="T">The type of array's elements.</typeparam> /// <remarks>You can't create virtual array manually. For creation use methods /// <see cref="jpeg_common_struct.CreateSamplesArray"/> and /// <see cref="jpeg_common_struct.CreateBlocksArray"/>. /// </remarks> #if EXPOSE_LIBJPEG public #endif class jvirt_array<T> { internal delegate T[][] Allocator(int width, int height); private jpeg_common_struct m_cinfo; private T[][] m_buffer; /* => the in-memory buffer */ /// <summary> /// Request a virtual 2-D array /// </summary> /// <param name="width">Width of array</param> /// <param name="height">Total virtual array height</param> /// <param name="allocator">The allocator.</param> internal jvirt_array(int width, int height, Allocator allocator) { m_cinfo = null; m_buffer = allocator(width, height); Debug.Assert(m_buffer != null); } /// <summary> /// Gets or sets the error processor. /// </summary> /// <value>The error processor.<br/> /// Default value: <c>null</c> /// </value> /// <remarks>Uses only for calling /// <see cref="M:BitMiracle.LibJpeg.Classic.jpeg_common_struct.ERREXIT(BitMiracle.LibJpeg.Classic.J_MESSAGE_CODE)">jpeg_common_struct.ERREXIT</see> /// on error.</remarks> public jpeg_common_struct ErrorProcessor { get { return m_cinfo; } set { m_cinfo = value; } } /// <summary> /// Access the part of a virtual array. /// </summary> /// <param name="startRow">The first row in required block.</param> /// <param name="numberOfRows">The number of required rows.</param> /// <returns>The required part of virtual array.</returns> public T[][] Access(int startRow, int numberOfRows) { /* debugging check */ if (startRow + numberOfRows > m_buffer.Length) { if (m_cinfo != null) m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_BAD_VIRTUAL_ACCESS); else throw new InvalidOperationException("Bogus virtual array access"); } /* Return proper part of the buffer */ T[][] ret = new T[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) ret[i] = m_buffer[startRow + i]; return ret; } } }
wwqly12/Snaker
Assets/Plugins/Reign/Platforms/Shared/ImageTools/JPG/LibJpeg/Classic/jvirt_array.cs
C#
mit
3,478
<style> h2 { color:#464646; font-family:Georgia, "Times New Roman", "Bitstream Charter", Times, serif; font-size:24px; font-size-adjust:none; font-stretch:normal; font-style:italic; font-variant:normal; font-weight:normal; line-height:35px; margin:0; padding:14px 15px 3px 0; text-shadow:0 1px 0 #FFFFFF; } </style> <?php global $General; if($_REQUEST['user_id']) { include_once(TEMPLATEPATH . '/library/includes/affiliates/admin_affiliate_sale_report_detail.php'); }else { ?> <br /> <h2><?php _e(AFF_MEMBERS_PAGE_TITLE); ?></h2> <?php global $wpdb; $targetpage = get_option('siteurl').'/wp-admin/admin.php?page=affiliate_report'; $recordsperpage = 30; $pagination = $_REQUEST['pagination']; $total_pages = $wpdb->get_var("SELECT COUNT(u.ID) FROM $wpdb->users u,$wpdb->usermeta um WHERE um.user_id=u.ID and (um.meta_key='wp_capabilities' and um.meta_value like \"%affiliate%\")"); if($pagination == '') { $pagination = 1; } $strtlimit = ($pagination-1)*$recordsperpage; $endlimit = $strtlimit+$recordsperpage; $usersql = "select u.ID,u.user_login from $wpdb->users u ,$wpdb->usermeta um WHERE um.user_id=u.ID and (um.meta_key='wp_capabilities' and um.meta_value like \"%affiliate%\") order by user_login"; $userinfo = $wpdb->get_results($usersql); if($userinfo) { ?> <table width="100%" class="widefat post fixed" > <thead> <tr> <th class="title"><?php _e(AFF_USER_NAME_TEXT); ?> </th> <th class="title"><?php _e(AFF_TOTAL_SALES_AMOUNT_TEXT); ?> </th> <th class="title"><?php _e(AFF_TOTAL_SHARE_AMT_TEXT); ?> </th> </tr> <?php foreach($userinfo as $userinfoObj) { $user_role = get_usermeta($userinfoObj->ID,'wp_capabilities'); if($user_role['affiliate']) { $total_amt_array = get_total_share_amt($userinfoObj->ID); ?> <tr> <td class="row1" ><a href="<?php echo get_option('siteurl');?>/wp-admin/admin.php?page=affiliates_settings&user_id=<?php echo $userinfoObj->ID;?>"><?php echo $userinfoObj->user_login;?></a></td> <td class="row1" ><?php echo $General->get_amount_format($total_amt_array[1],0);?></td> <td class="row1" ><?php echo $General->get_amount_format($total_amt_array[0],0);?></td> </tr> <?php } } ?> <tr><td colspan="3" align="center"> <?php if($total_pages>$recordsperpage) { echo $General->get_pagination($targetpage,$total_pages,$recordsperpage,$pagination); } ?> </td></tr> </thead> </table> <?php } } function get_total_share_amt($user_id) { $user_affiliate_data = get_usermeta($user_id,'user_affiliate_data'); if($user_affiliate_data) { $order_amt_total = 0; $share_total = 0; $total_orders = 0; $product_qty = 0; foreach($user_affiliate_data as $key => $val) { $order_user_id = preg_replace('/(([_])[0-9]*)/','',$val['orderNumber']); $order_number = preg_replace('/([0-9]*([_]))/','',$val['orderNumber']); if(!is_array(get_usermeta($order_user_id,'user_order_info'))) { $user_order_info = unserialize(get_usermeta($order_user_id,'user_order_info')); }else { $user_order_info = get_usermeta($order_user_id,'user_order_info'); } $order_info1 = $user_order_info[$order_number-1][0]; $cart_info = $order_info1['cart_info']['cart_info']; $order_info = $order_info1['order_info']; if($order_info['order_status'] == 'approve') { $total_orders++; $order_amount = $val['order_amt'] - $order_info['discount_amt']; if($val['share_amt']>0) { $share_amt = ($order_amount*$val['share_amt'])/100; } $share_total = $share_total + $share_amt; $order_amt_total = $order_amt_total + $order_amount; for($c=0;$c<count($cart_info);$c++) { $product_qty = $product_qty + $cart_info[$c]['product_qty']; } } } } return array($share_total,$order_amt_total,$total_orders,$product_qty); } ?>
iamandrebulatov/Profile
Post-Hack/2/public_html/thinkinglimoCOM/wp-content/themes/Store/library/includes/affiliates/admin_affiliates_report.php
PHP
mit
3,914
import { Context } from '../../../src/context/Context'; describe('Context', () => { describe('Response', () => { it('should return the response object', () => { const res: any = 1; const context = new Context(undefined, res, undefined, undefined); expect(context.Response).toBe(1); }); }); describe('Request', () => { it('should return the request object', () => { const req: any = 1; const context = new Context(req, undefined, undefined, undefined); expect(context.Request).toBe(1); }); }); describe('Services', () => { it('should return the repositories object', () => { const services: any = 1; const context = new Context(undefined, undefined, undefined, services); expect(context.Services).toBe(1); }); }); describe('DataLoaders', () => { it('should return the dataLoaders object', () => { const dataLoaders: any = 1; const context = new Context(undefined, undefined, dataLoaders, undefined); expect(context.DataLoaders).toBe(1); }); }); describe('hasUserRoles', () => { it('should return the dataLoaders object', () => { const req: any = { acceptsLanguages: () => 'de' }; const context = new Context(req, undefined, undefined, undefined); expect(context.getLanguage()).toBe('de'); }); }); describe('hasUserRoles', () => { it('should return the request object', () => { const context = new Context(undefined, undefined, undefined, undefined); expect(context.hasUserRoles([])).toBeTruthy(); }); }); });
w3tecch/express-graphql-typescript-boilerplate
test/unit/context/context.spec.ts
TypeScript
mit
1,786
from .base import DerivedType from categorical import CategoricalComparator from .categorical_type import CategoricalType class ExistsType(CategoricalType) : type = "Exists" _predicate_functions = [] def __init__(self, definition) : super(CategoricalType, self ).__init__(definition) self.cat_comparator = CategoricalComparator([0,1]) self.higher_vars = [] for higher_var in self.cat_comparator.dummy_names : dummy_var = DerivedType({'name' : higher_var, 'type' : 'Dummy', 'has missing' : self.has_missing}) self.higher_vars.append(dummy_var) def comparator(self, field_1, field_2) : if field_1 and field_2 : return self.cat_comparator(1, 1) elif field_1 or field_2 : return self.cat_comparator(0, 1) else : return self.cat_comparator(0, 0) # This flag tells fieldDistances in dedupe.core to pass # missing values (None) into the comparator comparator.missing = True
tfmorris/dedupe
dedupe/variables/exists.py
Python
mit
1,117
using System; namespace Cooking.CookingProducts { public abstract class Vegetable { public Vegetable() { this.IsRotten = false; this.IsPeeled = false; this.IsCut = false; this.IsCooked = false; } public bool IsRotten { get; set; } public bool IsPeeled { get; set; } public bool IsCut { get; set; } public bool IsCooked { get; set; } public void Cut() { this.IsCut = true; } public void Peel() { this.IsPeeled = true; } public void Cook() { this.IsCooked = true; } public override string ToString() { string name = this.GetType().Name; string isPeeled = this.IsPeeled ? "peeled" : "not peeled"; string isCut = this.IsCut ? "cut" : "not cut"; return string.Format("{0}/{1}/{2}", name, isPeeled, isCut); } } }
studware/Ange-Git
MyTelerikAcademyHomeWorks/HighQualityCode/HW6.ControlFlow-ConditionalStatements-And-Loops/HW6.CtrlFlowConditionalStatementsAndLoops/Cooking/CookingProducts/Vegetable.cs
C#
mit
1,016
import sys, os import pickle import nltk import paths from utils import * def words_to_dict(words): return dict(zip(words, range(0, len(words)))) nltk.data.path.append(paths.nltk_data_path) use_wordnet = True if use_wordnet: stemmer = nltk.stem.wordnet.WordNetLemmatizer() stem = stemmer.lemmatize else: stemmer = nltk.stem.porter.PorterStemmer() stem = stemmer.stem def tokens(text): replacements = [("---"," "), ("--"," "), ("-", "")] # trying to capture multi-word keywords for (src,tgt) in replacements: text = text.replace(src,tgt) return preprocess(text) def make_bow(doc,d): bow = {} for word in doc: if word in d: wordid = d[word] bow[wordid] = bow.get(wordid,0) + 1 # XXX we should notify something about non-stopwords that we couldn't parse return bow modes = ["fulltext","abstracts"] ks = ["20","50","100","200"] dist = ["kl","euclidean"] if __name__ == '__main__': args = sys.argv[1:] mode = modes[0] k = ks[0] dfun = dist[0] num = 20 while len(args) > 1: if args[0] == "-k": if args[1] in ks: k = args[1] args = args[2:] if args[0] in ["-m","--mode"]: if args[1] in modes: mode = args[1] args = args[2:] if args[0] in ["-n","--num"]: if int(args[1]) in range(1,50): num = int(args[1]) args = args[2:] if args[0] in ["-d","--distance"]: if args[1] in dist: dfun = args[1] args = args[2:] model = os.path.join(mode,"lda" + k,"final") words = os.path.join(mode,"vocab.dat") docs = os.path.join(mode,"docs.dat") pdf_file = args[0] (base,_) = os.path.splitext(pdf_file) text = os.popen("/usr/bin/pdftotext \"%s\" -" % pdf_file).read() # XXX safe filenames! vocab = words_to_dict(open(words).read().split()) bow = make_bow(map(stem,tokens(text)),vocab) dat_file = base + ".dat" out = open(dat_file,"w") out.write(str(len(bow))) out.write(' ') for term in bow: out.write(str(term)) out.write(':') out.write(str(bow[term])) out.write(' ') out.write('\n') out.close() log = base + ".log" os.system(paths.lda + " inf settings.txt %s %s %s >%s 2>&1" % (model,dat_file,base,log)) # XXX capture output, handle errors inf = read(base + "-gamma.dat") gammas = read(model + ".gamma") papers = zip(read(docs), map(lambda s: map(float,s.split()), gammas)) tgt = ["INPUT PDF"] + map(lambda s: map(float,s.split()), inf) # XXX these are the topic values, if we want to visualize them # XXX be careful to not leak our filenames if dfun == "euclidean": metric = distance fmt = '%d' elif dfun == "kl": metric = kl_divergence fmt = '%f' else: metric = kl_divergence fmt = '%f' papers = map(lambda s: (metric(s[1],tgt[1]),s), papers) papers.sort(lambda x,y: cmp(x[0],y[0])) print "\nRelated papers:\n" for (d,(doc,gs)) in papers[0:num]: print (' %s (' + fmt + ')') % (doc,d)
mgree/tmpl
www/backend/infer.py
Python
mit
3,314
<?php /* User Data Access Object * This class provides functionality to retrieve values and * pieces of data that are specifically involved with the * user objects. * */ require_once __DIR__.'./../conf.php'; require_once __DIR__.'/Database.php'; require_once BASE_INCLUDE . '/models/User.php'; class UserDAO extends Database{ public $user = NULL; /* Might throw a UnknownUserException */ public function __load_user( $user_id ){ $this->user = $this->user_exist($user_id); } } ?>
EdgeCaseBerg/green-web
dash-auth/db/UserDAO.php
PHP
mit
495
#include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("logicoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("logicoin://")) { uri.replace(0, 11, "logicoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "LogiCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "logicoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=LogiCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("LogiCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " logicoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("LogiCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
whatevercode/logicoin
src/qt/guiutil.cpp
C++
mit
16,271
"""calibrated_image.py was written by Ryan Petersburg for use with fiber characterization on the EXtreme PREcision Spectrograph """ import numpy as np from .base_image import BaseImage from .numpy_array_handler import filter_image, subframe_image class CalibratedImage(BaseImage): """Fiber face image analysis class Class that contains calibration images and executes corrections based on those images Attributes ---------- dark : str, array_like, or None The input used to set the dark image. See BaseImage.convert_image_to_array() for details ambient : str, array_like, or None The input used to set the ambient image. See BaseImage.convert_image_to_array() for details flat : str, array_like, or None The input used to set the flat image. See BaseImage.convert_image_to_array() for details kernel_size : int (odd) The kernel side length used when filtering the image. This value may need to be tweaked, especially with few co-added images, due to random noise. The filtered image is used for the centering algorithms, so for a "true test" use kernel_size=1, but be careful, because this may lead to needing a fairly high threshold for the noise. new_calibration : bool Whether or not self.calibration has been set with new images Args ---- image_input : str, array_like, or None, optional See BaseImage class for details dark : str, array_like, or None, optional Image input to instantiate BaseImage for dark image ambient : str, array_like, or None, optional Image input to instantiate BaseImage for ambient image flat : str, array_like, or None, optional Image input to instantiate BaseImage for flat image kernel_size : int (odd), optional Set the kernel size for filtering **kwargs : keworded arguments Passed into the BaseImage superclass """ def __init__(self, image_input, dark=None, ambient=None, flat=None, kernel_size=9, **kwargs): self.dark = dark self.ambient = ambient self.flat = flat self.kernel_size = kernel_size self.new_calibration = True super(CalibratedImage, self).__init__(image_input, **kwargs) #=========================================================================# #==== Primary Image Getters ==============================================# #=========================================================================# def get_uncorrected_image(self): """Return the raw image without corrections or filtering. Returns ------- uncorrected_image : 2D numpy array Raw image or average of images (depending on image_input) """ return self.convert_image_to_array(self.image_input) def get_image(self): """Return the corrected image This method must be called to get access to the corrected 2D numpy array being analyzed. Attempts to access a previously saved image under self.image_file or otherwise applies corrections to the raw images pulled from their respective files Returns ------- image : 2D numpy array Image corrected by calibration images """ if self.image_file is not None and not self.new_calibration: return self.image_from_file(self.image_file) return self.execute_error_corrections(self.get_uncorrected_image()) def get_uncorrected_filtered_image(self, kernel_size=None, **kwargs): """Return a median filtered image Args ---- kernel_size : {None, int (odd)}, optional The side length of the kernel used to median filter the image. Uses self.kernel_size if None. Returns ------- filtered_image : 2D numpy array The stored image median filtered with the given kernel_size """ image = self.get_uncorrected_image() if image is None: return None if kernel_size is None: kernel_size = self.kernel_size return filter_image(image, kernel_size, **kwargs) def get_filtered_image(self, kernel_size=None, **kwargs): """Return an error corrected and median filtered image Returns ------- filtered_image : 2D numpy array The stored image median filtered with the given kernel_size and error corrected using the given method """ image = self.get_image() if image is None: return None if kernel_size is None: kernel_size = self.kernel_size return filter_image(image, kernel_size, **kwargs) #=========================================================================# #==== Calibration Image Getters ==========================================# #=========================================================================# def get_dark_image(self): """Returns the dark image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """ return BaseImage(self.dark).get_image() def get_ambient_image(self): """Returns the ambient image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """ return CalibratedImage(self.ambient, dark=self.dark).get_image() def get_flat_image(self): """Returns the flat image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """ return CalibratedImage(self.flat, dark=self.dark).get_image() def set_dark(self, dark): """Sets the dark calibration image.""" self.dark = dark self.new_calibration = True def set_ambient(self, ambient): """Sets the ambient calibration image.""" self.ambient = ambient self.new_calibration = True def set_flat(self, flat): """Sets the flat calibration images.""" self.flat = flat self.new_calibration = True #=========================================================================# #==== Image Calibration Algorithm ========================================# #=========================================================================# def execute_error_corrections(self, image): """Applies corrective images to image Applies dark image to the flat field and ambient images. Then applies flat field and ambient image correction to the primary image Args ---- image : 2D numpy array Image to be corrected Returns ------- corrected_image : 2D numpy array Corrected image """ if image is None: return None corrected_image = image dark_image = self.get_dark_image() if dark_image is not None and dark_image.shape != corrected_image.shape: dark_image = subframe_image(dark_image, self.subframe_x, self.subframe_y, self.width, self.height) corrected_image = self.remove_dark_image(corrected_image, dark_image) ambient_image = self.get_ambient_image() if ambient_image is not None: if ambient_image.shape != corrected_image.shape: ambient_image = subframe_image(ambient_image, self.subframe_x, self.subframe_y, self.width, self.height) ambient_exp_time = BaseImage(self.ambient).exp_time if self.exp_time is not None and ambient_exp_time != self.exp_time: corrected_image = self.remove_dark_image(corrected_image, ambient_image * self.exp_time / ambient_exp_time) else: corrected_image = self.remove_dark_image(corrected_image, ambient_image) flat_image = self.get_flat_image() if flat_image is not None: if flat_image.shape != corrected_image.shape: flat_image = subframe_image(flat_image, self.subframe_x, self.subframe_y, self.width, self.height) corrected_image *= flat_image.mean() / flat_image self.new_calibration = False return corrected_image def remove_dark_image(self, image, dark_image=None): """Uses dark image to correct image Args ---- image : 2D numpy array numpy array of the image dark_image : 2D numpy array dark image to be removed Returns ------- output_array : 2D numpy array corrected image """ if dark_image is None: dark_image = self.get_dark_image() if dark_image is None: dark_image = np.zeros_like(image) output_image = image - dark_image # Renormalize to the approximate smallest value (avoiding hot pixels) output_image -= filter_image(output_image, 5).min() # Prevent any dark/ambient image hot pixels from leaking through output_image *= (output_image > -1000.0).astype('uint8') return output_image #=========================================================================# #==== Attribute Setters ==================================================# #=========================================================================# def set_attributes_from_object(self, object_file): super(CalibratedImage, self).set_attributes_from_object(object_file) self.dark = self.change_path(self.dark) self.ambient = self.change_path(self.ambient) self.flat = self.change_path(self.flat)
rpetersburg/fiber_properties
fiber_properties/calibrated_image.py
Python
mit
11,258
# frozen_string_literal: true # Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum, this matches the default thread size of Active Record. # threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }.to_i threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests, default is # 3000. # port ENV.fetch('PORT') { 3000 } # Specifies the `environment` that Puma will run in. # environment ENV.fetch('RAILS_ENV') { 'development' } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked webserver processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). # # workers ENV.fetch("WEB_CONCURRENCY") { 2 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write # process behavior so workers use less memory. If you use this option # you need to make sure to reconnect any threads in the `on_worker_boot` # block. # # preload_app! # The code in the `on_worker_boot` will be called if you are using # clustered mode by specifying a number of `workers`. After each worker # process is booted this block will be run, if you are using `preload_app!` # option you will want to use this block to reconnect to any threads # or connections that may have been created at application boot, Ruby # cannot share connections between processes. # # on_worker_boot do # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) # end # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart
wanganyv/cii-best-practices-badge
config/puma.rb
Ruby
mit
2,038
using Exrin.Abstraction; using Exrin.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TeslaDefinition.Interfaces.Model; using TeslaDefinition.Model; using Xamarin.Forms; namespace Tesla.ViewModel.MainTabs { public class ServiceVisualState : VisualState { public ServiceVisualState(IBaseModel model) : base(model) { } public IList<Booking> Bookings { get { return Get<IList<Booking>>(); } set { Set(value); } } public override void Init() { Task.Run(async () => { Bookings = await ServiceModel.GetBookings(); }); } public static AppLinkEntry GetAppLink(ServiceCentre centre) { var url = $"http://exrin.net/servicecentre/{centre.Id.ToString()}"; var entry = new AppLinkEntry { Title = "Service Centre", Description = centre.Name, AppLinkUri = new Uri(url, UriKind.RelativeOrAbsolute), IsLinkActive = true }; if (Device.OS == TargetPlatform.iOS) entry.Thumbnail = ImageSource.FromFile("logo.png"); entry.KeyValues.Add("contentType", "Service"); entry.KeyValues.Add("appName", "Tesla"); entry.KeyValues.Add("companyName", "Tesla"); return entry; } private IServiceModel ServiceModel { get { return base.Model as IServiceModel; } } } }
adamped/Tesla-Mobile-App
Tesla/Tesla/Tesla/ViewModel/MainTabs/ServiceVisualState.cs
C#
mit
1,507
<?php require_once __DIR__.'/../Base.php'; use Kanboard\Model\TaskFinder; use Kanboard\Model\TaskLink; use Kanboard\Model\TaskCreation; use Kanboard\Model\Project; class TaskLinkTest extends Base { // Check postgres issue: "Cardinality violation: 7 ERROR: more than one row returned by a subquery used as an expression" public function testGetTaskWithMultipleMilestoneLink() { $tf = new TaskFinder($this->container); $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 1, 'title' => 'B'))); $this->assertEquals(3, $tc->create(array('project_id' => 1, 'title' => 'C'))); $this->assertNotFalse($tl->create(1, 2, 9)); $this->assertNotFalse($tl->create(1, 3, 9)); $task = $tf->getExtendedQuery()->findOne(); $this->assertNotEmpty($task); } public function testCreateTaskLinkWithNoOpposite() { $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 1, 'title' => 'B'))); $this->assertEquals(1, $tl->create(1, 2, 1)); $links = $tl->getAll(1); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('relates to', $links[0]['label']); $this->assertEquals('B', $links[0]['title']); $this->assertEquals(2, $links[0]['task_id']); $this->assertEquals(1, $links[0]['is_active']); $links = $tl->getAll(2); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('relates to', $links[0]['label']); $this->assertEquals('A', $links[0]['title']); $this->assertEquals(1, $links[0]['task_id']); $this->assertEquals(1, $links[0]['is_active']); $task_link = $tl->getById(1); $this->assertNotEmpty($task_link); $this->assertEquals(1, $task_link['id']); $this->assertEquals(1, $task_link['task_id']); $this->assertEquals(2, $task_link['opposite_task_id']); $this->assertEquals(1, $task_link['link_id']); $opposite_task_link = $tl->getOppositeTaskLink($task_link); $this->assertNotEmpty($opposite_task_link); $this->assertEquals(2, $opposite_task_link['id']); $this->assertEquals(2, $opposite_task_link['task_id']); $this->assertEquals(1, $opposite_task_link['opposite_task_id']); $this->assertEquals(1, $opposite_task_link['link_id']); } public function testCreateTaskLinkWithOpposite() { $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 1, 'title' => 'B'))); $this->assertEquals(1, $tl->create(1, 2, 2)); $links = $tl->getAll(1); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('blocks', $links[0]['label']); $this->assertEquals('B', $links[0]['title']); $this->assertEquals(2, $links[0]['task_id']); $this->assertEquals(1, $links[0]['is_active']); $links = $tl->getAll(2); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('is blocked by', $links[0]['label']); $this->assertEquals('A', $links[0]['title']); $this->assertEquals(1, $links[0]['task_id']); $this->assertEquals(1, $links[0]['is_active']); $task_link = $tl->getById(1); $this->assertNotEmpty($task_link); $this->assertEquals(1, $task_link['id']); $this->assertEquals(1, $task_link['task_id']); $this->assertEquals(2, $task_link['opposite_task_id']); $this->assertEquals(2, $task_link['link_id']); $opposite_task_link = $tl->getOppositeTaskLink($task_link); $this->assertNotEmpty($opposite_task_link); $this->assertEquals(2, $opposite_task_link['id']); $this->assertEquals(2, $opposite_task_link['task_id']); $this->assertEquals(1, $opposite_task_link['opposite_task_id']); $this->assertEquals(3, $opposite_task_link['link_id']); } public function testGroupByLabel() { $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 1, 'title' => 'B'))); $this->assertEquals(3, $tc->create(array('project_id' => 1, 'title' => 'C'))); $this->assertNotFalse($tl->create(1, 2, 2)); $this->assertNotFalse($tl->create(1, 3, 2)); $links = $tl->getAllGroupedByLabel(1); $this->assertCount(1, $links); $this->assertArrayHasKey('blocks', $links); $this->assertCount(2, $links['blocks']); $this->assertEquals('test', $links['blocks'][0]['project_name']); $this->assertEquals('Backlog', $links['blocks'][0]['column_title']); $this->assertEquals('blocks', $links['blocks'][0]['label']); } public function testUpdate() { $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test1'))); $this->assertEquals(2, $p->create(array('name' => 'test2'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 2, 'title' => 'B'))); $this->assertEquals(3, $tc->create(array('project_id' => 1, 'title' => 'C'))); $this->assertEquals(1, $tl->create(1, 2, 5)); $this->assertTrue($tl->update(1, 1, 3, 11)); $links = $tl->getAll(1); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('is fixed by', $links[0]['label']); $this->assertEquals('C', $links[0]['title']); $this->assertEquals(3, $links[0]['task_id']); $links = $tl->getAll(2); $this->assertEmpty($links); $links = $tl->getAll(3); $this->assertNotEmpty($links); $this->assertCount(1, $links); $this->assertEquals('fixes', $links[0]['label']); $this->assertEquals('A', $links[0]['title']); $this->assertEquals(1, $links[0]['task_id']); } public function testRemove() { $tl = new TaskLink($this->container); $p = new Project($this->container); $tc = new TaskCreation($this->container); $this->assertEquals(1, $p->create(array('name' => 'test'))); $this->assertEquals(1, $tc->create(array('project_id' => 1, 'title' => 'A'))); $this->assertEquals(2, $tc->create(array('project_id' => 1, 'title' => 'B'))); $this->assertEquals(1, $tl->create(1, 2, 2)); $links = $tl->getAll(1); $this->assertNotEmpty($links); $links = $tl->getAll(2); $this->assertNotEmpty($links); $this->assertTrue($tl->remove($links[0]['id'])); $links = $tl->getAll(1); $this->assertEmpty($links); $links = $tl->getAll(2); $this->assertEmpty($links); } }
mcorteel/kanboard
tests/units/Model/TaskLinkTest.php
PHP
mit
8,050
{ var x = f; x = items[0]; x = items[1]; }
stas-vilchik/bdd-ml
data/2043.js
JavaScript
mit
49
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.io.IOException; import java.util.*; import java.util.List; import javax.activation.*; import javax.swing.*; import javax.swing.table.*; public final class MainPanel extends JPanel { private final TransferHandler handler = new TableRowTransferHandler(); private final String[] columnNames = {"String", "Integer", "Boolean"}; private final Object[][] data = { {"AAA", 12, true}, {"aaa", 1, false}, {"BBB", 13, true}, {"bbb", 2, false}, {"CCC", 15, true}, {"ccc", 3, false}, {"DDD", 17, true}, {"ddd", 4, false}, {"EEE", 18, true}, {"eee", 5, false}, {"FFF", 19, true}, {"fff", 6, false}, {"GGG", 92, true}, {"ggg", 0, false} }; private final DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { // ArrayIndexOutOfBoundsException: 0 >= 0 // Bug ID: JDK-6967479 JTable sorter fires even if the model is empty // http://bugs.java.com/view_bug.do?bug_id=6967479 //return getValueAt(0, column).getClass(); switch (column) { case 0: return String.class; case 1: return Number.class; case 2: return Boolean.class; default: return super.getColumnClass(column); } } }; private final JTable table = new JTable(model); public MainPanel() { super(new BorderLayout()); table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setTransferHandler(handler); table.setDropMode(DropMode.INSERT_ROWS); table.setDragEnabled(true); table.setFillsViewportHeight(true); //table.setAutoCreateRowSorter(true); //XXX //Disable row Cut, Copy, Paste ActionMap map = table.getActionMap(); AbstractAction dummy = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { /* Dummy action */ } }; map.put(TransferHandler.getCutAction().getValue(Action.NAME), dummy); map.put(TransferHandler.getCopyAction().getValue(Action.NAME), dummy); map.put(TransferHandler.getPasteAction().getValue(Action.NAME), dummy); JPanel p = new JPanel(new BorderLayout()); p.add(new JScrollPane(table)); p.setBorder(BorderFactory.createTitledBorder("Drag & Drop JTable")); add(p); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } //Demo - BasicDnD (Drag and Drop and Data Transfer)>http://docs.oracle.com/javase/tutorial/uiswing/dnd/basicdemo.html class TableRowTransferHandler extends TransferHandler { private final DataFlavor localObjectFlavor; private int[] indices; private int addIndex = -1; //Location where items were added private int addCount; //Number of items added. public TableRowTransferHandler() { super(); localObjectFlavor = new ActivationDataFlavor(Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items"); } @Override protected Transferable createTransferable(JComponent c) { JTable table = (JTable) c; DefaultTableModel model = (DefaultTableModel) table.getModel(); List<Object> list = new ArrayList<>(); indices = table.getSelectedRows(); for (int i: indices) { list.add(model.getDataVector().get(i)); } Object[] transferedObjects = list.toArray(); return new DataHandler(transferedObjects, localObjectFlavor.getMimeType()); } @Override public boolean canImport(TransferSupport info) { JTable table = (JTable) info.getComponent(); boolean isDropable = info.isDrop() && info.isDataFlavorSupported(localObjectFlavor); //XXX bug? table.setCursor(isDropable ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop); return isDropable; } @Override public int getSourceActions(JComponent c) { return MOVE; //TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport info) { if (!canImport(info)) { return false; } TransferHandler.DropLocation tdl = info.getDropLocation(); if (!(tdl instanceof JTable.DropLocation)) { return false; } JTable.DropLocation dl = (JTable.DropLocation) tdl; JTable target = (JTable) info.getComponent(); DefaultTableModel model = (DefaultTableModel) target.getModel(); int index = dl.getRow(); //boolean insert = dl.isInsert(); int max = model.getRowCount(); if (index < 0 || index > max) { index = max; } addIndex = index; target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); try { Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor); addCount = values.length; for (int i = 0; i < values.length; i++) { int idx = index++; model.insertRow(idx, (Vector) values[i]); target.getSelectionModel().addSelectionInterval(idx, idx); } return true; } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } return false; } @Override protected void exportDone(JComponent c, Transferable data, int action) { cleanup(c, action == MOVE); } private void cleanup(JComponent c, boolean remove) { if (remove && indices != null) { c.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); DefaultTableModel model = (DefaultTableModel) ((JTable) c).getModel(); if (addCount > 0) { for (int i = 0; i < indices.length; i++) { if (indices[i] >= addIndex) { indices[i] += addCount; } } } for (int i = indices.length - 1; i >= 0; i--) { model.removeRow(indices[i]); } } indices = null; addCount = 0; addIndex = -1; } }
mhcrnl/java-swing-tips
DnDReorderTable/src/java/example/MainPanel.java
Java
mit
7,343
import xhr from './lib/xhr'; class ShowsModel { constructor() { this.shows = []; } fetch(cb) { xhr('https://raw.githubusercontent.com/dashersw/erste.js-demo/master/src/static/data/shows.json', (err, data) => { this.shows = data.slice(0, 20); cb(this.shows); }); }; } export default new ShowsModel();
korayguney/veteranteam_project
src/shows-model.js
JavaScript
mit
368
module Vagrant class VM include Vagrant::Util attr_reader :env attr_reader :name attr_reader :vm class << self # Finds a virtual machine by a given UUID and either returns # a Vagrant::VM object or returns nil. def find(uuid, env=nil, name=nil) vm = VirtualBox::VM.find(uuid) new(:vm => vm, :env => env, :name => name) end end def initialize(opts=nil) defaults = { :vm => nil, :env => nil, :name => nil } opts = defaults.merge(opts || {}) @vm = opts[:vm] @name = opts[:name] if !opts[:env].nil? # We have an environment, so we create a new child environment # specifically for this VM. This step will load any custom # config and such. @env = Vagrant::Environment.new({ :cwd => opts[:env].cwd, :parent => opts[:env], :vm => self }).load! # Load the associated system. load_system! end @loaded_system_distro = false end # Loads the system associated with the VM. The system class is # responsible for OS-specific functionality. More information # can be found by reading the documentation on {Vagrant::Systems::Base}. # # **This method should never be called manually.** def load_system!(system=nil) system ||= env.config.vm.system env.logger.info("vm: #{name}") { "Loading system: #{system}" } if system.is_a?(Class) raise Errors::VMSystemError, :_key => :invalid_class, :system => system.to_s if !(system <= Systems::Base) @system = system.new(self) elsif system.is_a?(Symbol) # Hard-coded internal systems mapping = { :debian => Systems::Debian, :ubuntu => Systems::Ubuntu, :freebsd => Systems::FreeBSD, :gentoo => Systems::Gentoo, :redhat => Systems::Redhat, :suse => Systems::Suse, :linux => Systems::Linux, :solaris => Systems::Solaris, :arch => Systems::Arch } raise Errors::VMSystemError, :_key => :unknown_type, :system => system.to_s if !mapping.has_key?(system) @system = mapping[system].new(self) else raise Errors::VMSystemError, :unspecified end end # Returns the system for this VM, loading the distro of the system if # we can. def system if !@loaded_system_distro && created? && vm.running? # Load the system distro for the first time result = @system.distro_dispatch load_system!(result) @loaded_system_distro = true end @system end # Access the {Vagrant::SSH} object associated with this VM. # On the initial call, this will initialize the object. On # subsequent calls it will reuse the existing object. def ssh @ssh ||= SSH.new(env) end # Returns a boolean true if the VM has been created, otherwise # returns false. # # @return [Boolean] def created? !vm.nil? end # Sets the currently active VM for this VM. If the VM is a valid, # created virtual machine, then it will also update the local data # to persist the VM. Otherwise, it will remove itself from the # local data (if it exists). def vm=(value) @vm = value env.local_data[:active] ||= {} if value && value.uuid env.local_data[:active][name.to_s] = value.uuid else env.local_data[:active].delete(name.to_s) end # Commit the local data so that the next time vagrant is initialized, # it realizes the VM exists env.local_data.commit end def uuid vm ? vm.uuid : nil end def reload! @vm = VirtualBox::VM.find(@vm.uuid) end def package(options=nil) env.actions.run(:package, { "validate" => false }.merge(options || {})) end def up(options=nil) env.actions.run(:up, options) end def start(options=nil) return if @vm.running? return resume if @vm.saved? env.actions.run(:start, options) end def halt(options=nil) env.actions.run(:halt, options) end def reload env.actions.run(:reload) end def provision env.actions.run(:provision) end def destroy env.actions.run(:destroy) end def suspend env.actions.run(:suspend) end def resume env.actions.run(:resume) end def saved? @vm.saved? end def powered_off?; @vm.powered_off? end end end
simonsd/vagrant
lib/vagrant/vm.rb
Ruby
mit
4,595