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
# encoding: utf-8 require 'spec_helper' describe Optimizer::Algebra::Projection::ExtensionOperand, '#optimizable?' do subject { object.optimizable? } let(:header) { Relation::Header.coerce([[:id, Integer], [:name, String], [:age, Integer]]) } let(:base) { Relation.new(header, LazyEnumerable.new([[1, 'Dan Kubb', 35]])) } let(:relation) { operand.project([:id, :name]) } let(:object) { described_class.new(relation) } before do expect(object.operation).to be_kind_of(Algebra::Projection) end context 'when the operand is an extension, and the extended attribtue is removed ' do let(:operand) { base.extend { |r| r.add(:active, true) } } it { should be(true) } end context 'when the operand is an extension, and the extended attribtue is not removed ' do let(:operand) { base.extend { |r| r.add(:active, true) } } let(:relation) { operand.project([:id, :name, :active]) } it { should be(false) } end context 'when the operand is not an extension' do let(:operand) { base } it { should be(false) } end end
dkubb/axiom-optimizer
spec/unit/axiom/optimizer/algebra/projection/extension_operand/optimizable_predicate_spec.rb
Ruby
mit
1,187
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace ASP.NET_Core_Email.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
elanderson/ASP.NET-Core-Email
ASP.NET-Core-Email/src/ASP.NET-Core-Email/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs
C#
mit
378
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/computed"; import create from "ember-metal/platform/create"; import { meta, inspect } from "ember-metal/utils"; import { addDependentKeys, removeDependentKeys } from "ember-metal/dependent_keys"; export default function alias(altKey) { return new AliasedProperty(altKey); } export function AliasedProperty(altKey) { this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = create(Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function(obj, keyName) { addDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.didUnwatch = function(obj, keyName) { removeDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.setup = function(obj, keyName) { Ember.assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName); var m = meta(obj); if (m.watching[keyName]) { addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function(obj, keyName) { var m = meta(obj); if (m.watching[keyName]) { removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function() { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new EmberError('Cannot set read-only property "' + keyName + '" on object: ' + inspect(obj)); } AliasedProperty.prototype.oneWay = function() { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { defineProperty(obj, keyName, null); return set(obj, keyName, value); } // Backwards compatibility with Ember Data AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = ComputedProperty.prototype.meta;
gdi2290/ember.js
packages/ember-metal/lib/alias.js
JavaScript
mit
2,326
/* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. * * author: emicklei */ V8D.receiveCallback = function(msg) { var obj = JSON.parse(msg); var context = this; if (obj.receiver != "this") { var namespaces = obj.receiver.split("."); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } } var func = context[obj.selector]; if (func != null) { return JSON.stringify(func.apply(context, obj.args)); } else { // try reporting the error if (console != null) { console.log("[JS] unable to perform", msg); } // TODO return error? return "null"; } } // This callback is set for handling function calls from Go transferred as JSON. // It is called from Go using "worker.Send(...)". // Throws a SyntaxError exception if the string to parse is not valid JSON. // $recv(V8D.receiveCallback); // This callback is set for handling function calls from Go transferred as JSON that expect a return value. // It is called from Go using "worker.SendSync(...)". // Throws a SyntaxError exception if the string to parse is not valid JSON. // Returns the JSON representation of the return value of the handling function. // $recvSync(V8D.receiveCallback); // callDispatch is used from Go to call a callback function that was registered. // V8D.callDispatch = function(functionRef /*, arguments */ ) { var jsonArgs = [].slice.call(arguments).splice(1); var callback = V8D.function_registry.take(functionRef) if (V8D.function_registry.none == callback) { $print("[JS] no function for reference:" + functionRef); return; } callback.apply(this, jsonArgs.map(function(each){ return JSON.parse(each); })); } // MessageSend is a constructor. // V8D.MessageSend = function MessageSend(receiver, selector, onReturn) { this.data = { "receiver": receiver, "selector": selector, "callback": onReturn, "args": [].slice.call(arguments).splice(3) }; } // MessageSend toJSON returns the JSON representation. // V8D.MessageSend.prototype = { toJSON: function() { return JSON.stringify(this.data); } } // callReturn performs a MessageSend in Go and returns the value from that result // V8D.callReturn = function(receiver, selector /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "args": [].slice.call(arguments).splice(2) }; return JSON.parse($sendSync(JSON.stringify(msg))); } // call performs a MessageSend in Go and does NOT return a value. // V8D.call = function(receiver, selector /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "args": [].slice.call(arguments).splice(2) }; $send(JSON.stringify(msg)); } // callThen performs a MessageSend in Go which can call the onReturn function. // It does not return the value of the perform. // V8D.callThen = function(receiver, selector, onReturnFunction /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "callback": V8D.function_registry.put(onReturnFunction), "args": [].slice.call(arguments).splice(3) }; $send(JSON.stringify(msg)); } // set adds/replaces the value for a variable in the global scope. // V8D.set = function(variableName,itsValue) { V8D.outerThis[variableName] = itsValue; } // get returns the value for a variable in the global scope. // V8D.get = function(variableName) { return V8D.outerThis[variableName]; }
emicklei/v8dispatcher
js/setup.js
JavaScript
mit
3,684
<?php namespace Symfony\Component\Serializer; use Symfony\Component\Serializer\SerializerInterface; /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * Defines the interface of encoders * * @author Jordi Boggiano <[email protected]> */ interface SerializerAwareInterface { /** * Sets the owning Serializer object * * @param SerializerInterface $serializer */ function setSerializer(SerializerInterface $serializer); }
flyingfeet/FlyingFeet
vendor/symfony/src/Symfony/Component/Serializer/SerializerAwareInterface.php
PHP
mit
608
// ƒwƒbƒ_ƒtƒ@ƒCƒ‹‚̃Cƒ“ƒNƒ‹[ƒh #include <windows.h> // •W€WindowsAPI #include <tchar.h> // TCHARŒ^ #include <string.h> // C•¶Žš—ñˆ— // ŠÖ”‚̃vƒƒgƒ^ƒCƒvéŒ¾ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂µ‚Ä“ÆŽ©‚̏ˆ—‚ð‚·‚é‚悤‚É’è‹`‚µ‚½ƒR[ƒ‹ƒoƒbƒNŠÖ”WindowProc. // _tWinMainŠÖ”‚Ì’è‹` int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd) { // •Ï”‚̐錾 HWND hWnd; // CreateWindow‚ō쐬‚µ‚½ƒEƒBƒ“ƒhƒE‚̃EƒBƒ“ƒhƒEƒnƒ“ƒhƒ‹‚ðŠi”[‚·‚éHWNDŒ^•Ï”hWnd. MSG msg; // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒWî•ñ‚ðŠi”[‚·‚éMSG\‘¢‘ÌŒ^•Ï”msg. WNDCLASS wc; // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒXî•ñ‚ð‚à‚ÂWNDCLASS\‘¢‘ÌŒ^•Ï”wc. // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚̐ݒè wc.lpszClassName = _T("SetBkColor"); // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX–¼‚Í"SetBkColor". wc.style = CS_HREDRAW | CS_VREDRAW; // ƒXƒ^ƒCƒ‹‚ÍCS_HREDRAW | CS_VREDRAW. wc.lpfnWndProc = WindowProc; // ƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ‚Í“ÆŽ©‚̏ˆ—‚ð’è‹`‚µ‚½WindowProc. wc.hInstance = hInstance; // ƒCƒ“ƒXƒ^ƒ“ƒXƒnƒ“ƒhƒ‹‚Í_tWinMain‚̈ø”. wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // ƒAƒCƒRƒ“‚̓AƒvƒŠƒP[ƒVƒ‡ƒ“Šù’è‚Ì‚à‚Ì. wc.hCursor = LoadCursor(NULL, IDC_ARROW); // ƒJ[ƒ\ƒ‹‚Í–îˆó. wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // ”wŒi‚Í”’ƒuƒ‰ƒV. wc.lpszMenuName = NULL; // ƒƒjƒ…[‚Í‚È‚µ. wc.cbClsExtra = 0; // 0‚Å‚¢‚¢. wc.cbWndExtra = 0; // 0‚Å‚¢‚¢. // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚Ì“o˜^ if (!RegisterClass(&wc)) { // RegisterClass‚ŃEƒBƒ“ƒhƒEƒNƒ‰ƒX‚ð“o˜^‚µ, 0‚ª•Ô‚Á‚½‚çƒGƒ‰[. // ƒGƒ‰[ˆ— MessageBox(NULL, _T("RegisterClass failed!"), _T("SetBkColor"), MB_OK | MB_ICONHAND); // MessageBox‚Å"RegisterClass failed!"‚ƃGƒ‰[ƒƒbƒZ[ƒW‚ð•\Ž¦. return -1; // ˆÙíI—¹(1) } // ƒEƒBƒ“ƒhƒE‚̍쐬 hWnd = CreateWindow(_T("SetBkColor"), _T("SetBkColor"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); // CreateWindow‚Å, ã‚Å“o˜^‚µ‚½"SetBkColor"ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚̃EƒBƒ“ƒhƒE‚ðì¬. if (hWnd == NULL) { // ƒEƒBƒ“ƒhƒE‚̍쐬‚ÉŽ¸”s‚µ‚½‚Æ‚«. // ƒGƒ‰[ˆ— MessageBox(NULL, _T("CreateWindow failed!"), _T("SetBkColor"), MB_OK | MB_ICONHAND); // MessageBox‚Å"CreateWindow failed!"‚ƃGƒ‰[ƒƒbƒZ[ƒW‚ð•\Ž¦. return -2; // ˆÙíI—¹(2) } // ƒEƒBƒ“ƒhƒE‚Ì•\Ž¦ ShowWindow(hWnd, SW_SHOW); // ShowWindow‚ÅSW_SHOW‚ðŽw’肵‚ăEƒBƒ“ƒhƒE‚Ì•\Ž¦. // ƒƒbƒZ[ƒWƒ‹[ƒv while (GetMessage(&msg, NULL, 0, 0) > 0) { // GetMessage‚сƒbƒZ[ƒW‚ðŽæ“¾, –ß‚è’l‚ª0‚æ‚è‘å‚«‚¢ŠÔ‚̓‹[ƒv‚µ‘±‚¯‚é. // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚Ì‘—o DispatchMessage(&msg); // DispatchMessage‚Ŏ󂯎æ‚Á‚½ƒƒbƒZ[ƒW‚ðƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ(‚±‚̏ꍇ‚Í“ÆŽ©‚É’è‹`‚µ‚½WindowProc)‚É‘—o. } // ƒvƒƒOƒ‰ƒ€‚̏I—¹ return (int)msg.wParam; // I—¹ƒR[ƒh(msg.wParam)‚ð–ß‚è’l‚Æ‚µ‚Ä•Ô‚·. } // WindowProcŠÖ”‚Ì’è‹` LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂µ‚Ä“ÆŽ©‚̏ˆ—‚ð‚·‚é‚悤‚É’è‹`‚µ‚½ƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ. // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂·‚鏈—. switch (uMsg) { // switch-casa•¶‚ÅuMsg‚Ì’l‚²‚Ƃɏˆ—‚ðU‚蕪‚¯‚é. // ƒEƒBƒ“ƒhƒE‚̍쐬‚ªŠJŽn‚³‚ꂽŽž. case WM_CREATE: // ƒEƒBƒ“ƒhƒE‚̍쐬‚ªŠJŽn‚³‚ꂽŽž.(uMsg‚ªWM_CREATE‚ÌŽž.) // WM_CREATEƒuƒƒbƒN { // ƒEƒBƒ“ƒhƒEì¬¬Œ÷ return 0; // return•¶‚Å0‚ð•Ô‚µ‚Ä, ƒEƒBƒ“ƒhƒEì¬¬Œ÷‚Æ‚·‚é. } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ƒEƒBƒ“ƒhƒE‚ª”jŠü‚³‚ꂽŽž. case WM_DESTROY: // ƒEƒBƒ“ƒhƒE‚ª”jŠü‚³‚ꂽŽž.(uMsg‚ªWM_DESTROY‚ÌŽž.) // WM_DESTROYƒuƒƒbƒN { // I—¹ƒƒbƒZ[ƒW‚Ì‘—M. PostQuitMessage(0); // PostQuitMessage‚ŏI—¹ƒR[ƒh‚ð0‚Æ‚µ‚ÄWM_QUITƒƒbƒZ[ƒW‚𑗐M.(‚·‚é‚ƃƒbƒZ[ƒWƒ‹[ƒv‚ÌGetMessage‚Ì–ß‚è’l‚ª0‚É‚È‚é‚Ì‚Å, ƒƒbƒZ[ƒWƒ‹[ƒv‚©‚甲‚¯‚é.) } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ‰æ–Ê‚Ì•`‰æ‚ð—v‹‚³‚ꂽŽž. case WM_PAINT: // ‰æ–Ê‚Ì•`‰æ‚ð—v‹‚³‚ꂽŽž.(uMsg‚ªWM_PAINT‚ÌŽž.) // WM_PAINTƒuƒƒbƒN { // ‚±‚̃uƒƒbƒN‚̃[ƒJƒ‹•Ï”E”z—ñ‚̐錾‚Ə‰Šú‰». HDC hDC; // ƒfƒoƒCƒXƒRƒ“ƒeƒLƒXƒgƒnƒ“ƒhƒ‹‚ðŠi”[‚·‚éHDCŒ^•Ï”hDC. PAINTSTRUCT ps; // ƒyƒCƒ“ƒgî•ñ‚ðŠÇ—‚·‚éPAINTSTRUCT\‘¢‘ÌŒ^‚̕ϐ”ps. TCHAR tszText[] = _T("ABCDE"); // TCHARŒ^”z—ñtszText‚ð"ABCDE"‚ŏ‰Šú‰». size_t uiLen = 0; // tszText‚Ì’·‚³‚ðŠi”[‚·‚邽‚ß‚Ìsize_tŒ^•Ï”uiLen‚ð0‚ɏ‰Šú‰». // ƒEƒBƒ“ƒhƒE‚Ì•`‰æŠJŽn hDC = BeginPaint(hwnd, &ps); // BeginPaint‚Å‚±‚̃EƒBƒ“ƒhƒE‚Ì•`‰æ‚̏€”õ‚ð‚·‚é. –ß‚è’l‚ɂ̓fƒoƒCƒXƒRƒ“ƒeƒLƒXƒgƒnƒ“ƒhƒ‹‚ª•Ô‚é‚Ì‚Å, hDC‚ÉŠi”[. // ”wŒiF‚̐ݒè SetBkColor(hDC, RGB(0x00, 0x00, 0xff)); // SetBkColor‚ՂðƒZƒbƒg. // •`‰æF‚̐ݒè SetTextColor(hDC, RGB(0xff, 0x00, 0x00)); // SetTextColor‚ŐԂðƒZƒbƒg. // •¶Žš—ñ‚Ì•`‰æ uiLen = _tcslen(tszText); // _tcslen‚ÅtszText‚Ì’·‚³‚ðŽæ“¾‚µ, uiLen‚ÉŠi”[. TextOut(hDC, 50, 50, tszText, (int)uiLen); // TextOut‚ŃEƒBƒ“ƒhƒEhwnd‚̍À•W(50, 50)‚̈ʒu‚ÉtszText‚ð•`‰æ. // ƒEƒBƒ“ƒhƒE‚Ì•`‰æI—¹ EndPaint(hwnd, &ps); // EndPaint‚Å‚±‚̃EƒBƒ“ƒhƒE‚Ì•`‰æˆ—‚ðI—¹‚·‚é. } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ã‹LˆÈŠO‚ÌŽž. default: // ã‹LˆÈŠO‚Ì’l‚ÌŽž‚ÌŠù’菈—. // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. } // ‚ ‚Æ‚ÍŠù’è‚̏ˆ—‚É”C‚¹‚é. return DefWindowProc(hwnd, uMsg, wParam, lParam); // –ß‚è’l‚àŠÜ‚ßDefWindowProc‚ÉŠù’è‚̏ˆ—‚ð”C‚¹‚é. }
bg1bgst333/Sample
winapi/SetBkColor/SetBkColor/src/SetBkColor/SetBkColor/SetBkColor.cpp
C++
mit
5,385
/** * * Modelo de Login usando MCV * Desenvolvido por Ricardo Hirashiki * Publicado em: http://www.sitedoricardo.com.br * Data: Ago/2011 * * Baseado na extensao criada por Wemerson Januario * http://code.google.com/p/login-window/ * */ Ext.define('Siccad.view.authentication.CapsWarningTooltip', { extend : 'Ext.tip.QuickTip', alias : 'widget.capswarningtooltip', target : 'authentication-login', id : 'toolcaps', anchor : 'left', anchorOffset : 60, width : 305, dismissDelay : 0, autoHide : false, disabled : false, title : '<b>Caps Lock est&aacute; ativada</b>', html : '<div>Se Caps lock estiver ativado, isso pode fazer com que voc&ecirc;</div>' + '<div>digite a senha incorretamente.</div><br/>' + '<div>Voc&ecirc; deve pressionar a tecla Caps lock para desativ&aacute;-la</div>' + '<div>antes de digitar a senha.</div>' });
romeugodoi/demo_sf2
src/Sicoob/SiccadBundle/Resources/public/js/siccad/view/authentication/CapsWarningTooltip.js
JavaScript
mit
1,010
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public Vector3 m_rotate; public float m_speed; void Start() { transform.rotation = Random.rotation; } // Update is called once per frame void Update () { transform.Rotate(m_rotate*Time.deltaTime* m_speed); } }
a172862967/ProceduralSphere
KGProceduralSphere/Assets/Demo/Rotate.cs
C#
mit
373
<?php /* SRVDVServerBundle:Registration:email.txt.twig */ class __TwigTemplate_d9fb642ef38579dd6542f4eacc9668ce91ac497e0fd5b3f1b1ca25429847bdfe extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'subject' => array($this, 'block_subject'), 'body_text' => array($this, 'block_body_text'), 'body_html' => array($this, 'block_body_html'), ); } protected function doDisplay(array $context, array $blocks = array()) { $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389->enter($__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SRVDVServerBundle:Registration:email.txt.twig")); // line 2 echo " "; // line 3 $this->displayBlock('subject', $context, $blocks); // line 8 $this->displayBlock('body_text', $context, $blocks); // line 13 $this->displayBlock('body_html', $context, $blocks); $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389->leave($__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389_prof); } // line 3 public function block_subject($context, array $blocks = array()) { $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe->enter($__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "subject")); // line 4 echo " "; // line 5 echo " "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.email.subject", array("%username%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "username", array()), "%confirmationUrl%" => (isset($context["confirmationUrl"]) ? $context["confirmationUrl"] : $this->getContext($context, "confirmationUrl"))), "FOSUserBundle"); echo " "; $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe->leave($__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe_prof); } // line 8 public function block_body_text($context, array $blocks = array()) { $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904->enter($__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body_text")); // line 9 echo " "; // line 10 echo " "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.email.message", array("%username%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "username", array()), "%confirmationUrl%" => (isset($context["confirmationUrl"]) ? $context["confirmationUrl"] : $this->getContext($context, "confirmationUrl"))), "FOSUserBundle"); echo " "; $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904->leave($__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904_prof); } // line 13 public function block_body_html($context, array $blocks = array()) { $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3->enter($__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body_html")); $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3->leave($__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3_prof); } public function getTemplateName() { return "SRVDVServerBundle:Registration:email.txt.twig"; } public function getDebugInfo() { return array ( 75 => 13, 65 => 10, 63 => 9, 57 => 8, 47 => 5, 45 => 4, 39 => 3, 32 => 13, 30 => 8, 28 => 3, 25 => 2,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% trans_default_domain 'FOSUserBundle' %} {% block subject %} {% autoescape false %} {{ 'registration.email.subject'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl}) }} {% endautoescape %} {% endblock %} {% block body_text %} {% autoescape false %} {{ 'registration.email.message'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl}) }} {% endautoescape %} {% endblock %} {% block body_html %}{% endblock %} ", "SRVDVServerBundle:Registration:email.txt.twig", "C:\\wamp64\\www\\serveurDeVoeux\\src\\SRVDV\\ServerBundle/Resources/views/Registration/email.txt.twig"); } }
youcefboukersi/serveurdevoeux
app/cache/dev/twig/a4/a4d5e331da6ebdf63a769ec513a07ed062a09e096299142f0540503ab3951bbb.php
PHP
mit
6,108
using Portal.CMS.Entities.Enumerators; using Portal.CMS.Services.Generic; using Portal.CMS.Services.PageBuilder; using Portal.CMS.Web.Architecture.ActionFilters; using Portal.CMS.Web.Architecture.Extensions; using Portal.CMS.Web.Areas.PageBuilder.ViewModels.Component; using Portal.CMS.Web.ViewModels.Shared; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.SessionState; namespace Portal.CMS.Web.Areas.PageBuilder.Controllers { [AdminFilter(ActionFilterResponseType.Modal)] [SessionState(SessionStateBehavior.ReadOnly)] public class ComponentController : Controller { private readonly IPageSectionService _pageSectionService; private readonly IPageComponentService _pageComponentService; private readonly IImageService _imageService; public ComponentController(IPageSectionService pageSectionService, IPageComponentService pageComponentService, IImageService imageService) { _pageSectionService = pageSectionService; _pageComponentService = pageComponentService; _imageService = imageService; } [HttpGet] [OutputCache(Duration = 86400)] public async Task<ActionResult> Add() { var model = new AddViewModel { PageComponentTypeList = await _pageComponentService.GetComponentTypesAsync() }; return View("_Add", model); } [HttpPost] [ValidateInput(false)] public async Task<JsonResult> Add(int pageSectionId, string containerElementId, string elementBody) { elementBody = elementBody.Replace("animated bounce", string.Empty); await _pageComponentService.AddAsync(pageSectionId, containerElementId, elementBody); return Json(new { State = true }); } [HttpPost] public async Task<ActionResult> Delete(int pageSectionId, string elementId) { try { await _pageComponentService.DeleteAsync(pageSectionId, elementId); return Json(new { State = true }); } catch (Exception ex) { return Json(new { State = false, Message = ex.InnerException }); } } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Edit(int pageSectionId, string elementId, string elementHtml) { await _pageComponentService.EditElementAsync(pageSectionId, elementId, elementHtml); return Content("Refresh"); } [HttpGet] public async Task<ActionResult> EditImage(int pageSectionId, string elementId, string elementType) { var imageList = await _imageService.GetAsync(); var model = new ImageViewModel { SectionId = pageSectionId, ElementType = elementType, ElementId = elementId, GeneralImages = new PaginationViewModel { PaginationType = "general", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.General) }, IconImages = new PaginationViewModel { PaginationType = "icon", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Icon) }, ScreenshotImages = new PaginationViewModel { PaginationType = "screenshot", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Screenshot) }, TextureImages = new PaginationViewModel { PaginationType = "texture", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Texture) } }; return View("_EditImage", model); } [HttpPost] public async Task<JsonResult> EditImage(ImageViewModel model) { try { var selectedImage = await _imageService.GetAsync(model.SelectedImageId); await _pageComponentService.EditImageAsync(model.SectionId, model.ElementType, model.ElementId, selectedImage.CDNImagePath()); return Json(new { State = true, Source = selectedImage.CDNImagePath() }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditVideo(int pageSectionId, string widgetWrapperElementId, string videoPlayerElementId) { var model = new VideoViewModel { SectionId = pageSectionId, WidgetWrapperElementId = widgetWrapperElementId, VideoPlayerElementId = videoPlayerElementId, VideoUrl = string.Empty }; return View("_EditVideo", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditVideo(VideoViewModel model) { try { await _pageComponentService.EditSourceAsync(model.SectionId, model.VideoPlayerElementId, model.VideoUrl); return Json(new { State = true }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditContainer(int pageSectionId, string elementId) { var model = new ContainerViewModel { SectionId = pageSectionId, ElementId = elementId }; return View("_EditContainer", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditContainer(ContainerViewModel model) { await _pageSectionService.EditAnimationAsync(model.SectionId, model.ElementId, model.Animation.ToString()); return Content("Refresh"); } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Link(int pageSectionId, string elementId, string elementHtml, string elementHref, string elementTarget) { await _pageComponentService.EditAnchorAsync(pageSectionId, elementId, elementHtml, elementHref, elementTarget); return Content("Refresh"); } [HttpPost] public async Task<JsonResult> Clone(int pageSectionId, string elementId, string componentStamp) { await _pageComponentService.CloneElementAsync(pageSectionId, elementId, componentStamp); return Json(new { State = true }); } } }
tommcclean/PortalCMS
Portal.CMS.Web/Areas/PageBuilder/Controllers/ComponentController.cs
C#
mit
7,137
<?php /** * Created by PhpStorm. * User: robert * Date: 1/14/15 * Time: 3:06 PM */ namespace Skema\Directive; class Binding extends Base { }
Skema/Skema
Skema/Directive/Binding.php
PHP
mit
149
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ActionOnDispose.cs // // // Implemention of IDisposable that runs a delegate on Dispose. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Provider of disposables that run actions.</summary> internal sealed class Disposables { /// <summary>An IDisposable that does nothing.</summary> internal readonly static IDisposable Nop = new NopDisposable(); /// <summary>Creates an IDisposable that runs an action when disposed.</summary> /// <typeparam name="T1">Specifies the type of the first argument.</typeparam> /// <typeparam name="T2">Specifies the type of the second argument.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <returns>The created disposable.</returns> internal static IDisposable Create<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2) { Contract.Requires(action != null, "Non-null disposer action required."); return new Disposable<T1, T2>(action, arg1, arg2); } /// <summary>Creates an IDisposable that runs an action when disposed.</summary> /// <typeparam name="T1">Specifies the type of the first argument.</typeparam> /// <typeparam name="T2">Specifies the type of the second argument.</typeparam> /// <typeparam name="T3">Specifies the type of the third argument.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <returns>The created disposable.</returns> internal static IDisposable Create<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3) { Contract.Requires(action != null, "Non-null disposer action required."); return new Disposable<T1, T2, T3>(action, arg1, arg2, arg3); } /// <summary>A disposable that's a nop.</summary> [DebuggerDisplay("Disposed = true")] private sealed class NopDisposable : IDisposable { void IDisposable.Dispose() { } } /// <summary>An IDisposable that will run a delegate when disposed.</summary> [DebuggerDisplay("Disposed = {Disposed}")] private sealed class Disposable<T1, T2> : IDisposable { /// <summary>First state argument.</summary> private readonly T1 _arg1; /// <summary>Second state argument.</summary> private readonly T2 _arg2; /// <summary>The action to run when disposed. Null if disposed.</summary> private Action<T1, T2> _action; /// <summary>Initializes the ActionOnDispose.</summary> /// <param name="action">The action to run when disposed.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> internal Disposable(Action<T1, T2> action, T1 arg1, T2 arg2) { Contract.Requires(action != null, "Non-null action needed for disposable"); _action = action; _arg1 = arg1; _arg2 = arg2; } /// <summary>Gets whether the IDisposable has been disposed.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private bool Disposed { get { return _action == null; } } /// <summary>Invoke the action.</summary> void IDisposable.Dispose() { Action<T1, T2> toRun = _action; if (toRun != null && Interlocked.CompareExchange(ref _action, null, toRun) == toRun) { toRun(_arg1, _arg2); } } } /// <summary>An IDisposable that will run a delegate when disposed.</summary> [DebuggerDisplay("Disposed = {Disposed}")] private sealed class Disposable<T1, T2, T3> : IDisposable { /// <summary>First state argument.</summary> private readonly T1 _arg1; /// <summary>Second state argument.</summary> private readonly T2 _arg2; /// <summary>Third state argument.</summary> private readonly T3 _arg3; /// <summary>The action to run when disposed. Null if disposed.</summary> private Action<T1, T2, T3> _action; /// <summary>Initializes the ActionOnDispose.</summary> /// <param name="action">The action to run when disposed.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> internal Disposable(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3) { Contract.Requires(action != null, "Non-null action needed for disposable"); _action = action; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } /// <summary>Gets whether the IDisposable has been disposed.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private bool Disposed { get { return _action == null; } } /// <summary>Invoke the action.</summary> void IDisposable.Dispose() { Action<T1, T2, T3> toRun = _action; if (toRun != null && Interlocked.CompareExchange(ref _action, null, toRun) == toRun) { toRun(_arg1, _arg2, _arg3); } } } } }
cuteant/dotnet-tpl-dataflow
source/Internal/ActionOnDispose.cs
C#
mit
5,481
using System; using System.Collections.Generic; using Esb.Transport; namespace Esb.Message { public interface IMessageQueue { void Add(Envelope message); IEnumerable<Envelope> Messages { get; } Envelope GetNextMessage(); void SuspendMessages(Type messageType); void ResumeMessages(Type messageType); void RerouteMessages(Type messageType); void RemoveMessages(Type messageType); event EventHandler<EventArgs> OnMessageArived; IRouter Router { get; set; } } }
Xynratron/WorkingCluster
Esb/Message/IMessageQueue.cs
C#
mit
548
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CRealMoveRequestDelayCheckerDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Register { class CRealMoveRequestDelayCheckerRegister : public IRegister { public: void Register() override { auto& hook_core = CATFCore::get_instance(); for (auto& r : Detail::CRealMoveRequestDelayChecker_functions) hook_core.reg_wrapper(r.pBind, r); } }; }; // end namespace Register END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/CRealMoveRequestDelayCheckerRegister.hpp
C++
mit
727
//----------------------------------------------------------------------- // <copyright file="LocalizableFormBase.cs" company="Hyperar"> // Copyright (c) Hyperar. All rights reserved. // </copyright> // <author>Matías Ezequiel Sánchez</author> //----------------------------------------------------------------------- namespace Hyperar.HattrickUltimate.UserInterface { using System; using System.Windows.Forms; using Interface; /// <summary> /// ILocalizableForm base implementation. /// </summary> public partial class LocalizableFormBase : Form, ILocalizableForm { #region Public Methods /// <summary> /// Populates controls' properties with the corresponding localized string. /// </summary> public virtual void PopulateLanguage() { } #endregion Public Methods #region Protected Methods /// <summary> /// Raises the System.Windows.Forms.Form.Load event. /// </summary> /// <param name="e">An System.EventArgs that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.PopulateLanguage(); } #endregion Protected Methods } }
hyperar/Hattrick-Ultimate
Hyperar.HattrickUltimate.UserInterface/LocalizableFormBase.cs
C#
mit
1,283
var width = window.innerWidth, height = window.innerHeight, boids = [], destination, canvas, context; const MAX_NUMBER = 100; const MAX_SPEED = 1; const radius = 5; init(); animation(); function init(){ canvas = document.getElementById('canvas'), context = canvas.getContext( "2d" ); canvas.width = width; canvas.height = height; destination = { x:Math.random()*width, y:Math.random()*height }; for (var i = 0; i <MAX_NUMBER; i++) { boids[i] = new Boid(); }; } var _animation; function animation(){ _animation = requestAnimationFrame(animation); context.clearRect(0,0,width,height); for (var i = 0; i < boids.length; i++) { boids[i].rule1(); boids[i].rule2(); boids[i].rule3(); boids[i].rule4(); boids[i].rule5(); boids[i].rule6(); var nowSpeed = Math.sqrt(boids[i].vx * boids[i].vx + boids[i].vy * boids[i].vy ); if(nowSpeed > MAX_SPEED){ boids[i].vx *= MAX_SPEED / nowSpeed; boids[i].vy *= MAX_SPEED / nowSpeed; } boids[i].x += boids[i].vx; boids[i].y += boids[i].vy; drawCircle(boids[i].x,boids[i].y); drawVector(boids[i].x,boids[i].y,boids[i].vx,boids[i].vy); }; } /* //mouseEvent document.onmousemove = function (event){ destination ={ x:event.screenX, y:event.screenY } }; */ function Boid(){ this.x = Math.random()*width; this.y = Math.random()*height; this.vx = 0.0; this.vy = 0.0; this.dx = Math.random()*width; this.dy = Math.random()*height; //群れの中心に向かう this.rule1 = function(){ var centerx = 0, centery = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { centerx += boids[i].x; centery += boids[i].y; }; }; centerx /= MAX_NUMBER-1; centery /= MAX_NUMBER-1; this.vx += (centerx-this.x)/1000; this.vy += (centery-this.y)/1000; } //他の個体と離れるように動く this.rule2 = function(){ var _vx = 0, _vy = 0; for (var i = 0; i < boids.length; i++) { if(this != boids[i]){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<25){ distance += 0.001; _vx -= (boids[i].x - this.x)/distance; _vy -= (boids[i].y - this.y)/distance; //this.dx = -boids[i].x; //this.dy = -boids[i].y; } } }; this.vx += _vx; this.vy += _vy; } //他の個体と同じ速度で動こうとする this.rule3 = function(){ var _pvx = 0, _pvy = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { _pvx += boids[i].vx; _pvy += boids[i].vy; } }; _pvx /= MAX_NUMBER-1; _pvy /= MAX_NUMBER-1; this.vx += (_pvx - this.vx)/10; this.vy += (_pvy - this.vy)/10; }; //壁側の時の振る舞い this.rule4 = function(){ if(this.x < 10 && this.vx < 0)this.vx += 10/(Math.abs( this.x ) + 1 ); if(this.x > width && this.vx > 0)this.vx -= 10/(Math.abs( width - this.x ) + 1 ); if (this.y < 10 && this.vy < 0)this.vy += 10/(Math.abs( this.y ) + 1 ); if(this.y > height && this.vy > 0)this.vy -= 10/(Math.abs( height - this.y ) + 1 ); }; //目的地に行く this.rule5 = function(){ var _dx = this.dx - this.x, _dy = this.dy - this.y; this.vx += (this.dx - this.x)/500; this.vy += (this.dy - this.y)/500; } //捕食する this.rule6 = function(){ var _vx = Math.random()-0.5, _vy = Math.random()-0.5; for (var i = 0; i < boids.length; i++) { if(this != boids[i] && this.dx != boids[i].dx && this.dy != boids[i].dy){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<20 && distance>15){ console.log(distance); distance += 0.001; _vx += (boids[i].x - this.x)/distance; _vy += (boids[i].y - this.y)/distance; drawLine(this.x,this.y,boids[i].x,boids[i].y); this.dx = boids[i].dx; this.dy = boids[i].dy; } } }; this.vx += _vx; this.vy += _vy; } } function distanceTo(x1,x2,y1,y2){ var dx = x2-x1, dy = y2-y1; return Math.sqrt(dx*dx+dy*dy); } function drawCircle(x,y){ context.beginPath(); context.strokeStyle = "#fff"; context.arc(x,y,radius,0,Math.PI*2,false); context.stroke(); } const VectorLong = 10; function drawVector(x,y,vx,vy){ context.beginPath(); var pointx = x+vx*VectorLong; var pointy = y+vy*VectorLong; context.moveTo(x,y); context.lineTo(pointx,pointy); context.stroke(); } function drawLine(x1,y1,x2,y2){ context.beginPath(); context.moveTo(x1,y1); context.lineTo(x2,y2); context.stroke(); }
yuuki2006628/boid
boid.js
JavaScript
mit
4,749
package com.facetime.spring.support; import java.util.ArrayList; import java.util.List; import com.facetime.core.conf.ConfigUtils; import com.facetime.core.utils.StringUtils; /** * 分页类 * * @author yufei * @param <T> */ public class Page<T> { private static int BEGIN_PAGE_SIZE = 20; /** 下拉分页列表的递增数量级 */ private static int ADD_PAGE_SIZE_RATIO = 10; public static int DEFAULT_PAGE_SIZE = 10; private static int MAX_PAGE_SIZE = 200; private QueryInfo<T> queryInfo = null; private List<T> queryResult = null; public Page() { this(new QueryInfo<T>()); } public Page(QueryInfo<T> queryInfo) { this.queryInfo = queryInfo; this.queryResult = new ArrayList<T>(15); } /** * @return 下拉分页列表的递增数量级 */ public final static int getAddPageSize() { String addPageSizeRatio = ConfigUtils.getProperty("add_page_size_ratio"); if (StringUtils.isValid(addPageSizeRatio)) ADD_PAGE_SIZE_RATIO = Integer.parseInt(addPageSizeRatio); return ADD_PAGE_SIZE_RATIO; } /** * @return 默认分页下拉列表的开始值 */ public final static int getBeginPageSize() { String beginPageSize = ConfigUtils.getProperty("begin_page_size"); if (StringUtils.isValid(beginPageSize)) BEGIN_PAGE_SIZE = Integer.parseInt(beginPageSize); return BEGIN_PAGE_SIZE; } /** * 默认列表记录显示条数 */ public static final int getDefaultPageSize() { String defaultPageSize = ConfigUtils.getProperty("default_page_size"); if (StringUtils.isValid(defaultPageSize)) DEFAULT_PAGE_SIZE = Integer.parseInt(defaultPageSize); return DEFAULT_PAGE_SIZE; } /** * 默认分页列表显示的最大记录条数 */ public static final int getMaxPageSize() { String maxPageSize = ConfigUtils.getProperty("max_page_size"); if (StringUtils.isValid(maxPageSize)) { MAX_PAGE_SIZE = Integer.parseInt(maxPageSize); } return MAX_PAGE_SIZE; } public String getBeanName() { return this.queryInfo.getBeanName(); } public int getCurrentPageNo() { return this.queryInfo.getCurrentPageNo(); } public String getKey() { return this.queryInfo.getKey(); } public Integer getNeedRowNum() { return this.getPageSize() - this.getQueryResult().size(); } public long getNextPage() { return this.queryInfo.getNextPage(); } public int getPageCount() { return this.queryInfo.getPageCount(); } public int getPageSize() { return this.queryInfo.getPageSize(); } public List<T> getParams() { return this.queryInfo.getParams(); } public int getPreviousPage() { return this.queryInfo.getPreviousPage(); } public String[] getProperties() { return this.queryInfo.getProperties(); } public List<T> getQueryResult() { return this.queryResult; } public int getRecordCount() { return this.queryInfo.getRecordCount(); } public String getSql() { return this.queryInfo.getSql(); } public boolean isHasResult() { return this.queryResult != null && this.queryResult.size() > 0; } public void setBeanName(String beanNameValue) { this.queryInfo.setBeanName(beanNameValue); } public void setCurrentPageNo(int currentPageNo) { this.queryInfo.setCurrentPageNo(currentPageNo); } public void setKey(String keyValue) { this.queryInfo.setKey(keyValue); } public void setPageCount(int pageCount) { this.queryInfo.setPageCount(pageCount); } public void setPageSize(int pageSize) { this.queryInfo.setPageSize(pageSize); } public void setParams(List<T> paramsValue) { this.queryInfo.setParams(paramsValue); } public void setProperties(String[] propertiesValue) { this.queryInfo.setProperties(propertiesValue); } public void setQueryResult(List<T> list) { this.queryResult = list; } public void setRecordCount(int count) { this.queryInfo.setRecordCount(count); } public void setSql(String sql) { this.queryInfo.setSql(sql); } }
allanfish/facetime
facetime-spring/src/main/java/com/facetime/spring/support/Page.java
Java
mit
3,885
package com.cnpc.framework.base.service.impl; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.cnpc.framework.base.entity.Dict; import com.cnpc.framework.base.pojo.TreeNode; import com.cnpc.framework.base.service.DictService; import com.cnpc.framework.constant.RedisConstant; import com.cnpc.framework.utils.StrUtil; import com.cnpc.framework.utils.TreeUtil; @Service("dictService") public class DictServiceImpl extends BaseServiceImpl implements DictService { @Override public List<TreeNode> getTreeData() { // 获取数据 String key = RedisConstant.DICT_PRE+"tree"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict order by levelCode asc"; List<Dict> dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } public List<Dict> getDictsByCode(String code) { String key = RedisConstant.DICT_PRE+ code; List dicts = redisDao.get(key, List.class); if (dicts == null) { String hql = "from Dict where code='" + code + "'"; Dict dict = this.get(hql); dicts = this.find("from Dict where parentId='" + dict.getId() + "' order by levelCode"); redisDao.add(key, dicts); return dicts; } else { return dicts; } } @Override public List<TreeNode> getTreeDataByCode(String code) { // 获取数据 String key = RedisConstant.DICT_PRE + code + "s"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict where code='" + code + "' order by levelCode asc"; List<Dict> dicts = this.find(hql); hql = "from Dict where code='" + code + "' or parent_id = '" +dicts.get(0).getId()+ "' order by levelCode asc"; dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } @Override public List<TreeNode> getMeasureTreeData() { // 获取数据 String hql = "from Dict WHERE (levelCode LIKE '000026%' OR levelCode LIKE '000027%') order by levelCode asc"; List<Dict> funcs = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : funcs) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 return TreeUtil.getNodeList(nodelist); } }
Squama/Master
AdminEAP-framework/src/main/java/com/cnpc/framework/base/service/impl/DictServiceImpl.java
Java
mit
4,363
#include "unicorn/format.hpp" #include <cmath> #include <cstdio> using namespace RS::Unicorn::Literals; using namespace std::chrono; using namespace std::literals; namespace RS::Unicorn { namespace UnicornDetail { namespace { // These will always be called with x>=0 and prec>=0 Ustring float_print(long double x, int prec, bool exp) { std::vector<char> buf(32); int len = 0; for (;;) { if (exp) len = snprintf(buf.data(), buf.size(), "%.*Le", prec, x); else len = snprintf(buf.data(), buf.size(), "%.*Lf", prec, x); if (len < int(buf.size())) return buf.data(); buf.resize(2 * buf.size()); } } void float_strip(Ustring& str) { static const Regex pattern("(.*)(\\.(?:\\d*[1-9])?)(0+)(e.*)?", Regex::full); auto match = pattern(str); if (match) { Ustring result(match[1]); if (match.count(2) != 1) result += match[2]; result += match[4]; str.swap(result); } } Ustring float_digits(long double x, int prec) { prec = std::max(prec, 1); auto result = float_print(x, prec - 1, true); auto epos = result.find_first_of("Ee"); auto exponent = strtol(result.data() + epos + 1, nullptr, 10); result.resize(epos); if (exponent < 0) { if (prec > 1) result.erase(1, 1); result.insert(0, 1 - exponent, '0'); result[1] = '.'; } else if (exponent >= prec - 1) { if (prec > 1) result.erase(1, 1); result.insert(result.end(), exponent - prec + 1, '0'); } else if (exponent > 0) { result.erase(1, 1); result.insert(exponent + 1, 1, '.'); } return result; } Ustring float_exp(long double x, int prec) { prec = std::max(prec, 1); auto result = float_print(x, prec - 1, true); auto epos = result.find_first_of("Ee"); char esign = 0; if (result[epos + 1] == '-') esign = '-'; auto epos2 = result.find_first_not_of("+-0", epos + 1); Ustring exponent; if (epos2 < result.size()) exponent = result.substr(epos2); result.resize(epos); result += 'e'; if (esign) result += esign; if (exponent.empty()) result += '0'; else result += exponent; return result; } Ustring float_fixed(long double x, int prec) { return float_print(x, prec, false); } Ustring float_general(long double x, int prec) { using std::floor; using std::log10; if (x == 0) return float_digits(x, prec); auto exp = int(floor(log10(x))); auto d_estimate = exp < 0 ? prec + 1 - exp : exp < prec - 1 ? prec + 1 : exp + 1; auto e_estimate = exp < 0 ? prec + 4 : prec + 3; auto e_vs_d = e_estimate - d_estimate; if (e_vs_d <= -2) return float_exp(x, prec); if (e_vs_d >= 2) return float_digits(x, prec); auto dform = float_digits(x, prec); auto eform = float_exp(x, prec); return dform.size() <= eform.size() ? dform : eform; } Ustring string_escape(const Ustring& s, uint64_t mode) { Ustring result; result.reserve(s.size() + 2); if (mode & Format::quote) result += '\"'; for (auto i = utf_begin(s), e = utf_end(s); i != e; ++i) { switch (*i) { case U'\0': result += "\\0"; break; case U'\t': result += "\\t"; break; case U'\n': result += "\\n"; break; case U'\f': result += "\\f"; break; case U'\r': result += "\\r"; break; case U'\\': result += "\\\\"; break; case U'\"': if (mode & Format::quote) result += '\\'; result += '\"'; break; default: if (*i >= 32 && *i <= 126) { result += char(*i); } else if (*i >= 0xa0 && ! (mode & Format::ascii)) { result.append(s, i.offset(), i.count()); } else if (*i <= 0xff) { result += "\\x"; result += format_radix(*i, 16, 2); } else { result += "\\x{"; result += format_radix(*i, 16, 1); result += '}'; } break; } } if (mode & Format::quote) result += '\"'; return result; } template <typename Range> Ustring string_values(const Range& s, int base, int prec, int defprec) { if (prec < 0) prec = defprec; Ustring result; for (auto c: s) { result += format_radix(char_to_uint(c), base, prec); result += ' '; } if (! result.empty()) result.pop_back(); return result; } } // Formatting for specific types void translate_flags(const Ustring& str, uint64_t& flags, int& prec, size_t& width, char32_t& pad) { flags = 0; prec = -1; width = 0; pad = U' '; auto i = utf_begin(str), end = utf_end(str); while (i != end) { if (*i == U'<' || *i == U'=' || *i == U'>') { if (*i == U'<') flags |= Format::left; else if (*i == U'=') flags |= Format::centre; else flags |= Format::right; ++i; if (i != end && ! char_is_digit(*i)) pad = *i++; if (i != end && char_is_digit(*i)) i = str_to_int<size_t>(width, i); } else if (char_is_ascii(*i) && ascii_isalpha(char(*i))) { flags |= letter_to_mask(char(*i++)); } else if (char_is_digit(*i)) { i = str_to_int<int>(prec, i); } else { ++i; } } } Ustring format_ldouble(long double t, uint64_t flags, int prec) { using std::fabs; static constexpr auto format_flags = Format::digits | Format::exp | Format::fixed | Format::general; static constexpr auto sign_flags = Format::sign | Format::signz; if (popcount(flags & format_flags) > 1 || popcount(flags & sign_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (prec < 0) prec = 6; auto mag = fabs(t); Ustring s; if (flags & Format::digits) s = float_digits(mag, prec); else if (flags & Format::exp) s = float_exp(mag, prec); else if (flags & Format::fixed) s = float_fixed(mag, prec); else s = float_general(mag, prec); if (flags & Format::stripz) float_strip(s); if (t < 0 || (flags & Format::sign) || (t > 0 && (flags & Format::signz))) s.insert(s.begin(), t < 0 ? '-' : '+'); return s; } // Alignment and padding Ustring format_align(Ustring src, uint64_t flags, size_t width, char32_t pad) { if (popcount(flags & (Format::left | Format::centre | Format::right)) > 1) throw std::invalid_argument("Inconsistent formatting alignment flags"); if (popcount(flags & (Format::lower | Format::title | Format::upper)) > 1) throw std::invalid_argument("Inconsistent formatting case conversion flags"); if (flags & Format::lower) str_lowercase_in(src); else if (flags & Format::title) str_titlecase_in(src); else if (flags & Format::upper) str_uppercase_in(src); size_t len = str_length(src, flags & format_length_flags); if (width <= len) return src; size_t extra = width - len; Ustring dst; if (flags & Format::right) str_append_chars(dst, extra, pad); else if (flags & Format::centre) str_append_chars(dst, extra / 2, pad); dst += src; if (flags & Format::left) str_append_chars(dst, extra, pad); else if (flags & Format::centre) str_append_chars(dst, (extra + 1) / 2, pad); return dst; } } // Basic formattng functions Ustring format_type(bool t, uint64_t flags, int /*prec*/) { static constexpr auto format_flags = Format::binary | Format::tf | Format::yesno; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (flags & Format::binary) return t ? "1" : "0"; else if (flags & Format::yesno) return t ? "yes" : "no"; else return t ? "true" : "false"; } Ustring format_type(const Ustring& t, uint64_t flags, int prec) { using namespace UnicornDetail; static constexpr auto format_flags = Format::ascii | Format::ascquote | Format::escape | Format::decimal | Format::hex | Format::hex8 | Format::hex16 | Format::quote; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (flags & Format::quote) return string_escape(t, Format::quote); else if (flags & Format::ascquote) return string_escape(t, Format::quote | Format::ascii); else if (flags & Format::escape) return string_escape(t, 0); else if (flags & Format::ascii) return string_escape(t, Format::ascii); else if (flags & Format::decimal) return string_values(utf_range(t), 10, prec, 1); else if (flags & Format::hex8) return string_values(t, 16, prec, 2); else if (flags & Format::hex16) return string_values(to_utf16(t), 16, prec, 4); else if (flags & Format::hex) return string_values(utf_range(t), 16, prec, 1); else return t; } Ustring format_type(system_clock::time_point t, uint64_t flags, int prec) { static constexpr auto format_flags = Format::iso | Format::common; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); auto zone = flags & Format::local ? local_zone : utc_zone; if (flags & Format::common) return format_date(t, "%c"s, zone); auto result = format_date(t, prec, zone); if (flags & Format::iso) { auto pos = result.find(' '); if (pos != npos) result[pos] = 'T'; } return result; } // Formatter class Format::Format(const Ustring& format): fmt(format), seq() { auto i = utf_begin(format), end = utf_end(format); while (i != end) { auto j = std::find(i, end, U'$'); add_literal(u_str(i, j)); i = std::next(j); if (i == end) break; Ustring prefix, suffix; if (char_is_digit(*i)) { auto k = std::find_if_not(i, end, char_is_digit); j = std::find_if_not(k, end, char_is_alphanumeric); prefix = u_str(i, k); suffix = u_str(k, j); } else if (*i == U'{') { auto k = std::next(i); if (char_is_digit(*k)) { auto l = std::find_if_not(k, end, char_is_digit); j = std::find(l, end, U'}'); if (j != end) { prefix = u_str(k, l); suffix = u_str(l, j); ++j; } } } if (prefix.empty()) { add_literal(i.str()); ++i; } else { add_index(str_to_int<unsigned>(prefix), suffix); i = j; } } } void Format::add_index(unsigned index, const Ustring& flags) { using namespace UnicornDetail; element elem; elem.index = index; translate_flags(to_utf8(flags), elem.flags, elem.prec, elem.width, elem.pad); seq.push_back(elem); if (index > 0 && index > num) num = index; } void Format::add_literal(const Ustring& text) { if (! text.empty()) { if (seq.empty() || seq.back().index != 0) seq.push_back({0, text, 0, 0, 0, 0}); else seq.back().text += text; } } }
CaptainCrowbar/unicorn-lib
unicorn/format.cpp
C++
mit
14,380
// // IOService.cpp // Firedrake // // Created by Sidney Just // Copyright (c) 2015 by Sidney Just // 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 "IOService.h" namespace IO { IODefineMeta(Service, RegistryEntry) String *kServiceProviderMatchKey; String *kServiceClassMatchKey; String *kServicePropertiesMatchKey; extern void RegisterClass(MetaClass *meta, Dictionary *properties); extern void RegisterProvider(Service *provider); extern void EnumerateClassesForProvider(Service *provider, const Function<bool (MetaClass *meta, Dictionary *properties)> &callback); void Service::InitialWakeUp(MetaClass *meta) { if(meta == Service::GetMetaClass()) { kServiceProviderMatchKey = String::Alloc()->InitWithCString("kServiceProviderMatchKey"); kServiceClassMatchKey = String::Alloc()->InitWithCString("kServiceClassMatchKey"); kServicePropertiesMatchKey = String::Alloc()->InitWithCString("kServicePropertiesMatchKey"); } RegistryEntry::InitialWakeUp(meta); } void Service::RegisterService(MetaClass *meta, Dictionary *properties) { RegisterClass(meta, properties); } Service *Service::InitWithProperties(Dictionary *properties) { if(!RegistryEntry::Init()) return nullptr; _started = false; _properties = properties->Retain(); return this; } Dictionary *Service::GetProperties() const { return _properties; } void Service::Start() { _started = true; } void Service::Stop() {} // Matching void Service::RegisterProvider() { IO::RegisterProvider(this); } bool Service::MatchProperties(__unused Dictionary *properties) { return true; } void Service::StartMatching() { DoMatch(); } void Service::DoMatch() { EnumerateClassesForProvider(this, [this](MetaClass *meta, Dictionary *properties) { if(MatchProperties(properties)) { Service *service = static_cast<Service *>(meta->Alloc()); service = service->InitWithProperties(properties); if(service) { PublishService(service); return true; } } return false; }); } void Service::PublishService(Service *service) { AttachChild(service); } void Service::AttachToParent(RegistryEntry *parent) { RegistryEntry::AttachToParent(parent); Start(); } }
JustSid/Firedrake
slib/libio/service/IOService.cpp
C++
mit
3,272
//----------------------------------------------------------------------- // <copyright file="IDemPlateFileGenerator.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation 2011. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.Research.Wwt.Sdk.Core { /// <summary> /// Interface for DEM plate file generator. /// </summary> public interface IDemPlateFileGenerator { /// <summary> /// Gets the number of processed tiles for the level in context. /// </summary> long TilesProcessed { get; } /// <summary> /// This function is used to create the plate file from already generated DEM pyramid. /// </summary> /// <param name="serializer"> /// DEM tile serializer to retrieve the tile. /// </param> void CreateFromDemTile(IDemTileSerializer serializer); } }
WorldWideTelescope/wwt-tile-sdk
Core/IDemPlateFileGenerator.cs
C#
mit
977
namespace PlacesToEat.Data.Common { using System; using System.Data.Entity; using System.Linq; using Contracts; using Models; public class DbUserRepository<T> : IDbUserRepository<T> where T : class, IAuditInfo, IDeletableEntity { public DbUserRepository(DbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository.", nameof(context)); } this.Context = context; this.DbSet = this.Context.Set<T>(); } private IDbSet<T> DbSet { get; } private DbContext Context { get; } public IQueryable<T> All() { return this.DbSet.AsQueryable().Where(x => !x.IsDeleted); } public IQueryable<T> AllWithDeleted() { return this.DbSet.AsQueryable(); } public void Delete(T entity) { entity.IsDeleted = true; entity.DeletedOn = DateTime.UtcNow; } public T GetById(string id) { return this.DbSet.Find(id); } public void HardDelete(T entity) { this.DbSet.Remove(entity); } public void Save() { this.Context.SaveChanges(); } } }
tcholakov/PlacesToEat
Source/Data/PlacesToEat.Data.Common/DbUserRepository{T}.cs
C#
mit
1,375
describe("Dragable Row Directive ", function () { var scope, container, element, html, compiled, compile; beforeEach(module("app", function ($provide) { $provide.value("authService", {}) })); beforeEach(inject(function ($compile, $rootScope) { html = '<div id="element-id" data-draggable-row=""' + ' data-draggable-elem-selector=".draggable"' + ' data-drop-area-selector=".drop-area">' + '<div class="draggable"></div>' + '<div class="drop-area" style="display: none;"></div>' + '</div>'; scope = $rootScope.$new(); compile = $compile; })); function prepareDirective(s) { container = angular.element(html); compiled = compile(container); element = compiled(s); s.$digest(); } /***********************************************************************************************************************/ it('should add draggable attribute to draggable element, when initialise', function () { prepareDirective(scope); expect(element.find('.draggable').attr('draggable')).toBe('true'); }); it('should prevent default, when dragging over allowed element', function () { prepareDirective(scope); var event = $.Event('dragover'); event.preventDefault = window.jasmine.createSpy('preventDefault'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; element.trigger(event); expect(event.preventDefault).toHaveBeenCalled(); }); it('should show drop area, when drag enter allowed element', function () { prepareDirective(scope); var event = $.Event('dragenter'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; element.trigger(event); expect(element.find('.drop-area').css('display')).not.toEqual('none'); expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow'); }); it('should call scope onDragEnd, when dragging ends', function () { prepareDirective(scope); var event = $.Event('dragend'); var isolateScope = element.isolateScope(); spyOn(isolateScope, 'onDragEnd'); element.trigger(event); expect(isolateScope.onDragEnd).toHaveBeenCalled(); }); it('should set drag data and call scope onDrag, when drag starts', function () { prepareDirective(scope); var event = $.Event('dragstart'); event.originalEvent = { dataTransfer: { setData: window.jasmine.createSpy('setData') } }; var isolateScope = element.isolateScope(); spyOn(isolateScope, 'onDrag'); element.find('.draggable').trigger(event); expect(isolateScope.onDrag).toHaveBeenCalled(); expect(event.originalEvent.dataTransfer.setData).toHaveBeenCalledWith('draggedRow', 'element-id'); }); it('should prevent default, when dragging over allowed drop area', function () { prepareDirective(scope); var event = $.Event('dragover'); event.preventDefault = window.jasmine.createSpy('preventDefault'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; element.find('.drop-area').trigger(event); expect(event.preventDefault).toHaveBeenCalled(); }); it('should show drop area, when drag enter allowed drop area', function () { prepareDirective(scope); var event = $.Event('dragenter'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; element.find('.drop-area').trigger(event); expect(element.find('.drop-area').css('display')).not.toEqual('none'); expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow'); }); it('should hide drop area, when drag leave drop area', function () { prepareDirective(scope); var event = $.Event('dragleave'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; element.find('.drop-area').trigger(event); expect(element.find('.drop-area').css('display')).toEqual('none'); expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow'); }); it('should hide drop area and call scope onDrop, when drop on drop area', function () { prepareDirective(scope); var event = $.Event('drop'); event.preventDefault = window.jasmine.createSpy('preventDefault'); event.originalEvent = { dataTransfer: { types: {}, getData: window.jasmine.createSpy('getData').and.returnValue("element-id") } }; var isolateScope = element.isolateScope(); spyOn(isolateScope, 'onDrop'); element.find('.drop-area').trigger(event); expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow'); expect(event.preventDefault).toHaveBeenCalled(); expect(element.find('.drop-area').css('display')).toEqual('none'); expect(isolateScope.onDrop).toHaveBeenCalled(); }); });
wongatech/remi
ReMi.Web/ReMi.Web.UI.Tests/Tests/app/common/directives/draggableRowTests.js
JavaScript
mit
5,831
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Ninject.Modules; using Ninject.Extensions.Conventions; namespace SongManager.Web.NinjectSupport { /// <summary> /// Automatically loads all Boot Modules and puts them into the Ninject Dependency Resolver /// </summary> public class DependencyBindingsModule : NinjectModule { public override void Load() { // Bind all BootModules Kernel.Bind( i => i.FromAssembliesMatching( "SongManager.Web.dll", "SongManager.Web.Core.dll", "SongManager.Web.Data.dll", "SongManager.Core.dll" ) .SelectAllClasses() .InheritedFrom( typeof( SongManager.Core.Boot.IBootModule ) ) .BindSingleInterface() ); } } }
fjeller/ADC2016_Mvc5Sample
SongManager/SongManager.Web/NinjectSupport/DependencyBindingsModule.cs
C#
mit
725
package com.kromracing.runningroute.client; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Widget; final public class Utils { private Utils() { } /** * Sets the HTML id for a widget. * @param widget The widget to have the id set, ex: TextBox * @param id ID in HTML, ex: textbox-location */ static void setId(final Widget widget, final String id) { if (widget instanceof CheckBox) { final Element checkBoxElement = widget.getElement(); // The first element is the actual box to check. That is the one we care about. final Element inputElement = DOM.getChild(checkBoxElement, 0); inputElement.setAttribute("id", id); //DOM.setElementAttribute(inputElement, "id", id); deprecated! } else { widget.getElement().setAttribute("id", id); //DOM.setElementAttribute(widget.getElement(), "id", id); deprecated! } } }
chadrosenquist/running-route
src/main/java/com/kromracing/runningroute/client/Utils.java
Java
mit
1,100
/** * This file was copied from https://github.com/jenkinsci/mercurial-plugin/raw/master/src/test/java/hudson/plugins/mercurial/MercurialRule.java * so we as well have a MercurialRule to create test repos with. * The file is licensed under the MIT License, which can by found at: http://www.opensource.org/licenses/mit-license.php * More information about this file and it's authors can be found at: https://github.com/jenkinsci/mercurial-plugin/ */ package org.paylogic.jenkins.advancedscm; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.Action; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import hudson.plugins.mercurial.HgExe; import hudson.plugins.mercurial.MercurialTagAction; import hudson.scm.PollingResult; import hudson.util.ArgumentListBuilder; import hudson.util.StreamTaskListener; import org.junit.Assume; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.ExternalResource; import org.jvnet.hudson.test.JenkinsRule; import org.paylogic.jenkins.ABuildCause; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import static java.util.Collections.sort; import static org.junit.Assert.*; public final class MercurialRule extends ExternalResource { private TaskListener listener; private final JenkinsRule j; public MercurialRule(JenkinsRule j) { this.j = j; } @Override protected void before() throws Exception { listener = new StreamTaskListener(System.out, Charset.defaultCharset()); try { if (new ProcessBuilder("hg", "--version").start().waitFor() != 0) { throw new AssumptionViolatedException("hg --version signaled an error"); } } catch(IOException ioe) { String message = ioe.getMessage(); if(message.startsWith("Cannot run program \"hg\"") && message.endsWith("No such file or directory")) { throw new AssumptionViolatedException("hg is not available; please check that your PATH environment variable is properly configured"); } Assume.assumeNoException(ioe); // failed to check availability of hg } } private Launcher launcher() { return j.jenkins.createLauncher(listener); } private HgExe hgExe() throws Exception { return new HgExe(null, null, launcher(), j.jenkins, listener, new EnvVars()); } public void hg(String... args) throws Exception { HgExe hg = hgExe(); assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).join()); } public void hg(File repo, String... args) throws Exception { HgExe hg = hgExe(); assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).pwd(repo).join()); } private static ArgumentListBuilder nobody(ArgumentListBuilder args) { return args.add("--config").add("[email protected]"); } public void touchAndCommit(File repo, String... names) throws Exception { for (String name : names) { FilePath toTouch = new FilePath(repo).child(name); if (!toTouch.exists()) { toTouch.getParent().mkdirs(); toTouch.touch(0); hg(repo, "add", name); } else { toTouch.write(toTouch.readToString() + "extra line\n", "UTF-8"); } } hg(repo, "commit", "--message", "added " + Arrays.toString(names)); } public String buildAndCheck(FreeStyleProject p, String name, Action... actions) throws Exception { FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new ABuildCause(), actions).get()); // Somehow this needs a cause or it will fail if (!b.getWorkspace().child(name).exists()) { Set<String> children = new TreeSet<String>(); for (FilePath child : b.getWorkspace().list()) { children.add(child.getName()); } fail("Could not find " + name + " among " + children); } assertNotNull(b.getAction(MercurialTagAction.class)); @SuppressWarnings("deprecation") String log = b.getLog(); return log; } public PollingResult pollSCMChanges(FreeStyleProject p) { return p.poll(new StreamTaskListener(System.out, Charset .defaultCharset())); } public String getLastChangesetId(File repo) throws Exception { return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-l1", "--template", "{node}")); } public String[] getBranches(File repo) throws Exception { String rawBranches = hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("branches")); ArrayList<String> list = new ArrayList<String>(); for (String line: rawBranches.split("\n")) { // line should contain: <branchName> <revision>:<hash> (yes, with lots of whitespace) String[] seperatedByWhitespace = line.split("\\s+"); String branchName = seperatedByWhitespace[0]; list.add(branchName); } sort(list); return list.toArray(new String[list.size()]); } public String searchLog(File repo, String query) throws Exception { return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-k", query)); } }
jenkinsci/gatekeeper-plugin
src/test/java/org/paylogic/jenkins/advancedscm/MercurialRule.java
Java
mit
5,618
package zhou.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by zzhoujay on 2015/7/22 0022. */ public class NormalAdapter extends RecyclerView.Adapter<NormalAdapter.Holder> { private List<String> msg; public NormalAdapter(List<String> msg) { this.msg = msg; } @Override public Holder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_normal, null); Holder holder = new Holder(view); return holder; } @Override public void onBindViewHolder(Holder holder, int position) { String m = msg.get(position); holder.icon.setImageResource(R.mipmap.ic_launcher); holder.text.setText(m); } @Override public int getItemCount() { return msg == null ? 0 : msg.size(); } public static class Holder extends RecyclerView.ViewHolder { public TextView text; public ImageView icon; public Holder(View itemView) { super(itemView); text = (TextView) itemView.findViewById(R.id.item_text); icon = (ImageView) itemView.findViewById(R.id.item_icon); } } }
ChinaKim/AdvanceAdapter
app/src/main/java/zhou/adapter/NormalAdapter.java
Java
mit
1,412
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;GulfCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;位元幣&lt;/b&gt;版本</translation> </message> <message> <location line="+57"/> <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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> 這是一套實驗性的軟體. 此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php. 此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>版權</translation> </message> <message> <location line="+0"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>位址簿</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>點兩下來修改位址或標記</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>產生新位址</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>複製目前選取的位址到系統剪貼簿</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>新增位址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your GulfCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>複製位址</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>顯示 &amp;QR 條碼</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a GulfCoin address</source> <translation>簽署訊息是用來證明位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>從列表中刪除目前選取的位址</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>刪除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your GulfCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>編輯</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>付錢</translation> </message> <message> <location line="+265"/> <source>Export Address Book Data</source> <translation>匯出位址簿資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號區隔資料檔 (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入檔案 %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(沒有標記)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>密碼對話視窗</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>輸入密碼</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>新的密碼</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>重複新密碼</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <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>輸入錢包的新密碼.&lt;br/&gt;請用&lt;b&gt;10個以上的字元&lt;/b&gt;, 或是&lt;b&gt;8個以上的單字&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>錢包加密</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>這個動作需要用你的錢包密碼來解鎖</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>錢包解鎖</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>這個動作需要用你的錢包密碼來解密</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>錢包解密</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>變更密碼</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>輸入錢包的新舊密碼.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>錢包加密確認</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>警告: 如果將錢包加密後忘記密碼, 你會&lt;b&gt;失去其中所有的位元幣&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>你確定要將錢包加密嗎?</translation> </message> <message> <location line="+15"/> <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>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>警告: 大寫字母鎖定作用中!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>錢包已加密</translation> </message> <message> <location line="-56"/> <source>GulfCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your gulfcoins from being stolen by malware infecting your computer.</source> <translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>錢包加密失敗</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>提供的密碼不符.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>錢包解鎖失敗</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用來解密錢包的密碼輸入錯誤.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>錢包解密失敗</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>錢包密碼變更成功.</translation> </message> </context> <context> <name>GulfCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+254"/> <source>Sign &amp;message...</source> <translation>訊息簽署...</translation> </message> <message> <location line="+246"/> <source>Synchronizing with network...</source> <translation>網路同步中...</translation> </message> <message> <location line="-321"/> <source>&amp;Overview</source> <translation>總覽</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>顯示錢包一般總覽</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>交易</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>瀏覽交易紀錄</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>編輯位址與標記的儲存列表</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>顯示收款位址的列表</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>結束</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>結束應用程式</translation> </message> <message> <location line="+7"/> <source>Show information about GulfCoin</source> <translation>顯示位元幣相關資訊</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>關於 &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>顯示有關於 Qt 的資訊</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>選項...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>錢包加密...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>錢包備份...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>密碼變更...</translation> </message> <message> <location line="+251"/> <source>Importing blocks from disk...</source> <translation>從磁碟匯入區塊中...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>重建磁碟區塊索引中...</translation> </message> <message> <location line="-319"/> <source>Send coins to a GulfCoin address</source> <translation>付錢到位元幣位址</translation> </message> <message> <location line="+52"/> <source>Modify configuration options for GulfCoin</source> <translation>修改位元幣的設定選項</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>將錢包備份到其它地方</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>變更錢包加密用的密碼</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>除錯視窗</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>開啓除錯與診斷主控台</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>驗證訊息...</translation> </message> <message> <location line="-183"/> <location line="+6"/> <location line="+508"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="-514"/> <location line="+6"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+107"/> <source>&amp;Send</source> <translation>付出</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>收受</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>位址</translation> </message> <message> <location line="+23"/> <location line="+2"/> <source>&amp;About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+10"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>顯示或隱藏</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>顯示或隱藏主視窗</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>將屬於你的錢包的密鑰加密</translation> </message> <message> <location line="+7"/> <source>Sign messages with your GulfCoin addresses to prove you own them</source> <translation>用位元幣位址簽署訊息來證明那是你的</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified GulfCoin addresses</source> <translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>檔案</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>設定</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>求助</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>分頁工具列</translation> </message> <message> <location line="-228"/> <location line="+288"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-5"/> <location line="+5"/> <source>GulfCoin client</source> <translation>位元幣客戶端軟體</translation> </message> <message numerus="yes"> <location line="+121"/> <source>%n active connection(s) to GulfCoin network</source> <translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>目前沒有區塊來源...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>已處理了 %1 個區塊的交易紀錄.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n 個小時</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n 天</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n 個星期</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>落後 %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>最近收到的區塊是在 %1 之前生產出來.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>會看不見在這之後的交易.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>最新狀態</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>進度追趕中...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>確認交易手續費</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>付款交易</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>收款交易</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金額: %2 類別: %3 位址: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI 處理</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid GulfCoin address or malformed URI parameters.</source> <translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;解鎖中&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;上鎖中&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+110"/> <source>A fatal error occurred. GulfCoin can no longer continue safely and will quit.</source> <translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+105"/> <source>Network Alert</source> <translation>網路警報</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>編輯位址</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>標記</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>與這個位址簿項目關聯的標記</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>位址</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>新收款位址</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>新增付款位址</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>編輯收款位址</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>編輯付款位址</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>輸入的位址&quot;%1&quot;已存在於位址簿中.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid GulfCoin address.</source> <translation>輸入的位址 &quot;%1&quot; 並不是有效的位元幣位址.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>無法將錢包解鎖.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>新密鑰產生失敗.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation>將會建立新的資料目錄.</translation> </message> <message> <location line="+22"/> <source>name</source> <translation>名稱</translation> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>目錄已經存在了. 如果你要在裡面建立新目錄的話, 請加上 %1.</translation> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation>已經存在該路徑了, 並且不是一個目錄.</translation> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation>無法在這裡新增資料目錄</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+517"/> <location line="+13"/> <source>GulfCoin-Qt</source> <translation>位元幣-Qt</translation> </message> <message> <location line="-13"/> <source>version</source> <translation>版本</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>使用界面選項</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>設定語言, 比如說 &quot;de_DE&quot; (預設: 系統語系)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>啓動時最小化 </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>顯示啓動畫面 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation>啓動時選擇資料目錄 (預設值: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation>歡迎</translation> </message> <message> <location line="+9"/> <source>Welcome to GulfCoin-Qt.</source> <translation>歡迎使用&quot;位元幣-Qt&quot;</translation> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where GulfCoin-Qt will store its data.</source> <translation>由於這是程式第一次啓動, 你可以選擇&quot;位元幣-Qt&quot;儲存資料的地方.</translation> </message> <message> <location line="+10"/> <source>GulfCoin-Qt will download and store a copy of the GulfCoin 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>位元幣-Qt 會下載並儲存一份位元幣區塊鏈結的拷貝. 至少有 %1GB 的資料會儲存到這個目錄中, 並且還會持續增長. 另外錢包資料也會儲存在這個目錄.</translation> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation>用預設的資料目錄</translation> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation>用自定的資料目錄:</translation> </message> <message> <location filename="../intro.cpp" line="+100"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation>GB 可用空間</translation> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation>(需要 %1GB)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>選項</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>主要</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>付交易手續費</translation> </message> <message> <location line="+31"/> <source>Automatically start GulfCoin after logging in to the system.</source> <translation>在登入系統後自動啓動位元幣.</translation> </message> <message> <location line="+3"/> <source>&amp;Start GulfCoin on system login</source> <translation>系統登入時啟動位元幣</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>回復所有客戶端軟體選項成預設值.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>選項回復</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>網路</translation> </message> <message> <location line="+6"/> <source>Automatically open the GulfCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自動在路由器上開啟 GulfCoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>用 &amp;UPnP 設定通訊埠對應</translation> </message> <message> <location line="+7"/> <source>Connect to the GulfCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>透過 SOCKS 代理伺服器連線:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>代理伺服器位址:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>通訊埠:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>代理伺服器的通訊埠 (比如說 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 協定版本:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>視窗</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>最小化視窗後只在通知區域顯示圖示</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>最小化至通知區域而非工作列</translation> </message> <message> <location line="+7"/> <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>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>關閉時最小化</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>顯示</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>使用界面語言</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting GulfCoin.</source> <translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>金額顯示單位:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>選擇操作界面與付錢時預設顯示的細分單位.</translation> </message> <message> <location line="+9"/> <source>Whether to show GulfCoin addresses in the transaction list or not.</source> <translation>是否要在交易列表中顯示位元幣位址.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>在交易列表顯示位址</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>好</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>取消</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>套用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+54"/> <source>default</source> <translation>預設</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>確認回復選項</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>你想要就做下去嗎?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting GulfCoin.</source> <translation>這個設定會在位元幣程式重啓後生效.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>提供的代理伺服器位址無效</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GulfCoin network after a connection is established, but this process has not completed yet.</source> <translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation>未確認金額:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation>已確認金額:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>目前可用餘額</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>尚未確認的交易的總金額, 可用餘額不包含此金額</translation> </message> <message> <location line="+13"/> <source>Immature:</source> <translation>未熟成</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>尚未熟成的開採金額</translation> </message> <message> <location line="+13"/> <source>Total:</source> <translation>總金額:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>目前全部餘額</translation> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;最近交易&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>沒同步</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+108"/> <source>Cannot start gulfcoin: click-to-pay handler</source> <translation>無法啟動 gulfcoin 隨按隨付處理器</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+92"/> <location filename="../intro.cpp" line="-32"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>錯誤: 不存在指定的資料目錄 &quot;%1&quot;.</translation> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>錯誤: 無法新增指定的資料目錄 &quot;%1&quot;.</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR 條碼對話視窗</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>付款單</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>金額:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>標記:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>訊息:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>儲存為...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+64"/> <source>Error encoding URI into QR Code.</source> <translation>將 URI 編碼成 QR 條碼失敗</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>輸入的金額無效, 請檢查看看.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>儲存 QR 條碼</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG 圖檔 (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>客戶端軟體名稱</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+345"/> <source>N/A</source> <translation>無</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>客戶端軟體版本</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>資訊</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>使用 OpenSSL 版本</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>啓動時間</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>網路</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>連線數</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>位於測試網路</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>區塊鎖鏈</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>目前區塊數</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>估算總區塊數</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>最近區塊時間</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>開啓</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+7"/> <source>Show the GulfCoin-Qt help message to get a list with possible GulfCoin command-line options.</source> <translation>顯示&quot;位元幣-Qt&quot;的求助訊息, 來取得可用的命令列選項列表.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>顯示</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>主控台</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>建置日期</translation> </message> <message> <location line="-104"/> <source>GulfCoin - Debug window</source> <translation>位元幣 - 除錯視窗</translation> </message> <message> <location line="+25"/> <source>GulfCoin Core</source> <translation>位元幣核心</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>除錯紀錄檔</translation> </message> <message> <location line="+7"/> <source>Open the GulfCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>清主控台</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the GulfCoin RPC console.</source> <translation>歡迎使用位元幣 RPC 主控台.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>請用上下游標鍵來瀏覽歷史指令, 且可用 &lt;b&gt;Ctrl-L&lt;/b&gt; 來清理畫面.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>請打 &lt;b&gt;help&lt;/b&gt; 來看可用指令的簡介.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+128"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>付錢</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>一次付給多個人</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>加收款人</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>移除所有交易欄位</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+10"/> <source>123.456 ABC</source> <translation>123.456 ABC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>確認付款動作</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>付出</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-62"/> <location line="+2"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 給 %2 (%3)</translation> </message> <message> <location line="+6"/> <source>Confirm send coins</source> <translation>確認要付錢</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>確定要付出 %1 嗎?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>和</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>無效的收款位址, 請再檢查看看.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>付款金額必須大於 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>金額超過餘額了.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>錯誤: 交易產生失敗!</translation> </message> <message> <location line="+5"/> <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>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>金額:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>付給:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>輸入一個標記給這個位址, 並加到位址簿中</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>標記:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>從位址簿中選一個位址</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>去掉這個收款人</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>簽章 - 簽署或驗證訊息</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+6"/> <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>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>從位址簿選一個位址</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>在這裡輸入你想簽署的訊息</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>簽章</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>複製目前的簽章到系統剪貼簿</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this GulfCoin address</source> <translation>簽署訊息是用來證明這個位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>重置所有訊息簽署欄位</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+6"/> <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>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用&quot;中間人攻擊法&quot;詐騙.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>重置所有訊息驗證欄位</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>按&quot;訊息簽署&quot;來產生簽章</translation> </message> <message> <location line="+3"/> <source>Enter GulfCoin signature</source> <translation>輸入位元幣簽章</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>輸入的位址無效.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>請檢查位址是否正確後再試一次.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>輸入的位址沒有指到任何密鑰.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>錢包解鎖已取消.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>沒有所輸入位址的密鑰.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>訊息簽署失敗.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>訊息已簽署.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>無法將這個簽章解碼.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>請檢查簽章是否正確後再試一次.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>這個簽章與訊息的數位摘要不符.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>訊息驗證失敗.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>訊息已驗證.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/離線中</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/未確認</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>經確認 %1 次</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>狀態</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, 已公告至 %n 個節點</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>來源</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>生產出</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>來處</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>目的</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>自己的位址</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>標籤</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>入帳</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>不被接受</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>出帳</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>交易手續費</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>淨額</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>訊息</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>附註</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>交易識別碼</translation> </message> <message> <location line="+3"/> <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>生產出來的錢要再等 1 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成&quot;不被接受&quot;, 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>除錯資訊</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>交易</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>輸入</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>是</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>否</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, 尚未成功公告出去</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>未知</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>交易明細</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>此版面顯示交易的詳細說明</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>金額</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>離線中 (經確認 %1 次)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>已確認 (經確認 %1 次)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>生產出但不被接受</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>收受自</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>付給自己</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(不適用)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>收到交易的日期與時間.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>交易的種類.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>交易的目標位址.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>減去或加入至餘額的金額</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>全部</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>今天</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>這週</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>這個月</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>上個月</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>今年</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>指定範圍...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>給自己</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>其他</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>輸入位址或標記來搜尋</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>最小金額</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>複製位址</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>複製金額</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>複製交易識別碼</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>編輯標記</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>顯示交易明細</translation> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation>匯出交易資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號分隔資料檔 (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>已確認</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>識別碼</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入至 %1 檔案.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>範圍:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>至</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>付錢</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+197"/> <source>Backup Wallet</source> <translation>錢包備份</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>錢包資料檔 (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>備份失敗</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>儲存錢包資料到新的地方失敗</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>備份成功</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>錢包的資料已經成功儲存到新的地方了.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+98"/> <source>GulfCoin version</source> <translation>位元幣版本</translation> </message> <message> <location line="+104"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="-30"/> <source>Send command to -server or gulfcoind</source> <translation>送指令給 -server 或 gulfcoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>列出指令 </translation> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation>取得指令說明 </translation> </message> <message> <location line="+25"/> <source>Options:</source> <translation>選項: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: gulfcoin.conf)</source> <translation>指定設定檔 (預設: gulfcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: gulfcoind.pid)</source> <translation>指定行程識別碼檔案 (預設: gulfcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>指定資料目錄 </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 12401 or testnet: 22401)</source> <translation>在通訊埠 &lt;port&gt; 聽候連線 (預設: 12401, 或若為測試網路: 22401)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>維持與節點連線數的上限為 &lt;n&gt; 個 (預設: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>指定自己公開的位址</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation> </message> <message> <location line="-136"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 12402 or testnet: 22402)</source> <translation>在通訊埠 &lt;port&gt; 聽候 JSON-RPC 連線 (預設: 12402, 或若為測試網路: 22402)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令列與 JSON-RPC 指令 </translation> </message> <message> <location line="+77"/> <source>Run in the background as a daemon and accept commands</source> <translation>以背景程式執行並接受指令</translation> </message> <message> <location line="+38"/> <source>Use the test network</source> <translation>使用測試網路 </translation> </message> <message> <location line="-114"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=gulfcoinrpc 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;GulfCoin Alert&quot; [email protected] </source> <translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword): %s 建議你使用以下隨機產生的密碼: rpcuser=gulfcoinrpc rpcpassword=%s (你不用記住這個密碼) 使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同! 如果設定檔還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;. 也建議你設定警示通知, 發生問題時你才會被通知到; 比如說設定為: alertnotify=echo %%s | mail -s &quot;GulfCoin Alert&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 &quot;[主機]:通訊埠&quot; 這種格式</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. GulfCoin is probably already running.</source> <translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+3"/> <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>進入回歸測試模式, 特別的區塊鎖鏈使用中, 可以立即解出區塊. 目的是用來做回歸測試, 以及配合應用程式的開發.</translation> </message> <message> <location line="+4"/> <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>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> <message> <location line="+4"/> <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>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong GulfCoin will not work properly.</source> <translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation> </message> <message> <location line="+3"/> <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>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>區塊產生選項:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>只連線至指定節點(可多個)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>發現區塊資料庫壞掉了</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>你要現在重建區塊資料庫嗎?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>初始化區塊資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>錢包資料庫環境 %s 初始化錯誤!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>載入區塊資料庫失敗</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>打開區塊資料庫檔案失敗</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>錯誤: 磁碟空間很少!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>錯誤: 系統錯誤:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>讀取區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>讀取區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>同步區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>寫入區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>寫入區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>寫入區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>寫入檔案資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>寫入位元幣資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>寫入交易索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>寫入回復資料失敗</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>生產位元幣 (預設值: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>創世區塊不正確或找不到. 資料目錄錯了嗎?</translation> </message> <message> <location line="+18"/> <source>Not enough file descriptors available.</source> <translation>檔案描述器不足.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation>指定錢包檔(會在資料目錄中)</translation> </message> <message> <location line="+20"/> <source>Verifying blocks...</source> <translation>驗證區塊資料中...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>驗證錢包資料中...</translation> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation>錢包檔 %s 沒有在資料目錄 %s 裡面</translation> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation> </message> <message> <location line="-76"/> <source>Imports blocks from external blk000??.dat file</source> <translation>從其它來源的 blk000??.dat 檔匯入區塊</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation> </message> <message> <location line="+78"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>無效的 -tor 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -minrelaytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -mintxfee=&lt;amount&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>維護全部交易的索引 (預設為 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>每個連線的接收緩衝區大小上限為 &lt;n&gt;*1000 個位元組 (預設: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>每個連線的傳送緩衝區大小上限為 &lt;n&gt;*1000 位元組 (預設: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>只和 &lt;net&gt; 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>輸出額外的網路除錯資訊</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>在除錯輸出內容前附加時間</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the GulfCoin Wiki for SSL setup instructions)</source> <translation>SSL 選項: (SSL 設定程序請見 GulfCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>輸出追蹤或除錯資訊給除錯器</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>設定區塊大小下限為多少位元組 (預設: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>簽署交易失敗</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation> </message> <message> <location line="+5"/> <source>System error: </source> <translation>系統錯誤:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>交易金額太小</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>交易金額必須是正的</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>交易位元量太大</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 連線使用者名稱</translation> </message> <message> <location line="+5"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation> </message> <message> <location line="-52"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 連線密碼</translation> </message> <message> <location line="-68"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>只允許從指定網路位址來的 JSON-RPC 連線</translation> </message> <message> <location line="+77"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>送指令給在 &lt;ip&gt; 的節點 (預設: 127.0.0.1) </translation> </message> <message> <location line="-121"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation> </message> <message> <location line="+149"/> <source>Upgrade wallet to latest format</source> <translation>將錢包升級成最新的格式</translation> </message> <message> <location line="-22"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>設定密鑰池大小為 &lt;n&gt; (預設: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation> </message> <message> <location line="+36"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>於 JSON-RPC 連線使用 OpenSSL (https) </translation> </message> <message> <location line="-27"/> <source>Server certificate file (default: server.cert)</source> <translation>伺服器憑證檔 (預設: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>伺服器密鑰檔 (預設: server.pem) </translation> </message> <message> <location line="-156"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+171"/> <source>This help message</source> <translation>此協助訊息 </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation> </message> <message> <location line="-93"/> <source>Connect through socks proxy</source> <translation>透過 SOCKS 代理伺服器連線</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation> </message> <message> <location line="+56"/> <source>Loading addresses...</source> <translation>載入位址中...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of GulfCoin</source> <translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 GulfCoin</translation> </message> <message> <location line="+96"/> <source>Wallet needed to be rewritten: restart GulfCoin to complete</source> <translation>錢包需要重寫: 請重啟位元幣來完成</translation> </message> <message> <location line="-98"/> <source>Error loading wallet.dat</source> <translation>載入檔案 wallet.dat 失敗</translation> </message> <message> <location line="+29"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>無效的 -proxy 位址: &apos;%s&apos;</translation> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>在 -onlynet 指定了不明的網路別: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>在 -socks 指定了不明的代理協定版本: %i</translation> </message> <message> <location line="-98"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>無法解析 -bind 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>無法解析 -externalip 位址: &apos;%s&apos;</translation> </message> <message> <location line="+45"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -paytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>無效的金額</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>累積金額不足</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>載入區塊索引中...</translation> </message> <message> <location line="-58"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. GulfCoin is probably already running.</source> <translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>交易付款時每 KB 的交易手續費</translation> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>載入錢包中...</translation> </message> <message> <location line="-53"/> <source>Cannot downgrade wallet</source> <translation>無法將錢包格式降級</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>無法寫入預設位址</translation> </message> <message> <location line="+65"/> <source>Rescanning...</source> <translation>重新掃描中...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>載入完成</translation> </message> <message> <location line="+84"/> <source>To use the %s option</source> <translation>為了要使用 %s 選項</translation> </message> <message> <location line="-76"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="-31"/> <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>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=&lt;password&gt;): %s 如果這個檔案還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;.</translation> </message> </context> </TS>
coingulf/gulfcoin
src/qt/locale/bitcoin_zh_TW.ts
TypeScript
mit
119,082
package UserInterface.Animation; /** * Makes shit get big, makes shit get small. */ public class SizeAnimation extends Animation { protected int iW, iH, fW, fH, cW, cH; public SizeAnimation(long period, int paceType, boolean loop, int iW, int iH, int fW, int fH) { super(period, paceType, loop); this.iW = iW; this.iH = iH; this.fW = fW; this.fH = fH; this.cW = iW; this.cH = iH; } @Override protected void updateAnimation(double p) { cW = (int)Math.round((fW - iW)*p) + iW; cH = (int)Math.round((fH - iH)*p) + iH; } public int getWidth() { return cW; } public int getHeight() { return cH; } }
Daskie/Crazy8-CPE-103
src/UserInterface/Animation/SizeAnimation.java
Java
mit
731
import _ from 'lodash'; import { createSelector } from 'reselect'; const srcFilesSelector = state => state.srcFiles; const featuresSelector = state => state.features; const featureByIdSelector = state => state.featureById; const keywordSelector = (state, keyword) => keyword; function getMarks(feature, ele) { const marks = []; switch (ele.type) { case 'component': if (ele.connectToStore) marks.push('C'); if (_.find(feature.routes, { component: ele.name })) marks.push('R'); break; case 'action': if (ele.isAsync) marks.push('A'); break; default: break; } return marks; } function getComponentsTreeData(feature) { const components = feature.components; return { key: `${feature.key}-components`, className: 'components', label: 'Components', icon: 'appstore-o', count: components.length, children: components.map(comp => ({ key: comp.file, className: 'component', label: comp.name, icon: 'appstore-o', searchable: true, marks: getMarks(feature, comp), })), }; } function getActionsTreeData(feature) { const actions = feature.actions; return { key: `${feature.key}-actions`, className: 'actions', label: 'Actions', icon: 'notification', count: actions.length, children: actions.map(action => ({ key: action.file, className: 'action', label: action.name, icon: 'notification', searchable: true, marks: getMarks(feature, action), })), }; } function getChildData(child) { return { key: child.file, className: child.children ? 'misc-folder' : 'misc-file', label: child.name, icon: child.children ? 'folder' : 'file', searchable: !child.children, children: child.children ? child.children.map(getChildData) : null, }; } function getMiscTreeData(feature) { const misc = feature.misc; return { key: `${feature.key}-misc`, className: 'misc', label: 'Misc', icon: 'folder', children: misc.map(getChildData), }; } export const getExplorerTreeData = createSelector( srcFilesSelector, featuresSelector, featureByIdSelector, (srcFiles, features, featureById) => { const featureNodes = features.map((fid) => { const feature = featureById[fid]; return { key: feature.key, className: 'feature', label: feature.name, icon: 'book', children: [ { label: 'Routes', key: `${fid}-routes`, searchable: false, className: 'routes', icon: 'share-alt', count: feature.routes.length }, getActionsTreeData(feature), getComponentsTreeData(feature), getMiscTreeData(feature), ], }; }); const allNodes = [ { key: 'features', label: 'Features', icon: 'features', children: _.compact(featureNodes), }, { key: 'others-node', label: 'Others', icon: 'folder', children: srcFiles.map(getChildData), } ]; return { root: true, children: allNodes }; } ); function filterTreeNode(node, keyword) { const reg = new RegExp(_.escapeRegExp(keyword), 'i'); return { ...node, children: _.compact(node.children.map((child) => { if (child.searchable && reg.test(child.label)) return child; if (child.children) { const c = filterTreeNode(child, keyword); return c.children.length > 0 ? c : null; } return null; })), }; } export const getFilteredExplorerTreeData = createSelector( getExplorerTreeData, keywordSelector, (treeData, keyword) => { if (!keyword) return treeData; return filterTreeNode(treeData, keyword); } ); // when searching the tree, all nodes should be expanded, the tree component needs expandedKeys property. export const getExpandedKeys = createSelector( getFilteredExplorerTreeData, (treeData) => { const keys = []; let arr = [...treeData.children]; while (arr.length) { const pop = arr.pop(); if (pop.children) { keys.push(pop.key); arr = [...arr, ...pop.children]; } } return keys; } );
supnate/rekit-portal
src/features/home/selectors/explorerTreeData.js
JavaScript
mit
4,178
<?php class Receiving_lib { var $CI; function __construct() { $this->CI =& get_instance(); } function get_cart() { if(!$this->CI->session->userdata('cartRecv')) $this->set_cart(array()); return $this->CI->session->userdata('cartRecv'); } function set_cart($cart_data) { $this->CI->session->set_userdata('cartRecv',$cart_data); } function get_supplier() { if(!$this->CI->session->userdata('supplier')) $this->set_supplier(-1); return $this->CI->session->userdata('supplier'); } function set_supplier($supplier_id) { $this->CI->session->set_userdata('supplier',$supplier_id); } function get_mode() { if(!$this->CI->session->userdata('recv_mode')) $this->set_mode('receive'); return $this->CI->session->userdata('recv_mode'); } function set_mode($mode) { $this->CI->session->set_userdata('recv_mode',$mode); } function get_stock_source() { if(!$this->CI->session->userdata('recv_stock_source')) { $location_id = $this->CI->Stock_locations->get_default_location_id(); $this->set_stock_source($location_id); } return $this->CI->session->userdata('recv_stock_source'); } function get_comment() { return $this->CI->session->userdata('comment'); } function set_comment($comment) { $this->CI->session->set_userdata('comment', $comment); } function clear_comment() { $this->CI->session->unset_userdata('comment'); } function get_invoice_number() { return $this->CI->session->userdata('recv_invoice_number'); } function set_invoice_number($invoice_number) { $this->CI->session->set_userdata('recv_invoice_number', $invoice_number); } function clear_invoice_number() { $this->CI->session->unset_userdata('recv_invoice_number'); } function set_stock_source($stock_source) { $this->CI->session->set_userdata('recv_stock_source',$stock_source); } function clear_stock_source() { $this->CI->session->unset_userdata('recv_stock_source'); } function get_stock_destination() { if(!$this->CI->session->userdata('recv_stock_destination')) { $location_id = $this->CI->Stock_locations->get_default_location_id(); $this->set_stock_destination($location_id); } return $this->CI->session->userdata('recv_stock_destination'); } function set_stock_destination($stock_destination) { $this->CI->session->set_userdata('recv_stock_destination',$stock_destination); } function clear_stock_destination() { $this->CI->session->unset_userdata('recv_stock_destination'); } function add_item($item_id,$quantity=1,$item_location,$discount=0,$price=null,$description=null,$serialnumber=null) { //make sure item exists in database. if(!$this->CI->Item->exists($item_id)) { //try to get item id given an item_number $item_id = $this->CI->Item->get_item_id($item_id); if(!$item_id) return false; } //Get items in the receiving so far. $items = $this->get_cart(); //We need to loop through all items in the cart. //If the item is already there, get it's key($updatekey). //We also need to get the next key that we are going to use in case we need to add the //item to the list. Since items can be deleted, we can't use a count. we use the highest key + 1. $maxkey=0; //Highest key so far $itemalreadyinsale=FALSE; //We did not find the item yet. $insertkey=0; //Key to use for new entry. $updatekey=0; //Key to use to update(quantity) foreach ($items as $item) { //We primed the loop so maxkey is 0 the first time. //Also, we have stored the key in the element itself so we can compare. //There is an array function to get the associated key for an element, but I like it better //like that! if($maxkey <= $item['line']) { $maxkey = $item['line']; } if($item['item_id']==$item_id && $item['item_location']==$item_location) { $itemalreadyinsale=TRUE; $updatekey=$item['line']; } } $insertkey=$maxkey+1; $item_info=$this->CI->Item->get_info($item_id,$item_location); //array records are identified by $insertkey and item_id is just another field. $item = array(($insertkey)=> array( 'item_id'=>$item_id, 'item_location'=>$item_location, 'stock_name'=>$this->CI->Stock_locations->get_location_name($item_location), 'line'=>$insertkey, 'name'=>$item_info->name, 'description'=>$description!=null ? $description: $item_info->description, 'serialnumber'=>$serialnumber!=null ? $serialnumber: '', 'allow_alt_description'=>$item_info->allow_alt_description, 'is_serialized'=>$item_info->is_serialized, 'quantity'=>$quantity, 'discount'=>$discount, 'in_stock'=>$this->CI->Item_quantities->get_item_quantity($item_id, $item_location)->quantity, 'price'=>$price!=null ? $price: $item_info->cost_price ) ); //Item already exists if($itemalreadyinsale) { $items[$updatekey]['quantity']+=$quantity; } else { //add to existing array $items+=$item; } $this->set_cart($items); return true; } function edit_item($line,$description,$serialnumber,$quantity,$discount,$price) { $items = $this->get_cart(); if(isset($items[$line])) { $items[$line]['description'] = $description; $items[$line]['serialnumber'] = $serialnumber; $items[$line]['quantity'] = $quantity; $items[$line]['discount'] = $discount; $items[$line]['price'] = $price; $this->set_cart($items); } return false; } function is_valid_receipt($receipt_receiving_id) { //RECV # $pieces = explode(' ',$receipt_receiving_id); if(count($pieces)==2) { return $this->CI->Receiving->exists($pieces[1]); } else { return $this->CI->Receiving->get_receiving_by_invoice_number($receipt_receiving_id)->num_rows() > 0; } return false; } function is_valid_item_kit($item_kit_id) { //KIT # $pieces = explode(' ',$item_kit_id); if(count($pieces)==2) { return $this->CI->Item_kit->exists($pieces[1]); } return false; } function return_entire_receiving($receipt_receiving_id) { //POS # $pieces = explode(' ',$receipt_receiving_id); if ($pieces[0] == "RECV") { $receiving_id = $pieces[1]; } else { $receiving = $this->CI->Receiving->get_receiving_by_invoice_number($receipt_receiving_id)->row(); $receiving_id = $receiving->receiving_id; } $this->empty_cart(); $this->delete_supplier(); $this->clear_comment(); foreach($this->CI->Receiving->get_receiving_items($receiving_id)->result() as $row) { $this->add_item($row->item_id,-$row->quantity_purchased,$row->item_location,$row->discount_percent,$row->item_unit_price,$row->description,$row->serialnumber); } $this->set_supplier($this->CI->Receiving->get_supplier($receiving_id)->person_id); } function add_item_kit($external_item_kit_id,$item_location) { //KIT # $pieces = explode(' ',$external_item_kit_id); $item_kit_id = $pieces[1]; foreach ($this->CI->Item_kit_items->get_info($item_kit_id) as $item_kit_item) { $this->add_item($item_kit_item['item_id'],$item_kit_item['quantity'],$item_location); } } function copy_entire_receiving($receiving_id) { $this->empty_cart(); $this->delete_supplier(); foreach($this->CI->Receiving->get_receiving_items($receiving_id)->result() as $row) { $this->add_item($row->item_id,$row->quantity_purchased,$row->item_location,$row->discount_percent,$row->item_unit_price,$row->description,$row->serialnumber); } $this->set_supplier($this->CI->Receiving->get_supplier($receiving_id)->person_id); $receiving_info=$this->CI->Receiving->get_info($receiving_id); //$this->set_invoice_number($receiving_info->row()->invoice_number); } function copy_entire_requisition($requisition_id,$item_location) { $this->empty_cart(); $this->delete_supplier(); foreach($this->CI->Receiving->get_requisition_items($requisition_id)->result() as $row) { $this->add_item_unit($row->item_id,$row->requisition_quantity,$item_location,$row->description); } $this->set_supplier($this->CI->Receiving->get_supplier($requisition_id)->person_id); $receiving_info=$this->CI->Receiving->get_info($receiving_id); //$this->set_invoice_number($receiving_info->row()->invoice_number); } function delete_item($line) { $items=$this->get_cart(); unset($items[$line]); $this->set_cart($items); } function empty_cart() { $this->CI->session->unset_userdata('cartRecv'); } function delete_supplier() { $this->CI->session->unset_userdata('supplier'); } function clear_mode() { $this->CI->session->unset_userdata('receiving_mode'); } function clear_all() { $this->clear_mode(); $this->empty_cart(); $this->delete_supplier(); $this->clear_comment(); $this->clear_invoice_number(); } function get_item_total($quantity, $price, $discount_percentage) { $total = bcmul($quantity, $price, PRECISION); $discount_fraction = bcdiv($discount_percentage, 100, PRECISION); $discount_amount = bcmul($total, $discount_fraction, PRECISION); return bcsub($total, $discount_amount, PRECISION); } function get_total() { $total = 0; foreach($this->get_cart() as $item) { $total += $this->get_item_total($item['quantity'], $item['price'], $item['discount']); } return $total; } } ?>
songwutk/opensourcepos
application/libraries/Receiving_lib.php
PHP
mit
9,998
package com.mauriciotogneri.apply.compiler.syntactic.nodes.arithmetic; import com.mauriciotogneri.apply.compiler.lexical.Token; import com.mauriciotogneri.apply.compiler.syntactic.TreeNode; import com.mauriciotogneri.apply.compiler.syntactic.nodes.ExpressionBinaryNode; public class ArithmeticModuleNode extends ExpressionBinaryNode { public ArithmeticModuleNode(Token token, TreeNode left, TreeNode right) { super(token, left, right); } @Override public String sourceCode() { return String.format("mod(%s, %s)", left.sourceCode(), right.sourceCode()); } }
mauriciotogneri/apply
src/main/java/com/mauriciotogneri/apply/compiler/syntactic/nodes/arithmetic/ArithmeticModuleNode.java
Java
mit
603
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-user', template: '<router-outlet></router-outlet>' }) export class UserComponent implements OnInit { constructor(public router: Router) { } ngOnInit() { if (this.router.url === '/user') { this.router.navigate(['/dashboard']); } } }
ahmelessawy/Hospital-Dashboard
Client/src/app/layouts/user/user.component.ts
TypeScript
mit
402
exports.login = function* (ctx) { const result = yield ctx.service.mine.login(ctx.request.body); if (!result) { ctx.status = 400; ctx.body = { status: 400, msg: `please check your username and password`, } return; } ctx.body = { access_token: result.access_token, msg: 'login success', }; ctx.status = 200; } exports.signup = function* (ctx) { const result = yield ctx.service.mine.signup(ctx.request.body); if (!result.result) { ctx.status = 400; ctx.body = { status: 400, msg: result.msg, } return; } ctx.status = 201; ctx.body = { status: 201, msg: 'success', } } exports.info = function* (ctx) { const info = yield ctx.service.mine.info(ctx.auth.user_id); if (info == null) { ctx.status = 200; ctx.body = { status: 200, msg: 'there is no info for current user', } return; } ctx.body = info; ctx.status = 200; } exports.statistics = function* (ctx) { const info = yield ctx.service.mine.statistics(ctx.auth.user_id); if (info == null) { ctx.status = 200; ctx.body = { shares_count: 0, friends_count: 0, helpful_count: 0, }; return; } ctx.body = info; ctx.status = 200; } exports.accounts = function* (ctx) { const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id); ctx.body = accounts; ctx.status = 200; } exports.update = function* (ctx) { let profile = ctx.request.body; profile.id = ctx.auth.user_id; const result = yield ctx.service.mine.update(profile); if (result) { ctx.status = 204; return; } ctx.status = 500; ctx.body = { msg: 'update profile failed', } } exports.avatar = function* (ctx) { const parts = ctx.multipart(); const { filename, error } = yield ctx.service.mine.avatar(parts, `avatar/${ctx.auth.user_id}`); if (error) { ctx.status = 500; ctx.body = { status: 500, msg: 'update avatar failed', }; return false; } ctx.status = 200; ctx.body = { filename, msg: 'success', } }
VIPShare/VIPShare-REST-Server
app/controller/mine.js
JavaScript
mit
2,077
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; namespace Umbraco.Core { ///<summary> /// Extension methods for dictionary & concurrentdictionary ///</summary> internal static class DictionaryExtensions { /// <summary> /// Method to Get a value by the key. If the key doesn't exist it will create a new TVal object for the key and return it. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TVal"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <returns></returns> public static TVal GetOrCreate<TKey, TVal>(this IDictionary<TKey, TVal> dict, TKey key) where TVal : class, new() { if (dict.ContainsKey(key) == false) { dict.Add(key, new TVal()); } return dict[key]; } /// <summary> /// Updates an item with the specified key with the specified value /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="updateFactory"></param> /// <returns></returns> /// <remarks> /// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression /// /// If there is an item in the dictionary with the key, it will keep trying to update it until it can /// </remarks> public static bool TryUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory) { TValue curValue; while (dict.TryGetValue(key, out curValue)) { if (dict.TryUpdate(key, updateFactory(curValue), curValue)) return true; //if we're looping either the key was removed by another thread, or another thread //changed the value, so we start again. } return false; } /// <summary> /// Updates an item with the specified key with the specified value /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="updateFactory"></param> /// <returns></returns> /// <remarks> /// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression /// /// WARNING: If the value changes after we've retreived it, then the item will not be updated /// </remarks> public static bool TryUpdateOptimisitic<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory) { TValue curValue; if (!dict.TryGetValue(key, out curValue)) return false; dict.TryUpdate(key, updateFactory(curValue), curValue); return true;//note we return true whether we succeed or not, see explanation below. } /// <summary> /// Converts a dictionary to another type by only using direct casting /// </summary> /// <typeparam name="TKeyOut"></typeparam> /// <typeparam name="TValOut"></typeparam> /// <param name="d"></param> /// <returns></returns> public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d) { var result = new Dictionary<TKeyOut, TValOut>(); foreach (DictionaryEntry v in d) { result.Add((TKeyOut)v.Key, (TValOut)v.Value); } return result; } /// <summary> /// Converts a dictionary to another type using the specified converters /// </summary> /// <typeparam name="TKeyOut"></typeparam> /// <typeparam name="TValOut"></typeparam> /// <param name="d"></param> /// <param name="keyConverter"></param> /// <param name="valConverter"></param> /// <returns></returns> public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d, Func<object, TKeyOut> keyConverter, Func<object, TValOut> valConverter) { var result = new Dictionary<TKeyOut, TValOut>(); foreach (DictionaryEntry v in d) { result.Add(keyConverter(v.Key), valConverter(v.Value)); } return result; } /// <summary> /// Converts a dictionary to a NameValueCollection /// </summary> /// <param name="d"></param> /// <returns></returns> public static NameValueCollection ToNameValueCollection(this IDictionary<string, string> d) { var n = new NameValueCollection(); foreach (var i in d) { n.Add(i.Key, i.Value); } return n; } /// <summary> /// Merges all key/values from the sources dictionaries into the destination dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TK"></typeparam> /// <typeparam name="TV"></typeparam> /// <param name="destination">The source dictionary to merge other dictionaries into</param> /// <param name="overwrite"> /// By default all values will be retained in the destination if the same keys exist in the sources but /// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that /// it will just use the last found key/value if this is true. /// </param> /// <param name="sources">The other dictionaries to merge values from</param> public static void MergeLeft<T, TK, TV>(this T destination, IEnumerable<IDictionary<TK, TV>> sources, bool overwrite = false) where T : IDictionary<TK, TV> { foreach (var p in sources.SelectMany(src => src).Where(p => overwrite || destination.ContainsKey(p.Key) == false)) { destination[p.Key] = p.Value; } } /// <summary> /// Merges all key/values from the sources dictionaries into the destination dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TK"></typeparam> /// <typeparam name="TV"></typeparam> /// <param name="destination">The source dictionary to merge other dictionaries into</param> /// <param name="overwrite"> /// By default all values will be retained in the destination if the same keys exist in the sources but /// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that /// it will just use the last found key/value if this is true. /// </param> /// <param name="source">The other dictionary to merge values from</param> public static void MergeLeft<T, TK, TV>(this T destination, IDictionary<TK, TV> source, bool overwrite = false) where T : IDictionary<TK, TV> { destination.MergeLeft(new[] {source}, overwrite); } /// <summary> /// Returns the value of the key value based on the key, if the key is not found, a null value is returned /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TVal">The type of the val.</typeparam> /// <param name="d">The d.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static TVal GetValue<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, TVal defaultValue = default(TVal)) { if (d.ContainsKey(key)) { return d[key]; } return defaultValue; } /// <summary> /// Returns the value of the key value based on the key as it's string value, if the key is not found, then an empty string is returned /// </summary> /// <param name="d"></param> /// <param name="key"></param> /// <returns></returns> public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key) { if (d.ContainsKey(key)) { return d[key].ToString(); } return String.Empty; } /// <summary> /// Returns the value of the key value based on the key as it's string value, if the key is not found or is an empty string, then the provided default value is returned /// </summary> /// <param name="d"></param> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, string defaultValue) { if (d.ContainsKey(key)) { var value = d[key].ToString(); if (value != string.Empty) return value; } return defaultValue; } /// <summary>contains key ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <typeparam name="TValue">Value Type</typeparam> /// <returns>The contains key ignore case.</returns> public static bool ContainsKeyIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key) { return dictionary.Keys.InvariantContains(key); } /// <summary> /// Converts a dictionary object to a query string representation such as: /// firstname=shannon&lastname=deminick /// </summary> /// <param name="d"></param> /// <returns></returns> public static string ToQueryString(this IDictionary<string, object> d) { if (!d.Any()) return ""; var builder = new StringBuilder(); foreach (var i in d) { builder.Append(String.Format("{0}={1}&", HttpUtility.UrlEncode(i.Key), i.Value == null ? string.Empty : HttpUtility.UrlEncode(i.Value.ToString()))); } return builder.ToString().TrimEnd('&'); } /// <summary>The get entry ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <typeparam name="TValue">The type</typeparam> /// <returns>The entry</returns> public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key) { return dictionary.GetValueIgnoreCase(key, default(TValue)); } /// <summary>The get entry ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <typeparam name="TValue">The type</typeparam> /// <returns>The entry</returns> public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue defaultValue) { key = dictionary.Keys.FirstOrDefault(i => i.InvariantEquals(key)); return key.IsNullOrWhiteSpace() == false ? dictionary[key] : defaultValue; } } }
lars-erik/Umbraco-CMS
src/Umbraco.Core/DictionaryExtensions.cs
C#
mit
12,153
import * as yargs from "yargs"; import { getEnvironment, getSlimConfig } from "../cli-helpers"; export const devCommand: yargs.CommandModule = { command: "dev", describe: "Start a development server.", builder: { open: { alias: "o", type: "boolean", description: "Automatically open the web browser." }, "update-dlls": { alias: "u", type: "boolean", description: "Create dynamically linked libraries for vendors (@angular/core, etc.) and polyfills." }, cordova: { type: "boolean", description: "Output the build to the target directory." }, aot: { type: "boolean", description: "Use the Angular AOT compiler." } }, handler: (options: Options) => { const dllTask = require("../tasks/dll.task"); const devTask = require("../tasks/dev.task"); const rootDir = process.cwd(); const slimConfig = getSlimConfig(rootDir); const environmentVariables = getEnvironment(rootDir); return dllTask(environmentVariables, slimConfig, options["update-dlls"]) .then(() => devTask(environmentVariables, slimConfig, options.open, options.aot)) .then(code => { process.exit(code); }) .catch(code => { process.exit(code); }); } };
INSIDEM2M/slim
src/commands/dev.command.ts
TypeScript
mit
1,457
export const browserVersions = () => { let u = navigator.userAgent return { // 移动终端浏览器版本信息 trident: u.indexOf('Trident') > -1, // IE内核 presto: u.indexOf('Presto') > -1, // opera内核 webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, // 是否iPad webApp: u.indexOf('Safari') === -1 // 是否web应该程序,没有头部与底部 } }
donfo/generator-vue-tpl
generators/app/templates/src/utils/browser.js
JavaScript
mit
833
module YandexMusic class Client include YandexMusic::Auth include YandexMusic::Endpoints::Search include YandexMusic::Endpoints::ArtistAlbums include YandexMusic::Endpoints::AlbumsTracks def initialize(client_id, client_secret) @client_id, @client_secret = client_id, client_secret end private def http @faraday ||= Faraday.new do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP faraday.use YandexMusic::AppHttpClient # run requests through app emulator end end def prepared(params) params.inject({}) do |result, (key, value)| result[key.to_s.gsub("_", "-")] = value result end end def parse_time(string) Time.new(*string.scan(/\d+/).slice(0, 6).map(&:to_i), string.match(/[+-]{1}\d{2}:\d{2}/)[0]).utc end end end
localhots/yandex_music
lib/yandex_music/client.rb
Ruby
mit
962
<?php $hostname = "localhost"; $user = "root"; $password = "admin"; $database = "employees"; mysql_connect($hostname, $user, $password); mysql_set_charset('utf8'); @mysql_select_db($database) or die( "Unable to select database"); mysql_query("SET NAMES 'utf8'"); $mysqli = new mysqli($hostname, $user, $password, $database); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit; } if (!$mysqli->set_charset("utf8")) { printf("Error loading character set utf8: %s\n", $mysqli->error); exit; }
frankyhung93/Learn_Coding
php/mysql/db_connect.php
PHP
mit
554
/** * Get a number suffix * e.g. 1 -> st * @param {int} i number to get suffix * @return suffix */ var getSuffix = function (i) { var j = i % 10, k = i % 100; if (j == 1 && k != 11) { return i + "st"; } if (j == 2 && k != 12) { return i + "nd"; } if (j == 3 && k != 13) { return i + "rd"; } return i + "th"; } module.exports = { getSuffix: getSuffix, };
kayoumido/Ram-Bot
utility/tools.js
JavaScript
mit
429
namespace CSharpGL { partial class FormPropertyGrid { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.SuspendLayout(); // // propertyGrid1 // this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid1.Font = new System.Drawing.Font("宋体", 12F); this.propertyGrid1.Location = new System.Drawing.Point(0, 0); this.propertyGrid1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(534, 545); this.propertyGrid1.TabIndex = 0; // // FormProperyGrid // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(534, 545); this.Controls.Add(this.propertyGrid1); this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.Name = "FormProperyGrid"; this.Text = "FormPropertyGrid"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.PropertyGrid propertyGrid1; } }
bitzhuwei/CSharpGL
Infrastructure/CSharpGL.Models/FormPropertyGrid.Designer.cs
C#
mit
2,212
package net.pinemz.hm.gui; import net.pinemz.hm.R; import net.pinemz.hm.api.HmApi; import net.pinemz.hm.api.Prefecture; import net.pinemz.hm.api.PrefectureCollection; import net.pinemz.hm.storage.CommonSettings; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.google.common.base.Optional; public class SettingsActivity extends BasicActivity { public static final String TAG = "SettingsActivity"; private RequestQueue requestQueue; private HmApi hmApi; private PrefectureCollection prefectures; private CommonSettings settings; private ListView listViewPrefectures; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_settings); this.requestQueue = Volley.newRequestQueue(this.getApplicationContext()); this.hmApi = new HmApi(this.getApplicationContext(), this.requestQueue); this.listViewPrefectures = (ListView)this.findViewById(R.id.listViewPrefectures); assert this.listViewPrefectures != null; // Ý’èƒNƒ‰ƒX‚ð€”õ this.settings = new CommonSettings(this.getApplicationContext()); } @Override protected void onResume() { Log.d(TAG, "onResume"); super.onResume(); // “s“¹•{Œ§‚ð“ǂݍž‚Þ this.loadPrefectures(); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); this.requestQueue = null; this.hmApi = null; // Ý’èƒNƒ‰ƒX‚ð‰ð•ú this.settings = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.d(TAG, "onOptionsItemSelected"); return super.onOptionsItemSelected(item); } public void okButtonClicked(View view) { Log.d(TAG, "okButtonClicked"); assert view instanceof Button; // Œ»Ý‘I‘ð‚³‚ê‚Ä‚¢‚鍀–Ú‚ðŽæ“¾ int checkedPosition = this.listViewPrefectures.getCheckedItemPosition(); Log.v(TAG, "onButtonClicked>getCheckedItemPosition = " + checkedPosition); if (checkedPosition == ListView.INVALID_POSITION) { return; } // ‘I‘ð‚³‚ê‚Ä‚¢‚é“s“¹•{Œ§–¼‚ðŽæ“¾ String checkedPrefectureName = (String)this.listViewPrefectures.getItemAtPosition(checkedPosition); assert checkedPrefectureName != null; // “s“¹•{Œ§‚̃f[ƒ^‚ðŽæ“¾ Optional<Prefecture> prefecture = this.prefectures.getByName(checkedPrefectureName); // ƒf[ƒ^‚ª³í‚É‘¶Ý‚·‚éê‡ if (prefecture.isPresent()) { Log.i(TAG, "Prefecture.id = " + prefecture.get().getId()); Log.i(TAG, "Prefecture.name = " + prefecture.get().getName()); this.saveSettings(prefecture.get()); } } public void cancelButtonClicked(View view) { Log.d(TAG, "cancelButtonClicked"); assert view instanceof Button; this.cancelSettings(); } private void setPrefectures(PrefectureCollection prefectures) { Log.d(TAG, "setPrefectures"); this.prefectures = prefectures; assert prefectures != null; ArrayAdapter<String> adapter = new ArrayAdapter<>( this.getApplicationContext(), android.R.layout.simple_list_item_single_choice, prefectures.getNames() ); this.listViewPrefectures.setAdapter(adapter); this.listViewPrefectures.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // æ“ª‚ð‰Šúó‘Ô‚Å‘I‘ð if (adapter.getCount() > 0) { int prefectureId = this.settings.loadPrefectureId(); // ƒf[ƒ^‚ª•Û‘¶‚³‚ê‚Ä‚È‚¢ê‡‚́AÅ‰‚Ì“s“¹•{Œ§‚ð‘I‘ð if (prefectureId < 0) { prefectureId = prefectures.getIds()[0]; } // “s“¹•{Œ§ ID ‚̈ꗗ‚ðŽæ“¾ Integer[] ids = prefectures.getIds(); // ˆê’v‚µ‚½ê‡A‘I‘ð for (int i = 0; i < ids.length; ++i) { if (ids[i] == prefectureId) { this.listViewPrefectures.setItemChecked(i, true); break; } } } } /** * Ý’è‚ð•Û‘¶‚·‚é * @param prefecture •Û‘¶‚·‚é“s“¹•{Œ§ */ private void saveSettings(Prefecture prefecture) { Log.d(TAG, "saveSettings"); assert prefecture != null; // ’l‚ð•Û‘¶ this.settings.savePrefectureId(prefecture.getId()); // ƒƒbƒZ[ƒW‚ð•\Ž¦ Toast.makeText( this.getApplicationContext(), R.string.setting_save_toast, Toast.LENGTH_SHORT ).show(); this.finish(); } /** * Ý’è‚Ì•Û‘¶‚ðƒLƒƒƒ“ƒZƒ‹‚·‚é */ private void cancelSettings() { Toast.makeText( this.getApplicationContext(), R.string.setting_cancel_toast, Toast.LENGTH_SHORT ).show(); this.finish(); } private void loadPrefectures() { // ƒ[ƒfƒBƒ“ƒOƒƒbƒZ[ƒW‚ð•\Ž¦ this.showProgressDialog(R.string.loading_msg_prefectures); // ƒf[ƒ^‚ð“ǂݍž‚Þ this.hmApi.getPrefectures(new HmApi.Listener<PrefectureCollection>() { @Override public void onSuccess(HmApi api, PrefectureCollection data) { Log.d(TAG, "HmApi.Listener#onSuccess"); SettingsActivity.this.closeDialog(); SettingsActivity.this.setPrefectures(data); } @Override public void onFailure() { Log.e(TAG, "HmApi.Listener#onFailure"); SettingsActivity.this.showFinishAlertDialog( R.string.network_failed_title, R.string.network_failed_msg_prefectures ); } @Override public void onException(Exception exception) { Log.e(TAG, "HmApi.Listener#onException", exception); SettingsActivity.this.showFinishAlertDialog( R.string.network_error_title, R.string.network_error_msg_prefectures ); } }); } }
pine613/android-hm
android-hm/src/net/pinemz/hm/gui/SettingsActivity.java
Java
mit
6,222
/* * This file is part of Zinc, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016, Jamie Mansfield <https://github.com/jamierocks> * * 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 uk.jamierocks.zinc.example; import com.google.common.collect.Lists; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandArgs; import org.spongepowered.api.text.Text; import uk.jamierocks.zinc.Command; import uk.jamierocks.zinc.TabComplete; import java.util.List; public class ExampleCommands { @Command(name = "example") public CommandResult exampleCommand(CommandSource source, CommandArgs args) { source.sendMessage(Text.of("This is the base command.")); return CommandResult.success(); } @Command(parent = "example", name = "sub") public CommandResult exampleSubCommand(CommandSource source, CommandArgs args) { source.sendMessage(Text.of("This is a sub command.")); return CommandResult.success(); } @TabComplete(name = "example") public List<String> tabComplete(CommandSource source, String args) { return Lists.newArrayList(); } }
jamierocks/Zinc
Example/src/main/java/uk/jamierocks/zinc/example/ExampleCommands.java
Java
mit
2,269
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ApplyEditsResult, EndOfLinePreference, FindMatch, IInternalModelContentChange, ISingleEditOperationIdentifier, ITextBuffer, ITextSnapshot, ValidAnnotatedEditOperation, IValidEditOperation } from 'vs/editor/common/model'; import { PieceTreeBase, StringBuffer } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase'; import { SearchData } from 'vs/editor/common/model/textModelSearch'; import { countEOL, StringEOL } from 'vs/editor/common/model/tokensStore'; import { TextChange } from 'vs/editor/common/model/textChange'; export interface IValidatedEditOperation { sortIndex: number; identifier: ISingleEditOperationIdentifier | null; range: Range; rangeOffset: number; rangeLength: number; text: string; eolCount: number; firstLineLength: number; lastLineLength: number; forceMoveMarkers: boolean; isAutoWhitespaceEdit: boolean; } export interface IReverseSingleEditOperation extends IValidEditOperation { sortIndex: number; } export class PieceTreeTextBuffer implements ITextBuffer { private readonly _pieceTree: PieceTreeBase; private readonly _BOM: string; private _mightContainRTL: boolean; private _mightContainNonBasicASCII: boolean; constructor(chunks: StringBuffer[], BOM: string, eol: '\r\n' | '\n', containsRTL: boolean, isBasicASCII: boolean, eolNormalized: boolean) { this._BOM = BOM; this._mightContainNonBasicASCII = !isBasicASCII; this._mightContainRTL = containsRTL; this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized); } // #region TextBuffer public equals(other: ITextBuffer): boolean { if (!(other instanceof PieceTreeTextBuffer)) { return false; } if (this._BOM !== other._BOM) { return false; } if (this.getEOL() !== other.getEOL()) { return false; } return this._pieceTree.equal(other._pieceTree); } public mightContainRTL(): boolean { return this._mightContainRTL; } public mightContainNonBasicASCII(): boolean { return this._mightContainNonBasicASCII; } public getBOM(): string { return this._BOM; } public getEOL(): '\r\n' | '\n' { return this._pieceTree.getEOL(); } public createSnapshot(preserveBOM: boolean): ITextSnapshot { return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : ''); } public getOffsetAt(lineNumber: number, column: number): number { return this._pieceTree.getOffsetAt(lineNumber, column); } public getPositionAt(offset: number): Position { return this._pieceTree.getPositionAt(offset); } public getRangeAt(start: number, length: number): Range { let end = start + length; const startPosition = this.getPositionAt(start); const endPosition = this.getPositionAt(end); return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); } public getValueInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): string { if (range.isEmpty()) { return ''; } const lineEnding = this._getEndOfLine(eol); return this._pieceTree.getValueInRange(range, lineEnding); } public getValueLengthInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): number { if (range.isEmpty()) { return 0; } if (range.startLineNumber === range.endLineNumber) { return (range.endColumn - range.startColumn); } let startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn); let endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn); return endOffset - startOffset; } public getCharacterCountInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): number { if (this._mightContainNonBasicASCII) { // we must count by iterating let result = 0; const fromLineNumber = range.startLineNumber; const toLineNumber = range.endLineNumber; for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { const lineContent = this.getLineContent(lineNumber); const fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0); const toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length); for (let offset = fromOffset; offset < toOffset; offset++) { if (strings.isHighSurrogate(lineContent.charCodeAt(offset))) { result = result + 1; offset = offset + 1; } else { result = result + 1; } } } result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber); return result; } return this.getValueLengthInRange(range, eol); } public getLength(): number { return this._pieceTree.getLength(); } public getLineCount(): number { return this._pieceTree.getLineCount(); } public getLinesContent(): string[] { return this._pieceTree.getLinesContent(); } public getLineContent(lineNumber: number): string { return this._pieceTree.getLineContent(lineNumber); } public getLineCharCode(lineNumber: number, index: number): number { return this._pieceTree.getLineCharCode(lineNumber, index); } public getLineLength(lineNumber: number): number { return this._pieceTree.getLineLength(lineNumber); } public getLineMinColumn(lineNumber: number): number { return 1; } public getLineMaxColumn(lineNumber: number): number { return this.getLineLength(lineNumber) + 1; } public getLineFirstNonWhitespaceColumn(lineNumber: number): number { const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 1; } public getLineLastNonWhitespaceColumn(lineNumber: number): number { const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 2; } private _getEndOfLine(eol: EndOfLinePreference): string { switch (eol) { case EndOfLinePreference.LF: return '\n'; case EndOfLinePreference.CRLF: return '\r\n'; case EndOfLinePreference.TextDefined: return this.getEOL(); } throw new Error('Unknown EOL preference'); } public setEOL(newEOL: '\r\n' | '\n'): void { this._pieceTree.setEOL(newEOL); } public applyEdits(rawOperations: ValidAnnotatedEditOperation[], recordTrimAutoWhitespace: boolean, computeUndoEdits: boolean): ApplyEditsResult { let mightContainRTL = this._mightContainRTL; let mightContainNonBasicASCII = this._mightContainNonBasicASCII; let canReduceOperations = true; let operations: IValidatedEditOperation[] = []; for (let i = 0; i < rawOperations.length; i++) { let op = rawOperations[i]; if (canReduceOperations && op._isTracked) { canReduceOperations = false; } let validatedRange = op.range; if (!mightContainRTL && op.text) { // check if the new inserted text contains RTL mightContainRTL = strings.containsRTL(op.text); } if (!mightContainNonBasicASCII && op.text) { mightContainNonBasicASCII = !strings.isBasicASCII(op.text); } let validText = ''; let eolCount = 0; let firstLineLength = 0; let lastLineLength = 0; if (op.text) { let strEOL: StringEOL; [eolCount, firstLineLength, lastLineLength, strEOL] = countEOL(op.text); const bufferEOL = this.getEOL(); const expectedStrEOL = (bufferEOL === '\r\n' ? StringEOL.CRLF : StringEOL.LF); if (strEOL === StringEOL.Unknown || strEOL === expectedStrEOL) { validText = op.text; } else { validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL); } } operations[i] = { sortIndex: i, identifier: op.identifier || null, range: validatedRange, rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn), rangeLength: this.getValueLengthInRange(validatedRange), text: validText, eolCount: eolCount, firstLineLength: firstLineLength, lastLineLength: lastLineLength, forceMoveMarkers: Boolean(op.forceMoveMarkers), isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false }; } // Sort operations ascending operations.sort(PieceTreeTextBuffer._sortOpsAscending); let hasTouchingRanges = false; for (let i = 0, count = operations.length - 1; i < count; i++) { let rangeEnd = operations[i].range.getEndPosition(); let nextRangeStart = operations[i + 1].range.getStartPosition(); if (nextRangeStart.isBeforeOrEqual(rangeEnd)) { if (nextRangeStart.isBefore(rangeEnd)) { // overlapping ranges throw new Error('Overlapping ranges are not allowed!'); } hasTouchingRanges = true; } } if (canReduceOperations) { operations = this._reduceOperations(operations); } // Delta encode operations let reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []); let newTrimAutoWhitespaceCandidates: { lineNumber: number, oldContent: string }[] = []; if (recordTrimAutoWhitespace) { for (let i = 0; i < operations.length; i++) { let op = operations[i]; let reverseRange = reverseRanges[i]; if (op.isAutoWhitespaceEdit && op.range.isEmpty()) { // Record already the future line numbers that might be auto whitespace removal candidates on next edit for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) { let currentLineContent = ''; if (lineNumber === reverseRange.startLineNumber) { currentLineContent = this.getLineContent(op.range.startLineNumber); if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) { continue; } } newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent }); } } } } let reverseOperations: IReverseSingleEditOperation[] | null = null; if (computeUndoEdits) { let reverseRangeDeltaOffset = 0; reverseOperations = []; for (let i = 0; i < operations.length; i++) { const op = operations[i]; const reverseRange = reverseRanges[i]; const bufferText = this.getValueInRange(op.range); const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset; reverseRangeDeltaOffset += (op.text.length - bufferText.length); reverseOperations[i] = { sortIndex: op.sortIndex, identifier: op.identifier, range: reverseRange, text: bufferText, textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text) }; } // Can only sort reverse operations when the order is not significant if (!hasTouchingRanges) { reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex); } } this._mightContainRTL = mightContainRTL; this._mightContainNonBasicASCII = mightContainNonBasicASCII; const contentChanges = this._doApplyEdits(operations); let trimAutoWhitespaceLineNumbers: number[] | null = null; if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) { // sort line numbers auto whitespace removal candidates for next edit descending newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber); trimAutoWhitespaceLineNumbers = []; for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) { let lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber; if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) { // Do not have the same line number twice continue; } let prevContent = newTrimAutoWhitespaceCandidates[i].oldContent; let lineContent = this.getLineContent(lineNumber); if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) { continue; } trimAutoWhitespaceLineNumbers.push(lineNumber); } } return new ApplyEditsResult( reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers ); } /** * Transform operations such that they represent the same logic edit, * but that they also do not cause OOM crashes. */ private _reduceOperations(operations: IValidatedEditOperation[]): IValidatedEditOperation[] { if (operations.length < 1000) { // We know from empirical testing that a thousand edits work fine regardless of their shape. return operations; } // At one point, due to how events are emitted and how each operation is handled, // some operations can trigger a high amount of temporary string allocations, // that will immediately get edited again. // e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line // Therefore, the strategy is to collapse all the operations into a huge single edit operation return [this._toSingleEditOperation(operations)]; } _toSingleEditOperation(operations: IValidatedEditOperation[]): IValidatedEditOperation { let forceMoveMarkers = false; const firstEditRange = operations[0].range; const lastEditRange = operations[operations.length - 1].range; const entireEditRange = new Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn); let lastEndLineNumber = firstEditRange.startLineNumber; let lastEndColumn = firstEditRange.startColumn; const result: string[] = []; for (let i = 0, len = operations.length; i < len; i++) { const operation = operations[i]; const range = operation.range; forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers; // (1) -- Push old text result.push(this.getValueInRange(new Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn))); // (2) -- Push new text if (operation.text.length > 0) { result.push(operation.text); } lastEndLineNumber = range.endLineNumber; lastEndColumn = range.endColumn; } const text = result.join(''); const [eolCount, firstLineLength, lastLineLength] = countEOL(text); return { sortIndex: 0, identifier: operations[0].identifier, range: entireEditRange, rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn), rangeLength: this.getValueLengthInRange(entireEditRange, EndOfLinePreference.TextDefined), text: text, eolCount: eolCount, firstLineLength: firstLineLength, lastLineLength: lastLineLength, forceMoveMarkers: forceMoveMarkers, isAutoWhitespaceEdit: false }; } private _doApplyEdits(operations: IValidatedEditOperation[]): IInternalModelContentChange[] { operations.sort(PieceTreeTextBuffer._sortOpsDescending); let contentChanges: IInternalModelContentChange[] = []; // operations are from bottom to top for (let i = 0; i < operations.length; i++) { let op = operations[i]; const startLineNumber = op.range.startLineNumber; const startColumn = op.range.startColumn; const endLineNumber = op.range.endLineNumber; const endColumn = op.range.endColumn; if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) { // no-op continue; } if (op.text) { // replacement this._pieceTree.delete(op.rangeOffset, op.rangeLength); this._pieceTree.insert(op.rangeOffset, op.text, true); } else { // deletion this._pieceTree.delete(op.rangeOffset, op.rangeLength); } const contentChangeRange = new Range(startLineNumber, startColumn, endLineNumber, endColumn); contentChanges.push({ range: contentChangeRange, rangeLength: op.rangeLength, text: op.text, rangeOffset: op.rangeOffset, forceMoveMarkers: op.forceMoveMarkers }); } return contentChanges; } findMatchesLineByLine(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[] { return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount); } // #endregion // #region helper // testing purpose. public getPieceTree(): PieceTreeBase { return this._pieceTree; } /** * Assumes `operations` are validated and sorted ascending */ public static _getInverseEditRanges(operations: IValidatedEditOperation[]): Range[] { let result: Range[] = []; let prevOpEndLineNumber: number = 0; let prevOpEndColumn: number = 0; let prevOp: IValidatedEditOperation | null = null; for (let i = 0, len = operations.length; i < len; i++) { let op = operations[i]; let startLineNumber: number; let startColumn: number; if (prevOp) { if (prevOp.range.endLineNumber === op.range.startLineNumber) { startLineNumber = prevOpEndLineNumber; startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn); } else { startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber); startColumn = op.range.startColumn; } } else { startLineNumber = op.range.startLineNumber; startColumn = op.range.startColumn; } let resultRange: Range; if (op.text.length > 0) { // the operation inserts something const lineCount = op.eolCount + 1; if (lineCount === 1) { // single line insert resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength); } else { // multi line insert resultRange = new Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1); } } else { // There is nothing to insert resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn); } prevOpEndLineNumber = resultRange.endLineNumber; prevOpEndColumn = resultRange.endColumn; result.push(resultRange); prevOp = op; } return result; } private static _sortOpsAscending(a: IValidatedEditOperation, b: IValidatedEditOperation): number { let r = Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return a.sortIndex - b.sortIndex; } return r; } private static _sortOpsDescending(a: IValidatedEditOperation, b: IValidatedEditOperation): number { let r = Range.compareRangesUsingEnds(a.range, b.range); if (r === 0) { return b.sortIndex - a.sortIndex; } return -r; } // #endregion }
joaomoreno/vscode
src/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer.ts
TypeScript
mit
18,581
// Template Source: BaseEntityCollectionPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.TermsAndConditionsAcceptanceStatus; import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionRequestBuilder; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionResponse; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Terms And Conditions Acceptance Status Collection Page. */ public class TermsAndConditionsAcceptanceStatusCollectionPage extends BaseCollectionPage<TermsAndConditionsAcceptanceStatus, TermsAndConditionsAcceptanceStatusCollectionRequestBuilder> { /** * A collection page for TermsAndConditionsAcceptanceStatus * * @param response the serialized TermsAndConditionsAcceptanceStatusCollectionResponse from the service * @param builder the request builder for the next collection page */ public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final TermsAndConditionsAcceptanceStatusCollectionResponse response, @Nonnull final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder builder) { super(response, builder); } /** * Creates the collection page for TermsAndConditionsAcceptanceStatus * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final java.util.List<TermsAndConditionsAcceptanceStatus> pageContents, @Nullable final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/TermsAndConditionsAcceptanceStatusCollectionPage.java
Java
mit
2,194
// Script by Bo Tranberg // http://botranberg.dk // https://github.com/tranberg/citations // // This script requires jQuery and jQuery UI $(function() { // Inser html for dialog just before the button to open it var butt = document.getElementById('citations'); butt.insertAdjacentHTML('beforeBegin', '\ <div id="dialog" title="Cite this paper" style="text-align:left"> \ <p style="text-align: center;"><b>Copy and paste one of the formatted citations into your bibliography manager.</b></p> \ <table style="border-collapse:separate; border-spacing:2em"> \ <tr style="vertical-align:top;"> \ <td><strong>APA</strong></td> \ <td><span id="APA1"></span><span id="APA2"></span><span id="APA3"></span><span id="APA4" style="font-style: italic"></span></td> \ </tr> \ <tr style="vertical-align:top;"> \ <td><strong>Bibtex</strong></td> \ <td> \ @article{<span id="bibtag"></span>,<br> \ &nbsp;&nbsp;&nbsp;&nbsp;title={<span id="bibtitle"></span>},<br> \ &nbsp;&nbsp;&nbsp;&nbsp;author={<span id="bibauthor"></span>},<br> \ &nbsp;&nbsp;&nbsp;&nbsp;journal={<span id="bibjournal"></span>},<br> \ &nbsp;&nbsp;&nbsp;&nbsp;year={<span id="bibyear"></span>},<br> \ &nbsp;&nbsp;&nbsp;&nbsp;url={<span id="biburl"></span>},<br> \ } \ </td> \ </tr> \ </table> \ </div>'); // Definitions of citations dialog $("#dialog").dialog({ autoOpen: false, show: { effect: "fade", duration: 200 }, hide: { effect: "fade", duration: 200 }, maxWidth:600, maxHeight: 600, width: 660, height: 400, modal: true, }); // Open citation dialog on click $("#citations").click(function() { $("#dialog").dialog("open"); }); // Find authors var metas = document.getElementsByTagName('meta'); var author = '' // Determine number of authors var numAuthors = 0 for (i=0; i<metas.length; i++) { if (metas[i].getAttribute("name") == "citation_author") { numAuthors += 1 }; }; // Build a string of authors for Bibtex var authorIndex = 0 for (i=0; i<metas.length; i++) { if (metas[i].getAttribute("name") == "citation_author") { authorIndex += 1 if (authorIndex>1) { if (authorIndex<=numAuthors) { author = author+' and ' }; }; author = author+metas[i].getAttribute("content") }; }; // Populate formatted citations in Bibtex var title = $("meta[name='citation_title']").attr('content') // The following test might seem stupid, but it's needed because some php function at OpenPsych appends two whitespaces to the start of the title in the meta data if (title[1] == ' ') { title = title.slice(2) }; var journal = $("meta[name='citation_journal_title']").attr('content') var pubyear = $("meta[name='citation_publication_date']").attr('content').substring(0,4) var puburl = document.URL // Build a string for the Bibtex tag if (author.indexOf(',') < author.indexOf(' ')) { var firstAuthor = author.substr(0,author.indexOf(',')); } else { var firstAuthor = author.substr(0,author.indexOf(' ')); }; if (title.indexOf(',')<title.indexOf('0')) { var startTitle = title.substr(0,title.indexOf(',')); } else { var startTitle = title.substr(0,title.indexOf(' ')); }; $('#bibtag').html(firstAuthor+pubyear) $('#bibtitle').html(title) $('#bibauthor').html(author) $('#bibjournal').html(journal) $('#bibyear').html(pubyear) $('#biburl').html(puburl) //Build a string of authors for APA var author = '' var authorIndex = 0 for (i=0; i<metas.length; i++) { if (metas[i].getAttribute("name") == "citation_author") { authorIndex += 1 if (authorIndex>1) { if (authorIndex<numAuthors) { author = author+', ' }; }; if (authorIndex>1) { if (authorIndex===numAuthors) { author = author+', & ' }; }; // Check if author only has a single name if (metas[i].getAttribute("content").indexOf(', ')>0) { // Append author string with the surnames and first letter of next author's name author = author+metas[i].getAttribute("content").substr(0,metas[i].getAttribute("content").indexOf(', ')+3)+'.' // If the author has several names, append the first letter of these to the string if (metas[i].getAttribute("content").indexOf(', ') < metas[i].getAttribute("content").lastIndexOf(' ')-1) { var extraNames = metas[i].getAttribute("content").substr(metas[i].getAttribute("content").indexOf(', ')+2) var addNames = extraNames.substr(extraNames.indexOf(' ')) author = author+addNames.substr(addNames.indexOf(' ')) }; } else { author = author+metas[i].getAttribute("content") }; }; }; // Populate formatted citations in APA $('#APA1').html(author) $('#APA2').html(' ('+pubyear+').') $('#APA3').html(' '+title+'.') $('#APA4').html(' '+journal+'.') });
tranberg/citations
js/cite.js
JavaScript
mit
6,059
package io.github.ageofwar.telejam.updates; import io.github.ageofwar.telejam.Bot; import io.github.ageofwar.telejam.TelegramException; import io.github.ageofwar.telejam.methods.GetUpdates; import java.io.IOException; import java.util.Collections; import java.util.Objects; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.LongUnaryOperator; /** * Utility class that reads new updates received from a bot. * * @author Michi Palazzo */ public final class UpdateReader implements AutoCloseable { private final Bot bot; private final ConcurrentLinkedQueue<Update> updates; private final LongUnaryOperator backOff; private long lastUpdateId; /** * Constructs an UpdateReader. * * @param bot the bot that receive updates * @param backOff back off to be used when long polling fails */ public UpdateReader(Bot bot, LongUnaryOperator backOff) { this.bot = Objects.requireNonNull(bot); this.backOff = Objects.requireNonNull(backOff); updates = new ConcurrentLinkedQueue<>(); lastUpdateId = -1; } /** * Constructs an UpdateReader. * * @param bot the bot that receive updates */ public UpdateReader(Bot bot) { this(bot, a -> 500L); } /** * Returns the number of updates that can be read from this update reader without blocking by the * next invocation read method for this update reader. The next invocation * might be the same thread or another thread. * If the available updates are more than {@code Integer.MAX_VALUE}, returns * {@code Integer.MAX_VALUE}. * * @return the number of updates that can be read from this update reader * without blocking by the next invocation read method */ public int available() { return updates.size(); } /** * Tells whether this stream is ready to be read. * * @return <code>true</code> if the next read() is guaranteed not to block for input, * <code>false</code> otherwise. Note that returning false does not guarantee that the * next read will block. */ public boolean ready() { return !updates.isEmpty(); } /** * Reads one update from the stream. * * @return the read update * @throws IOException if an I/O Exception occurs * @throws InterruptedException if any thread has interrupted the current * thread while waiting for updates */ public Update read() throws IOException, InterruptedException { if (!ready()) { for (long attempts = 0; getUpdates() == 0; attempts++) { Thread.sleep(backOff.applyAsLong(attempts)); } } return updates.remove(); } /** * Retrieves new updates received from the bot. * * @return number of updates received * @throws IOException if an I/O Exception occurs */ public int getUpdates() throws IOException { try { Update[] newUpdates = getUpdates(lastUpdateId + 1); Collections.addAll(updates, newUpdates); if (newUpdates.length > 0) { lastUpdateId = newUpdates[newUpdates.length - 1].getId(); } return newUpdates.length; } catch (Throwable e) { if (!(e instanceof TelegramException)) { lastUpdateId++; } throw e; } } /** * Discards buffered updates and all received updates. * * @throws IOException if an I/O Exception occurs */ public void discardAll() throws IOException { Update[] newUpdate = getUpdates(-1); if (newUpdate.length == 1) { lastUpdateId = newUpdate[0].getId(); } updates.clear(); } private Update[] getUpdates(long offset) throws IOException { GetUpdates getUpdates = new GetUpdates() .offset(offset) .allowedUpdates(); return bot.execute(getUpdates); } @Override public void close() throws IOException { try { Update nextUpdate = updates.peek(); getUpdates(nextUpdate != null ? nextUpdate.getId() : lastUpdateId + 1); lastUpdateId = -1; updates.clear(); } catch (IOException e) { throw new IOException("Unable to close update reader", e); } } }
AgeOfWar/Telejam
src/main/java/io/github/ageofwar/telejam/updates/UpdateReader.java
Java
mit
4,138
""" ``editquality generate_make -h`` :: Code-generate Makefile from template and configuration :Usage: generate_make -h | --help generate_make [--config=<path>] [--main=<filename>] [--output=<path>] [--templates=<path>] [--debug] :Options: --config=<path> Directory to search for configuration files [default: config/] --main=<filename> Override to use a main template other than the default [default: Makefile.j2] --output=<path> Where to write the Makefile output. [default: <stdout>] --templates=<path> Directory to search for input templates. [default: templates/] --debug Print debug logging """ # TODO: # * make API calls to learn things # * ores/config has dict merge # * survey dependency solvers # https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninja-build-files # ** Still considering: scons, doit, drake, ninja, meson # ** Don't like so far: waf # * Where can we store information about samples? # Original population rates; how we've distorted them. import logging import os.path import sys import docopt from .. import config from ..codegen import generate logger = logging.getLogger(__name__) def main(argv=None): args = docopt.docopt(__doc__, argv=argv) logging.basicConfig( level=logging.DEBUG if args['--debug'] else logging.WARNING, format='%(asctime)s %(levelname)s:%(name)s -- %(message)s' ) config_path = args["--config"] output_f = sys.stdout \ if args["--output"] == "<stdout>" \ else open(args["--output"], "w") templates_path = args["--templates"] main_template_path = args["--main"] if not os.path.isabs(main_template_path): # Join a filename to the default templates dir. main_template_path = os.path.join(templates_path, main_template_path) with open(main_template_path, "r") as f: main_template = f.read() variables = config.load_config(config_path) output = generate.generate(variables, templates_path, main_template) output_f.write(output)
wiki-ai/editquality
editquality/utilities/generate_make.py
Python
mit
2,362
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Product(Model): _required = [] _attribute_map = { 'integer': {'key': 'integer', 'type': 'int'}, 'string': {'key': 'string', 'type': 'str'}, } def __init__(self, *args, **kwargs): """Product :param int integer :param str string """ self.integer = None self.string = None super(Product, self).__init__(*args, **kwargs)
vulcansteel/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/auto_rest_swagger_bat_array_service/models/product.py
Python
mit
931
import React from 'react'; import PropTypes from 'prop-types'; import styled, { keyframes } from 'styled-components'; const blink = keyframes` from, to { opacity: 1; } 50% { opacity: 0; } `; const CursorSpan = styled.span` font-weight: 100; color: black; font-size: 1em; padding-left: 2px; animation: ${blink} 1s step-end infinite; `; const Cursor = ({ className }) => ( <CursorSpan className={className}>|</CursorSpan> ); Cursor.propTypes = { className: PropTypes.string }; Cursor.defaultProps = { className: '' }; export default Cursor;
adamjking3/react-typing-animation
src/Cursor.js
JavaScript
mit
572
// Copyright Louis Dionne 2015 // Distributed under the Boost Software License, Version 1.0. #include <type_traits> template <typename T> using void_t = std::conditional_t<true, void, T>; // sample(common_type-N3843) template <typename T, typename U> using builtin_common_t = std::decay_t<decltype( true ? std::declval<T>() : std::declval<U>() )>; template <typename, typename ...> struct ct { }; template <typename T> struct ct<void, T> : std::decay<T> { }; template <typename T, typename U, typename ...V> struct ct<void_t<builtin_common_t<T, U>>, T, U, V...> : ct<void, builtin_common_t<T, U>, V...> { }; template <typename ...T> struct common_type : ct<void, T...> { }; // end-sample template <typename ...Ts> using common_type_t = typename common_type<Ts...>::type; ////////////////////////////////////////////////////////////////////////////// // Tests ////////////////////////////////////////////////////////////////////////////// template <typename T, typename = void> struct has_type : std::false_type { }; template <typename T> struct has_type<T, void_t<typename T::type>> : std::true_type { }; struct A { }; struct B { }; struct C { }; // Ensure proper behavior in normal cases static_assert(std::is_same< common_type_t<char>, char >{}, ""); static_assert(std::is_same< common_type_t<A, A>, A >{}, ""); static_assert(std::is_same< common_type_t<char, short, char, short>, int >{}, ""); static_assert(std::is_same< common_type_t<char, double, short, char, short, double>, double >{}, ""); static_assert(std::is_same< common_type_t<char, short, float, short>, float >{}, ""); // Ensure SFINAE-friendliness static_assert(!has_type<common_type<>>{}, ""); static_assert(!has_type<common_type<int, void>>{}, ""); int main() { }
ldionne/hana-cppnow-2015
code/common_type-N3843.cpp
C++
mit
1,800
package remove_duplicates_from_sorted_list; import common.ListNode; public class RemoveDuplicatesfromSortedList { public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head != null) { ListNode pre = head; ListNode p = pre.next; while (p != null) { if (p.val == pre.val) { pre.next = p.next; } else { pre = p; } p = p.next; } } return head; } } public static class UnitTest { } }
quantumlaser/code2016
LeetCode/Answers/Leetcode-java-solution/remove_duplicates_from_sorted_list/RemoveDuplicatesfromSortedList.java
Java
mit
668
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Umbraco.Core.Models.EntityBase { /// <summary> /// A base class for use to implement IRememberBeingDirty/ICanBeDirty /// </summary> public abstract class TracksChangesEntityBase : IRememberBeingDirty { /// <summary> /// Tracks the properties that have changed /// </summary> private readonly IDictionary<string, bool> _propertyChangedInfo = new Dictionary<string, bool>(); /// <summary> /// Tracks the properties that we're changed before the last commit (or last call to ResetDirtyProperties) /// </summary> private IDictionary<string, bool> _lastPropertyChangedInfo = null; /// <summary> /// Property changed event /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Method to call on a property setter. /// </summary> /// <param name="propertyInfo">The property info.</param> protected virtual void OnPropertyChanged(PropertyInfo propertyInfo) { _propertyChangedInfo[propertyInfo.Name] = true; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyInfo.Name)); } } /// <summary> /// Indicates whether a specific property on the current entity is dirty. /// </summary> /// <param name="propertyName">Name of the property to check</param> /// <returns>True if Property is dirty, otherwise False</returns> public virtual bool IsPropertyDirty(string propertyName) { return _propertyChangedInfo.Any(x => x.Key == propertyName); } /// <summary> /// Indicates whether the current entity is dirty. /// </summary> /// <returns>True if entity is dirty, otherwise False</returns> public virtual bool IsDirty() { return _propertyChangedInfo.Any(); } /// <summary> /// Indicates that the entity had been changed and the changes were committed /// </summary> /// <returns></returns> public bool WasDirty() { return _lastPropertyChangedInfo != null && _lastPropertyChangedInfo.Any(); } /// <summary> /// Indicates whether a specific property on the current entity was changed and the changes were committed /// </summary> /// <param name="propertyName">Name of the property to check</param> /// <returns>True if Property was changed, otherwise False. Returns false if the entity had not been previously changed.</returns> public virtual bool WasPropertyDirty(string propertyName) { return WasDirty() && _lastPropertyChangedInfo.Any(x => x.Key == propertyName); } /// <summary> /// Resets the remembered dirty properties from before the last commit /// </summary> public void ForgetPreviouslyDirtyProperties() { _lastPropertyChangedInfo.Clear(); } /// <summary> /// Resets dirty properties by clearing the dictionary used to track changes. /// </summary> /// <remarks> /// Please note that resetting the dirty properties could potentially /// obstruct the saving of a new or updated entity. /// </remarks> public virtual void ResetDirtyProperties() { ResetDirtyProperties(true); } /// <summary> /// Resets dirty properties by clearing the dictionary used to track changes. /// </summary> /// <param name="rememberPreviouslyChangedProperties"> /// true if we are to remember the last changes made after resetting /// </param> /// <remarks> /// Please note that resetting the dirty properties could potentially /// obstruct the saving of a new or updated entity. /// </remarks> public virtual void ResetDirtyProperties(bool rememberPreviouslyChangedProperties) { if (rememberPreviouslyChangedProperties) { //copy the changed properties to the last changed properties _lastPropertyChangedInfo = _propertyChangedInfo.ToDictionary(v => v.Key, v => v.Value); } _propertyChangedInfo.Clear(); } /// <summary> /// Used by inheritors to set the value of properties, this will detect if the property value actually changed and if it did /// it will ensure that the property has a dirty flag set. /// </summary> /// <param name="setValue"></param> /// <param name="value"></param> /// <param name="propertySelector"></param> /// <returns>returns true if the value changed</returns> /// <remarks> /// This is required because we don't want a property to show up as "dirty" if the value is the same. For example, when we /// save a document type, nearly all properties are flagged as dirty just because we've 'reset' them, but they are all set /// to the same value, so it's really not dirty. /// </remarks> internal bool SetPropertyValueAndDetectChanges<T>(Func<T, T> setValue, T value, PropertyInfo propertySelector) { var initVal = value; var newVal = setValue(value); if (!Equals(initVal, newVal)) { OnPropertyChanged(propertySelector); return true; } return false; } } }
zidad/Umbraco-CMS
src/Umbraco.Core/Models/EntityBase/TracksChangesEntityBase.cs
C#
mit
5,915
# coding=utf8 """ Parser for todo format string. from todo.parser import parser parser.parse(string) # return an Todo instance """ from models import Task from models import Todo from ply import lex from ply import yacc class TodoLexer(object): """ Lexer for Todo format string. Tokens ID e.g. '1.' DONE e.g. '(x)' TASK e.g. 'This is a task' """ tokens = ( "ID", "DONE", "TASK", ) t_ignore = "\x20\x09" # ignore spaces and tabs def t_ID(self, t): r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?' t.value = int(t.value[:-1]) return t def t_DONE(self, t): r'(\(x\))' return t def t_TASK(self, t): r'((?!\(x\))).+' return t def t_newline(self, t): r'\n+' t.lexer.lineno += len(t.value) def t_error(self, t): raise SyntaxError( "Illegal character: '%s' at Line %d" % (t.value[0], t.lineno) ) def __init__(self): self.lexer = lex.lex(module=self) class TodoParser(object): """ Parser for Todo format string, works with a todo lexer. Parse string to Python list todo_str = "1. (x) Write email to tom" TodoParser().parse(todo_str) """ tokens = TodoLexer.tokens def p_error(self, p): if p: raise SyntaxError( "Character '%s' at line %d" % (p.value[0], p.lineno) ) else: raise SyntaxError("SyntaxError at EOF") def p_start(self, p): "start : translation_unit" p[0] = self.todo def p_translation_unit(self, p): """ translation_unit : translate_task | translation_unit translate_task | """ pass def p_translation_task(self, p): """ translate_task : ID DONE TASK | ID TASK """ if len(p) == 4: done = True content = p[3] elif len(p) == 3: done = False content = p[2] task = Task(p[1], content, done) self.todo.append(task) def __init__(self): self.parser = yacc.yacc(module=self, debug=0, write_tables=0) def parse(self, data): # reset list self.todo = Todo() return self.parser.parse(data) lexer = TodoLexer() # build lexer parser = TodoParser() # build parser
guori12321/todo
todo/parser.py
Python
mit
2,473
/** * This program 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 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * **/ #include "stateengine/AtomicState.h" #include "stateengine/Defines.h" //-------------------------------------------------------------------- // TAtomicState //-------------------------------------------------------------------- //-------------------------------------------------------------------- namespace donut { typedef void (*TUpdaterFunction)(const TStateEngineId&, double); typedef void (*TStateCallBack)(const TStateEngineId&, TStateData *); //-------------------------------------------------------------------- TAtomicState::TAtomicState(TStateEngineId parStateEngineId, TStateId parId, TStateData (* parTStateData), void (* parEnterCallBack), void (* parLeaveCallBack), void (* parUpdater)) : FStateEngineId (parStateEngineId) { FEnterCallBack = parEnterCallBack; FLeaveCallBack = parLeaveCallBack; FStateData = parTStateData; FUpdater = parUpdater; FId = parId; } TAtomicState::~TAtomicState() { // assert_msg_NO_RELEASE(FStateData!=NULL, "The state data has been already deleted. you do not need to.") delete FStateData; } void TAtomicState::AddTransition(TTransitionId parId, TTransition * parTransition) { FOutTransitions[parId] = parTransition; } #if _DEBUG void TAtomicState::AddInTransition(const TTransition * parTransition) { // FInTransitions.push_back(parTransition) } #endif void TAtomicState::Update(double parDt) { void (*updater)( const TStateEngineId&, double) = *((TUpdaterFunction*) (&FUpdater)); updater(FStateEngineId , parDt); } void TAtomicState::Enter() { void (*enter)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FEnterCallBack)); enter(FStateEngineId, FStateData); } void TAtomicState::Leave() { void (*leave)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FLeaveCallBack)); leave(FStateEngineId, FStateData); } void TAtomicState::TransitionCallBack() { } } // End namestate StateEngine
AnisB/Donut
engine/src/stateengine/AtomicState.cpp
C++
mit
2,621
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), //Bundle ajouté new FOS\UserBundle\FOSUserBundle(), new Psa\PageBundle\PsaPageBundle(), //new Psa\UserBundle\PsaUserBundle(), new Psa\AdminBundle\PsaAdminBundle(), new Psa\CommonBundle\PsaCommonBundle(), //Forum Bundles new EWZ\Bundle\TimeBundle\EWZTimeBundle(), new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(), new CCDNComponent\CommonBundle\CCDNComponentCommonBundle(), new CCDNComponent\BBCodeBundle\CCDNComponentBBCodeBundle(), new CCDNComponent\CrumbTrailBundle\CCDNComponentCrumbTrailBundle(), new CCDNComponent\DashboardBundle\CCDNComponentDashboardBundle(), new CCDNComponent\AttachmentBundle\CCDNComponentAttachmentBundle(), new CCDNComponent\MenuBundle\CCDNComponentMenuBundle(), new CCDNForum\KarmaBundle\CCDNForumKarmaBundle(), new CCDNUser\UserBundle\CCDNUserUserBundle(), new CCDNForum\AdminBundle\CCDNForumAdminBundle(), new CCDNForum\ForumBundle\CCDNForumForumBundle(), new CCDNUser\AdminBundle\CCDNUserAdminBundle(), new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(), new CCDNUser\ProfileBundle\CCDNUserProfileBundle(), new CCDNForum\ModeratorBundle\CCDNForumModeratorBundle(), new CCDNUser\MemberBundle\CCDNUserMemberBundle(), new CCDNMessage\MessageBundle\CCDNMessageMessageBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); $bundles[] = new CoreSphere\ConsoleBundle\CoreSphereConsoleBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
psamada2012/psa
app/AppKernel.php
PHP
mit
3,052
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\Scope; /** * GraphvizDumper dumps a service container as a graphviz file. * * You can convert the generated dot file with the dot utility (http://www.graphviz.org/): * * dot -Tpng container.dot > foo.png * * @author Fabien Potencier <[email protected]> */ class GraphvizDumper extends Dumper { private $nodes; private $edges; private $options = array( 'graph' => array('ratio' => 'compress'), 'node' => array('fontsize' => 11, 'fontname' => 'Arial', 'shape' => 'record'), 'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => 0.5), 'node.instance' => array('fillcolor' => '#9999ff', 'style' => 'filled'), 'node.definition' => array('fillcolor' => '#eeeeee'), 'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'), ); /** * Dumps the service container as a graphviz graph. * * Available options: * * * graph: The default options for the whole graph * * node: The default options for nodes * * edge: The default options for edges * * node.instance: The default options for services that are defined directly by object instances * * node.definition: The default options for services that are defined via service definition instances * * node.missing: The default options for missing services * * @param array $options An array of options * * @return string The dot representation of the service container */ public function dump(array $options = array()) { foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) { if (isset($options[$key])) { $this->options[$key] = array_merge($this->options[$key], $options[$key]); } } $this->nodes = $this->findNodes(); $this->edges = array(); foreach ($this->container->getDefinitions() as $id => $definition) { $this->edges[$id] = array_merge( $this->findEdges($id, $definition->getArguments(), true, ''), $this->findEdges($id, $definition->getProperties(), false, '') ); foreach ($definition->getMethodCalls() as $call) { $this->edges[$id] = array_merge( $this->edges[$id], $this->findEdges($id, $call[1], false, $call[0].'()') ); } } return $this->startDot().$this->addNodes().$this->addEdges().$this->endDot(); } /** * Returns all nodes. * * @return string A string representation of all nodes */ private function addNodes() { $code = ''; foreach ($this->nodes as $id => $node) { $aliases = $this->getAliases($id); $code .= sprintf(" node_%s [label=\"%s\\n%s\\n\", shape=%s%s];\n", $this->dotize($id), $id.($aliases ? ' ('.implode(', ', $aliases).')' : ''), $node['class'], $this->options['node']['shape'], $this->addAttributes($node['attributes'])); } return $code; } /** * Returns all edges. * * @return string A string representation of all edges */ private function addEdges() { $code = ''; foreach ($this->edges as $id => $edges) { foreach ($edges as $edge) { $code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed'); } } return $code; } /** * Finds all edges belonging to a specific service id. * * @param string $id The service id used to find edges * @param array $arguments An array of arguments * @param bool $required * @param string $name * * @return array An array of edges */ private function findEdges($id, $arguments, $required, $name) { $edges = array(); foreach ($arguments as $argument) { if ($argument instanceof Parameter) { $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null; } elseif (is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) { $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null; } if ($argument instanceof Reference) { if (!$this->container->has((string) $argument)) { $this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']); } $edges[] = array('name' => $name, 'required' => $required, 'to' => $argument); } elseif (is_array($argument)) { $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name)); } } return $edges; } /** * Finds all nodes. * * @return array An array of all nodes */ private function findNodes() { $nodes = array(); $container = $this->cloneContainer(); foreach ($container->getDefinitions() as $id => $definition) { $class = $definition->getClass(); if ('\\' === substr($class, 0, 1)) { $class = substr($class, 1); } $nodes[$id] = array('class' => str_replace('\\', '\\\\', $this->container->getParameterBag()->resolveValue($class)), 'attributes' => array_merge($this->options['node.definition'], array('style' => ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope() ? 'filled' : 'dotted'))); $container->setDefinition($id, new Definition('stdClass')); } foreach ($container->getServiceIds() as $id) { $service = $container->get($id); if (array_key_exists($id, $container->getAliases())) { continue; } if (!$container->hasDefinition($id)) { $class = ('service_container' === $id) ? get_class($this->container) : get_class($service); $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => $this->options['node.instance']); } } return $nodes; } private function cloneContainer() { $parameterBag = new ParameterBag($this->container->getParameterBag()->all()); $container = new ContainerBuilder($parameterBag); $container->setDefinitions($this->container->getDefinitions()); $container->setAliases($this->container->getAliases()); $container->setResources($this->container->getResources()); foreach ($this->container->getScopes() as $scope => $parentScope) { $container->addScope(new Scope($scope, $parentScope)); } foreach ($this->container->getExtensions() as $extension) { $container->registerExtension($extension); } return $container; } /** * Returns the start dot. * * @return string The string representation of a start dot */ private function startDot() { return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n", $this->addOptions($this->options['graph']), $this->addOptions($this->options['node']), $this->addOptions($this->options['edge']) ); } /** * Returns the end dot. * * @return string */ private function endDot() { return "}\n"; } /** * Adds attributes. * * @param array $attributes An array of attributes * * @return string A comma separated list of attributes */ private function addAttributes($attributes) { $code = array(); foreach ($attributes as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } return $code ? ', '.implode(', ', $code) : ''; } /** * Adds options. * * @param array $options An array of options * * @return string A space separated list of options */ private function addOptions($options) { $code = array(); foreach ($options as $k => $v) { $code[] = sprintf('%s="%s"', $k, $v); } return implode(' ', $code); } /** * Dotizes an identifier. * * @param string $id The identifier to dotize * * @return string A dotized string */ private function dotize($id) { return strtolower(preg_replace('/\W/i', '_', $id)); } /** * Compiles an array of aliases for a specified service id. * * @param string $id A service id * * @return array An array of aliases */ private function getAliases($id) { $aliases = array(); foreach ($this->container->getAliases() as $alias => $origin) { if ($id == $origin) { $aliases[] = $alias; } } return $aliases; } }
Harmeko/badass_shop
vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php
PHP
mit
10,241
'use strict'; angular.module('mean.system').directive('googleMaps', ['GoogleMaps', 'Global', function(GoogleMaps, Global) { return { restrict: 'E', template: '<div id="map" style="height: 600px; width: 100%;"></div>', controller: function() { var mapOptions; if ( GoogleMaps ) { mapOptions = { center: new GoogleMaps.LatLng(-34.397, 150.644), zoom: 14, mapTypeId: GoogleMaps.MapTypeId.ROADMAP }; Global.map = new GoogleMaps.Map(document.getElementById('map'), mapOptions); } } }; }]);
ezekielriva/bus-locator
public/system/directives/google-maps.js
JavaScript
mit
612
import { Component, OnInit, HostListener, ElementRef } from '@angular/core'; import { Router, NavigationEnd, NavigationExtras } from '@angular/router'; import { AuthService } from '../../services/auth.service'; @Component({ selector: 'app-nav', templateUrl: 'app-nav.component.html' }) export class AppNavComponent implements OnInit { loggedIn: boolean; menuDropped: boolean; searchKeyword: string; constructor( public auth: AuthService, private router: Router, private elementRef: ElementRef ) { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { this.menuDropped = false; this.searchKeyword = ''; } }); this.searchKeyword = ''; } ngOnInit() { this.auth.checkLogin(); } toggleMenu() { this.menuDropped = !this.menuDropped; } logout(): void { this.auth.logout(); this.menuDropped = false; } searchPackages(e: Event): void { e.preventDefault(); const navigationExtras: NavigationExtras = { queryParams: { 'keyword': this.searchKeyword } }; this.router.navigate(['search'], navigationExtras); } @HostListener('document:click', ['$event']) onBlur(e: MouseEvent) { if (!this.menuDropped) { return; } let toggleBtn = this.elementRef.nativeElement.querySelector('.drop-menu-act'); if (e.target === toggleBtn || toggleBtn.contains(<any>e.target)) { return; } let dropMenu: HTMLElement = this.elementRef.nativeElement.querySelector('.nav-dropdown'); if (dropMenu && dropMenu !== e.target && !dropMenu.contains((<any>e.target))) { this.menuDropped = false; } } }
Izak88/morose
src/app/components/app-nav/app-nav.component.ts
TypeScript
mit
1,671
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "walletmodel.h" #include "miningpage.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> WalletView::WalletView(QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); receiveCoinsPage = new ReceiveCoinsDialog(); sendCoinsPage = new SendCoinsDialog(); miningPage = new MiningPage(); addWidget(overviewPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); addWidget(miningPage); // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); miningPage->setClientModel(clientModel); } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsPage->setModel(walletModel); miningPage->setWalletModel(walletModel); if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::gotoMiningPage() { setCurrentWidget(miningPage); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::usedSendingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); }
coinkeeper/2015-06-22_19-00_ziftrcoin
src/qt/walletview.cpp
C++
mit
10,319
<?php return array ( 'id' => 'samsung_gt_m5650_ver1', 'fallback' => 'generic_dolfin', 'capabilities' => array ( 'pointing_method' => 'touchscreen', 'mobile_browser_version' => '1.0', 'uaprof' => 'http://wap.samsungmobile.com/uaprof/GT-M5650.rdf', 'model_name' => 'GT M5650', 'brand_name' => 'Samsung', 'marketing_name' => 'Corby Lindy', 'release_date' => '2010_february', 'softkey_support' => 'true', 'table_support' => 'true', 'wml_1_1' => 'true', 'wml_1_2' => 'true', 'xhtml_support_level' => '3', 'wml_1_3' => 'true', 'columns' => '20', 'rows' => '16', 'max_image_width' => '228', 'resolution_width' => '240', 'resolution_height' => '320', 'max_image_height' => '280', 'jpg' => 'true', 'gif' => 'true', 'bmp' => 'true', 'wbmp' => 'true', 'png' => 'true', 'colors' => '65536', 'nokia_voice_call' => 'true', 'streaming_vcodec_mpeg4_asp' => '0', 'streaming_vcodec_h263_0' => '10', 'streaming_3g2' => 'true', 'streaming_3gpp' => 'true', 'streaming_acodec_amr' => 'nb', 'streaming_vcodec_h264_bp' => '1', 'streaming_video' => 'true', 'streaming_vcodec_mpeg4_sp' => '0', 'wap_push_support' => 'true', 'mms_png' => 'true', 'mms_max_size' => '307200', 'mms_max_width' => '0', 'mms_spmidi' => 'true', 'mms_max_height' => '0', 'mms_gif_static' => 'true', 'mms_wav' => 'true', 'mms_vcard' => 'true', 'mms_midi_monophonic' => 'true', 'mms_bmp' => 'true', 'mms_wbmp' => 'true', 'mms_amr' => 'true', 'mms_jpeg_baseline' => 'true', 'aac' => 'true', 'sp_midi' => 'true', 'mp3' => 'true', 'amr' => 'true', 'midi_monophonic' => 'true', 'imelody' => 'true', 'j2me_midp_2_0' => 'true', 'j2me_cldc_1_0' => 'true', 'j2me_cldc_1_1' => 'true', 'j2me_midp_1_0' => 'true', 'wifi' => 'true', 'max_data_rate' => '3600', 'directdownload_support' => 'true', 'oma_support' => 'true', 'oma_v_1_0_separate_delivery' => 'true', 'image_inlining' => 'true', ), );
cuckata23/wurfl-data
data/samsung_gt_m5650_ver1.php
PHP
mit
2,098
<?php /** * File: SimpleImage.php * Author: Simon Jarvis * Modified by: Miguel Fermín * Based in: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html */ class Image_compression_helper { public $image; public $image_type; public function __construct($filename = null) { if (!empty($filename)) { $this->load($filename); } } public function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if ($this->image_type == IMAGETYPE_JPEG) { $this->image = imagecreatefromjpeg($filename); } elseif ($this->image_type == IMAGETYPE_GIF) { $this->image = imagecreatefromgif($filename); } elseif ($this->image_type == IMAGETYPE_PNG) { $this->image = imagecreatefrompng($filename); } else { throw new Exception("The file you're trying to open is not supported"); } } public function example($url) { // Usage: // Load the original image $image = new SimpleImage($url); // Resize the image to 600px width and the proportional height $image->resizeToWidth(600); $image->save('lemon_resized.jpg'); // Create a squared version of the image $image->square(200); $image->save('lemon_squared.jpg'); // Scales the image to 75% $image->scale(75); $image->save('lemon_scaled.jpg'); // Resize the image to specific width and height $image->resize(80, 60); $image->save('lemon_resized2.jpg'); // Resize the canvas and fill the empty space with a color of your choice $image->maxareafill(600, 400, 32, 39, 240); $image->save('lemon_filled.jpg'); // Output the image to the browser: $image->output(); } public function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = null) { if ($image_type == IMAGETYPE_JPEG) { imagejpeg($this->image, $filename, $compression); } elseif ($image_type == IMAGETYPE_GIF) { imagegif($this->image, $filename); } elseif ($image_type == IMAGETYPE_PNG) { imagepng($this->image, $filename); } if ($permissions != null) { chmod($filename, $permissions); } } public function output($image_type = IMAGETYPE_JPEG, $quality = 80) { if ($image_type == IMAGETYPE_JPEG) { header("Content-type: image/jpeg"); imagejpeg($this->image, null, $quality); } elseif ($image_type == IMAGETYPE_GIF) { header("Content-type: image/gif"); imagegif($this->image); } elseif ($image_type == IMAGETYPE_PNG) { header("Content-type: image/png"); imagepng($this->image); } } public function getWidth() { return imagesx($this->image); } public function getHeight() { return imagesy($this->image); } public function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = round($this->getWidth() * $ratio); $this->resize($width, $height); } public function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = round($this->getHeight() * $ratio); $this->resize($width, $height); } public function square($size) { $new_image = imagecreatetruecolor($size, $size); if ($this->getWidth() > $this->getHeight()) { $this->resizeToHeight($size); imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0)); imagealphablending($new_image, false); imagesavealpha($new_image, true); imagecopy($new_image, $this->image, 0, 0, ($this->getWidth() - $size) / 2, 0, $size, $size); } else { $this->resizeToWidth($size); imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0)); imagealphablending($new_image, false); imagesavealpha($new_image, true); imagecopy($new_image, $this->image, 0, 0, 0, ($this->getHeight() - $size) / 2, $size, $size); } $this->image = $new_image; } public function scale($scale) { $width = $this->getWidth() * $scale / 100; $height = $this->getHeight() * $scale / 100; $this->resize($width, $height); } public function resize($width, $height) { $new_image = imagecreatetruecolor($width, $height); imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0)); imagealphablending($new_image, false); imagesavealpha($new_image, true); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } public function cut($x, $y, $width, $height) { $new_image = imagecreatetruecolor($width, $height); imagecolortransparent($new_image, imagecolorallocate($new_image, 0, 0, 0)); imagealphablending($new_image, false); imagesavealpha($new_image, true); imagecopy($new_image, $this->image, 0, 0, $x, $y, $width, $height); $this->image = $new_image; } public function maxarea($width, $height = null) { $height = $height ? $height : $width; if ($this->getWidth() > $width) { $this->resizeToWidth($width); } if ($this->getHeight() > $height) { $this->resizeToheight($height); } } public function minarea($width, $height = null) { $height = $height ? $height : $width; if ($this->getWidth() < $width) { $this->resizeToWidth($width); } if ($this->getHeight() < $height) { $this->resizeToheight($height); } } public function cutFromCenter($width, $height) { if ($width < $this->getWidth() && $width > $height) { $this->resizeToWidth($width); } if ($height < $this->getHeight() && $width < $height) { $this->resizeToHeight($height); } $x = ($this->getWidth() / 2) - ($width / 2); $y = ($this->getHeight() / 2) - ($height / 2); return $this->cut($x, $y, $width, $height); } public function maxareafill($width, $height, $red = 0, $green = 0, $blue = 0) { $this->maxarea($width, $height); $new_image = imagecreatetruecolor($width, $height); $color_fill = imagecolorallocate($new_image, $red, $green, $blue); imagefill($new_image, 0, 0, $color_fill); imagecopyresampled($new_image, $this->image, floor(($width - $this->getWidth()) / 2), floor(($height - $this->getHeight()) / 2), 0, 0, $this->getWidth(), $this->getHeight(), $this->getWidth(), $this->getHeight() ); $this->image = $new_image; } }
ryno888/thehappydog
application/helpers/image_compression_helper.php
PHP
mit
7,553
# == Schema Information # # Table name: accounts # # id :integer not null, primary key # type :string default("Account"), not null # description :string default(""), not null # currency :string default("USD"), not null # created_at :datetime not null # updated_at :datetime not null # owner_id :integer # owner_type :string # standalone :boolean default(FALSE) # override_fee_percentage :integer # # Indexes # # index_accounts_on_item_id (owner_id) # index_accounts_on_item_type (owner_type) # index_accounts_on_type (type) # class Account::SoftwarePublicInterest < Account end
bountysource/core
app/models/account/software_public_interest.rb
Ruby
mit
800
package illume.analysis; import java.awt.image.BufferedImage; /* This simple analyser example averages pixel values. */ public class SimpleImageAnalyser<T extends BufferedImage> extends AbstractImageAnalyser<T> { @Override public double analyse(T input) { int sum_r = 0; int sum_g = 0; int sum_b = 0; for (int y = 0; y < input.getHeight(); y++) { for (int x = 0; x < input.getWidth(); x++) { final int clr = input.getRGB(x, y); sum_r += (clr & 0x00ff0000) >> 16; sum_g += (clr & 0x0000ff00) >> 8; sum_b += clr & 0x000000ff; } } double sum_rgb = ((sum_r + sum_b + sum_g) / 3.0d); double avg = sum_rgb / (input.getHeight() * input.getWidth()); // 8-bit RGB return avg / 255; } }
HSAR/Illume
src/main/java/illume/analysis/SimpleImageAnalyser.java
Java
mit
852
import { ExtraGlamorousProps } from './glamorous-component' import { ViewProperties, TextStyle, ViewStyle, ImageStyle, TextInputProperties, ImageProperties, ScrollViewProps, TextProperties, TouchableHighlightProperties, TouchableNativeFeedbackProperties, TouchableOpacityProperties, TouchableWithoutFeedbackProps, FlatListProperties, SectionListProperties } from 'react-native' export interface NativeComponent { Image: React.StatelessComponent< ImageProperties & ExtraGlamorousProps & ImageStyle > ScrollView: React.StatelessComponent< ScrollViewProps & ExtraGlamorousProps & ViewStyle > Text: React.StatelessComponent< TextProperties & ExtraGlamorousProps & TextStyle > TextInput: React.StatelessComponent< TextInputProperties & ExtraGlamorousProps & TextStyle > TouchableHighlight: React.StatelessComponent< TouchableHighlightProperties & ExtraGlamorousProps & ViewStyle > TouchableNativeFeedback: React.StatelessComponent< TouchableNativeFeedbackProperties & ExtraGlamorousProps & ViewStyle > TouchableOpacity: React.StatelessComponent< TouchableOpacityProperties & ExtraGlamorousProps & ViewStyle > TouchableWithoutFeedback: React.StatelessComponent< TouchableWithoutFeedbackProps & ExtraGlamorousProps & ViewStyle > View: React.StatelessComponent< ViewProperties & ExtraGlamorousProps & ViewStyle > FlatList: React.StatelessComponent< FlatListProperties<any> & ExtraGlamorousProps & ViewStyle > SectionList: React.StatelessComponent< SectionListProperties<any> & ExtraGlamorousProps & ViewStyle > }
robinpowered/glamorous-native
typings/built-in-glamorous-components.d.ts
TypeScript
mit
1,623
var express = require('../') , Router = express.Router , request = require('./support/http') , methods = require('methods') , assert = require('assert'); describe('Router', function(){ var router, app; beforeEach(function(){ router = new Router; app = express(); }) describe('.match(method, url, i)', function(){ it('should match based on index', function(){ router.route('get', '/foo', function(){}); router.route('get', '/foob?', function(){}); router.route('get', '/bar', function(){}); var method = 'GET'; var url = '/foo?bar=baz'; var route = router.match(method, url, 0); route.constructor.name.should.equal('Route'); route.method.should.equal('get'); route.path.should.equal('/foo'); var route = router.match(method, url, 1); route.path.should.equal('/foob?'); var route = router.match(method, url, 2); assert(!route); url = '/bar'; var route = router.match(method, url); route.path.should.equal('/bar'); }) }) describe('.matchRequest(req, i)', function(){ it('should match based on index', function(){ router.route('get', '/foo', function(){}); router.route('get', '/foob?', function(){}); router.route('get', '/bar', function(){}); var req = { method: 'GET', url: '/foo?bar=baz' }; var route = router.matchRequest(req, 0); route.constructor.name.should.equal('Route'); route.method.should.equal('get'); route.path.should.equal('/foo'); var route = router.matchRequest(req, 1); req._route_index.should.equal(1); route.path.should.equal('/foob?'); var route = router.matchRequest(req, 2); assert(!route); req.url = '/bar'; var route = router.matchRequest(req); route.path.should.equal('/bar'); }) }) describe('.middleware', function(){ it('should dispatch', function(done){ router.route('get', '/foo', function(req, res){ res.send('foo'); }); app.use(router.middleware); request(app) .get('/foo') .expect('foo', done); }) }) describe('.multiple callbacks', function(){ it('should throw if a callback is null', function(){ assert.throws(function () { router.route('get', '/foo', null, function(){}); }) }) it('should throw if a callback is undefined', function(){ assert.throws(function () { router.route('get', '/foo', undefined, function(){}); }) }) it('should throw if a callback is not a function', function(){ assert.throws(function () { router.route('get', '/foo', 'not a function', function(){}); }) }) it('should not throw if all callbacks are functions', function(){ router.route('get', '/foo', function(){}, function(){}); }) }) describe('.all', function() { it('should support using .all to capture all http verbs', function() { var router = new Router(); router.all('/foo', function(){}); var url = '/foo?bar=baz'; methods.forEach(function testMethod(method) { var route = router.match(method, url); route.constructor.name.should.equal('Route'); route.method.should.equal(method); route.path.should.equal('/foo'); }); }) }) })
Mitdasein/AngularBlogGitHub
mongodb/visionmedia-express-7724fc6/test/Router.js
JavaScript
mit
3,342
#include "EventQueueThread.h"
InfiniteInteractive/LimitlessSDK
sdk/Utilities/eventQueueThread.cpp
C++
mit
30
using Foundation; using System; using System.Linq; using UIKit; namespace UICatalog { public partial class BaseSearchController : UITableViewController, IUISearchResultsUpdating { private const string CellIdentifier = "searchResultsCell"; private readonly string[] allItems = { "Here's", "to", "the", "crazy", "ones.", "The", "misfits.", "The", "rebels.", "The", "troublemakers.", "The", "round", "pegs", "in", "the", "square", "holes.", "The", "ones", "who", "see", "things", "differently.", "They're", "not", "fond", "of", @"rules.", "And", "they", "have", "no", "respect", "for", "the", "status", "quo.", "You", "can", "quote", "them,", "disagree", "with", "them,", "glorify", "or", "vilify", "them.", "About", "the", "only", "thing", "you", "can't", "do", "is", "ignore", "them.", "Because", "they", "change", "things.", "They", "push", "the", "human", "race", "forward.", "And", "while", "some", "may", "see", "them", "as", "the", "crazy", "ones,", "we", "see", "genius.", "Because", "the", "people", "who", "are", "crazy", "enough", "to", "think", "they", "can", "change", "the", "world,", "are", "the", "ones", "who", "do." }; private string[] items; private string query; public BaseSearchController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); items = allItems; } protected void ApplyFilter(string filter) { query = filter; items = string.IsNullOrEmpty(query) ? allItems : allItems.Where(s => s.Contains(query)).ToArray(); TableView.ReloadData(); } public override nint RowsInSection(UITableView tableView, nint section) { return items.Length; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath); cell.TextLabel.Text = items[indexPath.Row]; return cell; } #region IUISearchResultsUpdating [Export("updateSearchResultsForSearchController:")] public void UpdateSearchResultsForSearchController(UISearchController searchController) { // UpdateSearchResultsForSearchController is called when the controller is being dismissed // to allow those who are using the controller they are search as the results controller a chance to reset their state. // No need to update anything if we're being dismissed. if (searchController.Active) { ApplyFilter(searchController.SearchBar.Text); } } #endregion } }
xamarin/monotouch-samples
UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs
C#
mit
2,884
<?php /** * This file is part of the Cubiche package. * * Copyright (c) Cubiche * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cubiche\Core\EventDispatcher; use Cubiche\Core\Bus\MessageInterface; /** * Event interface. * * @author Ivannis Suárez Jerez <[email protected]> */ interface EventInterface extends MessageInterface { /** * Stop event propagation. * * @return $this */ public function stopPropagation(); /** * Check whether propagation was stopped. * * @return bool */ public function isPropagationStopped(); /** * Get the event name. * * @return string */ public function eventName(); }
cubiche/cubiche
src/Cubiche/Core/EventDispatcher/EventInterface.php
PHP
mit
799
<?php namespace Kordy\Ticketit\Controllers; use App\Http\Controllers\Controller; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Kordy\Ticketit\Models\Agent; use Kordy\Ticketit\Models\Setting; use Kordy\Ticketit\Seeds\SettingsTableSeeder; use Kordy\Ticketit\Seeds\TicketitTableSeeder; class InstallController extends Controller { public $migrations_tables = []; public function __construct() { $migrations = \File::files(dirname(dirname(__FILE__)).'/Migrations'); foreach ($migrations as $migration) { $this->migrations_tables[] = basename($migration, '.php'); } } public function publicAssets() { $public = $this->allFilesList(public_path('vendor/ticketit')); $assets = $this->allFilesList(base_path('vendor/kordy/ticketit/src/Public')); if ($public !== $assets) { Artisan::call('vendor:publish', [ '--provider' => 'Kordy\\Ticketit\\TicketitServiceProvider', '--tag' => ['public'], ]); } } /* * Initial install form */ public function index() { // if all migrations are not yet installed or missing settings table, // then start the initial install with admin and master template choices if (count($this->migrations_tables) == count($this->inactiveMigrations()) || in_array('2015_10_08_123457_create_settings_table', $this->inactiveMigrations()) ) { $views_files_list = $this->viewsFilesList('../resources/views/') + ['another' => trans('ticketit::install.another-file')]; $inactive_migrations = $this->inactiveMigrations(); $users_list = User::lists('first_name', 'id')->toArray(); return view('ticketit::install.index', compact('views_files_list', 'inactive_migrations', 'users_list')); } // other than that, Upgrade to a new version, installing new migrations and new settings slugs if (Agent::isAdmin()) { $inactive_migrations = $this->inactiveMigrations(); $inactive_settings = $this->inactiveSettings(); return view('ticketit::install.upgrade', compact('inactive_migrations', 'inactive_settings')); } \Log::emergency('Ticketit needs upgrade, admin should login and visit ticketit-install to activate the upgrade'); throw new \Exception('Ticketit needs upgrade, admin should login and visit ticketit install route'); } /* * Do all pre-requested setup */ public function setup(Request $request) { $master = $request->master; if ($master == 'another') { $another_file = $request->other_path; $views_content = strstr(substr(strstr($another_file, 'views/'), 6), '.blade.php', true); $master = str_replace('/', '.', $views_content); } $this->initialSettings($master); $admin_id = $request->admin_id; $admin = User::find($admin_id); $admin->ticketit_admin = true; $admin->save(); return redirect('/'.Setting::grab('main_route')); } /* * Do version upgrade */ public function upgrade() { if (Agent::isAdmin()) { $this->initialSettings(); return redirect('/'.Setting::grab('main_route')); } \Log::emergency('Ticketit upgrade path access: Only admin is allowed to upgrade'); throw new \Exception('Ticketit upgrade path access: Only admin is allowed to upgrade'); } /* * Initial installer to install migrations, seed default settings, and configure the master_template */ public function initialSettings($master = false) { $inactive_migrations = $this->inactiveMigrations(); if ($inactive_migrations) { // If a migration is missing, do the migrate Artisan::call('vendor:publish', [ '--provider' => 'Kordy\\Ticketit\\TicketitServiceProvider', '--tag' => ['db'], ]); Artisan::call('migrate'); $this->settingsSeeder($master); // if this is the first install of the html editor, seed old posts text to the new html column if (in_array('2016_01_15_002617_add_htmlcontent_to_ticketit_and_comments', $inactive_migrations)) { Artisan::call('ticketit:htmlify'); } } elseif ($this->inactiveSettings()) { // new settings to be installed $this->settingsSeeder($master); } \Cache::forget('settings'); } /** * Run the settings table seeder. * * @param string $master */ public function settingsSeeder($master = false) { $cli_path = 'config/ticketit.php'; // if seeder run from cli, use the cli path $provider_path = '../config/ticketit.php'; // if seeder run from provider, use the provider path $config_settings = []; $settings_file_path = false; if (File::isFile($cli_path)) { $settings_file_path = $cli_path; } elseif (File::isFile($provider_path)) { $settings_file_path = $provider_path; } if ($settings_file_path) { $config_settings = include $settings_file_path; File::move($settings_file_path, $settings_file_path.'.backup'); } $seeder = new SettingsTableSeeder(); if ($master) { $config_settings['master_template'] = $master; } $seeder->config = $config_settings; $seeder->run(); } /** * Get list of all files in the views folder. * * @return mixed */ public function viewsFilesList($dir_path) { $dir_files = File::files($dir_path); $files = []; foreach ($dir_files as $file) { $path = basename($file); $name = strstr(basename($file), '.', true); $files[$name] = $path; } return $files; } /** * Get list of all files in the views folder. * * @return mixed */ public function allFilesList($dir_path) { $files = []; if (File::exists($dir_path)) { $dir_files = File::allFiles($dir_path); foreach ($dir_files as $file) { $path = basename($file); $name = strstr(basename($file), '.', true); $files[$name] = $path; } } return $files; } /** * Get all Ticketit Package migrations that were not migrated. * * @return array */ public function inactiveMigrations() { $inactiveMigrations = []; $migration_arr = []; // Package Migrations $tables = $this->migrations_tables; // Application active migrations $migrations = DB::select('select * from migrations'); foreach ($migrations as $migration_parent) { // Count active package migrations $migration_arr [] = $migration_parent->migration; } foreach ($tables as $table) { if (!in_array($table, $migration_arr)) { $inactiveMigrations [] = $table; } } return $inactiveMigrations; } /** * Check if all Ticketit Package settings that were not installed to setting table. * * @return bool */ public function inactiveSettings() { $seeder = new SettingsTableSeeder(); // Package Settings $installed_settings = DB::table('ticketit_settings')->lists('value', 'slug'); // Application active migrations $default_Settings = $seeder->getDefaults(); if (count($installed_settings) == count($default_Settings)) { return false; } $inactive_settings = array_diff_key($default_Settings, $installed_settings); return $inactive_settings; } /** * Generate demo users, agents, and tickets. * * @return \Illuminate\Http\RedirectResponse */ public function demoDataSeeder() { $seeder = new TicketitTableSeeder(); $seeder->run(); session()->flash('status', 'Demo tickets, users, and agents are seeded!'); return redirect()->action('\Kordy\Ticketit\Controllers\TicketsController@index'); } }
maxvishnja/ticketsystem
src/Controllers/InstallController.php
PHP
mit
8,480
package com.covoex.qarvox; import com.covoex.qarvox.Application.BasicFunction; /** * @author Myeongjun Kim */ public class Main { public static void main(String[] args) { BasicFunction.programStart(); } }
Covoex/Qarvox
src/main/java/com/covoex/qarvox/Main.java
Java
mit
227
<?php /* Safe sample input : get the field UserData from the variable $_POST sanitize : use of ternary condition construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_POST['UserData']; $tainted = $tainted == 'safe1' ? 'safe1' : 'safe2'; $var = http_redirect("pages/'". $tainted . "'.php"); ?>
stivalet/PHP-Vulnerability-test-suite
URF/CWE_601/safe/CWE_601__POST__ternary_white_list__http_redirect_file_id-concatenation_simple_quote.php
PHP
mit
1,220
import {Curve} from '../curve' export class Line extends Curve { constructor(p0, v) { super(); this.p0 = p0; this.v = v; this._pointsCache = new Map(); } intersectSurface(surface) { if (surface.isPlane) { const s0 = surface.normal.multiply(surface.w); return surface.normal.dot(s0.minus(this.p0)) / surface.normal.dot(this.v); // 4.7.4 } else { return super.intersectSurface(surface); } } intersectCurve(curve, surface) { if (curve.isLine && surface.isPlane) { const otherNormal = surface.normal.cross(curve.v)._normalize(); return otherNormal.dot(curve.p0.minus(this.p0)) / otherNormal.dot(this.v); // (4.8.3) } return super.intersectCurve(curve, surface); } parametricEquation(t) { return this.p0.plus(this.v.multiply(t)); } t(point) { return point.minus(this.p0).dot(this.v); } pointOfSurfaceIntersection(surface) { let point = this._pointsCache.get(surface); if (!point) { const t = this.intersectSurface(surface); point = this.parametricEquation(t); this._pointsCache.set(surface, point); } return point; } translate(vector) { return new Line(this.p0.plus(vector), this.v); } approximate(resolution, from, to, path) { } offset() {}; } Line.prototype.isLine = true; Line.fromTwoPlanesIntersection = function(plane1, plane2) { const n1 = plane1.normal; const n2 = plane2.normal; const v = n1.cross(n2)._normalize(); const pf1 = plane1.toParametricForm(); const pf2 = plane2.toParametricForm(); const r0diff = pf1.r0.minus(pf2.r0); const ww = r0diff.minus(n2.multiply(r0diff.dot(n2))); const p0 = pf2.r0.plus( ww.multiply( n1.dot(r0diff) / n1.dot(ww))); return new Line(p0, v); }; Line.fromSegment = function(a, b) { return new Line(a, b.minus(a)._normalize()); };
Autodrop3d/autodrop3dServer
public/webcad/app/brep/geom/impl/line.js
JavaScript
mit
1,860
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_11_01 module Models # # Properties of the Radius client root certificate of # VpnServerConfiguration. # class VpnServerConfigRadiusClientRootCertificate include MsRestAzure # @return [String] The certificate name. attr_accessor :name # @return [String] The Radius client root certificate thumbprint. attr_accessor :thumbprint # # Mapper for VpnServerConfigRadiusClientRootCertificate class as Ruby # Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VpnServerConfigRadiusClientRootCertificate', type: { name: 'Composite', class_name: 'VpnServerConfigRadiusClientRootCertificate', model_properties: { name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, thumbprint: { client_side_validation: true, required: false, serialized_name: 'thumbprint', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2019-11-01/generated/azure_mgmt_network/models/vpn_server_config_radius_client_root_certificate.rb
Ruby
mit
1,617
<?php /** * * Enter address data for the cart, when anonymous users checkout * * @package VirtueMart * @subpackage User * @author Max Milbers * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id: edit_address_addshipto.php 7499 2013-12-18 15:11:51Z Milbo $ */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); ?> <fieldset> <legend> <?php echo '<span class="userfields_info">' .vmText::_('COM_VIRTUEMART_USER_FORM_SHIPTO_LBL').'</span>'; ?> </legend> <?php echo $this->lists['shipTo']; ?> </fieldset>
yaelduckwen/libriastore
joomla/templates/horme_3/html/com_virtuemart/user/edit_address_addshipto.php
PHP
mit
988
#include "TString.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TGraphAsymmErrors.h" #include <fstream> #include <Riostream.h> #include <sstream> #include <fstream> using namespace std; TGraphErrors* GetGraphWithSymmYErrorsFromFile(TString txtFileName, Color_t markerColor=1, Style_t markerStyle=20, Size_t markerSize=1, Style_t lineStyle=1,Width_t lineWidth=2, bool IsNoErr=0) { Float_t x_array[400],ex_array[400],y_array[400],ey_array[400]; Char_t buffer[2048]; Float_t x,y,ex,ey; Int_t nlines = 0; ifstream infile(txtFileName.Data()); if (!infile.is_open()) { cout << "Error opening file. Exiting." << endl; } else { while (!infile.eof()) { infile.getline(buffer,2048); sscanf(buffer,"%f %f %f\n",&x,&y,&ey); x_array[nlines] = x; ex_array[nlines] = 0; y_array[nlines] = y; ey_array[nlines] = ey; if(IsNoErr) ey_array[nlines]=0; nlines++; } } TGraphErrors *graph = new TGraphErrors(nlines-1,x_array,y_array,ex_array,ey_array); txtFileName.Remove(txtFileName.Index(".txt"),4); graph->SetName(txtFileName.Data()); graph->SetMarkerStyle(markerStyle); graph->SetMarkerColor(markerColor); graph->SetLineStyle(lineStyle); graph->SetLineColor(markerColor); graph->SetMarkerSize(markerSize); graph->SetLineWidth(3); return graph; } void drawSysBoxValue(TGraph* gr, int fillcolor=TColor::GetColor("#ffff00"), double xwidth=0.3, double *percent, double xshift=0) { TBox* box; for(int n=0;n<gr->GetN();n++) { double x,y; gr->GetPoint(n,x,y); double yerr = percent[n]; box = new TBox(x+xshift-xwidth,y-fabs(yerr),x+xwidth,y+fabs(yerr)); box->SetLineWidth(0); box->SetFillColor(kGray); box->Draw("Fsame"); } }
tuos/FlowAndCorrelations
flowCorr/paperMacro/qm/GetFileAndSys.C
C++
mit
1,754
<?php // Documentation test config file for "Components / Jumbotron" part return [ 'title' => 'Jumbotron', 'url' => '%bootstrap-url%/components/jumbotron/', 'rendering' => function (\Laminas\View\Renderer\PhpRenderer $oView) { echo $oView->jumbotron([ 'title' => 'Hello, world!', 'lead' => 'This is a simple hero unit, a simple jumbotron-style component ' . 'for calling extra attention to featured content or information.', '---' => ['attributes' => ['class' => 'my-4']], 'It uses utility classes for typography and spacing to space ' . 'content out within the larger container.', 'button' => [ 'options' => [ 'tag' => 'a', 'label' => 'Learn more', 'variant' => 'primary', 'size' => 'lg', ], 'attributes' => [ 'href' => '#', ] ], ]) . PHP_EOL; // To make the jumbotron full width, and without rounded corners, add the option fluid echo $oView->jumbotron( [ 'title' => 'Fluid jumbotron', 'lead' => 'This is a modified jumbotron that occupies the entire horizontal space of its parent.', ], ['fluid' => true] ); }, 'expected' => '<div class="jumbotron">' . PHP_EOL . ' <h1 class="display-4">Hello, world!</h1>' . PHP_EOL . ' <p class="lead">This is a simple hero unit, a simple jumbotron-style component ' . 'for calling extra attention to featured content or information.</p>' . PHP_EOL . ' <hr class="my-4" />' . PHP_EOL . ' <p>It uses utility classes for typography and spacing to space ' . 'content out within the larger container.</p>' . PHP_EOL . ' <a href="&#x23;" class="btn&#x20;btn-lg&#x20;btn-primary" role="button">Learn more</a>' . PHP_EOL . '</div>' . PHP_EOL . '<div class="jumbotron&#x20;jumbotron-fluid">' . PHP_EOL . ' <div class="container">' . PHP_EOL . ' <h1 class="display-4">Fluid jumbotron</h1>' . PHP_EOL . ' <p class="lead">This is a modified jumbotron that occupies ' . 'the entire horizontal space of its parent.</p>' . PHP_EOL . ' </div>' . PHP_EOL . '</div>', ];
neilime/zf-twbs-helper-module
tests/TestSuite/Documentation/Components/Jumbotron.php
PHP
mit
2,445
""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs)
chriso/gauged
gauged/drivers/__init__.py
Python
mit
1,960
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders 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. */ package mockit.external.asm4; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * A Java field or method type. This class can be used to make it easier to * manipulate type and method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The sort of the <tt>void</tt> type. See {@link #getSort getSort}. */ public static final int VOID = 0; /** * The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}. */ public static final int BOOLEAN = 1; /** * The sort of the <tt>char</tt> type. See {@link #getSort getSort}. */ public static final int CHAR = 2; /** * The sort of the <tt>byte</tt> type. See {@link #getSort getSort}. */ public static final int BYTE = 3; /** * The sort of the <tt>short</tt> type. See {@link #getSort getSort}. */ public static final int SHORT = 4; /** * The sort of the <tt>int</tt> type. See {@link #getSort getSort}. */ public static final int INT = 5; /** * The sort of the <tt>float</tt> type. See {@link #getSort getSort}. */ public static final int FLOAT = 6; /** * The sort of the <tt>long</tt> type. See {@link #getSort getSort}. */ public static final int LONG = 7; /** * The sort of the <tt>double</tt> type. See {@link #getSort getSort}. */ public static final int DOUBLE = 8; /** * The sort of array reference types. See {@link #getSort getSort}. */ public static final int ARRAY = 9; /** * The sort of object reference types. See {@link #getSort getSort}. */ public static final int OBJECT = 10; /** * The sort of method types. See {@link #getSort getSort}. */ public static final int METHOD = 11; /** * The <tt>void</tt> type. */ public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The <tt>boolean</tt> type. */ public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>char</tt> type. */ public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The <tt>byte</tt> type. */ public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>short</tt> type. */ public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The <tt>int</tt> type. */ public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The <tt>float</tt> type. */ public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The <tt>long</tt> type. */ public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The <tt>double</tt> type. */ public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); private static final Type[] NO_ARGS = new Type[0]; // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, * for primitive types, the size, descriptor and getOpcode offsets for this * type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset * for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a reference type. * * @param sort the sort of the reference type to be constructed. * @param buf a buffer containing the descriptor of the previous type. * @param off the offset of this descriptor in the previous buffer. * @param len the length of this descriptor. */ private Type(int sort, char[] buf, int off, int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor a field or method type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given internal name. * * @param internalName an internal name. * @return the Java type corresponding to the given internal name. */ public static Type getObjectType(String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); } /** * Returns the Java type corresponding to the given method descriptor. * Equivalent to <code>Type.getType(methodDescriptor)</code>. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the given method descriptor. */ public static Type getMethodType(String methodDescriptor) { return getType(methodDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given class. * * @param c a class. * @return the Java type corresponding to the given class. */ public static Type getType(Class<?> c) { if (c.isPrimitive()) { if (c == Integer.TYPE) { return INT_TYPE; } else if (c == Void.TYPE) { return VOID_TYPE; } else if (c == Boolean.TYPE) { return BOOLEAN_TYPE; } else if (c == Byte.TYPE) { return BYTE_TYPE; } else if (c == Character.TYPE) { return CHAR_TYPE; } else if (c == Short.TYPE) { return SHORT_TYPE; } else if (c == Double.TYPE) { return DOUBLE_TYPE; } else if (c == Float.TYPE) { return FLOAT_TYPE; } else /* if (c == Long.TYPE) */{ return LONG_TYPE; } } else { return getType(getDescriptor(c)); } } /** * Returns the Java method type corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the Java method type corresponding to the given constructor. */ public static Type getType(Constructor<?> c) { return getType(getConstructorDescriptor(c)); } /** * Returns the Java method type corresponding to the given method. * * @param m a {@link Method Method} object. * @return the Java method type corresponding to the given method. */ public static Type getType(Method m) { return getType(getMethodDescriptor(m)); } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ public static Type[] getArgumentTypes(String methodDescriptor) { if (methodDescriptor.charAt(1) == ')') return NO_ARGS; char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java type corresponding to the return type of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the return type of the given * method descriptor. */ public static Type getReturnType(String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); return getType(buf, methodDescriptor.indexOf(')') + 1); } /** * Computes the size of the arguments and of the return value of a method. * * @param desc the descriptor of a method. * @return the size of the arguments of the method (plus one for the * implicit this argument), argSize, and the size of its return * value, retSize, packed into a single int i = * <tt>(argSize << 2) | retSize</tt> (argSize is therefore equal * to <tt>i >> 2</tt>, and retSize to <tt>i & 0x03</tt>). */ public static int getArgumentsAndReturnSizes(String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. For * method descriptors, buf is supposed to contain nothing more than the * descriptor itself. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(char[] buf, int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); case 'L': len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); case '(': return new Type(METHOD, buf, 0, buf.length); default: throw new IllegalArgumentException("Invalid type descriptor: " + new String(buf)); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the sort of this Java type. * * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, * {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT}, * {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG}, * {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY}, * {@link #OBJECT OBJECT} or {@link #METHOD METHOD}. */ public int getSort() { return sort; } /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ public int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ public Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the binary name of the class corresponding to this type. This * method must not be used on method types. * * @return the binary name of the class corresponding to this type. */ public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); case OBJECT: return new String(buf, off, len).replace('/', '.'); default: return null; } } /** * Returns the internal name of the class corresponding to this object or * array type. The internal name of a class is its fully qualified name (as * returned by Class.getName(), where '.' are replaced by '/'. This method * should only be used for an object or array type. * * @return the internal name of the class corresponding to this object type. */ public String getInternalName() { return new String(buf, off, len); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ public String getDescriptor() { StringBuffer buf = new StringBuffer(); getDescriptor(buf); return buf.toString(); } /** * Appends the descriptor corresponding to this Java type to the given * string buffer. * * @param buf the string buffer to which the descriptor must be appended. */ private void getDescriptor(StringBuffer buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == OBJECT) { buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } else { // sort == ARRAY || sort == METHOD buf.append(this.buf, off, len); } } // ------------------------------------------------------------------------ // Direct conversion from classes to type descriptors, // without intermediate Type objects // ------------------------------------------------------------------------ /** * Returns the internal name of the given class. The internal name of a * class is its fully qualified name, as returned by Class.getName(), where * '.' are replaced by '/'. * * @param c an object or array class. * @return the internal name of the given class. */ public static String getInternalName(Class<?> c) { return c.getName().replace('.', '/'); } /** * Returns the descriptor corresponding to the given Java type. * * @param c an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getDescriptor(Class<?> c) { StringBuffer buf = new StringBuffer(); getDescriptor(buf, c); return buf.toString(); } /** * Returns the descriptor corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the descriptor of the given constructor. */ public static String getConstructorDescriptor(Constructor<?> c) { Class<?>[] parameters = c.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } return buf.append(")V").toString(); } /** * Returns the descriptor corresponding to the given method. * * @param m a {@link Method Method} object. * @return the descriptor of the given method. */ public static String getMethodDescriptor(Method m) { Class<?>[] parameters = m.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } buf.append(')'); getDescriptor(buf, m.getReturnType()); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * * @param buf the string buffer to which the descriptor must be appended. * @param c the class whose descriptor must be computed. */ private static void getDescriptor(StringBuffer buf, Class<?> c) { Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } // ------------------------------------------------------------------------ // Corresponding size and opcodes // ------------------------------------------------------------------------ /** * Returns the size of values of this type. This method must not be used for * method types. * * @return the size of values of this type, i.e., 2 for <tt>long</tt> and * <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise. */ public int getSize() { // the size is in byte 0 of 'off' for primitive types (buf == null) return buf == null ? off & 0xFF : 1; } /** * Returns a JVM instruction opcode adapted to this Java type. This method * must not be used for method types. * * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, * ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, * ISHR, IUSHR, IAND, IOR, IXOR and IRETURN. * @return an opcode that is similar to the given opcode, but adapted to * this Java type. For example, if this type is <tt>float</tt> and * <tt>opcode</tt> is IRETURN, this method returns FRETURN. */ public int getOpcode(int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } } // ------------------------------------------------------------------------ // Equals, hashCode and toString // ------------------------------------------------------------------------ /** * Tests if the given object is equal to this type. * * @param o the object to be compared to this type. * @return <tt>true</tt> if the given object is equal to this type. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort >= ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; } /** * Returns a hash code value for this type. * * @return a hash code value for this type. */ @Override public int hashCode() { int hc = 13 * sort; if (sort >= ARRAY) { for (int i = off, end = i + len; i < end; i++) { hc = 17 * (hc + buf[i]); } } return hc; } /** * Returns a string representation of this type. * * @return the descriptor of this type. */ @Override public String toString() { return getDescriptor(); } }
borisbrodski/jmockit
main/src/mockit/external/asm4/Type.java
Java
mit
25,672
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibtokin.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
ibtokin/ibtokin
manage.py
Python
mit
805
<table class="table table-striped table-bordered table-hover"> <tr> <th>Student Id</th> <th>Student Name</th> <th>Course</th> <!--<th> <select class="form-control" name='Year Level' required> <option> THIRD YEAR</option> <option> ALL</option> <option> FIRST YEAR</option> <option> SECOND YEAR</option> <option> FOURTH YEAR</option> </select> </th>--> <th colspan="2">Action</th> </tr> <?php // fetch the records in tbl_enrollment $result = $this->enrollment->getStud($param); foreach($result as $info) { extract($info); $stud_info = $this->party->getStudInfo($partyid); $course = $this->course->getCourse($coursemajor); ?> <tr> <td><?php echo $stud_info['legacyid']; ?></td> <td><?php echo $stud_info['lastname'] . ' , ' . $stud_info['firstname'] ?></td> <td><?php echo $course; ?></td> <!--<td></td>--> <td> <?php if($stud_info['status'] != 'C'){ ?> <a class="a-table label label-info" href="/rgstr_build/<?php echo $stud_info['legacyid'];?>">View Records <span class="glyphicon glyphicon-file"></span></a> <?php } ?> </td> </tr> <?php //} } ?> </table>
Jheysoon/lcis
application/views/registrar/ajax/tbl_studlist.php
PHP
mit
1,567
/** * <copyright> * </copyright> * * $Id$ */ package org.eclipse.bpel4chor.model.pbd; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Query</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}</li> * </ul> * </p> * * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery() * @model * @generated */ public interface Query extends ExtensibleElements { /** * Returns the value of the '<em><b>Query Language</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Query Language</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Query Language</em>' attribute. * @see #setQueryLanguage(String) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_QueryLanguage() * @model * @generated */ String getQueryLanguage(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Query Language</em>' attribute. * @see #getQueryLanguage() * @generated */ void setQueryLanguage(String value); /** * Returns the value of the '<em><b>Opaque</b></em>' attribute. * The literals are from the enumeration {@link org.eclipse.bpel4chor.model.pbd.OpaqueBoolean}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Opaque</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Opaque</em>' attribute. * @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean * @see #setOpaque(OpaqueBoolean) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Opaque() * @model * @generated */ OpaqueBoolean getOpaque(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Opaque</em>' attribute. * @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean * @see #getOpaque() * @generated */ void setOpaque(OpaqueBoolean value); /** * Returns the value of the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see #setValue(String) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Value() * @model * @generated */ String getValue(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(String value); } // Query
chorsystem/middleware
chorDataModel/src/main/java/org/eclipse/bpel4chor/model/pbd/Query.java
Java
mit
3,371
import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextPane; import java.awt.SystemColor; /** * The GUIError object is used to show an error message if the Path of Exile API is not responding. * * @author Joschn */ public class GUIError{ private JFrame windowError; private JButton buttonRetry; private volatile boolean buttonPressed = false; private ButtonRetryListener buttonRetryListener = new ButtonRetryListener(); private String errorMessage = "Error! Path of Exile's API is not responding! Servers are probably down! Check www.pathofexile.com"; private String version = "2.7"; /** * Constructor for the GUIError object. */ public GUIError(){ initialize(); } /** * Initializes the GUI. */ private void initialize(){ Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // error window windowError = new JFrame(); windowError.setBounds(100, 100, 300, 145); windowError.setLocation(dim.width/2-windowError.getSize().width/2, dim.height/2-windowError.getSize().height/2); windowError.setResizable(false); windowError.setTitle("Ladder Tracker v" + version); windowError.setIconImage(new ImageIcon(getClass().getResource("icon.png")).getImage()); windowError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); windowError.getContentPane().setLayout(null); // button retry buttonRetry = new JButton("Retry"); buttonRetry.setBounds(10, 80, 274, 23); buttonRetry.addActionListener(buttonRetryListener); windowError.getContentPane().add(buttonRetry); // error text JTextPane textError = new JTextPane(); textError.setText(errorMessage); textError.setEditable(false); textError.setBackground(SystemColor.menu); textError.setBounds(10, 21, 274, 39); windowError.getContentPane().add(textError); } /** * Shows the error GUI and waits for the retry button to be pressed. */ public void show(){ windowError.setVisible(true); while(!buttonPressed){} windowError.dispose(); } /** * The definition of the action listener for the retry button. * * @author Joschn */ private class ButtonRetryListener implements ActionListener{ public void actionPerformed(ActionEvent e){ buttonPressed = true; } } }
jkjoschua/poe-ladder-tracker-java
LadderTracker/src/GUIError.java
Java
mit
2,387
import { GraphQLError } from '../../error/GraphQLError'; import type { SchemaDefinitionNode, SchemaExtensionNode, } from '../../language/ast'; import type { ASTVisitor } from '../../language/visitor'; import type { SDLValidationContext } from '../ValidationContext'; /** * Unique operation types * * A GraphQL document is only valid if it has only one type per operation. */ export function UniqueOperationTypesRule( context: SDLValidationContext, ): ASTVisitor { const schema = context.getSchema(); const definedOperationTypes = Object.create(null); const existingOperationTypes = schema ? { query: schema.getQueryType(), mutation: schema.getMutationType(), subscription: schema.getSubscriptionType(), } : {}; return { SchemaDefinition: checkOperationTypes, SchemaExtension: checkOperationTypes, }; function checkOperationTypes( node: SchemaDefinitionNode | SchemaExtensionNode, ) { // See: https://github.com/graphql/graphql-js/issues/2203 /* c8 ignore next */ const operationTypesNodes = node.operationTypes ?? []; for (const operationType of operationTypesNodes) { const operation = operationType.operation; const alreadyDefinedOperationType = definedOperationTypes[operation]; if (existingOperationTypes[operation]) { context.reportError( new GraphQLError( `Type for ${operation} already defined in the schema. It cannot be redefined.`, operationType, ), ); } else if (alreadyDefinedOperationType) { context.reportError( new GraphQLError( `There can be only one ${operation} type in schema.`, [alreadyDefinedOperationType, operationType], ), ); } else { definedOperationTypes[operation] = operationType; } } return false; } }
graphql/graphql-js
src/validation/rules/UniqueOperationTypesRule.ts
TypeScript
mit
1,903
#include "DirectShow.h"
xylsxyls/xueyelingshuang
src/DirectShow/DirectShow/src/DirectShow.cpp
C++
mit
23
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace Podcasts.Converters { public class PodcastDurationConverter : TypedConverter<TimeSpan?, string> { public override string Convert(TimeSpan? duration, object parameter, string language) { if (!duration.HasValue) { return "--"; } else if (duration.Value.TotalHours >= 1.0) { return duration?.ToString(@"h\:mm\:ss"); } else { return duration?.ToString(@"m\:ss"); } } public override TimeSpan? ConvertBack(string value, object parameter, string language) { throw new NotImplementedException(); } } }
AndrewGaspar/Podcasts
Podcasts.Shared/Converters/PodcastDurationConverter.cs
C#
mit
904
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import PipelineRunNodeedges from './PipelineRunNodeedges'; /** * The PipelineRunNode model module. * @module model/PipelineRunNode * @version 1.1.2-pre.0 */ class PipelineRunNode { /** * Constructs a new <code>PipelineRunNode</code>. * @alias module:model/PipelineRunNode */ constructor() { PipelineRunNode.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PipelineRunNode</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PipelineRunNode} obj Optional instance to populate. * @return {module:model/PipelineRunNode} The populated <code>PipelineRunNode</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PipelineRunNode(); if (data.hasOwnProperty('_class')) { obj['_class'] = ApiClient.convertToType(data['_class'], 'String'); } if (data.hasOwnProperty('displayName')) { obj['displayName'] = ApiClient.convertToType(data['displayName'], 'String'); } if (data.hasOwnProperty('durationInMillis')) { obj['durationInMillis'] = ApiClient.convertToType(data['durationInMillis'], 'Number'); } if (data.hasOwnProperty('edges')) { obj['edges'] = ApiClient.convertToType(data['edges'], [PipelineRunNodeedges]); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('result')) { obj['result'] = ApiClient.convertToType(data['result'], 'String'); } if (data.hasOwnProperty('startTime')) { obj['startTime'] = ApiClient.convertToType(data['startTime'], 'String'); } if (data.hasOwnProperty('state')) { obj['state'] = ApiClient.convertToType(data['state'], 'String'); } } return obj; } } /** * @member {String} _class */ PipelineRunNode.prototype['_class'] = undefined; /** * @member {String} displayName */ PipelineRunNode.prototype['displayName'] = undefined; /** * @member {Number} durationInMillis */ PipelineRunNode.prototype['durationInMillis'] = undefined; /** * @member {Array.<module:model/PipelineRunNodeedges>} edges */ PipelineRunNode.prototype['edges'] = undefined; /** * @member {String} id */ PipelineRunNode.prototype['id'] = undefined; /** * @member {String} result */ PipelineRunNode.prototype['result'] = undefined; /** * @member {String} startTime */ PipelineRunNode.prototype['startTime'] = undefined; /** * @member {String} state */ PipelineRunNode.prototype['state'] = undefined; export default PipelineRunNode;
cliffano/swaggy-jenkins
clients/javascript/generated/src/model/PipelineRunNode.js
JavaScript
mit
3,684
package com.lamost.update; import java.io.IOException; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; /** * Created by Jia on 2016/4/6. */ public class UpdateWebService { private static final String TAG = "WebService"; // 命名空间 private final static String SERVICE_NS = "http://ws.smarthome.zfznjj.com/"; // 阿里云 private final static String SERVICE_URL = "http://101.201.211.87:8080/zfzn02/services/smarthome?wsdl=SmarthomeWs.wsdl"; // SOAP Action private static String soapAction = ""; // 调用的方法名称 private static String methodName = ""; private HttpTransportSE ht; private SoapSerializationEnvelope envelope; private SoapObject soapObject; private SoapObject result; public UpdateWebService() { ht = new HttpTransportSE(SERVICE_URL); // ① ht.debug = true; } public String getAppVersionVoice(String appName) { ht = new HttpTransportSE(SERVICE_URL); ht.debug = true; methodName = "getAppVersionVoice"; soapAction = SERVICE_NS + methodName;// 通常为命名空间 + 调用的方法名称 // 使用SOAP1.1协议创建Envelop对象 envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // ② // 实例化SoapObject对象 soapObject = new SoapObject(SERVICE_NS, methodName); // ③ // 将soapObject对象设置为 SoapSerializationEnvelope对象的传出SOAP消息 envelope.bodyOut = soapObject; // ⑤ envelope.dotNet = true; envelope.setOutputSoapObject(soapObject); soapObject.addProperty("appName", appName); try { // System.out.println("测试1"); ht.call(soapAction, envelope); // System.out.println("测试2"); // 根据测试发现,运行这行代码时有时会抛出空指针异常,使用加了一句进行处理 if (envelope != null && envelope.getResponse() != null) { // 获取服务器响应返回的SOAP消息 // System.out.println("测试3"); result = (SoapObject) envelope.bodyIn; // ⑦ // 接下来就是从SoapObject对象中解析响应数据的过程了 // System.out.println("测试4"); String flag = result.getProperty(0).toString(); Log.e(TAG, "*********Webservice masterReadElecticOrder 服务器返回值:" + flag); return flag; } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } finally { resetParam(); } return -1 + ""; } private void resetParam() { envelope = null; soapObject = null; result = null; } }
SummerBlack/MasterServer
app/src/main/java/com/lamost/update/UpdateWebService.java
Java
mit
2,678
<?php namespace gries\Pokemath\Numbers; use gries\Pokemath\PokeNumber; class Mienshao extends PokeNumber { public function __construct() { parent::__construct('mienshao'); } }
gries/pokemath
src/Numbers/Mienshao.php
PHP
mit
198
<?php /** * This file is automatically created by Recurly's OpenAPI generation process * and thus any edits you make by hand will be lost. If you wish to make a * change to this file, please create a Github issue explaining the changes you * need and we will usher them to the appropriate places. */ namespace Recurly\Resources; use Recurly\RecurlyResource; // phpcs:disable class ShippingMethodMini extends RecurlyResource { private $_code; private $_id; private $_name; private $_object; protected static $array_hints = [ ]; /** * Getter method for the code attribute. * The internal name used identify the shipping method. * * @return ?string */ public function getCode(): ?string { return $this->_code; } /** * Setter method for the code attribute. * * @param string $code * * @return void */ public function setCode(string $code): void { $this->_code = $code; } /** * Getter method for the id attribute. * Shipping Method ID * * @return ?string */ public function getId(): ?string { return $this->_id; } /** * Setter method for the id attribute. * * @param string $id * * @return void */ public function setId(string $id): void { $this->_id = $id; } /** * Getter method for the name attribute. * The name of the shipping method displayed to customers. * * @return ?string */ public function getName(): ?string { return $this->_name; } /** * Setter method for the name attribute. * * @param string $name * * @return void */ public function setName(string $name): void { $this->_name = $name; } /** * Getter method for the object attribute. * Object type * * @return ?string */ public function getObject(): ?string { return $this->_object; } /** * Setter method for the object attribute. * * @param string $object * * @return void */ public function setObject(string $object): void { $this->_object = $object; } }
recurly/recurly-client-php
lib/recurly/resources/shipping_method_mini.php
PHP
mit
2,229
class Client { constructor(http_client){ this.http_client = http_client this.method_list = [] } xyz() { return this.http_client } } function chainable_client () { HttpClient = require('./http_client.js') http_client = new HttpClient(arguments[0]) chainable_method = require('./chainable_method.js') return chainable_method(new Client(http_client), true) } module.exports = chainable_client
balous/nodejs-kerio-api
lib/kerio-api.js
JavaScript
mit
409
<?php /* * jQuery File Upload Plugin PHP Class 6.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ class UploadHandler { protected $options; // PHP File Upload error message codes: // http://php.net/manual/en/features.file-upload.errors.php protected $error_messages = array( 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk', 8 => 'A PHP extension stopped the file upload', 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini', 'max_file_size' => 'File is too big', 'min_file_size' => 'File is too small', 'accept_file_types' => 'Filetype not allowed', 'max_number_of_files' => 'Maximum number of files exceeded', 'max_width' => 'Image exceeds maximum width', 'min_width' => 'Image requires a minimum width', 'max_height' => 'Image exceeds maximum height', 'min_height' => 'Image requires a minimum height' ); function __construct($options = null, $initialize = true) { $this->options = array( 'script_url' => $this->get_full_url().'/', 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/', 'upload_url' => $this->get_full_url().'/files/', 'user_dirs' => false, 'mkdir_mode' => 0755, 'param_name' => 'files', // Set the following option to 'POST', if your server does not support // DELETE requests. This is a parameter sent to the client: 'delete_type' => 'DELETE', 'access_control_allow_origin' => '*', 'access_control_allow_credentials' => false, 'access_control_allow_methods' => array( 'OPTIONS', 'HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' ), 'access_control_allow_headers' => array( 'Content-Type', 'Content-Range', 'Content-Disposition' ), // Enable to provide file downloads via GET requests to the PHP script: 'download_via_php' => false, // Defines which files can be displayed inline when downloaded: 'inline_file_types' => '/\.(gif|jpe?g|png)$/i', // Defines which files (based on their names) are accepted for upload: 'accept_file_types' => '/.+$/i', // The php.ini settings upload_max_filesize and post_max_size // take precedence over the following max_file_size setting: 'max_file_size' => null, 'min_file_size' => 1, // The maximum number of files for the upload directory: 'max_number_of_files' => null, // Image resolution restrictions: 'max_width' => null, 'max_height' => null, 'min_width' => 1, 'min_height' => 1, // Set the following option to false to enable resumable uploads: 'discard_aborted_uploads' => true, // Set to true to rotate images based on EXIF meta data, if available: 'orient_image' => false, 'image_versions' => array( // Uncomment the following version to restrict the size of // uploaded images: /* '' => array( 'max_width' => 1920, 'max_height' => 1200, 'jpeg_quality' => 95 ), */ // Uncomment the following to create medium sized images: /* 'medium' => array( 'max_width' => 800, 'max_height' => 600, 'jpeg_quality' => 80 ), */ 'thumbnail' => array( 'max_width' => 80, 'max_height' => 80 ) ) ); if ($options) { $this->options = array_merge($this->options, $options); } if ($initialize) { $this->initialize(); } } protected function initialize() { switch ($_SERVER['REQUEST_METHOD']) { case 'OPTIONS': case 'HEAD': $this->head(); break; case 'GET': $this->get(); break; case 'PATCH': case 'PUT': case 'POST': $this->post(); break; case 'DELETE': $this->delete(); break; default: $this->header('HTTP/1.1 405 Method Not Allowed'); } } protected function get_full_url() { $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'; return ($https ? 'https://' : 'http://'). (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : ''). (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME']. ($https && $_SERVER['SERVER_PORT'] === 443 || $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))). substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/')); } protected function get_user_id() { @session_start(); return session_id(); } protected function get_user_path() { if ($this->options['user_dirs']) { return $this->get_user_id().'/'; } return ''; } protected function get_upload_path($file_name = null, $version = null) { $file_name = $file_name ? $file_name : ''; $version_path = empty($version) ? '' : $version.'/'; return $this->options['upload_dir'].$this->get_user_path() .$version_path.$file_name; } protected function get_query_separator($url) { return strpos($url, '?') === false ? '?' : '&'; } protected function get_download_url($file_name, $version = null) { if ($this->options['download_via_php']) { $url = $this->options['script_url'] .$this->get_query_separator($this->options['script_url']) .'file='.rawurlencode($file_name); if ($version) { $url .= '&version='.rawurlencode($version); } return $url.'&download=1'; } $version_path = empty($version) ? '' : rawurlencode($version).'/'; return $this->options['upload_url'].$this->get_user_path() .$version_path.rawurlencode($file_name); } protected function set_file_delete_properties($file) { $file->delete_url = $this->options['script_url'] .$this->get_query_separator($this->options['script_url']) .'file='.rawurlencode($file->name); $file->delete_type = $this->options['delete_type']; if ($file->delete_type !== 'DELETE') { $file->delete_url .= '&_method=DELETE'; } if ($this->options['access_control_allow_credentials']) { $file->delete_with_credentials = true; } } // Fix for overflowing signed 32 bit integers, // works for sizes up to 2^32-1 bytes (4 GiB - 1): protected function fix_integer_overflow($size) { if ($size < 0) { $size += 2.0 * (PHP_INT_MAX + 1); } return $size; } protected function get_file_size($file_path, $clear_stat_cache = false) { if ($clear_stat_cache) { clearstatcache(true, $file_path); } return $this->fix_integer_overflow(filesize($file_path)); } protected function is_valid_file_object($file_name) { $file_path = $this->get_upload_path($file_name); if (is_file($file_path) && $file_name[0] !== '.') { return true; } return false; } protected function get_file_object($file_name) { if ($this->is_valid_file_object($file_name)) { $file = new stdClass(); $file->name = $file_name; $file->size = $this->get_file_size( $this->get_upload_path($file_name) ); $file->url = $this->get_download_url($file->name); foreach($this->options['image_versions'] as $version => $options) { if (!empty($version)) { if (is_file($this->get_upload_path($file_name, $version))) { $file->{$version.'_url'} = $this->get_download_url( $file->name, $version ); } } } $this->set_file_delete_properties($file); return $file; } return null; } protected function get_file_objects($iteration_method = 'get_file_object') { $upload_dir = $this->get_upload_path(); if (!is_dir($upload_dir)) { return array(); } return array_values(array_filter(array_map( array($this, $iteration_method), scandir($upload_dir) ))); } protected function count_file_objects() { return count($this->get_file_objects('is_valid_file_object')); } protected function create_scaled_image($file_name, $version, $options) { $file_path = $this->get_upload_path($file_name); if (!empty($version)) { $version_dir = $this->get_upload_path(null, $version); if (!is_dir($version_dir)) { mkdir($version_dir, $this->options['mkdir_mode'], true); } $new_file_path = $version_dir.'/'.$file_name; } else { $new_file_path = $file_path; } list($img_width, $img_height) = @getimagesize($file_path); if (!$img_width || !$img_height) { return false; } $scale = min( $options['max_width'] / $img_width, $options['max_height'] / $img_height ); if ($scale >= 1) { if ($file_path !== $new_file_path) { return copy($file_path, $new_file_path); } return true; } $new_width = $img_width * $scale; $new_height = $img_height * $scale; $new_img = @imagecreatetruecolor($new_width, $new_height); switch (strtolower(substr(strrchr($file_name, '.'), 1))) { case 'jpg': case 'jpeg': $src_img = @imagecreatefromjpeg($file_path); $write_image = 'imagejpeg'; $image_quality = isset($options['jpeg_quality']) ? $options['jpeg_quality'] : 75; break; case 'gif': @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0)); $src_img = @imagecreatefromgif($file_path); $write_image = 'imagegif'; $image_quality = null; break; case 'png': @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0)); @imagealphablending($new_img, false); @imagesavealpha($new_img, true); $src_img = @imagecreatefrompng($file_path); $write_image = 'imagepng'; $image_quality = isset($options['png_quality']) ? $options['png_quality'] : 9; break; default: $src_img = null; } $success = $src_img && @imagecopyresampled( $new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height ) && $write_image($new_img, $new_file_path, $image_quality); // Free up memory (imagedestroy does not delete files): @imagedestroy($src_img); @imagedestroy($new_img); return $success; } protected function get_error_message($error) { return array_key_exists($error, $this->error_messages) ? $this->error_messages[$error] : $error; } function get_config_bytes($val) { $val = trim($val); $last = strtolower($val[strlen($val)-1]); switch($last) { case 'g': $val *= 1024; case 'm': $val *= 1024; case 'k': $val *= 1024; } return $this->fix_integer_overflow($val); } protected function validate($uploaded_file, $file, $error, $index) { if ($error) { $file->error = $this->get_error_message($error); return false; } $content_length = $this->fix_integer_overflow(intval($_SERVER['CONTENT_LENGTH'])); if ($content_length > $this->get_config_bytes(ini_get('post_max_size'))) { $file->error = $this->get_error_message('post_max_size'); return false; } if (!preg_match($this->options['accept_file_types'], $file->name)) { $file->error = $this->get_error_message('accept_file_types'); return false; } if ($uploaded_file && is_uploaded_file($uploaded_file)) { $file_size = $this->get_file_size($uploaded_file); } else { $file_size = $content_length; } if ($this->options['max_file_size'] && ( $file_size > $this->options['max_file_size'] || $file->size > $this->options['max_file_size']) ) { $file->error = $this->get_error_message('max_file_size'); return false; } if ($this->options['min_file_size'] && $file_size < $this->options['min_file_size']) { $file->error = $this->get_error_message('min_file_size'); return false; } if (is_int($this->options['max_number_of_files']) && ( $this->count_file_objects() >= $this->options['max_number_of_files']) ) { $file->error = $this->get_error_message('max_number_of_files'); return false; } list($img_width, $img_height) = @getimagesize($uploaded_file); if (is_int($img_width)) { if ($this->options['max_width'] && $img_width > $this->options['max_width']) { $file->error = $this->get_error_message('max_width'); return false; } if ($this->options['max_height'] && $img_height > $this->options['max_height']) { $file->error = $this->get_error_message('max_height'); return false; } if ($this->options['min_width'] && $img_width < $this->options['min_width']) { $file->error = $this->get_error_message('min_width'); return false; } if ($this->options['min_height'] && $img_height < $this->options['min_height']) { $file->error = $this->get_error_message('min_height'); return false; } } return true; } protected function upcount_name_callback($matches) { $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1; $ext = isset($matches[2]) ? $matches[2] : ''; return ' ('.$index.')'.$ext; } protected function upcount_name($name) { return preg_replace_callback( '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcount_name_callback'), $name, 1 ); } protected function get_unique_filename($name, $type, $index, $content_range) { while(is_dir($this->get_upload_path($name))) { $name = $this->upcount_name($name); } // Keep an existing filename if this is part of a chunked upload: $uploaded_bytes = $this->fix_integer_overflow(intval($content_range[1])); while(is_file($this->get_upload_path($name))) { if ($uploaded_bytes === $this->get_file_size( $this->get_upload_path($name))) { break; } $name = $this->upcount_name($name); } return $name; } protected function trim_file_name($name, $type, $index, $content_range) { // Remove path information and dots around the filename, to prevent uploading // into different directories or replacing hidden system files. // Also remove control characters and spaces (\x00..\x20) around the filename: $name = trim(basename(stripslashes($name)), ".\x00..\x20"); // Use a timestamp for empty filenames: if (!$name) { $name = str_replace('.', '-', microtime(true)); } // Add missing file extension for known image types: if (strpos($name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) { $name .= '.'.$matches[1]; } return $name; } protected function get_file_name($name, $type, $index, $content_range) { return $this->get_unique_filename( $this->trim_file_name($name, $type, $index, $content_range), $type, $index, $content_range ); } protected function handle_form_data($file, $index) { // Handle form data, e.g. $_REQUEST['description'][$index] } protected function orient_image($file_path) { if (!function_exists('exif_read_data')) { return false; } $exif = @exif_read_data($file_path); if ($exif === false) { return false; } $orientation = intval(@$exif['Orientation']); if (!in_array($orientation, array(3, 6, 8))) { return false; } $image = @imagecreatefromjpeg($file_path); switch ($orientation) { case 3: $image = @imagerotate($image, 180, 0); break; case 6: $image = @imagerotate($image, 270, 0); break; case 8: $image = @imagerotate($image, 90, 0); break; default: return false; } $success = imagejpeg($image, $file_path); // Free up memory (imagedestroy does not delete files): @imagedestroy($image); return $success; } protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) { $file = new stdClass(); $file->name = $this->get_file_name($name, $type, $index, $content_range); $file->size = $this->fix_integer_overflow(intval($size)); $file->type = $type; if ($this->validate($uploaded_file, $file, $error, $index)) { $this->handle_form_data($file, $index); $upload_dir = $this->get_upload_path(); if (!is_dir($upload_dir)) { mkdir($upload_dir, $this->options['mkdir_mode'], true); } $file_path = $this->get_upload_path($file->name); $append_file = $content_range && is_file($file_path) && $file->size > $this->get_file_size($file_path); if ($uploaded_file && is_uploaded_file($uploaded_file)) { // multipart/formdata uploads (POST method uploads) if ($append_file) { file_put_contents( $file_path, fopen($uploaded_file, 'r'), FILE_APPEND ); } else { move_uploaded_file($uploaded_file, $file_path); } } else { // Non-multipart uploads (PUT method support) file_put_contents( $file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0 ); } $file_size = $this->get_file_size($file_path, $append_file); if ($file_size === $file->size) { if ($this->options['orient_image']) { $this->orient_image($file_path); } $file->url = $this->get_download_url($file->name); foreach($this->options['image_versions'] as $version => $options) { if ($this->create_scaled_image($file->name, $version, $options)) { if (!empty($version)) { $file->{$version.'_url'} = $this->get_download_url( $file->name, $version ); } else { $file_size = $this->get_file_size($file_path, true); } } } } else if (!$content_range && $this->options['discard_aborted_uploads']) { unlink($file_path); $file->error = 'abort'; } $file->size = $file_size; $this->set_file_delete_properties($file); } return $file; } protected function readfile($file_path) { return readfile($file_path); } protected function body($str) { echo $str; } protected function header($str) { header($str); } protected function generate_response($content, $print_response = true) { if ($print_response) { $json = json_encode($content); $redirect = isset($_REQUEST['redirect']) ? stripslashes($_REQUEST['redirect']) : null; if ($redirect) { $this->header('Location: '.sprintf($redirect, rawurlencode($json))); return; } $this->head(); if (isset($_SERVER['HTTP_CONTENT_RANGE'])) { $files = isset($content[$this->options['param_name']]) ? $content[$this->options['param_name']] : null; if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) { $this->header('Range: 0-'.($this->fix_integer_overflow(intval($files[0]->size)) - 1)); } } $this->body($json); } return $content; } protected function get_version_param() { return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null; } protected function get_file_name_param() { return isset($_GET['file']) ? basename(stripslashes($_GET['file'])) : null; } protected function get_file_type($file_path) { switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) { case 'jpeg': case 'jpg': return 'image/jpeg'; case 'png': return 'image/png'; case 'gif': return 'image/gif'; default: return ''; } } protected function download() { if (!$this->options['download_via_php']) { $this->header('HTTP/1.1 403 Forbidden'); return; } $file_name = $this->get_file_name_param(); if ($this->is_valid_file_object($file_name)) { $file_path = $this->get_upload_path($file_name, $this->get_version_param()); if (is_file($file_path)) { if (!preg_match($this->options['inline_file_types'], $file_name)) { $this->header('Content-Description: File Transfer'); $this->header('Content-Type: application/octet-stream'); $this->header('Content-Disposition: attachment; filename="'.$file_name.'"'); $this->header('Content-Transfer-Encoding: binary'); } else { // Prevent Internet Explorer from MIME-sniffing the content-type: $this->header('X-Content-Type-Options: nosniff'); $this->header('Content-Type: '.$this->get_file_type($file_path)); $this->header('Content-Disposition: inline; filename="'.$file_name.'"'); } $this->header('Content-Length: '.$this->get_file_size($file_path)); $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path))); $this->readfile($file_path); } } } protected function send_content_type_header() { $this->header('Vary: Accept'); if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) { $this->header('Content-type: application/json'); } else { $this->header('Content-type: text/plain'); } } protected function send_access_control_headers() { $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']); $this->header('Access-Control-Allow-Credentials: ' .($this->options['access_control_allow_credentials'] ? 'true' : 'false')); $this->header('Access-Control-Allow-Methods: ' .implode(', ', $this->options['access_control_allow_methods'])); $this->header('Access-Control-Allow-Headers: ' .implode(', ', $this->options['access_control_allow_headers'])); } public function head() { $this->header('Pragma: no-cache'); $this->header('Cache-Control: no-store, no-cache, must-revalidate'); $this->header('Content-Disposition: inline; filename="files.json"'); // Prevent Internet Explorer from MIME-sniffing the content-type: $this->header('X-Content-Type-Options: nosniff'); if ($this->options['access_control_allow_origin']) { $this->send_access_control_headers(); } $this->send_content_type_header(); } public function get($print_response = true) { if ($print_response && isset($_GET['download'])) { return $this->download(); } $file_name = $this->get_file_name_param(); if ($file_name) { $response = array( substr($this->options['param_name'], 0, -1) => $this->get_file_object($file_name) ); } else { $response = array( $this->options['param_name'] => $this->get_file_objects() ); } return $this->generate_response($response, $print_response); } public function post($print_response = true) { if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') { return $this->delete($print_response); } $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null; // Parse the Content-Disposition header, if available: $file_name = isset($_SERVER['HTTP_CONTENT_DISPOSITION']) ? rawurldecode(preg_replace( '/(^[^"]+")|("$)/', '', $_SERVER['HTTP_CONTENT_DISPOSITION'] )) : null; // Parse the Content-Range header, which has the following form: // Content-Range: bytes 0-524287/2000000 $content_range = isset($_SERVER['HTTP_CONTENT_RANGE']) ? preg_split('/[^0-9]+/', $_SERVER['HTTP_CONTENT_RANGE']) : null; $size = $content_range ? $content_range[3] : null; $files = array(); if ($upload && is_array($upload['tmp_name'])) { // param_name is an array identifier like "files[]", // $_FILES is a multi-dimensional array: foreach ($upload['tmp_name'] as $index => $value) { $files[] = $this->handle_file_upload( $upload['tmp_name'][$index], $file_name ? $file_name : $upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $index, $content_range ); } } else { // param_name is a single object identifier like "file", // $_FILES is a one-dimensional array: $files[] = $this->handle_file_upload( isset($upload['tmp_name']) ? $upload['tmp_name'] : null, $file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ? $size : (isset($upload['size']) ? $upload['size'] : $_SERVER['CONTENT_LENGTH']), isset($upload['type']) ? $upload['type'] : $_SERVER['CONTENT_TYPE'], isset($upload['error']) ? $upload['error'] : null, null, $content_range ); } return $this->generate_response( array($this->options['param_name'] => $files), $print_response ); } public function delete($print_response = true) { $file_name = $this->get_file_name_param(); $file_path = $this->get_upload_path($file_name); $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path); if ($success) { foreach($this->options['image_versions'] as $version => $options) { if (!empty($version)) { $file = $this->get_upload_path($file_name, $version); if (is_file($file)) { unlink($file); } } } } return $this->generate_response(array('success' => $success), $print_response); } }
bakercp/ofxIpVideoServer
example/bin/data/jQuery-File-Upload-master/server/php/UploadHandler.php
PHP
mit
30,399
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var RegService = (function () { function RegService(_http) { this._http = _http; } RegService.prototype.ngOnInit = function () { }; RegService.prototype.getUsers = function () { return this._http.get('http://ankitesh.pythonanywhere.com/api/v1.0/get_books_data') .map(function (response) { return response.json(); }); }; RegService.prototype.regUser = function (User) { var payload = JSON.stringify({ payload: { "Username": User.Username, "Email_id": User.Email_id, "Password": User.Password } }); return this._http.post('http://ankitesh.pythonanywhere.com/api/v1.0/get_book_summary', payload) .map(function (response) { return response.json(); }); }; return RegService; }()); RegService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], RegService); exports.RegService = RegService; //# sourceMappingURL=register.service.js.map
AkshayRaul/MEAN_ToDo
public/app/services/register/register.service.js
JavaScript
mit
1,804
require File.expand_path('../../spec_helper', __FILE__) module Pod describe Command::Search do extend SpecHelper::TemporaryRepos describe 'Search' do it 'registers it self' do Command.parse(%w{ search }).should.be.instance_of Command::Search end it 'runs with correct parameters' do lambda { run_command('search', 'JSON') }.should.not.raise lambda { run_command('search', 'JSON', '--simple') }.should.not.raise end it 'complains for wrong parameters' do lambda { run_command('search') }.should.raise CLAide::Help lambda { run_command('search', 'too', '--wrong') }.should.raise CLAide::Help lambda { run_command('search', '--wrong') }.should.raise CLAide::Help end it 'searches for a pod with name matching the given query ignoring case' do output = run_command('search', 'json', '--simple') output.should.include? 'JSONKit' end it 'searches for a pod with name, summary, or description matching the given query ignoring case' do output = run_command('search', 'engelhart') output.should.include? 'JSONKit' end it 'searches for a pod with name, summary, or description matching the given multi-word query ignoring case' do output = run_command('search', 'very', 'high', 'performance') output.should.include? 'JSONKit' end it 'prints search results in order' do output = run_command('search', 'lib') output.should.match /BananaLib.*JSONKit/m end it 'restricts the search to Pods supported on iOS' do output = run_command('search', 'BananaLib', '--ios') output.should.include? 'BananaLib' Specification.any_instance.stubs(:available_platforms).returns([Platform.osx]) output = run_command('search', 'BananaLib', '--ios') output.should.not.include? 'BananaLib' end it 'restricts the search to Pods supported on OS X' do output = run_command('search', 'BananaLib', '--osx') output.should.not.include? 'BananaLib' end it 'restricts the search to Pods supported on Watch OS' do output = run_command('search', 'a', '--watchos') output.should.include? 'Realm' output.should.not.include? 'BananaLib' end it 'restricts the search to Pods supported on tvOS' do output = run_command('search', 'n', '--tvos') output.should.include? 'monkey' output.should.not.include? 'BananaLib' end it 'outputs with the silent parameter' do output = run_command('search', 'BananaLib', '--silent') output.should.include? 'BananaLib' end it 'shows a friendly message when locally searching with invalid regex' do lambda { run_command('search', '--regex', '+') }.should.raise CLAide::Help end it 'does not try to validate the query as a regex with plain-text search' do lambda { run_command('search', '+') }.should.not.raise CLAide::Help end it 'uses regex search when asked for regex mode' do output = run_command('search', '--regex', 'Ba(na)+Lib') output.should.include? 'BananaLib' output.should.not.include? 'Pod+With+Plus+Signs' output.should.not.include? 'JSONKit' end it 'uses plain-text search when not asked for regex mode' do output = run_command('search', 'Pod+With+Plus+Signs') output.should.include? 'Pod+With+Plus+Signs' output.should.not.include? 'BananaLib' end end describe 'option --web' do extend SpecHelper::TemporaryRepos it 'searches with invalid regex' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=NSAttributedString%2BCCLFormat']) run_command('search', '--web', 'NSAttributedString+CCLFormat') end it 'should url encode search queries' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=NSAttributedString%2BCCLFormat']) run_command('search', '--web', 'NSAttributedString+CCLFormat') end it 'searches the web via the open! command' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=bananalib']) run_command('search', '--web', 'bananalib') end it 'includes option --osx correctly' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Aosx%20bananalib']) run_command('search', '--web', '--osx', 'bananalib') end it 'includes option --ios correctly' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Aios%20bananalib']) run_command('search', '--web', '--ios', 'bananalib') end it 'includes option --watchos correctly' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Awatchos%20bananalib']) run_command('search', '--web', '--watchos', 'bananalib') end it 'includes option --tvos correctly' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Atvos%20bananalib']) run_command('search', '--web', '--tvos', 'bananalib') end it 'includes any new platform option correctly' do Platform.stubs(:all).returns([Platform.ios, Platform.tvos, Platform.new('whateveros')]) Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Awhateveros%20bananalib']) run_command('search', '--web', '--whateveros', 'bananalib') end it 'does not matter in which order the ios/osx options are set' do Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Aios%20on%3Aosx%20bananalib']) run_command('search', '--web', '--ios', '--osx', 'bananalib') Executable.expects(:execute_command).with(:open, ['https://cocoapods.org/?q=on%3Aios%20on%3Aosx%20bananalib']) run_command('search', '--web', '--osx', '--ios', 'bananalib') end end end end
CocoaPods/cocoapods-search
spec/command/search_spec.rb
Ruby
mit
6,098
package cn.winxo.gank.module.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import cn.winxo.gank.R; import cn.winxo.gank.adapter.DetailTitleBinder; import cn.winxo.gank.adapter.DetailViewBinder; import cn.winxo.gank.base.BaseMvpActivity; import cn.winxo.gank.data.Injection; import cn.winxo.gank.data.entity.constants.Constant; import cn.winxo.gank.data.entity.remote.GankData; import cn.winxo.gank.module.contract.DetailContract; import cn.winxo.gank.module.presenter.DetailPresenter; import cn.winxo.gank.util.Toasts; import java.text.SimpleDateFormat; import java.util.Locale; import me.drakeet.multitype.Items; import me.drakeet.multitype.MultiTypeAdapter; public class DetailActivity extends BaseMvpActivity<DetailContract.Presenter> implements DetailContract.View { protected Toolbar mToolbar; protected RecyclerView mRecycler; protected SwipeRefreshLayout mSwipeLayout; private long mDate; private MultiTypeAdapter mTypeAdapter; @Override protected int setLayoutResourceID() { return R.layout.activity_detail; } @Override protected void init(Bundle savedInstanceState) { super.init(savedInstanceState); mDate = getIntent().getLongExtra(Constant.ExtraKey.DATE, -1); } @Override protected void initView() { mToolbar = findViewById(R.id.toolbar); mRecycler = findViewById(R.id.recycler); mSwipeLayout = findViewById(R.id.swipe_layout); mToolbar.setNavigationOnClickListener(view -> finish()); mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); mRecycler.setLayoutManager(new LinearLayoutManager(this)); mTypeAdapter = new MultiTypeAdapter(); mTypeAdapter.register(String.class, new DetailTitleBinder()); DetailViewBinder detailViewBinder = new DetailViewBinder(); detailViewBinder.setOnItemTouchListener((v, gankData) -> { Intent intent = new Intent(); intent.setClass(DetailActivity.this, WebActivity.class); intent.putExtra("url", gankData.getUrl()); intent.putExtra("name", gankData.getDesc()); startActivity(intent); }); mTypeAdapter.register(GankData.class, detailViewBinder); mRecycler.setAdapter(mTypeAdapter); mSwipeLayout.setOnRefreshListener(() -> mPresenter.refreshDayGank(mDate)); } @Override protected void initData() { if (mDate != -1) { String dateShow = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(mDate); mToolbar.setTitle(dateShow); mSwipeLayout.setRefreshing(true); mPresenter.loadDayGank(mDate); } else { finish(); } } @Override protected DetailPresenter onLoadPresenter() { return new DetailPresenter(this, Injection.provideGankDataSource(this)); } @Override public void showLoading() { mSwipeLayout.setRefreshing(true); } @Override public void hideLoading() { mSwipeLayout.setRefreshing(false); } @Override public void loadSuccess(Items items) { hideLoading(); mTypeAdapter.setItems(items); mTypeAdapter.notifyDataSetChanged(); } @Override public void loadFail(String message) { Toasts.showShort("数据加载失败,请稍后再试"); Log.e("DetailActivity", "loadFail: " + message); } }
yunxu-it/GMeizi
app/src/main/java/cn/winxo/gank/module/view/DetailActivity.java
Java
mit
3,411
<?php /* UserFrosting Version: 0.2.2 By Alex Weissman Copyright (c) 2014 Based on the UserCake user management system, v2.0.2. Copyright (c) 2009-2012 UserFrosting, like UserCake, is 100% free and open-source. 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. */ /********************************* * Formatting Functions *********************************/ /** * Converts phone numbers to the formatting standard * * @param String $num A unformatted phone number * @return String Returns the formatted phone number */ function formatPhone($num) { $num = preg_replace('/[^0-9]/', '', $num); $len = strlen($num); if($len == 7) $num = preg_replace('/([0-9]{3})([0-9]{4})/', '$1-$2', $num); elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', '($1) $2-$3', $num); return $num; } function formatCurrency($num){ if ($num === "") return ""; else return number_format($num, 2); } function formatDateComponents($stamp) { $formatted = []; $formatted['date'] = date("M jS, Y", $stamp); $formatted['day'] = date("l", $stamp); $formatted['time'] = date("g:i a", $stamp); return $formatted; } function formatSignInDate($stamp){ $stamp = intval($stamp); if ($stamp == '0'){ return "Brand new!"; } else { $datetime = new DateTime(); $datetime->setTimestamp($stamp); return $datetime->format('l, F j Y'); } } // Filter out all non-digits from a string function filterNonDigits($num){ return preg_replace("/[^0-9]/", "", $num); } // Convert text that might be in a different case or with trailing/leading whitespace to a standard form function str_normalize($str) { return strtolower(trim($str)); } // Parse a comment block into a description and array of parameters function parseCommentBlock($comment){ $lines = explode("\n", $comment); $result = array('description' => "", 'parameters' => array()); foreach ($lines as $line){ if (!preg_match('/^\s*\/?\*+\/?\s*$/', $line)){ // Extract description or parameters if (preg_match('/^\s*\**\s*@param\s+(\w+)\s+\$(\w+)\s+(.*)$/', $line, $matches)){ $type = $matches[1]; $name = $matches[2]; $description = $matches[3]; $result['parameters'][$name] = array('type' => $type, 'description' => $description); } else if (preg_match('/^\s*\**\s*@(.*)$/', $line, $matches)){ // Skip other types of special entities } else if (preg_match('/^\s*\**\s*(.*)$/', $line, $matches)){ $description = $matches[1]; $result['description'] .= $description; } } } return $result; } // Useful for testing output of API functions function prettyPrint( $json ) { $result = ''; $level = 0; $in_quotes = false; $in_escape = false; $ends_line_level = NULL; $json_length = strlen( $json ); for( $i = 0; $i < $json_length; $i++ ) { $char = $json[$i]; $new_line_level = NULL; $post = ""; if( $ends_line_level !== NULL ) { $new_line_level = $ends_line_level; $ends_line_level = NULL; } if ( $in_escape ) { $in_escape = false; } else if( $char === '"' ) { $in_quotes = !$in_quotes; } else if( ! $in_quotes ) { switch( $char ) { case '}': case ']': $level--; $ends_line_level = NULL; $new_line_level = $level; break; case '{': case '[': $level++; case ',': $ends_line_level = $level; break; case ':': $post = " "; break; case " ": case "\t": case "\n": case "\r": $char = ""; $ends_line_level = $new_line_level; $new_line_level = NULL; break; } } else if ( $char === '\\' ) { $in_escape = true; } if( $new_line_level !== NULL ) { $result .= "\n".str_repeat( "\t", $new_line_level ); } $result .= $char.$post; } return $result; } /********************************* * Language Functions *********************************/ //Retrieve a list of all .php files in models/languages function getLanguageFiles() { $directory = "../models/languages/"; $languages = glob($directory . "*.php"); //print each file name return $languages; } //Inputs language strings from selected language. function lang($key,$markers = NULL) { global $lang; if($markers == NULL) { $str = $lang[$key]; } else { //Replace any dyamic markers $str = $lang[$key]; $iteration = 1; foreach($markers as $marker) { $str = str_replace("%m".$iteration."%",$marker,$str); $iteration++; } } //Ensure we have something to return if($str == "") { return ("No language key=$key found (markers=$markers)"); } else { return $str; } } function getCurrentLanguage($language){ $ex_l = explode('/', $language); $ex_l_2 = explode('.', $ex_l[2]); return $ex_l_2[0]; } /********************************* * Security Functions *********************************/ //Retrieve a list of all .php files in a given directory function getPageFiles($directory) { $pages = glob("../" . $directory . "/*.php"); $row = array(); //print each file name foreach ($pages as $page){ $page_with_path = $directory . "/" . basename($page); $row[$page_with_path] = $page_with_path; } return $row; } //Destroys a session as part of logout function destroySession($name) { if(isset($_SESSION[$name])) { $_SESSION[$name] = NULL; unset($_SESSION[$name]); } } //Generate a unique code function getUniqueCode($length = "") { $code = md5(uniqid(rand(), true)); if ($length != "") return substr($code, 0, $length); else return $code; } //Generate an activation key function generateActivationToken($gen = null) { do { $gen = md5(uniqid(mt_rand(), false)); } while(validateActivationToken($gen)); return $gen; } // Master function for validating passwords. Ensures backwards compatibility with sha1 (usercake) and the old homegrown implementation of crypt function passwordVerifyUF($password, $hash){ if (getPasswordHashTypeUF($hash) == "sha1"){ $salt = substr($hash, 0, 25); // Extract the salt from the hash $hash_input = $salt . sha1($salt . $password); if ($hash_input == $hash){ return true; } else { return false; } } // Homegrown implementation (assuming that current install has been using a cost parameter of 12) else if (getPasswordHashTypeUF($hash) == "homegrown"){ /*used for manual implementation of bcrypt*/ $cost = '12'; if (substr($hash, 0, 60) == crypt($password, "$2y$".$cost."$".substr($hash, 60))){ return true; } else { return false; } // Modern implementation } else { return password_verify($password, $hash); } } // Hash a new password. Uses the modern implementation. function passwordHashUF($password){ return password_hash($password, PASSWORD_BCRYPT); } function getPasswordHashTypeUF($hash){ // If the password in the db is 65 characters long, we have an sha1-hashed password. if (strlen($hash) == 65) return "sha1"; else if (substr($hash, 0, 7) == "$2y$12$") return "homegrown"; else return "modern"; } //multipurpose security function. works on strings, array's etc. function security($value) { if(is_array($value)) { $value = array_map('security', $value); } else { if(!get_magic_quotes_gpc()) { $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); } else { $value = htmlspecialchars(stripslashes($value), ENT_QUOTES, 'UTF-8'); } $value = str_replace("\\", "\\\\", $value); } return $value; } //get ip address //taken from https://gist.github.com/cballou/2201933 function get_ip_address() { $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'); foreach ($ip_keys as $key) { if (array_key_exists($key, $_SERVER) === true) { foreach (explode(',', $_SERVER[$key]) as $ip) { $ip = trim($ip); if (validate_ip($ip)) { return $ip; } } } } return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false; } //validate ip address function validate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { return false; } return true; } //getuseragent //taken from comments @ php.net function getBrowser() { $u_agent = $_SERVER['HTTP_USER_AGENT']; $bname = 'Unknown'; $platform = 'Unknown'; $version= ""; if (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; } elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) { $bname = 'Internet Explorer'; $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $bname = 'Mozilla Firefox'; $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $bname = 'Google Chrome'; $ub = "Chrome"; } elseif(preg_match('/Safari/i',$u_agent)) { $bname = 'Apple Safari'; $ub = "Safari"; } elseif(preg_match('/Opera/i',$u_agent)) { $bname = 'Opera'; $ub = "Opera"; } elseif(preg_match('/Netscape/i',$u_agent)) { $bname = 'Netscape'; $ub = "Netscape"; } $known = array('Version', $ub, 'other'); $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { //no match } $i = count($matches['browser']); if ($i != 1) { if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){ $version= $matches['version'][0];}else{ $version= $matches['version'][1];} } else { $version= $matches['version'][0];} if ($version==null || $version=="") {$version="?";} return array( 'userAgent' => $u_agent, 'name' => $bname, 'version' => $version, 'platform' => $platform, 'pattern' => $pattern ); } //to be used with csrf token system /* simply add inside of a form tag like so: form_protect($loggedInUser->csrf_token); then in the processing script: require_once __DIR__ . '/models/post.php'; < OR > require_once 'models/post.php'; */ function form_protect($token) { if(isUserLoggedIn()) {echo '<input type="hidden" name="csrf_token" value="'. $token .'">';} } // Check that request is made by a logged in user. Immediately fail if not. function checkLoggedInUser($ajax){ if (!isUserLoggedIn()){ addAlert("danger", lang("LOGIN_REQUIRED")); apiReturnError($ajax, getReferralPage()); } } // Check that a CSRF token is specified and valid. function checkCSRF($ajax, $csrf_token){ global $loggedInUser; if ($csrf_token) { if (!$loggedInUser->csrf_validate(trim($csrf_token))){ addAlert("danger", lang("ACCESS_DENIED")); if (LOG_AUTH_FAILURES) error_log("CSRF token failure - invalid token."); apiReturnError($ajax, $failure_landing_page); } } else { addAlert("danger", lang("ACCESS_DENIED")); if (LOG_AUTH_FAILURES) error_log("CSRF token failure - token not specified."); apiReturnError($ajax, $failure_landing_page); } } /********************************* * Validation Functions. TODO: Switch over to Valitron. *********************************/ //Checks if an email is valid function isValidEmail($email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { return true; } else { return false; } } function isValidName($name) { return preg_match('/^[A-Za-z0-9 ]+$/', $name); } //Checks if a string is within a min and max length function minMaxRange($min, $max, $what) { if(strlen(trim($what)) < $min) return true; else if(strlen(trim($what)) > $max) return true; else return false; } /********************************* * Miscellaneous Functions *********************************/ /** * array_merge_recursive does indeed merge arrays, but it converts values with duplicate * keys to arrays rather than overwriting the value in the first array with the duplicate * value in the second array, as array_merge does. I.e., with array_merge_recursive, * this happens (documented behavior): * * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value')); * => array('key' => array('org value', 'new value')); * * array_merge_recursive_distinct does not change the datatypes of the values in the arrays. * Matching keys' values in the second array overwrite those in the first array, as is the * case with array_merge, i.e.: * * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value')); * => array('key' => array('new value')); * * Parameters are passed by reference, though only for performance reasons. They're not * altered by this function. * * @param array $array1 * @param array $array2 * @return array * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk> * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com> */ function array_merge_recursive_distinct ( array &$array1, array &$array2 ) { $merged = $array1; foreach ( $array2 as $key => &$value ) { if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) ) { $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value ); } else { $merged [$key] = $value; } } return $merged; } function generateCaptcha(){ /* generates a base 64 string to be placed inside the src attribute of an html image tag. @blame -r3wt */ $md5_hash = md5(rand(0,99999)); $security_code = substr($md5_hash, 25, 5); $enc = md5($security_code); $_SESSION['captcha'] = $enc; $width = 150; $height = 30; $image = imagecreatetruecolor(150, 30); //color pallette $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0); $red = imagecolorallocate($image,255,0,0); $yellow = imagecolorallocate($image, 255, 255, 0); $dark_grey = imagecolorallocate($image, 64,64,64); $blue = imagecolorallocate($image, 0,0,255); //create white rectangle imagefilledrectangle($image,0,0,150,30,$white); //add some lines for($i=0;$i<2;$i++) { imageline($image,0,rand()%10,10,rand()%30,$dark_grey); imageline($image,0,rand()%30,150,rand()%30,$red); imageline($image,0,rand()%30,150,rand()%30,$yellow); } // RandTab color pallette $randc[0] = imagecolorallocate($image, 0, 0, 0); $randc[1] = imagecolorallocate($image,255,0,0); $randc[2] = imagecolorallocate($image, 255, 255, 0); $randc[3] = imagecolorallocate($image, 64,64,64); $randc[4] = imagecolorallocate($image, 0,0,255); //add some dots for($i=0;$i<1000;$i++) { imagesetpixel($image,rand()%200,rand()%50,$randc[rand()%5]); } //calculate center of text $x = ( 150 - 0 - imagefontwidth( 5 ) * strlen( $security_code ) ) / 2 + 0 + 5; //write string twice ImageString($image,5, $x, 7, $security_code, $black); ImageString($image,5, $x, 7, $security_code, $black); //start ob ob_start(); ImagePng($image); //get binary image data $data = ob_get_clean(); //return base64 return 'data:image/png;base64,'.chunk_split(base64_encode($data)); //return the base64 encoded image. } function checkUpgrade($version, $dev_env){ if(is_dir("upgrade/") && $dev_env != TRUE) { // Grab up the current changes from the master repo so that we can update (cache them to file if able to otherwise move on) $versions = file_get_contents('upgrade/versions.txt'); // Grab all versions from the update url and push the values to a array $versionList = explode("\n", $versions); // Remove new lines and carriage returns from the array $versionList = str_replace(array("\n", "\r"), '', $versionList); // Search the array to find out where the currently installed version falls $nV = array_search($version, $versionList); // Find out if the update is in the list or not $newVersion = isset($versionList[$nV - 1]); // Find out if we need to do the update or not based on the version information // If update is found then forward to the installer to run the script else exit if($newVersion != NULL) { header('Location: upgrade/'); die(); } } }
AmazinGears/CoinC
models/funcs.php
PHP
mit
18,102
package br.com.swconsultoria.nfe.schema.retEnvEpec; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * Tipo Evento * * <p>Classe Java de TEvento complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="TEvento"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="infEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/> * &lt;element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;/choice> * &lt;element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/> * &lt;element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/> * &lt;element name="tpEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[0-9]{6}"/> * &lt;enumeration value="110140"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="nSeqEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[1-9]|[1][0-9]{0,1}|20"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="verEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="detEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Id" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}ID"> * &lt;pattern value="ID[0-9]{52}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}Signature"/> * &lt;/sequence> * &lt;attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEvento" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = { "infEvento", "signature" }) public class TEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento infEvento; @XmlElement(name = "Signature", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected SignatureType signature; @XmlAttribute(name = "versao", required = true) protected String versao; /** * Obtm o valor da propriedade infEvento. * * @return possible object is * {@link TEvento.InfEvento } */ public TEvento.InfEvento getInfEvento() { return infEvento; } /** * Define o valor da propriedade infEvento. * * @param value allowed object is * {@link TEvento.InfEvento } */ public void setInfEvento(TEvento.InfEvento value) { this.infEvento = value; } /** * Obtm o valor da propriedade signature. * * @return possible object is * {@link SignatureType } */ public SignatureType getSignature() { return signature; } /** * Define o valor da propriedade signature. * * @param value allowed object is * {@link SignatureType } */ public void setSignature(SignatureType value) { this.signature = value; } /** * Obtm o valor da propriedade versao. * * @return possible object is * {@link String } */ public String getVersao() { return versao; } /** * Define o valor da propriedade versao. * * @param value allowed object is * {@link String } */ public void setVersao(String value) { this.versao = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/> * &lt;element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;/choice> * &lt;element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/> * &lt;element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/> * &lt;element name="tpEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[0-9]{6}"/> * &lt;enumeration value="110140"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="nSeqEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[1-9]|[1][0-9]{0,1}|20"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="verEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="detEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Id" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}ID"> * &lt;pattern value="ID[0-9]{52}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "cOrgao", "tpAmb", "cnpj", "cpf", "chNFe", "dhEvento", "tpEvento", "nSeqEvento", "verEvento", "detEvento" }) public static class InfEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String cOrgao; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpAmb; @XmlElement(name = "CNPJ", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cnpj; @XmlElement(name = "CPF", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cpf; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String chNFe; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String dhEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String nSeqEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String verEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento.DetEvento detEvento; @XmlAttribute(name = "Id", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; /** * Obtm o valor da propriedade cOrgao. * * @return possible object is * {@link String } */ public String getCOrgao() { return cOrgao; } /** * Define o valor da propriedade cOrgao. * * @param value allowed object is * {@link String } */ public void setCOrgao(String value) { this.cOrgao = value; } /** * Obtm o valor da propriedade tpAmb. * * @return possible object is * {@link String } */ public String getTpAmb() { return tpAmb; } /** * Define o valor da propriedade tpAmb. * * @param value allowed object is * {@link String } */ public void setTpAmb(String value) { this.tpAmb = value; } /** * Obtm o valor da propriedade cnpj. * * @return possible object is * {@link String } */ public String getCNPJ() { return cnpj; } /** * Define o valor da propriedade cnpj. * * @param value allowed object is * {@link String } */ public void setCNPJ(String value) { this.cnpj = value; } /** * Obtm o valor da propriedade cpf. * * @return possible object is * {@link String } */ public String getCPF() { return cpf; } /** * Define o valor da propriedade cpf. * * @param value allowed object is * {@link String } */ public void setCPF(String value) { this.cpf = value; } /** * Obtm o valor da propriedade chNFe. * * @return possible object is * {@link String } */ public String getChNFe() { return chNFe; } /** * Define o valor da propriedade chNFe. * * @param value allowed object is * {@link String } */ public void setChNFe(String value) { this.chNFe = value; } /** * Obtm o valor da propriedade dhEvento. * * @return possible object is * {@link String } */ public String getDhEvento() { return dhEvento; } /** * Define o valor da propriedade dhEvento. * * @param value allowed object is * {@link String } */ public void setDhEvento(String value) { this.dhEvento = value; } /** * Obtm o valor da propriedade tpEvento. * * @return possible object is * {@link String } */ public String getTpEvento() { return tpEvento; } /** * Define o valor da propriedade tpEvento. * * @param value allowed object is * {@link String } */ public void setTpEvento(String value) { this.tpEvento = value; } /** * Obtm o valor da propriedade nSeqEvento. * * @return possible object is * {@link String } */ public String getNSeqEvento() { return nSeqEvento; } /** * Define o valor da propriedade nSeqEvento. * * @param value allowed object is * {@link String } */ public void setNSeqEvento(String value) { this.nSeqEvento = value; } /** * Obtm o valor da propriedade verEvento. * * @return possible object is * {@link String } */ public String getVerEvento() { return verEvento; } /** * Define o valor da propriedade verEvento. * * @param value allowed object is * {@link String } */ public void setVerEvento(String value) { this.verEvento = value; } /** * Obtm o valor da propriedade detEvento. * * @return possible object is * {@link TEvento.InfEvento.DetEvento } */ public TEvento.InfEvento.DetEvento getDetEvento() { return detEvento; } /** * Define o valor da propriedade detEvento. * * @param value allowed object is * {@link TEvento.InfEvento.DetEvento } */ public void setDetEvento(TEvento.InfEvento.DetEvento value) { this.detEvento = value; } /** * Obtm o valor da propriedade id. * * @return possible object is * {@link String } */ public String getId() { return id; } /** * Define o valor da propriedade id. * * @param value allowed object is * {@link String } */ public void setId(String value) { this.id = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "descEvento", "cOrgaoAutor", "tpAutor", "verAplic", "dhEmi", "tpNF", "ie", "dest" }) public static class DetEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String descEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String cOrgaoAutor; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpAutor; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String verAplic; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String dhEmi; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpNF; @XmlElement(name = "IE", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String ie; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento.DetEvento.Dest dest; @XmlAttribute(name = "versao", required = true) protected String versao; /** * Obtm o valor da propriedade descEvento. * * @return possible object is * {@link String } */ public String getDescEvento() { return descEvento; } /** * Define o valor da propriedade descEvento. * * @param value allowed object is * {@link String } */ public void setDescEvento(String value) { this.descEvento = value; } /** * Obtm o valor da propriedade cOrgaoAutor. * * @return possible object is * {@link String } */ public String getCOrgaoAutor() { return cOrgaoAutor; } /** * Define o valor da propriedade cOrgaoAutor. * * @param value allowed object is * {@link String } */ public void setCOrgaoAutor(String value) { this.cOrgaoAutor = value; } /** * Obtm o valor da propriedade tpAutor. * * @return possible object is * {@link String } */ public String getTpAutor() { return tpAutor; } /** * Define o valor da propriedade tpAutor. * * @param value allowed object is * {@link String } */ public void setTpAutor(String value) { this.tpAutor = value; } /** * Obtm o valor da propriedade verAplic. * * @return possible object is * {@link String } */ public String getVerAplic() { return verAplic; } /** * Define o valor da propriedade verAplic. * * @param value allowed object is * {@link String } */ public void setVerAplic(String value) { this.verAplic = value; } /** * Obtm o valor da propriedade dhEmi. * * @return possible object is * {@link String } */ public String getDhEmi() { return dhEmi; } /** * Define o valor da propriedade dhEmi. * * @param value allowed object is * {@link String } */ public void setDhEmi(String value) { this.dhEmi = value; } /** * Obtm o valor da propriedade tpNF. * * @return possible object is * {@link String } */ public String getTpNF() { return tpNF; } /** * Define o valor da propriedade tpNF. * * @param value allowed object is * {@link String } */ public void setTpNF(String value) { this.tpNF = value; } /** * Obtm o valor da propriedade ie. * * @return possible object is * {@link String } */ public String getIE() { return ie; } /** * Define o valor da propriedade ie. * * @param value allowed object is * {@link String } */ public void setIE(String value) { this.ie = value; } /** * Obtm o valor da propriedade dest. * * @return possible object is * {@link TEvento.InfEvento.DetEvento.Dest } */ public TEvento.InfEvento.DetEvento.Dest getDest() { return dest; } /** * Define o valor da propriedade dest. * * @param value allowed object is * {@link TEvento.InfEvento.DetEvento.Dest } */ public void setDest(TEvento.InfEvento.DetEvento.Dest value) { this.dest = value; } /** * Obtm o valor da propriedade versao. * * @return possible object is * {@link String } */ public String getVersao() { return versao; } /** * Define o valor da propriedade versao. * * @param value allowed object is * {@link String } */ public void setVersao(String value) { this.versao = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "uf", "cnpj", "cpf", "idEstrangeiro", "ie", "vnf", "vicms", "vst" }) public static class Dest { @XmlElement(name = "UF", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) @XmlSchemaType(name = "string") protected TUf uf; @XmlElement(name = "CNPJ", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cnpj; @XmlElement(name = "CPF", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cpf; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe") protected String idEstrangeiro; @XmlElement(name = "IE", namespace = "http://www.portalfiscal.inf.br/nfe") protected String ie; @XmlElement(name = "vNF", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vnf; @XmlElement(name = "vICMS", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vicms; @XmlElement(name = "vST", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vst; /** * Obtm o valor da propriedade uf. * * @return possible object is * {@link TUf } */ public TUf getUF() { return uf; } /** * Define o valor da propriedade uf. * * @param value allowed object is * {@link TUf } */ public void setUF(TUf value) { this.uf = value; } /** * Obtm o valor da propriedade cnpj. * * @return possible object is * {@link String } */ public String getCNPJ() { return cnpj; } /** * Define o valor da propriedade cnpj. * * @param value allowed object is * {@link String } */ public void setCNPJ(String value) { this.cnpj = value; } /** * Obtm o valor da propriedade cpf. * * @return possible object is * {@link String } */ public String getCPF() { return cpf; } /** * Define o valor da propriedade cpf. * * @param value allowed object is * {@link String } */ public void setCPF(String value) { this.cpf = value; } /** * Obtm o valor da propriedade idEstrangeiro. * * @return possible object is * {@link String } */ public String getIdEstrangeiro() { return idEstrangeiro; } /** * Define o valor da propriedade idEstrangeiro. * * @param value allowed object is * {@link String } */ public void setIdEstrangeiro(String value) { this.idEstrangeiro = value; } /** * Obtm o valor da propriedade ie. * * @return possible object is * {@link String } */ public String getIE() { return ie; } /** * Define o valor da propriedade ie. * * @param value allowed object is * {@link String } */ public void setIE(String value) { this.ie = value; } /** * Obtm o valor da propriedade vnf. * * @return possible object is * {@link String } */ public String getVNF() { return vnf; } /** * Define o valor da propriedade vnf. * * @param value allowed object is * {@link String } */ public void setVNF(String value) { this.vnf = value; } /** * Obtm o valor da propriedade vicms. * * @return possible object is * {@link String } */ public String getVICMS() { return vicms; } /** * Define o valor da propriedade vicms. * * @param value allowed object is * {@link String } */ public void setVICMS(String value) { this.vicms = value; } /** * Obtm o valor da propriedade vst. * * @return possible object is * {@link String } */ public String getVST() { return vst; } /** * Define o valor da propriedade vst. * * @param value allowed object is * {@link String } */ public void setVST(String value) { this.vst = value; } } } } }
Samuel-Oliveira/Java_NFe
src/main/java/br/com/swconsultoria/nfe/schema/retEnvEpec/TEvento.java
Java
mit
40,213
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Form_Element_Select */ // require_once 'Zend/Form/Element/Select.php'; /** * Multiselect form element * * @category Zend * @package Zend_Form * @subpackage Element * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ class Zend_Form_Element_Multiselect extends Zend_Form_Element_Select { /** * 'multiple' attribute * @var string */ public $multiple = 'multiple'; /** * Use formSelect view helper by default * @var string */ public $helper = 'formSelect'; /** * Multiselect is an array of values by default * @var bool */ protected $_isArray = true; }
ProfilerTeam/Profiler
protected/vendors/Zend/Form/Element/Multiselect.php
PHP
mit
1,461
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.formrecognizer.administration; import com.azure.ai.formrecognizer.administration.models.AccountProperties; import com.azure.ai.formrecognizer.administration.models.BuildModelOptions; import com.azure.ai.formrecognizer.administration.models.CopyAuthorization; import com.azure.ai.formrecognizer.administration.models.CopyAuthorizationOptions; import com.azure.ai.formrecognizer.administration.models.CreateComposedModelOptions; import com.azure.ai.formrecognizer.administration.models.DocumentBuildMode; import com.azure.ai.formrecognizer.administration.models.DocumentModel; import com.azure.ai.formrecognizer.administration.models.ModelOperation; import com.azure.ai.formrecognizer.administration.models.ModelOperationStatus; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.util.polling.AsyncPollResponse; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Code snippet for {@link DocumentModelAdministrationAsyncClient} */ public class DocumentModelAdminAsyncClientJavaDocCodeSnippets { private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder().buildAsyncClient(); /** * Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.initialization DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder().buildAsyncClient(); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.initialization } /** * Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline */ public void createDocumentTrainingAsyncClientWithPipeline() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.pipeline.instantiation HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.pipeline.instantiation } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginBuildModel(String, DocumentBuildMode, String)} */ public void beginBuildModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}"; documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE, "model-name" ) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginBuildModel(String, DocumentBuildMode, String, BuildModelOptions)} * with options */ public void beginBuildModelWithOptions() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String-BuildModelOptions String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE, "model-name", new BuildModelOptions() .setDescription("model desc") .setPrefix("Invoice") .setTags(attrs)) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); System.out.printf("Model assigned tags: %s%n", documentModel.getTags()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String-BuildModelOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#deleteModel} */ public void deleteModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModel#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.deleteModel(modelId) .subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId)); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModel#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#deleteModelWithResponse(String)} */ public void deleteModelWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModelWithResponse#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId) .subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model ID: %s is deleted.%n", modelId); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModelWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getCopyAuthorization(String)} */ public void getCopyAuthorization() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorization#string String modelId = "my-copied-model"; documentModelAdministrationAsyncClient.getCopyAuthorization(modelId) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource ID; %s, target resource region: %s%n", copyAuthorization.getTargetModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpiresOn(), copyAuthorization.getTargetResourceId(), copyAuthorization.getTargetResourceRegion() )); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorization#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getCopyAuthorizationWithResponse(String, CopyAuthorizationOptions)} */ public void getCopyAuthorizationWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse#string-CopyAuthorizationOptions String modelId = "my-copied-model"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(modelId, new CopyAuthorizationOptions() .setDescription("model desc") .setTags(attrs)) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, " + "expiration time: %s, target resource ID; %s, target resource region: %s%n", copyAuthorization.getStatusCode(), copyAuthorization.getValue().getTargetModelId(), copyAuthorization.getValue().getAccessToken(), copyAuthorization.getValue().getExpiresOn(), copyAuthorization.getValue().getTargetResourceId(), copyAuthorization.getValue().getTargetResourceRegion() )); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse#string-CopyAuthorizationOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getAccountProperties()} */ public void getAccountProperties() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountProperties documentModelAdministrationAsyncClient.getAccountProperties() .subscribe(accountProperties -> { System.out.printf("Max number of models that can be build for this account: %d%n", accountProperties.getDocumentModelLimit()); System.out.printf("Current count of built document analysis models: %d%n", accountProperties.getDocumentModelCount()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountProperties } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getAccountPropertiesWithResponse()} */ public void getAccountPropertiesWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountPropertiesWithResponse documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse() .subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be build for this account: %d%n", accountProperties.getDocumentModelLimit()); System.out.printf("Current count of built document analysis models: %d%n", accountProperties.getDocumentModelCount()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountPropertiesWithResponse } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCreateComposedModel(List, String)} */ public void beginCreateComposedModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String String modelId1 = "{model_Id_1}"; String modelId2 = "{model_Id_2}"; documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2), "my-composed-model") // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCreateComposedModel(List, String, CreateComposedModelOptions)} * with options */ public void beginCreateComposedModelWithOptions() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String-createComposedModelOptions String modelId1 = "{model_Id_1}"; String modelId2 = "{model_Id_2}"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2), "my-composed-model", new CreateComposedModelOptions().setDescription("model-desc").setTags(attrs)) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); System.out.printf("Model assigned tags: %s%n", documentModel.getTags()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String-createComposedModelOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCopyModel(String, CopyAuthorization)} */ public void beginCopy() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCopyModel#string-copyAuthorization String copyModelId = "copy-model"; String targetModelId = "my-copied-model-id"; // Get authorization to copy the model to target resource documentModelAdministrationAsyncClient.getCopyAuthorization(targetModelId) // Start copy operation from the source client // The ID of the model that needs to be copied to the target resource .subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModel(copyModelId, copyAuthorization) .filter(pollResponse -> pollResponse.getStatus().isComplete()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> System.out.printf("Copied model has model ID: %s, was created on: %s.%n,", documentModel.getModelId(), documentModel.getCreatedOn()))); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCopyModel#string-copyAuthorization } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#listModels()} */ public void listModels() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listModels documentModelAdministrationAsyncClient.listModels() .subscribe(documentModelInfo -> System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n", documentModelInfo.getModelId(), documentModelInfo.getDescription(), documentModelInfo.getCreatedOn())); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listModels } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModel(String)} */ public void getModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModel#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModel#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModelWithResponse(String)} */ public void getModelWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModelWithResponse#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); DocumentModel documentModel = response.getValue(); System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModelWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModel(String)} */ public void getOperation() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperation#string String operationId = "{operation_Id}"; documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> { System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId()); if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) { System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage()); } }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperation#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getOperationWithResponse(String)} */ public void getOperationWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperationWithResponse#string String operationId = "{operation_Id}"; documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); ModelOperation modelOperation = response.getValue(); System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId()); if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) { System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage()); } }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperationWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#listOperations()} */ public void listOperations() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listOperations documentModelAdministrationAsyncClient.listOperations() .subscribe(modelOperation -> { System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn()); System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn()); System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listOperations } }
Azure/azure-sdk-for-java
sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/administration/DocumentModelAdminAsyncClientJavaDocCodeSnippets.java
Java
mit
24,260
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; namespace NetsuiteEnvironmentViewer { //http://stackoverflow.com/questions/6442911/how-do-i-sync-scrolling-in-2-treeviews-using-the-slider public partial class MyTreeView : TreeView { public MyTreeView() : base() { } private List<MyTreeView> linkedTreeViews = new List<MyTreeView>(); /// <summary> /// Links the specified tree view to this tree view. Whenever either treeview /// scrolls, the other will scroll too. /// </summary> /// <param name="treeView">The TreeView to link.</param> public void AddLinkedTreeView(MyTreeView treeView) { if (treeView == this) throw new ArgumentException("Cannot link a TreeView to itself!", "treeView"); if (!linkedTreeViews.Contains(treeView)) { //add the treeview to our list of linked treeviews linkedTreeViews.Add(treeView); //add this to the treeview's list of linked treeviews treeView.AddLinkedTreeView(this); //make sure the TreeView is linked to all of the other TreeViews that this TreeView is linked to for (int i = 0; i < linkedTreeViews.Count; i++) { //get the linked treeview var linkedTreeView = linkedTreeViews[i]; //link the treeviews together if (linkedTreeView != treeView) linkedTreeView.AddLinkedTreeView(treeView); } } } /// <summary> /// Sets the destination's scroll positions to that of the source. /// </summary> /// <param name="source">The source of the scroll positions.</param> /// <param name="dest">The destinations to set the scroll positions for.</param> private void SetScrollPositions(MyTreeView source, MyTreeView dest) { //get the scroll positions of the source int horizontal = User32.GetScrollPos(source.Handle, Orientation.Horizontal); int vertical = User32.GetScrollPos(source.Handle, Orientation.Vertical); //set the scroll positions of the destination User32.SetScrollPos(dest.Handle, Orientation.Horizontal, horizontal, true); User32.SetScrollPos(dest.Handle, Orientation.Vertical, vertical, true); } protected override void WndProc(ref Message m) { //process the message base.WndProc(ref m); //pass scroll messages onto any linked views if (m.Msg == User32.WM_VSCROLL || m.Msg == User32.WM_MOUSEWHEEL) { foreach (var linkedTreeView in linkedTreeViews) { //set the scroll positions of the linked tree view SetScrollPositions(this, linkedTreeView); //copy the windows message Message copy = new Message { HWnd = linkedTreeView.Handle, LParam = m.LParam, Msg = m.Msg, Result = m.Result, WParam = m.WParam }; //pass the message onto the linked tree view linkedTreeView.ReceiveWndProc(ref copy); } } } /// <summary> /// Recieves a WndProc message without passing it onto any linked treeviews. This is useful to avoid infinite loops. /// </summary> /// <param name="m">The windows message.</param> private void ReceiveWndProc(ref Message m) { base.WndProc(ref m); } /// <summary> /// Imported functions from the User32.dll /// </summary> private class User32 { public const int WM_VSCROLL = 0x115; public const int WM_MOUSEWHEEL = 0x020A; [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetScrollPos(IntPtr hWnd, System.Windows.Forms.Orientation nBar); [DllImport("user32.dll")] public static extern int SetScrollPos(IntPtr hWnd, System.Windows.Forms.Orientation nBar, int nPos, bool bRedraw); } } }
zacarius89/NetsuiteEnvironmentViewer
NetsuiteEnvironmentViewer/windowsFormClients/treeViewClient.cs
C#
mit
3,736