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
import { OpaqueToken } from './di'; /** * A DI Token representing a unique string id assigned to the application by Angular and used * primarily for prefixing application attributes and CSS styles when * {@link ViewEncapsulation#Emulated} is being used. * * If you need to avoid randomly generated value to be used as an application id, you can provide * a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector} * using this token. * @experimental */ export declare const APP_ID: any; export declare function _appIdRandomProviderFactory(): string; /** * Providers that will generate a random APP_ID_TOKEN. * @experimental */ export declare const APP_ID_RANDOM_PROVIDER: { provide: any; useFactory: () => string; deps: any[]; }; /** * A function that will be executed when a platform is initialized. * @experimental */ export declare const PLATFORM_INITIALIZER: any; /** * All callbacks provided via this token will be called for every component that is bootstrapped. * Signature of the callback: * * `(componentRef: ComponentRef) => void`. * * @experimental */ export declare const APP_BOOTSTRAP_LISTENER: OpaqueToken; /** * A token which indicates the root directory of the application * @experimental */ export declare const PACKAGE_ROOT_URL: any;
oleksandr-minakov/northshore
ui/node_modules/@angular/core/src/application_tokens.d.ts
TypeScript
apache-2.0
1,325
cask :v1 => 'navicat-for-sqlite' do version '11.1.13' # navicat-premium.rb and navicat-for-* should be upgraded together sha256 'd8dfce2de0af81f7c0883773a3c5ed1be64eb076fb67708344d0748244b7566a' url "http://download.navicat.com/download/navicat#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}_sqlite_en.dmg" name 'Navicat for SQLite' homepage 'http://www.navicat.com/products/navicat-for-sqlite' license :commercial tags :vendor => 'Navicat' app 'Navicat for SQLite.app' end
bcaceiro/homebrew-cask
Casks/navicat-for-sqlite.rb
Ruby
bsd-2-clause
489
/** * Listens for the app launching then creates the window * * @see http://developer.chrome.com/apps/app.runtime.html * @see http://developer.chrome.com/apps/app.window.html */ chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('index.html', { id: "camCaptureID", innerBounds: { width: 700, height: 600 } }); });
Jabqooo/chrome-app-samples
samples/camera-capture/background.js
JavaScript
apache-2.0
375
""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from __future__ import division, print_function, absolute_import from numpy.testing import assert_, dec, TestCase, run_module_suite from scipy._lib.six import xrange from scipy.optimize import nonlin, root from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np from test_minpack import pressure_network SOLVERS = {'anderson': nonlin.anderson, 'diagbroyden': nonlin.diagbroyden, 'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing, 'broyden1': nonlin.broyden1, 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov} MUST_WORK = {'anderson': nonlin.anderson, 'broyden1': nonlin.broyden1, 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov} #------------------------------------------------------------------------------- # Test problems #------------------------------------------------------------------------------- def F(x): x = np.asmatrix(x).T d = matrix(diag([3,2,1.5,1,0.5])) c = 0.01 f = -d*x - c*float(x.T*x)*x return f F.xin = [1,1,1,1,1] F.KNOWN_BAD = {} def F2(x): return x F2.xin = [1,2,3,4,5,6] F2.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing} def F2_lucky(x): return x F2_lucky.xin = [0,0,0,0,0,0] F2_lucky.KNOWN_BAD = {} def F3(x): A = np.mat('-2 1 0; 1 -2 1; 0 1 -2') b = np.mat('1 2 3') return np.dot(A, x) - b F3.xin = [1,2,3] F3.KNOWN_BAD = {} def F4_powell(x): A = 1e4 return [A*x[0]*x[1] - 1, np.exp(-x[0]) + np.exp(-x[1]) - (1 + 1/A)] F4_powell.xin = [-1, -2] F4_powell.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing, 'diagbroyden': nonlin.diagbroyden} def F5(x): return pressure_network(x, 4, np.array([.5, .5, .5, .5])) F5.xin = [2., 0, 2, 0] F5.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, 'linearmixing': nonlin.linearmixing, 'diagbroyden': nonlin.diagbroyden} def F6(x): x1, x2 = x J0 = np.array([[-4.256, 14.7], [0.8394989, 0.59964207]]) v = np.array([(x1 + 3) * (x2**5 - 7) + 3*6, np.sin(x2 * np.exp(x1) - 1)]) return -np.linalg.solve(J0, v) F6.xin = [-0.5, 1.4] F6.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, 'linearmixing': nonlin.linearmixing, 'diagbroyden': nonlin.diagbroyden} #------------------------------------------------------------------------------- # Tests #------------------------------------------------------------------------------- class TestNonlin(object): """ Check the Broyden methods for a few test problems. broyden1, broyden2, and newton_krylov must succeed for all functions. Some of the others don't -- tests in KNOWN_BAD are skipped. """ def _check_nonlin_func(self, f, func, f_tol=1e-2): x = func(f, f.xin, f_tol=f_tol, maxiter=200, verbose=0) assert_(np.absolute(f(x)).max() < f_tol) def _check_root(self, f, method, f_tol=1e-2): res = root(f, f.xin, method=method, options={'ftol': f_tol, 'maxiter': 200, 'disp': 0}) assert_(np.absolute(res.fun).max() < f_tol) @dec.knownfailureif(True) def _check_func_fail(self, *a, **kw): pass def test_problem_nonlin(self): for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: for func in SOLVERS.values(): if func in f.KNOWN_BAD.values(): if func in MUST_WORK.values(): yield self._check_func_fail, f, func continue yield self._check_nonlin_func, f, func def test_tol_norm_called(self): # Check that supplying tol_norm keyword to nonlin_solve works self._tol_norm_used = False def local_norm_func(x): self._tol_norm_used = True return np.absolute(x).max() nonlin.newton_krylov(F, F.xin, f_tol=1e-2, maxiter=200, verbose=0, tol_norm=local_norm_func) assert_(self._tol_norm_used) def test_problem_root(self): for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: for meth in SOLVERS: if meth in f.KNOWN_BAD: if meth in MUST_WORK: yield self._check_func_fail, f, meth continue yield self._check_root, f, meth class TestSecant(TestCase): """Check that some Jacobian approximations satisfy the secant condition""" xs = [np.array([1,2,3,4,5], float), np.array([2,3,4,5,1], float), np.array([3,4,5,1,2], float), np.array([4,5,1,2,3], float), np.array([9,1,9,1,3], float), np.array([0,1,9,1,3], float), np.array([5,5,7,1,1], float), np.array([1,2,7,5,1], float),] fs = [x**2 - 1 for x in xs] def _check_secant(self, jac_cls, npoints=1, **kw): """ Check that the given Jacobian approximation satisfies secant conditions for last `npoints` points. """ jac = jac_cls(**kw) jac.setup(self.xs[0], self.fs[0], None) for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): jac.update(x, f) for k in xrange(min(npoints, j+1)): dx = self.xs[j-k+1] - self.xs[j-k] df = self.fs[j-k+1] - self.fs[j-k] assert_(np.allclose(dx, jac.solve(df))) # Check that the `npoints` secant bound is strict if j >= npoints: dx = self.xs[j-npoints+1] - self.xs[j-npoints] df = self.fs[j-npoints+1] - self.fs[j-npoints] assert_(not np.allclose(dx, jac.solve(df))) def test_broyden1(self): self._check_secant(nonlin.BroydenFirst) def test_broyden2(self): self._check_secant(nonlin.BroydenSecond) def test_broyden1_update(self): # Check that BroydenFirst update works as for a dense matrix jac = nonlin.BroydenFirst(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) B = np.identity(5) * (-1/0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] B += (df - dot(B, dx))[:,None] * dx[None,:] / dot(dx, dx) jac.update(x, f) assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13)) def test_broyden2_update(self): # Check that BroydenSecond update works as for a dense matrix jac = nonlin.BroydenSecond(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) H = np.identity(5) * (-0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df) jac.update(x, f) assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) def test_anderson(self): # Anderson mixing (with w0=0) satisfies secant conditions # for the last M iterates, see [Ey]_ # # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3) class TestLinear(TestCase): """Solve a linear equation; some methods find the exact solution in a finite number of steps""" def _check(self, jac, N, maxiter, complex=False, **kw): np.random.seed(123) A = np.random.randn(N, N) if complex: A = A + 1j*np.random.randn(N, N) b = np.random.randn(N) if complex: b = b + 1j*np.random.randn(N) def func(x): return dot(A, x) - b sol = nonlin.nonlin_solve(func, np.zeros(N), jac, maxiter=maxiter, f_tol=1e-6, line_search=None, verbose=0) assert_(np.allclose(dot(A, sol), b, atol=1e-6)) def test_broyden1(self): # Broyden methods solve linear systems exactly in 2*N steps self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, False) self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, True) def test_broyden2(self): # Broyden methods solve linear systems exactly in 2*N steps self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, False) self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, True) def test_anderson(self): # Anderson is rather similar to Broyden, if given enough storage space self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, False) self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, True) def test_krylov(self): # Krylov methods solve linear systems exactly in N inner steps self._check(nonlin.KrylovJacobian, 20, 2, False, inner_m=10) self._check(nonlin.KrylovJacobian, 20, 2, True, inner_m=10) class TestJacobianDotSolve(object): """Check that solve/dot methods in Jacobian approximations are consistent""" def _func(self, x): return x**2 - 1 + np.dot(self.A, x) def _check_dot(self, jac_cls, complex=False, tol=1e-6, **kw): np.random.seed(123) N = 7 def rand(*a): q = np.random.rand(*a) if complex: q = q + 1j*np.random.rand(*a) return q def assert_close(a, b, msg): d = abs(a - b).max() f = tol + abs(b).max()*tol if d > f: raise AssertionError('%s: err %g' % (msg, d)) self.A = rand(N, N) # initialize x0 = np.random.rand(N) jac = jac_cls(**kw) jac.setup(x0, self._func(x0), self._func) # check consistency for k in xrange(2*N): v = rand(N) if hasattr(jac, '__array__'): Jd = np.array(jac) if hasattr(jac, 'solve'): Gv = jac.solve(v) Gv2 = np.linalg.solve(Jd, v) assert_close(Gv, Gv2, 'solve vs array') if hasattr(jac, 'rsolve'): Gv = jac.rsolve(v) Gv2 = np.linalg.solve(Jd.T.conj(), v) assert_close(Gv, Gv2, 'rsolve vs array') if hasattr(jac, 'matvec'): Jv = jac.matvec(v) Jv2 = np.dot(Jd, v) assert_close(Jv, Jv2, 'dot vs array') if hasattr(jac, 'rmatvec'): Jv = jac.rmatvec(v) Jv2 = np.dot(Jd.T.conj(), v) assert_close(Jv, Jv2, 'rmatvec vs array') if hasattr(jac, 'matvec') and hasattr(jac, 'solve'): Jv = jac.matvec(v) Jv2 = jac.solve(jac.matvec(Jv)) assert_close(Jv, Jv2, 'dot vs solve') if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'): Jv = jac.rmatvec(v) Jv2 = jac.rmatvec(jac.rsolve(Jv)) assert_close(Jv, Jv2, 'rmatvec vs rsolve') x = rand(N) jac.update(x, self._func(x)) def test_broyden1(self): self._check_dot(nonlin.BroydenFirst, complex=False) self._check_dot(nonlin.BroydenFirst, complex=True) def test_broyden2(self): self._check_dot(nonlin.BroydenSecond, complex=False) self._check_dot(nonlin.BroydenSecond, complex=True) def test_anderson(self): self._check_dot(nonlin.Anderson, complex=False) self._check_dot(nonlin.Anderson, complex=True) def test_diagbroyden(self): self._check_dot(nonlin.DiagBroyden, complex=False) self._check_dot(nonlin.DiagBroyden, complex=True) def test_linearmixing(self): self._check_dot(nonlin.LinearMixing, complex=False) self._check_dot(nonlin.LinearMixing, complex=True) def test_excitingmixing(self): self._check_dot(nonlin.ExcitingMixing, complex=False) self._check_dot(nonlin.ExcitingMixing, complex=True) def test_krylov(self): self._check_dot(nonlin.KrylovJacobian, complex=False, tol=1e-4) self._check_dot(nonlin.KrylovJacobian, complex=True, tol=1e-4) class TestNonlinOldTests(TestCase): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) """ def test_broyden1(self): x = nonlin.broyden1(F,F.xin,iter=12,alpha=1) assert_(nonlin.norm(x) < 1e-9) assert_(nonlin.norm(F(x)) < 1e-9) def test_broyden2(self): x = nonlin.broyden2(F,F.xin,iter=12,alpha=1) assert_(nonlin.norm(x) < 1e-9) assert_(nonlin.norm(F(x)) < 1e-9) def test_anderson(self): x = nonlin.anderson(F,F.xin,iter=12,alpha=0.03,M=5) assert_(nonlin.norm(x) < 0.33) def test_linearmixing(self): x = nonlin.linearmixing(F,F.xin,iter=60,alpha=0.5) assert_(nonlin.norm(x) < 1e-7) assert_(nonlin.norm(F(x)) < 1e-7) def test_exciting(self): x = nonlin.excitingmixing(F,F.xin,iter=20,alpha=0.5) assert_(nonlin.norm(x) < 1e-5) assert_(nonlin.norm(F(x)) < 1e-5) def test_diagbroyden(self): x = nonlin.diagbroyden(F,F.xin,iter=11,alpha=1) assert_(nonlin.norm(x) < 1e-8) assert_(nonlin.norm(F(x)) < 1e-8) def test_root_broyden1(self): res = root(F, F.xin, method='broyden1', options={'nit': 12, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-9) assert_(nonlin.norm(res.fun) < 1e-9) def test_root_broyden2(self): res = root(F, F.xin, method='broyden2', options={'nit': 12, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-9) assert_(nonlin.norm(res.fun) < 1e-9) def test_root_anderson(self): res = root(F, F.xin, method='anderson', options={'nit': 12, 'jac_options': {'alpha': 0.03, 'M': 5}}) assert_(nonlin.norm(res.x) < 0.33) def test_root_linearmixing(self): res = root(F, F.xin, method='linearmixing', options={'nit': 60, 'jac_options': {'alpha': 0.5}}) assert_(nonlin.norm(res.x) < 1e-7) assert_(nonlin.norm(res.fun) < 1e-7) def test_root_excitingmixing(self): res = root(F, F.xin, method='excitingmixing', options={'nit': 20, 'jac_options': {'alpha': 0.5}}) assert_(nonlin.norm(res.x) < 1e-5) assert_(nonlin.norm(res.fun) < 1e-5) def test_root_diagbroyden(self): res = root(F, F.xin, method='diagbroyden', options={'nit': 11, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-8) assert_(nonlin.norm(res.fun) < 1e-8) if __name__ == "__main__": run_module_suite()
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/scipy/optimize/tests/test_nonlin.py
Python
gpl-2.0
15,160
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.psi; import com.intellij.openapi.components.ServiceManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; public abstract class JavaDirectoryService { public static JavaDirectoryService getInstance() { return ServiceManager.getService(JavaDirectoryService.class); } /** * Returns the package corresponding to the directory. * * @return the package instance, or null if the directory does not correspond to any package. */ @Nullable public abstract PsiPackage getPackage(@NotNull PsiDirectory dir); /** * Returns the list of Java classes contained in the directory. * * @return the array of classes. */ @NotNull public abstract PsiClass[] getClasses(@NotNull PsiDirectory dir); /** * Creates a class with the specified name in the directory. * * @param name the name of the class to create (not including the file extension). * @return the created class instance. * @throws IncorrectOperationException if the operation failed for some reason. */ @NotNull public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException; /** * Creates a class with the specified name in the directory. * * @param name the name of the class to create (not including the file extension). * @param templateName custom file template to create class text based on. * @return the created class instance. * @throws IncorrectOperationException if the operation failed for some reason. * @since 5.1 */ @NotNull public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException; /** * @param askForUndefinedVariables * true show dialog asking for undefined variables * false leave them blank */ public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName, boolean askForUndefinedVariables) throws IncorrectOperationException; /** * @param additionalProperties additional properties to be substituted in the template */ public abstract PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName, boolean askForUndefinedVariables, @NotNull final Map<String, String> additionalProperties) throws IncorrectOperationException; /** * Checks if it's possible to create a class with the specified name in the directory, * and throws an exception if the creation is not possible. Does not actually modify * anything. * * @param name the name of the class to check creation possibility (not including the file extension). * @throws IncorrectOperationException if the creation is not possible. */ public abstract void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException; /** * Creates an interface class with the specified name in the directory. * * @param name the name of the interface to create (not including the file extension). * @return the created interface instance. * @throws IncorrectOperationException if the operation failed for some reason. */ @NotNull public abstract PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException; /** * Creates an enumeration class with the specified name in the directory. * * @param name the name of the enumeration class to create (not including the file extension). * @return the created class instance. * @throws IncorrectOperationException if the operation failed for some reason. */ @NotNull public abstract PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException; /** * Creates an annotation class with the specified name in the directory. * * @param name the name of the annotation class to create (not including the file extension). * @return the created class instance. * @throws IncorrectOperationException if the operation failed for some reason. */ @NotNull public abstract PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException; /** * Checks if the directory is a source root for the project to which it belongs. * * @return true if the directory is a source root, false otherwise */ public abstract boolean isSourceRoot(@NotNull PsiDirectory dir); public abstract LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir); }
caot/intellij-community
java/java-psi-api/src/com/intellij/psi/JavaDirectoryService.java
Java
apache-2.0
5,506
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Franz Willer <franz.willer@gwi-ag.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.common; import java.util.Arrays; /** * @author gunter.zeilinger@tiani.com * @version $Revision: 2772 $ $Date: 2006-09-20 16:58:51 +0800 (周三, 20 9月 2006) $ * @since 06.10.2004 * */ public class SPSStatus { private static final String[] ENUM = { "SCHEDULED", "ARRIVED", "READY", "STARTED", "COMPLETED", "DISCONTINUED" }; public static final int SCHEDULED = 0; public static final int ARRIVED = 1; public static final int READY = 2; public static final int STARTED = 3; public static final int COMPLETED = 4; public static final int DISCONTINUED = 5; public static final String toString(int value) { return ENUM[value]; } public static final int toInt(String s) { final int index = Arrays.asList(ENUM).indexOf(s); if (index == -1) throw new IllegalArgumentException(s); return index; } public static int[] toInts(String[] ss) { if (ss == null) { return null; } int[] ret = new int[ss.length]; for (int i = 0; i < ret.length; i++) { ret[i] = toInt(ss[i]); } return ret; } }
medicayun/medicayundicom
dcm4jboss-all/trunk/dcm4jboss-ejb/src/java/org/dcm4chex/archive/common/SPSStatus.java
Java
apache-2.0
3,087
<?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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FormTextarea.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * Abstract class for extension */ require_once 'Zend/View/Helper/FormElement.php'; /** * Helper to generate a "textarea" element * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_View_Helper_FormTextarea extends Zend_View_Helper_FormElement { /** * The default number of rows for a textarea. * * @access public * * @var int */ public $rows = 24; /** * The default number of columns for a textarea. * * @access public * * @var int */ public $cols = 80; /** * Generates a 'textarea' element. * * @access public * * @param string|array $name If a string, the element name. If an * array, all other parameters are ignored, and the array elements * are extracted in place of added parameters. * * @param mixed $value The element value. * * @param array $attribs Attributes for the element tag. * * @return string The element XHTML. */ public function formTextarea($name, $value = null, $attribs = null) { $info = $this->_getInfo($name, $value, $attribs); extract($info); // name, value, attribs, options, listsep, disable // is it disabled? $disabled = ''; if ($disable) { // disabled. $disabled = ' disabled="disabled"'; } // Make sure that there are 'rows' and 'cols' values // as required by the spec. noted by Orjan Persson. if (empty($attribs['rows'])) { $attribs['rows'] = (int) $this->rows; } if (empty($attribs['cols'])) { $attribs['cols'] = (int) $this->cols; } // build the element $xhtml = '<textarea name="' . $this->view->escape($name) . '"' . ' id="' . $this->view->escape($id) . '"' . $disabled . $this->_htmlAttribs($attribs) . '>' . $this->view->escape($value) . '</textarea>'; return $xhtml; } }
chisimba/modules
zend/resources/Zend/View/Helper/FormTextarea.php
PHP
gpl-2.0
2,995
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.cvsSupport2.actions.update; import com.intellij.cvsSupport2.cvsoperations.dateOrRevision.RevisionOrDate; import com.intellij.cvsSupport2.cvsoperations.dateOrRevision.SimpleRevision; import org.netbeans.lib.cvsclient.command.KeywordSubstitution; /** * author: lesya */ public class UpdateByBranchUpdateSettings implements UpdateSettings{ private final String myBranchName; private final boolean myMakeNewFilesReadOnly; public UpdateByBranchUpdateSettings(String branchName, boolean makeNewFilesReadOnly) { myBranchName = branchName; myMakeNewFilesReadOnly = makeNewFilesReadOnly; } public boolean getPruneEmptyDirectories() { return true; } public String getBranch1ToMergeWith() { return null; } public String getBranch2ToMergeWith() { return null; } public boolean getResetAllSticky() { return false; } public boolean getDontMakeAnyChanges() { return false; } public boolean getCreateDirectories() { return true; } public boolean getCleanCopy() { return false; } public KeywordSubstitution getKeywordSubstitution() { return null; } public RevisionOrDate getRevisionOrDate() { return new SimpleRevision(myBranchName); } public boolean getMakeNewFilesReadOnly() { return myMakeNewFilesReadOnly; } }
akosyakov/intellij-community
plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/update/UpdateByBranchUpdateSettings.java
Java
apache-2.0
1,930
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.DataInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import com.google.common.base.Preconditions; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; /** * An implementation of the abstract class {@link EditLogInputStream}, * which is used to updates HDFS meta-data state on a backup node. * * @see org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol#journal * (org.apache.hadoop.hdfs.server.protocol.NamenodeRegistration, * int, int, byte[]) */ class EditLogBackupInputStream extends EditLogInputStream { final String address; // sender address private final ByteBufferInputStream inner; private DataInputStream in; private FSEditLogOp.Reader reader = null; private FSEditLogLoader.PositionTrackingInputStream tracker = null; private int version = 0; /** * A ByteArrayInputStream, which lets modify the underlying byte array. */ private static class ByteBufferInputStream extends ByteArrayInputStream { ByteBufferInputStream() { super(new byte[0]); } void setData(byte[] newBytes) { super.buf = newBytes; super.count = newBytes == null ? 0 : newBytes.length; super.mark = 0; reset(); } /** * Number of bytes read from the stream so far. */ int length() { return count; } } EditLogBackupInputStream(String name) throws IOException { address = name; inner = new ByteBufferInputStream(); in = null; reader = null; } @Override public String getName() { return address; } @Override protected FSEditLogOp nextOp() throws IOException { Preconditions.checkState(reader != null, "Must call setBytes() before readOp()"); return reader.readOp(false); } @Override protected FSEditLogOp nextValidOp() { try { return reader.readOp(true); } catch (IOException e) { throw new RuntimeException("got unexpected IOException " + e, e); } } @Override public int getVersion(boolean verifyVersion) throws IOException { return this.version; } @Override public long getPosition() { return tracker.getPos(); } @Override public void close() throws IOException { in.close(); } @Override public long length() throws IOException { // file size + size of both buffers return inner.length(); } void setBytes(byte[] newBytes, int version) throws IOException { inner.setData(newBytes); tracker = new FSEditLogLoader.PositionTrackingInputStream(inner); in = new DataInputStream(tracker); this.version = version; reader = FSEditLogOp.Reader.create(in, tracker, version); } void clear() throws IOException { setBytes(null, 0); reader = null; this.version = 0; } @Override public long getFirstTxId() { return HdfsServerConstants.INVALID_TXID; } @Override public long getLastTxId() { return HdfsServerConstants.INVALID_TXID; } @Override public boolean isInProgress() { return true; } @Override public void setMaxOpSize(int maxOpSize) { reader.setMaxOpSize(maxOpSize); } @Override public boolean isLocalLog() { return true; } }
cnfire/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/EditLogBackupInputStream.java
Java
apache-2.0
4,051
--TEST-- GH-1351: Test result does not serialize test class in process isolation --SKIPIF-- <?php if (!extension_loaded('pdo') || !in_array('sqlite', PDO::getAvailableDrivers())) { print 'skip: PDO_SQLITE is required'; } ?> --FILE-- <?php $_SERVER['argv'][1] = '--no-configuration'; $_SERVER['argv'][2] = '--process-isolation'; $_SERVER['argv'][3] = 'Issue1351Test'; $_SERVER['argv'][4] = __DIR__ . '/1351/Issue1351Test.php'; require __DIR__ . '/../../bootstrap.php'; PHPUnit_TextUI_Command::main(); ?> --EXPECTF-- PHPUnit %s by Sebastian Bergmann and contributors. F.E.E 5 / 5 (100%) Time: %s, Memory: %sMb There were 2 errors: 1) Issue1351Test::testExceptionPre RuntimeException: Expected rethrown exception. %A Caused by LogicException: Expected exception. %A 2) Issue1351Test::testPhpCoreLanguageException PDOException: SQLSTATE[HY000]: General error: 1 no such table: php_wtf %A -- There was 1 failure: 1) Issue1351Test::testFailurePre Expected failure. %A FAILURES! Tests: 5, Assertions: 5, Errors: 2, Failures: 1.
shankarnakai/gbdesign
wp-content/mu-plugins/vsigestao/vendor/phpunit/phpunit/tests/Regression/GitHub/1351.phpt
PHP
gpl-2.0
1,097
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.refactoring.convertToJava.invocators; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiSubstitutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod; import org.jetbrains.plugins.groovy.refactoring.convertToJava.ExpressionGenerator; /** * @author Max Medvedev */ public abstract class CustomMethodInvocator { private static final ExtensionPointName<CustomMethodInvocator> EP_NAME = ExtensionPointName.create("org.intellij.groovy.convertToJava.customMethodInvocator"); protected abstract boolean invoke(@NotNull ExpressionGenerator generator, @NotNull PsiMethod method, @Nullable GrExpression caller, @NotNull GrExpression[] exprs, @NotNull GrNamedArgument[] namedArgs, @NotNull GrClosableBlock[] closures, @NotNull PsiSubstitutor substitutor, @NotNull GroovyPsiElement context); public static boolean invokeMethodOn(@NotNull ExpressionGenerator generator, @NotNull GrGdkMethod method, @Nullable GrExpression caller, @NotNull GrExpression[] exprs, @NotNull GrNamedArgument[] namedArgs, @NotNull GrClosableBlock[] closures, @NotNull PsiSubstitutor substitutor, @NotNull GroovyPsiElement context) { final PsiMethod staticMethod = method.getStaticMethod(); for (CustomMethodInvocator invocator : EP_NAME.getExtensions()) { if (invocator.invoke(generator, staticMethod, caller, exprs, namedArgs, closures, substitutor, context)) { return true; } } return false; } }
liveqmock/platform-tools-idea
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/invocators/CustomMethodInvocator.java
Java
apache-2.0
3,095
<?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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Translate * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: Exception.php 20096 2010-01-06 02:05:09Z bkarwin $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Exception */ require_once 'Zend/Exception.php'; /** * @category Zend * @package Zend_Translate * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Translate_Exception extends Zend_Exception { }
chisimba/modules
zend/resources/Zend/Translate/Exception.php
PHP
gpl-2.0
1,099
/** * Copyright (C) 2011 Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // markup required: // <span class=" field-with-fancyplaceholder"><label for="email">Email Address</span></label><input type="text" id="login_apple_id"></span> // // css required: // span.field-with-fancyplaceholder{display:block;display:inline-block;position:relative;vertical-align:top;} // span.field-with-fancyplaceholder label.placeholder{color:#999;cursor:text;pointer-events:none;} // span.field-with-fancyplaceholder label.placeholder span{position:absolute;z-index:2;-webkit-user-select:none;padding:3px 6px;} // span.field-with-fancyplaceholder label.focus{color:#ccc;} // span.field-with-fancyplaceholder label.hidden{color:#fff;} // span.field-with-fancyplaceholder input.invalid{background:#ffffc5;color:#F30;} // span.field-with-fancyplaceholder input.editing{color:#000;background:none repeat scroll 0 0 transparent;overflow:hidden;} // // then: $(".field-with-fancyplaceholder input").fancyPlaceholder(); define(['jquery'], function($) { $.fn.fancyPlaceholder = function() { var pollingInterval, foundInputsAndLables = []; function hideOrShowLabels(){ $.each(foundInputsAndLables, function(i, inputAndLable){ inputAndLable[1][inputAndLable[0].val() ? 'hide' : 'show'](); }); } return this.each(function() { var $input = $(this), $label = $("label[for="+$input.attr('id')+"]"); $label.addClass('placeholder').wrapInner("<span/>").css({ 'font-family' : $input.css('font-family'), 'font-size' : $input.css('font-size') }); $input .focus(function(){ $label.addClass('focus', 300); }) .blur(function(){ $label.removeClass('focus', 300); }) .bind('keyup', hideOrShowLabels); // if this was already focused before we got here, make it light gray now. sorry, ie7 cant do :focus selector, it doesn't get this. try { if ($("input:focus").get(0) == this) { $input.triggerHandler('focus'); } } catch(e) {} foundInputsAndLables.push([$input, $label]); if (!pollingInterval) { window.setInterval(hideOrShowLabels, 100); } }); }; });
ajpi222/canvas-lms-hdi
public/javascripts/jquery.fancyplaceholder.js
JavaScript
agpl-3.0
2,861
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.navigation; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; /** * Allows a plugin to add items to "Goto Class" and "Goto Symbol" lists. * * @see ChooseByNameRegistry */ public interface ChooseByNameContributor { ExtensionPointName<ChooseByNameContributor> CLASS_EP_NAME = ExtensionPointName.create("com.intellij.gotoClassContributor"); ExtensionPointName<ChooseByNameContributor> SYMBOL_EP_NAME = ExtensionPointName.create("com.intellij.gotoSymbolContributor"); ExtensionPointName<ChooseByNameContributor> FILE_EP_NAME = ExtensionPointName.create("com.intellij.gotoFileContributor"); /** * Returns the list of names for the specified project to which it is possible to navigate * by name. * * @param project the project in which the navigation is performed. * @param includeNonProjectItems if true, the names of non-project items (for example, * library classes) should be included in the returned array. * @return the array of names. */ @NotNull String[] getNames(Project project, boolean includeNonProjectItems); /** * Returns the list of navigation items matching the specified name. * * @param name the name selected from the list. * @param pattern the original pattern entered in the dialog * @param project the project in which the navigation is performed. * @param includeNonProjectItems if true, the navigation items for non-project items (for example, * library classes) should be included in the returned array. * @return the array of navigation items. */ @NotNull NavigationItem[] getItemsByName(String name, final String pattern, Project project, boolean includeNonProjectItems); }
caot/intellij-community
platform/lang-api/src/com/intellij/navigation/ChooseByNameContributor.java
Java
apache-2.0
2,515
if (require.register) { var qs = require('querystring'); } else { var qs = require('../') , expect = require('expect.js'); } var date = new Date(0); var str_identities = { 'basics': [ { str: 'foo=bar', obj: {'foo' : 'bar'}}, { str: 'foo=%22bar%22', obj: {'foo' : '\"bar\"'}}, { str: 'foo=', obj: {'foo': ''}}, { str: 'foo=1&bar=2', obj: {'foo' : '1', 'bar' : '2'}}, { str: 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj: {'my weird field': "q1!2\"'w$5&7/z8)?"}}, { str: 'foo%3Dbaz=bar', obj: {'foo=baz': 'bar'}}, { str: 'foo=bar&bar=baz', obj: {foo: 'bar', bar: 'baz'}} ], 'escaping': [ { str: 'foo=foo%20bar', obj: {foo: 'foo bar'}}, { str: 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj: { cht: 'p3' , chd: 't:60,40' , chs: '250x100' , chl: 'Hello|World' }} ], 'nested': [ { str: 'foo[0]=bar&foo[1]=quux', obj: {'foo' : ['bar', 'quux']}}, { str: 'foo[0]=bar', obj: {foo: ['bar']}}, { str: 'foo[0]=1&foo[1]=2', obj: {'foo' : ['1', '2']}}, { str: 'foo=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : 'bar', 'baz' : ['1', '2', '3']}}, { str: 'foo[0]=bar&baz[0]=1&baz[1]=2&baz[2]=3', obj: {'foo' : ['bar'], 'baz' : ['1', '2', '3']}}, { str: 'x[y][z]=1', obj: {'x' : {'y' : {'z' : '1'}}}}, { str: 'x[y][z][0]=1', obj: {'x' : {'y' : {'z' : ['1']}}}}, { str: 'x[y][z]=2', obj: {'x' : {'y' : {'z' : '2'}}}}, { str: 'x[y][z][0]=1&x[y][z][1]=2', obj: {'x' : {'y' : {'z' : ['1', '2']}}}}, { str: 'x[y][0][z]=1', obj: {'x' : {'y' : [{'z' : '1'}]}}}, { str: 'x[y][0][z][0]=1', obj: {'x' : {'y' : [{'z' : ['1']}]}}}, { str: 'x[y][0][z]=1&x[y][0][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'w' : '2'}]}}}, { str: 'x[y][0][v][w]=1', obj: {'x' : {'y' : [{'v' : {'w' : '1'}}]}}}, { str: 'x[y][0][z]=1&x[y][0][v][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'v' : {'w' : '2'}}]}}}, { str: 'x[y][0][z]=1&x[y][1][z]=2', obj: {'x' : {'y' : [{'z' : '1'}, {'z' : '2'}]}}}, { str: 'x[y][0][z]=1&x[y][0][w]=a&x[y][1][z]=2&x[y][1][w]=3', obj: {'x' : {'y' : [{'z' : '1', 'w' : 'a'}, {'z' : '2', 'w' : '3'}]}}}, { str: 'user[name][first]=tj&user[name][last]=holowaychuk', obj: { user: { name: { first: 'tj', last: 'holowaychuk' }}}} ], 'errors': [ { obj: 'foo=bar', message: 'stringify expects an object' }, { obj: ['foo', 'bar'], message: 'stringify expects an object' } ], 'numbers': [ { str: 'limit[0]=1&limit[1]=2&limit[2]=3', obj: { limit: [1, 2, '3'] }}, { str: 'limit=1', obj: { limit: 1 }} ], 'others': [ { str: 'at=' + encodeURIComponent(date), obj: { at: date } } ] }; function test(type) { return function(){ var str, obj; for (var i = 0; i < str_identities[type].length; i++) { str = str_identities[type][i].str; obj = str_identities[type][i].obj; expect(qs.stringify(obj)).to.eql(str); } } } describe('qs.stringify()', function(){ it('should support the basics', test('basics')) it('should support escapes', test('escaping')) it('should support nesting', test('nested')) it('should support numbers', test('numbers')) it('should support others', test('others')) })
gglinux/node.js
webChat/node_modules/qs/test/stringify.js
JavaScript
apache-2.0
3,198
# databases/__init__.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Include imports from the sqlalchemy.dialects package for backwards compatibility with pre 0.6 versions. """ from ..dialects.sqlite import base as sqlite from ..dialects.postgresql import base as postgresql postgres = postgresql from ..dialects.mysql import base as mysql from ..dialects.drizzle import base as drizzle from ..dialects.oracle import base as oracle from ..dialects.firebird import base as firebird from ..dialects.mssql import base as mssql from ..dialects.sybase import base as sybase __all__ = ( 'drizzle', 'firebird', 'mssql', 'mysql', 'postgresql', 'sqlite', 'oracle', 'sybase', )
jessekl/flixr
venv/lib/python2.7/site-packages/sqlalchemy/databases/__init__.py
Python
mit
881
module ChefCompat module CopiedFromChef def self.extend_chef_module(chef_module, target) target.instance_eval do include chef_module @chef_module = chef_module def self.method_missing(name, *args, &block) @chef_module.send(name, *args, &block) end def self.const_missing(name) @chef_module.const_get(name) end end end # This patch to CopiedFromChef's ActionClass is necessary for the include to work require 'chef/resource' class Chef < ::Chef class Resource < ::Chef::Resource module ActionClass def self.use_inline_resources end def self.include_resource_dsl(include_resource_dsl) end end end end end end
Coveros/starcanada2016
www-db/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb
Ruby
apache-2.0
784
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btMultiBodyDynamicsWorld.h" #include "btMultiBodyConstraintSolver.h" #include "btMultiBody.h" #include "btMultiBodyLinkCollider.h" #include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" #include "LinearMath/btQuickprof.h" #include "btMultiBodyConstraint.h" #include "LinearMath/btIDebugDraw.h" void btMultiBodyDynamicsWorld::addMultiBody(btMultiBody* body, short group, short mask) { m_multiBodies.push_back(body); } void btMultiBodyDynamicsWorld::removeMultiBody(btMultiBody* body) { m_multiBodies.remove(body); } void btMultiBodyDynamicsWorld::calculateSimulationIslands() { BT_PROFILE("calculateSimulationIslands"); getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher()); { //merge islands based on speculative contact manifolds too for (int i=0;i<this->m_predictiveManifolds.size();i++) { btPersistentManifold* manifold = m_predictiveManifolds[i]; const btCollisionObject* colObj0 = manifold->getBody0(); const btCollisionObject* colObj1 = manifold->getBody1(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } { int i; int numConstraints = int(m_constraints.size()); for (i=0;i< numConstraints ; i++ ) { btTypedConstraint* constraint = m_constraints[i]; if (constraint->isEnabled()) { const btRigidBody* colObj0 = &constraint->getRigidBodyA(); const btRigidBody* colObj1 = &constraint->getRigidBodyB(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } } //merge islands linked by Featherstone link colliders for (int i=0;i<m_multiBodies.size();i++) { btMultiBody* body = m_multiBodies[i]; { btMultiBodyLinkCollider* prev = body->getBaseCollider(); for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* cur = body->getLink(b).m_collider; if (((cur) && (!(cur)->isStaticOrKinematicObject())) && ((prev) && (!(prev)->isStaticOrKinematicObject()))) { int tagPrev = prev->getIslandTag(); int tagCur = cur->getIslandTag(); getSimulationIslandManager()->getUnionFind().unite(tagPrev, tagCur); } if (cur && !cur->isStaticOrKinematicObject()) prev = cur; } } } //merge islands linked by multibody constraints { for (int i=0;i<this->m_multiBodyConstraints.size();i++) { btMultiBodyConstraint* c = m_multiBodyConstraints[i]; int tagA = c->getIslandIdA(); int tagB = c->getIslandIdB(); if (tagA>=0 && tagB>=0) getSimulationIslandManager()->getUnionFind().unite(tagA, tagB); } } //Store the island id in each body getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld()); } void btMultiBodyDynamicsWorld::updateActivationState(btScalar timeStep) { BT_PROFILE("btMultiBodyDynamicsWorld::updateActivationState"); for ( int i=0;i<m_multiBodies.size();i++) { btMultiBody* body = m_multiBodies[i]; if (body) { body->checkMotionAndSleepIfRequired(timeStep); if (!body->isAwake()) { btMultiBodyLinkCollider* col = body->getBaseCollider(); if (col && col->getActivationState() == ACTIVE_TAG) { col->setActivationState( WANTS_DEACTIVATION); col->setDeactivationTime(0.f); } for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* col = body->getLink(b).m_collider; if (col && col->getActivationState() == ACTIVE_TAG) { col->setActivationState( WANTS_DEACTIVATION); col->setDeactivationTime(0.f); } } } else { btMultiBodyLinkCollider* col = body->getBaseCollider(); if (col && col->getActivationState() != DISABLE_DEACTIVATION) col->setActivationState( ACTIVE_TAG ); for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* col = body->getLink(b).m_collider; if (col && col->getActivationState() != DISABLE_DEACTIVATION) col->setActivationState( ACTIVE_TAG ); } } } } btDiscreteDynamicsWorld::updateActivationState(timeStep); } SIMD_FORCE_INLINE int btGetConstraintIslandId2(const btTypedConstraint* lhs) { int islandId; const btCollisionObject& rcolObj0 = lhs->getRigidBodyA(); const btCollisionObject& rcolObj1 = lhs->getRigidBodyB(); islandId= rcolObj0.getIslandTag()>=0?rcolObj0.getIslandTag():rcolObj1.getIslandTag(); return islandId; } class btSortConstraintOnIslandPredicate2 { public: bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) const { int rIslandId0,lIslandId0; rIslandId0 = btGetConstraintIslandId2(rhs); lIslandId0 = btGetConstraintIslandId2(lhs); return lIslandId0 < rIslandId0; } }; SIMD_FORCE_INLINE int btGetMultiBodyConstraintIslandId(const btMultiBodyConstraint* lhs) { int islandId; int islandTagA = lhs->getIslandIdA(); int islandTagB = lhs->getIslandIdB(); islandId= islandTagA>=0?islandTagA:islandTagB; return islandId; } class btSortMultiBodyConstraintOnIslandPredicate { public: bool operator() ( const btMultiBodyConstraint* lhs, const btMultiBodyConstraint* rhs ) const { int rIslandId0,lIslandId0; rIslandId0 = btGetMultiBodyConstraintIslandId(rhs); lIslandId0 = btGetMultiBodyConstraintIslandId(lhs); return lIslandId0 < rIslandId0; } }; struct MultiBodyInplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback { btContactSolverInfo* m_solverInfo; btMultiBodyConstraintSolver* m_solver; btMultiBodyConstraint** m_multiBodySortedConstraints; int m_numMultiBodyConstraints; btTypedConstraint** m_sortedConstraints; int m_numConstraints; btIDebugDraw* m_debugDrawer; btDispatcher* m_dispatcher; btAlignedObjectArray<btCollisionObject*> m_bodies; btAlignedObjectArray<btPersistentManifold*> m_manifolds; btAlignedObjectArray<btTypedConstraint*> m_constraints; btAlignedObjectArray<btMultiBodyConstraint*> m_multiBodyConstraints; MultiBodyInplaceSolverIslandCallback( btMultiBodyConstraintSolver* solver, btDispatcher* dispatcher) :m_solverInfo(NULL), m_solver(solver), m_multiBodySortedConstraints(NULL), m_numConstraints(0), m_debugDrawer(NULL), m_dispatcher(dispatcher) { } MultiBodyInplaceSolverIslandCallback& operator=(MultiBodyInplaceSolverIslandCallback& other) { btAssert(0); (void)other; return *this; } SIMD_FORCE_INLINE void setup ( btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btMultiBodyConstraint** sortedMultiBodyConstraints, int numMultiBodyConstraints, btIDebugDraw* debugDrawer) { btAssert(solverInfo); m_solverInfo = solverInfo; m_multiBodySortedConstraints = sortedMultiBodyConstraints; m_numMultiBodyConstraints = numMultiBodyConstraints; m_sortedConstraints = sortedConstraints; m_numConstraints = numConstraints; m_debugDrawer = debugDrawer; m_bodies.resize (0); m_manifolds.resize (0); m_constraints.resize (0); m_multiBodyConstraints.resize(0); } virtual void processIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId) { if (islandId<0) { ///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id m_solver->solveMultiBodyGroup( bodies,numBodies,manifolds, numManifolds,m_sortedConstraints, m_numConstraints, &m_multiBodySortedConstraints[0],m_numConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher); } else { //also add all non-contact constraints/joints for this island btTypedConstraint** startConstraint = 0; btMultiBodyConstraint** startMultiBodyConstraint = 0; int numCurConstraints = 0; int numCurMultiBodyConstraints = 0; int i; //find the first constraint for this island for (i=0;i<m_numConstraints;i++) { if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId) { startConstraint = &m_sortedConstraints[i]; break; } } //count the number of constraints in this island for (;i<m_numConstraints;i++) { if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId) { numCurConstraints++; } } for (i=0;i<m_numMultiBodyConstraints;i++) { if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId) { startMultiBodyConstraint = &m_multiBodySortedConstraints[i]; break; } } //count the number of multi body constraints in this island for (;i<m_numMultiBodyConstraints;i++) { if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId) { numCurMultiBodyConstraints++; } } if (m_solverInfo->m_minimumSolverBatchSize<=1) { m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher); } else { for (i=0;i<numBodies;i++) m_bodies.push_back(bodies[i]); for (i=0;i<numManifolds;i++) m_manifolds.push_back(manifolds[i]); for (i=0;i<numCurConstraints;i++) m_constraints.push_back(startConstraint[i]); for (i=0;i<numCurMultiBodyConstraints;i++) m_multiBodyConstraints.push_back(startMultiBodyConstraint[i]); if ((m_constraints.size()+m_manifolds.size())>m_solverInfo->m_minimumSolverBatchSize) { processConstraints(); } else { //printf("deferred\n"); } } } } void processConstraints() { btCollisionObject** bodies = m_bodies.size()? &m_bodies[0]:0; btPersistentManifold** manifold = m_manifolds.size()?&m_manifolds[0]:0; btTypedConstraint** constraints = m_constraints.size()?&m_constraints[0]:0; btMultiBodyConstraint** multiBodyConstraints = m_multiBodyConstraints.size() ? &m_multiBodyConstraints[0] : 0; //printf("mb contacts = %d, mb constraints = %d\n", mbContacts, m_multiBodyConstraints.size()); m_solver->solveMultiBodyGroup( bodies,m_bodies.size(),manifold, m_manifolds.size(),constraints, m_constraints.size() ,multiBodyConstraints, m_multiBodyConstraints.size(), *m_solverInfo,m_debugDrawer,m_dispatcher); m_bodies.resize(0); m_manifolds.resize(0); m_constraints.resize(0); m_multiBodyConstraints.resize(0); } }; btMultiBodyDynamicsWorld::btMultiBodyDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btMultiBodyConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration) :btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration), m_multiBodyConstraintSolver(constraintSolver) { //split impulse is not yet supported for Featherstone hierarchies getSolverInfo().m_splitImpulse = false; getSolverInfo().m_solverMode |=SOLVER_USE_2_FRICTION_DIRECTIONS; m_solverMultiBodyIslandCallback = new MultiBodyInplaceSolverIslandCallback(constraintSolver,dispatcher); } btMultiBodyDynamicsWorld::~btMultiBodyDynamicsWorld () { delete m_solverMultiBodyIslandCallback; } void btMultiBodyDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) { btAlignedObjectArray<btScalar> scratch_r; btAlignedObjectArray<btVector3> scratch_v; btAlignedObjectArray<btMatrix3x3> scratch_m; BT_PROFILE("solveConstraints"); m_sortedConstraints.resize( m_constraints.size()); int i; for (i=0;i<getNumConstraints();i++) { m_sortedConstraints[i] = m_constraints[i]; } m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate2()); btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0; m_sortedMultiBodyConstraints.resize(m_multiBodyConstraints.size()); for (i=0;i<m_multiBodyConstraints.size();i++) { m_sortedMultiBodyConstraints[i] = m_multiBodyConstraints[i]; } m_sortedMultiBodyConstraints.quickSort(btSortMultiBodyConstraintOnIslandPredicate()); btMultiBodyConstraint** sortedMultiBodyConstraints = m_sortedMultiBodyConstraints.size() ? &m_sortedMultiBodyConstraints[0] : 0; m_solverMultiBodyIslandCallback->setup(&solverInfo,constraintsPtr,m_sortedConstraints.size(),sortedMultiBodyConstraints,m_sortedMultiBodyConstraints.size(), getDebugDrawer()); m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds()); /// solve all the constraints for this island m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),m_solverMultiBodyIslandCallback); { BT_PROFILE("btMultiBody addForce and stepVelocities"); for (int i=0;i<this->m_multiBodies.size();i++) { btMultiBody* bod = m_multiBodies[i]; bool isSleeping = false; if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING) { isSleeping = true; } for (int b=0;b<bod->getNumLinks();b++) { if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING) isSleeping = true; } if (!isSleeping) { //useless? they get resized in stepVelocities once again (AND DIFFERENTLY) scratch_r.resize(bod->getNumLinks()+1); //multidof? ("Y"s use it and it is used to store qdd) scratch_v.resize(bod->getNumLinks()+1); scratch_m.resize(bod->getNumLinks()+1); bod->addBaseForce(m_gravity * bod->getBaseMass()); for (int j = 0; j < bod->getNumLinks(); ++j) { bod->addLinkForce(j, m_gravity * bod->getLinkMass(j)); } bool doNotUpdatePos = false; if(bod->isMultiDof()) { if(!bod->isUsingRK4Integration()) { bod->stepVelocitiesMultiDof(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m); } else { // int numDofs = bod->getNumDofs() + 6; int numPosVars = bod->getNumPosVars() + 7; btAlignedObjectArray<btScalar> scratch_r2; scratch_r2.resize(2*numPosVars + 8*numDofs); //convenience btScalar *pMem = &scratch_r2[0]; btScalar *scratch_q0 = pMem; pMem += numPosVars; btScalar *scratch_qx = pMem; pMem += numPosVars; btScalar *scratch_qd0 = pMem; pMem += numDofs; btScalar *scratch_qd1 = pMem; pMem += numDofs; btScalar *scratch_qd2 = pMem; pMem += numDofs; btScalar *scratch_qd3 = pMem; pMem += numDofs; btScalar *scratch_qdd0 = pMem; pMem += numDofs; btScalar *scratch_qdd1 = pMem; pMem += numDofs; btScalar *scratch_qdd2 = pMem; pMem += numDofs; btScalar *scratch_qdd3 = pMem; pMem += numDofs; btAssert((pMem - (2*numPosVars + 8*numDofs)) == &scratch_r2[0]); ///// //copy q0 to scratch_q0 and qd0 to scratch_qd0 scratch_q0[0] = bod->getWorldToBaseRot().x(); scratch_q0[1] = bod->getWorldToBaseRot().y(); scratch_q0[2] = bod->getWorldToBaseRot().z(); scratch_q0[3] = bod->getWorldToBaseRot().w(); scratch_q0[4] = bod->getBasePos().x(); scratch_q0[5] = bod->getBasePos().y(); scratch_q0[6] = bod->getBasePos().z(); // for(int link = 0; link < bod->getNumLinks(); ++link) { for(int dof = 0; dof < bod->getLink(link).m_posVarCount; ++dof) scratch_q0[7 + bod->getLink(link).m_cfgOffset + dof] = bod->getLink(link).m_jointPos[dof]; } // for(int dof = 0; dof < numDofs; ++dof) scratch_qd0[dof] = bod->getVelocityVector()[dof]; //// struct { btMultiBody *bod; btScalar *scratch_qx, *scratch_q0; void operator()() { for(int dof = 0; dof < bod->getNumPosVars() + 7; ++dof) scratch_qx[dof] = scratch_q0[dof]; } } pResetQx = {bod, scratch_qx, scratch_q0}; // struct { void operator()(btScalar dt, const btScalar *pDer, const btScalar *pCurVal, btScalar *pVal, int size) { for(int i = 0; i < size; ++i) pVal[i] = pCurVal[i] + dt * pDer[i]; } } pEulerIntegrate; // struct { void operator()(btMultiBody *pBody, const btScalar *pData) { btScalar *pVel = const_cast<btScalar*>(pBody->getVelocityVector()); for(int i = 0; i < pBody->getNumDofs() + 6; ++i) pVel[i] = pData[i]; } } pCopyToVelocityVector; // struct { void operator()(const btScalar *pSrc, btScalar *pDst, int start, int size) { for(int i = 0; i < size; ++i) pDst[i] = pSrc[start + i]; } } pCopy; // btScalar h = solverInfo.m_timeStep; #define output &scratch_r[bod->getNumDofs()] //calc qdd0 from: q0 & qd0 bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd0, 0, numDofs); //calc q1 = q0 + h/2 * qd0 pResetQx(); bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd0); //calc qd1 = qd0 + h/2 * qdd0 pEulerIntegrate(btScalar(.5)*h, scratch_qdd0, scratch_qd0, scratch_qd1, numDofs); // //calc qdd1 from: q1 & qd1 pCopyToVelocityVector(bod, scratch_qd1); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd1, 0, numDofs); //calc q2 = q0 + h/2 * qd1 pResetQx(); bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd1); //calc qd2 = qd0 + h/2 * qdd1 pEulerIntegrate(btScalar(.5)*h, scratch_qdd1, scratch_qd0, scratch_qd2, numDofs); // //calc qdd2 from: q2 & qd2 pCopyToVelocityVector(bod, scratch_qd2); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd2, 0, numDofs); //calc q3 = q0 + h * qd2 pResetQx(); bod->stepPositionsMultiDof(h, scratch_qx, scratch_qd2); //calc qd3 = qd0 + h * qdd2 pEulerIntegrate(h, scratch_qdd2, scratch_qd0, scratch_qd3, numDofs); // //calc qdd3 from: q3 & qd3 pCopyToVelocityVector(bod, scratch_qd3); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd3, 0, numDofs); // //calc q = q0 + h/6(qd0 + 2*(qd1 + qd2) + qd3) //calc qd = qd0 + h/6(qdd0 + 2*(qdd1 + qdd2) + qdd3) btAlignedObjectArray<btScalar> delta_q; delta_q.resize(numDofs); btAlignedObjectArray<btScalar> delta_qd; delta_qd.resize(numDofs); for(int i = 0; i < numDofs; ++i) { delta_q[i] = h/btScalar(6.)*(scratch_qd0[i] + 2*scratch_qd1[i] + 2*scratch_qd2[i] + scratch_qd3[i]); delta_qd[i] = h/btScalar(6.)*(scratch_qdd0[i] + 2*scratch_qdd1[i] + 2*scratch_qdd2[i] + scratch_qdd3[i]); //delta_q[i] = h*scratch_qd0[i]; //delta_qd[i] = h*scratch_qdd0[i]; } // pCopyToVelocityVector(bod, scratch_qd0); bod->applyDeltaVeeMultiDof(&delta_qd[0], 1); // if(!doNotUpdatePos) { btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector()); pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs(); for(int i = 0; i < numDofs; ++i) pRealBuf[i] = delta_q[i]; //bod->stepPositionsMultiDof(1, 0, &delta_q[0]); bod->setPosUpdated(true); } //ugly hack which resets the cached data to t0 (needed for constraint solver) { for(int link = 0; link < bod->getNumLinks(); ++link) bod->getLink(link).updateCacheMultiDof(); bod->stepVelocitiesMultiDof(0, scratch_r, scratch_v, scratch_m); } } } else//if(bod->isMultiDof()) { bod->stepVelocities(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m); } bod->clearForcesAndTorques(); }//if (!isSleeping) } } m_solverMultiBodyIslandCallback->processConstraints(); m_constraintSolver->allSolved(solverInfo, m_debugDrawer); } void btMultiBodyDynamicsWorld::integrateTransforms(btScalar timeStep) { btDiscreteDynamicsWorld::integrateTransforms(timeStep); { BT_PROFILE("btMultiBody stepPositions"); //integrate and update the Featherstone hierarchies btAlignedObjectArray<btQuaternion> world_to_local; btAlignedObjectArray<btVector3> local_origin; for (int b=0;b<m_multiBodies.size();b++) { btMultiBody* bod = m_multiBodies[b]; bool isSleeping = false; if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING) { isSleeping = true; } for (int b=0;b<bod->getNumLinks();b++) { if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING) isSleeping = true; } if (!isSleeping) { int nLinks = bod->getNumLinks(); ///base + num m_links world_to_local.resize(nLinks+1); local_origin.resize(nLinks+1); if(bod->isMultiDof()) { if(!bod->isPosUpdated()) bod->stepPositionsMultiDof(timeStep); else { btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector()); pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs(); bod->stepPositionsMultiDof(1, 0, pRealBuf); bod->setPosUpdated(false); } } else bod->stepPositions(timeStep); world_to_local[0] = bod->getWorldToBaseRot(); local_origin[0] = bod->getBasePos(); if (bod->getBaseCollider()) { btVector3 posr = local_origin[0]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); bod->getBaseCollider()->setWorldTransform(tr); } for (int k=0;k<bod->getNumLinks();k++) { const int parent = bod->getParent(k); world_to_local[k+1] = bod->getParentToLocalRot(k) * world_to_local[parent+1]; local_origin[k+1] = local_origin[parent+1] + (quatRotate(world_to_local[k+1].inverse() , bod->getRVector(k))); } for (int m=0;m<bod->getNumLinks();m++) { btMultiBodyLinkCollider* col = bod->getLink(m).m_collider; if (col) { int link = col->m_link; btAssert(link == m); int index = link+1; btVector3 posr = local_origin[index]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[index].x(),-world_to_local[index].y(),-world_to_local[index].z(),world_to_local[index].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); col->setWorldTransform(tr); } } } else { bod->clearVelocities(); } } } } void btMultiBodyDynamicsWorld::addMultiBodyConstraint( btMultiBodyConstraint* constraint) { m_multiBodyConstraints.push_back(constraint); } void btMultiBodyDynamicsWorld::removeMultiBodyConstraint( btMultiBodyConstraint* constraint) { m_multiBodyConstraints.remove(constraint); } void btMultiBodyDynamicsWorld::debugDrawMultiBodyConstraint(btMultiBodyConstraint* constraint) { constraint->debugDraw(getDebugDrawer()); } void btMultiBodyDynamicsWorld::debugDrawWorld() { BT_PROFILE("btMultiBodyDynamicsWorld debugDrawWorld"); bool drawConstraints = false; if (getDebugDrawer()) { int mode = getDebugDrawer()->getDebugMode(); if (mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits)) { drawConstraints = true; } if (drawConstraints) { BT_PROFILE("btMultiBody debugDrawWorld"); btAlignedObjectArray<btQuaternion> world_to_local; btAlignedObjectArray<btVector3> local_origin; for (int c=0;c<m_multiBodyConstraints.size();c++) { btMultiBodyConstraint* constraint = m_multiBodyConstraints[c]; debugDrawMultiBodyConstraint(constraint); } for (int b = 0; b<m_multiBodies.size(); b++) { btMultiBody* bod = m_multiBodies[b]; int nLinks = bod->getNumLinks(); ///base + num m_links world_to_local.resize(nLinks + 1); local_origin.resize(nLinks + 1); world_to_local[0] = bod->getWorldToBaseRot(); local_origin[0] = bod->getBasePos(); { btVector3 posr = local_origin[0]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4] = { -world_to_local[0].x(), -world_to_local[0].y(), -world_to_local[0].z(), world_to_local[0].w() }; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3])); getDebugDrawer()->drawTransform(tr, 0.1); } for (int k = 0; k<bod->getNumLinks(); k++) { const int parent = bod->getParent(k); world_to_local[k + 1] = bod->getParentToLocalRot(k) * world_to_local[parent + 1]; local_origin[k + 1] = local_origin[parent + 1] + (quatRotate(world_to_local[k + 1].inverse(), bod->getRVector(k))); } for (int m = 0; m<bod->getNumLinks(); m++) { int link = m; int index = link + 1; btVector3 posr = local_origin[index]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4] = { -world_to_local[index].x(), -world_to_local[index].y(), -world_to_local[index].z(), world_to_local[index].w() }; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3])); getDebugDrawer()->drawTransform(tr, 0.1); } } } } btDiscreteDynamicsWorld::debugDrawWorld(); }
LauriM/PropellerEngine
thirdparty/Bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp
C++
bsd-2-clause
27,139
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ return [ 'code' => '672', 'patterns' => [ 'national' => [ 'general' => '/^[13]\\d{5}$/', 'fixed' => '/^(?:1(?:06|17|28|39)|3[012]\\d)\\d{3}$/', 'mobile' => '/^38\\d{4}$/', 'emergency' => '/^9(?:11|55|77)$/', ], 'possible' => [ 'general' => '/^\\d{5,6}$/', 'emergency' => '/^\\d{3}$/', ], ], ];
Urbannet/cleanclean
yii2/vendor/zendframework/zend-i18n/src/Validator/PhoneNumber/NF.php
PHP
bsd-3-clause
720
<?php require_once('../../config.php'); require_once('lib.php'); require_once('edit_form.php'); $cmid = required_param('cmid', PARAM_INT); // Course Module ID $id = optional_param('id', 0, PARAM_INT); // EntryID if (!$cm = get_coursemodule_from_id('glossary', $cmid)) { print_error('invalidcoursemodule'); } if (!$course = $DB->get_record('course', array('id'=>$cm->course))) { print_error('coursemisconf'); } require_login($course, false, $cm); $context = context_module::instance($cm->id); if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) { print_error('invalidid', 'glossary'); } $url = new moodle_url('/mod/glossary/edit.php', array('cmid'=>$cm->id)); if (!empty($id)) { $url->param('id', $id); } $PAGE->set_url($url); if ($id) { // if entry is specified if (isguestuser()) { print_error('guestnoedit', 'glossary', "$CFG->wwwroot/mod/glossary/view.php?id=$cmid"); } if (!$entry = $DB->get_record('glossary_entries', array('id'=>$id, 'glossaryid'=>$glossary->id))) { print_error('invalidentry'); } $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways); if (!has_capability('mod/glossary:manageentries', $context) and !($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context)))) { if ($USER->id != $entry->userid) { print_error('errcannoteditothers', 'glossary', "view.php?id=$cm->id&amp;mode=entry&amp;hook=$id"); } elseif (!$ineditperiod) { print_error('erredittimeexpired', 'glossary', "view.php?id=$cm->id&amp;mode=entry&amp;hook=$id"); } } //prepare extra data if ($aliases = $DB->get_records_menu("glossary_alias", array("entryid"=>$id), '', 'id, alias')) { $entry->aliases = implode("\n", $aliases) . "\n"; } if ($categoriesarr = $DB->get_records_menu("glossary_entries_categories", array('entryid'=>$id), '', 'id, categoryid')) { // TODO: this fetches cats from both main and secondary glossary :-( $entry->categories = array_values($categoriesarr); } } else { // new entry require_capability('mod/glossary:write', $context); // note: guest user does not have any write capability $entry = new stdClass(); $entry->id = null; } list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry); $entry = file_prepare_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry', $entry->id); $entry = file_prepare_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary', 'attachment', $entry->id); $entry->cmid = $cm->id; // create form and set initial data $mform = new mod_glossary_entry_form(null, array('current'=>$entry, 'cm'=>$cm, 'glossary'=>$glossary, 'definitionoptions'=>$definitionoptions, 'attachmentoptions'=>$attachmentoptions)); if ($mform->is_cancelled()){ if ($id){ redirect("view.php?id=$cm->id&mode=entry&hook=$id"); } else { redirect("view.php?id=$cm->id"); } } else if ($data = $mform->get_data()) { $entry = glossary_edit_entry($data, $course, $cm, $glossary, $context); if (core_tag_tag::is_enabled('mod_glossary', 'glossary_entries') && isset($data->tags)) { core_tag_tag::set_item_tags('mod_glossary', 'glossary_entries', $data->id, $context, $data->tags); } redirect("view.php?id=$cm->id&mode=entry&hook=$entry->id"); } if (!empty($id)) { $PAGE->navbar->add(get_string('edit')); } $PAGE->set_title($glossary->name); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); echo $OUTPUT->heading(format_string($glossary->name), 2); if ($glossary->intro) { echo $OUTPUT->box(format_module_intro('glossary', $glossary, $cm->id), 'generalbox', 'intro'); } $data = new StdClass(); $data->tags = core_tag_tag::get_item_tags_array('mod_glossary', 'glossary_entries', $id); $mform->set_data($data); $mform->display(); echo $OUTPUT->footer();
evltuma/moodle
mod/glossary/edit.php
PHP
gpl-3.0
4,125
// Copyright 2013 the V8 project authors. All rights reserved. // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. description( "This test checks that the following expressions or statements are valid ECMASCRIPT code or should throw parse error" ); function runTest(_a, errorType) { var success; if (typeof _a != "string") testFailed("runTest expects string argument: " + _a); try { eval(_a); success = true; } catch (e) { success = !(e instanceof SyntaxError); } if ((!!errorType) == !success) { if (errorType) testPassed('Invalid: "' + _a + '"'); else testPassed('Valid: "' + _a + '"'); } else { if (errorType) testFailed('Invalid: "' + _a + '" should throw ' + errorType.name); else testFailed('Valid: "' + _a + '" should NOT throw '); } } function valid(_a) { // Test both the grammar and the syntax checker runTest(_a, false); runTest("function f() { " + _a + " }", false); } function invalid(_a, _type) { _type = _type || SyntaxError; // Test both the grammar and the syntax checker runTest(_a, true); runTest("function f() { " + _a + " }", true); } // known issue: // some statements requires statement as argument, and // it seems the End-Of-File terminator is converted to semicolon // "a:[EOF]" is not parse error, while "{ a: }" is parse error // "if (a)[EOF]" is not parse error, while "{ if (a) }" is parse error // known issues of bison parser: // accepts: 'function f() { return 6 + }' (only inside a function declaration) // some comma expressions: see reparsing-semicolon-insertion.js debug ("Unary operators and member access"); valid (""); invalid("(a"); invalid("a[5"); invalid("a[5 + 6"); invalid("a."); invalid("()"); invalid("a.'l'"); valid ("a: +~!new a"); invalid("new -a"); valid ("new (-1)") valid ("a: b: c: new f(x++)++") valid ("(a)++"); valid ("(1--).x"); invalid("a-- ++"); invalid("(a:) --b"); valid ("++ -- ++ a"); valid ("++ new new a ++"); valid ("delete void 0"); invalid("delete the void"); invalid("(a++"); valid ("++a--"); valid ("++((a))--"); valid ("(a.x++)++"); invalid("1: null"); invalid("+-!~"); invalid("+-!~(("); invalid("a)"); invalid("a]"); invalid(".l"); invalid("1.l"); valid ("1 .l"); debug ("Binary and conditional operators"); valid ("a + + typeof this"); invalid("a + * b"); invalid("a ? b"); invalid("a ? b :"); invalid("%a"); invalid("a-"); valid ("a = b ? b = c : d = e"); valid ("s: a[1].l ? b.l['s'] ? c++ : d : true"); valid ("a ? b + 1 ? c + 3 * d.l : d[5][6] : e"); valid ("a in b instanceof delete -c"); invalid("a in instanceof b.l"); valid ("- - true % 5"); invalid("- false = 3"); valid ("a: b: c: (1 + null) = 3"); valid ("a[2] = b.l += c /= 4 * 7 ^ !6"); invalid("a + typeof b += c in d"); invalid("typeof a &= typeof b"); valid ("a: ((typeof (a))) >>>= a || b.l && c"); valid ("a: b: c[a /= f[a %= b]].l[c[x] = 7] -= a ? b <<= f : g"); valid ("-void+x['y'].l == x.l != 5 - f[7]"); debug ("Function calls (and new with arguments)"); valid ("a()()()"); valid ("s: l: a[2](4 == 6, 5 = 6)(f[4], 6)"); valid ("s: eval(a.apply(), b.call(c[5] - f[7]))"); invalid("a("); invalid("a(5"); invalid("a(5,"); invalid("a(5,)"); invalid("a(5,6"); valid ("a(b[7], c <d> e.l, new a() > b)"); invalid("a(b[5)"); invalid("a(b.)"); valid ("~new new a(1)(i++)(c[l])"); invalid("a(*a)"); valid ("((((a))((b)()).l))()"); valid ("(a)[b + (c) / (d())].l--"); valid ("new (5)"); invalid("new a(5"); valid ("new (f + 5)(6, (g)() - 'l'() - true(false))"); invalid("a(.length)"); debug ("function declaration and expression"); valid ("function f() {}"); valid ("function f(a,b) {}"); invalid("function () {}"); invalid("function f(a b) {}"); invalid("function f(a,) {}"); invalid("function f(a,"); invalid("function f(a, 1) {}"); valid ("function g(arguments, eval) {}"); valid ("function f() {} + function g() {}"); invalid("(function a{})"); invalid("(function this(){})"); valid ("(delete new function f(){} + function(a,b){}(5)(6))"); valid ("6 - function (m) { function g() {} }"); invalid("function l() {"); invalid("function l++(){}"); debug ("Array and object literal, comma operator"); // Note these are tested elsewhere, no need to repeat those tests here valid ("[] in [5,6] * [,5,] / [,,5,,] || [a,] && new [,b] % [,,]"); invalid("[5,"); invalid("[,"); invalid("(a,)"); valid ("1 + {get get(){}, set set(a){}, get1:4, set1:get-set, }"); invalid("1 + {a"); invalid("1 + {a:"); invalid("1 + {get l("); invalid(",a"); valid ("(4,(5,a(3,4))),f[4,a-6]"); invalid("(,f)"); invalid("a,,b"); invalid("a ? b, c : d"); debug ("simple statements"); valid ("{ }"); invalid("{ { }"); valid ("{ ; ; ; }"); valid ("a: { ; }"); invalid("{ a: }"); valid ("{} f; { 6 + f() }"); valid ("{ a[5],6; {} ++b-new (-5)() } c().l++"); valid ("{ l1: l2: l3: { this } a = 32 ; { i++ ; { { { } } ++i } } }"); valid ("if (a) ;"); invalid("{ if (a) }"); invalid("if a {}"); invalid("if (a"); invalid("if (a { }"); valid ("x: s: if (a) ; else b"); invalid("else {}"); valid ("if (a) if (b) y; else {} else ;"); invalid("if (a) {} else x; else"); invalid("if (a) { else }"); valid ("if (a.l + new b()) 4 + 5 - f()"); valid ("if (a) with (x) ; else with (y) ;"); invalid("with a.b { }"); valid ("while (a() - new b) ;"); invalid("while a {}"); valid ("do ; while(0) i++"); // Is this REALLY valid? (Firefox also accepts this) valid ("do if (a) x; else y; while(z)"); invalid("do g; while 4"); invalid("do g; while ((4)"); valid ("{ { do do do ; while(0) while(0) while(0) } }"); valid ("do while (0) if (a) {} else y; while(0)"); valid ("if (a) while (b) if (c) with(d) {} else e; else f"); invalid("break ; break your_limits ; continue ; continue living ; debugger"); invalid("debugger X"); invalid("break 0.2"); invalid("continue a++"); invalid("continue (my_friend)"); valid ("while (1) break"); valid ("do if (a) with (b) continue; else debugger; while (false)"); invalid("do if (a) while (false) else debugger"); invalid("while if (a) ;"); valid ("if (a) function f() {} else function g() {}"); valid ("if (a()) while(0) function f() {} else function g() {}"); invalid("if (a()) function f() { else function g() }"); invalid("if (a) if (b) ; else function f {}"); invalid("if (a) if (b) ; else function (){}"); valid ("throw a"); valid ("throw a + b in void c"); invalid("throw"); debug ("var and const statements"); valid ("var a, b = null"); valid ("const a = 5, b, c"); invalid("var"); invalid("var = 7"); invalid("var c (6)"); valid ("if (a) var a,b; else const b, c"); invalid("var 5 = 6"); valid ("while (0) var a, b, c=6, d, e, f=5*6, g=f*h, h"); invalid("var a = if (b) { c }"); invalid("var a = var b"); valid ("const a = b += c, a, a, a = (b - f())"); invalid("var a %= b | 5"); invalid("var (a) = 5"); invalid("var a = (4, b = 6"); invalid("const 'l' = 3"); invalid("var var = 3"); valid ("var varr = 3 in 1"); valid ("const a, a, a = void 7 - typeof 8, a = 8"); valid ("const x_x = 6 /= 7 ? e : f"); invalid("var a = ?"); invalid("const a = *7"); invalid("var a = :)"); valid ("var a = a in b in c instanceof d"); invalid("var a = b ? c, b"); invalid("const a = b : c"); debug ("for statement"); valid ("for ( ; ; ) { break }"); valid ("for ( a ; ; ) { break }"); valid ("for ( ; a ; ) { break }"); valid ("for ( ; ; a ) { break }"); valid ("for ( a ; a ; ) break"); valid ("for ( a ; ; a ) break"); valid ("for ( ; a ; a ) break"); invalid("for () { }"); invalid("for ( a ) { }"); invalid("for ( ; ) ;"); invalid("for a ; b ; c { }"); invalid("for (a ; { }"); invalid("for ( a ; ) ;"); invalid("for ( ; a ) break"); valid ("for (var a, b ; ; ) { break } "); valid ("for (var a = b, b = a ; ; ) break"); valid ("for (var a = b, c, d, b = a ; x in b ; ) { break }"); valid ("for (var a = b, c, d ; ; 1 in a()) break"); invalid("for ( ; var a ; ) break"); invalid("for (const a; ; ) break"); invalid("for ( %a ; ; ) { }"); valid ("for (a in b) break"); valid ("for (a() in b) break"); valid ("for (a().l[4] in b) break"); valid ("for (new a in b in c in d) break"); valid ("for (new new new a in b) break"); invalid("for (delete new a() in b) break"); invalid("for (a * a in b) break"); valid ("for ((a * a) in b) break"); invalid("for (a++ in b) break"); valid ("for ((a++) in b) break"); invalid("for (++a in b) break"); valid ("for ((++a) in b) break"); invalid("for (a, b in c) break"); invalid("for (a,b in c ;;) break"); valid ("for (a,(b in c) ;;) break"); valid ("for ((a, b) in c) break"); invalid("for (a ? b : c in c) break"); valid ("for ((a ? b : c) in c) break"); valid ("for (var a in b in c) break"); valid ("for (var a = 5 += 6 in b) break"); invalid("for (var a += 5 in b) break"); invalid("for (var a = in b) break"); invalid("for (var a, b in b) break"); invalid("for (var a = -6, b in b) break"); invalid("for (var a, b = 8 in b) break"); valid ("for (var a = (b in c) in d) break"); invalid("for (var a = (b in c in d) break"); invalid("for (var (a) in b) { }"); valid ("for (var a = 7, b = c < d >= d ; f()[6]++ ; --i()[1]++ ) {}"); debug ("try statement"); invalid("try { break } catch(e) {}"); valid ("try {} finally { c++ }"); valid ("try { with (x) { } } catch(e) {} finally { if (a) ; }"); invalid("try {}"); invalid("catch(e) {}"); invalid("finally {}"); invalid("try a; catch(e) {}"); invalid("try {} catch(e) a()"); invalid("try {} finally a()"); invalid("try {} catch(e)"); invalid("try {} finally"); invalid("try {} finally {} catch(e) {}"); invalid("try {} catch (...) {}"); invalid("try {} catch {}"); valid ("if (a) try {} finally {} else b;"); valid ("if (--a()) do with(1) try {} catch(ke) { f() ; g() } while (a in b) else {}"); invalid("if (a) try {} else b; catch (e) { }"); invalid("try { finally {}"); debug ("switch statement"); valid ("switch (a) {}"); invalid("switch () {}"); invalid("case 5:"); invalid("default:"); invalid("switch (a) b;"); invalid("switch (a) case 3: b;"); valid ("switch (f()) { case 5 * f(): default: case '6' - 9: ++i }"); invalid("switch (true) { default: case 6: default: }"); invalid("switch (l) { f(); }"); invalid("switch (l) { case 1: ; a: case 5: }"); valid ("switch (g() - h[5].l) { case 1 + 6: a: b: c: ++f }"); invalid("switch (g) { case 1: a: }"); invalid("switch (g) { case 1: a: default: }"); invalid("switch g { case 1: l() }"); invalid("switch (g) { case 1:"); valid ("switch (l) { case a = b ? c : d : }"); valid ("switch (sw) { case a ? b - 7[1] ? [c,,] : d = 6 : { } : }"); invalid("switch (l) { case b ? c : }"); valid ("switch (l) { case 1: a: with(g) switch (g) { case 2: default: } default: }"); invalid("switch (4 - ) { }"); invalid("switch (l) { default case: 5; }"); invalid("L: L: ;"); invalid("L: L1: L: ;"); invalid("L: L1: L2: L3: L4: L: ;"); invalid("for(var a,b 'this shouldn\'t be allowed' false ; ) ;"); invalid("for(var a,b '"); valid("function __proto__(){}") valid("(function __proto__(){})") valid("'use strict'; function __proto__(){}") valid("'use strict'; (function __proto__(){})") valid("if (0) $foo; ") valid("if (0) _foo; ") valid("if (0) foo$; ") valid("if (0) foo_; ") valid("if (0) obj.$foo; ") valid("if (0) obj._foo; ") valid("if (0) obj.foo$; ") valid("if (0) obj.foo_; ") valid("if (0) obj.foo\\u03bb; ") valid("if (0) new a(b+c).d = 5"); valid("if (0) new a(b+c) = 5"); valid("([1 || 1].a = 1)"); valid("({a: 1 || 1}.a = 1)"); invalid("var a.b = c"); invalid("var a.b;"); try { eval("a.b.c = {};"); } catch(e1) { e=e1; shouldBe("e.line", "1") } foo = 'FAIL'; bar = 'PASS'; try { eval("foo = 'PASS'; a.b.c = {}; bar = 'FAIL';"); } catch(e) { shouldBe("foo", "'PASS'"); shouldBe("bar", "'PASS'"); }
victorzhao/miniblink49
v8_4_5/test/webkit/fast/js/parser-syntax-check.js
JavaScript
gpl-3.0
13,137
require File.expand_path('../../../spec_helper', __FILE__) require 'date' describe "Date.ajd_to_amjd" do it "needs to be reviewed for spec completeness" end
takano32/rubinius
spec/ruby/library/date/ajd_to_amjd_spec.rb
Ruby
bsd-3-clause
160
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Abstract class for the transformations plugins * * @package PhpMyAdmin */ if (! defined('PHPMYADMIN')) { exit; } /* It also implements the transformations interface */ require_once 'TransformationsInterface.int.php'; /** * Provides a common interface that will have to * be implemented by all of the transformations plugins. * * @package PhpMyAdmin */ abstract class TransformationsPlugin implements TransformationsInterface { /** * Does the actual work of each specific transformations plugin. * * @param array $options transformation options * * @return void */ public function applyTransformationNoWrap($options = array()) { ; } /** * Does the actual work of each specific transformations plugin. * * @param string $buffer text to be transformed * @param array $options transformation options * @param string $meta meta information * * @return string the transformed text */ abstract public function applyTransformation( $buffer, $options = array(), $meta = '' ); /** * Returns passed options or default values if they were not set * * @param string[] $options List of passed options * @param string[] $defaults List of default values * * @return string[] List of options possibly filled in by defaults. */ public function getOptions($options, $defaults) { $result = array(); foreach ($defaults as $key => $value) { if (isset($options[$key]) && $options[$key] !== '') { $result[$key] = $options[$key]; } else { $result[$key] = $value; } } return $result; } }
Dokaponteam/ITF_Project
xampp/phpMyAdmin/libraries/plugins/TransformationsPlugin.class.php
PHP
mit
1,804
<?php /************************************************************************************* * m68k.php * -------- * Author: Benny Baumann (BenBE@omorphia.de) * Copyright: (c) 2007 Benny Baumann (http://www.omorphia.de/), Nigel McNie (http://qbnz.com/highlighter) * Release Version: 1.0.8.11 * Date Started: 2007/02/06 * * Motorola 68000 Assembler language file for GeSHi. * * Syntax definition as commonly used by the motorola documentation for the * MC68HC908GP32 Microcontroller (and maybe others). * * CHANGES * ------- * 2008/05/23 (1.0.7.22) * - Added description of extra language features (SF#1970248) * 2007/06/02 (1.0.0) * - First Release * * TODO (updated 2007/06/02) * ------------------------- * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi 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. * * GeSHi 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 GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( 'LANG_NAME' => 'Motorola 68000 Assembler', 'COMMENT_SINGLE' => array(1 => ';'), 'COMMENT_MULTI' => array(), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '', 'KEYWORDS' => array( /*CPU*/ 1 => array( 'adc','add','ais','aix','and','asl','asr','bcc','bclr','bcs','beq', 'bge','bgt','bhcc','bhcs','bhi','bhs','bih','bil','bit','ble','blo', 'bls','blt','bmc','bmi','bms','bne','bpl','bra','brclr','brn', 'brset','bset','bsr','cbeq','clc','cli','clr','cmp','com','cphx', 'cpx','daa','dbnz','dec','div','eor','inc','jmp','jsr','lda','ldhx', 'ldx','lsl','lsr','mov','mul','neg','nop','nsa','ora','psha','pshh', 'pshx','pula','pulh','pulx','rol','ror','rsp','rti','rts','sbc', 'sec','sei','sta','sthx','stop','stx','sub','swi','tap','tax','tpa', 'tst','tsx','txa','txs','wait' ), /*registers*/ 2 => array( 'a','h','x', 'hx','sp' ), /*Directive*/ 3 => array( '#define','#endif','#else','#ifdef','#ifndef','#include','#undef', '.db','.dd','.df','.dq','.dt','.dw','.end','.org','equ' ), ), 'SYMBOLS' => array( ',' ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => false, 1 => false, 2 => false, 3 => false, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #0000ff; font-weight:bold;', 2 => 'color: #0000ff;', 3 => 'color: #46aa03; font-weight:bold;' ), 'COMMENTS' => array( 1 => 'color: #adadad; font-style: italic;', ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #0000ff;' ), 'STRINGS' => array( 0 => 'color: #7f007f;' ), 'NUMBERS' => array( 0 => 'color: #dd22dd;' ), 'METHODS' => array( ), 'SYMBOLS' => array( 0 => 'color: #008000;' ), 'REGEXPS' => array( 0 => 'color: #22bbff;', 1 => 'color: #22bbff;', 2 => 'color: #993333;' ), 'SCRIPT' => array( ) ), 'URLS' => array( 1 => '', 2 => '', 3 => '' ), 'OOLANG' => false, 'OBJECT_SPLITTERS' => array( ), 'REGEXPS' => array( //Hex numbers 0 => '#?0[0-9a-fA-F]{1,32}[hH]', //Binary numbers 1 => '\%[01]{1,64}[bB]', //Labels 2 => '^[_a-zA-Z][_a-zA-Z0-9]*?\:' ), 'STRICT_MODE_APPLIES' => GESHI_NEVER, 'SCRIPT_DELIMITERS' => array( ), 'HIGHLIGHT_STRICT_BLOCK' => array( ), 'TAB_WIDTH' => 8 );
MinecraftSnowServer/Server-Docker
web/wiki/vendor/easybook/geshi/geshi/m68k.php
PHP
mit
4,666
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import com.google.common.collect.ImmutableMap; import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.*; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.mapper.core.IntegerFieldMapper; import org.elasticsearch.index.mapper.core.StringFieldMapper; import org.elasticsearch.test.ESSingleNodeTestCase; import java.io.IOException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; public class DynamicMappingTests extends ESSingleNodeTestCase { public void testDynamicTrue() throws IOException { String mapping = jsonBuilder().startObject().startObject("type") .field("dynamic", "true") .startObject("properties") .startObject("field1").field("type", "string").endObject() .endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("test", "type", "1", jsonBuilder() .startObject() .field("field1", "value1") .field("field2", "value2") .bytes()); assertThat(doc.rootDoc().get("field1"), equalTo("value1")); assertThat(doc.rootDoc().get("field2"), equalTo("value2")); } public void testDynamicFalse() throws IOException { String mapping = jsonBuilder().startObject().startObject("type") .field("dynamic", "false") .startObject("properties") .startObject("field1").field("type", "string").endObject() .endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("test", "type", "1", jsonBuilder() .startObject() .field("field1", "value1") .field("field2", "value2") .bytes()); assertThat(doc.rootDoc().get("field1"), equalTo("value1")); assertThat(doc.rootDoc().get("field2"), nullValue()); } public void testDynamicStrict() throws IOException { String mapping = jsonBuilder().startObject().startObject("type") .field("dynamic", "strict") .startObject("properties") .startObject("field1").field("type", "string").endObject() .endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); try { defaultMapper.parse("test", "type", "1", jsonBuilder() .startObject() .field("field1", "value1") .field("field2", "value2") .bytes()); fail(); } catch (StrictDynamicMappingException e) { // all is well } try { defaultMapper.parse("test", "type", "1", XContentFactory.jsonBuilder() .startObject() .field("field1", "value1") .field("field2", (String) null) .bytes()); fail(); } catch (StrictDynamicMappingException e) { // all is well } } public void testDynamicFalseWithInnerObjectButDynamicSetOnRoot() throws IOException { String mapping = jsonBuilder().startObject().startObject("type") .field("dynamic", "false") .startObject("properties") .startObject("obj1").startObject("properties") .startObject("field1").field("type", "string").endObject() .endObject().endObject() .endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("test", "type", "1", jsonBuilder() .startObject().startObject("obj1") .field("field1", "value1") .field("field2", "value2") .endObject() .bytes()); assertThat(doc.rootDoc().get("obj1.field1"), equalTo("value1")); assertThat(doc.rootDoc().get("obj1.field2"), nullValue()); } public void testDynamicStrictWithInnerObjectButDynamicSetOnRoot() throws IOException { String mapping = jsonBuilder().startObject().startObject("type") .field("dynamic", "strict") .startObject("properties") .startObject("obj1").startObject("properties") .startObject("field1").field("type", "string").endObject() .endObject().endObject() .endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); try { defaultMapper.parse("test", "type", "1", jsonBuilder() .startObject().startObject("obj1") .field("field1", "value1") .field("field2", "value2") .endObject() .bytes()); fail(); } catch (StrictDynamicMappingException e) { // all is well } } public void testDynamicMappingOnEmptyString() throws Exception { IndexService service = createIndex("test"); client().prepareIndex("test", "type").setSource("empty_field", "").get(); MappedFieldType fieldType = service.mapperService().fullName("empty_field"); assertNotNull(fieldType); } public void testTypeNotCreatedOnIndexFailure() throws IOException, InterruptedException { XContentBuilder mapping = jsonBuilder().startObject().startObject("_default_") .field("dynamic", "strict") .endObject().endObject(); IndexService indexService = createIndex("test", Settings.EMPTY, "_default_", mapping); try { client().prepareIndex().setIndex("test").setType("type").setSource(jsonBuilder().startObject().field("test", "test").endObject()).get(); fail(); } catch (StrictDynamicMappingException e) { } GetMappingsResponse getMappingsResponse = client().admin().indices().prepareGetMappings("test").get(); assertNull(getMappingsResponse.getMappings().get("test").get("type")); } private String serialize(ToXContent mapper) throws Exception { XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); mapper.toXContent(builder, new ToXContent.MapParams(ImmutableMap.<String, String>of())); return builder.endObject().string(); } private Mapper parse(DocumentMapper mapper, DocumentMapperParser parser, XContentBuilder builder) throws Exception { Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build(); ParseContext.InternalParseContext ctx = new ParseContext.InternalParseContext(settings, parser, mapper, new ContentPath(0)); SourceToParse source = SourceToParse.source(builder.bytes()); ctx.reset(XContentHelper.createParser(source.source()), new ParseContext.Document(), source); assertEquals(XContentParser.Token.START_OBJECT, ctx.parser().nextToken()); ctx.parser().nextToken(); return DocumentParser.parseObject(ctx, mapper.root()); } public void testDynamicMappingsNotNeeded() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("foo").field("type", "string").endObject().endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().field("foo", "bar").endObject()); // foo is already defined in the mappings assertNull(update); } public void testField() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject() .startObject("type").endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().field("foo", "bar").endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals("{\"type\":{\"properties\":{\"foo\":{\"type\":\"string\"}}}}", serialize(update)); } public void testIncremental() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); // Make sure that mapping updates are incremental, this is important for performance otherwise // every new field introduction runs in linear time with the total number of fields String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("foo").field("type", "string").endObject().endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().field("foo", "bar").field("bar", "baz").endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") // foo is NOT in the update .startObject("bar").field("type", "string").endObject() .endObject().endObject().string(), serialize(update)); } public void testIntroduceTwoFields() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject() .startObject("type").endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().field("foo", "bar").field("bar", "baz").endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("bar").field("type", "string").endObject() .startObject("foo").field("type", "string").endObject() .endObject().endObject().string(), serialize(update)); } public void testObject() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject() .startObject("type").endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().startObject("foo").startObject("bar").field("baz", "foo").endObject().endObject().endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("foo").startObject("properties").startObject("bar").startObject("properties").startObject("baz").field("type", "string").endObject().endObject().endObject().endObject().endObject() .endObject().endObject().endObject().string(), serialize(update)); } public void testArray() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject() .startObject("type").endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().startArray("foo").value("bar").value("baz").endArray().endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("foo").field("type", "string").endObject() .endObject().endObject().endObject().string(), serialize(update)); } public void testInnerDynamicMapping() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties") .startObject("foo").field("type", "object").endObject() .endObject().endObject().endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().startObject("foo").startObject("bar").field("baz", "foo").endObject().endObject().endObject()); assertNotNull(update); // original mapping not modified assertEquals(mapping, serialize(mapper)); // but we have an update assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("foo").startObject("properties").startObject("bar").startObject("properties").startObject("baz").field("type", "string").endObject().endObject().endObject().endObject().endObject() .endObject().endObject().endObject().string(), serialize(update)); } public void testComplexArray() throws Exception { IndexService indexService = createIndex("test"); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); String mapping = XContentFactory.jsonBuilder().startObject() .startObject("type").endObject() .endObject().string(); DocumentMapper mapper = parser.parse(mapping); assertEquals(mapping, serialize(mapper)); Mapper update = parse(mapper, parser, XContentFactory.jsonBuilder().startObject().startArray("foo") .startObject().field("bar", "baz").endObject() .startObject().field("baz", 3).endObject() .endArray().endObject()); assertEquals(mapping, serialize(mapper)); assertEquals(XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("foo").startObject("properties") .startObject("bar").field("type", "string").endObject() .startObject("baz").field("type", "long").endObject() .endObject().endObject() .endObject().endObject().endObject().string(), serialize(update)); } public void testReuseExistingMappings() throws IOException, Exception { IndexService indexService = createIndex("test", Settings.EMPTY, "type", "my_field1", "type=string,store=yes", "my_field2", "type=integer,precision_step=10"); // Even if the dynamic type of our new field is long, we already have a mapping for the same field // of type string so it should be mapped as a string DocumentMapper newMapper = indexService.mapperService().documentMapperWithAutoCreate("type2").getDocumentMapper(); Mapper update = parse(newMapper, indexService.mapperService().documentMapperParser(), XContentFactory.jsonBuilder().startObject().field("my_field1", 42).endObject()); Mapper myField1Mapper = null; for (Mapper m : update) { if (m.name().equals("my_field1")) { myField1Mapper = m; } } assertNotNull(myField1Mapper); // same type assertTrue(myField1Mapper instanceof StringFieldMapper); // and same option assertTrue(((StringFieldMapper) myField1Mapper).fieldType().stored()); // Even if dynamic mappings would map a numeric field as a long, here it should map it as a integer // since we already have a mapping of type integer update = parse(newMapper, indexService.mapperService().documentMapperParser(), XContentFactory.jsonBuilder().startObject().field("my_field2", 42).endObject()); Mapper myField2Mapper = null; for (Mapper m : update) { if (m.name().equals("my_field2")) { myField2Mapper = m; } } assertNotNull(myField2Mapper); // same type assertTrue(myField2Mapper instanceof IntegerFieldMapper); // and same option assertEquals(10, ((IntegerFieldMapper) myField2Mapper).fieldType().numericPrecisionStep()); // This can't work try { parse(newMapper, indexService.mapperService().documentMapperParser(), XContentFactory.jsonBuilder().startObject().field("my_field2", "foobar").endObject()); fail("Cannot succeed, incompatible types"); } catch (MapperParsingException e) { // expected } } }
sc0ttkclark/elasticsearch
core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingTests.java
Java
apache-2.0
19,930
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.portal.api; import java.util.List; import java.util.Map; import org.sakaiproject.site.api.Site; /** * @author ieb * */ public interface PageFilter { /** * @param newPages * @param site * @return */ List filter(List newPages, Site site); /** * Filter the list of placements, potentially making them hierachical if required * @param l * @param site * @return */ List<Map> filterPlacements(List<Map> l, Site site); }
bzhouduke123/sakai
portal/portal-api/api/src/java/org/sakaiproject/portal/api/PageFilter.java
Java
apache-2.0
1,396
#!/usr/bin/env node var DocGenerator = require('../lib/utilities/doc-generator.js'); (new DocGenerator()).generate();
waddedMeat/ember-proxy-example
test-app/node_modules/ember-cli/bin/generate-docs.js
JavaScript
mit
119
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "quuid.h" #include "qdatastream.h" #include "qendian.h" #include "qdebug.h" #ifndef QT_BOOTSTRAPPED #include "qcryptographichash.h" #endif QT_BEGIN_NAMESPACE static const char digits[] = "0123456789abcdef"; template <class Char, class Integral> void _q_toHex(Char *&dst, Integral value) { value = qToBigEndian(value); const char* p = reinterpret_cast<const char*>(&value); for (uint i = 0; i < sizeof(Integral); ++i, dst += 2) { uint j = (p[i] >> 4) & 0xf; dst[0] = Char(digits[j]); j = p[i] & 0xf; dst[1] = Char(digits[j]); } } template <class Char, class Integral> bool _q_fromHex(const Char *&src, Integral &value) { value = 0; for (uint i = 0; i < sizeof(Integral) * 2; ++i) { int ch = *src++; int tmp; if (ch >= '0' && ch <= '9') tmp = ch - '0'; else if (ch >= 'a' && ch <= 'f') tmp = ch - 'a' + 10; else if (ch >= 'A' && ch <= 'F') tmp = ch - 'A' + 10; else return false; value = value * 16 + tmp; } return true; } template <class Char> void _q_uuidToHex(Char *&dst, const uint &d1, const ushort &d2, const ushort &d3, const uchar (&d4)[8]) { *dst++ = Char('{'); _q_toHex(dst, d1); *dst++ = Char('-'); _q_toHex(dst, d2); *dst++ = Char('-'); _q_toHex(dst, d3); *dst++ = Char('-'); for (int i = 0; i < 2; i++) _q_toHex(dst, d4[i]); *dst++ = Char('-'); for (int i = 2; i < 8; i++) _q_toHex(dst, d4[i]); *dst = Char('}'); } template <class Char> bool _q_uuidFromHex(const Char *&src, uint &d1, ushort &d2, ushort &d3, uchar (&d4)[8]) { if (*src == Char('{')) src++; if (!_q_fromHex(src, d1) || *src++ != Char('-') || !_q_fromHex(src, d2) || *src++ != Char('-') || !_q_fromHex(src, d3) || *src++ != Char('-') || !_q_fromHex(src, d4[0]) || !_q_fromHex(src, d4[1]) || *src++ != Char('-') || !_q_fromHex(src, d4[2]) || !_q_fromHex(src, d4[3]) || !_q_fromHex(src, d4[4]) || !_q_fromHex(src, d4[5]) || !_q_fromHex(src, d4[6]) || !_q_fromHex(src, d4[7])) { return false; } return true; } #ifndef QT_BOOTSTRAPPED static QUuid createFromName(const QUuid &ns, const QByteArray &baseData, QCryptographicHash::Algorithm algorithm, int version) { QByteArray hashResult; // create a scope so later resize won't reallocate { QCryptographicHash hash(algorithm); hash.addData(ns.toRfc4122()); hash.addData(baseData); hashResult = hash.result(); } hashResult.resize(16); // Sha1 will be too long QUuid result = QUuid::fromRfc4122(hashResult); result.data3 &= 0x0FFF; result.data3 |= (version << 12); result.data4[0] &= 0x3F; result.data4[0] |= 0x80; return result; } #endif /*! \class QUuid \inmodule QtCore \brief The QUuid class stores a Universally Unique Identifier (UUID). \reentrant Using \e{U}niversally \e{U}nique \e{ID}entifiers (UUID) is a standard way to uniquely identify entities in a distributed computing environment. A UUID is a 16-byte (128-bit) number generated by some algorithm that is meant to guarantee that the UUID will be unique in the distributed computing environment where it is used. The acronym GUID is often used instead, \e{G}lobally \e{U}nique \e{ID}entifiers, but it refers to the same thing. \target Variant field Actually, the GUID is one \e{variant} of UUID. Multiple variants are in use. Each UUID contains a bit field that specifies which type (variant) of UUID it is. Call variant() to discover which type of UUID an instance of QUuid contains. It extracts the three most significant bits of byte 8 of the 16 bytes. In QUuid, byte 8 is \c{QUuid::data4[0]}. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the three most significant bits of parameter \c{b1}, which becomes \c{QUuid::data4[0]} and contains the variant field in its three most significant bits. In the table, 'x' means \e {don't care}. \table \header \li msb0 \li msb1 \li msb2 \li Variant \row \li 0 \li x \li x \li NCS (Network Computing System) \row \li 1 \li 0 \li x \li DCE (Distributed Computing Environment) \row \li 1 \li 1 \li 0 \li Microsoft (GUID) \row \li 1 \li 1 \li 1 \li Reserved for future expansion \endtable \target Version field If variant() returns QUuid::DCE, the UUID also contains a \e{version} field in the four most significant bits of \c{QUuid::data3}, and you can call version() to discover which version your QUuid contains. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the four most significant bits of parameter \c{w2}, which becomes \c{QUuid::data3} and contains the version field in its four most significant bits. \table \header \li msb0 \li msb1 \li msb2 \li msb3 \li Version \row \li 0 \li 0 \li 0 \li 1 \li Time \row \li 0 \li 0 \li 1 \li 0 \li Embedded POSIX \row \li 0 \li 0 \li 1 \li 1 \li Md5(Name) \row \li 0 \li 1 \li 0 \li 0 \li Random \row \li 0 \li 1 \li 0 \li 1 \li Sha1 \endtable The field layouts for the DCE versions listed in the table above are specified in the \l{http://www.ietf.org/rfc/rfc4122.txt} {Network Working Group UUID Specification}. Most platforms provide a tool for generating new UUIDs, e.g. \c uuidgen and \c guidgen. You can also use createUuid(). UUIDs generated by createUuid() are of the random type. Their QUuid::Version bits are set to QUuid::Random, and their QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated by createUuid() will not be unique. But it is \l{http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Random_UUID_probability_of_duplicates} {a \e{very} small chance}. UUIDs can be constructed from numeric values or from strings, or using the static createUuid() function. They can be converted to a string with toString(). UUIDs have a variant() and a version(), and null UUIDs return true from isNull(). */ /*! \fn QUuid::QUuid(const GUID &guid) Casts a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid &QUuid::operator=(const GUID &guid) Assigns a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::operator GUID() const Returns a Windows GUID from a QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::QUuid() Creates the null UUID. toString() will output the null UUID as "{00000000-0000-0000-0000-000000000000}". */ /*! \fn QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8) Creates a UUID with the value specified by the parameters, \a l, \a w1, \a w2, \a b1, \a b2, \a b3, \a b4, \a b5, \a b6, \a b7, \a b8. Example: \snippet code/src_corelib_plugin_quuid.cpp 0 */ /*! Creates a QUuid object from the string \a text, which must be formatted as five hex fields separated by '-', e.g., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. The curly braces shown here are optional, but it is normal to include them. If the conversion fails, a null UUID is created. See toString() for an explanation of how the five hex fields map to the public data members in QUuid. \sa toString(), QUuid() */ QUuid::QUuid(const QString &text) { if (text.length() < 36) { *this = QUuid(); return; } const ushort *data = reinterpret_cast<const ushort *>(text.unicode()); if (*data == '{' && text.length() < 37) { *this = QUuid(); return; } if (!_q_uuidFromHex(data, data1, data2, data3, data4)) { *this = QUuid(); return; } } /*! \internal */ QUuid::QUuid(const char *text) { if (!text) { *this = QUuid(); return; } if (!_q_uuidFromHex(text, data1, data2, data3, data4)) { *this = QUuid(); return; } } /*! Creates a QUuid object from the QByteArray \a text, which must be formatted as five hex fields separated by '-', e.g., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. The curly braces shown here are optional, but it is normal to include them. If the conversion fails, a null UUID is created. See toByteArray() for an explanation of how the five hex fields map to the public data members in QUuid. \since 4.8 \sa toByteArray(), QUuid() */ QUuid::QUuid(const QByteArray &text) { if (text.length() < 36) { *this = QUuid(); return; } const char *data = text.constData(); if (*data == '{' && text.length() < 37) { *this = QUuid(); return; } if (!_q_uuidFromHex(data, data1, data2, data3, data4)) { *this = QUuid(); return; } } /*! \since 5.0 \fn QUuid QUuid::createUuidV3(const QUuid &ns, const QByteArray &baseData); This function returns a new UUID with variant QUuid::DCE and version QUuid::Md5. \a ns is the namespace and \a baseData is the basic data as described by RFC 4122. \sa variant(), version(), createUuidV5() */ /*! \since 5.0 \fn QUuid QUuid::createUuidV3(const QUuid &ns, const QString &baseData); This function returns a new UUID with variant QUuid::DCE and version QUuid::Md5. \a ns is the namespace and \a baseData is the basic data as described by RFC 4122. \sa variant(), version(), createUuidV5() */ /*! \since 5.0 \fn QUuid QUuid::createUuidV5(const QUuid &ns, const QByteArray &baseData); This function returns a new UUID with variant QUuid::DCE and version QUuid::Sha1. \a ns is the namespace and \a baseData is the basic data as described by RFC 4122. \sa variant(), version(), createUuidV3() */ /*! \since 5.0 \fn QUuid QUuid::createUuidV5(const QUuid &ns, const QString &baseData); This function returns a new UUID with variant QUuid::DCE and version QUuid::Sha1. \a ns is the namespace and \a baseData is the basic data as described by RFC 4122. \sa variant(), version(), createUuidV3() */ #ifndef QT_BOOTSTRAPPED QUuid QUuid::createUuidV3(const QUuid &ns, const QByteArray &baseData) { return createFromName(ns, baseData, QCryptographicHash::Md5, 3); } QUuid QUuid::createUuidV5(const QUuid &ns, const QByteArray &baseData) { return createFromName(ns, baseData, QCryptographicHash::Sha1, 5); } #endif /*! Creates a QUuid object from the binary representation of the UUID, as specified by RFC 4122 section 4.1.2. See toRfc4122() for a further explanation of the order of \a bytes required. The byte array accepted is NOT a human readable format. If the conversion fails, a null UUID is created. \since 4.8 \sa toRfc4122(), QUuid() */ QUuid QUuid::fromRfc4122(const QByteArray &bytes) { if (bytes.isEmpty() || bytes.length() != 16) return QUuid(); uint d1; ushort d2, d3; uchar d4[8]; const uchar *data = reinterpret_cast<const uchar *>(bytes.constData()); d1 = qFromBigEndian<quint32>(data); data += sizeof(quint32); d2 = qFromBigEndian<quint16>(data); data += sizeof(quint16); d3 = qFromBigEndian<quint16>(data); data += sizeof(quint16); for (int i = 0; i < 8; ++i) { d4[i] = *(data); data++; } return QUuid(d1, d2, d3, d4[0], d4[1], d4[2], d4[3], d4[4], d4[5], d4[6], d4[7]); } /*! \fn bool QUuid::operator==(const QUuid &other) const Returns \c true if this QUuid and the \a other QUuid are identical; otherwise returns \c false. */ /*! \fn bool QUuid::operator!=(const QUuid &other) const Returns \c true if this QUuid and the \a other QUuid are different; otherwise returns \c false. */ /*! Returns the string representation of this QUuid. The string is formatted as five hex fields separated by '-' and enclosed in curly braces, i.e., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. From left to right, the five hex fields are obtained from the four public data members in QUuid as follows: \table \header \li Field # \li Source \row \li 1 \li data1 \row \li 2 \li data2 \row \li 3 \li data3 \row \li 4 \li data4[0] .. data4[1] \row \li 5 \li data4[2] .. data4[7] \endtable */ QString QUuid::toString() const { QString result(38, Qt::Uninitialized); ushort *data = (ushort *)result.unicode(); _q_uuidToHex(data, data1, data2, data3, data4); return result; } /*! Returns the binary representation of this QUuid. The byte array is formatted as five hex fields separated by '-' and enclosed in curly braces, i.e., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. From left to right, the five hex fields are obtained from the four public data members in QUuid as follows: \table \header \li Field # \li Source \row \li 1 \li data1 \row \li 2 \li data2 \row \li 3 \li data3 \row \li 4 \li data4[0] .. data4[1] \row \li 5 \li data4[2] .. data4[7] \endtable \since 4.8 */ QByteArray QUuid::toByteArray() const { QByteArray result(38, Qt::Uninitialized); char *data = result.data(); _q_uuidToHex(data, data1, data2, data3, data4); return result; } /*! Returns the binary representation of this QUuid. The byte array is in big endian format, and formatted according to RFC 4122, section 4.1.2 - "Layout and byte order". The order is as follows: \table \header \li Field # \li Source \row \li 1 \li data1 \row \li 2 \li data2 \row \li 3 \li data3 \row \li 4 \li data4[0] .. data4[7] \endtable \since 4.8 */ QByteArray QUuid::toRfc4122() const { // we know how many bytes a UUID has, I hope :) QByteArray bytes(16, Qt::Uninitialized); uchar *data = reinterpret_cast<uchar*>(bytes.data()); qToBigEndian(data1, data); data += sizeof(quint32); qToBigEndian(data2, data); data += sizeof(quint16); qToBigEndian(data3, data); data += sizeof(quint16); for (int i = 0; i < 8; ++i) { *(data) = data4[i]; data++; } return bytes; } #ifndef QT_NO_DATASTREAM /*! \relates QUuid Writes the UUID \a id to the data stream \a s. */ QDataStream &operator<<(QDataStream &s, const QUuid &id) { QByteArray bytes; if (s.byteOrder() == QDataStream::BigEndian) { bytes = id.toRfc4122(); } else { // we know how many bytes a UUID has, I hope :) bytes = QByteArray(16, Qt::Uninitialized); uchar *data = reinterpret_cast<uchar*>(bytes.data()); qToLittleEndian(id.data1, data); data += sizeof(quint32); qToLittleEndian(id.data2, data); data += sizeof(quint16); qToLittleEndian(id.data3, data); data += sizeof(quint16); for (int i = 0; i < 8; ++i) { *(data) = id.data4[i]; data++; } } if (s.writeRawData(bytes.data(), 16) != 16) { s.setStatus(QDataStream::WriteFailed); } return s; } /*! \relates QUuid Reads a UUID from the stream \a s into \a id. */ QDataStream &operator>>(QDataStream &s, QUuid &id) { QByteArray bytes(16, Qt::Uninitialized); if (s.readRawData(bytes.data(), 16) != 16) { s.setStatus(QDataStream::ReadPastEnd); return s; } if (s.byteOrder() == QDataStream::BigEndian) { id = QUuid::fromRfc4122(bytes); } else { const uchar *data = reinterpret_cast<const uchar *>(bytes.constData()); id.data1 = qFromLittleEndian<quint32>(data); data += sizeof(quint32); id.data2 = qFromLittleEndian<quint16>(data); data += sizeof(quint16); id.data3 = qFromLittleEndian<quint16>(data); data += sizeof(quint16); for (int i = 0; i < 8; ++i) { id.data4[i] = *(data); data++; } } return s; } #endif // QT_NO_DATASTREAM /*! Returns \c true if this is the null UUID {00000000-0000-0000-0000-000000000000}; otherwise returns \c false. */ bool QUuid::isNull() const { return data4[0] == 0 && data4[1] == 0 && data4[2] == 0 && data4[3] == 0 && data4[4] == 0 && data4[5] == 0 && data4[6] == 0 && data4[7] == 0 && data1 == 0 && data2 == 0 && data3 == 0; } /*! \enum QUuid::Variant This enum defines the values used in the \l{Variant field} {variant field} of the UUID. The value in the variant field determines the layout of the 128-bit value. \value VarUnknown Variant is unknown \value NCS Reserved for NCS (Network Computing System) backward compatibility \value DCE Distributed Computing Environment, the scheme used by QUuid \value Microsoft Reserved for Microsoft backward compatibility (GUID) \value Reserved Reserved for future definition */ /*! \enum QUuid::Version This enum defines the values used in the \l{Version field} {version field} of the UUID. The version field is meaningful only if the value in the \l{Variant field} {variant field} is QUuid::DCE. \value VerUnknown Version is unknown \value Time Time-based, by using timestamp, clock sequence, and MAC network card address (if available) for the node sections \value EmbeddedPOSIX DCE Security version, with embedded POSIX UUIDs \value Name Name-based, by using values from a name for all sections \value Md5 Alias for Name \value Random Random-based, by using random numbers for all sections \value Sha1 */ /*! \fn QUuid::Variant QUuid::variant() const Returns the value in the \l{Variant field} {variant field} of the UUID. If the return value is QUuid::DCE, call version() to see which layout it uses. The null UUID is considered to be of an unknown variant. \sa version() */ QUuid::Variant QUuid::variant() const { if (isNull()) return VarUnknown; // Check the 3 MSB of data4[0] if ((data4[0] & 0x80) == 0x00) return NCS; else if ((data4[0] & 0xC0) == 0x80) return DCE; else if ((data4[0] & 0xE0) == 0xC0) return Microsoft; else if ((data4[0] & 0xE0) == 0xE0) return Reserved; return VarUnknown; } /*! \fn QUuid::Version QUuid::version() const Returns the \l{Version field} {version field} of the UUID, if the UUID's \l{Variant field} {variant field} is QUuid::DCE. Otherwise it returns QUuid::VerUnknown. \sa variant() */ QUuid::Version QUuid::version() const { // Check the 4 MSB of data3 Version ver = (Version)(data3>>12); if (isNull() || (variant() != DCE) || ver < Time || ver > Sha1) return VerUnknown; return ver; } /*! \fn bool QUuid::operator<(const QUuid &other) const Returns \c true if this QUuid has the same \l{Variant field} {variant field} as the \a other QUuid and is lexicographically \e{before} the \a other QUuid. If the \a other QUuid has a different variant field, the return value is determined by comparing the two \l{QUuid::Variant} {variants}. \sa variant() */ #define ISLESS(f1, f2) if (f1!=f2) return (f1<f2); bool QUuid::operator<(const QUuid &other) const { if (variant() != other.variant()) return variant() < other.variant(); ISLESS(data1, other.data1); ISLESS(data2, other.data2); ISLESS(data3, other.data3); for (int n = 0; n < 8; n++) { ISLESS(data4[n], other.data4[n]); } return false; } /*! \fn bool QUuid::operator>(const QUuid &other) const Returns \c true if this QUuid has the same \l{Variant field} {variant field} as the \a other QUuid and is lexicographically \e{after} the \a other QUuid. If the \a other QUuid has a different variant field, the return value is determined by comparing the two \l{QUuid::Variant} {variants}. \sa variant() */ #define ISMORE(f1, f2) if (f1!=f2) return (f1>f2); bool QUuid::operator>(const QUuid &other) const { if (variant() != other.variant()) return variant() > other.variant(); ISMORE(data1, other.data1); ISMORE(data2, other.data2); ISMORE(data3, other.data3); for (int n = 0; n < 8; n++) { ISMORE(data4[n], other.data4[n]); } return false; } /*! \fn QUuid QUuid::createUuid() On any platform other than Windows, this function returns a new UUID with variant QUuid::DCE and version QUuid::Random. If the /dev/urandom device exists, then the numbers used to construct the UUID will be of cryptographic quality, which will make the UUID unique. Otherwise, the numbers of the UUID will be obtained from the local pseudo-random number generator (qrand(), which is seeded by qsrand()) which is usually not of cryptograhic quality, which means that the UUID can't be guaranteed to be unique. On a Windows platform, a GUID is generated, which almost certainly \e{will} be unique, on this or any other system, networked or not. \sa variant(), version() */ #if defined(Q_OS_WIN32) QT_BEGIN_INCLUDE_NAMESPACE #include <objbase.h> // For CoCreateGuid QT_END_INCLUDE_NAMESPACE QUuid QUuid::createUuid() { GUID guid; CoCreateGuid(&guid); QUuid result = guid; return result; } #else // !Q_OS_WIN32 QT_BEGIN_INCLUDE_NAMESPACE #include "qdatetime.h" #include "qfile.h" #include "qthreadstorage.h" #include <stdlib.h> // for RAND_MAX QT_END_INCLUDE_NAMESPACE #if !defined(QT_BOOTSTRAPPED) && defined(Q_OS_UNIX) Q_GLOBAL_STATIC(QThreadStorage<QFile *>, devUrandomStorage); #endif QUuid QUuid::createUuid() { QUuid result; uint *data = &(result.data1); #if defined(Q_OS_UNIX) QFile *devUrandom; # if !defined(QT_BOOTSTRAPPED) devUrandom = devUrandomStorage()->localData(); if (!devUrandom) { devUrandom = new QFile(QLatin1String("/dev/urandom")); devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered); devUrandomStorage()->setLocalData(devUrandom); } # else QFile file(QLatin1String("/dev/urandom")); devUrandom = &file; devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered); # endif enum { AmountToRead = 4 * sizeof(uint) }; if (devUrandom->isOpen() && devUrandom->read((char *) data, AmountToRead) == AmountToRead) { // we got what we wanted, nothing more to do ; } else #endif { static const int intbits = sizeof(int)*8; static int randbits = 0; if (!randbits) { int r = 0; int max = RAND_MAX; do { ++r; } while ((max=max>>1)); randbits = r; } // Seed the PRNG once per thread with a combination of current time, a // stack address and a serial counter (since thread stack addresses are // re-used). #ifndef QT_BOOTSTRAPPED static QThreadStorage<int *> uuidseed; if (!uuidseed.hasLocalData()) { int *pseed = new int; static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(2); qsrand(*pseed = QDateTime::currentDateTime().toTime_t() + quintptr(&pseed) + serial.fetchAndAddRelaxed(1)); uuidseed.setLocalData(pseed); } #else static bool seeded = false; if (!seeded) qsrand(QDateTime::currentDateTime().toTime_t() + quintptr(&seeded)); #endif int chunks = 16 / sizeof(uint); while (chunks--) { uint randNumber = 0; for (int filled = 0; filled < intbits; filled += randbits) randNumber |= qrand()<<filled; *(data+chunks) = randNumber; } } result.data4[0] = (result.data4[0] & 0x3F) | 0x80; // UV_DCE result.data3 = (result.data3 & 0x0FFF) | 0x4000; // UV_Random return result; } #endif // !Q_OS_WIN32 /*! \fn bool QUuid::operator==(const GUID &guid) const Returns \c true if this UUID is equal to the Windows GUID \a guid; otherwise returns \c false. */ /*! \fn bool QUuid::operator!=(const GUID &guid) const Returns \c true if this UUID is not equal to the Windows GUID \a guid; otherwise returns \c false. */ #ifndef QT_NO_DEBUG_STREAM /*! \relates QUuid Writes the UUID \a id to the output stream for debugging information \a dbg. */ QDebug operator<<(QDebug dbg, const QUuid &id) { dbg.nospace() << "QUuid(" << id.toString() << ')'; return dbg.space(); } #endif /*! \since 5.0 \relates QUuid Returns a hash of the UUID \a uuid, using \a seed to seed the calculation. */ uint qHash(const QUuid &uuid, uint seed) Q_DECL_NOTHROW { return uuid.data1 ^ uuid.data2 ^ (uuid.data3 << 16) ^ ((uuid.data4[0] << 24) | (uuid.data4[1] << 16) | (uuid.data4[2] << 8) | uuid.data4[3]) ^ ((uuid.data4[4] << 24) | (uuid.data4[5] << 16) | (uuid.data4[6] << 8) | uuid.data4[7]) ^ seed; } QT_END_NAMESPACE
Observer-Wu/phantomjs
src/qt/qtbase/src/corelib/plugin/quuid.cpp
C++
bsd-3-clause
27,549
import { ArrayIterator, AsyncIterator, BufferedIterator, ClonedIterator, EmptyIterator, IntegerIterator, MultiTransformIterator, SingletonIterator, SimpleTransformIterator, TransformIterator } from "asynciterator"; function test_asynciterator() { // We can't instantiate an abstract class. const it1: AsyncIterator<number> = <any> {}; const read1: number = it1.read(); it1.each((data: number) => console.log(data)); it1.each((data: number) => console.log(data), {}); it1.close(); const it2: AsyncIterator<string> = <any> {}; const read2: string = it2.read(); it2.each((data: string) => console.log(data)); it2.each((data: string) => console.log(data), {}); it2.close(); const it3: AsyncIterator<AsyncIterator<string>> = <any> {}; const read3: AsyncIterator<string> = it3.read(); it3.each((data: AsyncIterator<string>) => data.each((data: string) => console.log(data))); it3.each((data: AsyncIterator<string>) => data.each((data: string) => console.log(data), {}), {}); it3.close(); const readable2: boolean = it1.readable; const closed2: boolean = it1.closed; const ended2: boolean = it1.ended; it1.setProperty('name1', 123); it2.setProperty('name2', 'someValue'); const p1: number = it1.getProperty('name1'); const p2: string = it1.getProperty('name2'); it1.getProperty('name1', (value: number) => console.log(value)); it1.getProperty('name2', (value: string) => console.log(value)); const ps1: {[id: string]: any} = it1.getProperties(); it1.setProperties({ name1: 1234, name2: 'someOtherValue' }); it1.copyProperties(it2, [ 'name1', 'name2' ]); const str: string = it1.toString(); const stit1: SimpleTransformIterator<number, string> = it1.transform(); const stit2: SimpleTransformIterator<number, string> = it1.map((number: number) => 'i' + number); const stit3: AsyncIterator<string> = it1.map((number: number) => 'i' + number); const stit4: AsyncIterator<number> = it2.map(parseInt); const stit5: AsyncIterator<number> = it1.map((number: number) => number + 1); const stit6: AsyncIterator<number> = it1.filter((number: number) => number < 10); const stit7: AsyncIterator<number> = it1.prepend([0, 1, 2]); const stit8: AsyncIterator<number> = it1.append([0, 1, 2]); const stit9: AsyncIterator<number> = it1.surround([0, 1, 2], [0, 1, 2]); const stit10: AsyncIterator<number> = it1.skip(2); const stit11: AsyncIterator<number> = it1.take(2); const stit12: AsyncIterator<number> = it1.range(2, 20); const stit13: AsyncIterator<number> = it1.clone(); const intit1: IntegerIterator = AsyncIterator.range(10, 100, 1); const intit2: IntegerIterator = AsyncIterator.range(10, 100); const intit3: IntegerIterator = AsyncIterator.range(10); const intit4: IntegerIterator = AsyncIterator.range(); } function test_emptyiterator() { const it1: AsyncIterator<number> = new EmptyIterator(); const it2: AsyncIterator<string> = new EmptyIterator(); } function test_singletoniterator() { const it1: AsyncIterator<number> = new SingletonIterator(3); const it2: AsyncIterator<string> = new SingletonIterator('a'); } function test_arrayiterator() { const it1: AsyncIterator<number> = new ArrayIterator([1, 2, 3]); const it2: AsyncIterator<string> = new ArrayIterator(['a', 'b', 'c']); } function test_integeriterator() { const it1: IntegerIterator = new IntegerIterator(); const it2: AsyncIterator<number> = new IntegerIterator({}); const it3: AsyncIterator<number> = new IntegerIterator({ start: 0 }); const it4: AsyncIterator<number> = new IntegerIterator({ end: 100 }); const it5: AsyncIterator<number> = new IntegerIterator({ step: 10 }); } function test_bufferediterator() { const it1: BufferedIterator<number> = new BufferedIterator(); const it2: AsyncIterator<number> = new BufferedIterator({}); const it3: AsyncIterator<number> = new BufferedIterator({ maxBufferSize: 10 }); const it4: AsyncIterator<number> = new BufferedIterator({ autoStart: true }); } function test_transformiterator() { const it1: TransformIterator<number, string> = new TransformIterator<number, string>(); const it2: AsyncIterator<string> = new TransformIterator<number, string>(); const it3: AsyncIterator<number> = new TransformIterator<string, number>(it1); const it4: AsyncIterator<number> = new TransformIterator<string, number>(it1, {}); const it5: AsyncIterator<number> = new TransformIterator<string, number>(it1, { optional: true }); const it6: AsyncIterator<number> = new TransformIterator<string, number>({ source: it1 }); const source: AsyncIterator<number> = it1.source; } function test_simpletransformiterator() { const it1: SimpleTransformIterator<number, string> = new SimpleTransformIterator<number, string>(); const it2: TransformIterator<number, string> = new SimpleTransformIterator<number, string>(); const it3: AsyncIterator<string> = new SimpleTransformIterator<number, string>(); const it4: AsyncIterator<number> = new SimpleTransformIterator<string, number>(it1); const it5: AsyncIterator<number> = new SimpleTransformIterator<string, number>(it1, {}); const it6: AsyncIterator<number> = new SimpleTransformIterator<string, number>({}); const it7: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ optional: true }); const it8: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ source: it1 }); const it9: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ offset: 2 }); const it10: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ limit: 2 }); const it11: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ prepend: [0, 1, 2] }); const it12: AsyncIterator<number> = new SimpleTransformIterator<string, number>({ append: [0, 1, 2] }); const it13: AsyncIterator<number> = new SimpleTransformIterator<number, number>( { filter: (val: number) => val > 10 }); const it14: AsyncIterator<number> = new SimpleTransformIterator<number, number>({ map: (val: number) => val + 1 }); const it15: AsyncIterator<number> = new SimpleTransformIterator<number, number>( { transform: (val: number, cb: (result: number) => void) => cb(val + 1) }); } function test_multitransformiterator() { const it1: MultiTransformIterator<number, string> = new MultiTransformIterator<number, string>(); const it2: TransformIterator<number, string> = new MultiTransformIterator<number, string>(); const it3: AsyncIterator<string> = new MultiTransformIterator<number, string>(); const it4: AsyncIterator<number> = new MultiTransformIterator<string, number>(it1); const it5: AsyncIterator<number> = new MultiTransformIterator<string, number>(it1, {}); const it6: AsyncIterator<number> = new MultiTransformIterator<string, number>({}); const it7: AsyncIterator<number> = new MultiTransformIterator<string, number>({ optional: true }); const it8: AsyncIterator<number> = new MultiTransformIterator<string, number>({ source: it1 }); } function test_clonediterator() { const it1: ClonedIterator<number> = new ClonedIterator<number>(); const it2: ClonedIterator<number> = new ClonedIterator<number>(it1); }
aaronryden/DefinitelyTyped
types/asynciterator/asynciterator-tests.ts
TypeScript
mit
7,358
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.benchmark; import com.google.common.collect.Maps; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import static java.util.Objects.requireNonNull; public class AverageBenchmarkResults implements BenchmarkResultHook { private final Map<String, Long> resultsSum = new LinkedHashMap<>(); private int resultsCount; @Override public BenchmarkResultHook addResults(Map<String, Long> results) { requireNonNull(results, "results is null"); for (Entry<String, Long> entry : results.entrySet()) { Long currentSum = resultsSum.get(entry.getKey()); if (currentSum == null) { currentSum = 0L; } resultsSum.put(entry.getKey(), currentSum + entry.getValue()); } resultsCount++; return this; } public Map<String, Double> getAverageResultsValues() { return Maps.transformValues(resultsSum, input -> 1.0 * input / resultsCount); } public Map<String, String> getAverageResultsStrings() { return Maps.transformValues(resultsSum, input -> String.format("%,3.2f", 1.0 * input / resultsCount)); } @Override public void finished() { } }
marsorp/blog
presto166/presto-benchmark/src/main/java/com/facebook/presto/benchmark/AverageBenchmarkResults.java
Java
apache-2.0
1,837
// Copyright 2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 gax import ( "time" "golang.org/x/net/context" ) // A user defined call stub. type APICall func(context.Context) error // Invoke calls the given APICall, // performing retries as specified by opts, if any. func Invoke(ctx context.Context, call APICall, opts ...CallOption) error { var settings CallSettings for _, opt := range opts { opt.Resolve(&settings) } return invoke(ctx, call, settings, Sleep) } // Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing. // If interrupted, Sleep returns ctx.Err(). func Sleep(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) select { case <-ctx.Done(): t.Stop() return ctx.Err() case <-t.C: return nil } } type sleeper func(ctx context.Context, d time.Duration) error // invoke implements Invoke, taking an additional sleeper argument for testing. func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { var retryer Retryer for { err := call(ctx) if err == nil { return nil } if settings.Retry == nil { return err } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r } else { return err } } if d, ok := retryer.Retry(err); !ok { return err } else if err = sp(ctx, d); err != nil { return err } } }
stardog-union/stardog-graviton
vendor/github.com/hashicorp/terraform/vendor/github.com/googleapis/gax-go/invoke.go
GO
apache-2.0
2,878
class Test { void foo() { int b = 0; <selection>int i = b << 1;</selection> } }
lshain-android-source/tools-idea
java/java-tests/testData/refactoring/suggestedTypes/LtLtInt.java
Java
apache-2.0
91
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Microsoft.Internal { internal static class AttributeServices { // MemberInfo Attribute helpers public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo) where T : System.Attribute { return memberInfo.GetCustomAttributes<T>(false); } public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return memberInfo.GetCustomAttributes<T>(inherit); } public static T GetFirstAttribute<T>(this MemberInfo memberInfo) where T : System.Attribute { return GetAttributes<T>(memberInfo).FirstOrDefault(); } public static T GetFirstAttribute<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return GetAttributes<T>(memberInfo, inherit).FirstOrDefault(); } public static bool IsAttributeDefined<T>(this MemberInfo memberInfo) where T : System.Attribute { return memberInfo.IsDefined(typeof(T), false); } public static bool IsAttributeDefined<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return memberInfo.IsDefined(typeof(T), inherit); } // ParameterInfo Attribute helpers public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return parameterInfo.GetCustomAttributes<T>(false); } public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return parameterInfo.GetCustomAttributes<T>(inherit); } public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return GetAttributes<T>(parameterInfo).FirstOrDefault(); } public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return GetAttributes<T>(parameterInfo, inherit).FirstOrDefault(); } public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return parameterInfo.IsDefined(typeof(T), false); } public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return parameterInfo.IsDefined(typeof(T), inherit); } } }
iamjasonp/corefx
src/System.Composition.Convention/src/Microsoft/Internal/AttributeServices.cs
C#
mit
2,881
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.cluster.repositories.verify; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.master.TransportMasterNodeAction; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.repositories.RepositoryVerificationException; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; /** * Transport action for verifying repository operation */ public class TransportVerifyRepositoryAction extends TransportMasterNodeAction<VerifyRepositoryRequest, VerifyRepositoryResponse> { private final RepositoriesService repositoriesService; protected final ClusterName clusterName; @Inject public TransportVerifyRepositoryAction(Settings settings, ClusterName clusterName, TransportService transportService, ClusterService clusterService, RepositoriesService repositoriesService, ThreadPool threadPool, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, VerifyRepositoryAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, VerifyRepositoryRequest.class); this.repositoriesService = repositoriesService; this.clusterName = clusterName; } @Override protected String executor() { return ThreadPool.Names.MANAGEMENT; } @Override protected VerifyRepositoryResponse newResponse() { return new VerifyRepositoryResponse(); } @Override protected ClusterBlockException checkBlock(VerifyRepositoryRequest request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); } @Override protected void masterOperation(final VerifyRepositoryRequest request, ClusterState state, final ActionListener<VerifyRepositoryResponse> listener) { repositoriesService.verifyRepository(request.name(), new ActionListener<RepositoriesService.VerifyResponse>() { @Override public void onResponse(RepositoriesService.VerifyResponse verifyResponse) { if (verifyResponse.failed()) { listener.onFailure(new RepositoryVerificationException(request.name(), verifyResponse.failureDescription())); } else { listener.onResponse(new VerifyRepositoryResponse(clusterName, verifyResponse.nodes())); } } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }); } }
shashi95/kafkaES
core/src/main/java/org/elasticsearch/action/admin/cluster/repositories/verify/TransportVerifyRepositoryAction.java
Java
apache-2.0
3,999
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin; /** * Helper class to determine hardware related characteristics such as the * number of processors and the amount of memory on the node. */ @InterfaceAudience.Private @InterfaceStability.Unstable public class NodeManagerHardwareUtils { private static final Log LOG = LogFactory .getLog(NodeManagerHardwareUtils.class); /** * * Returns the number of CPUs on the node. This value depends on the * configuration setting which decides whether to count logical processors * (such as hyperthreads) as cores or not. * * @param conf * - Configuration object * @return Number of CPUs */ public static int getNodeCPUs(Configuration conf) { ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); return NodeManagerHardwareUtils.getNodeCPUs(plugin, conf); } /** * * Returns the number of CPUs on the node. This value depends on the * configuration setting which decides whether to count logical processors * (such as hyperthreads) as cores or not. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - Configuration object * @return Number of CPU cores on the node. */ public static int getNodeCPUs(ResourceCalculatorPlugin plugin, Configuration conf) { int numProcessors = plugin.getNumProcessors(); boolean countLogicalCores = conf.getBoolean(YarnConfiguration.NM_COUNT_LOGICAL_PROCESSORS_AS_CORES, YarnConfiguration.DEFAULT_NM_COUNT_LOGICAL_PROCESSORS_AS_CORES); if (!countLogicalCores) { numProcessors = plugin.getNumCores(); } return numProcessors; } /** * * Returns the fraction of CPUs that should be used for YARN containers. * The number is derived based on various configuration params such as * YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT * * @param conf * - Configuration object * @return Fraction of CPUs to be used for YARN containers */ public static float getContainersCPUs(Configuration conf) { ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); return NodeManagerHardwareUtils.getContainersCPUs(plugin, conf); } /** * * Returns the fraction of CPUs that should be used for YARN containers. * The number is derived based on various configuration params such as * YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - Configuration object * @return Fraction of CPUs to be used for YARN containers */ public static float getContainersCPUs(ResourceCalculatorPlugin plugin, Configuration conf) { int numProcessors = getNodeCPUs(plugin, conf); int nodeCpuPercentage = getNodeCpuPercentage(conf); return (nodeCpuPercentage * numProcessors) / 100.0f; } /** * Gets the percentage of physical CPU that is configured for YARN containers. * This is percent {@literal >} 0 and {@literal <=} 100 based on * {@link YarnConfiguration#NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT} * @param conf Configuration object * @return percent {@literal >} 0 and {@literal <=} 100 */ public static int getNodeCpuPercentage(Configuration conf) { int nodeCpuPercentage = Math.min(conf.getInt( YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT, YarnConfiguration.DEFAULT_NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT), 100); nodeCpuPercentage = Math.max(0, nodeCpuPercentage); if (nodeCpuPercentage == 0) { String message = "Illegal value for " + YarnConfiguration.NM_RESOURCE_PERCENTAGE_PHYSICAL_CPU_LIMIT + ". Value cannot be less than or equal to 0."; throw new IllegalArgumentException(message); } return nodeCpuPercentage; } /** * Function to return the number of vcores on the system that can be used for * YARN containers. If a number is specified in the configuration file, then * that number is returned. If nothing is specified - 1. If the OS is an * "unknown" OS(one for which we don't have ResourceCalculatorPlugin * implemented), return the default NodeManager cores. 2. If the config * variable yarn.nodemanager.cpu.use_logical_processors is set to true, it * returns the logical processor count(count hyperthreads as cores), else it * returns the physical cores count. * * @param conf * - the configuration for the NodeManager * @return the number of cores to be used for YARN containers * */ public static int getVCores(Configuration conf) { // is this os for which we can determine cores? ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); return NodeManagerHardwareUtils.getVCores(plugin, conf); } /** * Function to return the number of vcores on the system that can be used for * YARN containers. If a number is specified in the configuration file, then * that number is returned. If nothing is specified - 1. If the OS is an * "unknown" OS(one for which we don't have ResourceCalculatorPlugin * implemented), return the default NodeManager cores. 2. If the config * variable yarn.nodemanager.cpu.use_logical_processors is set to true, it * returns the logical processor count(count hyperthreads as cores), else it * returns the physical cores count. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - the configuration for the NodeManager * @return the number of cores to be used for YARN containers * */ public static int getVCores(ResourceCalculatorPlugin plugin, Configuration conf) { int cores; boolean hardwareDetectionEnabled = conf.getBoolean( YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION, YarnConfiguration.DEFAULT_NM_ENABLE_HARDWARE_CAPABILITY_DETECTION); String message; if (!hardwareDetectionEnabled || plugin == null) { cores = conf.getInt(YarnConfiguration.NM_VCORES, YarnConfiguration.DEFAULT_NM_VCORES); if (cores == -1) { cores = YarnConfiguration.DEFAULT_NM_VCORES; } } else { cores = conf.getInt(YarnConfiguration.NM_VCORES, -1); if (cores == -1) { float physicalCores = NodeManagerHardwareUtils.getContainersCPUs(plugin, conf); float multiplier = conf.getFloat(YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER, YarnConfiguration.DEFAULT_NM_PCORES_VCORES_MULTIPLIER); if (multiplier > 0) { float tmp = physicalCores * multiplier; if (tmp > 0 && tmp < 1) { // on a single core machine - tmp can be between 0 and 1 cores = 1; } else { cores = (int) tmp; } } else { message = "Illegal value for " + YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } } } if(cores <= 0) { message = "Illegal value for " + YarnConfiguration.NM_VCORES + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } return cores; } /** * Function to return how much memory we should set aside for YARN containers. * If a number is specified in the configuration file, then that number is * returned. If nothing is specified - 1. If the OS is an "unknown" OS(one for * which we don't have ResourceCalculatorPlugin implemented), return the * default NodeManager physical memory. 2. If the OS has a * ResourceCalculatorPlugin implemented, the calculation is 0.8 * (RAM - 2 * * JVM-memory) i.e. use 80% of the memory after accounting for memory used by * the DataNode and the NodeManager. If the number is less than 1GB, log a * warning message. * * @param conf * - the configuration for the NodeManager * @return the amount of memory that will be used for YARN containers in MB. */ public static int getContainerMemoryMB(Configuration conf) { return NodeManagerHardwareUtils.getContainerMemoryMB( ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf), conf); } /** * Function to return how much memory we should set aside for YARN containers. * If a number is specified in the configuration file, then that number is * returned. If nothing is specified - 1. If the OS is an "unknown" OS(one for * which we don't have ResourceCalculatorPlugin implemented), return the * default NodeManager physical memory. 2. If the OS has a * ResourceCalculatorPlugin implemented, the calculation is 0.8 * (RAM - 2 * * JVM-memory) i.e. use 80% of the memory after accounting for memory used by * the DataNode and the NodeManager. If the number is less than 1GB, log a * warning message. * * @param plugin * - ResourceCalculatorPlugin object to determine hardware specs * @param conf * - the configuration for the NodeManager * @return the amount of memory that will be used for YARN containers in MB. */ public static int getContainerMemoryMB(ResourceCalculatorPlugin plugin, Configuration conf) { int memoryMb; boolean hardwareDetectionEnabled = conf.getBoolean( YarnConfiguration.NM_ENABLE_HARDWARE_CAPABILITY_DETECTION, YarnConfiguration.DEFAULT_NM_ENABLE_HARDWARE_CAPABILITY_DETECTION); if (!hardwareDetectionEnabled || plugin == null) { memoryMb = conf.getInt(YarnConfiguration.NM_PMEM_MB, YarnConfiguration.DEFAULT_NM_PMEM_MB); if (memoryMb == -1) { memoryMb = YarnConfiguration.DEFAULT_NM_PMEM_MB; } } else { memoryMb = conf.getInt(YarnConfiguration.NM_PMEM_MB, -1); if (memoryMb == -1) { int physicalMemoryMB = (int) (plugin.getPhysicalMemorySize() / (1024 * 1024)); int hadoopHeapSizeMB = (int) (Runtime.getRuntime().maxMemory() / (1024 * 1024)); int containerPhysicalMemoryMB = (int) (0.8f * (physicalMemoryMB - (2 * hadoopHeapSizeMB))); int reservedMemoryMB = conf.getInt(YarnConfiguration.NM_SYSTEM_RESERVED_PMEM_MB, -1); if (reservedMemoryMB != -1) { containerPhysicalMemoryMB = physicalMemoryMB - reservedMemoryMB; } if(containerPhysicalMemoryMB <= 0) { LOG.error("Calculated memory for YARN containers is too low." + " Node memory is " + physicalMemoryMB + " MB, system reserved memory is " + reservedMemoryMB + " MB."); } containerPhysicalMemoryMB = Math.max(containerPhysicalMemoryMB, 0); memoryMb = containerPhysicalMemoryMB; } } if(memoryMb <= 0) { String message = "Illegal value for " + YarnConfiguration.NM_PMEM_MB + ". Value must be greater than 0."; throw new IllegalArgumentException(message); } return memoryMb; } }
cnfire/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/util/NodeManagerHardwareUtils.java
Java
apache-2.0
12,556
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // DO NOT EDIT. GENERATED BY // go run makeisprint.go -output isprint.go package strconv // (470+136+73)*2 + (342)*4 = 2726 bytes var isPrint16 = []uint16{ 0x0020, 0x007e, 0x00a1, 0x0377, 0x037a, 0x037f, 0x0384, 0x0556, 0x0559, 0x058a, 0x058d, 0x05c7, 0x05d0, 0x05ea, 0x05f0, 0x05f4, 0x0606, 0x061b, 0x061e, 0x070d, 0x0710, 0x074a, 0x074d, 0x07b1, 0x07c0, 0x07fa, 0x0800, 0x082d, 0x0830, 0x085b, 0x085e, 0x085e, 0x08a0, 0x08b4, 0x08e3, 0x098c, 0x098f, 0x0990, 0x0993, 0x09b2, 0x09b6, 0x09b9, 0x09bc, 0x09c4, 0x09c7, 0x09c8, 0x09cb, 0x09ce, 0x09d7, 0x09d7, 0x09dc, 0x09e3, 0x09e6, 0x09fb, 0x0a01, 0x0a0a, 0x0a0f, 0x0a10, 0x0a13, 0x0a39, 0x0a3c, 0x0a42, 0x0a47, 0x0a48, 0x0a4b, 0x0a4d, 0x0a51, 0x0a51, 0x0a59, 0x0a5e, 0x0a66, 0x0a75, 0x0a81, 0x0ab9, 0x0abc, 0x0acd, 0x0ad0, 0x0ad0, 0x0ae0, 0x0ae3, 0x0ae6, 0x0af1, 0x0af9, 0x0af9, 0x0b01, 0x0b0c, 0x0b0f, 0x0b10, 0x0b13, 0x0b39, 0x0b3c, 0x0b44, 0x0b47, 0x0b48, 0x0b4b, 0x0b4d, 0x0b56, 0x0b57, 0x0b5c, 0x0b63, 0x0b66, 0x0b77, 0x0b82, 0x0b8a, 0x0b8e, 0x0b95, 0x0b99, 0x0b9f, 0x0ba3, 0x0ba4, 0x0ba8, 0x0baa, 0x0bae, 0x0bb9, 0x0bbe, 0x0bc2, 0x0bc6, 0x0bcd, 0x0bd0, 0x0bd0, 0x0bd7, 0x0bd7, 0x0be6, 0x0bfa, 0x0c00, 0x0c39, 0x0c3d, 0x0c4d, 0x0c55, 0x0c5a, 0x0c60, 0x0c63, 0x0c66, 0x0c6f, 0x0c78, 0x0cb9, 0x0cbc, 0x0ccd, 0x0cd5, 0x0cd6, 0x0cde, 0x0ce3, 0x0ce6, 0x0cf2, 0x0d01, 0x0d3a, 0x0d3d, 0x0d4e, 0x0d57, 0x0d57, 0x0d5f, 0x0d63, 0x0d66, 0x0d75, 0x0d79, 0x0d7f, 0x0d82, 0x0d96, 0x0d9a, 0x0dbd, 0x0dc0, 0x0dc6, 0x0dca, 0x0dca, 0x0dcf, 0x0ddf, 0x0de6, 0x0def, 0x0df2, 0x0df4, 0x0e01, 0x0e3a, 0x0e3f, 0x0e5b, 0x0e81, 0x0e84, 0x0e87, 0x0e8a, 0x0e8d, 0x0e8d, 0x0e94, 0x0ea7, 0x0eaa, 0x0ebd, 0x0ec0, 0x0ecd, 0x0ed0, 0x0ed9, 0x0edc, 0x0edf, 0x0f00, 0x0f6c, 0x0f71, 0x0fda, 0x1000, 0x10c7, 0x10cd, 0x10cd, 0x10d0, 0x124d, 0x1250, 0x125d, 0x1260, 0x128d, 0x1290, 0x12b5, 0x12b8, 0x12c5, 0x12c8, 0x1315, 0x1318, 0x135a, 0x135d, 0x137c, 0x1380, 0x1399, 0x13a0, 0x13f5, 0x13f8, 0x13fd, 0x1400, 0x169c, 0x16a0, 0x16f8, 0x1700, 0x1714, 0x1720, 0x1736, 0x1740, 0x1753, 0x1760, 0x1773, 0x1780, 0x17dd, 0x17e0, 0x17e9, 0x17f0, 0x17f9, 0x1800, 0x180d, 0x1810, 0x1819, 0x1820, 0x1877, 0x1880, 0x18aa, 0x18b0, 0x18f5, 0x1900, 0x192b, 0x1930, 0x193b, 0x1940, 0x1940, 0x1944, 0x196d, 0x1970, 0x1974, 0x1980, 0x19ab, 0x19b0, 0x19c9, 0x19d0, 0x19da, 0x19de, 0x1a1b, 0x1a1e, 0x1a7c, 0x1a7f, 0x1a89, 0x1a90, 0x1a99, 0x1aa0, 0x1aad, 0x1ab0, 0x1abe, 0x1b00, 0x1b4b, 0x1b50, 0x1b7c, 0x1b80, 0x1bf3, 0x1bfc, 0x1c37, 0x1c3b, 0x1c49, 0x1c4d, 0x1c7f, 0x1cc0, 0x1cc7, 0x1cd0, 0x1cf9, 0x1d00, 0x1df5, 0x1dfc, 0x1f15, 0x1f18, 0x1f1d, 0x1f20, 0x1f45, 0x1f48, 0x1f4d, 0x1f50, 0x1f7d, 0x1f80, 0x1fd3, 0x1fd6, 0x1fef, 0x1ff2, 0x1ffe, 0x2010, 0x2027, 0x2030, 0x205e, 0x2070, 0x2071, 0x2074, 0x209c, 0x20a0, 0x20be, 0x20d0, 0x20f0, 0x2100, 0x218b, 0x2190, 0x23fa, 0x2400, 0x2426, 0x2440, 0x244a, 0x2460, 0x2b73, 0x2b76, 0x2b95, 0x2b98, 0x2bb9, 0x2bbd, 0x2bd1, 0x2bec, 0x2bef, 0x2c00, 0x2cf3, 0x2cf9, 0x2d27, 0x2d2d, 0x2d2d, 0x2d30, 0x2d67, 0x2d6f, 0x2d70, 0x2d7f, 0x2d96, 0x2da0, 0x2e42, 0x2e80, 0x2ef3, 0x2f00, 0x2fd5, 0x2ff0, 0x2ffb, 0x3001, 0x3096, 0x3099, 0x30ff, 0x3105, 0x312d, 0x3131, 0x31ba, 0x31c0, 0x31e3, 0x31f0, 0x4db5, 0x4dc0, 0x9fd5, 0xa000, 0xa48c, 0xa490, 0xa4c6, 0xa4d0, 0xa62b, 0xa640, 0xa6f7, 0xa700, 0xa7ad, 0xa7b0, 0xa7b7, 0xa7f7, 0xa82b, 0xa830, 0xa839, 0xa840, 0xa877, 0xa880, 0xa8c4, 0xa8ce, 0xa8d9, 0xa8e0, 0xa8fd, 0xa900, 0xa953, 0xa95f, 0xa97c, 0xa980, 0xa9d9, 0xa9de, 0xaa36, 0xaa40, 0xaa4d, 0xaa50, 0xaa59, 0xaa5c, 0xaac2, 0xaadb, 0xaaf6, 0xab01, 0xab06, 0xab09, 0xab0e, 0xab11, 0xab16, 0xab20, 0xab65, 0xab70, 0xabed, 0xabf0, 0xabf9, 0xac00, 0xd7a3, 0xd7b0, 0xd7c6, 0xd7cb, 0xd7fb, 0xf900, 0xfa6d, 0xfa70, 0xfad9, 0xfb00, 0xfb06, 0xfb13, 0xfb17, 0xfb1d, 0xfbc1, 0xfbd3, 0xfd3f, 0xfd50, 0xfd8f, 0xfd92, 0xfdc7, 0xfdf0, 0xfdfd, 0xfe00, 0xfe19, 0xfe20, 0xfe6b, 0xfe70, 0xfefc, 0xff01, 0xffbe, 0xffc2, 0xffc7, 0xffca, 0xffcf, 0xffd2, 0xffd7, 0xffda, 0xffdc, 0xffe0, 0xffee, 0xfffc, 0xfffd, } var isNotPrint16 = []uint16{ 0x00ad, 0x038b, 0x038d, 0x03a2, 0x0530, 0x0560, 0x0588, 0x0590, 0x06dd, 0x083f, 0x0984, 0x09a9, 0x09b1, 0x09de, 0x0a04, 0x0a29, 0x0a31, 0x0a34, 0x0a37, 0x0a3d, 0x0a5d, 0x0a84, 0x0a8e, 0x0a92, 0x0aa9, 0x0ab1, 0x0ab4, 0x0ac6, 0x0aca, 0x0b04, 0x0b29, 0x0b31, 0x0b34, 0x0b5e, 0x0b84, 0x0b91, 0x0b9b, 0x0b9d, 0x0bc9, 0x0c04, 0x0c0d, 0x0c11, 0x0c29, 0x0c45, 0x0c49, 0x0c57, 0x0c80, 0x0c84, 0x0c8d, 0x0c91, 0x0ca9, 0x0cb4, 0x0cc5, 0x0cc9, 0x0cdf, 0x0cf0, 0x0d04, 0x0d0d, 0x0d11, 0x0d45, 0x0d49, 0x0d84, 0x0db2, 0x0dbc, 0x0dd5, 0x0dd7, 0x0e83, 0x0e89, 0x0e98, 0x0ea0, 0x0ea4, 0x0ea6, 0x0eac, 0x0eba, 0x0ec5, 0x0ec7, 0x0f48, 0x0f98, 0x0fbd, 0x0fcd, 0x10c6, 0x1249, 0x1257, 0x1259, 0x1289, 0x12b1, 0x12bf, 0x12c1, 0x12d7, 0x1311, 0x1680, 0x170d, 0x176d, 0x1771, 0x191f, 0x1a5f, 0x1cf7, 0x1f58, 0x1f5a, 0x1f5c, 0x1f5e, 0x1fb5, 0x1fc5, 0x1fdc, 0x1ff5, 0x208f, 0x2bc9, 0x2c2f, 0x2c5f, 0x2d26, 0x2da7, 0x2daf, 0x2db7, 0x2dbf, 0x2dc7, 0x2dcf, 0x2dd7, 0x2ddf, 0x2e9a, 0x3040, 0x318f, 0x321f, 0x32ff, 0xa9ce, 0xa9ff, 0xab27, 0xab2f, 0xfb37, 0xfb3d, 0xfb3f, 0xfb42, 0xfb45, 0xfe53, 0xfe67, 0xfe75, 0xffe7, } var isPrint32 = []uint32{ 0x010000, 0x01004d, 0x010050, 0x01005d, 0x010080, 0x0100fa, 0x010100, 0x010102, 0x010107, 0x010133, 0x010137, 0x01018c, 0x010190, 0x01019b, 0x0101a0, 0x0101a0, 0x0101d0, 0x0101fd, 0x010280, 0x01029c, 0x0102a0, 0x0102d0, 0x0102e0, 0x0102fb, 0x010300, 0x010323, 0x010330, 0x01034a, 0x010350, 0x01037a, 0x010380, 0x0103c3, 0x0103c8, 0x0103d5, 0x010400, 0x01049d, 0x0104a0, 0x0104a9, 0x010500, 0x010527, 0x010530, 0x010563, 0x01056f, 0x01056f, 0x010600, 0x010736, 0x010740, 0x010755, 0x010760, 0x010767, 0x010800, 0x010805, 0x010808, 0x010838, 0x01083c, 0x01083c, 0x01083f, 0x01089e, 0x0108a7, 0x0108af, 0x0108e0, 0x0108f5, 0x0108fb, 0x01091b, 0x01091f, 0x010939, 0x01093f, 0x01093f, 0x010980, 0x0109b7, 0x0109bc, 0x0109cf, 0x0109d2, 0x010a06, 0x010a0c, 0x010a33, 0x010a38, 0x010a3a, 0x010a3f, 0x010a47, 0x010a50, 0x010a58, 0x010a60, 0x010a9f, 0x010ac0, 0x010ae6, 0x010aeb, 0x010af6, 0x010b00, 0x010b35, 0x010b39, 0x010b55, 0x010b58, 0x010b72, 0x010b78, 0x010b91, 0x010b99, 0x010b9c, 0x010ba9, 0x010baf, 0x010c00, 0x010c48, 0x010c80, 0x010cb2, 0x010cc0, 0x010cf2, 0x010cfa, 0x010cff, 0x010e60, 0x010e7e, 0x011000, 0x01104d, 0x011052, 0x01106f, 0x01107f, 0x0110c1, 0x0110d0, 0x0110e8, 0x0110f0, 0x0110f9, 0x011100, 0x011143, 0x011150, 0x011176, 0x011180, 0x0111cd, 0x0111d0, 0x0111f4, 0x011200, 0x01123d, 0x011280, 0x0112a9, 0x0112b0, 0x0112ea, 0x0112f0, 0x0112f9, 0x011300, 0x01130c, 0x01130f, 0x011310, 0x011313, 0x011339, 0x01133c, 0x011344, 0x011347, 0x011348, 0x01134b, 0x01134d, 0x011350, 0x011350, 0x011357, 0x011357, 0x01135d, 0x011363, 0x011366, 0x01136c, 0x011370, 0x011374, 0x011480, 0x0114c7, 0x0114d0, 0x0114d9, 0x011580, 0x0115b5, 0x0115b8, 0x0115dd, 0x011600, 0x011644, 0x011650, 0x011659, 0x011680, 0x0116b7, 0x0116c0, 0x0116c9, 0x011700, 0x011719, 0x01171d, 0x01172b, 0x011730, 0x01173f, 0x0118a0, 0x0118f2, 0x0118ff, 0x0118ff, 0x011ac0, 0x011af8, 0x012000, 0x012399, 0x012400, 0x012474, 0x012480, 0x012543, 0x013000, 0x01342e, 0x014400, 0x014646, 0x016800, 0x016a38, 0x016a40, 0x016a69, 0x016a6e, 0x016a6f, 0x016ad0, 0x016aed, 0x016af0, 0x016af5, 0x016b00, 0x016b45, 0x016b50, 0x016b77, 0x016b7d, 0x016b8f, 0x016f00, 0x016f44, 0x016f50, 0x016f7e, 0x016f8f, 0x016f9f, 0x01b000, 0x01b001, 0x01bc00, 0x01bc6a, 0x01bc70, 0x01bc7c, 0x01bc80, 0x01bc88, 0x01bc90, 0x01bc99, 0x01bc9c, 0x01bc9f, 0x01d000, 0x01d0f5, 0x01d100, 0x01d126, 0x01d129, 0x01d172, 0x01d17b, 0x01d1e8, 0x01d200, 0x01d245, 0x01d300, 0x01d356, 0x01d360, 0x01d371, 0x01d400, 0x01d49f, 0x01d4a2, 0x01d4a2, 0x01d4a5, 0x01d4a6, 0x01d4a9, 0x01d50a, 0x01d50d, 0x01d546, 0x01d54a, 0x01d6a5, 0x01d6a8, 0x01d7cb, 0x01d7ce, 0x01da8b, 0x01da9b, 0x01daaf, 0x01e800, 0x01e8c4, 0x01e8c7, 0x01e8d6, 0x01ee00, 0x01ee24, 0x01ee27, 0x01ee3b, 0x01ee42, 0x01ee42, 0x01ee47, 0x01ee54, 0x01ee57, 0x01ee64, 0x01ee67, 0x01ee9b, 0x01eea1, 0x01eebb, 0x01eef0, 0x01eef1, 0x01f000, 0x01f02b, 0x01f030, 0x01f093, 0x01f0a0, 0x01f0ae, 0x01f0b1, 0x01f0f5, 0x01f100, 0x01f10c, 0x01f110, 0x01f16b, 0x01f170, 0x01f19a, 0x01f1e6, 0x01f202, 0x01f210, 0x01f23a, 0x01f240, 0x01f248, 0x01f250, 0x01f251, 0x01f300, 0x01f6d0, 0x01f6e0, 0x01f6ec, 0x01f6f0, 0x01f6f3, 0x01f700, 0x01f773, 0x01f780, 0x01f7d4, 0x01f800, 0x01f80b, 0x01f810, 0x01f847, 0x01f850, 0x01f859, 0x01f860, 0x01f887, 0x01f890, 0x01f8ad, 0x01f910, 0x01f918, 0x01f980, 0x01f984, 0x01f9c0, 0x01f9c0, 0x020000, 0x02a6d6, 0x02a700, 0x02b734, 0x02b740, 0x02b81d, 0x02b820, 0x02cea1, 0x02f800, 0x02fa1d, 0x0e0100, 0x0e01ef, } var isNotPrint32 = []uint16{ // add 0x10000 to each entry 0x000c, 0x0027, 0x003b, 0x003e, 0x039e, 0x0809, 0x0836, 0x0856, 0x08f3, 0x0a04, 0x0a14, 0x0a18, 0x10bd, 0x1135, 0x11e0, 0x1212, 0x1287, 0x1289, 0x128e, 0x129e, 0x1304, 0x1329, 0x1331, 0x1334, 0x246f, 0x6a5f, 0x6b5a, 0x6b62, 0xd455, 0xd49d, 0xd4ad, 0xd4ba, 0xd4bc, 0xd4c4, 0xd506, 0xd515, 0xd51d, 0xd53a, 0xd53f, 0xd545, 0xd551, 0xdaa0, 0xee04, 0xee20, 0xee23, 0xee28, 0xee33, 0xee38, 0xee3a, 0xee48, 0xee4a, 0xee4c, 0xee50, 0xee53, 0xee58, 0xee5a, 0xee5c, 0xee5e, 0xee60, 0xee63, 0xee6b, 0xee73, 0xee78, 0xee7d, 0xee7f, 0xee8a, 0xeea4, 0xeeaa, 0xf0c0, 0xf0d0, 0xf12f, 0xf57a, 0xf5a4, }
shines77/go
src/strconv/isprint.go
GO
bsd-3-clause
9,915
/*! UIkit 2.13.1 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ (function(addon) { var component; if (jQuery && UIkit) { component = addon(jQuery, UIkit); } if (typeof define == "function" && define.amd) { define("uikit-notify", ["uikit"], function(){ return component || addon(jQuery, UIkit); }); } })(function($, UI){ "use strict"; var containers = {}, messages = {}, notify = function(options){ if ($.type(options) == 'string') { options = { message: options }; } if (arguments[1]) { options = $.extend(options, $.type(arguments[1]) == 'string' ? {status:arguments[1]} : arguments[1]); } return (new Message(options)).show(); }, closeAll = function(group, instantly){ var id; if (group) { for(id in messages) { if(group===messages[id].group) messages[id].close(instantly); } } else { for(id in messages) { messages[id].close(instantly); } } }; var Message = function(options){ var $this = this; this.options = $.extend({}, Message.defaults, options); this.uuid = UI.Utils.uid("notifymsg"); this.element = UI.$([ '<div class="@-notify-message">', '<a class="@-close"></a>', '<div></div>', '</div>' ].join('')).data("notifyMessage", this); this.content(this.options.message); // status if (this.options.status) { this.element.addClass('@-notify-message-'+this.options.status); this.currentstatus = this.options.status; } this.group = this.options.group; messages[this.uuid] = this; if(!containers[this.options.pos]) { containers[this.options.pos] = UI.$('<div class="@-notify @-notify-'+this.options.pos+'"></div>').appendTo('body').on("click", UI.prefix(".@-notify-message"), function(){ UI.$(this).data("notifyMessage").close(); }); } }; $.extend(Message.prototype, { uuid: false, element: false, timout: false, currentstatus: "", group: false, show: function() { if (this.element.is(":visible")) return; var $this = this; containers[this.options.pos].show().prepend(this.element); var marginbottom = parseInt(this.element.css("margin-bottom"), 10); this.element.css({"opacity":0, "margin-top": -1*this.element.outerHeight(), "margin-bottom":0}).animate({"opacity":1, "margin-top": 0, "margin-bottom":marginbottom}, function(){ if ($this.options.timeout) { var closefn = function(){ $this.close(); }; $this.timeout = setTimeout(closefn, $this.options.timeout); $this.element.hover( function() { clearTimeout($this.timeout); }, function() { $this.timeout = setTimeout(closefn, $this.options.timeout); } ); } }); return this; }, close: function(instantly) { var $this = this, finalize = function(){ $this.element.remove(); if(!containers[$this.options.pos].children().length) { containers[$this.options.pos].hide(); } $this.options.onClose.apply($this, []); delete messages[$this.uuid]; }; if (this.timeout) clearTimeout(this.timeout); if (instantly) { finalize(); } else { this.element.animate({"opacity":0, "margin-top": -1* this.element.outerHeight(), "margin-bottom":0}, function(){ finalize(); }); } }, content: function(html){ var container = this.element.find(">div"); if(!html) { return container.html(); } container.html(html); return this; }, status: function(status) { if (!status) { return this.currentstatus; } this.element.removeClass('@-notify-message-'+this.currentstatus).addClass('@-notify-message-'+status); this.currentstatus = status; return this; } }); Message.defaults = { message: "", status: "", timeout: 5000, group: null, pos: 'top-center', onClose: function() {} }; UI.notify = notify; UI.notify.message = Message; UI.notify.closeAll = closeAll; return notify; });
AppConcur/islacart
sites/all/themes/marketplace/vendor/uikit/js/components/notify.js
JavaScript
gpl-2.0
4,965
<?php /** * @package FrameworkOnFramework * @subpackage form * @copyright Copyright (C) 2010 - 2012 Akeeba Ltd. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // Protect from unauthorized access defined('_JEXEC') or die; /** * Field header for Published (enabled) columns * * @package FrameworkOnFramework * @since 2.0 */ class FOFFormHeaderPublished extends FOFFormHeaderFieldselectable { /** * Create objects for the options * * @return array The array of option objects */ protected function getOptions() { $config = array( 'published' => 1, 'unpublished' => 1, 'archived' => 0, 'trash' => 0, 'all' => 0, ); $stack = array(); if ($this->element['show_published'] == 'false') { $config['published'] = 0; } if ($this->element['show_unpublished'] == 'false') { $config['unpublished'] = 0; } if ($this->element['show_archived'] == 'true') { $config['archived'] = 1; } if ($this->element['show_trash'] == 'true') { $config['trash'] = 1; } if ($this->element['show_all'] == 'true') { $config['all'] = 1; } $options = JHtml::_('jgrid.publishedOptions', $config); reset($options); return $options; } }
effortlesssites/template
tmp/com_akeeba-3.9.2-core/fof/form/header/published.php
PHP
gpl-2.0
1,276
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class CompareInfoIsSuffixTests { private static CompareInfo s_invariantCompare = CultureInfo.InvariantCulture.CompareInfo; private static CompareInfo s_hungarianCompare = new CultureInfo("hu-HU").CompareInfo; private static CompareInfo s_turkishCompare = new CultureInfo("tr-TR").CompareInfo; public static IEnumerable<object[]> IsSuffix_TestData() { // Empty strings yield return new object[] { s_invariantCompare, "foo", "", CompareOptions.None, true }; yield return new object[] { s_invariantCompare, "", "", CompareOptions.None, true }; // Long strings yield return new object[] { s_invariantCompare, new string('a', 5555), "aaaaaaaaaaaaaaa", CompareOptions.None, true }; yield return new object[] { s_invariantCompare, new string('a', 5555), new string('a', 5000), CompareOptions.None, true }; yield return new object[] { s_invariantCompare, new string('a', 5555), new string('a', 5000) + "b", CompareOptions.None, false }; // Hungarian yield return new object[] { s_hungarianCompare, "foobardzsdzs", "rddzs", CompareOptions.Ordinal, false }; yield return new object[] { s_invariantCompare, "foobardzsdzs", "rddzs", CompareOptions.None, false }; yield return new object[] { s_invariantCompare, "foobardzsdzs", "rddzs", CompareOptions.Ordinal, false }; // Turkish yield return new object[] { s_turkishCompare, "Hi", "I", CompareOptions.None, false }; yield return new object[] { s_turkishCompare, "Hi", "I", CompareOptions.IgnoreCase, false }; yield return new object[] { s_turkishCompare, "Hi", "\u0130", CompareOptions.None, false }; yield return new object[] { s_turkishCompare, "Hi", "\u0130", CompareOptions.IgnoreCase, true }; yield return new object[] { s_invariantCompare, "Hi", "I", CompareOptions.None, false }; yield return new object[] { s_invariantCompare, "Hi", "I", CompareOptions.IgnoreCase, true }; yield return new object[] { s_invariantCompare, "Hi", "\u0130", CompareOptions.None, false }; yield return new object[] { s_invariantCompare, "Hi", "\u0130", CompareOptions.IgnoreCase, false }; // Unicode yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "A\u0300", CompareOptions.None, true }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "A\u0300", CompareOptions.Ordinal, false }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", CompareOptions.None, false }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", CompareOptions.IgnoreCase, true }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", CompareOptions.Ordinal, false }; yield return new object[] { s_invariantCompare, "Exhibit \u00C0", "a\u0300", CompareOptions.OrdinalIgnoreCase, false }; yield return new object[] { s_invariantCompare, "FooBar", "Foo\u0400Bar", CompareOptions.Ordinal, false }; yield return new object[] { s_invariantCompare, "FooBA\u0300R", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, true }; // Ignore symbols yield return new object[] { s_invariantCompare, "More Test's", "Tests", CompareOptions.IgnoreSymbols, true }; yield return new object[] { s_invariantCompare, "More Test's", "Tests", CompareOptions.None, false }; // Platform differences yield return new object[] { s_hungarianCompare, "foobardzsdzs", "rddzs", CompareOptions.None, PlatformDetection.IsWindows ? true : false }; } [Theory] [MemberData(nameof(IsSuffix_TestData))] public void IsSuffix(CompareInfo compareInfo, string source, string value, CompareOptions options, bool expected) { if (options == CompareOptions.None) { Assert.Equal(expected, compareInfo.IsSuffix(source, value)); } Assert.Equal(expected, compareInfo.IsSuffix(source, value, options)); } [Fact] public void IsSuffix_UnassignedUnicode() { bool result = PlatformDetection.IsWindows ? true : false; IsSuffix(s_invariantCompare, "FooBar", "Foo\uFFFFBar", CompareOptions.None, result); IsSuffix(s_invariantCompare, "FooBar", "Foo\uFFFFBar", CompareOptions.IgnoreNonSpace, result); } [Fact] public void IsSuffix_Invalid() { // Source is null AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.IsSuffix(null, "")); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.IsSuffix(null, "", CompareOptions.None)); // Prefix is null AssertExtensions.Throws<ArgumentNullException>("suffix", () => s_invariantCompare.IsSuffix("", null)); AssertExtensions.Throws<ArgumentNullException>("suffix", () => s_invariantCompare.IsSuffix("", null, CompareOptions.None)); // Source and prefix are null AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.IsSuffix(null, null)); AssertExtensions.Throws<ArgumentNullException>("source", () => s_invariantCompare.IsSuffix(null, null, CompareOptions.None)); // Options are invalid AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.IsSuffix("Test's", "Tests", CompareOptions.StringSort)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.IsSuffix("Test's", "Tests", CompareOptions.Ordinal | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.IsSuffix("Test's", "Tests", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth)); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.IsSuffix("Test's", "Tests", (CompareOptions)(-1))); AssertExtensions.Throws<ArgumentException>("options", () => s_invariantCompare.IsSuffix("Test's", "Tests", (CompareOptions)0x11111111)); } } }
BrennanConroy/corefx
src/System.Globalization/tests/CompareInfo/CompareInfoTests.IsSuffix.cs
C#
mit
6,686
package graph import ( "errors" "fmt" "net" "net/url" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/image" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) type v1Puller struct { *TagStore endpoint registry.APIEndpoint config *ImagePullConfig sf *streamformatter.StreamFormatter repoInfo *registry.RepositoryInfo session *registry.Session } func (p *v1Puller) Pull(tag string) (fallback bool, err error) { if utils.DigestReference(tag) { // Allowing fallback, because HTTPS v1 is before HTTP v2 return true, registry.ErrNoSupport{errors.New("Cannot pull by digest with v1 registry")} } tlsConfig, err := p.registryService.TLSConfig(p.repoInfo.Index.Name) if err != nil { return false, err } // Adds Docker-specific headers as well as user-specified headers (metaHeaders) tr := transport.NewTransport( // TODO(tiborvass): was ReceiveTimeout registry.NewTransport(tlsConfig), registry.DockerHeaders(p.config.MetaHeaders)..., ) client := registry.HTTPClient(tr) v1Endpoint, err := p.endpoint.ToV1Endpoint(p.config.MetaHeaders) if err != nil { logrus.Debugf("Could not get v1 endpoint: %v", err) return true, err } p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint) if err != nil { // TODO(dmcgowan): Check if should fallback logrus.Debugf("Fallback from error: %s", err) return true, err } if err := p.pullRepository(tag); err != nil { // TODO(dmcgowan): Check if should fallback return false, err } return false, nil } func (p *v1Puller) pullRepository(askedTag string) error { out := p.config.OutStream out.Write(p.sf.FormatStatus("", "Pulling repository %s", p.repoInfo.CanonicalName)) repoData, err := p.session.GetRepositoryData(p.repoInfo.RemoteName) if err != nil { if strings.Contains(err.Error(), "HTTP code: 404") { return fmt.Errorf("Error: image %s not found", utils.ImageReference(p.repoInfo.RemoteName, askedTag)) } // Unexpected HTTP error return err } logrus.Debugf("Retrieving the tag list") tagsList := make(map[string]string) if askedTag == "" { tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo.RemoteName) } else { var tagID string tagID, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo.RemoteName, askedTag) tagsList[askedTag] = tagID } if err != nil { if err == registry.ErrRepoNotFound && askedTag != "" { return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName) } logrus.Errorf("unable to get remote tags: %s", err) return err } for tag, id := range tagsList { repoData.ImgList[id] = &registry.ImgData{ ID: id, Tag: tag, Checksum: "", } } logrus.Debugf("Registering tags") // If no tag has been specified, pull them all if askedTag == "" { for tag, id := range tagsList { repoData.ImgList[id].Tag = tag } } else { // Otherwise, check that the tag exists and use only that one id, exists := tagsList[askedTag] if !exists { return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName) } repoData.ImgList[id].Tag = askedTag } errors := make(chan error) layersDownloaded := false imgIDs := []string{} sessionID := p.session.ID() defer func() { p.graph.Release(sessionID, imgIDs...) }() for _, image := range repoData.ImgList { downloadImage := func(img *registry.ImgData) { if askedTag != "" && img.Tag != askedTag { errors <- nil return } if img.Tag == "" { logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID) errors <- nil return } // ensure no two downloads of the same image happen at the same time if c, err := p.poolAdd("pull", "img:"+img.ID); err != nil { if c != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil)) <-c out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) } else { logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) } errors <- nil return } defer p.poolRemove("pull", "img:"+img.ID) // we need to retain it until tagging p.graph.Retain(sessionID, img.ID) imgIDs = append(imgIDs, img.ID) out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s", img.Tag, p.repoInfo.CanonicalName), nil)) success := false var lastErr, err error var isDownloaded bool for _, ep := range p.repoInfo.Index.Mirrors { ep += "v1/" out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil { // Don't report errors when pulling from mirrors. logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err) continue } layersDownloaded = layersDownloaded || isDownloaded success = true break } if !success { for _, ep := range repoData.Endpoints { out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil { // It's not ideal that only the last error is returned, it would be better to concatenate the errors. // As the error is also given to the output stream the user will see the error. lastErr = err out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err), nil)) continue } layersDownloaded = layersDownloaded || isDownloaded success = true break } } if !success { err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.CanonicalName, lastErr) out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), err.Error(), nil)) errors <- err return } out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) errors <- nil } go downloadImage(image) } var lastError error for i := 0; i < len(repoData.ImgList); i++ { if err := <-errors; err != nil { lastError = err } } if lastError != nil { return lastError } for tag, id := range tagsList { if askedTag != "" && tag != askedTag { continue } if err := p.Tag(p.repoInfo.LocalName, tag, id, true); err != nil { return err } } requestedTag := p.repoInfo.LocalName if len(askedTag) > 0 { requestedTag = utils.ImageReference(p.repoInfo.LocalName, askedTag) } writeStatus(requestedTag, out, p.sf, layersDownloaded) return nil } func (p *v1Puller) pullImage(imgID, endpoint string, token []string) (bool, error) { history, err := p.session.GetRemoteHistory(imgID, endpoint) if err != nil { return false, err } out := p.config.OutStream out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Pulling dependent layers", nil)) // FIXME: Try to stream the images? // FIXME: Launch the getRemoteImage() in goroutines sessionID := p.session.ID() // As imgID has been retained in pullRepository, no need to retain again p.graph.Retain(sessionID, history[1:]...) defer p.graph.Release(sessionID, history[1:]...) layersDownloaded := false for i := len(history) - 1; i >= 0; i-- { id := history[i] // ensure no two downloads of the same layer happen at the same time if c, err := p.poolAdd("pull", "layer:"+id); err != nil { logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err) <-c } defer p.poolRemove("pull", "layer:"+id) if !p.graph.Exists(id) { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Pulling metadata", nil)) var ( imgJSON []byte imgSize int64 err error img *image.Image ) retries := 5 for j := 1; j <= retries; j++ { imgJSON, imgSize, err = p.session.GetRemoteImageJSON(id, endpoint) if err != nil && j == retries { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, err } else if err != nil { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } img, err = image.NewImgJSON(imgJSON) layersDownloaded = true if err != nil && j == retries { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, fmt.Errorf("Failed to parse json: %s", err) } else if err != nil { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else { break } } for j := 1; j <= retries; j++ { // Get the layer status := "Pulling fs layer" if j > 1 { status = fmt.Sprintf("Pulling fs layer [retries: %d]", j) } out.Write(p.sf.FormatProgress(stringid.TruncateID(id), status, nil)) layer, err := p.session.GetRemoteImageLayer(img.ID, endpoint, imgSize) if uerr, ok := err.(*url.Error); ok { err = uerr.Err } if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else if err != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, err } layersDownloaded = true defer layer.Close() err = p.graph.Register(img, progressreader.New(progressreader.Config{ In: layer, Out: out, Formatter: p.sf, Size: imgSize, NewLines: false, ID: stringid.TruncateID(id), Action: "Downloading", })) if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else if err != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error downloading dependent layers", nil)) return layersDownloaded, err } else { break } } } out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Download complete", nil)) } return layersDownloaded, nil }
fmoliveira/docker
graph/pull_v1.go
GO
apache-2.0
10,610
package rancher import ( "testing" "github.com/hashicorp/terraform/helper/resource" ) func TestAccRancherEnvironment_importBasic(t *testing.T) { resourceName := "rancher_environment.foo" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckRancherEnvironmentDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccRancherEnvironmentConfig, }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
stardog-union/stardog-graviton
vendor/github.com/hashicorp/terraform/builtin/providers/rancher/import_rancher_environment_test.go
GO
apache-2.0
605
class MyExc(Exception): pass e = MyExc(100, "Some error") print(e) print(repr(e)) print(e.args) try: raise MyExc("Some error") except MyExc as e: print("Caught exception:", repr(e)) try: raise MyExc("Some error2") except Exception as e: print("Caught exception:", repr(e)) try: raise MyExc("Some error2") except: print("Caught user exception")
AriZuu/micropython
tests/basics/subclass_native3.py
Python
mit
376
/*! * Bootstrap-select v1.7.0 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2015 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nu a fost selectat nimic', noneResultsText: 'Nu exista niciun rezultat {0}', countSelectedText: '{0} din {1} selectat(e)', maxOptionsText: ['Limita a fost atinsa ({n} {var} max)', 'Limita de grup a fost atinsa ({n} {var} max)', ['iteme', 'item']], multipleSeparator: ', ' }; })(jQuery);
dominic/cdnjs
ajax/libs/bootstrap-select/1.7.0/js/i18n/defaults-ro_RO.js
JavaScript
mit
597
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """MX-like base classes.""" import cStringIO import struct import dns.exception import dns.rdata import dns.name class MXBase(dns.rdata.Rdata): """Base class for rdata that is like an MX record. @ivar preference: the preference value @type preference: int @ivar exchange: the exchange name @type exchange: dns.name.Name object""" __slots__ = ['preference', 'exchange'] def __init__(self, rdclass, rdtype, preference, exchange): super(MXBase, self).__init__(rdclass, rdtype) self.preference = preference self.exchange = exchange def to_text(self, origin=None, relativize=True, **kw): exchange = self.exchange.choose_relativity(origin, relativize) return '%d %s' % (self.preference, exchange) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): preference = tok.get_uint16() exchange = tok.get_name() exchange = exchange.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, preference, exchange) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): pref = struct.pack("!H", self.preference) file.write(pref) self.exchange.to_wire(file, compress, origin) def to_digestable(self, origin = None): return struct.pack("!H", self.preference) + \ self.exchange.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (preference, ) = struct.unpack('!H', wire[current : current + 2]) current += 2 rdlen -= 2 (exchange, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: exchange = exchange.relativize(origin) return cls(rdclass, rdtype, preference, exchange) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.exchange = self.exchange.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!H", self.preference) op = struct.pack("!H", other.preference) v = cmp(sp, op) if v == 0: v = cmp(self.exchange, other.exchange) return v class UncompressedMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when converted to DNS wire format, and whose digestable form is not downcased.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedMX, self).to_wire(file, None, origin) def to_digestable(self, origin = None): f = cStringIO.StringIO() self.to_wire(f, None, origin) return f.getvalue() class UncompressedDowncasingMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when convert to DNS wire format.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedDowncasingMX, self).to_wire(file, None, origin)
enigmamarketing/csf-allow-domains
usr/local/csf/bin/csf-allow-domains/dns/rdtypes/mxbase.py
Python
mit
3,968
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.vending.expansion.downloader.impl; import com.android.vending.expansion.downloader.R; import com.google.android.vending.expansion.downloader.DownloadProgressInfo; import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller; import com.google.android.vending.expansion.downloader.Helpers; import com.google.android.vending.expansion.downloader.IDownloaderClient; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Messenger; /** * This class handles displaying the notification associated with the download * queue going on in the download manager. It handles multiple status types; * Some require user interaction and some do not. Some of the user interactions * may be transient. (for example: the user is queried to continue the download * on 3G when it started on WiFi, but then the phone locks onto WiFi again so * the prompt automatically goes away) * <p/> * The application interface for the downloader also needs to understand and * handle these transient states. */ public class DownloadNotification implements IDownloaderClient { private int mState; private final Context mContext; private final NotificationManager mNotificationManager; private String mCurrentTitle; private IDownloaderClient mClientProxy; final ICustomNotification mCustomNotification; private Notification mNotification; private Notification mCurrentNotification; private CharSequence mLabel; private String mCurrentText; private PendingIntent mContentIntent; private DownloadProgressInfo mProgressInfo; static final String LOGTAG = "DownloadNotification"; static final int NOTIFICATION_ID = LOGTAG.hashCode(); public PendingIntent getClientIntent() { return mContentIntent; } public void setClientIntent(PendingIntent mClientIntent) { this.mContentIntent = mClientIntent; } public void resendState() { if (null != mClientProxy) { mClientProxy.onDownloadStateChanged(mState); } } @Override public void onDownloadStateChanged(int newState) { if (null != mClientProxy) { mClientProxy.onDownloadStateChanged(newState); } if (newState != mState) { mState = newState; if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) { return; } int stringDownloadID; int iconResource; boolean ongoingEvent; // get the new title string and paused text switch (newState) { case 0: iconResource = android.R.drawable.stat_sys_warning; stringDownloadID = R.string.state_unknown; ongoingEvent = false; break; case IDownloaderClient.STATE_DOWNLOADING: iconResource = android.R.drawable.stat_sys_download; stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState); ongoingEvent = true; break; case IDownloaderClient.STATE_FETCHING_URL: case IDownloaderClient.STATE_CONNECTING: iconResource = android.R.drawable.stat_sys_download_done; stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState); ongoingEvent = true; break; case IDownloaderClient.STATE_COMPLETED: case IDownloaderClient.STATE_PAUSED_BY_REQUEST: iconResource = android.R.drawable.stat_sys_download_done; stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState); ongoingEvent = false; break; case IDownloaderClient.STATE_FAILED: case IDownloaderClient.STATE_FAILED_CANCELED: case IDownloaderClient.STATE_FAILED_FETCHING_URL: case IDownloaderClient.STATE_FAILED_SDCARD_FULL: case IDownloaderClient.STATE_FAILED_UNLICENSED: iconResource = android.R.drawable.stat_sys_warning; stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState); ongoingEvent = false; break; default: iconResource = android.R.drawable.stat_sys_warning; stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState); ongoingEvent = true; break; } mCurrentText = mContext.getString(stringDownloadID); mCurrentTitle = mLabel.toString(); mCurrentNotification.tickerText = mLabel + ": " + mCurrentText; mCurrentNotification.icon = iconResource; mCurrentNotification.setLatestEventInfo(mContext, mCurrentTitle, mCurrentText, mContentIntent); if (ongoingEvent) { mCurrentNotification.flags |= Notification.FLAG_ONGOING_EVENT; } else { mCurrentNotification.flags &= ~Notification.FLAG_ONGOING_EVENT; mCurrentNotification.flags |= Notification.FLAG_AUTO_CANCEL; } mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification); } } @Override public void onDownloadProgress(DownloadProgressInfo progress) { mProgressInfo = progress; if (null != mClientProxy) { mClientProxy.onDownloadProgress(progress); } if (progress.mOverallTotal <= 0) { // we just show the text mNotification.tickerText = mCurrentTitle; mNotification.icon = android.R.drawable.stat_sys_download; mNotification.setLatestEventInfo(mContext, mLabel, mCurrentText, mContentIntent); mCurrentNotification = mNotification; } else { mCustomNotification.setCurrentBytes(progress.mOverallProgress); mCustomNotification.setTotalBytes(progress.mOverallTotal); mCustomNotification.setIcon(android.R.drawable.stat_sys_download); mCustomNotification.setPendingIntent(mContentIntent); mCustomNotification.setTicker(mLabel + ": " + mCurrentText); mCustomNotification.setTitle(mLabel); mCustomNotification.setTimeRemaining(progress.mTimeRemaining); mCurrentNotification = mCustomNotification.updateNotification(mContext); } mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification); } public interface ICustomNotification { void setTitle(CharSequence title); void setTicker(CharSequence ticker); void setPendingIntent(PendingIntent mContentIntent); void setTotalBytes(long totalBytes); void setCurrentBytes(long currentBytes); void setIcon(int iconResource); void setTimeRemaining(long timeRemaining); Notification updateNotification(Context c); } /** * Called in response to onClientUpdated. Creates a new proxy and notifies * it of the current state. * * @param msg the client Messenger to notify */ public void setMessenger(Messenger msg) { mClientProxy = DownloaderClientMarshaller.CreateProxy(msg); if (null != mProgressInfo) { mClientProxy.onDownloadProgress(mProgressInfo); } if (mState != -1) { mClientProxy.onDownloadStateChanged(mState); } } /** * Constructor * * @param ctx The context to use to obtain access to the Notification * Service */ DownloadNotification(Context ctx, CharSequence applicationLabel) { mState = -1; mContext = ctx; mLabel = applicationLabel; mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); mCustomNotification = CustomNotificationFactory .createCustomNotification(); mNotification = new Notification(); mCurrentNotification = mNotification; } @Override public void onServiceConnected(Messenger m) { } }
alebianco/ANE-Android-Expansion
source/android/play_apk_expansion/downloader_library/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
Java
mit
9,068
<?php namespace Gliph\Visitor; /** * Interface for stateful algorithm visitors. */ interface StatefulVisitorInterface { const NOT_STARTED = 0; const IN_PROGRESS = 1; const COMPLETE = 2; /** * Returns an integer indicating the current state of the visitor. * * @return int * State should be one of the three StatefulVisitorInterface constants: * - 0: indicates the algorithm has not yet started. * - 1: indicates the algorithm is in progress. * - 2: indicates the algorithm is complete. */ public function getState(); }
webflo/d8-core
vendor/sdboyer/gliph/src/Gliph/Visitor/StatefulVisitorInterface.php
PHP
gpl-2.0
594
cask 'pocket-tanks' do version :latest sha256 :no_check url 'http://www.blitwise.com/ptanks_mac.dmg' name 'Pocket Tanks' homepage 'http://www.blitwise.com/index.html' app 'Pocket Tanks.app' end
wastrachan/homebrew-cask
Casks/pocket-tanks.rb
Ruby
bsd-2-clause
208
// Utility functions String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); }; function supportsHtmlStorage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function get_text(el) { ret = " "; var length = el.childNodes.length; for(var i = 0; i < length; i++) { var node = el.childNodes[i]; if(node.nodeType != 8) { if ( node.nodeType != 1 ) { // Strip white space. ret += node.nodeValue; } else { ret += get_text( node ); } } } return ret.trim(); }
sandbox-team/techtalk-portal
vendor/zenpen/js/utils.js
JavaScript
mit
641
'use strict'; var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native'); var DESCRIPTORS = require('../internals/descriptors'); var global = require('../internals/global'); var isObject = require('../internals/is-object'); var has = require('../internals/has'); var classof = require('../internals/classof'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var redefine = require('../internals/redefine'); var defineProperty = require('../internals/object-define-property').f; var getPrototypeOf = require('../internals/object-get-prototype-of'); var setPrototypeOf = require('../internals/object-set-prototype-of'); var wellKnownSymbol = require('../internals/well-known-symbol'); var uid = require('../internals/uid'); var Int8Array = global.Int8Array; var Int8ArrayPrototype = Int8Array && Int8Array.prototype; var Uint8ClampedArray = global.Uint8ClampedArray; var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; var TypedArray = Int8Array && getPrototypeOf(Int8Array); var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); var ObjectPrototype = Object.prototype; var isPrototypeOf = ObjectPrototype.isPrototypeOf; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQIRED = false; var NAME; var TypedArrayConstructorsList = { Int8Array: 1, Uint8Array: 1, Uint8ClampedArray: 1, Int16Array: 2, Uint16Array: 2, Int32Array: 4, Uint32Array: 4, Float32Array: 4, Float64Array: 8 }; var isView = function isView(it) { var klass = classof(it); return klass === 'DataView' || has(TypedArrayConstructorsList, klass); }; var isTypedArray = function (it) { return isObject(it) && has(TypedArrayConstructorsList, classof(it)); }; var aTypedArray = function (it) { if (isTypedArray(it)) return it; throw TypeError('Target is not a typed array'); }; var aTypedArrayConstructor = function (C) { if (setPrototypeOf) { if (isPrototypeOf.call(TypedArray, C)) return C; } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) { var TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { return C; } } throw TypeError('Target is not a typed array constructor'); }; var exportTypedArrayMethod = function (KEY, property, forced) { if (!DESCRIPTORS) return; if (forced) for (var ARRAY in TypedArrayConstructorsList) { var TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { delete TypedArrayConstructor.prototype[KEY]; } } if (!TypedArrayPrototype[KEY] || forced) { redefine(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); } }; var exportTypedArrayStaticMethod = function (KEY, property, forced) { var ARRAY, TypedArrayConstructor; if (!DESCRIPTORS) return; if (setPrototypeOf) { if (forced) for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { delete TypedArrayConstructor[KEY]; } } if (!TypedArray[KEY] || forced) { // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property); } catch (error) { /* empty */ } } else return; } for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { redefine(TypedArrayConstructor, KEY, property); } } }; for (NAME in TypedArrayConstructorsList) { if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { // eslint-disable-next-line no-shadow TypedArray = function TypedArray() { throw TypeError('Incorrect invocation'); }; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME], TypedArray); } } if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { TypedArrayPrototype = TypedArray.prototype; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); } } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); } if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) { TYPED_ARRAY_TAG_REQIRED = true; defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () { return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; } }); for (NAME in TypedArrayConstructorsList) if (global[NAME]) { createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME); } } module.exports = { NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, aTypedArray: aTypedArray, aTypedArrayConstructor: aTypedArrayConstructor, exportTypedArrayMethod: exportTypedArrayMethod, exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, isView: isView, isTypedArray: isTypedArray, TypedArray: TypedArray, TypedArrayPrototype: TypedArrayPrototype };
BigBoss424/portfolio
v8/development/node_modules/jimp/node_modules/core-js/internals/array-buffer-view-core.js
JavaScript
apache-2.0
6,017
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $ */ /** * The view that controls the showing and hiding of the sidebar. * * Although the sidebar view doesn't dispatch any events directly, it is a * resizable element (../utils/Resizer.js), which means it can dispatch Resizer * events. For example, if you want to listen for the sidebar showing * or hiding itself, set up listeners for the corresponding Resizer events, * panelCollapsed and panelExpanded: * * $("#sidebar").on("panelCollapsed", ...); * $("#sidebar").on("panelExpanded", ...); */ define(function (require, exports, module) { "use strict"; var AppInit = require("utils/AppInit"), ProjectManager = require("project/ProjectManager"), WorkingSetView = require("project/WorkingSetView"), MainViewManager = require("view/MainViewManager"), CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Strings = require("strings"), Resizer = require("utils/Resizer"), _ = require("thirdparty/lodash"); // These vars are initialized by the htmlReady handler // below since they refer to DOM elements var $sidebar, $gearMenu, $splitViewMenu, $projectTitle, $projectFilesContainer, $workingSetViewsContainer; var _cmdSplitNone, _cmdSplitVertical, _cmdSplitHorizontal; /** * @private * Update project title when the project root changes */ function _updateProjectTitle() { var displayName = ProjectManager.getProjectRoot().name; var fullPath = ProjectManager.getProjectRoot().fullPath; if (displayName === "" && fullPath === "/") { displayName = "/"; } $projectTitle.html(_.escape(displayName)); $projectTitle.attr("title", fullPath); // Trigger a scroll on the project files container to // reposition the scroller shadows and avoid issue #2255 $projectFilesContainer.trigger("scroll"); } /** * Toggle sidebar visibility. */ function toggle() { Resizer.toggle($sidebar); } /** * Show the sidebar. */ function show() { Resizer.show($sidebar); } /** * Hide the sidebar. */ function hide() { Resizer.hide($sidebar); } /** * Returns the visibility state of the sidebar. * @return {boolean} true if element is visible, false if it is not visible */ function isVisible() { return Resizer.isVisible($sidebar); } /** * Update state of working set * @private */ function _updateWorkingSetState() { if (MainViewManager.getPaneCount() === 1 && MainViewManager.getWorkingSetSize(MainViewManager.ACTIVE_PANE) === 0) { $workingSetViewsContainer.hide(); $gearMenu.hide(); } else { $workingSetViewsContainer.show(); $gearMenu.show(); } } /** * Update state of splitview and option elements * @private */ function _updateUIStates() { var spriteIndex, ICON_CLASSES = ["splitview-icon-none", "splitview-icon-vertical", "splitview-icon-horizontal"], layoutScheme = MainViewManager.getLayoutScheme(); if (layoutScheme.columns > 1) { spriteIndex = 1; } else if (layoutScheme.rows > 1) { spriteIndex = 2; } else { spriteIndex = 0; } // SplitView Icon $splitViewMenu.removeClass(ICON_CLASSES.join(" ")) .addClass(ICON_CLASSES[spriteIndex]); // SplitView Menu _cmdSplitNone.setChecked(spriteIndex === 0); _cmdSplitVertical.setChecked(spriteIndex === 1); _cmdSplitHorizontal.setChecked(spriteIndex === 2); // Options icon _updateWorkingSetState(); } /** * Handle No Split Command * @private */ function _handleSplitViewNone() { MainViewManager.setLayoutScheme(1, 1); } /** * Handle Vertical Split Command * @private */ function _handleSplitViewVertical() { MainViewManager.setLayoutScheme(1, 2); } /** * Handle Horizontal Split Command * @private */ function _handleSplitViewHorizontal() { MainViewManager.setLayoutScheme(2, 1); } // Initialize items dependent on HTML DOM AppInit.htmlReady(function () { $sidebar = $("#sidebar"); $gearMenu = $sidebar.find(".working-set-option-btn"); $splitViewMenu = $sidebar.find(".working-set-splitview-btn"); $projectTitle = $sidebar.find("#project-title"); $projectFilesContainer = $sidebar.find("#project-files-container"); $workingSetViewsContainer = $sidebar.find("#working-set-list-container"); function _resizeSidebarSelection() { var $element; $sidebar.find(".sidebar-selection").each(function (index, element) { $element = $(element); $element.width($element.parent()[0].scrollWidth); }); } // init $sidebar.on("panelResizeStart", function (evt, width) { $sidebar.find(".sidebar-selection-extension").css("display", "none"); $sidebar.find(".scroller-shadow").css("display", "none"); }); $sidebar.on("panelResizeUpdate", function (evt, width) { $sidebar.find(".sidebar-selection").width(width); ProjectManager._setFileTreeSelectionWidth(width); }); $sidebar.on("panelResizeEnd", function (evt, width) { _resizeSidebarSelection(); $sidebar.find(".sidebar-selection-extension").css("display", "block").css("left", width); $sidebar.find(".scroller-shadow").css("display", "block"); $projectFilesContainer.triggerHandler("scroll"); WorkingSetView.syncSelectionIndicator(); }); $sidebar.on("panelCollapsed", function (evt, width) { CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_SHOW_SIDEBAR); }); $sidebar.on("panelExpanded", function (evt, width) { WorkingSetView.refresh(); _resizeSidebarSelection(); $sidebar.find(".scroller-shadow").css("display", "block"); $sidebar.find(".sidebar-selection-extension").css("left", width); $projectFilesContainer.triggerHandler("scroll"); WorkingSetView.syncSelectionIndicator(); CommandManager.get(Commands.VIEW_HIDE_SIDEBAR).setName(Strings.CMD_HIDE_SIDEBAR); }); // AppInit.htmlReady in utils/Resizer executes before, so it's possible that the sidebar // is collapsed before we add the event. Check here initially if (!$sidebar.is(":visible")) { $sidebar.trigger("panelCollapsed"); } // wire up an event handler to monitor when panes are created MainViewManager.on("paneCreate", function (evt, paneId) { WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId); }); MainViewManager.on("paneLayoutChange", function () { _updateUIStates(); }); MainViewManager.on("workingSetAdd workingSetAddList workingSetRemove workingSetRemoveList workingSetUpdate", function () { _updateWorkingSetState(); }); // create WorkingSetViews for each pane already created _.forEach(MainViewManager.getPaneIdList(), function (paneId) { WorkingSetView.createWorkingSetViewForPane($workingSetViewsContainer, paneId); }); _updateUIStates(); // Tooltips $gearMenu.attr("title", Strings.GEAR_MENU_TOOLTIP); $splitViewMenu.attr("title", Strings.SPLITVIEW_MENU_TOOLTIP); }); ProjectManager.on("projectOpen", _updateProjectTitle); /** * Register Command Handlers */ _cmdSplitNone = CommandManager.register(Strings.CMD_SPLITVIEW_NONE, Commands.CMD_SPLITVIEW_NONE, _handleSplitViewNone); _cmdSplitVertical = CommandManager.register(Strings.CMD_SPLITVIEW_VERTICAL, Commands.CMD_SPLITVIEW_VERTICAL, _handleSplitViewVertical); _cmdSplitHorizontal = CommandManager.register(Strings.CMD_SPLITVIEW_HORIZONTAL, Commands.CMD_SPLITVIEW_HORIZONTAL, _handleSplitViewHorizontal); CommandManager.register(Strings.CMD_HIDE_SIDEBAR, Commands.VIEW_HIDE_SIDEBAR, toggle); // Define public API exports.toggle = toggle; exports.show = show; exports.hide = hide; exports.isVisible = isVisible; });
resir014/brackets
src/project/SidebarView.js
JavaScript
mit
10,278
package rdsutils import ( "net/http" "strings" "time" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/signer/v4" ) // BuildAuthToken will return a authentication token for the database's connect // based on the RDS database endpoint, AWS region, IAM user or role, and AWS credentials. // // Endpoint consists of the hostname and port, IE hostname:port, of the RDS database. // Region is the AWS region the RDS database is in and where the authentication token // will be generated for. DbUser is the IAM user or role the request will be authenticated // for. The creds is the AWS credentials the authentication token is signed with. // // An error is returned if the authentication token is unable to be signed with // the credentials, or the endpoint is not a valid URL. // // The following example shows how to use BuildAuthToken to create an authentication // token for connecting to a MySQL database in RDS. // // authToken, err := BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds) // // // Create the MySQL DNS string for the DB connection // // user:password@protocol(endpoint)/dbname?<params> // dnsStr = fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true", // dbUser, authToken, dbEndpoint, dbName, // ) // // // Use db to perform SQL operations on database // db, err := sql.Open("mysql", dnsStr) // // See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html // for more information on using IAM database authentication with RDS. func BuildAuthToken(endpoint, region, dbUser string, creds *credentials.Credentials) (string, error) { // the scheme is arbitrary and is only needed because validation of the URL requires one. if !(strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://")) { endpoint = "https://" + endpoint } req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", err } values := req.URL.Query() values.Set("Action", "connect") values.Set("DBUser", dbUser) req.URL.RawQuery = values.Encode() signer := v4.Signer{ Credentials: creds, } _, err = signer.Presign(req, nil, "rds-db", region, 15*time.Minute, time.Now()) if err != nil { return "", err } url := req.URL.String() if strings.HasPrefix(url, "http://") { url = url[len("http://"):] } else if strings.HasPrefix(url, "https://") { url = url[len("https://"):] } return url, nil }
whosonfirst/go-whosonfirst-updated
vendor/github.com/whosonfirst/go-whosonfirst-s3/vendor/src/github.com/aws/aws-sdk-go/service/rds/rdsutils/connect.go
GO
bsd-3-clause
2,417
"""Utilities to evaluate models with respect to a variable """ # Author: Alexander Fabisch <afabisch@informatik.uni-bremen.de> # # License: BSD 3 clause import warnings import numpy as np from .base import is_classifier, clone from .cross_validation import check_cv from .externals.joblib import Parallel, delayed from .cross_validation import _safe_split, _score, _fit_and_score from .metrics.scorer import check_scoring from .utils import indexable from .utils.fixes import astype __all__ = ['learning_curve', 'validation_curve'] def learning_curve(estimator, X, y, train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=1, pre_dispatch="all", verbose=0): """Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the :ref:`User Guide <learning_curves>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. train_sizes : array-like, shape (n_ticks,), dtype float or int Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class. (default: np.linspace(0.1, 1.0, 5)) cv : integer, cross-validation generator, optional If an integer is passed, it is the number of folds (defaults to 3). Specific cross-validation objects can be passed, see sklearn.cross_validation module for the list of possible objects scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. exploit_incremental_learning : boolean, optional, default: False If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. Returns ------- train_sizes_abs : array, shape = (n_unique_ticks,), dtype int Numbers of training examples that has been used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_learning_curve.py <example_model_selection_plot_learning_curve.py>` """ if exploit_incremental_learning and not hasattr(estimator, "partial_fit"): raise ValueError("An estimator must support the partial_fit interface " "to exploit incremental learning") X, y = indexable(X, y) # Make a list since we will be iterating multiple times over the folds cv = list(check_cv(cv, X, y, classifier=is_classifier(estimator))) scorer = check_scoring(estimator, scoring=scoring) # HACK as long as boolean indices are allowed in cv generators if cv[0][0].dtype == bool: new_cv = [] for i in range(len(cv)): new_cv.append((np.nonzero(cv[i][0])[0], np.nonzero(cv[i][1])[0])) cv = new_cv n_max_training_samples = len(cv[0][0]) # Because the lengths of folds can be significantly different, it is # not guaranteed that we use all of the available training data when we # use the first 'n_max_training_samples' samples. train_sizes_abs = _translate_train_sizes(train_sizes, n_max_training_samples) n_unique_ticks = train_sizes_abs.shape[0] if verbose > 0: print("[learning_curve] Training set sizes: " + str(train_sizes_abs)) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) if exploit_incremental_learning: classes = np.unique(y) if is_classifier(estimator) else None out = parallel(delayed(_incremental_fit_estimator)( clone(estimator), X, y, classes, train, test, train_sizes_abs, scorer, verbose) for train, test in cv) else: out = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train[:n_train_samples], test, verbose, parameters=None, fit_params=None, return_train_score=True) for train, test in cv for n_train_samples in train_sizes_abs) out = np.array(out)[:, :2] n_cv_folds = out.shape[0] // n_unique_ticks out = out.reshape(n_cv_folds, n_unique_ticks, 2) out = np.asarray(out).transpose((2, 1, 0)) return train_sizes_abs, out[0], out[1] def _translate_train_sizes(train_sizes, n_max_training_samples): """Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes : array-like, shape (n_ticks,), dtype float or int Numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. n_max_training_samples : int Maximum number of training samples (upper bound of 'train_sizes'). Returns ------- train_sizes_abs : array, shape (n_unique_ticks,), dtype int Numbers of training examples that will be used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. """ train_sizes_abs = np.asarray(train_sizes) n_ticks = train_sizes_abs.shape[0] n_min_required_samples = np.min(train_sizes_abs) n_max_required_samples = np.max(train_sizes_abs) if np.issubdtype(train_sizes_abs.dtype, np.float): if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0: raise ValueError("train_sizes has been interpreted as fractions " "of the maximum number of training samples and " "must be within (0, 1], but is within [%f, %f]." % (n_min_required_samples, n_max_required_samples)) train_sizes_abs = astype(train_sizes_abs * n_max_training_samples, dtype=np.int, copy=False) train_sizes_abs = np.clip(train_sizes_abs, 1, n_max_training_samples) else: if (n_min_required_samples <= 0 or n_max_required_samples > n_max_training_samples): raise ValueError("train_sizes has been interpreted as absolute " "numbers of training samples and must be within " "(0, %d], but is within [%d, %d]." % (n_max_training_samples, n_min_required_samples, n_max_required_samples)) train_sizes_abs = np.unique(train_sizes_abs) if n_ticks > train_sizes_abs.shape[0]: warnings.warn("Removed duplicate entries from 'train_sizes'. Number " "of ticks will be less than than the size of " "'train_sizes' %d instead of %d)." % (train_sizes_abs.shape[0], n_ticks), RuntimeWarning) return train_sizes_abs def _incremental_fit_estimator(estimator, X, y, classes, train, test, train_sizes, scorer, verbose): """Train estimator on training subsets incrementally and compute scores.""" train_scores, test_scores = [], [] partitions = zip(train_sizes, np.split(train, train_sizes)[:-1]) for n_train_samples, partial_train in partitions: train_subset = train[:n_train_samples] X_train, y_train = _safe_split(estimator, X, y, train_subset) X_partial_train, y_partial_train = _safe_split(estimator, X, y, partial_train) X_test, y_test = _safe_split(estimator, X, y, test, train_subset) if y_partial_train is None: estimator.partial_fit(X_partial_train, classes=classes) else: estimator.partial_fit(X_partial_train, y_partial_train, classes=classes) train_scores.append(_score(estimator, X_train, y_train, scorer)) test_scores.append(_score(estimator, X_test, y_test, scorer)) return np.array((train_scores, test_scores)).T def validation_curve(estimator, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=1, pre_dispatch="all", verbose=0): """Validation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide <validation_curve>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. param_name : string Name of the parameter that will be varied. param_range : array-like, shape (n_values,) The values of the parameter that will be evaluated. cv : integer, cross-validation generator, optional If an integer is passed, it is the number of folds (defaults to 3). Specific cross-validation objects can be passed, see sklearn.cross_validation module for the list of possible objects scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. Returns ------- train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_validation_curve.py <example_model_selection_plot_validation_curve.py>` """ X, y = indexable(X, y) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) out = parallel(delayed(_fit_and_score)( estimator, X, y, scorer, train, test, verbose, parameters={param_name: v}, fit_params=None, return_train_score=True) for train, test in cv for v in param_range) out = np.asarray(out)[:, :2] n_params = len(param_range) n_cv_folds = out.shape[0] // n_params out = out.reshape(n_cv_folds, n_params, 2).transpose((2, 1, 0)) return out[0], out[1]
Achuth17/scikit-learn
sklearn/learning_curve.py
Python
bsd-3-clause
13,467
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package store type Watcher interface { EventChan() chan *Event StartIndex() uint64 // The EtcdIndex at which the Watcher was created Remove() } type watcher struct { eventChan chan *Event stream bool recursive bool sinceIndex uint64 startIndex uint64 hub *watcherHub removed bool remove func() } func (w *watcher) EventChan() chan *Event { return w.eventChan } func (w *watcher) StartIndex() uint64 { return w.startIndex } // notify function notifies the watcher. If the watcher interests in the given path, // the function will return true. func (w *watcher) notify(e *Event, originalPath bool, deleted bool) bool { // watcher is interested the path in three cases and under one condition // the condition is that the event happens after the watcher's sinceIndex // 1. the path at which the event happens is the path the watcher is watching at. // For example if the watcher is watching at "/foo" and the event happens at "/foo", // the watcher must be interested in that event. // 2. the watcher is a recursive watcher, it interests in the event happens after // its watching path. For example if watcher A watches at "/foo" and it is a recursive // one, it will interest in the event happens at "/foo/bar". // 3. when we delete a directory, we need to force notify all the watchers who watches // at the file we need to delete. // For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher // should get notified even if "/foo" is not the path it is watching. if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex { // We cannot block here if the eventChan capacity is full, otherwise // etcd will hang. eventChan capacity is full when the rate of // notifications are higher than our send rate. // If this happens, we close the channel. select { case w.eventChan <- e: default: // We have missed a notification. Remove the watcher. // Removing the watcher also closes the eventChan. w.remove() } return true } return false } // Remove removes the watcher from watcherHub // The actual remove function is guaranteed to only be executed once func (w *watcher) Remove() { w.hub.mutex.Lock() defer w.hub.mutex.Unlock() close(w.eventChan) if w.remove != nil { w.remove() } } // nopWatcher is a watcher that receives nothing, always blocking. type nopWatcher struct{} func NewNopWatcher() Watcher { return &nopWatcher{} } func (w *nopWatcher) EventChan() chan *Event { return nil } func (w *nopWatcher) StartIndex() uint64 { return 0 } func (w *nopWatcher) Remove() {}
dmirubtsov/k8s-executor
vendor/k8s.io/kubernetes/vendor/github.com/coreos/etcd/store/watcher.go
GO
apache-2.0
3,230
using System; namespace Notifications.Model { public interface IScenario { string Name { get; } bool Contains(Type scenarioType); Scenario FindScenario(Type scenarioType); } }
TA-Team-Giant/PAaaS
pAaaS/Notifications/Model/IScenario.cs
C#
mit
218
export default function Home() { return <div className="red-text">This text should be red.</div> }
flybayer/next.js
test/integration/scss-fixtures/webpack-error/pages/index.js
JavaScript
mit
101
/* */ module.exports = { "default": require("core-js/library/fn/math/sign"), __esModule: true };
pauldijou/outdated
test/basic/jspm_packages/npm/babel-runtime@5.8.9/core-js/math/sign.js
JavaScript
apache-2.0
97
require 'formula' class Avce00 < Formula homepage 'http://avce00.maptools.org/avce00/index.html' url 'http://avce00.maptools.org/dl/avce00-2.0.0.tar.gz' sha1 '2948d9b1cfb6e80faf2e9b90c86fd224617efd75' def install system "make", "CC=#{ENV.cc}" bin.install "avcimport", "avcexport", "avcdelete", "avctest" end end
jtrag/homebrew
Library/Formula/avce00.rb
Ruby
bsd-2-clause
333
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package validation import ( "testing" "github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/api" ) func TestValidatePriorityWithNoWeight(t *testing.T) { policy := api.Policy{Priorities: []api.PriorityPolicy{{Name: "NoWeightPriority"}}} if ValidatePolicy(policy) == nil { t.Errorf("Expected error about priority weight not being positive") } } func TestValidatePriorityWithZeroWeight(t *testing.T) { policy := api.Policy{Priorities: []api.PriorityPolicy{{Name: "NoWeightPriority", Weight: 0}}} if ValidatePolicy(policy) == nil { t.Errorf("Expected error about priority weight not being positive") } } func TestValidatePriorityWithNonZeroWeight(t *testing.T) { policy := api.Policy{Priorities: []api.PriorityPolicy{{Name: "WeightPriority", Weight: 2}}} errs := ValidatePolicy(policy) if errs != nil { t.Errorf("Unexpected errors %v", errs) } } func TestValidatePriorityWithNegativeWeight(t *testing.T) { policy := api.Policy{Priorities: []api.PriorityPolicy{{Name: "WeightPriority", Weight: -2}}} if ValidatePolicy(policy) == nil { t.Errorf("Expected error about priority weight not being positive") } }
tya/kubernetes
plugin/pkg/scheduler/api/validation/validation_test.go
GO
apache-2.0
1,732
module CodeRay # = WordList # # <b>A Hash subclass designed for mapping word lists to token types.</b> # # A WordList is a Hash with some additional features. # It is intended to be used for keyword recognition. # # WordList is optimized to be used in Scanners, # typically to decide whether a given ident is a special token. # # For case insensitive words use WordList::CaseIgnoring. # # Example: # # # define word arrays # RESERVED_WORDS = %w[ # asm break case continue default do else # ] # # PREDEFINED_TYPES = %w[ # int long short char void # ] # # # make a WordList # IDENT_KIND = WordList.new(:ident). # add(RESERVED_WORDS, :reserved). # add(PREDEFINED_TYPES, :predefined_type) # # ... # # def scan_tokens tokens, options # ... # # elsif scan(/[A-Za-z_][A-Za-z_0-9]*/) # # use it # kind = IDENT_KIND[match] # ... class WordList < Hash # Create a new WordList with +default+ as default value. def initialize default = false super default end # Add words to the list and associate them with +value+. # # Returns +self+, so you can concat add calls. def add words, value = true words.each { |word| self[word] = value } self end end # A CaseIgnoring WordList is like a WordList, only that # keys are compared case-insensitively (normalizing keys using +downcase+). class WordList::CaseIgnoring < WordList def [] key super key.downcase end def []= key, value super key.downcase, value end end end
emineKoc/WiseWit
wisewitapi/vendor/bundle/gems/coderay-1.1.1/lib/coderay/helpers/word_list.rb
Ruby
gpl-3.0
1,662
<?php /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-01 at 23:10:44. */ class JGithubPackageOrgsMembersTest extends PHPUnit_Framework_TestCase { /** * @var JRegistry Options for the GitHub object. * @since 11.4 */ protected $options; /** * @var JGithubHttp Mock client object. * @since 11.4 */ protected $client; /** * @var JHttpResponse Mock response object. * @since 12.3 */ protected $response; /** * @var JGithubPackageOrgsMembers */ protected $object; /** * @var string Sample JSON string. * @since 12.3 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON error message. * @since 12.3 */ protected $errorString = '{"message": "Generic Error"}'; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @since ¿ * * @return void */ protected function setUp() { parent::setUp(); $this->options = new JRegistry; $this->client = $this->getMock('JGithubHttp', array('get', 'post', 'delete', 'patch', 'put')); $this->response = $this->getMock('JHttpResponse'); $this->object = new JGithubPackageOrgsMembers($this->options, $this->client); } /** * @covers JGithubPackageOrgsMembers::getList */ public function testGetList() { $this->response->code = 200; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->getList('joomla'), $this->equalTo(json_decode($this->sampleString)) ); } /** * @covers JGithubPackageOrgsMembers::getList */ public function testGetListNotAMember() { $this->response->code = 302; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->getList('joomla'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::getList * * @expectedException UnexpectedValueException */ public function testGetListUnexpected() { $this->response->code = 666; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->getList('joomla'), $this->equalTo(json_decode($this->sampleString)) ); } /** * @covers JGithubPackageOrgsMembers::check */ public function testCheck() { $this->response->code = 204; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->check('joomla', 'elkuku'), $this->equalTo(true) ); } /** * @covers JGithubPackageOrgsMembers::check */ public function testCheckNoMember() { $this->response->code = 404; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->check('joomla', 'elkuku'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::check */ public function testCheckRequesterNoMember() { $this->response->code = 302; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->check('joomla', 'elkuku'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::check * * @expectedException UnexpectedValueException */ public function testCheckUnexpectedr() { $this->response->code = 666; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->check('joomla', 'elkuku'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::remove */ public function testRemove() { $this->response->code = 204; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('delete') ->with('/orgs/joomla/members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->remove('joomla', 'elkuku'), $this->equalTo(json_decode($this->sampleString)) ); } /** * @covers JGithubPackageOrgsMembers::getListPublic */ public function testGetListPublic() { $this->response->code = 200; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/public_members') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->getListPublic('joomla'), $this->equalTo(json_decode($this->sampleString)) ); } /** * @covers JGithubPackageOrgsMembers::checkPublic */ public function testCheckPublic() { $this->response->code = 204; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/public_members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->checkPublic('joomla', 'elkuku'), $this->equalTo(true) ); } /** * @covers JGithubPackageOrgsMembers::checkPublic */ public function testCheckPublicNo() { $this->response->code = 404; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/public_members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->checkPublic('joomla', 'elkuku'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::checkPublic * * @expectedException UnexpectedValueException */ public function testCheckPublicUnexpected() { $this->response->code = 666; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('get') ->with('/orgs/joomla/public_members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->checkPublic('joomla', 'elkuku'), $this->equalTo(false) ); } /** * @covers JGithubPackageOrgsMembers::publicize */ public function testPublicize() { $this->response->code = 204; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('put') ->with('/orgs/joomla/public_members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->publicize('joomla', 'elkuku'), $this->equalTo(json_decode($this->sampleString)) ); } /** * @covers JGithubPackageOrgsMembers::conceal */ public function testConceal() { $this->response->code = 204; $this->response->body = $this->sampleString; $this->client->expects($this->once()) ->method('delete') ->with('/orgs/joomla/public_members/elkuku') ->will($this->returnValue($this->response)); $this->assertThat( $this->object->conceal('joomla', 'elkuku'), $this->equalTo(json_decode($this->sampleString)) ); } }
1nv4d3r5/joomla-cms
tests/unit/suites/libraries/joomla/github/orgs/JGithubPackageOrgsMembersTest.php
PHP
gpl-2.0
7,908
function loadedScript() { return "externalScript1"; }
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/svg/linking/scripted/testScripts/externalScript1.js
JavaScript
bsd-3-clause
56
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.okhttp.internal; import com.squareup.okhttp.Authenticator; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.net.Proxy; import java.util.ArrayList; import java.util.List; public final class RecordingOkAuthenticator implements Authenticator { public final List<Response> responses = new ArrayList<>(); public final List<Proxy> proxies = new ArrayList<>(); public final String credential; public RecordingOkAuthenticator(String credential) { this.credential = credential; } public Response onlyResponse() { if (responses.size() != 1) throw new IllegalStateException(); return responses.get(0); } public Proxy onlyProxy() { if (proxies.size() != 1) throw new IllegalStateException(); return proxies.get(0); } @Override public Request authenticate(Proxy proxy, Response response) { responses.add(response); proxies.add(proxy); return response.request().newBuilder() .addHeader("Authorization", credential) .build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) { responses.add(response); proxies.add(proxy); return response.request().newBuilder() .addHeader("Proxy-Authorization", credential) .build(); } }
cdut007/PMS_TASK
third_party/okhttp-master/okhttp-tests/src/test/java/com/squareup/okhttp/internal/RecordingOkAuthenticator.java
Java
mit
1,901
require 'formula' class Gplcver < Formula desc "Pragmatic C Software GPL Cver 2001" homepage 'http://gplcver.sourceforge.net/' url 'https://downloads.sourceforge.net/project/gplcver/gplcver/2.12a/gplcver-2.12a.src.tar.bz2' sha1 '946bb35b6279646c6e10c309922ed17deb2aca8a' def install inreplace 'src/makefile.osx' do |s| s.gsub! '-mcpu=powerpc', '' s.change_make_var! 'CFLAGS', "$(INCS) $(OPTFLGS) #{ENV.cflags}" s.change_make_var! 'LFLAGS', '' end system "make", "-C", "src", "-f", "makefile.osx" bin.install 'bin/cver' end end
stoshiya/homebrew
Library/Formula/gplcver.rb
Ruby
bsd-2-clause
576
/** * angular-strap * @version v2.1.2 - 2014-10-19 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function($templateCache) { $templateCache.put('popover/popover.tpl.html', '<div class="popover"><div class="arrow"></div><h3 class="popover-title" ng-bind="title" ng-show="title"></h3><div class="popover-content" ng-bind="content"></div></div>'); }]);
radhikabhanu/crowdsource-platform
staticfiles/bower_components/angular-strap/dist/modules/popover.tpl.js
JavaScript
mit
553
module.exports = TapProducer var Results = require("./tap-results") , inherits = require("inherits") , yamlish = require("yamlish") TapProducer.encode = function (result, diag) { var tp = new TapProducer(diag) , out = "" tp.on("data", function (c) { out += c }) if (Array.isArray(result)) { result.forEach(tp.write, tp) } else tp.write(result) tp.end() return out } var Stream = require("stream").Stream inherits(TapProducer, Stream) function TapProducer (diag) { Stream.call(this) this.diag = diag this.count = 0 this.readable = this.writable = true this.results = new Results } TapProducer.prototype.trailer = true TapProducer.prototype.write = function (res) { // console.error("TapProducer.write", res) if (typeof res === "function") throw new Error("wtf?") if (!this.writable) this.emit("error", new Error("not writable")) if (!this._didHead) { this.emit("data", "TAP version 13\n") this._didHead = true } var diag = res.diag if (diag === undefined) diag = this.diag this.emit("data", encodeResult(res, this.count + 1, diag)) if (typeof res === "string") return true if (res.bailout) { var bo = "bail out!" if (typeof res.bailout === "string") bo += " " + res.bailout this.emit("data", bo) return } this.results.add(res, false) this.count ++ } TapProducer.prototype.end = function (res) { if (res) this.write(res) // console.error("TapProducer end", res, this.results) this.emit("data", "\n1.."+this.results.testsTotal+"\n") if (this.trailer && typeof this.trailer !== "string") { // summary trailer. var trailer = "tests "+this.results.testsTotal + "\n" if (this.results.pass) { trailer += "pass " + this.results.pass + "\n" } if (this.results.fail) { trailer += "fail " + this.results.fail + "\n" } if (this.results.skip) { trailer += "skip "+this.results.skip + "\n" } if (this.results.todo) { trailer += "todo "+this.results.todo + "\n" } if (this.results.bailedOut) { trailer += "bailed out" + "\n" } if (this.results.testsTotal === this.results.pass) { trailer += "\nok\n" } this.trailer = trailer } if (this.trailer) this.write(this.trailer) this.writable = false this.emit("end", null, this.count, this.ok) } function encodeResult (res, count, diag) { // console.error(res, count, diag) if (typeof res === "string") { res = res.split(/\r?\n/).map(function (l) { if (!l.trim()) return l.trim() return "# " + l }).join("\n") if (res.substr(-1) !== "\n") res += "\n" return res } if (res.bailout) return "" if (!!process.env.TAP_NODIAG) diag = false else if (!!process.env.TAP_DIAG) diag = true else if (diag === undefined) diag = !res.ok var output = "" res.name = res.name && ("" + res.name).trim() output += ( !res.ok ? "not " : "") + "ok " + count + ( !res.name ? "" : " " + res.name.replace(/[\r\n]/g, " ") ) + ( res.skip ? " # SKIP " + ( res.explanation || "" ) : res.todo ? " # TODO " + ( res.explanation || "" ) : "" ) + "\n" if (!diag) return output var d = {} , dc = 0 Object.keys(res).filter(function (k) { return k !== "ok" && k !== "name" && k !== "id" }).forEach(function (k) { dc ++ d[k] = res[k] }) //console.error(d, "about to encode") if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n" return output }
joshdrink/app_swig
wp-content/themes/brew/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js
JavaScript
gpl-2.0
3,516
// Code generated by protoc-gen-gogo. // source: combos/unsafeboth/one.proto // DO NOT EDIT! /* Package one is a generated protocol buffer package. It is generated from these files: combos/unsafeboth/one.proto It has these top-level messages: Subby AllTypesOneOf TwoOneofs CustomOneof */ package one import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import github_com_gogo_protobuf_test_custom "github.com/gogo/protobuf/test/custom" import github_com_gogo_protobuf_test_casttype "github.com/gogo/protobuf/test/casttype" import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" import compress_gzip "compress/gzip" import bytes "bytes" import io_ioutil "io/ioutil" import strings "strings" import reflect "reflect" import unsafe "unsafe" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Subby struct { Sub *string `protobuf:"bytes,1,opt,name=sub" json:"sub,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Subby) Reset() { *m = Subby{} } func (*Subby) ProtoMessage() {} func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} } type AllTypesOneOf struct { // Types that are valid to be assigned to TestOneof: // *AllTypesOneOf_Field1 // *AllTypesOneOf_Field2 // *AllTypesOneOf_Field3 // *AllTypesOneOf_Field4 // *AllTypesOneOf_Field5 // *AllTypesOneOf_Field6 // *AllTypesOneOf_Field7 // *AllTypesOneOf_Field8 // *AllTypesOneOf_Field9 // *AllTypesOneOf_Field10 // *AllTypesOneOf_Field11 // *AllTypesOneOf_Field12 // *AllTypesOneOf_Field13 // *AllTypesOneOf_Field14 // *AllTypesOneOf_Field15 // *AllTypesOneOf_SubMessage TestOneof isAllTypesOneOf_TestOneof `protobuf_oneof:"test_oneof"` XXX_unrecognized []byte `json:"-"` } func (m *AllTypesOneOf) Reset() { *m = AllTypesOneOf{} } func (*AllTypesOneOf) ProtoMessage() {} func (*AllTypesOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} } type isAllTypesOneOf_TestOneof interface { isAllTypesOneOf_TestOneof() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type AllTypesOneOf_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"` } type AllTypesOneOf_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"` } type AllTypesOneOf_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"` } type AllTypesOneOf_Field4 struct { Field4 int64 `protobuf:"varint,4,opt,name=Field4,oneof"` } type AllTypesOneOf_Field5 struct { Field5 uint32 `protobuf:"varint,5,opt,name=Field5,oneof"` } type AllTypesOneOf_Field6 struct { Field6 uint64 `protobuf:"varint,6,opt,name=Field6,oneof"` } type AllTypesOneOf_Field7 struct { Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,oneof"` } type AllTypesOneOf_Field8 struct { Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,oneof"` } type AllTypesOneOf_Field9 struct { Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,oneof"` } type AllTypesOneOf_Field10 struct { Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,oneof"` } type AllTypesOneOf_Field11 struct { Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,oneof"` } type AllTypesOneOf_Field12 struct { Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,oneof"` } type AllTypesOneOf_Field13 struct { Field13 bool `protobuf:"varint,13,opt,name=Field13,oneof"` } type AllTypesOneOf_Field14 struct { Field14 string `protobuf:"bytes,14,opt,name=Field14,oneof"` } type AllTypesOneOf_Field15 struct { Field15 []byte `protobuf:"bytes,15,opt,name=Field15,oneof"` } type AllTypesOneOf_SubMessage struct { SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"` } func (*AllTypesOneOf_Field1) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field2) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field3) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field4) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field5) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field6) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field7) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field8) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field9) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field10) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field11) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field12) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field13) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field14) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_Field15) isAllTypesOneOf_TestOneof() {} func (*AllTypesOneOf_SubMessage) isAllTypesOneOf_TestOneof() {} func (m *AllTypesOneOf) GetTestOneof() isAllTypesOneOf_TestOneof { if m != nil { return m.TestOneof } return nil } func (m *AllTypesOneOf) GetField1() float64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field1); ok { return x.Field1 } return 0 } func (m *AllTypesOneOf) GetField2() float32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field2); ok { return x.Field2 } return 0 } func (m *AllTypesOneOf) GetField3() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field3); ok { return x.Field3 } return 0 } func (m *AllTypesOneOf) GetField4() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field4); ok { return x.Field4 } return 0 } func (m *AllTypesOneOf) GetField5() uint32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field5); ok { return x.Field5 } return 0 } func (m *AllTypesOneOf) GetField6() uint64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field6); ok { return x.Field6 } return 0 } func (m *AllTypesOneOf) GetField7() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field7); ok { return x.Field7 } return 0 } func (m *AllTypesOneOf) GetField8() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field8); ok { return x.Field8 } return 0 } func (m *AllTypesOneOf) GetField9() uint32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field9); ok { return x.Field9 } return 0 } func (m *AllTypesOneOf) GetField10() int32 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field10); ok { return x.Field10 } return 0 } func (m *AllTypesOneOf) GetField11() uint64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field11); ok { return x.Field11 } return 0 } func (m *AllTypesOneOf) GetField12() int64 { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field12); ok { return x.Field12 } return 0 } func (m *AllTypesOneOf) GetField13() bool { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field13); ok { return x.Field13 } return false } func (m *AllTypesOneOf) GetField14() string { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field14); ok { return x.Field14 } return "" } func (m *AllTypesOneOf) GetField15() []byte { if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field15); ok { return x.Field15 } return nil } func (m *AllTypesOneOf) GetSubMessage() *Subby { if x, ok := m.GetTestOneof().(*AllTypesOneOf_SubMessage); ok { return x.SubMessage } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*AllTypesOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _AllTypesOneOf_OneofMarshaler, _AllTypesOneOf_OneofUnmarshaler, _AllTypesOneOf_OneofSizer, []interface{}{ (*AllTypesOneOf_Field1)(nil), (*AllTypesOneOf_Field2)(nil), (*AllTypesOneOf_Field3)(nil), (*AllTypesOneOf_Field4)(nil), (*AllTypesOneOf_Field5)(nil), (*AllTypesOneOf_Field6)(nil), (*AllTypesOneOf_Field7)(nil), (*AllTypesOneOf_Field8)(nil), (*AllTypesOneOf_Field9)(nil), (*AllTypesOneOf_Field10)(nil), (*AllTypesOneOf_Field11)(nil), (*AllTypesOneOf_Field12)(nil), (*AllTypesOneOf_Field13)(nil), (*AllTypesOneOf_Field14)(nil), (*AllTypesOneOf_Field15)(nil), (*AllTypesOneOf_SubMessage)(nil), } } func _AllTypesOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*AllTypesOneOf) // test_oneof switch x := m.TestOneof.(type) { case *AllTypesOneOf_Field1: _ = b.EncodeVarint(1<<3 | proto.WireFixed64) _ = b.EncodeFixed64(math.Float64bits(x.Field1)) case *AllTypesOneOf_Field2: _ = b.EncodeVarint(2<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2))) case *AllTypesOneOf_Field3: _ = b.EncodeVarint(3<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field3)) case *AllTypesOneOf_Field4: _ = b.EncodeVarint(4<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field4)) case *AllTypesOneOf_Field5: _ = b.EncodeVarint(5<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field5)) case *AllTypesOneOf_Field6: _ = b.EncodeVarint(6<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field6)) case *AllTypesOneOf_Field7: _ = b.EncodeVarint(7<<3 | proto.WireVarint) _ = b.EncodeZigzag32(uint64(x.Field7)) case *AllTypesOneOf_Field8: _ = b.EncodeVarint(8<<3 | proto.WireVarint) _ = b.EncodeZigzag64(uint64(x.Field8)) case *AllTypesOneOf_Field9: _ = b.EncodeVarint(9<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field9)) case *AllTypesOneOf_Field10: _ = b.EncodeVarint(10<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field10)) case *AllTypesOneOf_Field11: _ = b.EncodeVarint(11<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field11)) case *AllTypesOneOf_Field12: _ = b.EncodeVarint(12<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field12)) case *AllTypesOneOf_Field13: t := uint64(0) if x.Field13 { t = 1 } _ = b.EncodeVarint(13<<3 | proto.WireVarint) _ = b.EncodeVarint(t) case *AllTypesOneOf_Field14: _ = b.EncodeVarint(14<<3 | proto.WireBytes) _ = b.EncodeStringBytes(x.Field14) case *AllTypesOneOf_Field15: _ = b.EncodeVarint(15<<3 | proto.WireBytes) _ = b.EncodeRawBytes(x.Field15) case *AllTypesOneOf_SubMessage: _ = b.EncodeVarint(16<<3 | proto.WireBytes) if err := b.EncodeMessage(x.SubMessage); err != nil { return err } case nil: default: return fmt.Errorf("AllTypesOneOf.TestOneof has unexpected type %T", x) } return nil } func _AllTypesOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*AllTypesOneOf) switch tag { case 1: // test_oneof.Field1 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &AllTypesOneOf_Field1{math.Float64frombits(x)} return true, err case 2: // test_oneof.Field2 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &AllTypesOneOf_Field2{math.Float32frombits(uint32(x))} return true, err case 3: // test_oneof.Field3 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &AllTypesOneOf_Field3{int32(x)} return true, err case 4: // test_oneof.Field4 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &AllTypesOneOf_Field4{int64(x)} return true, err case 5: // test_oneof.Field5 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &AllTypesOneOf_Field5{uint32(x)} return true, err case 6: // test_oneof.Field6 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &AllTypesOneOf_Field6{x} return true, err case 7: // test_oneof.Field7 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.TestOneof = &AllTypesOneOf_Field7{int32(x)} return true, err case 8: // test_oneof.Field8 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag64() m.TestOneof = &AllTypesOneOf_Field8{int64(x)} return true, err case 9: // test_oneof.Field9 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &AllTypesOneOf_Field9{uint32(x)} return true, err case 10: // test_oneof.Field10 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &AllTypesOneOf_Field10{int32(x)} return true, err case 11: // test_oneof.Field11 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &AllTypesOneOf_Field11{x} return true, err case 12: // test_oneof.Field12 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &AllTypesOneOf_Field12{int64(x)} return true, err case 13: // test_oneof.Field13 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &AllTypesOneOf_Field13{x != 0} return true, err case 14: // test_oneof.Field14 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.TestOneof = &AllTypesOneOf_Field14{x} return true, err case 15: // test_oneof.Field15 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.TestOneof = &AllTypesOneOf_Field15{x} return true, err case 16: // test_oneof.sub_message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Subby) err := b.DecodeMessage(msg) m.TestOneof = &AllTypesOneOf_SubMessage{msg} return true, err default: return false, nil } } func _AllTypesOneOf_OneofSizer(msg proto.Message) (n int) { m := msg.(*AllTypesOneOf) // test_oneof switch x := m.TestOneof.(type) { case *AllTypesOneOf_Field1: n += proto.SizeVarint(1<<3 | proto.WireFixed64) n += 8 case *AllTypesOneOf_Field2: n += proto.SizeVarint(2<<3 | proto.WireFixed32) n += 4 case *AllTypesOneOf_Field3: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field3)) case *AllTypesOneOf_Field4: n += proto.SizeVarint(4<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field4)) case *AllTypesOneOf_Field5: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field5)) case *AllTypesOneOf_Field6: n += proto.SizeVarint(6<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field6)) case *AllTypesOneOf_Field7: n += proto.SizeVarint(7<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31)))) case *AllTypesOneOf_Field8: n += proto.SizeVarint(8<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63)))) case *AllTypesOneOf_Field9: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *AllTypesOneOf_Field10: n += proto.SizeVarint(10<<3 | proto.WireFixed32) n += 4 case *AllTypesOneOf_Field11: n += proto.SizeVarint(11<<3 | proto.WireFixed64) n += 8 case *AllTypesOneOf_Field12: n += proto.SizeVarint(12<<3 | proto.WireFixed64) n += 8 case *AllTypesOneOf_Field13: n += proto.SizeVarint(13<<3 | proto.WireVarint) n += 1 case *AllTypesOneOf_Field14: n += proto.SizeVarint(14<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field14))) n += len(x.Field14) case *AllTypesOneOf_Field15: n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field15))) n += len(x.Field15) case *AllTypesOneOf_SubMessage: s := proto.Size(x.SubMessage) n += proto.SizeVarint(16<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type TwoOneofs struct { // Types that are valid to be assigned to One: // *TwoOneofs_Field1 // *TwoOneofs_Field2 // *TwoOneofs_Field3 One isTwoOneofs_One `protobuf_oneof:"one"` // Types that are valid to be assigned to Two: // *TwoOneofs_Field34 // *TwoOneofs_Field35 // *TwoOneofs_SubMessage2 Two isTwoOneofs_Two `protobuf_oneof:"two"` XXX_unrecognized []byte `json:"-"` } func (m *TwoOneofs) Reset() { *m = TwoOneofs{} } func (*TwoOneofs) ProtoMessage() {} func (*TwoOneofs) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{2} } type isTwoOneofs_One interface { isTwoOneofs_One() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type isTwoOneofs_Two interface { isTwoOneofs_Two() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type TwoOneofs_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"` } type TwoOneofs_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"` } type TwoOneofs_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"` } type TwoOneofs_Field34 struct { Field34 string `protobuf:"bytes,34,opt,name=Field34,oneof"` } type TwoOneofs_Field35 struct { Field35 []byte `protobuf:"bytes,35,opt,name=Field35,oneof"` } type TwoOneofs_SubMessage2 struct { SubMessage2 *Subby `protobuf:"bytes,36,opt,name=sub_message2,json=subMessage2,oneof"` } func (*TwoOneofs_Field1) isTwoOneofs_One() {} func (*TwoOneofs_Field2) isTwoOneofs_One() {} func (*TwoOneofs_Field3) isTwoOneofs_One() {} func (*TwoOneofs_Field34) isTwoOneofs_Two() {} func (*TwoOneofs_Field35) isTwoOneofs_Two() {} func (*TwoOneofs_SubMessage2) isTwoOneofs_Two() {} func (m *TwoOneofs) GetOne() isTwoOneofs_One { if m != nil { return m.One } return nil } func (m *TwoOneofs) GetTwo() isTwoOneofs_Two { if m != nil { return m.Two } return nil } func (m *TwoOneofs) GetField1() float64 { if x, ok := m.GetOne().(*TwoOneofs_Field1); ok { return x.Field1 } return 0 } func (m *TwoOneofs) GetField2() float32 { if x, ok := m.GetOne().(*TwoOneofs_Field2); ok { return x.Field2 } return 0 } func (m *TwoOneofs) GetField3() int32 { if x, ok := m.GetOne().(*TwoOneofs_Field3); ok { return x.Field3 } return 0 } func (m *TwoOneofs) GetField34() string { if x, ok := m.GetTwo().(*TwoOneofs_Field34); ok { return x.Field34 } return "" } func (m *TwoOneofs) GetField35() []byte { if x, ok := m.GetTwo().(*TwoOneofs_Field35); ok { return x.Field35 } return nil } func (m *TwoOneofs) GetSubMessage2() *Subby { if x, ok := m.GetTwo().(*TwoOneofs_SubMessage2); ok { return x.SubMessage2 } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{ (*TwoOneofs_Field1)(nil), (*TwoOneofs_Field2)(nil), (*TwoOneofs_Field3)(nil), (*TwoOneofs_Field34)(nil), (*TwoOneofs_Field35)(nil), (*TwoOneofs_SubMessage2)(nil), } } func _TwoOneofs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*TwoOneofs) // one switch x := m.One.(type) { case *TwoOneofs_Field1: _ = b.EncodeVarint(1<<3 | proto.WireFixed64) _ = b.EncodeFixed64(math.Float64bits(x.Field1)) case *TwoOneofs_Field2: _ = b.EncodeVarint(2<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2))) case *TwoOneofs_Field3: _ = b.EncodeVarint(3<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field3)) case nil: default: return fmt.Errorf("TwoOneofs.One has unexpected type %T", x) } // two switch x := m.Two.(type) { case *TwoOneofs_Field34: _ = b.EncodeVarint(34<<3 | proto.WireBytes) _ = b.EncodeStringBytes(x.Field34) case *TwoOneofs_Field35: _ = b.EncodeVarint(35<<3 | proto.WireBytes) _ = b.EncodeRawBytes(x.Field35) case *TwoOneofs_SubMessage2: _ = b.EncodeVarint(36<<3 | proto.WireBytes) if err := b.EncodeMessage(x.SubMessage2); err != nil { return err } case nil: default: return fmt.Errorf("TwoOneofs.Two has unexpected type %T", x) } return nil } func _TwoOneofs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*TwoOneofs) switch tag { case 1: // one.Field1 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.One = &TwoOneofs_Field1{math.Float64frombits(x)} return true, err case 2: // one.Field2 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.One = &TwoOneofs_Field2{math.Float32frombits(uint32(x))} return true, err case 3: // one.Field3 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.One = &TwoOneofs_Field3{int32(x)} return true, err case 34: // two.Field34 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Two = &TwoOneofs_Field34{x} return true, err case 35: // two.Field35 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Two = &TwoOneofs_Field35{x} return true, err case 36: // two.sub_message2 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Subby) err := b.DecodeMessage(msg) m.Two = &TwoOneofs_SubMessage2{msg} return true, err default: return false, nil } } func _TwoOneofs_OneofSizer(msg proto.Message) (n int) { m := msg.(*TwoOneofs) // one switch x := m.One.(type) { case *TwoOneofs_Field1: n += proto.SizeVarint(1<<3 | proto.WireFixed64) n += 8 case *TwoOneofs_Field2: n += proto.SizeVarint(2<<3 | proto.WireFixed32) n += 4 case *TwoOneofs_Field3: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field3)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } // two switch x := m.Two.(type) { case *TwoOneofs_Field34: n += proto.SizeVarint(34<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field34))) n += len(x.Field34) case *TwoOneofs_Field35: n += proto.SizeVarint(35<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field35))) n += len(x.Field35) case *TwoOneofs_SubMessage2: s := proto.Size(x.SubMessage2) n += proto.SizeVarint(36<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type CustomOneof struct { // Types that are valid to be assigned to Custom: // *CustomOneof_Stringy // *CustomOneof_CustomType // *CustomOneof_CastType // *CustomOneof_MyCustomName Custom isCustomOneof_Custom `protobuf_oneof:"custom"` XXX_unrecognized []byte `json:"-"` } func (m *CustomOneof) Reset() { *m = CustomOneof{} } func (*CustomOneof) ProtoMessage() {} func (*CustomOneof) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{3} } type isCustomOneof_Custom interface { isCustomOneof_Custom() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type CustomOneof_Stringy struct { Stringy string `protobuf:"bytes,34,opt,name=Stringy,oneof"` } type CustomOneof_CustomType struct { CustomType github_com_gogo_protobuf_test_custom.Uint128 `protobuf:"bytes,35,opt,name=CustomType,oneof,customtype=github.com/gogo/protobuf/test/custom.Uint128"` } type CustomOneof_CastType struct { CastType github_com_gogo_protobuf_test_casttype.MyUint64Type `protobuf:"varint,36,opt,name=CastType,oneof,casttype=github.com/gogo/protobuf/test/casttype.MyUint64Type"` } type CustomOneof_MyCustomName struct { MyCustomName int64 `protobuf:"varint,37,opt,name=CustomName,oneof"` } func (*CustomOneof_Stringy) isCustomOneof_Custom() {} func (*CustomOneof_CustomType) isCustomOneof_Custom() {} func (*CustomOneof_CastType) isCustomOneof_Custom() {} func (*CustomOneof_MyCustomName) isCustomOneof_Custom() {} func (m *CustomOneof) GetCustom() isCustomOneof_Custom { if m != nil { return m.Custom } return nil } func (m *CustomOneof) GetStringy() string { if x, ok := m.GetCustom().(*CustomOneof_Stringy); ok { return x.Stringy } return "" } func (m *CustomOneof) GetCastType() github_com_gogo_protobuf_test_casttype.MyUint64Type { if x, ok := m.GetCustom().(*CustomOneof_CastType); ok { return x.CastType } return 0 } func (m *CustomOneof) GetMyCustomName() int64 { if x, ok := m.GetCustom().(*CustomOneof_MyCustomName); ok { return x.MyCustomName } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*CustomOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _CustomOneof_OneofMarshaler, _CustomOneof_OneofUnmarshaler, _CustomOneof_OneofSizer, []interface{}{ (*CustomOneof_Stringy)(nil), (*CustomOneof_CustomType)(nil), (*CustomOneof_CastType)(nil), (*CustomOneof_MyCustomName)(nil), } } func _CustomOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*CustomOneof) // custom switch x := m.Custom.(type) { case *CustomOneof_Stringy: _ = b.EncodeVarint(34<<3 | proto.WireBytes) _ = b.EncodeStringBytes(x.Stringy) case *CustomOneof_CustomType: _ = b.EncodeVarint(35<<3 | proto.WireBytes) dAtA, err := x.CustomType.Marshal() if err != nil { return err } _ = b.EncodeRawBytes(dAtA) case *CustomOneof_CastType: _ = b.EncodeVarint(36<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.CastType)) case *CustomOneof_MyCustomName: _ = b.EncodeVarint(37<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.MyCustomName)) case nil: default: return fmt.Errorf("CustomOneof.Custom has unexpected type %T", x) } return nil } func _CustomOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*CustomOneof) switch tag { case 34: // custom.Stringy if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Custom = &CustomOneof_Stringy{x} return true, err case 35: // custom.CustomType if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) if err != nil { return true, err } var cc github_com_gogo_protobuf_test_custom.Uint128 c := &cc err = c.Unmarshal(x) m.Custom = &CustomOneof_CustomType{*c} return true, err case 36: // custom.CastType if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Custom = &CustomOneof_CastType{github_com_gogo_protobuf_test_casttype.MyUint64Type(x)} return true, err case 37: // custom.CustomName if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Custom = &CustomOneof_MyCustomName{int64(x)} return true, err default: return false, nil } } func _CustomOneof_OneofSizer(msg proto.Message) (n int) { m := msg.(*CustomOneof) // custom switch x := m.Custom.(type) { case *CustomOneof_Stringy: n += proto.SizeVarint(34<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Stringy))) n += len(x.Stringy) case *CustomOneof_CustomType: n += proto.SizeVarint(35<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(x.CustomType.Size())) n += x.CustomType.Size() case *CustomOneof_CastType: n += proto.SizeVarint(36<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.CastType)) case *CustomOneof_MyCustomName: n += proto.SizeVarint(37<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.MyCustomName)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } func init() { proto.RegisterType((*Subby)(nil), "one.Subby") proto.RegisterType((*AllTypesOneOf)(nil), "one.AllTypesOneOf") proto.RegisterType((*TwoOneofs)(nil), "one.TwoOneofs") proto.RegisterType((*CustomOneof)(nil), "one.CustomOneof") } func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *AllTypesOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *TwoOneofs) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *CustomOneof) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{} var gzipped = []byte{ // 4043 bytes of a gzipped FileDescriptorSet 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x5a, 0x5b, 0x70, 0xe3, 0xe6, 0x75, 0x16, 0x78, 0x91, 0xc8, 0x43, 0x8a, 0x82, 0x20, 0x79, 0x8d, 0x95, 0x63, 0xee, 0x2e, 0x6d, 0xc7, 0xb2, 0x1d, 0x4b, 0xb6, 0x56, 0xda, 0x0b, 0xb7, 0x89, 0x87, 0xa4, 0xb8, 0x5a, 0x6d, 0x25, 0x51, 0x01, 0xa5, 0x78, 0x9d, 0x3e, 0x60, 0x40, 0xf0, 0x27, 0x85, 0x5d, 0x10, 0x60, 0x00, 0x70, 0xd7, 0xf2, 0xd3, 0x76, 0xdc, 0xcb, 0x64, 0x3a, 0xbd, 0xa5, 0x9d, 0x69, 0xe2, 0x3a, 0x6e, 0x9b, 0x99, 0xd6, 0x69, 0xd2, 0x4b, 0xd2, 0x4b, 0x9a, 0xe9, 0x53, 0x5f, 0xd2, 0xfa, 0xa9, 0xe3, 0xbc, 0x75, 0x3a, 0x1d, 0x8f, 0x57, 0xf1, 0x4c, 0xd3, 0xd6, 0x6d, 0xdd, 0xc6, 0x33, 0xcd, 0x74, 0x5f, 0x3a, 0xff, 0x0d, 0x00, 0x2f, 0x5a, 0x50, 0x99, 0x3a, 0x79, 0x92, 0x70, 0xce, 0xf9, 0x3e, 0x1c, 0x9c, 0xff, 0xfc, 0xe7, 0x1c, 0xfc, 0x04, 0x7c, 0x6f, 0x0d, 0xce, 0xb6, 0x6d, 0xbb, 0x6d, 0xa2, 0xe5, 0xae, 0x63, 0x7b, 0x76, 0xa3, 0xd7, 0x5a, 0x6e, 0x22, 0x57, 0x77, 0x8c, 0xae, 0x67, 0x3b, 0x4b, 0x44, 0x26, 0xcd, 0x50, 0x8b, 0x25, 0x6e, 0x51, 0xd8, 0x86, 0xd9, 0xab, 0x86, 0x89, 0xd6, 0x7d, 0xc3, 0x3a, 0xf2, 0xa4, 0x4b, 0x90, 0x68, 0x19, 0x26, 0x92, 0x85, 0xb3, 0xf1, 0xc5, 0xcc, 0xca, 0xe3, 0x4b, 0x03, 0xa0, 0xa5, 0x7e, 0xc4, 0x2e, 0x16, 0x2b, 0x04, 0x51, 0x78, 0x2f, 0x01, 0x73, 0x23, 0xb4, 0x92, 0x04, 0x09, 0x4b, 0xeb, 0x60, 0x46, 0x61, 0x31, 0xad, 0x90, 0xff, 0x25, 0x19, 0xa6, 0xba, 0x9a, 0x7e, 0x4b, 0x6b, 0x23, 0x39, 0x46, 0xc4, 0xfc, 0x52, 0xca, 0x03, 0x34, 0x51, 0x17, 0x59, 0x4d, 0x64, 0xe9, 0x87, 0x72, 0xfc, 0x6c, 0x7c, 0x31, 0xad, 0x84, 0x24, 0xd2, 0x33, 0x30, 0xdb, 0xed, 0x35, 0x4c, 0x43, 0x57, 0x43, 0x66, 0x70, 0x36, 0xbe, 0x98, 0x54, 0x44, 0xaa, 0x58, 0x0f, 0x8c, 0x9f, 0x84, 0x99, 0x3b, 0x48, 0xbb, 0x15, 0x36, 0xcd, 0x10, 0xd3, 0x1c, 0x16, 0x87, 0x0c, 0x2b, 0x90, 0xed, 0x20, 0xd7, 0xd5, 0xda, 0x48, 0xf5, 0x0e, 0xbb, 0x48, 0x4e, 0x90, 0xa7, 0x3f, 0x3b, 0xf4, 0xf4, 0x83, 0x4f, 0x9e, 0x61, 0xa8, 0xbd, 0xc3, 0x2e, 0x92, 0x4a, 0x90, 0x46, 0x56, 0xaf, 0x43, 0x19, 0x92, 0xc7, 0xc4, 0xaf, 0x6a, 0xf5, 0x3a, 0x83, 0x2c, 0x29, 0x0c, 0x63, 0x14, 0x53, 0x2e, 0x72, 0x6e, 0x1b, 0x3a, 0x92, 0x27, 0x09, 0xc1, 0x93, 0x43, 0x04, 0x75, 0xaa, 0x1f, 0xe4, 0xe0, 0x38, 0xa9, 0x02, 0x69, 0xf4, 0xb2, 0x87, 0x2c, 0xd7, 0xb0, 0x2d, 0x79, 0x8a, 0x90, 0x3c, 0x31, 0x62, 0x15, 0x91, 0xd9, 0x1c, 0xa4, 0x08, 0x70, 0xd2, 0x05, 0x98, 0xb2, 0xbb, 0x9e, 0x61, 0x5b, 0xae, 0x9c, 0x3a, 0x2b, 0x2c, 0x66, 0x56, 0x3e, 0x36, 0x32, 0x11, 0x6a, 0xd4, 0x46, 0xe1, 0xc6, 0xd2, 0x26, 0x88, 0xae, 0xdd, 0x73, 0x74, 0xa4, 0xea, 0x76, 0x13, 0xa9, 0x86, 0xd5, 0xb2, 0xe5, 0x34, 0x21, 0x38, 0x33, 0xfc, 0x20, 0xc4, 0xb0, 0x62, 0x37, 0xd1, 0xa6, 0xd5, 0xb2, 0x95, 0x9c, 0xdb, 0x77, 0x2d, 0x9d, 0x82, 0x49, 0xf7, 0xd0, 0xf2, 0xb4, 0x97, 0xe5, 0x2c, 0xc9, 0x10, 0x76, 0x55, 0xf8, 0x9f, 0x24, 0xcc, 0x8c, 0x93, 0x62, 0x57, 0x20, 0xd9, 0xc2, 0x4f, 0x29, 0xc7, 0x4e, 0x12, 0x03, 0x8a, 0xe9, 0x0f, 0xe2, 0xe4, 0x8f, 0x18, 0xc4, 0x12, 0x64, 0x2c, 0xe4, 0x7a, 0xa8, 0x49, 0x33, 0x22, 0x3e, 0x66, 0x4e, 0x01, 0x05, 0x0d, 0xa7, 0x54, 0xe2, 0x47, 0x4a, 0xa9, 0x1b, 0x30, 0xe3, 0xbb, 0xa4, 0x3a, 0x9a, 0xd5, 0xe6, 0xb9, 0xb9, 0x1c, 0xe5, 0xc9, 0x52, 0x95, 0xe3, 0x14, 0x0c, 0x53, 0x72, 0xa8, 0xef, 0x5a, 0x5a, 0x07, 0xb0, 0x2d, 0x64, 0xb7, 0xd4, 0x26, 0xd2, 0x4d, 0x39, 0x75, 0x4c, 0x94, 0x6a, 0xd8, 0x64, 0x28, 0x4a, 0x36, 0x95, 0xea, 0xa6, 0x74, 0x39, 0x48, 0xb5, 0xa9, 0x63, 0x32, 0x65, 0x9b, 0x6e, 0xb2, 0xa1, 0x6c, 0xdb, 0x87, 0x9c, 0x83, 0x70, 0xde, 0xa3, 0x26, 0x7b, 0xb2, 0x34, 0x71, 0x62, 0x29, 0xf2, 0xc9, 0x14, 0x06, 0xa3, 0x0f, 0x36, 0xed, 0x84, 0x2f, 0xa5, 0xc7, 0xc0, 0x17, 0xa8, 0x24, 0xad, 0x80, 0x54, 0xa1, 0x2c, 0x17, 0xee, 0x68, 0x1d, 0xb4, 0x70, 0x09, 0x72, 0xfd, 0xe1, 0x91, 0xe6, 0x21, 0xe9, 0x7a, 0x9a, 0xe3, 0x91, 0x2c, 0x4c, 0x2a, 0xf4, 0x42, 0x12, 0x21, 0x8e, 0xac, 0x26, 0xa9, 0x72, 0x49, 0x05, 0xff, 0xbb, 0x70, 0x11, 0xa6, 0xfb, 0x6e, 0x3f, 0x2e, 0xb0, 0xf0, 0xc5, 0x49, 0x98, 0x1f, 0x95, 0x73, 0x23, 0xd3, 0xff, 0x14, 0x4c, 0x5a, 0xbd, 0x4e, 0x03, 0x39, 0x72, 0x9c, 0x30, 0xb0, 0x2b, 0xa9, 0x04, 0x49, 0x53, 0x6b, 0x20, 0x53, 0x4e, 0x9c, 0x15, 0x16, 0x73, 0x2b, 0xcf, 0x8c, 0x95, 0xd5, 0x4b, 0x5b, 0x18, 0xa2, 0x50, 0xa4, 0xf4, 0x29, 0x48, 0xb0, 0x12, 0x87, 0x19, 0x9e, 0x1e, 0x8f, 0x01, 0xe7, 0xa2, 0x42, 0x70, 0xd2, 0x23, 0x90, 0xc6, 0x7f, 0x69, 0x6c, 0x27, 0x89, 0xcf, 0x29, 0x2c, 0xc0, 0x71, 0x95, 0x16, 0x20, 0x45, 0xd2, 0xac, 0x89, 0x78, 0x6b, 0xf0, 0xaf, 0xf1, 0xc2, 0x34, 0x51, 0x4b, 0xeb, 0x99, 0x9e, 0x7a, 0x5b, 0x33, 0x7b, 0x88, 0x24, 0x4c, 0x5a, 0xc9, 0x32, 0xe1, 0x67, 0xb0, 0x4c, 0x3a, 0x03, 0x19, 0x9a, 0x95, 0x86, 0xd5, 0x44, 0x2f, 0x93, 0xea, 0x93, 0x54, 0x68, 0xa2, 0x6e, 0x62, 0x09, 0xbe, 0xfd, 0x4d, 0xd7, 0xb6, 0xf8, 0xd2, 0x92, 0x5b, 0x60, 0x01, 0xb9, 0xfd, 0xc5, 0xc1, 0xc2, 0xf7, 0xe8, 0xe8, 0xc7, 0x1b, 0xcc, 0xc5, 0xc2, 0xb7, 0x62, 0x90, 0x20, 0xfb, 0x6d, 0x06, 0x32, 0x7b, 0x2f, 0xed, 0x56, 0xd5, 0xf5, 0xda, 0x7e, 0x79, 0xab, 0x2a, 0x0a, 0x52, 0x0e, 0x80, 0x08, 0xae, 0x6e, 0xd5, 0x4a, 0x7b, 0x62, 0xcc, 0xbf, 0xde, 0xdc, 0xd9, 0xbb, 0xb0, 0x2a, 0xc6, 0x7d, 0xc0, 0x3e, 0x15, 0x24, 0xc2, 0x06, 0xe7, 0x57, 0xc4, 0xa4, 0x24, 0x42, 0x96, 0x12, 0x6c, 0xde, 0xa8, 0xae, 0x5f, 0x58, 0x15, 0x27, 0xfb, 0x25, 0xe7, 0x57, 0xc4, 0x29, 0x69, 0x1a, 0xd2, 0x44, 0x52, 0xae, 0xd5, 0xb6, 0xc4, 0x94, 0xcf, 0x59, 0xdf, 0x53, 0x36, 0x77, 0x36, 0xc4, 0xb4, 0xcf, 0xb9, 0xa1, 0xd4, 0xf6, 0x77, 0x45, 0xf0, 0x19, 0xb6, 0xab, 0xf5, 0x7a, 0x69, 0xa3, 0x2a, 0x66, 0x7c, 0x8b, 0xf2, 0x4b, 0x7b, 0xd5, 0xba, 0x98, 0xed, 0x73, 0xeb, 0xfc, 0x8a, 0x38, 0xed, 0xdf, 0xa2, 0xba, 0xb3, 0xbf, 0x2d, 0xe6, 0xa4, 0x59, 0x98, 0xa6, 0xb7, 0xe0, 0x4e, 0xcc, 0x0c, 0x88, 0x2e, 0xac, 0x8a, 0x62, 0xe0, 0x08, 0x65, 0x99, 0xed, 0x13, 0x5c, 0x58, 0x15, 0xa5, 0x42, 0x05, 0x92, 0x24, 0xbb, 0x24, 0x09, 0x72, 0x5b, 0xa5, 0x72, 0x75, 0x4b, 0xad, 0xed, 0xee, 0x6d, 0xd6, 0x76, 0x4a, 0x5b, 0xa2, 0x10, 0xc8, 0x94, 0xea, 0xa7, 0xf7, 0x37, 0x95, 0xea, 0xba, 0x18, 0x0b, 0xcb, 0x76, 0xab, 0xa5, 0xbd, 0xea, 0xba, 0x18, 0x2f, 0xe8, 0x30, 0x3f, 0xaa, 0xce, 0x8c, 0xdc, 0x19, 0xa1, 0x25, 0x8e, 0x1d, 0xb3, 0xc4, 0x84, 0x6b, 0x68, 0x89, 0xbf, 0x22, 0xc0, 0xdc, 0x88, 0x5a, 0x3b, 0xf2, 0x26, 0x2f, 0x40, 0x92, 0xa6, 0x28, 0xed, 0x3e, 0x4f, 0x8d, 0x2c, 0xda, 0x24, 0x61, 0x87, 0x3a, 0x10, 0xc1, 0x85, 0x3b, 0x70, 0xfc, 0x98, 0x0e, 0x8c, 0x29, 0x86, 0x9c, 0x7c, 0x55, 0x00, 0xf9, 0x38, 0xee, 0x88, 0x42, 0x11, 0xeb, 0x2b, 0x14, 0x57, 0x06, 0x1d, 0x38, 0x77, 0xfc, 0x33, 0x0c, 0x79, 0xf1, 0xa6, 0x00, 0xa7, 0x46, 0x0f, 0x2a, 0x23, 0x7d, 0xf8, 0x14, 0x4c, 0x76, 0x90, 0x77, 0x60, 0xf3, 0x66, 0xfd, 0xf1, 0x11, 0x2d, 0x00, 0xab, 0x07, 0x63, 0xc5, 0x50, 0xe1, 0x1e, 0x12, 0x3f, 0x6e, 0xda, 0xa0, 0xde, 0x0c, 0x79, 0xfa, 0xf9, 0x18, 0x3c, 0x34, 0x92, 0x7c, 0xa4, 0xa3, 0x8f, 0x02, 0x18, 0x56, 0xb7, 0xe7, 0xd1, 0x86, 0x4c, 0xeb, 0x53, 0x9a, 0x48, 0xc8, 0xde, 0xc7, 0xb5, 0xa7, 0xe7, 0xf9, 0xfa, 0x38, 0xd1, 0x03, 0x15, 0x11, 0x83, 0x4b, 0x81, 0xa3, 0x09, 0xe2, 0x68, 0xfe, 0x98, 0x27, 0x1d, 0xea, 0x75, 0xcf, 0x81, 0xa8, 0x9b, 0x06, 0xb2, 0x3c, 0xd5, 0xf5, 0x1c, 0xa4, 0x75, 0x0c, 0xab, 0x4d, 0x0a, 0x70, 0xaa, 0x98, 0x6c, 0x69, 0xa6, 0x8b, 0x94, 0x19, 0xaa, 0xae, 0x73, 0x2d, 0x46, 0x90, 0x2e, 0xe3, 0x84, 0x10, 0x93, 0x7d, 0x08, 0xaa, 0xf6, 0x11, 0x85, 0xaf, 0x4f, 0x41, 0x26, 0x34, 0xd6, 0x49, 0xe7, 0x20, 0x7b, 0x53, 0xbb, 0xad, 0xa9, 0x7c, 0x54, 0xa7, 0x91, 0xc8, 0x60, 0xd9, 0x2e, 0x1b, 0xd7, 0x9f, 0x83, 0x79, 0x62, 0x62, 0xf7, 0x3c, 0xe4, 0xa8, 0xba, 0xa9, 0xb9, 0x2e, 0x09, 0x5a, 0x8a, 0x98, 0x4a, 0x58, 0x57, 0xc3, 0xaa, 0x0a, 0xd7, 0x48, 0x6b, 0x30, 0x47, 0x10, 0x9d, 0x9e, 0xe9, 0x19, 0x5d, 0x13, 0xa9, 0xf8, 0xe5, 0xc1, 0x25, 0x85, 0xd8, 0xf7, 0x6c, 0x16, 0x5b, 0x6c, 0x33, 0x03, 0xec, 0x91, 0x2b, 0xad, 0xc3, 0xa3, 0x04, 0xd6, 0x46, 0x16, 0x72, 0x34, 0x0f, 0xa9, 0xe8, 0x73, 0x3d, 0xcd, 0x74, 0x55, 0xcd, 0x6a, 0xaa, 0x07, 0x9a, 0x7b, 0x20, 0xcf, 0x63, 0x82, 0x72, 0x4c, 0x16, 0x94, 0xd3, 0xd8, 0x70, 0x83, 0xd9, 0x55, 0x89, 0x59, 0xc9, 0x6a, 0x5e, 0xd3, 0xdc, 0x03, 0xa9, 0x08, 0xa7, 0x08, 0x8b, 0xeb, 0x39, 0x86, 0xd5, 0x56, 0xf5, 0x03, 0xa4, 0xdf, 0x52, 0x7b, 0x5e, 0xeb, 0x92, 0xfc, 0x48, 0xf8, 0xfe, 0xc4, 0xc3, 0x3a, 0xb1, 0xa9, 0x60, 0x93, 0x7d, 0xaf, 0x75, 0x49, 0xaa, 0x43, 0x16, 0x2f, 0x46, 0xc7, 0x78, 0x05, 0xa9, 0x2d, 0xdb, 0x21, 0x9d, 0x25, 0x37, 0x62, 0x67, 0x87, 0x22, 0xb8, 0x54, 0x63, 0x80, 0x6d, 0xbb, 0x89, 0x8a, 0xc9, 0xfa, 0x6e, 0xb5, 0xba, 0xae, 0x64, 0x38, 0xcb, 0x55, 0xdb, 0xc1, 0x09, 0xd5, 0xb6, 0xfd, 0x00, 0x67, 0x68, 0x42, 0xb5, 0x6d, 0x1e, 0xde, 0x35, 0x98, 0xd3, 0x75, 0xfa, 0xcc, 0x86, 0xae, 0xb2, 0x11, 0xdf, 0x95, 0xc5, 0xbe, 0x60, 0xe9, 0xfa, 0x06, 0x35, 0x60, 0x39, 0xee, 0x4a, 0x97, 0xe1, 0xa1, 0x20, 0x58, 0x61, 0xe0, 0xec, 0xd0, 0x53, 0x0e, 0x42, 0xd7, 0x60, 0xae, 0x7b, 0x38, 0x0c, 0x94, 0xfa, 0xee, 0xd8, 0x3d, 0x1c, 0x84, 0x3d, 0x41, 0x5e, 0xdb, 0x1c, 0xa4, 0x6b, 0x1e, 0x6a, 0xca, 0x0f, 0x87, 0xad, 0x43, 0x0a, 0x69, 0x19, 0x44, 0x5d, 0x57, 0x91, 0xa5, 0x35, 0x4c, 0xa4, 0x6a, 0x0e, 0xb2, 0x34, 0x57, 0x3e, 0x13, 0x36, 0xce, 0xe9, 0x7a, 0x95, 0x68, 0x4b, 0x44, 0x29, 0x3d, 0x0d, 0xb3, 0x76, 0xe3, 0xa6, 0x4e, 0x33, 0x4b, 0xed, 0x3a, 0xa8, 0x65, 0xbc, 0x2c, 0x3f, 0x4e, 0xc2, 0x34, 0x83, 0x15, 0x24, 0xaf, 0x76, 0x89, 0x58, 0x7a, 0x0a, 0x44, 0xdd, 0x3d, 0xd0, 0x9c, 0x2e, 0x69, 0xed, 0x6e, 0x57, 0xd3, 0x91, 0xfc, 0x04, 0x35, 0xa5, 0xf2, 0x1d, 0x2e, 0xc6, 0x99, 0xed, 0xde, 0x31, 0x5a, 0x1e, 0x67, 0x7c, 0x92, 0x66, 0x36, 0x91, 0x31, 0xb6, 0x1b, 0x30, 0xdf, 0xb3, 0x0c, 0xcb, 0x43, 0x4e, 0xd7, 0x41, 0x78, 0x88, 0xa7, 0x3b, 0x51, 0xfe, 0xe7, 0xa9, 0x63, 0xc6, 0xf0, 0xfd, 0xb0, 0x35, 0x4d, 0x00, 0x65, 0xae, 0x37, 0x2c, 0x2c, 0x14, 0x21, 0x1b, 0xce, 0x0b, 0x29, 0x0d, 0x34, 0x33, 0x44, 0x01, 0xf7, 0xd8, 0x4a, 0x6d, 0x1d, 0x77, 0xc7, 0xcf, 0x56, 0xc5, 0x18, 0xee, 0xd2, 0x5b, 0x9b, 0x7b, 0x55, 0x55, 0xd9, 0xdf, 0xd9, 0xdb, 0xdc, 0xae, 0x8a, 0xf1, 0xa7, 0xd3, 0xa9, 0xef, 0x4f, 0x89, 0x77, 0xef, 0xde, 0xbd, 0x1b, 0x2b, 0x7c, 0x27, 0x06, 0xb9, 0xfe, 0xc9, 0x58, 0xfa, 0x29, 0x78, 0x98, 0xbf, 0xc6, 0xba, 0xc8, 0x53, 0xef, 0x18, 0x0e, 0x49, 0xd5, 0x8e, 0x46, 0x67, 0x4b, 0x3f, 0xca, 0xf3, 0xcc, 0xaa, 0x8e, 0xbc, 0x17, 0x0d, 0x07, 0x27, 0x62, 0x47, 0xf3, 0xa4, 0x2d, 0x38, 0x63, 0xd9, 0xaa, 0xeb, 0x69, 0x56, 0x53, 0x73, 0x9a, 0x6a, 0x70, 0x80, 0xa0, 0x6a, 0xba, 0x8e, 0x5c, 0xd7, 0xa6, 0x2d, 0xc2, 0x67, 0xf9, 0x98, 0x65, 0xd7, 0x99, 0x71, 0x50, 0x3b, 0x4b, 0xcc, 0x74, 0x20, 0x23, 0xe2, 0xc7, 0x65, 0xc4, 0x23, 0x90, 0xee, 0x68, 0x5d, 0x15, 0x59, 0x9e, 0x73, 0x48, 0xe6, 0xb9, 0x94, 0x92, 0xea, 0x68, 0xdd, 0x2a, 0xbe, 0xfe, 0xe8, 0xd6, 0x20, 0x1c, 0xc7, 0x7f, 0x8a, 0x43, 0x36, 0x3c, 0xd3, 0xe1, 0x11, 0x59, 0x27, 0xf5, 0x5b, 0x20, 0x3b, 0xfc, 0xb1, 0x07, 0x4e, 0x80, 0x4b, 0x15, 0x5c, 0xd8, 0x8b, 0x93, 0x74, 0xd2, 0x52, 0x28, 0x12, 0x37, 0x55, 0xbc, 0xa7, 0x11, 0x9d, 0xdf, 0x53, 0x0a, 0xbb, 0x92, 0x36, 0x60, 0xf2, 0xa6, 0x4b, 0xb8, 0x27, 0x09, 0xf7, 0xe3, 0x0f, 0xe6, 0xbe, 0x5e, 0x27, 0xe4, 0xe9, 0xeb, 0x75, 0x75, 0xa7, 0xa6, 0x6c, 0x97, 0xb6, 0x14, 0x06, 0x97, 0x4e, 0x43, 0xc2, 0xd4, 0x5e, 0x39, 0xec, 0x6f, 0x01, 0x44, 0x34, 0x6e, 0xe0, 0x4f, 0x43, 0xe2, 0x0e, 0xd2, 0x6e, 0xf5, 0x17, 0x5e, 0x22, 0xfa, 0x08, 0x53, 0x7f, 0x19, 0x92, 0x24, 0x5e, 0x12, 0x00, 0x8b, 0x98, 0x38, 0x21, 0xa5, 0x20, 0x51, 0xa9, 0x29, 0x38, 0xfd, 0x45, 0xc8, 0x52, 0xa9, 0xba, 0xbb, 0x59, 0xad, 0x54, 0xc5, 0x58, 0x61, 0x0d, 0x26, 0x69, 0x10, 0xf0, 0xd6, 0xf0, 0xc3, 0x20, 0x4e, 0xb0, 0x4b, 0xc6, 0x21, 0x70, 0xed, 0xfe, 0x76, 0xb9, 0xaa, 0x88, 0xb1, 0xf0, 0xf2, 0xba, 0x90, 0x0d, 0x8f, 0x73, 0x3f, 0x9e, 0x9c, 0xfa, 0x6b, 0x01, 0x32, 0xa1, 0xf1, 0x0c, 0x0f, 0x06, 0x9a, 0x69, 0xda, 0x77, 0x54, 0xcd, 0x34, 0x34, 0x97, 0x25, 0x05, 0x10, 0x51, 0x09, 0x4b, 0xc6, 0x5d, 0xb4, 0x1f, 0x8b, 0xf3, 0x6f, 0x08, 0x20, 0x0e, 0x8e, 0x76, 0x03, 0x0e, 0x0a, 0x3f, 0x51, 0x07, 0x5f, 0x17, 0x20, 0xd7, 0x3f, 0xcf, 0x0d, 0xb8, 0x77, 0xee, 0x27, 0xea, 0xde, 0xbb, 0x31, 0x98, 0xee, 0x9b, 0xe2, 0xc6, 0xf5, 0xee, 0x73, 0x30, 0x6b, 0x34, 0x51, 0xa7, 0x6b, 0x7b, 0xc8, 0xd2, 0x0f, 0x55, 0x13, 0xdd, 0x46, 0xa6, 0x5c, 0x20, 0x85, 0x62, 0xf9, 0xc1, 0x73, 0xe2, 0xd2, 0x66, 0x80, 0xdb, 0xc2, 0xb0, 0xe2, 0xdc, 0xe6, 0x7a, 0x75, 0x7b, 0xb7, 0xb6, 0x57, 0xdd, 0xa9, 0xbc, 0xa4, 0xee, 0xef, 0xfc, 0xf4, 0x4e, 0xed, 0xc5, 0x1d, 0x45, 0x34, 0x06, 0xcc, 0x3e, 0xc2, 0xad, 0xbe, 0x0b, 0xe2, 0xa0, 0x53, 0xd2, 0xc3, 0x30, 0xca, 0x2d, 0x71, 0x42, 0x9a, 0x83, 0x99, 0x9d, 0x9a, 0x5a, 0xdf, 0x5c, 0xaf, 0xaa, 0xd5, 0xab, 0x57, 0xab, 0x95, 0xbd, 0x3a, 0x7d, 0x71, 0xf6, 0xad, 0xf7, 0xfa, 0x37, 0xf5, 0x6b, 0x71, 0x98, 0x1b, 0xe1, 0x89, 0x54, 0x62, 0x33, 0x3b, 0x7d, 0x8d, 0x78, 0x76, 0x1c, 0xef, 0x97, 0xf0, 0x54, 0xb0, 0xab, 0x39, 0x1e, 0x1b, 0xf1, 0x9f, 0x02, 0x1c, 0x25, 0xcb, 0x33, 0x5a, 0x06, 0x72, 0xd8, 0x39, 0x03, 0x1d, 0xe4, 0x67, 0x02, 0x39, 0x3d, 0x6a, 0xf8, 0x04, 0x48, 0x5d, 0xdb, 0x35, 0x3c, 0xe3, 0x36, 0x52, 0x0d, 0x8b, 0x1f, 0x4a, 0xe0, 0xc1, 0x3e, 0xa1, 0x88, 0x5c, 0xb3, 0x69, 0x79, 0xbe, 0xb5, 0x85, 0xda, 0xda, 0x80, 0x35, 0x2e, 0xe0, 0x71, 0x45, 0xe4, 0x1a, 0xdf, 0xfa, 0x1c, 0x64, 0x9b, 0x76, 0x0f, 0x8f, 0x49, 0xd4, 0x0e, 0xf7, 0x0b, 0x41, 0xc9, 0x50, 0x99, 0x6f, 0xc2, 0xe6, 0xd8, 0xe0, 0x34, 0x24, 0xab, 0x64, 0xa8, 0x8c, 0x9a, 0x3c, 0x09, 0x33, 0x5a, 0xbb, 0xed, 0x60, 0x72, 0x4e, 0x44, 0x27, 0xf3, 0x9c, 0x2f, 0x26, 0x86, 0x0b, 0xd7, 0x21, 0xc5, 0xe3, 0x80, 0x5b, 0x32, 0x8e, 0x84, 0xda, 0xa5, 0x67, 0x52, 0xb1, 0xc5, 0xb4, 0x92, 0xb2, 0xb8, 0xf2, 0x1c, 0x64, 0x0d, 0x57, 0x0d, 0x0e, 0x47, 0x63, 0x67, 0x63, 0x8b, 0x29, 0x25, 0x63, 0xb8, 0xfe, 0x69, 0x58, 0xe1, 0xcd, 0x18, 0xe4, 0xfa, 0x0f, 0x77, 0xa5, 0x75, 0x48, 0x99, 0xb6, 0xae, 0x91, 0xd4, 0xa2, 0xbf, 0x2c, 0x2c, 0x46, 0x9c, 0x07, 0x2f, 0x6d, 0x31, 0x7b, 0xc5, 0x47, 0x2e, 0xfc, 0xbd, 0x00, 0x29, 0x2e, 0x96, 0x4e, 0x41, 0xa2, 0xab, 0x79, 0x07, 0x84, 0x2e, 0x59, 0x8e, 0x89, 0x82, 0x42, 0xae, 0xb1, 0xdc, 0xed, 0x6a, 0x16, 0x49, 0x01, 0x26, 0xc7, 0xd7, 0x78, 0x5d, 0x4d, 0xa4, 0x35, 0xc9, 0xd8, 0x6f, 0x77, 0x3a, 0xc8, 0xf2, 0x5c, 0xbe, 0xae, 0x4c, 0x5e, 0x61, 0x62, 0xe9, 0x19, 0x98, 0xf5, 0x1c, 0xcd, 0x30, 0xfb, 0x6c, 0x13, 0xc4, 0x56, 0xe4, 0x0a, 0xdf, 0xb8, 0x08, 0xa7, 0x39, 0x6f, 0x13, 0x79, 0x9a, 0x7e, 0x80, 0x9a, 0x01, 0x68, 0x92, 0x9c, 0x1c, 0x3e, 0xcc, 0x0c, 0xd6, 0x99, 0x9e, 0x63, 0x0b, 0xdf, 0x15, 0x60, 0x96, 0xbf, 0xa8, 0x34, 0xfd, 0x60, 0x6d, 0x03, 0x68, 0x96, 0x65, 0x7b, 0xe1, 0x70, 0x0d, 0xa7, 0xf2, 0x10, 0x6e, 0xa9, 0xe4, 0x83, 0x94, 0x10, 0xc1, 0x42, 0x07, 0x20, 0xd0, 0x1c, 0x1b, 0xb6, 0x33, 0x90, 0x61, 0x27, 0xf7, 0xe4, 0xe7, 0x1f, 0xfa, 0x6a, 0x0b, 0x54, 0x84, 0xdf, 0x68, 0xa4, 0x79, 0x48, 0x36, 0x50, 0xdb, 0xb0, 0xd8, 0x79, 0x22, 0xbd, 0xe0, 0xa7, 0x94, 0x09, 0xff, 0x94, 0xb2, 0x7c, 0x03, 0xe6, 0x74, 0xbb, 0x33, 0xe8, 0x6e, 0x59, 0x1c, 0x78, 0xbd, 0x76, 0xaf, 0x09, 0x9f, 0x85, 0x60, 0xc4, 0xfc, 0x4a, 0x2c, 0xbe, 0xb1, 0x5b, 0xfe, 0x5a, 0x6c, 0x61, 0x83, 0xe2, 0x76, 0xf9, 0x63, 0x2a, 0xa8, 0x65, 0x22, 0x1d, 0xbb, 0x0e, 0x3f, 0xf8, 0x38, 0x3c, 0xdb, 0x36, 0xbc, 0x83, 0x5e, 0x63, 0x49, 0xb7, 0x3b, 0xcb, 0x6d, 0xbb, 0x6d, 0x07, 0x3f, 0x77, 0xe1, 0x2b, 0x72, 0x41, 0xfe, 0x63, 0x3f, 0x79, 0xa5, 0x7d, 0xe9, 0x42, 0xe4, 0xef, 0x63, 0xc5, 0x1d, 0x98, 0x63, 0xc6, 0x2a, 0x39, 0x73, 0xa7, 0xaf, 0x06, 0xd2, 0x03, 0xcf, 0x5d, 0xe4, 0x6f, 0xbe, 0x47, 0x7a, 0xb5, 0x32, 0xcb, 0xa0, 0x58, 0x47, 0x5f, 0x20, 0x8a, 0x0a, 0x3c, 0xd4, 0xc7, 0x47, 0xf7, 0x25, 0x72, 0x22, 0x18, 0xbf, 0xc3, 0x18, 0xe7, 0x42, 0x8c, 0x75, 0x06, 0x2d, 0x56, 0x60, 0xfa, 0x24, 0x5c, 0x7f, 0xcb, 0xb8, 0xb2, 0x28, 0x4c, 0xb2, 0x01, 0x33, 0x84, 0x44, 0xef, 0xb9, 0x9e, 0xdd, 0x21, 0x45, 0xef, 0xc1, 0x34, 0x7f, 0xf7, 0x1e, 0xdd, 0x28, 0x39, 0x0c, 0xab, 0xf8, 0xa8, 0x62, 0x11, 0xc8, 0xcf, 0x0c, 0x4d, 0xa4, 0x9b, 0x11, 0x0c, 0x6f, 0x31, 0x47, 0x7c, 0xfb, 0xe2, 0x67, 0x60, 0x1e, 0xff, 0x4f, 0x6a, 0x52, 0xd8, 0x93, 0xe8, 0x53, 0x26, 0xf9, 0xbb, 0xaf, 0xd2, 0xbd, 0x38, 0xe7, 0x13, 0x84, 0x7c, 0x0a, 0xad, 0x62, 0x1b, 0x79, 0x1e, 0x72, 0x5c, 0x55, 0x33, 0x47, 0xb9, 0x17, 0x7a, 0x4d, 0x97, 0xbf, 0xf4, 0x7e, 0xff, 0x2a, 0x6e, 0x50, 0x64, 0xc9, 0x34, 0x8b, 0xfb, 0xf0, 0xf0, 0x88, 0xac, 0x18, 0x83, 0xf3, 0x35, 0xc6, 0x39, 0x3f, 0x94, 0x19, 0x98, 0x76, 0x17, 0xb8, 0xdc, 0x5f, 0xcb, 0x31, 0x38, 0x7f, 0x9b, 0x71, 0x4a, 0x0c, 0xcb, 0x97, 0x14, 0x33, 0x5e, 0x87, 0xd9, 0xdb, 0xc8, 0x69, 0xd8, 0x2e, 0x3b, 0x1a, 0x19, 0x83, 0xee, 0x75, 0x46, 0x37, 0xc3, 0x80, 0xe4, 0xac, 0x04, 0x73, 0x5d, 0x86, 0x54, 0x4b, 0xd3, 0xd1, 0x18, 0x14, 0x5f, 0x66, 0x14, 0x53, 0xd8, 0x1e, 0x43, 0x4b, 0x90, 0x6d, 0xdb, 0xac, 0x2d, 0x45, 0xc3, 0xdf, 0x60, 0xf0, 0x0c, 0xc7, 0x30, 0x8a, 0xae, 0xdd, 0xed, 0x99, 0xb8, 0x67, 0x45, 0x53, 0xfc, 0x0e, 0xa7, 0xe0, 0x18, 0x46, 0x71, 0x82, 0xb0, 0xfe, 0x2e, 0xa7, 0x70, 0x43, 0xf1, 0x7c, 0x01, 0x32, 0xb6, 0x65, 0x1e, 0xda, 0xd6, 0x38, 0x4e, 0xfc, 0x1e, 0x63, 0x00, 0x06, 0xc1, 0x04, 0x57, 0x20, 0x3d, 0xee, 0x42, 0xfc, 0xfe, 0xfb, 0x7c, 0x7b, 0xf0, 0x15, 0xd8, 0x80, 0x19, 0x5e, 0xa0, 0x0c, 0xdb, 0x1a, 0x83, 0xe2, 0x0f, 0x18, 0x45, 0x2e, 0x04, 0x63, 0x8f, 0xe1, 0x21, 0xd7, 0x6b, 0xa3, 0x71, 0x48, 0xde, 0xe4, 0x8f, 0xc1, 0x20, 0x2c, 0x94, 0x0d, 0x64, 0xe9, 0x07, 0xe3, 0x31, 0x7c, 0x95, 0x87, 0x92, 0x63, 0x30, 0x45, 0x05, 0xa6, 0x3b, 0x9a, 0xe3, 0x1e, 0x68, 0xe6, 0x58, 0xcb, 0xf1, 0x87, 0x8c, 0x23, 0xeb, 0x83, 0x58, 0x44, 0x7a, 0xd6, 0x49, 0x68, 0xbe, 0xc6, 0x23, 0x12, 0x82, 0xb1, 0xad, 0xe7, 0x7a, 0xe4, 0x00, 0xea, 0x24, 0x6c, 0x5f, 0xe7, 0x5b, 0x8f, 0x62, 0xb7, 0xc3, 0x8c, 0x57, 0x20, 0xed, 0x1a, 0xaf, 0x8c, 0x45, 0xf3, 0x47, 0x7c, 0xa5, 0x09, 0x00, 0x83, 0x5f, 0x82, 0xd3, 0x23, 0xdb, 0xc4, 0x18, 0x64, 0x7f, 0xcc, 0xc8, 0x4e, 0x8d, 0x68, 0x15, 0xac, 0x24, 0x9c, 0x94, 0xf2, 0x4f, 0x78, 0x49, 0x40, 0x03, 0x5c, 0xbb, 0xf8, 0x45, 0xc1, 0xd5, 0x5a, 0x27, 0x8b, 0xda, 0x9f, 0xf2, 0xa8, 0x51, 0x6c, 0x5f, 0xd4, 0xf6, 0xe0, 0x14, 0x63, 0x3c, 0xd9, 0xba, 0x7e, 0x83, 0x17, 0x56, 0x8a, 0xde, 0xef, 0x5f, 0xdd, 0x9f, 0x81, 0x05, 0x3f, 0x9c, 0x7c, 0x22, 0x75, 0xd5, 0x8e, 0xd6, 0x1d, 0x83, 0xf9, 0x9b, 0x8c, 0x99, 0x57, 0x7c, 0x7f, 0xa4, 0x75, 0xb7, 0xb5, 0x2e, 0x26, 0xbf, 0x01, 0x32, 0x27, 0xef, 0x59, 0x0e, 0xd2, 0xed, 0xb6, 0x65, 0xbc, 0x82, 0x9a, 0x63, 0x50, 0xff, 0xd9, 0xc0, 0x52, 0xed, 0x87, 0xe0, 0x98, 0x79, 0x13, 0x44, 0x7f, 0x56, 0x51, 0x8d, 0x4e, 0xd7, 0x76, 0xbc, 0x08, 0xc6, 0x3f, 0xe7, 0x2b, 0xe5, 0xe3, 0x36, 0x09, 0xac, 0x58, 0x85, 0x1c, 0xb9, 0x1c, 0x37, 0x25, 0xff, 0x82, 0x11, 0x4d, 0x07, 0x28, 0x56, 0x38, 0x74, 0xbb, 0xd3, 0xd5, 0x9c, 0x71, 0xea, 0xdf, 0x5f, 0xf2, 0xc2, 0xc1, 0x20, 0xac, 0x70, 0x78, 0x87, 0x5d, 0x84, 0xbb, 0xfd, 0x18, 0x0c, 0xdf, 0xe2, 0x85, 0x83, 0x63, 0x18, 0x05, 0x1f, 0x18, 0xc6, 0xa0, 0xf8, 0x2b, 0x4e, 0xc1, 0x31, 0x98, 0xe2, 0xd3, 0x41, 0xa3, 0x75, 0x50, 0xdb, 0x70, 0x3d, 0x87, 0xce, 0xc1, 0x0f, 0xa6, 0xfa, 0xf6, 0xfb, 0xfd, 0x43, 0x98, 0x12, 0x82, 0x16, 0xaf, 0xc3, 0xcc, 0xc0, 0x88, 0x21, 0x45, 0x7d, 0xb3, 0x20, 0xff, 0xec, 0x87, 0xac, 0x18, 0xf5, 0x4f, 0x18, 0xc5, 0x2d, 0xbc, 0xee, 0xfd, 0x73, 0x40, 0x34, 0xd9, 0xab, 0x1f, 0xfa, 0x4b, 0xdf, 0x37, 0x06, 0x14, 0xaf, 0xc2, 0x74, 0xdf, 0x0c, 0x10, 0x4d, 0xf5, 0x73, 0x8c, 0x2a, 0x1b, 0x1e, 0x01, 0x8a, 0x6b, 0x90, 0xc0, 0xfd, 0x3c, 0x1a, 0xfe, 0xf3, 0x0c, 0x4e, 0xcc, 0x8b, 0x9f, 0x84, 0x14, 0xef, 0xe3, 0xd1, 0xd0, 0x5f, 0x60, 0x50, 0x1f, 0x82, 0xe1, 0xbc, 0x87, 0x47, 0xc3, 0x7f, 0x91, 0xc3, 0x39, 0x04, 0xc3, 0xc7, 0x0f, 0xe1, 0xdf, 0xfc, 0x52, 0x82, 0xd5, 0x61, 0x1e, 0xbb, 0x2b, 0x30, 0xc5, 0x9a, 0x77, 0x34, 0xfa, 0xf3, 0xec, 0xe6, 0x1c, 0x51, 0xbc, 0x08, 0xc9, 0x31, 0x03, 0xfe, 0xcb, 0x0c, 0x4a, 0xed, 0x8b, 0x15, 0xc8, 0x84, 0x1a, 0x76, 0x34, 0xfc, 0x57, 0x18, 0x3c, 0x8c, 0xc2, 0xae, 0xb3, 0x86, 0x1d, 0x4d, 0xf0, 0xab, 0xdc, 0x75, 0x86, 0xc0, 0x61, 0xe3, 0xbd, 0x3a, 0x1a, 0xfd, 0x6b, 0x3c, 0xea, 0x1c, 0x52, 0x7c, 0x01, 0xd2, 0x7e, 0xfd, 0x8d, 0xc6, 0xff, 0x3a, 0xc3, 0x07, 0x18, 0x1c, 0x81, 0x50, 0xfd, 0x8f, 0xa6, 0xf8, 0x02, 0x8f, 0x40, 0x08, 0x85, 0xb7, 0xd1, 0x60, 0x4f, 0x8f, 0x66, 0xfa, 0x0d, 0xbe, 0x8d, 0x06, 0x5a, 0x3a, 0x5e, 0x4d, 0x52, 0x06, 0xa3, 0x29, 0x7e, 0x93, 0xaf, 0x26, 0xb1, 0xc7, 0x6e, 0x0c, 0x36, 0xc9, 0x68, 0x8e, 0xdf, 0xe2, 0x6e, 0x0c, 0xf4, 0xc8, 0xe2, 0x2e, 0x48, 0xc3, 0x0d, 0x32, 0x9a, 0xef, 0x8b, 0x8c, 0x6f, 0x76, 0xa8, 0x3f, 0x16, 0x5f, 0x84, 0x53, 0xa3, 0x9b, 0x63, 0x34, 0xeb, 0x97, 0x3e, 0x1c, 0x78, 0x9d, 0x09, 0xf7, 0xc6, 0xe2, 0x5e, 0x50, 0x65, 0xc3, 0x8d, 0x31, 0x9a, 0xf6, 0xb5, 0x0f, 0xfb, 0x0b, 0x6d, 0xb8, 0x2f, 0x16, 0x4b, 0x00, 0x41, 0x4f, 0x8a, 0xe6, 0x7a, 0x9d, 0x71, 0x85, 0x40, 0x78, 0x6b, 0xb0, 0x96, 0x14, 0x8d, 0xff, 0x32, 0xdf, 0x1a, 0x0c, 0x81, 0xb7, 0x06, 0xef, 0x46, 0xd1, 0xe8, 0x37, 0xf8, 0xd6, 0xe0, 0x90, 0xe2, 0x15, 0x48, 0x59, 0x3d, 0xd3, 0xc4, 0xb9, 0x25, 0x3d, 0xf8, 0x33, 0x22, 0xf9, 0x5f, 0xee, 0x33, 0x30, 0x07, 0x14, 0xd7, 0x20, 0x89, 0x3a, 0x0d, 0xd4, 0x8c, 0x42, 0xfe, 0xeb, 0x7d, 0x5e, 0x4f, 0xb0, 0x75, 0xf1, 0x05, 0x00, 0xfa, 0x32, 0x4d, 0x7e, 0x25, 0x8a, 0xc0, 0xfe, 0xdb, 0x7d, 0xf6, 0x85, 0x42, 0x00, 0x09, 0x08, 0xe8, 0xf7, 0x0e, 0x0f, 0x26, 0x78, 0xbf, 0x9f, 0x80, 0xbc, 0x80, 0x5f, 0x86, 0xa9, 0x9b, 0xae, 0x6d, 0x79, 0x5a, 0x3b, 0x0a, 0xfd, 0xef, 0x0c, 0xcd, 0xed, 0x71, 0xc0, 0x3a, 0xb6, 0x83, 0x3c, 0xad, 0xed, 0x46, 0x61, 0xff, 0x83, 0x61, 0x7d, 0x00, 0x06, 0xeb, 0x9a, 0xeb, 0x8d, 0xf3, 0xdc, 0xff, 0xc9, 0xc1, 0x1c, 0x80, 0x9d, 0xc6, 0xff, 0xdf, 0x42, 0x87, 0x51, 0xd8, 0x0f, 0xb8, 0xd3, 0xcc, 0xbe, 0xf8, 0x49, 0x48, 0xe3, 0x7f, 0xe9, 0x57, 0x3b, 0x11, 0xe0, 0xff, 0x62, 0xe0, 0x00, 0x81, 0xef, 0xec, 0x7a, 0x4d, 0xcf, 0x88, 0x0e, 0xf6, 0x7f, 0xb3, 0x95, 0xe6, 0xf6, 0xc5, 0x12, 0x64, 0x5c, 0xaf, 0xd9, 0xec, 0xb1, 0x89, 0x26, 0x02, 0xfe, 0x83, 0xfb, 0xfe, 0x4b, 0xae, 0x8f, 0x29, 0x9f, 0x1b, 0x7d, 0x58, 0x07, 0x1b, 0xf6, 0x86, 0x4d, 0x8f, 0xe9, 0xe0, 0x7e, 0x0a, 0x1e, 0xd1, 0xed, 0x4e, 0xc3, 0x76, 0x97, 0x69, 0x41, 0x69, 0xd8, 0xde, 0xc1, 0xb2, 0x6d, 0x31, 0x73, 0x29, 0x6e, 0x5b, 0x68, 0xe1, 0x64, 0xe7, 0x72, 0x85, 0xd3, 0x90, 0xac, 0xf7, 0x1a, 0x8d, 0x43, 0x49, 0x84, 0xb8, 0xdb, 0x6b, 0xb0, 0x0f, 0x4b, 0xf0, 0xbf, 0x85, 0x77, 0xe2, 0x30, 0x5d, 0x32, 0xcd, 0xbd, 0xc3, 0x2e, 0x72, 0x6b, 0x16, 0xaa, 0xb5, 0x24, 0x19, 0x26, 0xc9, 0x83, 0x3c, 0x4f, 0xcc, 0x84, 0x6b, 0x13, 0x0a, 0xbb, 0xf6, 0x35, 0x2b, 0xe4, 0xb8, 0x32, 0xe6, 0x6b, 0x56, 0x7c, 0xcd, 0x79, 0x7a, 0x5a, 0xe9, 0x6b, 0xce, 0xfb, 0x9a, 0x55, 0x72, 0x66, 0x19, 0xf7, 0x35, 0xab, 0xbe, 0x66, 0x8d, 0x9c, 0xc9, 0x4f, 0xfb, 0x9a, 0x35, 0x5f, 0x73, 0x81, 0x9c, 0xc2, 0x27, 0x7c, 0xcd, 0x05, 0x5f, 0x73, 0x91, 0x1c, 0xbe, 0xcf, 0xfa, 0x9a, 0x8b, 0xbe, 0xe6, 0x12, 0x39, 0x70, 0x97, 0x7c, 0xcd, 0x25, 0x5f, 0x73, 0x99, 0x7c, 0x41, 0x32, 0xe5, 0x6b, 0x2e, 0x4b, 0x0b, 0x30, 0x45, 0x9f, 0xec, 0x39, 0xf2, 0xab, 0xec, 0xcc, 0xb5, 0x09, 0x85, 0x0b, 0x02, 0xdd, 0xf3, 0xe4, 0x2b, 0x91, 0xc9, 0x40, 0xf7, 0x7c, 0xa0, 0x5b, 0x21, 0xdf, 0x4a, 0x8b, 0x81, 0x6e, 0x25, 0xd0, 0x9d, 0x97, 0xa7, 0xf1, 0xfa, 0x07, 0xba, 0xf3, 0x81, 0x6e, 0x55, 0xce, 0xe1, 0x15, 0x08, 0x74, 0xab, 0x81, 0x6e, 0x4d, 0x9e, 0x39, 0x2b, 0x2c, 0x66, 0x03, 0xdd, 0x9a, 0xf4, 0x2c, 0x64, 0xdc, 0x5e, 0x43, 0x65, 0x1f, 0x11, 0x90, 0xaf, 0x51, 0x32, 0x2b, 0xb0, 0x84, 0x73, 0x82, 0x2c, 0xeb, 0xb5, 0x09, 0x05, 0xdc, 0x5e, 0x83, 0x15, 0xc8, 0x72, 0x16, 0xc8, 0x79, 0x82, 0x4a, 0xbe, 0xc1, 0x2c, 0xbc, 0x2d, 0x40, 0x7a, 0xef, 0x8e, 0x4d, 0x7e, 0x93, 0x75, 0xff, 0x9f, 0x17, 0x97, 0x3b, 0x7d, 0x7e, 0x95, 0xfc, 0x6c, 0x96, 0xbe, 0x26, 0x28, 0x5c, 0x10, 0xe8, 0xd6, 0xe4, 0xc7, 0xc8, 0x03, 0xf9, 0xba, 0x35, 0x69, 0x19, 0xb2, 0xa1, 0x07, 0x5a, 0x21, 0x1f, 0x98, 0xf4, 0x3f, 0x91, 0xa0, 0x64, 0x82, 0x27, 0x5a, 0x29, 0x27, 0x01, 0xa7, 0x3d, 0xfe, 0xe3, 0xdd, 0xb1, 0x0b, 0x5f, 0x88, 0x41, 0x86, 0x1e, 0x41, 0x92, 0xa7, 0xc2, 0xb7, 0xa2, 0x23, 0xf9, 0x21, 0x73, 0x63, 0x42, 0xe1, 0x02, 0x49, 0x01, 0xa0, 0xa6, 0x38, 0xc3, 0xa9, 0x27, 0xe5, 0xe7, 0xfe, 0xf1, 0x9d, 0x33, 0x9f, 0x38, 0x76, 0x07, 0xe1, 0xd8, 0x2d, 0xd3, 0x02, 0xbb, 0xb4, 0x6f, 0x58, 0xde, 0xf3, 0x2b, 0x97, 0x70, 0x80, 0x03, 0x16, 0x69, 0x1f, 0x52, 0x15, 0xcd, 0x25, 0x5f, 0x98, 0x11, 0xd7, 0x13, 0xe5, 0x8b, 0xff, 0xfb, 0xce, 0x99, 0xf3, 0x11, 0x8c, 0xac, 0xf6, 0x2d, 0x6d, 0x1f, 0x62, 0xd6, 0x0b, 0xab, 0x18, 0x7e, 0x6d, 0x42, 0xf1, 0xa9, 0xa4, 0x15, 0xee, 0xea, 0x8e, 0xd6, 0xa1, 0x5f, 0xd2, 0xc4, 0xcb, 0xe2, 0xd1, 0x3b, 0x67, 0xb2, 0xdb, 0x87, 0x81, 0x3c, 0x70, 0x05, 0x5f, 0x95, 0x53, 0x30, 0x49, 0x5d, 0x2d, 0xaf, 0xbf, 0x75, 0x2f, 0x3f, 0xf1, 0xf6, 0xbd, 0xfc, 0xc4, 0x3f, 0xdc, 0xcb, 0x4f, 0xbc, 0x7b, 0x2f, 0x2f, 0x7c, 0x70, 0x2f, 0x2f, 0xfc, 0xf0, 0x5e, 0x5e, 0xb8, 0x7b, 0x94, 0x17, 0xbe, 0x7a, 0x94, 0x17, 0xbe, 0x71, 0x94, 0x17, 0xbe, 0x7d, 0x94, 0x17, 0xde, 0x3a, 0xca, 0x4f, 0xbc, 0x7d, 0x94, 0x9f, 0x78, 0xf7, 0x28, 0x2f, 0x7c, 0xff, 0x28, 0x3f, 0xf1, 0xc1, 0x51, 0x5e, 0xf8, 0xe1, 0x51, 0x5e, 0xb8, 0xfb, 0xbd, 0xbc, 0xf0, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x92, 0x09, 0x9d, 0x38, 0xda, 0x32, 0x00, 0x00, } r := bytes.NewReader(gzipped) gzipr, err := compress_gzip.NewReader(r) if err != nil { panic(err) } ungzipped, err := io_ioutil.ReadAll(gzipr) if err != nil { panic(err) } if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil { panic(err) } return d } func (this *Subby) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *Subby") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *Subby but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *Subby but is not nil && this == nil") } if this.Sub != nil && that1.Sub != nil { if *this.Sub != *that1.Sub { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", *this.Sub, *that1.Sub) } } else if this.Sub != nil { return fmt.Errorf("this.Sub == nil && that.Sub != nil") } else if that1.Sub != nil { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub) } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *Subby) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Sub != nil && that1.Sub != nil { if *this.Sub != *that1.Sub { return false } } else if this.Sub != nil { return false } else if that1.Sub != nil { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *AllTypesOneOf) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf) if !ok { that2, ok := that.(AllTypesOneOf) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf but is not nil && this == nil") } if that1.TestOneof == nil { if this.TestOneof != nil { return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil") } } else if this.TestOneof == nil { return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil") } else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *AllTypesOneOf_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field1) if !ok { that2, ok := that.(AllTypesOneOf_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *AllTypesOneOf_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field2) if !ok { that2, ok := that.(AllTypesOneOf_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *AllTypesOneOf_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field3) if !ok { that2, ok := that.(AllTypesOneOf_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *AllTypesOneOf_Field4) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field4) if !ok { that2, ok := that.(AllTypesOneOf_Field4) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field4") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is not nil && this == nil") } if this.Field4 != that1.Field4 { return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4) } return nil } func (this *AllTypesOneOf_Field5) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field5) if !ok { that2, ok := that.(AllTypesOneOf_Field5) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field5") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is not nil && this == nil") } if this.Field5 != that1.Field5 { return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5) } return nil } func (this *AllTypesOneOf_Field6) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field6) if !ok { that2, ok := that.(AllTypesOneOf_Field6) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field6") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is not nil && this == nil") } if this.Field6 != that1.Field6 { return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6) } return nil } func (this *AllTypesOneOf_Field7) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field7) if !ok { that2, ok := that.(AllTypesOneOf_Field7) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field7") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is not nil && this == nil") } if this.Field7 != that1.Field7 { return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7) } return nil } func (this *AllTypesOneOf_Field8) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field8) if !ok { that2, ok := that.(AllTypesOneOf_Field8) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field8") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is not nil && this == nil") } if this.Field8 != that1.Field8 { return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8) } return nil } func (this *AllTypesOneOf_Field9) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field9) if !ok { that2, ok := that.(AllTypesOneOf_Field9) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field9") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is not nil && this == nil") } if this.Field9 != that1.Field9 { return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9) } return nil } func (this *AllTypesOneOf_Field10) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field10) if !ok { that2, ok := that.(AllTypesOneOf_Field10) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field10") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is not nil && this == nil") } if this.Field10 != that1.Field10 { return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10) } return nil } func (this *AllTypesOneOf_Field11) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field11) if !ok { that2, ok := that.(AllTypesOneOf_Field11) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field11") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is not nil && this == nil") } if this.Field11 != that1.Field11 { return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11) } return nil } func (this *AllTypesOneOf_Field12) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field12) if !ok { that2, ok := that.(AllTypesOneOf_Field12) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field12") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is not nil && this == nil") } if this.Field12 != that1.Field12 { return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12) } return nil } func (this *AllTypesOneOf_Field13) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field13) if !ok { that2, ok := that.(AllTypesOneOf_Field13) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field13") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is not nil && this == nil") } if this.Field13 != that1.Field13 { return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13) } return nil } func (this *AllTypesOneOf_Field14) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field14) if !ok { that2, ok := that.(AllTypesOneOf_Field14) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field14") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is not nil && this == nil") } if this.Field14 != that1.Field14 { return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14) } return nil } func (this *AllTypesOneOf_Field15) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_Field15) if !ok { that2, ok := that.(AllTypesOneOf_Field15) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_Field15") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is not nil && this == nil") } if !bytes.Equal(this.Field15, that1.Field15) { return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15) } return nil } func (this *AllTypesOneOf_SubMessage) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*AllTypesOneOf_SubMessage) if !ok { that2, ok := that.(AllTypesOneOf_SubMessage) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *AllTypesOneOf_SubMessage") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is not nil && this == nil") } if !this.SubMessage.Equal(that1.SubMessage) { return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage) } return nil } func (this *AllTypesOneOf) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf) if !ok { that2, ok := that.(AllTypesOneOf) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.TestOneof == nil { if this.TestOneof != nil { return false } } else if this.TestOneof == nil { return false } else if !this.TestOneof.Equal(that1.TestOneof) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *AllTypesOneOf_Field1) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field1) if !ok { that2, ok := that.(AllTypesOneOf_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *AllTypesOneOf_Field2) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field2) if !ok { that2, ok := that.(AllTypesOneOf_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *AllTypesOneOf_Field3) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field3) if !ok { that2, ok := that.(AllTypesOneOf_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *AllTypesOneOf_Field4) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field4) if !ok { that2, ok := that.(AllTypesOneOf_Field4) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field4 != that1.Field4 { return false } return true } func (this *AllTypesOneOf_Field5) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field5) if !ok { that2, ok := that.(AllTypesOneOf_Field5) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field5 != that1.Field5 { return false } return true } func (this *AllTypesOneOf_Field6) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field6) if !ok { that2, ok := that.(AllTypesOneOf_Field6) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field6 != that1.Field6 { return false } return true } func (this *AllTypesOneOf_Field7) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field7) if !ok { that2, ok := that.(AllTypesOneOf_Field7) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field7 != that1.Field7 { return false } return true } func (this *AllTypesOneOf_Field8) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field8) if !ok { that2, ok := that.(AllTypesOneOf_Field8) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field8 != that1.Field8 { return false } return true } func (this *AllTypesOneOf_Field9) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field9) if !ok { that2, ok := that.(AllTypesOneOf_Field9) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field9 != that1.Field9 { return false } return true } func (this *AllTypesOneOf_Field10) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field10) if !ok { that2, ok := that.(AllTypesOneOf_Field10) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field10 != that1.Field10 { return false } return true } func (this *AllTypesOneOf_Field11) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field11) if !ok { that2, ok := that.(AllTypesOneOf_Field11) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field11 != that1.Field11 { return false } return true } func (this *AllTypesOneOf_Field12) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field12) if !ok { that2, ok := that.(AllTypesOneOf_Field12) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field12 != that1.Field12 { return false } return true } func (this *AllTypesOneOf_Field13) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field13) if !ok { that2, ok := that.(AllTypesOneOf_Field13) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field13 != that1.Field13 { return false } return true } func (this *AllTypesOneOf_Field14) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field14) if !ok { that2, ok := that.(AllTypesOneOf_Field14) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field14 != that1.Field14 { return false } return true } func (this *AllTypesOneOf_Field15) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_Field15) if !ok { that2, ok := that.(AllTypesOneOf_Field15) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !bytes.Equal(this.Field15, that1.Field15) { return false } return true } func (this *AllTypesOneOf_SubMessage) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*AllTypesOneOf_SubMessage) if !ok { that2, ok := that.(AllTypesOneOf_SubMessage) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.SubMessage.Equal(that1.SubMessage) { return false } return true } func (this *TwoOneofs) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs) if !ok { that2, ok := that.(TwoOneofs) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs but is not nil && this == nil") } if that1.One == nil { if this.One != nil { return fmt.Errorf("this.One != nil && that1.One == nil") } } else if this.One == nil { return fmt.Errorf("this.One == nil && that1.One != nil") } else if err := this.One.VerboseEqual(that1.One); err != nil { return err } if that1.Two == nil { if this.Two != nil { return fmt.Errorf("this.Two != nil && that1.Two == nil") } } else if this.Two == nil { return fmt.Errorf("this.Two == nil && that1.Two != nil") } else if err := this.Two.VerboseEqual(that1.Two); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *TwoOneofs_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field1) if !ok { that2, ok := that.(TwoOneofs_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *TwoOneofs_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field2) if !ok { that2, ok := that.(TwoOneofs_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *TwoOneofs_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field3) if !ok { that2, ok := that.(TwoOneofs_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *TwoOneofs_Field34) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field34) if !ok { that2, ok := that.(TwoOneofs_Field34) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field34") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field34 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field34 but is not nil && this == nil") } if this.Field34 != that1.Field34 { return fmt.Errorf("Field34 this(%v) Not Equal that(%v)", this.Field34, that1.Field34) } return nil } func (this *TwoOneofs_Field35) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_Field35) if !ok { that2, ok := that.(TwoOneofs_Field35) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_Field35") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_Field35 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_Field35 but is not nil && this == nil") } if !bytes.Equal(this.Field35, that1.Field35) { return fmt.Errorf("Field35 this(%v) Not Equal that(%v)", this.Field35, that1.Field35) } return nil } func (this *TwoOneofs_SubMessage2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*TwoOneofs_SubMessage2) if !ok { that2, ok := that.(TwoOneofs_SubMessage2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *TwoOneofs_SubMessage2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is not nil && this == nil") } if !this.SubMessage2.Equal(that1.SubMessage2) { return fmt.Errorf("SubMessage2 this(%v) Not Equal that(%v)", this.SubMessage2, that1.SubMessage2) } return nil } func (this *TwoOneofs) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs) if !ok { that2, ok := that.(TwoOneofs) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.One == nil { if this.One != nil { return false } } else if this.One == nil { return false } else if !this.One.Equal(that1.One) { return false } if that1.Two == nil { if this.Two != nil { return false } } else if this.Two == nil { return false } else if !this.Two.Equal(that1.Two) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *TwoOneofs_Field1) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_Field1) if !ok { that2, ok := that.(TwoOneofs_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *TwoOneofs_Field2) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_Field2) if !ok { that2, ok := that.(TwoOneofs_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *TwoOneofs_Field3) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_Field3) if !ok { that2, ok := that.(TwoOneofs_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *TwoOneofs_Field34) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_Field34) if !ok { that2, ok := that.(TwoOneofs_Field34) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field34 != that1.Field34 { return false } return true } func (this *TwoOneofs_Field35) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_Field35) if !ok { that2, ok := that.(TwoOneofs_Field35) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !bytes.Equal(this.Field35, that1.Field35) { return false } return true } func (this *TwoOneofs_SubMessage2) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*TwoOneofs_SubMessage2) if !ok { that2, ok := that.(TwoOneofs_SubMessage2) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.SubMessage2.Equal(that1.SubMessage2) { return false } return true } func (this *CustomOneof) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof) if !ok { that2, ok := that.(CustomOneof) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof but is not nil && this == nil") } if that1.Custom == nil { if this.Custom != nil { return fmt.Errorf("this.Custom != nil && that1.Custom == nil") } } else if this.Custom == nil { return fmt.Errorf("this.Custom == nil && that1.Custom != nil") } else if err := this.Custom.VerboseEqual(that1.Custom); err != nil { return err } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *CustomOneof_Stringy) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_Stringy) if !ok { that2, ok := that.(CustomOneof_Stringy) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_Stringy") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_Stringy but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_Stringy but is not nil && this == nil") } if this.Stringy != that1.Stringy { return fmt.Errorf("Stringy this(%v) Not Equal that(%v)", this.Stringy, that1.Stringy) } return nil } func (this *CustomOneof_CustomType) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_CustomType) if !ok { that2, ok := that.(CustomOneof_CustomType) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_CustomType") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_CustomType but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_CustomType but is not nil && this == nil") } if !this.CustomType.Equal(that1.CustomType) { return fmt.Errorf("CustomType this(%v) Not Equal that(%v)", this.CustomType, that1.CustomType) } return nil } func (this *CustomOneof_CastType) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_CastType) if !ok { that2, ok := that.(CustomOneof_CastType) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_CastType") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_CastType but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_CastType but is not nil && this == nil") } if this.CastType != that1.CastType { return fmt.Errorf("CastType this(%v) Not Equal that(%v)", this.CastType, that1.CastType) } return nil } func (this *CustomOneof_MyCustomName) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*CustomOneof_MyCustomName) if !ok { that2, ok := that.(CustomOneof_MyCustomName) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *CustomOneof_MyCustomName") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *CustomOneof_MyCustomName but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *CustomOneof_MyCustomName but is not nil && this == nil") } if this.MyCustomName != that1.MyCustomName { return fmt.Errorf("MyCustomName this(%v) Not Equal that(%v)", this.MyCustomName, that1.MyCustomName) } return nil } func (this *CustomOneof) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*CustomOneof) if !ok { that2, ok := that.(CustomOneof) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.Custom == nil { if this.Custom != nil { return false } } else if this.Custom == nil { return false } else if !this.Custom.Equal(that1.Custom) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *CustomOneof_Stringy) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*CustomOneof_Stringy) if !ok { that2, ok := that.(CustomOneof_Stringy) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Stringy != that1.Stringy { return false } return true } func (this *CustomOneof_CustomType) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*CustomOneof_CustomType) if !ok { that2, ok := that.(CustomOneof_CustomType) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.CustomType.Equal(that1.CustomType) { return false } return true } func (this *CustomOneof_CastType) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*CustomOneof_CastType) if !ok { that2, ok := that.(CustomOneof_CastType) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.CastType != that1.CastType { return false } return true } func (this *CustomOneof_MyCustomName) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*CustomOneof_MyCustomName) if !ok { that2, ok := that.(CustomOneof_MyCustomName) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.MyCustomName != that1.MyCustomName { return false } return true } func (this *Subby) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&one.Subby{") if this.Sub != nil { s = append(s, "Sub: "+valueToGoStringOne(this.Sub, "string")+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *AllTypesOneOf) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 20) s = append(s, "&one.AllTypesOneOf{") if this.TestOneof != nil { s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *AllTypesOneOf_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field4) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field4{` + `Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field5) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field5{` + `Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field6) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field6{` + `Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field7) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field7{` + `Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field8) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field8{` + `Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field9) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field9{` + `Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field10) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field10{` + `Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field11) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field11{` + `Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field12) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field12{` + `Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field13) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field13{` + `Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field14) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field14{` + `Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ") return s } func (this *AllTypesOneOf_Field15) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_Field15{` + `Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ") return s } func (this *AllTypesOneOf_SubMessage) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.AllTypesOneOf_SubMessage{` + `SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ") return s } func (this *TwoOneofs) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 10) s = append(s, "&one.TwoOneofs{") if this.One != nil { s = append(s, "One: "+fmt.Sprintf("%#v", this.One)+",\n") } if this.Two != nil { s = append(s, "Two: "+fmt.Sprintf("%#v", this.Two)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *TwoOneofs_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *TwoOneofs_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *TwoOneofs_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *TwoOneofs_Field34) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field34{` + `Field34:` + fmt.Sprintf("%#v", this.Field34) + `}`}, ", ") return s } func (this *TwoOneofs_Field35) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_Field35{` + `Field35:` + fmt.Sprintf("%#v", this.Field35) + `}`}, ", ") return s } func (this *TwoOneofs_SubMessage2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.TwoOneofs_SubMessage2{` + `SubMessage2:` + fmt.Sprintf("%#v", this.SubMessage2) + `}`}, ", ") return s } func (this *CustomOneof) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 8) s = append(s, "&one.CustomOneof{") if this.Custom != nil { s = append(s, "Custom: "+fmt.Sprintf("%#v", this.Custom)+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *CustomOneof_Stringy) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_Stringy{` + `Stringy:` + fmt.Sprintf("%#v", this.Stringy) + `}`}, ", ") return s } func (this *CustomOneof_CustomType) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_CustomType{` + `CustomType:` + fmt.Sprintf("%#v", this.CustomType) + `}`}, ", ") return s } func (this *CustomOneof_CastType) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_CastType{` + `CastType:` + fmt.Sprintf("%#v", this.CastType) + `}`}, ", ") return s } func (this *CustomOneof_MyCustomName) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.CustomOneof_MyCustomName{` + `MyCustomName:` + fmt.Sprintf("%#v", this.MyCustomName) + `}`}, ", ") return s } func valueToGoStringOne(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func NewPopulatedSubby(r randyOne, easy bool) *Subby { this := &Subby{} if r.Intn(10) != 0 { v1 := string(randStringOne(r)) this.Sub = &v1 } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 2) } return this } func NewPopulatedAllTypesOneOf(r randyOne, easy bool) *AllTypesOneOf { this := &AllTypesOneOf{} oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)] switch oneofNumber_TestOneof { case 1: this.TestOneof = NewPopulatedAllTypesOneOf_Field1(r, easy) case 2: this.TestOneof = NewPopulatedAllTypesOneOf_Field2(r, easy) case 3: this.TestOneof = NewPopulatedAllTypesOneOf_Field3(r, easy) case 4: this.TestOneof = NewPopulatedAllTypesOneOf_Field4(r, easy) case 5: this.TestOneof = NewPopulatedAllTypesOneOf_Field5(r, easy) case 6: this.TestOneof = NewPopulatedAllTypesOneOf_Field6(r, easy) case 7: this.TestOneof = NewPopulatedAllTypesOneOf_Field7(r, easy) case 8: this.TestOneof = NewPopulatedAllTypesOneOf_Field8(r, easy) case 9: this.TestOneof = NewPopulatedAllTypesOneOf_Field9(r, easy) case 10: this.TestOneof = NewPopulatedAllTypesOneOf_Field10(r, easy) case 11: this.TestOneof = NewPopulatedAllTypesOneOf_Field11(r, easy) case 12: this.TestOneof = NewPopulatedAllTypesOneOf_Field12(r, easy) case 13: this.TestOneof = NewPopulatedAllTypesOneOf_Field13(r, easy) case 14: this.TestOneof = NewPopulatedAllTypesOneOf_Field14(r, easy) case 15: this.TestOneof = NewPopulatedAllTypesOneOf_Field15(r, easy) case 16: this.TestOneof = NewPopulatedAllTypesOneOf_SubMessage(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 17) } return this } func NewPopulatedAllTypesOneOf_Field1(r randyOne, easy bool) *AllTypesOneOf_Field1 { this := &AllTypesOneOf_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field2(r randyOne, easy bool) *AllTypesOneOf_Field2 { this := &AllTypesOneOf_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field3(r randyOne, easy bool) *AllTypesOneOf_Field3 { this := &AllTypesOneOf_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field4(r randyOne, easy bool) *AllTypesOneOf_Field4 { this := &AllTypesOneOf_Field4{} this.Field4 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field4 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field5(r randyOne, easy bool) *AllTypesOneOf_Field5 { this := &AllTypesOneOf_Field5{} this.Field5 = uint32(r.Uint32()) return this } func NewPopulatedAllTypesOneOf_Field6(r randyOne, easy bool) *AllTypesOneOf_Field6 { this := &AllTypesOneOf_Field6{} this.Field6 = uint64(uint64(r.Uint32())) return this } func NewPopulatedAllTypesOneOf_Field7(r randyOne, easy bool) *AllTypesOneOf_Field7 { this := &AllTypesOneOf_Field7{} this.Field7 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field7 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field8(r randyOne, easy bool) *AllTypesOneOf_Field8 { this := &AllTypesOneOf_Field8{} this.Field8 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field8 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field9(r randyOne, easy bool) *AllTypesOneOf_Field9 { this := &AllTypesOneOf_Field9{} this.Field9 = uint32(r.Uint32()) return this } func NewPopulatedAllTypesOneOf_Field10(r randyOne, easy bool) *AllTypesOneOf_Field10 { this := &AllTypesOneOf_Field10{} this.Field10 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field10 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field11(r randyOne, easy bool) *AllTypesOneOf_Field11 { this := &AllTypesOneOf_Field11{} this.Field11 = uint64(uint64(r.Uint32())) return this } func NewPopulatedAllTypesOneOf_Field12(r randyOne, easy bool) *AllTypesOneOf_Field12 { this := &AllTypesOneOf_Field12{} this.Field12 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field12 *= -1 } return this } func NewPopulatedAllTypesOneOf_Field13(r randyOne, easy bool) *AllTypesOneOf_Field13 { this := &AllTypesOneOf_Field13{} this.Field13 = bool(bool(r.Intn(2) == 0)) return this } func NewPopulatedAllTypesOneOf_Field14(r randyOne, easy bool) *AllTypesOneOf_Field14 { this := &AllTypesOneOf_Field14{} this.Field14 = string(randStringOne(r)) return this } func NewPopulatedAllTypesOneOf_Field15(r randyOne, easy bool) *AllTypesOneOf_Field15 { this := &AllTypesOneOf_Field15{} v2 := r.Intn(100) this.Field15 = make([]byte, v2) for i := 0; i < v2; i++ { this.Field15[i] = byte(r.Intn(256)) } return this } func NewPopulatedAllTypesOneOf_SubMessage(r randyOne, easy bool) *AllTypesOneOf_SubMessage { this := &AllTypesOneOf_SubMessage{} this.SubMessage = NewPopulatedSubby(r, easy) return this } func NewPopulatedTwoOneofs(r randyOne, easy bool) *TwoOneofs { this := &TwoOneofs{} oneofNumber_One := []int32{1, 2, 3}[r.Intn(3)] switch oneofNumber_One { case 1: this.One = NewPopulatedTwoOneofs_Field1(r, easy) case 2: this.One = NewPopulatedTwoOneofs_Field2(r, easy) case 3: this.One = NewPopulatedTwoOneofs_Field3(r, easy) } oneofNumber_Two := []int32{34, 35, 36}[r.Intn(3)] switch oneofNumber_Two { case 34: this.Two = NewPopulatedTwoOneofs_Field34(r, easy) case 35: this.Two = NewPopulatedTwoOneofs_Field35(r, easy) case 36: this.Two = NewPopulatedTwoOneofs_SubMessage2(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 37) } return this } func NewPopulatedTwoOneofs_Field1(r randyOne, easy bool) *TwoOneofs_Field1 { this := &TwoOneofs_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedTwoOneofs_Field2(r randyOne, easy bool) *TwoOneofs_Field2 { this := &TwoOneofs_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedTwoOneofs_Field3(r randyOne, easy bool) *TwoOneofs_Field3 { this := &TwoOneofs_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedTwoOneofs_Field34(r randyOne, easy bool) *TwoOneofs_Field34 { this := &TwoOneofs_Field34{} this.Field34 = string(randStringOne(r)) return this } func NewPopulatedTwoOneofs_Field35(r randyOne, easy bool) *TwoOneofs_Field35 { this := &TwoOneofs_Field35{} v3 := r.Intn(100) this.Field35 = make([]byte, v3) for i := 0; i < v3; i++ { this.Field35[i] = byte(r.Intn(256)) } return this } func NewPopulatedTwoOneofs_SubMessage2(r randyOne, easy bool) *TwoOneofs_SubMessage2 { this := &TwoOneofs_SubMessage2{} this.SubMessage2 = NewPopulatedSubby(r, easy) return this } func NewPopulatedCustomOneof(r randyOne, easy bool) *CustomOneof { this := &CustomOneof{} oneofNumber_Custom := []int32{34, 35, 36, 37}[r.Intn(4)] switch oneofNumber_Custom { case 34: this.Custom = NewPopulatedCustomOneof_Stringy(r, easy) case 35: this.Custom = NewPopulatedCustomOneof_CustomType(r, easy) case 36: this.Custom = NewPopulatedCustomOneof_CastType(r, easy) case 37: this.Custom = NewPopulatedCustomOneof_MyCustomName(r, easy) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedOne(r, 38) } return this } func NewPopulatedCustomOneof_Stringy(r randyOne, easy bool) *CustomOneof_Stringy { this := &CustomOneof_Stringy{} this.Stringy = string(randStringOne(r)) return this } func NewPopulatedCustomOneof_CustomType(r randyOne, easy bool) *CustomOneof_CustomType { this := &CustomOneof_CustomType{} v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r) this.CustomType = *v4 return this } func NewPopulatedCustomOneof_CastType(r randyOne, easy bool) *CustomOneof_CastType { this := &CustomOneof_CastType{} this.CastType = github_com_gogo_protobuf_test_casttype.MyUint64Type(uint64(r.Uint32())) return this } func NewPopulatedCustomOneof_MyCustomName(r randyOne, easy bool) *CustomOneof_MyCustomName { this := &CustomOneof_MyCustomName{} this.MyCustomName = int64(r.Int63()) if r.Intn(2) == 0 { this.MyCustomName *= -1 } return this } type randyOne interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneOne(r randyOne) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringOne(r randyOne) string { v5 := r.Intn(100) tmps := make([]rune, v5) for i := 0; i < v5; i++ { tmps[i] = randUTF8RuneOne(r) } return string(tmps) } func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldOne(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) v6 := r.Int63() if r.Intn(2) == 0 { v6 *= -1 } dAtA = encodeVarintPopulateOne(dAtA, uint64(v6)) case 1: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateOne(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *Subby) Size() (n int) { var l int _ = l if m.Sub != nil { l = len(*m.Sub) n += 1 + l + sovOne(uint64(l)) } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *AllTypesOneOf) Size() (n int) { var l int _ = l if m.TestOneof != nil { n += m.TestOneof.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *AllTypesOneOf_Field1) Size() (n int) { var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field2) Size() (n int) { var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field3) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *AllTypesOneOf_Field4) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field4)) return n } func (m *AllTypesOneOf_Field5) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field5)) return n } func (m *AllTypesOneOf_Field6) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field6)) return n } func (m *AllTypesOneOf_Field7) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field7)) return n } func (m *AllTypesOneOf_Field8) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field8)) return n } func (m *AllTypesOneOf_Field9) Size() (n int) { var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field10) Size() (n int) { var l int _ = l n += 5 return n } func (m *AllTypesOneOf_Field11) Size() (n int) { var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field12) Size() (n int) { var l int _ = l n += 9 return n } func (m *AllTypesOneOf_Field13) Size() (n int) { var l int _ = l n += 2 return n } func (m *AllTypesOneOf_Field14) Size() (n int) { var l int _ = l l = len(m.Field14) n += 1 + l + sovOne(uint64(l)) return n } func (m *AllTypesOneOf_Field15) Size() (n int) { var l int _ = l if m.Field15 != nil { l = len(m.Field15) n += 1 + l + sovOne(uint64(l)) } return n } func (m *AllTypesOneOf_SubMessage) Size() (n int) { var l int _ = l if m.SubMessage != nil { l = m.SubMessage.Size() n += 2 + l + sovOne(uint64(l)) } return n } func (m *TwoOneofs) Size() (n int) { var l int _ = l if m.One != nil { n += m.One.Size() } if m.Two != nil { n += m.Two.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *TwoOneofs_Field1) Size() (n int) { var l int _ = l n += 9 return n } func (m *TwoOneofs_Field2) Size() (n int) { var l int _ = l n += 5 return n } func (m *TwoOneofs_Field3) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *TwoOneofs_Field34) Size() (n int) { var l int _ = l l = len(m.Field34) n += 2 + l + sovOne(uint64(l)) return n } func (m *TwoOneofs_Field35) Size() (n int) { var l int _ = l if m.Field35 != nil { l = len(m.Field35) n += 2 + l + sovOne(uint64(l)) } return n } func (m *TwoOneofs_SubMessage2) Size() (n int) { var l int _ = l if m.SubMessage2 != nil { l = m.SubMessage2.Size() n += 2 + l + sovOne(uint64(l)) } return n } func (m *CustomOneof) Size() (n int) { var l int _ = l if m.Custom != nil { n += m.Custom.Size() } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func (m *CustomOneof_Stringy) Size() (n int) { var l int _ = l l = len(m.Stringy) n += 2 + l + sovOne(uint64(l)) return n } func (m *CustomOneof_CustomType) Size() (n int) { var l int _ = l l = m.CustomType.Size() n += 2 + l + sovOne(uint64(l)) return n } func (m *CustomOneof_CastType) Size() (n int) { var l int _ = l n += 2 + sovOne(uint64(m.CastType)) return n } func (m *CustomOneof_MyCustomName) Size() (n int) { var l int _ = l n += 2 + sovOne(uint64(m.MyCustomName)) return n } func sovOne(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozOne(x uint64) (n int) { return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *Subby) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Subby{`, `Sub:` + valueToStringOne(this.Sub) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf{`, `TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field4) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field4{`, `Field4:` + fmt.Sprintf("%v", this.Field4) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field5) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field5{`, `Field5:` + fmt.Sprintf("%v", this.Field5) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field6) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field6{`, `Field6:` + fmt.Sprintf("%v", this.Field6) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field7) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field7{`, `Field7:` + fmt.Sprintf("%v", this.Field7) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field8) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field8{`, `Field8:` + fmt.Sprintf("%v", this.Field8) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field9) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field9{`, `Field9:` + fmt.Sprintf("%v", this.Field9) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field10) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field10{`, `Field10:` + fmt.Sprintf("%v", this.Field10) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field11) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field11{`, `Field11:` + fmt.Sprintf("%v", this.Field11) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field12) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field12{`, `Field12:` + fmt.Sprintf("%v", this.Field12) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field13) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field13{`, `Field13:` + fmt.Sprintf("%v", this.Field13) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field14) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field14{`, `Field14:` + fmt.Sprintf("%v", this.Field14) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_Field15) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_Field15{`, `Field15:` + fmt.Sprintf("%v", this.Field15) + `,`, `}`, }, "") return s } func (this *AllTypesOneOf_SubMessage) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AllTypesOneOf_SubMessage{`, `SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`, `}`, }, "") return s } func (this *TwoOneofs) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs{`, `One:` + fmt.Sprintf("%v", this.One) + `,`, `Two:` + fmt.Sprintf("%v", this.Two) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field34) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field34{`, `Field34:` + fmt.Sprintf("%v", this.Field34) + `,`, `}`, }, "") return s } func (this *TwoOneofs_Field35) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_Field35{`, `Field35:` + fmt.Sprintf("%v", this.Field35) + `,`, `}`, }, "") return s } func (this *TwoOneofs_SubMessage2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TwoOneofs_SubMessage2{`, `SubMessage2:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage2), "Subby", "Subby", 1) + `,`, `}`, }, "") return s } func (this *CustomOneof) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&CustomOneof{`, `Custom:` + fmt.Sprintf("%v", this.Custom) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func (this *CustomOneof_Stringy) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&CustomOneof_Stringy{`, `Stringy:` + fmt.Sprintf("%v", this.Stringy) + `,`, `}`, }, "") return s } func (this *CustomOneof_CustomType) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&CustomOneof_CustomType{`, `CustomType:` + fmt.Sprintf("%v", this.CustomType) + `,`, `}`, }, "") return s } func (this *CustomOneof_CastType) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&CustomOneof_CastType{`, `CastType:` + fmt.Sprintf("%v", this.CastType) + `,`, `}`, }, "") return s } func (this *CustomOneof_MyCustomName) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&CustomOneof_MyCustomName{`, `MyCustomName:` + fmt.Sprintf("%v", this.MyCustomName) + `,`, `}`, }, "") return s } func valueToStringOne(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *Subby) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Subby) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.Sub != nil { dAtA[i] = 0xa i++ i = encodeVarintOne(dAtA, i, uint64(len(*m.Sub))) i += copy(dAtA[i:], *m.Sub) } if m.XXX_unrecognized != nil { i += copy(dAtA[i:], m.XXX_unrecognized) } return i, nil } func (m *AllTypesOneOf) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *AllTypesOneOf) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.TestOneof != nil { nn1, err := m.TestOneof.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn1 } if m.XXX_unrecognized != nil { i += copy(dAtA[i:], m.XXX_unrecognized) } return i, nil } func (m *AllTypesOneOf_Field1) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x9 i++ *(*float64)(unsafe.Pointer(&dAtA[i])) = m.Field1 i += 8 return i, nil } func (m *AllTypesOneOf_Field2) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x15 i++ *(*float32)(unsafe.Pointer(&dAtA[i])) = m.Field2 i += 4 return i, nil } func (m *AllTypesOneOf_Field3) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x18 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field3)) return i, nil } func (m *AllTypesOneOf_Field4) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x20 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field4)) return i, nil } func (m *AllTypesOneOf_Field5) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x28 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field5)) return i, nil } func (m *AllTypesOneOf_Field6) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x30 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field6)) return i, nil } func (m *AllTypesOneOf_Field7) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x38 i++ i = encodeVarintOne(dAtA, i, uint64((uint32(m.Field7)<<1)^uint32((m.Field7>>31)))) return i, nil } func (m *AllTypesOneOf_Field8) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x40 i++ i = encodeVarintOne(dAtA, i, uint64((uint64(m.Field8)<<1)^uint64((m.Field8>>63)))) return i, nil } func (m *AllTypesOneOf_Field9) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x4d i++ *(*uint32)(unsafe.Pointer(&dAtA[i])) = m.Field9 i += 4 return i, nil } func (m *AllTypesOneOf_Field10) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x55 i++ *(*int32)(unsafe.Pointer(&dAtA[i])) = m.Field10 i += 4 return i, nil } func (m *AllTypesOneOf_Field11) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x59 i++ *(*uint64)(unsafe.Pointer(&dAtA[i])) = m.Field11 i += 8 return i, nil } func (m *AllTypesOneOf_Field12) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x61 i++ *(*int64)(unsafe.Pointer(&dAtA[i])) = m.Field12 i += 8 return i, nil } func (m *AllTypesOneOf_Field13) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x68 i++ if m.Field13 { dAtA[i] = 1 } else { dAtA[i] = 0 } i++ return i, nil } func (m *AllTypesOneOf_Field14) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x72 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field14))) i += copy(dAtA[i:], m.Field14) return i, nil } func (m *AllTypesOneOf_Field15) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.Field15 != nil { dAtA[i] = 0x7a i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field15))) i += copy(dAtA[i:], m.Field15) } return i, nil } func (m *AllTypesOneOf_SubMessage) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.SubMessage != nil { dAtA[i] = 0x82 i++ dAtA[i] = 0x1 i++ i = encodeVarintOne(dAtA, i, uint64(m.SubMessage.Size())) n2, err := m.SubMessage.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 } return i, nil } func (m *TwoOneofs) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *TwoOneofs) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.One != nil { nn3, err := m.One.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn3 } if m.Two != nil { nn4, err := m.Two.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn4 } if m.XXX_unrecognized != nil { i += copy(dAtA[i:], m.XXX_unrecognized) } return i, nil } func (m *TwoOneofs_Field1) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x9 i++ *(*float64)(unsafe.Pointer(&dAtA[i])) = m.Field1 i += 8 return i, nil } func (m *TwoOneofs_Field2) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x15 i++ *(*float32)(unsafe.Pointer(&dAtA[i])) = m.Field2 i += 4 return i, nil } func (m *TwoOneofs_Field3) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x18 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field3)) return i, nil } func (m *TwoOneofs_Field34) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x92 i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field34))) i += copy(dAtA[i:], m.Field34) return i, nil } func (m *TwoOneofs_Field35) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.Field35 != nil { dAtA[i] = 0x9a i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field35))) i += copy(dAtA[i:], m.Field35) } return i, nil } func (m *TwoOneofs_SubMessage2) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.SubMessage2 != nil { dAtA[i] = 0xa2 i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(m.SubMessage2.Size())) n5, err := m.SubMessage2.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n5 } return i, nil } func (m *CustomOneof) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *CustomOneof) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.Custom != nil { nn6, err := m.Custom.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn6 } if m.XXX_unrecognized != nil { i += copy(dAtA[i:], m.XXX_unrecognized) } return i, nil } func (m *CustomOneof_Stringy) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x92 i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Stringy))) i += copy(dAtA[i:], m.Stringy) return i, nil } func (m *CustomOneof_CustomType) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x9a i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(m.CustomType.Size())) n7, err := m.CustomType.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n7 return i, nil } func (m *CustomOneof_CastType) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0xa0 i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(m.CastType)) return i, nil } func (m *CustomOneof_MyCustomName) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0xa8 i++ dAtA[i] = 0x2 i++ i = encodeVarintOne(dAtA, i, uint64(m.MyCustomName)) return i, nil } func encodeFixed64One(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) dAtA[offset+4] = uint8(v >> 32) dAtA[offset+5] = uint8(v >> 40) dAtA[offset+6] = uint8(v >> 48) dAtA[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32One(dAtA []byte, offset int, v uint32) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintOne(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func (m *Subby) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Subby: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) m.Sub = &s iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOneUnsafe(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOneUnsafe } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *AllTypesOneOf) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: AllTypesOneOf: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: AllTypesOneOf: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var v float64 if iNdEx+8 > l { return io.ErrUnexpectedEOF } v = *(*float64)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 8 m.TestOneof = &AllTypesOneOf_Field1{v} case 2: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType) } var v float32 if iNdEx+4 > l { return io.ErrUnexpectedEOF } v = *(*float32)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 4 m.TestOneof = &AllTypesOneOf_Field2{v} case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &AllTypesOneOf_Field3{v} case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field4", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &AllTypesOneOf_Field4{v} case 5: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field5", wireType) } var v uint32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &AllTypesOneOf_Field5{v} case 6: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field6", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &AllTypesOneOf_Field6{v} case 7: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field7", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } v = int32((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31)) m.TestOneof = &AllTypesOneOf_Field7{v} case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field8", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63) m.TestOneof = &AllTypesOneOf_Field8{int64(v)} case 9: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field9", wireType) } var v uint32 if iNdEx+4 > l { return io.ErrUnexpectedEOF } v = *(*uint32)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 4 m.TestOneof = &AllTypesOneOf_Field9{v} case 10: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field10", wireType) } var v int32 if iNdEx+4 > l { return io.ErrUnexpectedEOF } v = *(*int32)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 4 m.TestOneof = &AllTypesOneOf_Field10{v} case 11: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field11", wireType) } var v uint64 if iNdEx+8 > l { return io.ErrUnexpectedEOF } v = *(*uint64)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 8 m.TestOneof = &AllTypesOneOf_Field11{v} case 12: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field12", wireType) } var v int64 if iNdEx+8 > l { return io.ErrUnexpectedEOF } v = *(*int64)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 8 m.TestOneof = &AllTypesOneOf_Field12{v} case 13: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field13", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int(b) & 0x7F) << shift if b < 0x80 { break } } b := bool(v != 0) m.TestOneof = &AllTypesOneOf_Field13{b} case 14: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field14", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.TestOneof = &AllTypesOneOf_Field14{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field15", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } v := make([]byte, postIndex-iNdEx) copy(v, dAtA[iNdEx:postIndex]) m.TestOneof = &AllTypesOneOf_Field15{v} iNdEx = postIndex case 16: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SubMessage", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } v := &Subby{} if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } m.TestOneof = &AllTypesOneOf_SubMessage{v} iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOneUnsafe(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOneUnsafe } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *TwoOneofs) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TwoOneofs: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TwoOneofs: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var v float64 if iNdEx+8 > l { return io.ErrUnexpectedEOF } v = *(*float64)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 8 m.One = &TwoOneofs_Field1{v} case 2: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType) } var v float32 if iNdEx+4 > l { return io.ErrUnexpectedEOF } v = *(*float32)(unsafe.Pointer(&dAtA[iNdEx])) iNdEx += 4 m.One = &TwoOneofs_Field2{v} case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } m.One = &TwoOneofs_Field3{v} case 34: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field34", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Two = &TwoOneofs_Field34{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex case 35: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field35", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } v := make([]byte, postIndex-iNdEx) copy(v, dAtA[iNdEx:postIndex]) m.Two = &TwoOneofs_Field35{v} iNdEx = postIndex case 36: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SubMessage2", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } v := &Subby{} if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } m.Two = &TwoOneofs_SubMessage2{v} iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOneUnsafe(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOneUnsafe } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *CustomOneof) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: CustomOneof: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CustomOneof: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 34: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Stringy", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Custom = &CustomOneof_Stringy{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex case 35: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CustomType", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthOneUnsafe } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } var vv github_com_gogo_protobuf_test_custom.Uint128 v := &vv if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } m.Custom = &CustomOneof_CustomType{*v} iNdEx = postIndex case 36: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field CastType", wireType) } var v github_com_gogo_protobuf_test_casttype.MyUint64Type for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (github_com_gogo_protobuf_test_casttype.MyUint64Type(b) & 0x7F) << shift if b < 0x80 { break } } m.Custom = &CustomOneof_CastType{v} case 37: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field MyCustomName", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOneUnsafe } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int64(b) & 0x7F) << shift if b < 0x80 { break } } m.Custom = &CustomOneof_MyCustomName{v} default: iNdEx = preIndex skippy, err := skipOneUnsafe(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOneUnsafe } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipOneUnsafe(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOneUnsafe } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOneUnsafe } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOneUnsafe } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthOneUnsafe } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOneUnsafe } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipOneUnsafe(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthOneUnsafe = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowOneUnsafe = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("combos/unsafeboth/one.proto", fileDescriptorOne) } var fileDescriptorOne = []byte{ // 600 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd3, 0x3f, 0x4f, 0xdb, 0x40, 0x14, 0x00, 0x70, 0x3f, 0x42, 0x42, 0xb8, 0x84, 0x92, 0x7a, 0xba, 0x52, 0xe9, 0x38, 0xa5, 0xad, 0x74, 0x43, 0x49, 0x88, 0x93, 0xf0, 0x67, 0xac, 0xa9, 0xaa, 0x2c, 0x14, 0xc9, 0xc0, 0x8c, 0x62, 0x7a, 0x09, 0x91, 0x88, 0x0f, 0x71, 0x67, 0x21, 0x6f, 0x7c, 0x86, 0x7e, 0x8a, 0x8e, 0x1d, 0xfb, 0x11, 0x18, 0x19, 0xab, 0x0e, 0x11, 0x76, 0x97, 0x8e, 0x8c, 0xa8, 0x53, 0x75, 0x36, 0xb9, 0xab, 0x54, 0x55, 0x5d, 0x3a, 0xc5, 0xef, 0xfd, 0x7c, 0x2f, 0xef, 0xf9, 0xee, 0xd0, 0xf3, 0x53, 0x31, 0x0d, 0x85, 0x6c, 0xc7, 0x91, 0x1c, 0x8e, 0x78, 0x28, 0xd4, 0x59, 0x5b, 0x44, 0xbc, 0x75, 0x71, 0x29, 0x94, 0x70, 0x4b, 0x22, 0xe2, 0x6b, 0x1b, 0xe3, 0x89, 0x3a, 0x8b, 0xc3, 0xd6, 0xa9, 0x98, 0xb6, 0xc7, 0x62, 0x2c, 0xda, 0xb9, 0x85, 0xf1, 0x28, 0x8f, 0xf2, 0x20, 0x7f, 0x2a, 0xd6, 0x34, 0x9f, 0xa1, 0xf2, 0x61, 0x1c, 0x86, 0x89, 0xdb, 0x40, 0x25, 0x19, 0x87, 0x18, 0x28, 0xb0, 0xe5, 0x40, 0x3f, 0x36, 0x67, 0x25, 0xb4, 0xf2, 0xe6, 0xfc, 0xfc, 0x28, 0xb9, 0xe0, 0xf2, 0x20, 0xe2, 0x07, 0x23, 0x17, 0xa3, 0xca, 0xbb, 0x09, 0x3f, 0xff, 0xd0, 0xc9, 0x5f, 0x83, 0x81, 0x13, 0x3c, 0xc6, 0x46, 0x3c, 0xbc, 0x40, 0x81, 0x2d, 0x18, 0xf1, 0x8c, 0x74, 0x71, 0x89, 0x02, 0x2b, 0x1b, 0xe9, 0x1a, 0xe9, 0xe1, 0x45, 0x0a, 0xac, 0x64, 0xa4, 0x67, 0xa4, 0x8f, 0xcb, 0x14, 0xd8, 0x8a, 0x91, 0xbe, 0x91, 0x2d, 0x5c, 0xa1, 0xc0, 0x16, 0x8d, 0x6c, 0x19, 0xd9, 0xc6, 0x4b, 0x14, 0xd8, 0x53, 0x23, 0xdb, 0x46, 0x76, 0x70, 0x95, 0x02, 0x73, 0x8d, 0xec, 0x18, 0xd9, 0xc5, 0xcb, 0x14, 0xd8, 0x92, 0x91, 0x5d, 0x77, 0x0d, 0x2d, 0x15, 0x93, 0x6d, 0x62, 0x44, 0x81, 0xad, 0x0e, 0x9c, 0x60, 0x9e, 0xb0, 0xd6, 0xc1, 0x35, 0x0a, 0xac, 0x62, 0xad, 0x63, 0xcd, 0xc3, 0x75, 0x0a, 0xac, 0x61, 0xcd, 0xb3, 0xd6, 0xc5, 0x2b, 0x14, 0x58, 0xd5, 0x5a, 0xd7, 0x5a, 0x0f, 0x3f, 0xd1, 0x3b, 0x60, 0xad, 0x67, 0xad, 0x8f, 0x57, 0x29, 0xb0, 0xba, 0xb5, 0xbe, 0xbb, 0x81, 0x6a, 0x32, 0x0e, 0x4f, 0xa6, 0x5c, 0xca, 0xe1, 0x98, 0xe3, 0x06, 0x05, 0x56, 0xf3, 0x50, 0x4b, 0x9f, 0x89, 0x7c, 0x5b, 0x07, 0x4e, 0x80, 0x64, 0x1c, 0xee, 0x17, 0xee, 0xd7, 0x11, 0x52, 0x5c, 0xaa, 0x13, 0x11, 0x71, 0x31, 0x6a, 0xde, 0x02, 0x5a, 0x3e, 0xba, 0x12, 0x07, 0x3a, 0x90, 0xff, 0x79, 0x73, 0xe7, 0x4d, 0x77, 0x7b, 0xb8, 0x99, 0x0f, 0x04, 0xc1, 0x3c, 0x61, 0xad, 0x8f, 0x5f, 0xe4, 0x03, 0x19, 0xeb, 0xbb, 0x6d, 0x54, 0xff, 0x6d, 0x20, 0x0f, 0xbf, 0xfc, 0x63, 0x22, 0x08, 0x6a, 0x76, 0x22, 0xcf, 0x2f, 0x23, 0x7d, 0xec, 0xf5, 0x8f, 0xba, 0x12, 0xcd, 0x8f, 0x0b, 0xa8, 0xb6, 0x17, 0x4b, 0x25, 0xa6, 0xf9, 0x54, 0xfa, 0xaf, 0x0e, 0xd5, 0xe5, 0x24, 0x1a, 0x27, 0x8f, 0x6d, 0x38, 0xc1, 0x3c, 0xe1, 0x06, 0x08, 0x15, 0xaf, 0xea, 0x13, 0x5e, 0x74, 0xe2, 0x6f, 0x7e, 0x9b, 0xad, 0xbf, 0xfe, 0xeb, 0x0d, 0xd2, 0xdf, 0xae, 0x7d, 0x9a, 0xaf, 0x69, 0x1d, 0x4f, 0x22, 0xd5, 0xf1, 0x76, 0xf4, 0x07, 0xb6, 0x55, 0xdc, 0x63, 0x54, 0xdd, 0x1b, 0x4a, 0x95, 0x57, 0xd4, 0xad, 0x2f, 0xfa, 0xdb, 0x3f, 0x67, 0xeb, 0xdd, 0x7f, 0x54, 0x1c, 0x4a, 0xa5, 0x92, 0x0b, 0xde, 0xda, 0x4f, 0x74, 0xd5, 0xad, 0x9e, 0x5e, 0x3e, 0x70, 0x02, 0x53, 0xca, 0xf5, 0xe6, 0xad, 0xbe, 0x1f, 0x4e, 0x39, 0x7e, 0xa5, 0xaf, 0x8b, 0xdf, 0xc8, 0x66, 0xeb, 0xf5, 0xfd, 0xc4, 0xe6, 0x6d, 0x2b, 0x3a, 0xf2, 0xab, 0xa8, 0x52, 0xb4, 0xea, 0xbf, 0xbd, 0x49, 0x89, 0x73, 0x9b, 0x12, 0xe7, 0x6b, 0x4a, 0x9c, 0xbb, 0x94, 0xc0, 0x7d, 0x4a, 0xe0, 0x21, 0x25, 0x70, 0x9d, 0x11, 0xf8, 0x94, 0x11, 0xf8, 0x9c, 0x11, 0xf8, 0x92, 0x11, 0xb8, 0xc9, 0x88, 0x73, 0x9b, 0x11, 0xe7, 0x2e, 0x23, 0xf0, 0x23, 0x23, 0xce, 0x7d, 0x46, 0xe0, 0x21, 0x23, 0x70, 0xfd, 0x9d, 0xc0, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa5, 0xf3, 0xa9, 0x7e, 0x7b, 0x04, 0x00, 0x00, }
kadel/kedge
vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/gogo/protobuf/test/oneof/combos/unsafeboth/one.pb.go
GO
apache-2.0
156,343
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_RENDERSTATES_HPP #define SFML_RENDERSTATES_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics/Export.hpp> #include <SFML/Graphics/BlendMode.hpp> #include <SFML/Graphics/Transform.hpp> namespace sf { class Shader; class Texture; //////////////////////////////////////////////////////////// /// \brief Define the states used for drawing to a RenderTarget /// //////////////////////////////////////////////////////////// class SFML_GRAPHICS_API RenderStates { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// /// Constructing a default set of render states is equivalent /// to using sf::RenderStates::Default. /// The default set defines: /// \li the BlendAlpha blend mode /// \li the identity transform /// \li a null texture /// \li a null shader /// //////////////////////////////////////////////////////////// RenderStates(); //////////////////////////////////////////////////////////// /// \brief Construct a default set of render states with a custom blend mode /// /// \param theBlendMode Blend mode to use /// //////////////////////////////////////////////////////////// RenderStates(const BlendMode& theBlendMode); //////////////////////////////////////////////////////////// /// \brief Construct a default set of render states with a custom transform /// /// \param theTransform Transform to use /// //////////////////////////////////////////////////////////// RenderStates(const Transform& theTransform); //////////////////////////////////////////////////////////// /// \brief Construct a default set of render states with a custom texture /// /// \param theTexture Texture to use /// //////////////////////////////////////////////////////////// RenderStates(const Texture* theTexture); //////////////////////////////////////////////////////////// /// \brief Construct a default set of render states with a custom shader /// /// \param theShader Shader to use /// //////////////////////////////////////////////////////////// RenderStates(const Shader* theShader); //////////////////////////////////////////////////////////// /// \brief Construct a set of render states with all its attributes /// /// \param theBlendMode Blend mode to use /// \param theTransform Transform to use /// \param theTexture Texture to use /// \param theShader Shader to use /// //////////////////////////////////////////////////////////// RenderStates(const BlendMode& theBlendMode, const Transform& theTransform, const Texture* theTexture, const Shader* theShader); //////////////////////////////////////////////////////////// // Static member data //////////////////////////////////////////////////////////// static const RenderStates Default; ///< Special instance holding the default render states //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// BlendMode blendMode; ///< Blending mode Transform transform; ///< Transform const Texture* texture; ///< Texture const Shader* shader; ///< Shader }; } // namespace sf #endif // SFML_RENDERSTATES_HPP //////////////////////////////////////////////////////////// /// \class sf::RenderStates /// \ingroup graphics /// /// There are four global states that can be applied to /// the drawn objects: /// \li the blend mode: how pixels of the object are blended with the background /// \li the transform: how the object is positioned/rotated/scaled /// \li the texture: what image is mapped to the object /// \li the shader: what custom effect is applied to the object /// /// High-level objects such as sprites or text force some of /// these states when they are drawn. For example, a sprite /// will set its own texture, so that you don't have to care /// about it when drawing the sprite. /// /// The transform is a special case: sprites, texts and shapes /// (and it's a good idea to do it with your own drawable classes /// too) combine their transform with the one that is passed in the /// RenderStates structure. So that you can use a "global" transform /// on top of each object's transform. /// /// Most objects, especially high-level drawables, can be drawn /// directly without defining render states explicitly -- the /// default set of states is ok in most cases. /// \code /// window.draw(sprite); /// \endcode /// /// If you want to use a single specific render state, /// for example a shader, you can pass it directly to the Draw /// function: sf::RenderStates has an implicit one-argument /// constructor for each state. /// \code /// window.draw(sprite, shader); /// \endcode /// /// When you're inside the Draw function of a drawable /// object (inherited from sf::Drawable), you can /// either pass the render states unmodified, or change /// some of them. /// For example, a transformable object will combine the /// current transform with its own transform. A sprite will /// set its texture. Etc. /// /// \see sf::RenderTarget, sf::Drawable /// ////////////////////////////////////////////////////////////
UgoLouche/QPacman
src/includes/SFML/Graphics/RenderStates.hpp
C++
gpl-3.0
6,538
<?php /** * @package Joomla.Site * @subpackage mod_related_items * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include the syndicate functions only once require_once __DIR__ . '/helper.php'; $cacheparams = new stdClass; $cacheparams->cachemode = 'safeuri'; $cacheparams->class = 'ModRelatedItemsHelper'; $cacheparams->method = 'getList'; $cacheparams->methodparams = $params; $cacheparams->modeparams = array('id' => 'int', 'Itemid' => 'int'); $list = JModuleHelper::moduleCache($module, $params, $cacheparams); if (!count($list)) { return; } $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx')); $showDate = $params->get('showDate', 0); require JModuleHelper::getLayoutPath('mod_related_items', $params->get('layout', 'default'));
RCBiczok/ArticleRefs
src/test/lib/joomla/3_1_5/modules/mod_related_items/mod_related_items.php
PHP
gpl-3.0
921
// Copyright (c) 2010, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // exception_handler_test.cc: Unit tests for google_breakpad::ExceptionHandler #include <pthread.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include "breakpad_googletest_includes.h" #include "client/mac/handler/exception_handler.h" #include "common/mac/MachIPC.h" #include "common/tests/auto_tempdir.h" #include "google_breakpad/processor/minidump.h" namespace google_breakpad { // This acts as the log sink for INFO logging from the processor // logging code. The logging output confuses XCode and makes it think // there are unit test failures. testlogging.h handles the overriding. std::ostringstream info_log; } namespace { using std::string; using google_breakpad::AutoTempDir; using google_breakpad::ExceptionHandler; using google_breakpad::MachPortSender; using google_breakpad::MachReceiveMessage; using google_breakpad::MachSendMessage; using google_breakpad::Minidump; using google_breakpad::MinidumpContext; using google_breakpad::MinidumpException; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpMemoryRegion; using google_breakpad::ReceivePort; using testing::Test; class ExceptionHandlerTest : public Test { public: void InProcessCrash(bool aborting); AutoTempDir tempDir; string lastDumpName; }; static void Crasher() { int *a = (int*)0x42; fprintf(stdout, "Going to crash...\n"); fprintf(stdout, "A = %d", *a); } static void AbortCrasher() { fprintf(stdout, "Going to crash...\n"); abort(); } static void SoonToCrash(void(*crasher)()) { crasher(); } static bool MDCallback(const char *dump_dir, const char *file_name, void *context, bool success) { string path(dump_dir); path.append("/"); path.append(file_name); path.append(".dmp"); int fd = *reinterpret_cast<int*>(context); (void)write(fd, path.c_str(), path.length() + 1); close(fd); exit(0); // not reached return true; } void ExceptionHandlerTest::InProcessCrash(bool aborting) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); // Fork off a child process so it can crash. pid_t pid = fork(); if (pid == 0) { // In the child process. close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // crash SoonToCrash(aborting ? &AbortCrasher : &Crasher); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); } TEST_F(ExceptionHandlerTest, InProcess) { InProcessCrash(false); } #if TARGET_OS_IPHONE TEST_F(ExceptionHandlerTest, InProcessAbort) { InProcessCrash(true); } #endif static bool DumpNameMDCallback(const char *dump_dir, const char *file_name, void *context, bool success) { ExceptionHandlerTest *self = reinterpret_cast<ExceptionHandlerTest*>(context); if (dump_dir && file_name) { self->lastDumpName = dump_dir; self->lastDumpName += "/"; self->lastDumpName += file_name; self->lastDumpName += ".dmp"; } return true; } TEST_F(ExceptionHandlerTest, WriteMinidump) { ExceptionHandler eh(tempDir.path(), NULL, DumpNameMDCallback, this, true, NULL); ASSERT_TRUE(eh.WriteMinidump()); // Ensure that minidump file exists and is > 0 bytes. ASSERT_FALSE(lastDumpName.empty()); struct stat st; ASSERT_EQ(0, stat(lastDumpName.c_str(), &st)); ASSERT_LT(0, st.st_size); // The minidump should not contain an exception stream. Minidump minidump(lastDumpName); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); EXPECT_FALSE(exception); } TEST_F(ExceptionHandlerTest, WriteMinidumpWithException) { ExceptionHandler eh(tempDir.path(), NULL, DumpNameMDCallback, this, true, NULL); ASSERT_TRUE(eh.WriteMinidump(true)); // Ensure that minidump file exists and is > 0 bytes. ASSERT_FALSE(lastDumpName.empty()); struct stat st; ASSERT_EQ(0, stat(lastDumpName.c_str(), &st)); ASSERT_LT(0, st.st_size); // The minidump should contain an exception stream. Minidump minidump(lastDumpName); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); ASSERT_TRUE(exception); const MDRawExceptionStream* raw_exception = exception->exception(); ASSERT_TRUE(raw_exception); EXPECT_EQ(MD_EXCEPTION_MAC_BREAKPOINT, raw_exception->exception_record.exception_code); } TEST_F(ExceptionHandlerTest, DumpChildProcess) { const int kTimeoutMs = 2000; // Create a mach port to receive the child task on. char machPortName[128]; sprintf(machPortName, "ExceptionHandlerTest.%d", getpid()); ReceivePort parent_recv_port(machPortName); // Give the child process a pipe to block on. int fds[2]; ASSERT_EQ(0, pipe(fds)); // Fork off a child process to dump. pid_t pid = fork(); if (pid == 0) { // In the child process close(fds[1]); // Send parent process the task and thread ports. MachSendMessage child_message(0); child_message.AddDescriptor(mach_task_self()); child_message.AddDescriptor(mach_thread_self()); MachPortSender child_sender(machPortName); if (child_sender.SendMessage(child_message, kTimeoutMs) != KERN_SUCCESS) exit(1); // Wait for the parent process. uint8_t data; read(fds[0], &data, 1); exit(0); } // In the parent process. ASSERT_NE(-1, pid); close(fds[0]); // Read the child's task and thread ports. MachReceiveMessage child_message; ASSERT_EQ(KERN_SUCCESS, parent_recv_port.WaitForMessage(&child_message, kTimeoutMs)); mach_port_t child_task = child_message.GetTranslatedPort(0); mach_port_t child_thread = child_message.GetTranslatedPort(1); ASSERT_NE((mach_port_t)MACH_PORT_NULL, child_task); ASSERT_NE((mach_port_t)MACH_PORT_NULL, child_thread); // Write a minidump of the child process. bool result = ExceptionHandler::WriteMinidumpForChild(child_task, child_thread, tempDir.path(), DumpNameMDCallback, this); ASSERT_EQ(true, result); // Ensure that minidump file exists and is > 0 bytes. ASSERT_FALSE(lastDumpName.empty()); struct stat st; ASSERT_EQ(0, stat(lastDumpName.c_str(), &st)); ASSERT_LT(0, st.st_size); // Unblock child process uint8_t data = 1; (void)write(fds[1], &data, 1); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); } // Test that memory around the instruction pointer is written // to the dump as a MinidumpMemoryRegion. TEST_F(ExceptionHandlerTest, InstructionPointerMemory) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); // These are defined here so the parent can use them to check the // data from the minidump afterwards. const u_int32_t kMemorySize = 256; // bytes const int kOffset = kMemorySize / 2; // This crashes with SIGILL on x86/x86-64/arm. const unsigned char instructions[] = { 0xff, 0xff, 0xff, 0xff }; pid_t pid = fork(); if (pid == 0) { close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // Get some executable memory. char* memory = reinterpret_cast<char*>(mmap(NULL, kMemorySize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); if (!memory) exit(0); // Write some instructions that will crash. Put them in the middle // of the block of memory, because the minidump should contain 128 // bytes on either side of the instruction pointer. memcpy(memory + kOffset, instructions, sizeof(instructions)); // Now execute the instructions, which should crash. typedef void (*void_function)(void); void_function memory_function = reinterpret_cast<void_function>(memory + kOffset); memory_function(); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); close(fds[1]); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); // Read the minidump. Locate the exception record and the // memory list, and then ensure that there is a memory region // in the memory list that covers the instruction pointer from // the exception record. Minidump minidump(minidump_file); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); MinidumpMemoryList* memory_list = minidump.GetMemoryList(); ASSERT_TRUE(exception); ASSERT_TRUE(memory_list); ASSERT_NE((unsigned int)0, memory_list->region_count()); MinidumpContext* context = exception->GetContext(); ASSERT_TRUE(context); u_int64_t instruction_pointer; switch (context->GetContextCPU()) { case MD_CONTEXT_X86: instruction_pointer = context->GetContextX86()->eip; break; case MD_CONTEXT_AMD64: instruction_pointer = context->GetContextAMD64()->rip; break; case MD_CONTEXT_ARM: instruction_pointer = context->GetContextARM()->iregs[15]; break; default: FAIL() << "Unknown context CPU: " << context->GetContextCPU(); break; } MinidumpMemoryRegion* region = memory_list->GetMemoryRegionForAddress(instruction_pointer); EXPECT_TRUE(region); EXPECT_EQ(kMemorySize, region->GetSize()); const u_int8_t* bytes = region->GetMemory(); ASSERT_TRUE(bytes); u_int8_t prefix_bytes[kOffset]; u_int8_t suffix_bytes[kMemorySize - kOffset - sizeof(instructions)]; memset(prefix_bytes, 0, sizeof(prefix_bytes)); memset(suffix_bytes, 0, sizeof(suffix_bytes)); EXPECT_TRUE(memcmp(bytes, prefix_bytes, sizeof(prefix_bytes)) == 0); EXPECT_TRUE(memcmp(bytes + kOffset, instructions, sizeof(instructions)) == 0); EXPECT_TRUE(memcmp(bytes + kOffset + sizeof(instructions), suffix_bytes, sizeof(suffix_bytes)) == 0); } // Test that the memory region around the instruction pointer is // bounded correctly on the low end. TEST_F(ExceptionHandlerTest, InstructionPointerMemoryMinBound) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); // These are defined here so the parent can use them to check the // data from the minidump afterwards. const u_int32_t kMemorySize = 256; // bytes const int kOffset = 0; // This crashes with SIGILL on x86/x86-64/arm. const unsigned char instructions[] = { 0xff, 0xff, 0xff, 0xff }; pid_t pid = fork(); if (pid == 0) { close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // Get some executable memory. char* memory = reinterpret_cast<char*>(mmap(NULL, kMemorySize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); if (!memory) exit(0); // Write some instructions that will crash. Put them at the start // of the block of memory, to ensure that the memory bounding // works properly. memcpy(memory + kOffset, instructions, sizeof(instructions)); // Now execute the instructions, which should crash. typedef void (*void_function)(void); void_function memory_function = reinterpret_cast<void_function>(memory + kOffset); memory_function(); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); close(fds[1]); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); // Read the minidump. Locate the exception record and the // memory list, and then ensure that there is a memory region // in the memory list that covers the instruction pointer from // the exception record. Minidump minidump(minidump_file); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); MinidumpMemoryList* memory_list = minidump.GetMemoryList(); ASSERT_TRUE(exception); ASSERT_TRUE(memory_list); ASSERT_NE((unsigned int)0, memory_list->region_count()); MinidumpContext* context = exception->GetContext(); ASSERT_TRUE(context); u_int64_t instruction_pointer; switch (context->GetContextCPU()) { case MD_CONTEXT_X86: instruction_pointer = context->GetContextX86()->eip; break; case MD_CONTEXT_AMD64: instruction_pointer = context->GetContextAMD64()->rip; break; case MD_CONTEXT_ARM: instruction_pointer = context->GetContextARM()->iregs[15]; break; default: FAIL() << "Unknown context CPU: " << context->GetContextCPU(); break; } MinidumpMemoryRegion* region = memory_list->GetMemoryRegionForAddress(instruction_pointer); EXPECT_TRUE(region); EXPECT_EQ(kMemorySize / 2, region->GetSize()); const u_int8_t* bytes = region->GetMemory(); ASSERT_TRUE(bytes); u_int8_t suffix_bytes[kMemorySize / 2 - sizeof(instructions)]; memset(suffix_bytes, 0, sizeof(suffix_bytes)); EXPECT_TRUE(memcmp(bytes + kOffset, instructions, sizeof(instructions)) == 0); EXPECT_TRUE(memcmp(bytes + kOffset + sizeof(instructions), suffix_bytes, sizeof(suffix_bytes)) == 0); } // Test that the memory region around the instruction pointer is // bounded correctly on the high end. TEST_F(ExceptionHandlerTest, InstructionPointerMemoryMaxBound) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); // These are defined here so the parent can use them to check the // data from the minidump afterwards. // Use 4k here because the OS will hand out a single page even // if a smaller size is requested, and this test wants to // test the upper bound of the memory range. const u_int32_t kMemorySize = 4096; // bytes // This crashes with SIGILL on x86/x86-64/arm. const unsigned char instructions[] = { 0xff, 0xff, 0xff, 0xff }; const int kOffset = kMemorySize - sizeof(instructions); pid_t pid = fork(); if (pid == 0) { close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // Get some executable memory. char* memory = reinterpret_cast<char*>(mmap(NULL, kMemorySize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0)); if (!memory) exit(0); // Write some instructions that will crash. Put them at the start // of the block of memory, to ensure that the memory bounding // works properly. memcpy(memory + kOffset, instructions, sizeof(instructions)); // Now execute the instructions, which should crash. typedef void (*void_function)(void); void_function memory_function = reinterpret_cast<void_function>(memory + kOffset); memory_function(); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); close(fds[1]); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); // Read the minidump. Locate the exception record and the // memory list, and then ensure that there is a memory region // in the memory list that covers the instruction pointer from // the exception record. Minidump minidump(minidump_file); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); MinidumpMemoryList* memory_list = minidump.GetMemoryList(); ASSERT_TRUE(exception); ASSERT_TRUE(memory_list); ASSERT_NE((unsigned int)0, memory_list->region_count()); MinidumpContext* context = exception->GetContext(); ASSERT_TRUE(context); u_int64_t instruction_pointer; switch (context->GetContextCPU()) { case MD_CONTEXT_X86: instruction_pointer = context->GetContextX86()->eip; break; case MD_CONTEXT_AMD64: instruction_pointer = context->GetContextAMD64()->rip; break; case MD_CONTEXT_ARM: instruction_pointer = context->GetContextARM()->iregs[15]; break; default: FAIL() << "Unknown context CPU: " << context->GetContextCPU(); break; } MinidumpMemoryRegion* region = memory_list->GetMemoryRegionForAddress(instruction_pointer); EXPECT_TRUE(region); const size_t kPrefixSize = 128; // bytes EXPECT_EQ(kPrefixSize + sizeof(instructions), region->GetSize()); const u_int8_t* bytes = region->GetMemory(); ASSERT_TRUE(bytes); u_int8_t prefix_bytes[kPrefixSize]; memset(prefix_bytes, 0, sizeof(prefix_bytes)); EXPECT_TRUE(memcmp(bytes, prefix_bytes, sizeof(prefix_bytes)) == 0); EXPECT_TRUE(memcmp(bytes + kPrefixSize, instructions, sizeof(instructions)) == 0); } // Ensure that an extra memory block doesn't get added when the // instruction pointer is not in mapped memory. TEST_F(ExceptionHandlerTest, InstructionPointerMemoryNullPointer) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); pid_t pid = fork(); if (pid == 0) { close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // Try calling a NULL pointer. typedef void (*void_function)(void); void_function memory_function = reinterpret_cast<void_function>(NULL); memory_function(); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); close(fds[1]); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); // Read the minidump. Locate the exception record and the // memory list, and then ensure that there is only one memory region // in the memory list (the thread memory from the single thread). Minidump minidump(minidump_file); ASSERT_TRUE(minidump.Read()); MinidumpException* exception = minidump.GetException(); MinidumpMemoryList* memory_list = minidump.GetMemoryList(); ASSERT_TRUE(exception); ASSERT_TRUE(memory_list); ASSERT_EQ((unsigned int)1, memory_list->region_count()); } static void *Junk(void *) { sleep(1000000); return NULL; } // Test that the memory list gets written correctly when multiple // threads are running. TEST_F(ExceptionHandlerTest, MemoryListMultipleThreads) { // Give the child process a pipe to report back on. int fds[2]; ASSERT_EQ(0, pipe(fds)); pid_t pid = fork(); if (pid == 0) { close(fds[0]); ExceptionHandler eh(tempDir.path(), NULL, MDCallback, &fds[1], true, NULL); // Run an extra thread so >2 memory regions will be written. pthread_t junk_thread; if (pthread_create(&junk_thread, NULL, Junk, NULL) == 0) pthread_detach(junk_thread); // Just crash. Crasher(); // not reached exit(1); } // In the parent process. ASSERT_NE(-1, pid); close(fds[1]); // Wait for the background process to return the minidump file. close(fds[1]); char minidump_file[PATH_MAX]; ssize_t nbytes = read(fds[0], minidump_file, sizeof(minidump_file)); ASSERT_NE(0, nbytes); // Ensure that minidump file exists and is > 0 bytes. struct stat st; ASSERT_EQ(0, stat(minidump_file, &st)); ASSERT_LT(0, st.st_size); // Child process should have exited with a zero status. int ret; ASSERT_EQ(pid, waitpid(pid, &ret, 0)); EXPECT_NE(0, WIFEXITED(ret)); EXPECT_EQ(0, WEXITSTATUS(ret)); // Read the minidump, and verify that the memory list can be read. Minidump minidump(minidump_file); ASSERT_TRUE(minidump.Read()); MinidumpMemoryList* memory_list = minidump.GetMemoryList(); ASSERT_TRUE(memory_list); // Verify that there are three memory regions: // one per thread, and one for the instruction pointer memory. ASSERT_EQ((unsigned int)3, memory_list->region_count()); } }
norrs/debian-tomahawk
thirdparty/breakpad/client/mac/tests/exception_handler_test.cc
C++
gpl-3.0
23,972
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/system_message_window_win.h" #include <dbt.h> #include "base/logging.h" #include "base/system_monitor/system_monitor.h" #include "base/win/wrapped_window_proc.h" #include "media/audio/win/core_audio_util_win.h" namespace content { namespace { const wchar_t kWindowClassName[] = L"Chrome_SystemMessageWindow"; // A static map from a device category guid to base::SystemMonitor::DeviceType. struct { const GUID device_category; const base::SystemMonitor::DeviceType device_type; } const kDeviceCategoryMap[] = { { KSCATEGORY_AUDIO, base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE }, { KSCATEGORY_VIDEO, base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE }, }; } // namespace // Manages the device notification handles for SystemMessageWindowWin. class SystemMessageWindowWin::DeviceNotifications { public: explicit DeviceNotifications(HWND hwnd) : notifications_() { Register(hwnd); } ~DeviceNotifications() { Unregister(); } void Register(HWND hwnd) { // Request to receive device notifications. All applications receive basic // notifications via WM_DEVICECHANGE but in order to receive detailed device // arrival and removal messages, we need to register. DEV_BROADCAST_DEVICEINTERFACE filter = {0}; filter.dbcc_size = sizeof(filter); filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; bool core_audio_support = media::CoreAudioUtil::IsSupported(); for (int i = 0; i < arraysize(kDeviceCategoryMap); ++i) { // If CoreAudio is supported, AudioDeviceListenerWin will // take care of monitoring audio devices. if (core_audio_support && KSCATEGORY_AUDIO == kDeviceCategoryMap[i].device_category) { continue; } filter.dbcc_classguid = kDeviceCategoryMap[i].device_category; DCHECK_EQ(notifications_[i], static_cast<HDEVNOTIFY>(NULL)); notifications_[i] = RegisterDeviceNotification( hwnd, &filter, DEVICE_NOTIFY_WINDOW_HANDLE); DPLOG_IF(ERROR, !notifications_[i]) << "RegisterDeviceNotification failed"; } } void Unregister() { for (int i = 0; i < arraysize(notifications_); ++i) { if (notifications_[i]) { UnregisterDeviceNotification(notifications_[i]); notifications_[i] = NULL; } } } private: HDEVNOTIFY notifications_[arraysize(kDeviceCategoryMap)]; DISALLOW_IMPLICIT_CONSTRUCTORS(DeviceNotifications); }; SystemMessageWindowWin::SystemMessageWindowWin() { WNDCLASSEX window_class; base::win::InitializeWindowClass( kWindowClassName, &base::win::WrappedWindowProc<SystemMessageWindowWin::WndProcThunk>, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, &window_class); instance_ = window_class.hInstance; ATOM clazz = RegisterClassEx(&window_class); DCHECK(clazz); window_ = CreateWindow(kWindowClassName, 0, 0, 0, 0, 0, 0, 0, 0, instance_, 0); SetWindowLongPtr(window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); device_notifications_.reset(new DeviceNotifications(window_)); } SystemMessageWindowWin::~SystemMessageWindowWin() { if (window_) { DestroyWindow(window_); UnregisterClass(kWindowClassName, instance_); } } LRESULT SystemMessageWindowWin::OnDeviceChange(UINT event_type, LPARAM data) { base::SystemMonitor* monitor = base::SystemMonitor::Get(); base::SystemMonitor::DeviceType device_type = base::SystemMonitor::DEVTYPE_UNKNOWN; switch (event_type) { case DBT_DEVNODES_CHANGED: // For this notification, we're happy with the default DEVTYPE_UNKNOWN. break; case DBT_DEVICEREMOVECOMPLETE: case DBT_DEVICEARRIVAL: { // This notification has more details about the specific device that // was added or removed. See if this is a category we're interested // in monitoring and if so report the specific device type. If we don't // find the category in our map, ignore the notification and do not // notify the system monitor. DEV_BROADCAST_DEVICEINTERFACE* device_interface = reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE*>(data); if (device_interface->dbcc_devicetype != DBT_DEVTYP_DEVICEINTERFACE) return TRUE; for (int i = 0; i < arraysize(kDeviceCategoryMap); ++i) { if (kDeviceCategoryMap[i].device_category == device_interface->dbcc_classguid) { device_type = kDeviceCategoryMap[i].device_type; break; } } // Devices that we do not have a DEVTYPE_ for, get detected via // DBT_DEVNODES_CHANGED, so we avoid sending additional notifications // for those here. if (device_type == base::SystemMonitor::DEVTYPE_UNKNOWN) return TRUE; break; } default: return TRUE; } monitor->ProcessDevicesChanged(device_type); return TRUE; } LRESULT CALLBACK SystemMessageWindowWin::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_DEVICECHANGE: return OnDeviceChange(static_cast<UINT>(wparam), lparam); default: break; } return ::DefWindowProc(hwnd, message, wparam, lparam); } } // namespace content
plxaye/chromium
src/content/browser/system_message_window_win.cc
C++
apache-2.0
5,414
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WKMediaCacheManager.h" #include "WKAPICast.h" #include "WebMediaCacheManagerProxy.h" using namespace WebKit; WKTypeID WKMediaCacheManagerGetTypeID() { return toAPI(WebMediaCacheManagerProxy::APIType); } void WKMediaCacheManagerGetHostnamesWithMediaCache(WKMediaCacheManagerRef mediaCacheManagerRef, void* context, WKMediaCacheManagerGetHostnamesWithMediaCacheFunction callback) { toImpl(mediaCacheManagerRef)->getHostnamesWithMediaCache(ArrayCallback::create(context, callback)); } void WKMediaCacheManagerClearCacheForHostname(WKMediaCacheManagerRef mediaCacheManagerRef, WKStringRef hostname) { toImpl(mediaCacheManagerRef)->clearCacheForHostname(toWTFString(hostname)); } void WKMediaCacheManagerClearCacheForAllHostnames(WKMediaCacheManagerRef mediaCacheManagerRef) { toImpl(mediaCacheManagerRef)->clearCacheForAllHostnames(); }
danialbehzadi/Nokia-RM-1013-2.0.0.11
webkit/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.cpp
C++
gpl-3.0
2,241
// Copyright 2015 go-swagger maintainers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package runtime import "github.com/go-openapi/strfmt" // A ClientAuthInfoWriterFunc converts a function to a request writer interface type ClientAuthInfoWriterFunc func(ClientRequest, strfmt.Registry) error // AuthenticateRequest adds authentication data to the request func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error { return fn(req, reg) } // A ClientAuthInfoWriter implementor knows how to write authentication info to a request type ClientAuthInfoWriter interface { AuthenticateRequest(ClientRequest, strfmt.Registry) error }
kgrygiel/autoscaler
vertical-pod-autoscaler/vendor/github.com/go-openapi/runtime/client_auth_info.go
GO
apache-2.0
1,188
/** * Resource drag and drop. * * @class M.course.dragdrop.resource * @constructor * @extends M.core.dragdrop */ var DRAGRESOURCE = function() { DRAGRESOURCE.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGRESOURCE, M.core.dragdrop, { initializer: function() { // Set group for parent class this.groups = ['resource']; this.samenodeclass = CSS.ACTIVITY; this.parentnodeclass = CSS.SECTION; this.resourcedraghandle = this.get_drag_handle(M.util.get_string('move', 'moodle'), CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.samenodelabel = { identifier: 'dragtoafter', component: 'quiz' }; this.parentnodelabel = { identifier: 'dragtostart', component: 'quiz' }; // Go through all sections this.setup_for_section(); // Initialise drag & drop for all resources/activities var nodeselector = 'li.' + CSS.ACTIVITY; var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: nodeselector, target: true, handles: ['.' + CSS.EDITINGMOVE], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false, cloneNode: true }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.SLOTS }); del.dd.plug(Y.Plugin.DDWinScroll); M.mod_quiz.quizbase.register_module(this); M.mod_quiz.dragres = this; }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function() { Y.Node.all('.mod-quiz-edit-content ul.slots ul.section').each(function(resources) { resources.setAttribute('data-draggroups', this.groups.join(' ')); // Define empty ul as droptarget, so that item could be moved to empty list new Y.DD.Drop({ node: resources, groups: this.groups, padding: '20 0 20 0' }); // Initialise each resource/activity in this section this.setup_for_resource('li.activity'); }, this); }, /** * Apply dragdrop features to the specified selector or node that refers to resource(s) * * @method setup_for_resource * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_resource: function(baseselector) { Y.Node.all(baseselector).each(function(resourcesnode) { // Replace move icons var move = resourcesnode.one('a.' + CSS.EDITINGMOVE); if (move) { move.replace(this.resourcedraghandle.cloneNode(true)); } }, this); }, drag_start: function(e) { // Get our drag object var drag = e.target; drag.get('dragNode').setContent(drag.get('node').get('innerHTML')); drag.get('dragNode').all('img.iconsmall').setStyle('vertical-align', 'baseline'); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, drop_hit: function(e) { var drag = e.drag; // Get a reference to our drag node var dragnode = drag.get('node'); var dropnode = e.drop.get('node'); // Add spinner if it not there var actionarea = dragnode.one(CSS.ACTIONAREA); var spinner = M.util.add_spinner(Y, actionarea); var params = {}; // Handle any variables which we must pass back through to var pageparams = this.get('config').pageparams; var varname; for (varname in pageparams) { params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'resource'; params.field = 'move'; params.id = Number(Y.Moodle.mod_quiz.util.slot.getId(dragnode)); params.sectionId = Y.Moodle.core_course.util.section.getId(dropnode.ancestor('li.section', true)); var previousslot = dragnode.previous(SELECTOR.SLOT); if (previousslot) { params.previousid = Number(Y.Moodle.mod_quiz.util.slot.getId(previousslot)); } var previouspage = dragnode.previous(SELECTOR.PAGE); if (previouspage) { params.page = Number(Y.Moodle.mod_quiz.util.page.getId(previouspage)); } // Do AJAX request var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { this.lock_drag_handle(drag, CSS.EDITINGMOVE); spinner.show(); }, success: function(tid, response) { var responsetext = Y.JSON.parse(response.responseText); var params = {element: dragnode, visible: responsetext.visible}; M.mod_quiz.quizbase.invoke_function('set_visibility_resource_ui', params); this.unlock_drag_handle(drag, CSS.EDITINGMOVE); window.setTimeout(function() { spinner.hide(); }, 250); M.mod_quiz.resource_toolbox.reorganise_edit_page(); }, failure: function(tid, response) { this.ajax_failure(response); this.unlock_drag_handle(drag, CSS.SECTIONHANDLE); spinner.hide(); window.location.reload(true); } }, context:this }); }, global_drop_over: function(e) { //Overriding parent method so we can stop the slots being dragged before the first page node. // Check that drop object belong to correct group. if (!e.drop || !e.drop.inGroup(this.groups)) { return; } // Get a reference to our drag and drop nodes. var drag = e.drag.get('node'), drop = e.drop.get('node'); // Save last drop target for the case of missed target processing. this.lastdroptarget = e.drop; // Are we dropping within the same parent node? if (drop.hasClass(this.samenodeclass)) { var where; if (this.goingup) { where = "before"; } else { where = "after"; } drop.insert(drag, where); } else if ((drop.hasClass(this.parentnodeclass) || drop.test('[data-droptarget="1"]')) && !drop.contains(drag)) { // We are dropping on parent node and it is empty if (this.goingup) { drop.append(drag); } else { drop.prepend(drag); } } this.drop_over(e); } }, { NAME: 'mod_quiz-dragdrop-resource', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_resource_dragdrop = function(params) { new DRAGRESOURCE(params); };
ernestovi/ups
moodle/mod/quiz/yui/src/dragdrop/js/resource.js
JavaScript
gpl-3.0
7,887
// Heartbeat options: // heartbeatInterval: interval to send pings, in milliseconds. // heartbeatTimeout: timeout to close the connection if a reply isn't // received, in milliseconds. // sendPing: function to call to send a ping on the connection. // onTimeout: function to call to close the connection. DDPCommon.Heartbeat = function (options) { var self = this; self.heartbeatInterval = options.heartbeatInterval; self.heartbeatTimeout = options.heartbeatTimeout; self._sendPing = options.sendPing; self._onTimeout = options.onTimeout; self._seenPacket = false; self._heartbeatIntervalHandle = null; self._heartbeatTimeoutHandle = null; }; _.extend(DDPCommon.Heartbeat.prototype, { stop: function () { var self = this; self._clearHeartbeatIntervalTimer(); self._clearHeartbeatTimeoutTimer(); }, start: function () { var self = this; self.stop(); self._startHeartbeatIntervalTimer(); }, _startHeartbeatIntervalTimer: function () { var self = this; self._heartbeatIntervalHandle = Meteor.setInterval( _.bind(self._heartbeatIntervalFired, self), self.heartbeatInterval ); }, _startHeartbeatTimeoutTimer: function () { var self = this; self._heartbeatTimeoutHandle = Meteor.setTimeout( _.bind(self._heartbeatTimeoutFired, self), self.heartbeatTimeout ); }, _clearHeartbeatIntervalTimer: function () { var self = this; if (self._heartbeatIntervalHandle) { Meteor.clearInterval(self._heartbeatIntervalHandle); self._heartbeatIntervalHandle = null; } }, _clearHeartbeatTimeoutTimer: function () { var self = this; if (self._heartbeatTimeoutHandle) { Meteor.clearTimeout(self._heartbeatTimeoutHandle); self._heartbeatTimeoutHandle = null; } }, // The heartbeat interval timer is fired when we should send a ping. _heartbeatIntervalFired: function () { var self = this; // don't send ping if we've seen a packet since we last checked, // *or* if we have already sent a ping and are awaiting a timeout. // That shouldn't happen, but it's possible if // `self.heartbeatInterval` is smaller than // `self.heartbeatTimeout`. if (! self._seenPacket && ! self._heartbeatTimeoutHandle) { self._sendPing(); // Set up timeout, in case a pong doesn't arrive in time. self._startHeartbeatTimeoutTimer(); } self._seenPacket = false; }, // The heartbeat timeout timer is fired when we sent a ping, but we // timed out waiting for the pong. _heartbeatTimeoutFired: function () { var self = this; self._heartbeatTimeoutHandle = null; self._onTimeout(); }, messageReceived: function () { var self = this; // Tell periodic checkin that we have seen a packet, and thus it // does not need to send a ping this cycle. self._seenPacket = true; // If we were waiting for a pong, we got it. if (self._heartbeatTimeoutHandle) { self._clearHeartbeatTimeoutTimer(); } } });
lawrenceAIO/meteor
packages/ddp-common/heartbeat.js
JavaScript
mit
3,044
require('./angular-locale_nl-cw'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/nl-cw.js
JavaScript
mit
64
require('./angular-locale_en-im'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/en-im.js
JavaScript
mit
64
<?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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright 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$ */ /** * Basic Interface for factilities that load Zend_Tool providers or manifests. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_Tool_Framework_Loader_Interface { /** * Load Providers and Manifests * * Returns an array of all loaded class names. * * @return array */ public function load(); }
hansbonini/cloud9-magento
www/lib/Zend/Tool/Framework/Loader/Interface.php
PHP
mit
1,265
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Assembly symbol referenced by a AssemblyRef for which we couldn't find a matching /// compilation reference but we found one that differs in version. /// Created only for assemblies that require runtime binding redirection policy, /// i.e. not for Framework assemblies. /// </summary> internal struct UnifiedAssembly<TAssemblySymbol> where TAssemblySymbol : class, IAssemblySymbol { /// <summary> /// Original reference that was unified to the identity of the <see cref="TargetAssembly"/>. /// </summary> internal readonly AssemblyIdentity OriginalReference; internal readonly TAssemblySymbol TargetAssembly; public UnifiedAssembly(TAssemblySymbol targetAssembly, AssemblyIdentity originalReference) { Debug.Assert(originalReference != null); Debug.Assert(targetAssembly != null); this.OriginalReference = originalReference; this.TargetAssembly = targetAssembly; } } }
balazssimon/meta-cs
src/Main/MetaDslx.CodeAnalysis.Common/ReferenceManager/UnifiedAssembly.cs
C#
apache-2.0
1,310
// This depends on tinytest, so it's a little weird to put it in // test-helpers, but it'll do for now. // Provides the testAsyncMulti helper, which creates an async test // (using Tinytest.addAsync) that tracks parallel and sequential // asynchronous calls. Specifically, the two features it provides // are: // 1) Executing an array of functions sequentially when those functions // contain async calls. // 2) Keeping track of when callbacks are outstanding, via "expect". // // To use, pass an array of functions that take arguments (test, expect). // (There is no onComplete callback; completion is determined automatically.) // Expect takes a callback closure and wraps it, returning a new callback closure, // and making a note that there is a callback oustanding. Pass this returned closure // to async functions as the callback, and the machinery in the wrapper will // record the fact that the callback has been called. // // A second form of expect takes data arguments to test for. // Essentially, expect("foo", "bar") is equivalent to: // expect(function(arg1, arg2) { test.equal([arg1, arg2], ["foo", "bar"]); }). // // You cannot "nest" expect or call it from a callback! Even if you have a chain // of callbacks, you need to call expect at the "top level" (synchronously) // but the callback you wrap has to be the last/innermost one. This sometimes // leads to some code contortions and should probably be fixed. // Example: (at top level of test file) // // testAsyncMulti("test name", [ // function(test, expect) { // ... tests here // Meteor.defer(expect(function() { // ... tests here // })); // // call_something_async('foo', 'bar', expect('baz')); // implicit callback // // }, // function(test, expect) { // ... more tests // } // ]); var ExpectationManager = function (test, onComplete) { var self = this; self.test = test; self.onComplete = onComplete; self.closed = false; self.dead = false; self.outstanding = 0; }; _.extend(ExpectationManager.prototype, { expect: function (/* arguments */) { var self = this; if (typeof arguments[0] === "function") var expected = arguments[0]; else var expected = _.toArray(arguments); if (self.closed) throw new Error("Too late to add more expectations to the test"); self.outstanding++; return function (/* arguments */) { if (self.dead) return; if (typeof expected === "function") { try { expected.apply({}, arguments); } catch (e) { if (self.cancel()) self.test.exception(e); } } else { self.test.equal(_.toArray(arguments), expected); } self.outstanding--; self._check_complete(); }; }, done: function () { var self = this; self.closed = true; self._check_complete(); }, cancel: function () { var self = this; if (! self.dead) { self.dead = true; return true; } return false; }, _check_complete: function () { var self = this; if (!self.outstanding && self.closed && !self.dead) { self.dead = true; self.onComplete(); } } }); testAsyncMulti = function (name, funcs) { // XXX Tests on remote browsers are _slow_. We need a better solution. var timeout = 180000; Tinytest.addAsync(name, function (test, onComplete) { var remaining = _.clone(funcs); var context = {}; var i = 0; var runNext = function () { var func = remaining.shift(); if (!func) { delete test.extraDetails.asyncBlock; onComplete(); } else { var em = new ExpectationManager(test, function () { Meteor.clearTimeout(timer); runNext(); }); var timer = Meteor.setTimeout(function () { if (em.cancel()) { test.fail({type: "timeout", message: "Async batch timed out"}); onComplete(); } return; }, timeout); test.extraDetails.asyncBlock = i++; try { func.apply(context, [test, _.bind(em.expect, em)]); } catch (exception) { if (em.cancel()) test.exception(exception); Meteor.clearTimeout(timer); // Because we called test.exception, we're not to call onComplete. return; } em.done(); } }; runNext(); }); }; // Call `fn` periodically until it returns true. If it does, call // `success`. If it doesn't before the timeout, call `failed`. simplePoll = function (fn, success, failed, timeout, step) { timeout = timeout || 10000; step = step || 100; var start = (new Date()).valueOf(); var helper = function () { if (fn()) { success(); return; } if (start + timeout < (new Date()).valueOf()) { failed(); return; } Meteor.setTimeout(helper, step); }; helper(); }; pollUntil = function (expect, f, timeout, step, noFail) { noFail = noFail || false; step = step || 100; var expectation = expect(true); simplePoll( f, function () { expectation(true) }, function () { expectation(noFail) }, timeout, step ); };
jrudio/meteor
packages/test-helpers/async_multi.js
JavaScript
mit
5,209
<?php namespace Drupal\Tests\devel\Kernel; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\KernelTests\KernelTestBase; use Drupal\devel\Twig\Extension\Debug; use Drupal\user\Entity\Role; use Drupal\user\Entity\User; /** * Tests Twig extensions. * * @group devel */ class DevelTwigExtensionTest extends KernelTestBase { use DevelDumperTestTrait; /** * The user used in test. * * @var \Drupal\user\UserInterface */ protected $develUser; /** * Modules to enable. * * @var array */ public static $modules = ['devel', 'user', 'system']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('user'); $this->installSchema('system', 'sequences'); $devel_role = Role::create([ 'id' => 'admin', 'permissions' => ['access devel information'], ]); $devel_role->save(); $this->develUser = User::create([ 'name' => $this->randomMachineName(), 'roles' => [$devel_role->id()], ]); $this->develUser->save(); } /** * {@inheritdoc} */ public function register(ContainerBuilder $container) { parent::register($container); $parameters = $container->getParameter('twig.config'); $parameters['debug'] = TRUE; $container->setParameter('twig.config', $parameters); } /** * Tests that Twig extension loads appropriately. */ public function testTwigExtensionLoaded() { $twig_service = \Drupal::service('twig'); $extension = $twig_service->getExtension('devel_debug'); $this->assertEquals(get_class($extension), Debug::class, 'Debug Extension loaded successfully.'); } /** * Tests that the Twig dump functions are registered properly. */ public function testDumpFunctionsRegistered() { /** @var \Twig_SimpleFunction[] $functions */ $functions = \Drupal::service('twig')->getFunctions(); $dump_functions = ['devel_dump', 'kpr']; $message_functions = ['devel_message', 'dpm', 'dsm']; $registered_functions = $dump_functions + $message_functions; foreach ($registered_functions as $name) { $function = $functions[$name]; $this->assertTrue($function instanceof \Twig_SimpleFunction); $this->assertEquals($function->getName(), $name); $this->assertTrue($function->needsContext()); $this->assertTrue($function->needsEnvironment()); $this->assertTrue($function->isVariadic()); is_callable($function->getCallable(), TRUE, $callable); if (in_array($name, $dump_functions)) { $this->assertEquals($callable, 'Drupal\devel\Twig\Extension\Debug::dump'); } else { $this->assertEquals($callable, 'Drupal\devel\Twig\Extension\Debug::message'); } } } /** * Tests that the Twig function for XDebug integration is registered properly. */ public function testXDebugIntegrationFunctionsRegistered() { /** @var \Twig_SimpleFunction $function */ $function = \Drupal::service('twig')->getFunction('devel_breakpoint'); $this->assertTrue($function instanceof \Twig_SimpleFunction); $this->assertEquals($function->getName(), 'devel_breakpoint'); $this->assertTrue($function->needsContext()); $this->assertTrue($function->needsEnvironment()); $this->assertTrue($function->isVariadic()); is_callable($function->getCallable(), TRUE, $callable); $this->assertEquals($callable, 'Drupal\devel\Twig\Extension\Debug::breakpoint'); } /** * Tests that the Twig extension's dump functions produce the expected output. */ public function testDumpFunctions() { $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump() }}'; $expected_template_output = 'test-with-context context! first value second value'; $context = [ 'twig_string' => 'context!', 'twig_array' => [ 'first' => 'first value', 'second' => 'second value', ], 'twig_object' => new \stdClass(), ]; /** @var \Drupal\Core\Template\TwigEnvironment $environment */ $environment = \Drupal::service('twig'); // Ensures that the twig extension does nothing if the current // user has not the adequate permission. $this->assertTrue($environment->isDebug()); $this->assertEquals($environment->renderInline($template, $context), $expected_template_output); \Drupal::currentUser()->setAccount($this->develUser); // Ensures that if no argument is passed to the function the twig context is // dumped. $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $this->assertContainsDump($output, $context, 'Twig context'); // Ensures that if an argument is passed to the function it is dumped. $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump(twig_array) }}'; $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $this->assertContainsDump($output, $context['twig_array']); // Ensures that if more than one argument is passed the function works // properly and every argument is dumped separately. $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_dump(twig_string, twig_array.first, twig_array, twig_object) }}'; $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $this->assertContainsDump($output, $context['twig_string']); $this->assertContainsDump($output, $context['twig_array']['first']); $this->assertContainsDump($output, $context['twig_array']); $this->assertContainsDump($output, $context['twig_object']); // Clear messages. drupal_get_messages(); $retrieve_message = function ($messages, $index) { return isset($messages['status'][$index]) ? (string) $messages['status'][$index] : NULL; }; // Ensures that if no argument is passed to the function the twig context is // dumped. $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message() }}'; $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $messages = drupal_get_messages(); $this->assertDumpExportEquals($retrieve_message($messages, 0), $context, 'Twig context'); // Ensures that if an argument is passed to the function it is dumped. $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message(twig_array) }}'; $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $messages = drupal_get_messages(); $this->assertDumpExportEquals($retrieve_message($messages, 0), $context['twig_array']); // Ensures that if more than one argument is passed to the function works // properly and every argument is dumped separately. $template = 'test-with-context {{ twig_string }} {{ twig_array.first }} {{ twig_array.second }}{{ devel_message(twig_string, twig_array.first, twig_array, twig_object) }}'; $output = (string) $environment->renderInline($template, $context); $this->assertContains($expected_template_output, $output); $messages = drupal_get_messages(); $this->assertDumpExportEquals($retrieve_message($messages, 0), $context['twig_string']); $this->assertDumpExportEquals($retrieve_message($messages, 1), $context['twig_array']['first']); $this->assertDumpExportEquals($retrieve_message($messages, 2), $context['twig_array']); $this->assertDumpExportEquals($retrieve_message($messages, 3), $context['twig_object']); } }
rekhajethani/d8.dev
web/modules/devel/tests/src/Kernel/DevelTwigExtensionTest.php
PHP
gpl-2.0
7,917
<?php /** * @file * Contains \Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase. */ namespace Drupal\Core\Field\Plugin\Field\FieldFormatter; use Drupal\Core\Field\AllowedTagsXssTrait; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Form\FormStateInterface; /** * Parent plugin for decimal and integer formatters. */ abstract class NumericFormatterBase extends FormatterBase { use AllowedTagsXssTrait; /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $options = array( '' => t('- None -'), '.' => t('Decimal point'), ',' => t('Comma'), ' ' => t('Space'), chr(8201) => t('Thin space'), "'" => t('Apostrophe'), ); $elements['thousand_separator'] = array( '#type' => 'select', '#title' => t('Thousand marker'), '#options' => $options, '#default_value' => $this->getSetting('thousand_separator'), '#weight' => 0, ); $elements['prefix_suffix'] = array( '#type' => 'checkbox', '#title' => t('Display prefix and suffix'), '#default_value' => $this->getSetting('prefix_suffix'), '#weight' => 10, ); return $elements; } /** * {@inheritdoc} */ public function settingsSummary() { $summary = array(); $summary[] = $this->numberFormat(1234.1234567890); if ($this->getSetting('prefix_suffix')) { $summary[] = t('Display with prefix and suffix.'); } return $summary; } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $elements = array(); $settings = $this->getFieldSettings(); foreach ($items as $delta => $item) { $output = $this->numberFormat($item->value); // Account for prefix and suffix. if ($this->getSetting('prefix_suffix')) { $prefixes = isset($settings['prefix']) ? array_map(array('Drupal\Core\Field\FieldFilteredMarkup', 'create'), explode('|', $settings['prefix'])) : array(''); $suffixes = isset($settings['suffix']) ? array_map(array('Drupal\Core\Field\FieldFilteredMarkup', 'create'), explode('|', $settings['suffix'])) : array(''); $prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0]; $suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0]; $output = $prefix . $output . $suffix; } // Output the raw value in a content attribute if the text of the HTML // element differs from the raw value (for example when a prefix is used). if (isset($item->_attributes) && $item->value != $output) { $item->_attributes += array('content' => $item->value); } $elements[$delta] = array('#markup' => $output); } return $elements; } /** * Formats a number. * * @param mixed $number * The numeric value. * * @return string * The formatted number. */ abstract protected function numberFormat($number); }
nrackleff/capstone
web/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/NumericFormatterBase.php
PHP
gpl-2.0
3,132
var assert = require('assert'); var Kareem = require('../'); describe('execPre', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('handles errors with multiple pres', function(done) { var execed = {}; hooks.pre('cook', function(done) { execed.first = true; done(); }); hooks.pre('cook', function(done) { execed.second = true; done('error!'); }); hooks.pre('cook', function(done) { execed.third = true; done(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { done('other error!'); }, 10); next(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next()', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 15); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 5); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next() when already done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 25); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('async pres with clone()', function(done) { var execed = false; hooks.pre('cook', true, function(next, done) { execed = true; setTimeout( function() { done(); }, 5); next(); }); hooks.clone().execPre('cook', null, function(err) { assert.ifError(err); assert.ok(execed); done(); }); }); it('returns correct error when async pre errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', function(next) { execed.second = true; setTimeout( function() { next('error!'); }, 15); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('lets async pres run when fully sync pres are done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done(); }, 5); next(); }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('allows passing arguments to the next pre', function(done) { var execed = {}; hooks.pre('cook', function(next) { execed.first = true; next(null, 'test'); }); hooks.pre('cook', function(next, p) { execed.second = true; assert.equal(p, 'test'); next(); }); hooks.pre('cook', function(next, p) { execed.third = true; assert.ok(!p); next(); }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(3, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); assert.ok(execed.third); done(); }); }); }); describe('execPreSync', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('executes hooks synchronously', function() { var execed = {}; hooks.pre('cook', function() { execed.first = true; }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPreSync('cook', null); assert.ok(execed.first); assert.ok(execed.second); }); it('works with no hooks specified', function() { assert.doesNotThrow(function() { hooks.execPreSync('cook', null); }); }); });
ChrisChenSZ/code
表单注册验证/node_modules/kareem/test/pre.test.js
JavaScript
apache-2.0
5,771
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "os" "github.com/spf13/pflag" "k8s.io/apiserver/pkg/server/healthz" "k8s.io/apiserver/pkg/util/flag" "k8s.io/apiserver/pkg/util/logs" "k8s.io/kubernetes/federation/cmd/federation-controller-manager/app" "k8s.io/kubernetes/federation/cmd/federation-controller-manager/app/options" _ "k8s.io/kubernetes/pkg/util/workqueue/prometheus" // for workqueue metric registration "k8s.io/kubernetes/pkg/version/verflag" ) func init() { healthz.DefaultHealthz() } func main() { s := options.NewCMServer() s.AddFlags(pflag.CommandLine) flag.InitFlags() logs.InitLogs() defer logs.FlushLogs() verflag.PrintAndExitIfRequested() if err := app.Run(s); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } }
sspeiche/origin
vendor/k8s.io/kubernetes/federation/cmd/federation-controller-manager/controller-manager.go
GO
apache-2.0
1,328
<?php namespace Illuminate\Foundation\Console; use Exception; use Illuminate\Support\Collection; use Illuminate\Foundation\Application; use Illuminate\Database\Eloquent\Model; use Symfony\Component\VarDumper\Caster\Caster; class IlluminateCaster { /** * Illuminate application methods to include in the presenter. * * @var array */ private static $appProperties = [ 'configurationIsCached', 'environment', 'environmentFile', 'isLocal', 'routesAreCached', 'runningUnitTests', 'version', 'path', 'basePath', 'configPath', 'databasePath', 'langPath', 'publicPath', 'storagePath', 'bootstrapPath', ]; /** * Get an array representing the properties of an application. * * @param \Illuminate\Foundation\Application $app * @return array */ public static function castApplication(Application $app) { $results = []; foreach (self::$appProperties as $property) { try { $val = $app->$property(); if (! is_null($val)) { $results[Caster::PREFIX_VIRTUAL.$property] = $val; } } catch (Exception $e) { // } } return $results; } /** * Get an array representing the properties of a collection. * * @param \Illuminate\Support\Collection $collection * @return array */ public static function castCollection(Collection $collection) { return [ Caster::PREFIX_VIRTUAL.'all' => $collection->all(), ]; } /** * Get an array representing the properties of a model. * * @param \Illuminate\Database\Eloquent\Model $model * @return array */ public static function castModel(Model $model) { $attributes = array_merge( $model->getAttributes(), $model->getRelations() ); $visible = array_flip( $model->getVisible() ?: array_diff(array_keys($attributes), $model->getHidden()) ); $results = []; foreach (array_intersect_key($attributes, $visible) as $key => $value) { $results[(isset($visible[$key]) ? Caster::PREFIX_VIRTUAL : Caster::PREFIX_PROTECTED).$key] = $value; } return $results; } }
gayathma/footballs
vendor/laravel/framework/src/Illuminate/Foundation/Console/IlluminateCaster.php
PHP
gpl-3.0
2,431
var s = `a b c`; assert.equal(s, 'a\n b\n c');
oleksandr-minakov/northshore
ui/node_modules/es6-templates/test/examples/multi-line.js
JavaScript
apache-2.0
61
// { dg-do assemble } // Copyright (C) 2000 Free Software Foundation // Contributed by Kriang Lerdsuwanakij <lerdsuwa@users.sourceforge.net> // Bug: We used reject template unification of two bound template template // parameters. template <class T, class U=int> class C { }; template <class T, class U> void f(C<T,U> c) { } template <class T> void f(C<T> c) { } template <template<class,class=int> class C, class T, class U> void g(C<T,U> c) { } template <template<class,class=int> class C, class T> void g(C<T> c) { } int main() { C<int,char> c1; f(c1); g(c1); C<int,int> c2; f(c2); g(c2); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.pt/ttp65.C
C++
gpl-2.0
615
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var reload = browserSync.reload; var src = { scss: 'app/scss/*.scss', css: 'app/css', html: 'app/*.html' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { browserSync({ server: "./app" }); gulp.watch(src.scss, ['sass']); gulp.watch(src.html).on('change', reload); }); // Compile sass into CSS gulp.task('sass', function() { return gulp.src(src.scss) .pipe(sass()) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); gulp.task('default', ['serve']);
yuyang545262477/Resume
项目二电商首页/node_modules/bs-recipes/recipes/gulp.sass/gulpfile.js
JavaScript
mit
691
// Validate.js 0.1.1 // (c) 2013 Wrapp // Validate.js may be freely distributed under the MIT license. // For all details and documentation: // http://validatejs.org/ (function(exports, module) { "use strict"; // The main function that calls the validators specified by the constraints. // The options are the following: // var validate = function(attributes, constraints, options) { var attr , error , validator , validatorName , validatorOptions , value , validators , errors = {}; options = options || {}; // Loops through each constraints, finds the correct validator and run it. for (attr in constraints) { value = attributes[attr]; validators = v.result(constraints[attr], value, attributes, attr); for (validatorName in validators) { validator = v.validators[validatorName]; if (!validator) { error = v.format("Unknown validator %{name}", {name: validatorName}); throw new Error(error); } validatorOptions = validators[validatorName]; // This allows the options to be a function. The function will be called // with the value, attribute name and the complete dict of attribues. // This is useful when you want to have different validations depending // on the attribute value. validatorOptions = v.result(validatorOptions, value, attributes, attr); if (!validatorOptions) continue; error = validator.call(validator, value, validatorOptions, attr, attributes); // The validator is allowed to return a string or an array. if (v.isString(error)) error = [error]; if (error && error.length > 0) errors[attr] = (errors[attr] || []).concat(error); } } // Return the errors if we have any for (attr in errors) return v.fullMessages(errors, options); }; var v = validate , root = this , XDate = root.XDate // Finds %{key} style patterns in the given string , FORMAT_REGEXP = /%\{([^\}]+)\}/g; // Copies over attributes from one or more sources to a single destination. // Very much similar to underscore's extend. // The first argument is the target object and the remaining arguments will be // used as targets. v.extend = function(obj) { var i , attr , source , sources = [].slice.call(arguments, 1); for (i = 0; i < sources.length; ++i) { source = sources[i]; for (attr in source) obj[attr] = source[attr]; } return obj; }; v.extend(validate, { // If the given argument is a call: function the and: function return the value // otherwise just return the value. Additional arguments will be passed as // arguments to the function. // Example: // ``` // result('foo') // 'foo' // result(Math.max, 1, 2) // 2 // ``` result: function(value) { var args = [].slice.call(arguments, 1); if (typeof value === 'function') value = value.apply(null, args); return value; }, // Checks if the value is a number. This function does not consider NaN a // number like many other `isNumber` functions do. isNumber: function(value) { return typeof value === 'number' && !isNaN(value); }, // A simple check to verify that the value is an integer. Uses `isNumber` // and a simple modulo check. isInteger: function(value) { return v.isNumber(value) && value % 1 === 0; }, // Uses the `Object` function to check if the given argument is an object. isObject: function(obj) { return obj === Object(obj); }, // Returns false if the object is `null` of `undefined` isDefined: function(obj) { return obj !== null && obj !== undefined; }, // Formats the specified strings with the given values like so: // ``` // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar" // ``` format: function(str, vals) { return str.replace(FORMAT_REGEXP, function(m0, m1) { return String(vals[m1]); }); }, // "Prettifies" the given string. // Prettifying means replacing - and _ with spaces as well as splitting // camel case words. prettify: function(str) { return str // Replaces - and _ with spaces .replace(/[_\-]/g, ' ') // Splits camel cased words .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) { return "" + m1 + " " + m2.toLowerCase(); }) .toLowerCase(); }, isString: function(value) { return typeof value === 'string'; }, isArray: function(value) { return {}.toString.call(value) === '[object Array]'; }, contains: function(obj, value) { var i; if (!v.isDefined(obj)) return false; if (v.isArray(obj)) { if (obj.indexOf(value)) return obj.indexOf(value) !== -1; for (i = obj.length - 1; i >= 0; --i) { if (obj[i] === value) return true; } return false; } return value in obj; }, capitalize: function(str) { if (!str) return str; return str[0].toUpperCase() + str.slice(1); }, fullMessages: function(errors, options) { options = options || {}; var ret = options.flatten ? [] : {} , attr , i , error; if (!errors) return ret; // Converts the errors of object of the format // {attr: [<error>, <error>, ...]} to contain the attribute name. for (attr in errors) { for (i = 0; i < errors[attr].length; ++i) { error = errors[attr][i]; if (error[0] === '^') error = error.slice(1); else if (options.fullMessages !== false) { error = v.format("%{attr} %{message}", { attr: v.capitalize(v.prettify(attr)), message: error }); } error = error.replace(/\\\^/g, "^"); // If flatten is true a flat array is returned. if (options.flatten) ret.push(error); else (ret[attr] || (ret[attr] = [])).push(error); } } return ret; }, }); validate.validators = { // Presence validates that the value isn't empty presence: function(value, options) { var message = options.message || "can't be blank" , attr; // Null and undefined aren't allowed if (!v.isDefined(value)) return message; if (typeof value === 'string') { // Tests if the string contains only whitespace (tab, newline, space etc) if ((/^\s*$/).test(value)) return message; } else if (v.isArray(value)) { // For arrays we use the length property if (value.length === 0) return message; } else if (v.isObject(value)) { // If we find at least one property we consider it non empty for (attr in value) return; return message; } }, length: function(value, options) { // Null and undefined are fine if (!v.isDefined(value)) return; var is = options.is , maximum = options.maximum , minimum = options.minimum , tokenizer = options.tokenizer || function(val) { return val; } , err , errors = []; value = tokenizer(value); // Is checks if (v.isNumber(is) && value.length !== is) { err = options.wrongLength || "is the wrong length (should be %{count} characters)"; errors.push(v.format(err, {count: is})); } if (v.isNumber(minimum) && value.length < minimum) { err = options.tooShort || "is too short (minimum is %{count} characters)"; errors.push(v.format(err, {count: minimum})); } if (v.isNumber(maximum) && value.length > maximum) { err = options.tooLong || "is too long (maximum is %{count} characters)"; errors.push(v.format(err, {count: maximum})); } if (errors.length > 0) return options.message || errors; }, numericality: function(value, options) { if (!v.isDefined(value)) return; var errors = [] , name , count , checks = { greaterThan: function(v, c) { return v > c; }, greaterThanOrEqualTo: function(v, c) { return v >= c; }, equalTo: function(v, c) { return v === c; }, lessThan: function(v, c) { return v < c; }, lessThanOrEqualTo: function(v, c) { return v <= c; } }; // Coerce the value to a number unless we're being strict. if (options.noStrings !== true && v.isString(value)) value = +value; // If it's not a number we shouldn't continue since it will compare it. if (!v.isNumber(value)) return options.message || "is not a number"; // Same logic as above, sort of. Don't bother with comparisons if this // doesn't pass. if (options.onlyInteger && !v.isInteger(value)) return options.message || "must be an integer"; for (name in checks) { count = options[name]; if (v.isNumber(count) && !checks[name](value, count)) { errors.push(v.format("must be %{type} %{count}", { count: count, type: v.prettify(name) })); } } if (options.odd && value % 2 !== 1) errors.push("must be odd"); if (options.even && value % 2 !== 0) errors.push("must be even"); if (errors.length) return options.message || errors; }, datetime: v.extend(function(value, options) { if (!v.isDefined(value)) return; var err , errors = [] , message = options.message , earliest = options.earliest ? this.parse(options.earliest, options) : NaN , latest = options.latest ? this.parse(options.latest, options) : NaN; value = this.parse(value, options); if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) return message || "must be a valid date"; if (!isNaN(earliest) && value < earliest) { err = "must be no earlier than %{date}"; err = v.format(err, {date: this.format(earliest, options)}); errors.push(err); } if (!isNaN(latest) && value > latest) { err = "must be no later than %{date}"; err = v.format(err, {date: this.format(latest, options)}); errors.push(err); } if (errors.length) return options.message || errors; }, { // This is the function that will be used to convert input to the number // of millis since the epoch. // It should return NaN if it's not a valid date. parse: function(value, options) { return new XDate(value, true).getTime(); }, // Formats the given timestamp. Uses ISO8601 to format them. // If options.dateOnly is true then only the year, month and day will be // output. format: function(date, options) { var format = options.dateFormat || (options.dateOnly ? "yyyy-MM-dd" : "u"); return new XDate(date, true).toString(format); } }), date: function(value, options) { options = v.extend({}, options, {onlyDate: true}); return v.validators.datetime(value, options); }, format: function(value, options) { if (v.isString(options) || (options instanceof RegExp)) options = {pattern: options}; var message = options.message || "is invalid" , pattern = options.pattern , match; if (!v.isDefined(value)) return; if (!v.isString(value)) return message; if (v.isString(pattern)) pattern = new RegExp(options.pattern, options.flags); match = pattern.exec(value); if (!match || match[0].length != value.length) return message; }, inclusion: function(value, options) { if (v.isArray(options)) options = {within: options}; if (!v.isDefined(value)) return; if (v.contains(options.within, value)) return; var message = options.message || "^%{value} is not included in the list"; return v.format(message, {value: value}); }, exclusion: function(value, options) { if (v.isArray(options)) options = {within: options}; if (!v.isDefined(value)) return; if (!v.contains(options.within, value)) return; var message = options.message || "^%{value} is restricted"; return v.format(message, {value: value}); } }; if (exports) { if (module && module.exports) exports = module.exports = validate; exports.validate = validate; } else root.validate = validate; }).call(this, typeof exports !== 'undefined' ? exports : null, typeof module !== 'undefined' ? module : null);
Piicksarn/cdnjs
ajax/libs/validate.js/0.1.1/validate.js
JavaScript
mit
12,865
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["sourceMap"] = factory(); else root["sourceMap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; exports.SourceNode = __webpack_require__(10).SourceNode; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ = __webpack_require__(2); var util = __webpack_require__(4); var ArraySet = __webpack_require__(5).ArraySet; var MappingList = __webpack_require__(6).MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = '' if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. 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. */ var base64 = __webpack_require__(3); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; /***/ }), /* 3 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; /***/ }), /* 4 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '<dir>/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(4); var binarySearch = __webpack_require__(8); var ArraySet = __webpack_require__(5).ArraySet; var base64VLQ = __webpack_require__(2); var quickSort = __webpack_require__(9).quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function(aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } if (!this._sources.has(needle.source)) { return []; } needle.source = this._sources.indexOf(needle.source); var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util.relative(this.sourceRoot, source); } if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; } source = this._sources.indexOf(source); var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); if (section.consumer.sourceRoot !== null) { source = util.join(section.consumer.sourceRoot, source); } this._sources.add(source); source = this._sources.indexOf(source); var name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; /***/ }), /* 8 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; /***/ }), /* 9 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ exports.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; var util = __webpack_require__(4); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; /***/ }) /******/ ]) }); ;
hellokidder/js-studying
微信小程序/wxtest/node_modules/source-map/dist/source-map.js
JavaScript
mit
101,940
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!appengine,!gccgo package intsets func popcnt(x word) int func havePOPCNT() bool var hasPOPCNT = havePOPCNT() // popcount returns the population count (number of set bits) of x. func popcount(x word) int { if hasPOPCNT { return popcnt(x) } return popcountTable(x) // faster than Hacker's Delight }
muzining/net
x/tools/container/intsets/popcnt_amd64.go
GO
bsd-3-clause
483