max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,360
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Garfieldpp(CMakePackage): """Garfield++ is a toolkit for the detailed simulation of particle detectors based on ionisation measurement in gases and semiconductors. """ homepage = "https://garfieldpp.web.cern.ch/garfieldpp/" url = "https://gitlab.cern.ch/garfield/garfieldpp/-/archive/4.0/garfieldpp-4.0.tar.gz" git = "https://gitlab.cern.ch/garfield/garfieldpp.git" tags = ['hep'] maintainers = ['mirguest'] variant('examples', default=False, description="Build garfield examples") version('master', branch='master') version('4.0', sha256='82bc1f0395213bd30a7cd854426e6757d0b4155e99ffd4405355c9648fa5ada3') version('3.0', sha256='c1282427a784658bc38b71c8e8cfc8c9f5202b185f0854d85f7c9c5a747c5406') depends_on('root') depends_on('gsl') depends_on('geant4', when='+examples') def cmake_args(self): args = [ self.define_from_variant('WITH_EXAMPLES', 'examples') ] return args
489
681
<gh_stars>100-1000 # _____ ______ _____ # / ____/ /\ | ____ | __ \ # | | / \ | |__ | |__) | Caer - Modern Computer Vision # | | / /\ \ | __| | _ / Languages: Python, C, C++, Cuda # | |___ / ____ \ | |____ | | \ \ http://github.com/jasmcaus/caer # \_____\/_/ \_ \______ |_| \_\ # Licensed under the MIT License <http://opensource.org/licenses/MIT> # SPDX-License-Identifier: MIT # Copyright (c) 2020-2021 The Caer Authors <http://github.com/jasmcaus> import numpy as np def _check_target_size(size): """ Common check to enforce type and sanity check on size tuples Args: size: Should be a tuple of size 2 (width, height) Returns: Raises a ValueError if ``size`` doesn't satisfy the required conditions. """ if not isinstance(size, (list, tuple)): raise ValueError("`target_size` must be a tuple of length 2 `(width,height)`") if len(size) != 2: raise ValueError("`target_size` must be a tuple of length 2 `(width,height)`") if size[0] < 0 or size[1] < 0: raise ValueError("Width and height must be >= 0") return True def _check_mean_sub_values(value, channels): """ Checks if mean subtraction values are valid based on the number of channels "value" must be a tuple of dimensions = number of channels Returns boolean: True -> Expression is valid False -> Expression is invalid """ if value is None: raise ValueError("Value(s) specified is of NoneType()") if isinstance(value, tuple): # If not a tuple, we convert it to one try: value = tuple(value) except TypeError: value = tuple([value]) if channels not in [1,3]: raise ValueError("Number of channels must be either 1 (Grayscale) or 3 (RGB/BGR)") if len(value) not in [1,3]: raise ValueError( "Tuple length must be either 1 (subtraction over the entire image) or 3 (per channel subtraction)" f"Got {value}" ) if len(value) == channels: return True else: raise ValueError(f"Expected a tuple of dimension {channels}. Got {value}") def _get_output(array, out, fname, dtype=None, output=None): """ output = _get_output(array, out, fname, dtype=None, output=None) Implements the caer output convention: (1) if `out` is None, return np.empty(array.shape, array.dtype) (2) else verify that output is of right size, shape, and contiguous Parameters ---------- array : Tensor out : Tensor or None fname : str Function name. Used in error messages Returns ------- output : Tensor """ detail = ".\nWhen an output argument is used, the checking is very strict as this is a performance feature." if dtype is None: dtype = array.dtype if output is not None: # pragma: no cover import warnings warnings.warn("Using deprecated `output` argument in function `%s`. Please use `out` in the future. It has exactly the same meaning and it matches what numpy uses." % fname, DeprecationWarning) if out is not None: warnings.warn("Using both `out` and `output` in function `%s`.\ncaer is going to ignore the `output` argument and use the `out` version exclusively." % fname) else: out = output if out is None: return np.empty(array.shape, dtype) if out.dtype != dtype: raise ValueError( "caer.%s: `out` has wrong type (out.dtype is %s; expected %s)%s" % (fname, out.dtype, dtype, detail)) if out.shape != array.shape: raise ValueError(f"caer.{fname}: `out` has wrong shape (got {out.shape}, while expecting {array.shape}){detail}") if not out.flags.contiguous: raise ValueError(f"caer.{fname}: `out` is not c-array{detail}") return out def _get_axis(array, axis, fname): """ axis = _get_axis(array, axis, fname) Checks that ``axis`` is a valid axis of ``array`` and normalises it. Parameters ---------- array : Tensor axis : int fname : str Function name. Used in error messages Returns ------- axis : int The positive index of the axis to use """ if axis < 0: axis += len(array.shape) if not (0 <= axis < len(array.shape)): raise ValueError(f"caer.{fname}: `axis` is out of bounds (maximum was {array.ndim}, got {axis})") return axis def _normalize_sequence(array, value, fname): """ values = _normalize_sequence(array, value, fname) If `value` is a sequence, checks that it has an element for each dimension of `array`. Otherwise, returns a sequence that repeats `value` once for each dimension of array. Parameters ---------- array : Tensor value : sequence or scalar fname : str Function name. Used in error messages Returns ------- values : sequence """ try: value = list(value) except TypeError: return [value for s in array.shape] if len(value) != array.ndim: raise ValueError( f"caer.{fname}: argument is sequence, but has wrong size ({len(value)} " f"for an array of {array.ndim} dimensions)" ) return value def _verify_is_floatingpoint_type(A, function_name): """ _verify_is_integer_type(array, "function") Checks that ``A`` is a floating-point array. If it is not, it raises ``TypeError``. Parameters ---------- A : Tensor function_name : str Used for error messages """ if not np.issubdtype(A.dtype, np.floating): raise TypeError(f"caer.{function_name}: This function only accepts floating-point types (passed array of type {A.dtype})") def _verify_is_integer_type(A, function_name): """ _verify_is_integer_type(array, "function") Checks that ``A`` is an integer array. If it is not, it raises ``TypeError``. Parameters ---------- A : Tensor function_name : str Used for error messages """ k = A.dtype.kind if k not in "iub": # integer, unsigned integer, boolean raise TypeError(f"caer.{function_name}: This function only accepts integer types (passed array of type {A.dtype})") def _verify_is_nonnegative_integer_type(A, function_name): """ _verify_is_nonnegative_integer_type(array, "function") Checks that ``A`` is an unsigned integer array. If it is not, it raises ``TypeError``. Parameters ---------- A : Tensor function_name : str Used for error messages """ _verify_is_integer_type(A, function_name) if A.dtype.kind == "i" and not np.all(A >= 0): raise ValueError( f"caer.{function_name}: This function only accepts positive integer types (passed array of type {A.dtype})" ) def _make_binary(array): """ bin = _make_binary(array) Returns (possibly a copy) of array as a boolean array """ array = np.asanyarray(array) if array.dtype != bool: return (array != 0) return array def _as_floating_point_array(array): """ array = _as_floating_point_array(array) Returns (possibly a copy) of array as a floating-point array """ array = np.asanyarray(array) if not np.issubdtype(array.dtype, np.floating): return array.astype(np.double) return array def _check_3(arr, funcname): if arr.ndim != 3 or arr.shape[2] != 3: raise ValueError( f"caer.{funcname}: this function expects an array of shape (h, w, 3), " f"received an array of shape {arr.shape}." ) def _check_2(arr, funcname): if arr.ndim != 2: raise ValueError(f"caer.{funcname}: this function can only handle 2D arrays (passed array with shape {arr.shape}).")
3,140
808
<reponame>stjordanis/symengine #include "catch.hpp" #include <symengine/add.h> #include <symengine/pow.h> #include <symengine/eval_mpc.h> #include <symengine/eval_mpfr.h> #include <symengine/symengine_exception.h> #include <symengine/real_double.h> #include <symengine/constants.h> using SymEngine::abs; using SymEngine::acos; using SymEngine::acosh; using SymEngine::acot; using SymEngine::acoth; using SymEngine::acsc; using SymEngine::acsch; using SymEngine::asec; using SymEngine::asech; using SymEngine::asin; using SymEngine::asinh; using SymEngine::atan; using SymEngine::atanh; using SymEngine::Basic; using SymEngine::Catalan; using SymEngine::constant; using SymEngine::cos; using SymEngine::cosh; using SymEngine::cot; using SymEngine::coth; using SymEngine::csc; using SymEngine::csch; using SymEngine::E; using SymEngine::EulerGamma; using SymEngine::eval_mpc; using SymEngine::gamma; using SymEngine::GoldenRatio; using SymEngine::I; using SymEngine::integer; using SymEngine::mul; using SymEngine::NotImplementedError; using SymEngine::one; using SymEngine::pi; using SymEngine::pow; using SymEngine::print_stack_on_segfault; using SymEngine::RCP; using SymEngine::real_double; using SymEngine::sec; using SymEngine::sech; using SymEngine::sin; using SymEngine::sinh; using SymEngine::sub; using SymEngine::SymEngineException; using SymEngine::tan; using SymEngine::tanh; TEST_CASE("eval: eval_mpc", "[eval_mpc]") { mpc_t a, b; mpfr_t real, imag; mpc_init2(a, 100); mpc_init2(b, 100); mpfr_init2(real, 100); mpfr_init2(imag, 100); RCP<const Basic> s = add(one, cos(integer(2))); RCP<const Basic> t = sin(integer(2)); RCP<const Basic> r = add(pow(E, mul(integer(2), I)), one); RCP<const Basic> arg1 = add(integer(2), mul(integer(3), I)); RCP<const Basic> arg2 = add(integer(4), mul(integer(5), I)); eval_mpc(a, *r, MPFR_RNDN); eval_mpfr(real, *s, MPFR_RNDN); eval_mpfr(imag, *t, MPFR_RNDN); mpc_set_fr_fr(b, real, imag, MPFR_RNDN); REQUIRE(mpc_cmp(a, b) == 0); std::vector<std::tuple<RCP<const Basic>, double, double>> testvec = { std::make_tuple(sin(arg1), 10.0590576035560, 10.0590576035561), std::make_tuple(cos(arg1), 10.0265146611769, 10.0265146611770), std::make_tuple(tan(arg1), 1.00324568840508, 1.00324568840509), std::make_tuple(csc(arg1), 0.09941289128779, 0.09941289128780), std::make_tuple(sec(arg1), 0.09973555455636, 0.09973555455637), std::make_tuple(cot(arg1), 0.99676481200707, 0.99676481200708), std::make_tuple(asin(arg1), 2.06384803478709, 2.06384803478710), std::make_tuple(acos(arg2), 2.70606901402754, 2.70606901402755), std::make_tuple(atan(arg1), 1.42840878608958, 1.42840878608959), std::make_tuple(acsc(arg1), 0.275919504119167, 0.275919504119168), std::make_tuple(asec(arg1), 1.439125555072813, 1.439125555072814), std::make_tuple(acot(arg2), 0.156440457398915, 0.156440457398916), std::make_tuple(sinh(arg1), 3.629604837263012, 3.629604837263013), std::make_tuple(cosh(arg2), 27.2913914057446, 27.2913914057447), std::make_tuple(tanh(arg1), 0.9654364796739529, 0.9654364796739530), std::make_tuple(csch(arg1), 0.275512085980707, 0.275512085980708), std::make_tuple(sech(arg1), 0.2659894183968419, 0.2659894183968420), std::make_tuple(coth(arg2), 0.999437204152625, 0.999437204152626), std::make_tuple(asinh(arg1), 2.19228221563667, 2.19228221563668), std::make_tuple(acosh(arg1), 2.22128593746801, 2.22128593746802), std::make_tuple(atanh(arg2), 1.45151270206482, 1.45151270206483), std::make_tuple(acsch(arg2), 0.156308000814648, 0.156308000814649), std::make_tuple(acoth(arg2), 0.155883315867942, 0.155883315867943), std::make_tuple(asech(arg1), 1.43912555507281, 1.43912555507282), std::make_tuple(log(arg1), 1.615742802564794, 1.615742802564795), std::make_tuple(abs(mul(arg1, arg2)), 23.086792761230, 23.086792761231), std::make_tuple(abs(arg1), 3.605551275463989, 3.605551275463990), }; for (unsigned i = 0; i < testvec.size(); i++) { eval_mpc(a, *std::get<0>(testvec[i]), MPFR_RNDN); mpc_abs(real, a, MPFR_RNDN); REQUIRE(mpfr_cmp_d(real, std::get<1>(testvec[i])) == 1); REQUIRE(mpfr_cmp_d(real, std::get<2>(testvec[i])) == -1); } r = add(one, mul(EulerGamma, I)); s = one; t = EulerGamma; eval_mpc(a, *r, MPFR_RNDN); eval_mpfr(real, *s, MPFR_RNDN); eval_mpfr(imag, *t, MPFR_RNDN); mpc_set_fr_fr(b, real, imag, MPFR_RNDN); REQUIRE(mpc_cmp(a, b) == 0); r = add(one, mul(Catalan, I)); s = one; t = Catalan; eval_mpc(a, *r, MPFR_RNDN); eval_mpfr(real, *s, MPFR_RNDN); eval_mpfr(imag, *t, MPFR_RNDN); mpc_set_fr_fr(b, real, imag, MPFR_RNDN); REQUIRE(mpc_cmp(a, b) == 0); r = add(one, mul(GoldenRatio, I)); s = one; t = GoldenRatio; eval_mpc(a, *r, MPFR_RNDN); eval_mpfr(real, *s, MPFR_RNDN); eval_mpfr(imag, *t, MPFR_RNDN); mpc_set_fr_fr(b, real, imag, MPFR_RNDN); REQUIRE(mpc_cmp(a, b) == 0); r = add(one, mul(E, I)); s = one; t = E; eval_mpc(a, *r, MPFR_RNDN); eval_mpfr(real, *s, MPFR_RNDN); eval_mpfr(imag, *t, MPFR_RNDN); mpc_set_fr_fr(b, real, imag, MPFR_RNDN); REQUIRE(mpc_cmp(a, b) == 0); CHECK_THROWS_AS(eval_mpc(a, *constant("dummy_constant"), MPFR_RNDN), NotImplementedError &); CHECK_THROWS_AS(eval_mpc(a, *gamma(arg1), MPFR_RNDN), NotImplementedError &); r = erf(add(one, mul(integer(2), I))); CHECK_THROWS_AS(eval_mpc(a, *r, MPFR_RNDN), NotImplementedError &); r = erfc(add(one, mul(integer(2), I))); CHECK_THROWS_AS(eval_mpc(a, *r, MPFR_RNDN), NotImplementedError &); mpfr_clear(real); mpfr_clear(imag); mpc_clear(a); mpc_clear(b); }
2,924
703
{ "article": { "title": "My new Article title", "author": "<NAME>", "tags": "This Post, Has Been Tagged", "body_html": "<h1>I like articles</h1>\n<p><strong>Yea</strong>, I like posting them through <span class=\"caps\">REST</span>.</p>", "published_at": "Thu Mar 24 15:45:47 UTC 2011", "image": { "src": "http://example.com/rails_logo.gif" } } }
163
1,056
/* * 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.netbeans.modules.maven.pom; import org.codehaus.plexus.util.StringOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.netbeans.modules.maven.model.Utilities; import org.netbeans.modules.maven.model.pom.Configuration; import org.netbeans.modules.maven.model.pom.DistributionManagement; import org.netbeans.modules.maven.model.pom.MailingList; import org.netbeans.modules.maven.model.pom.POMExtensibilityElement; import org.netbeans.modules.maven.model.pom.POMModel; import org.netbeans.modules.maven.model.pom.POMModelFactory; import org.netbeans.modules.maven.model.pom.Parent; import org.netbeans.modules.maven.model.pom.Plugin; import org.netbeans.modules.maven.model.pom.PluginExecution; import org.netbeans.modules.maven.model.pom.Project; import org.netbeans.modules.maven.model.pom.Properties; import org.netbeans.modules.maven.model.settings.Settings; import org.netbeans.modules.maven.model.settings.SettingsModel; import org.netbeans.modules.maven.model.settings.SettingsModelFactory; import org.netbeans.modules.xml.xam.ModelSource; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; /** * * @author mkleint */ public class ModelTest extends TestCase { public ModelTest(String name) { super(name); } public void testModelWrite() throws Exception { ModelSource source = createModelSource("sample.pom"); try { POMModel model = POMModelFactory.getDefault().getModel(source); assertNotNull(model.getRootComponent()); Project prj = model.getProject(); Parent parent = prj.getPomParent(); assertNotNull(parent); assertNotNull(parent.getGroupId()); assertEquals("org.codehaus.mojo", parent.getGroupId()); model.startTransaction(); parent.setGroupId("foo.bar"); model.endTransaction(); assertEquals("foo.bar", parent.getGroupId()); //this test fails here.. cannot rollback single property changes.. model.startTransaction(); parent.setGroupId("bar.foo"); model.rollbackTransaction(); assertEquals("foo.bar", parent.getGroupId()); } finally { File file = source.getLookup().lookup(File.class); file.deleteOnExit(); } } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // public void testModel() throws Exception { ModelSource source = createModelSource("sample.pom"); try { POMModel model = POMModelFactory.getDefault().getModel(source); assertNotNull(model.getRootComponent()); Project prj = model.getProject(); assertNotNull(prj); Parent parent = prj.getPomParent(); assertNotNull(parent); assertNotNull(parent.getGroupId()); assertEquals("org.codehaus.mojo", parent.getGroupId()); List<MailingList> lists = prj.getMailingLists(); assertEquals(3, lists.size()); for (MailingList lst : lists) { assertNotNull(lst); } Properties props = prj.getProperties(); assertNotNull(props); String val1 = props.getProperty("prop1"); assertEquals("foo", val1); String val2 = props.getProperty("prop2"); assertEquals("bar", val2); Map<String, String> p = props.getProperties(); assertEquals(2, p.size()); assertEquals("foo", p.get("prop1")); assertEquals("bar", p.get("prop2")); List<Plugin> plugins = prj.getBuild().getPlugins(); assertNotNull(plugins); assertEquals(4, plugins.size()); Plugin plug = plugins.get(1); assertEquals("modello-maven-plugin", plug.getArtifactId()); Configuration config = plug.getConfiguration(); assertNotNull(config); List<POMExtensibilityElement> lst = config.getConfigurationElements(); assertEquals(2, lst.size()); POMExtensibilityElement el = lst.get(1); assertEquals("version", el.getQName().getLocalPart()); assertEquals("1.0.0", el.getElementText()); List<PluginExecution> execs = plug.getExecutions(); assertNotNull(execs); PluginExecution ex = execs.get(0); assertEquals("build", ex.getId()); String[] goals = new String[]{ "xpp3-reader", "java", "xdoc", "xsd" }; assertEquals(Arrays.asList(goals), ex.getGoals()); DistributionManagement dm = prj.getDistributionManagement(); assertEquals("dav:https://dav.codehaus.org/repository/mojo/", dm.getRepository().getUrl()); assertEquals("dav:https://dav.codehaus.org/snapshots.repository/mojo/", dm.getSnapshotRepository().getUrl()); assertEquals("dav:https://dav.codehaus.org/mojo/nbm-maven-plugin", dm.getSite().getUrl()); // model.startTransaction(); // try { // parent.setGroupId("XXX"); // assertEquals("XXX", parent.getGroupId()); // } finally { // model.endTransaction(); // } } finally { File file = source.getLookup().lookup(File.class); file.deleteOnExit(); } } public void testSettings() throws Exception { ModelSource source = createModelSource("settings.xml"); try { assertTrue(source.isEditable()); SettingsModel model = SettingsModelFactory.getDefault().getModel(source); assertNotNull(model.getRootComponent()); Settings prj = model.getSettings(); assertNotNull(prj); List<org.netbeans.modules.maven.model.settings.Profile> profiles = prj.getProfiles(); assertNotNull(profiles); assertNotNull(prj.findProfileById("mkleint")); List<String> actives = prj.getActiveProfiles(); assertNotNull(actives); assertEquals("mkleint", actives.get(0)); } finally { File file = source.getLookup().lookup(File.class); file.deleteOnExit(); } } private ModelSource createModelSource(String templateName) throws FileNotFoundException, IOException, URISyntaxException { URL url = getClass().getClassLoader().getResource(templateName); File templateFile = org.openide.util.Utilities.toFile(url.toURI()); assertTrue(templateFile.exists()); FileObject fo = FileUtil.toFileObject(templateFile); FileInputStream str = new FileInputStream(templateFile); StringOutputStream out = new StringOutputStream(); FileUtil.copy(str, out); String dir = System.getProperty("java.io.tmpdir"); File sourceFile = new File(dir, templateName); ModelSource source = Utilities.createModelSourceForMissingFile(sourceFile, true, out.toString(), "text/xml"); assertTrue(source.isEditable()); return source; } }
3,480
1,179
<reponame>RavenSpear/optee_os<filename>core/lib/libtomcrypt/src/encauth/eax/eax_init.c // SPDX-License-Identifier: BSD-2-Clause /* LibTomCrypt, modular cryptographic library -- <NAME> * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ /** @file eax_init.c EAX implementation, initialized EAX state, by <NAME> */ #include "tomcrypt_private.h" #ifdef LTC_EAX_MODE /** Initialized an EAX state @param eax [out] The EAX state to initialize @param cipher The index of the desired cipher @param key The secret key @param keylen The length of the secret key (octets) @param nonce The use-once nonce for the session @param noncelen The length of the nonce (octets) @param header The header for the EAX state @param headerlen The header length (octets) @return CRYPT_OK if successful */ int eax_init(eax_state *eax, int cipher, const unsigned char *key, unsigned long keylen, const unsigned char *nonce, unsigned long noncelen, const unsigned char *header, unsigned long headerlen) { unsigned char *buf; int err, blklen; omac_state *omac; unsigned long len; LTC_ARGCHK(eax != NULL); LTC_ARGCHK(key != NULL); LTC_ARGCHK(nonce != NULL); if (headerlen > 0) { LTC_ARGCHK(header != NULL); } if ((err = cipher_is_valid(cipher)) != CRYPT_OK) { return err; } blklen = cipher_descriptor[cipher]->block_length; /* allocate ram */ buf = XMALLOC(MAXBLOCKSIZE); omac = XMALLOC(sizeof(*omac)); if (buf == NULL || omac == NULL) { if (buf != NULL) { XFREE(buf); } if (omac != NULL) { XFREE(omac); } return CRYPT_MEM; } /* N = LTC_OMAC_0K(nonce) */ zeromem(buf, MAXBLOCKSIZE); if ((err = omac_init(omac, cipher, key, keylen)) != CRYPT_OK) { goto LBL_ERR; } /* omac the [0]_n */ if ((err = omac_process(omac, buf, blklen)) != CRYPT_OK) { goto LBL_ERR; } /* omac the nonce */ if ((err = omac_process(omac, nonce, noncelen)) != CRYPT_OK) { goto LBL_ERR; } /* store result */ len = sizeof(eax->N); if ((err = omac_done(omac, eax->N, &len)) != CRYPT_OK) { goto LBL_ERR; } /* H = LTC_OMAC_1K(header) */ zeromem(buf, MAXBLOCKSIZE); buf[blklen - 1] = 1; if ((err = omac_init(&eax->headeromac, cipher, key, keylen)) != CRYPT_OK) { goto LBL_ERR; } /* omac the [1]_n */ if ((err = omac_process(&eax->headeromac, buf, blklen)) != CRYPT_OK) { goto LBL_ERR; } /* omac the header */ if (headerlen != 0) { if ((err = omac_process(&eax->headeromac, header, headerlen)) != CRYPT_OK) { goto LBL_ERR; } } /* note we don't finish the headeromac, this allows us to add more header later */ /* setup the CTR mode */ if ((err = ctr_start(cipher, eax->N, key, keylen, 0, CTR_COUNTER_BIG_ENDIAN, &eax->ctr)) != CRYPT_OK) { goto LBL_ERR; } /* setup the LTC_OMAC for the ciphertext */ if ((err = omac_init(&eax->ctomac, cipher, key, keylen)) != CRYPT_OK) { goto LBL_ERR; } /* omac [2]_n */ zeromem(buf, MAXBLOCKSIZE); buf[blklen-1] = 2; if ((err = omac_process(&eax->ctomac, buf, blklen)) != CRYPT_OK) { goto LBL_ERR; } err = CRYPT_OK; LBL_ERR: #ifdef LTC_CLEAN_STACK zeromem(buf, MAXBLOCKSIZE); zeromem(omac, sizeof(*omac)); #endif XFREE(omac); XFREE(buf); return err; } #endif /* ref: $Format:%D$ */ /* git commit: $Format:%H$ */ /* commit time: $Format:%ai$ */
1,680
692
package com.hubspot.mesos.protos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; import java.util.Optional; public class MesosParameter { private final Optional<String> key; private final Optional<String> value; @JsonCreator public MesosParameter( @JsonProperty("key") Optional<String> key, @JsonProperty("value") Optional<String> value ) { this.key = key; this.value = value; } public String getKey() { return key.orElse(null); } @JsonIgnore public boolean hasKey() { return key.isPresent(); } public String getValue() { return value.orElse(null); } @JsonIgnore public boolean hasValue() { return value.isPresent(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof MesosParameter) { final MesosParameter that = (MesosParameter) obj; return Objects.equals(this.key, that.key) && Objects.equals(this.value, that.value); } return false; } @Override public int hashCode() { return Objects.hash(key, value); } @Override public String toString() { return "MesosKeyValueObject{" + "key=" + key + ", value=" + value + '}'; } }
487
419
""" A simple plotting example ========================== A plotting example with a few simple tweaks """ import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure(figsize=(5, 4), dpi=72) axes = fig.add_axes([0.01, 0.01, .98, 0.98]) x = np.linspace(0, 2, 200, endpoint=True) y = np.sin(2 * np.pi * x) plt.plot(x, y, lw=.25, c='k') plt.xticks(np.arange(0.0, 2.0, 0.1)) plt.yticks(np.arange(-1.0, 1.0, 0.1)) plt.grid() plt.show()
215
14,499
<gh_stars>1000+ /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <iostream> #include <fstream> #include <unistd.h> extern void __infer_url_sink(char*); namespace files { extern char* FLAGS_cli_string; void read_file_call_exec_bad1(int length) { std::ifstream is("test.txt", std::ifstream::binary); if (is) { char* buffer = new char[length]; is.read(buffer, length); execle(buffer, NULL); is.close(); } } void read_file_call_exec_bad2(int length) { std::ifstream is("test.txt", std::ifstream::binary); if (is) { char* buffer = new char[length]; is.readsome(buffer, length); execle(buffer, NULL); is.close(); } } void read_file_call_exec_bad3(int length) { std::ifstream is("test.txt", std::ifstream::binary); if (is) { char* buffer = new char[length]; is.getline(buffer, length); execle(buffer, NULL); is.close(); } } // have to do matching on C procnames to make this work void FN_read_file_call_exec_bad5(int length) { std::ifstream is("test.txt", std::ifstream::binary); if (is) { char* buffer = new char[length]; is >> buffer; execle(buffer, NULL); is.close(); } } // make sure we handle reads via iostreams too void read_file_call_exec_bad5(std::iostream is, int length) { if (is) { char* buffer = new char[length]; is.getline(buffer, length); execle(buffer, NULL); } } void read_file_from_flag_ok(int length) { std::ofstream file1(FLAGS_cli_string, std::ifstream::binary); } void url_from_flag_ok() { __infer_url_sink(FLAGS_cli_string); } } // namespace files
668
506
<reponame>Ashindustry007/competitive-programming<gh_stars>100-1000 #!/usr/bin/env python3 # https://abc079.contest.atcoder.jp/tasks/abc079_c a, b, c, d = map(int, input()) if a + b + c + d == 7: print('{}+{}+{}+{}=7'.format(a, b, c, d)) elif a + b + c - d== 7: print('{}+{}+{}-{}=7'.format(a, b, c, d)) elif a + b - c + d == 7: print('{}+{}-{}+{}=7'.format(a, b, c, d)) elif a + b - c - d == 7: print('{}+{}-{}-{}=7'.format(a, b, c, d)) elif a - b + c + d == 7: print('{}-{}+{}+{}=7'.format(a, b, c, d)) elif a - b + c - d == 7: print('{}-{}+{}-{}=7'.format(a, b, c, d)) elif a - b - c + d == 7: print('{}-{}-{}+{}=7'.format(a, b, c, d)) elif a - b - c - d == 7: print('{}-{}-{}-{}=7'.format(a, b, c, d))
384
11,356
<reponame>shreyasvj25/turicreate<filename>deps/src/boost_1_65_1/boost/units/detail/heterogeneous_conversion.hpp // Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 <NAME> // Copyright (C) 2008 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_UNITS_DETAIL_HETEROGENEOUS_CONVERSION_HPP #define BOOST_UNITS_DETAIL_HETEROGENEOUS_CONVERSION_HPP #include <boost/mpl/minus.hpp> #include <boost/mpl/times.hpp> #include <boost/units/static_rational.hpp> #include <boost/units/homogeneous_system.hpp> #include <boost/units/detail/linear_algebra.hpp> namespace boost { namespace units { namespace detail { struct solve_end { template<class Begin, class Y> struct apply { typedef dimensionless_type type; }; }; struct no_solution {}; template<class X1, class X2, class Next> struct solve_normal { template<class Begin, class Y> struct apply { typedef typename Begin::next next; typedef list< typename mpl::minus< typename mpl::times<X1, Y>::type, typename mpl::times<X2, typename Begin::item>::type >::type, typename Next::template apply<next, Y>::type > type; }; }; template<class Next> struct solve_leading_zeroes { template<class Begin> struct apply { typedef list< typename Begin::item, typename Next::template apply<typename Begin::next>::type > type; }; typedef solve_leading_zeroes type; }; template<> struct solve_leading_zeroes<no_solution> { typedef no_solution type; }; template<class Next> struct solve_first_non_zero { template<class Begin> struct apply { typedef typename Next::template apply< typename Begin::next, typename Begin::item >::type type; }; }; template<class Next> struct solve_internal_zero { template<class Begin, class Y> struct apply { typedef list< typename Begin::item, typename Next::template apply<typename Begin::next, Y>::type > type; }; }; template<class T> struct make_solve_list_internal_zero { template<class Next, class X> struct apply { typedef solve_normal<T, X, Next> type; }; }; template<> struct make_solve_list_internal_zero<static_rational<0> > { template<class Next, class X> struct apply { typedef solve_internal_zero<Next> type; }; }; template<int N> struct make_solve_list_normal { template<class Begin, class X> struct apply { typedef typename make_solve_list_internal_zero< typename Begin::item >::template apply< typename make_solve_list_normal<N-1>::template apply<typename Begin::next, X>::type, X >::type type; }; }; template<> struct make_solve_list_normal<0> { template<class Begin, class X> struct apply { typedef solve_end type; }; }; template<int N> struct make_solve_list_leading_zeroes; template<class T> struct make_solve_list_first_non_zero { template<class Begin, int N> struct apply { typedef solve_first_non_zero< typename make_solve_list_normal<N-1>::template apply< typename Begin::next, typename Begin::item >::type > type; }; }; template<> struct make_solve_list_first_non_zero<static_rational<0> > { template<class Begin, int N> struct apply { typedef typename solve_leading_zeroes< typename make_solve_list_leading_zeroes<N-1>::template apply< typename Begin::next >::type >::type type; }; }; template<int N> struct make_solve_list_leading_zeroes { template<class Begin> struct apply { typedef typename make_solve_list_first_non_zero<typename Begin::item>::template apply<Begin, N>::type type; }; }; template<> struct make_solve_list_leading_zeroes<0> { template<class Begin> struct apply { typedef no_solution type; }; }; template<int N> struct try_add_unit_impl { template<class Begin, class L> struct apply { typedef typename try_add_unit_impl<N-1>::template apply<typename Begin::next, L>::type next; typedef typename Begin::item::template apply<next>::type type; BOOST_STATIC_ASSERT((next::size::value - 1 == type::size::value)); }; }; template<> struct try_add_unit_impl<0> { template<class Begin, class L> struct apply { typedef L type; }; }; template<int N> struct make_homogeneous_system_impl; template<class T, bool is_done> struct make_homogeneous_system_func; template<class T> struct make_homogeneous_system_func<T, false> { template<class Begin, class Current, class Units, class Dimensions, int N> struct apply { typedef typename make_homogeneous_system_impl<N-1>::template apply< typename Begin::next, list<T, Current>, list<typename Begin::item, Units>, Dimensions >::type type; }; }; template<class T> struct make_homogeneous_system_func<T, true> { template<class Begin, class Current, class Units, class Dimensions, int N> struct apply { typedef list<typename Begin::item, Units> type; }; }; template<> struct make_homogeneous_system_func<no_solution, false> { template<class Begin, class Current, class Units, class Dimensions, int N> struct apply { typedef typename make_homogeneous_system_impl<N-1>::template apply< typename Begin::next, Current, Units, Dimensions >::type type; }; }; template<> struct make_homogeneous_system_func<no_solution, true> { template<class Begin, class Current, class Units, class Dimensions, int N> struct apply { typedef typename make_homogeneous_system_impl<N-1>::template apply< typename Begin::next, Current, Units, Dimensions >::type type; }; }; template<int N> struct make_homogeneous_system_impl { template<class Begin, class Current, class Units, class Dimensions> struct apply { typedef typename expand_dimensions<Dimensions::size::value>::template apply< Dimensions, typename Begin::item::dimension_type >::type dimensions; typedef typename try_add_unit_impl<Current::size::value>::template apply<Current, dimensions>::type new_element; typedef typename make_solve_list_leading_zeroes<new_element::size::value>::template apply<new_element>::type new_func; typedef typename make_homogeneous_system_func< new_func, ((Current::size::value)+1) == (Dimensions::size::value) >::template apply<Begin, Current, Units, Dimensions, N>::type type; }; }; template<> struct make_homogeneous_system_impl<0> { template<class Begin, class Current, class Units, class Dimensions> struct apply { typedef Units type; }; }; template<class Units> struct make_homogeneous_system { typedef typename find_base_dimensions<Units>::type base_dimensions; typedef homogeneous_system< typename insertion_sort< typename make_homogeneous_system_impl< Units::size::value >::template apply< Units, dimensionless_type, dimensionless_type, base_dimensions >::type >::type > type; }; template<int N> struct extract_base_units { template<class Begin, class T> struct apply { typedef list< typename Begin::item::tag_type, typename extract_base_units<N-1>::template apply<typename Begin::next, T>::type > type; }; }; template<> struct extract_base_units<0> { template<class Begin, class T> struct apply { typedef T type; }; }; } } } #endif
3,423
333
// // YSCGifLoadImageView.h // MISVoiceSearchLib // // Created by yushichao on 16/10/18. // Copyright © 2016年 yushichao. All rights reserved. // #import <UIKit/UIKit.h> #import "YSCGifLoadImage.h" typedef void(^GifAnimatingCompleteCallBack)(void); @interface YSCGifLoadImageView : UIImageView /** * 开始播放 * * @param gifRepeatCount 播放次数 * @param gifRepeatDelayOffset 每次播放时间间隔 * @param completeCallBack gif播放完后的回掉 */ - (void)startGifAnimatingWithGifRepeatCount:(NSInteger)gifRepeatCount gifRepeatDelayOffset:(CGFloat)gifRepeatDelayOffset animatingCompleteCallBack:(GifAnimatingCompleteCallBack)completeCallBack; - (void)stopGifAnimation; @end
323
340
<reponame>rasky/cen64 // // arch/arm/rsp/vnxor.h // // This file is subject to the terms and conditions defined in // 'LICENSE', which is part of this source code package. // #include "common.h" #include <arm_neon.h> static inline uint16x8_t rsp_vnxor( uint16x8_t vs, uint16x8_t vt, uint16x8_t zero) { return vmvnq_u16(veorq_u16(vs, vt)); }
154
1,185
<reponame>goolulu/dubbo-samples<filename>test/dubbo-scenario-builder/src/test/java/org/apache/dubbo/scenario/builder/VersionMatcherTest.java<gh_stars>1000+ /* * 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.dubbo.scenario.builder; import org.junit.Assert; import org.junit.Test; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import static org.apache.dubbo.scenario.builder.VersionMatcher.CASE_VERSIONS_FILE; import static org.apache.dubbo.scenario.builder.VersionMatcher.OUTPUT_FILE; import static org.apache.dubbo.scenario.builder.VersionMatcher.CANDIDATE_VERSIONS; public class VersionMatcherTest { @Test public void testVersionMatch1() throws Exception { String caseVersionRules = "# Spring app\n" + "dubbo.version=2.7*, 3.*\n" + "spring.version= 4.*, 5.*\n\n\n"; String candidateVersions = "dubbo.version: 2.7.7,3.0;"; candidateVersions += "spring.version:4.1.13.RELEASE, 5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.7 -Dspring.version=4.1.13.RELEASE")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0 -Dspring.version=4.1.13.RELEASE")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.7 -Dspring.version=5.3.2")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0 -Dspring.version=5.3.2")); } @Test public void testVersionMatch2() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version=2.7*, 3.*\n" + "spring-boot.version=2.*\n\n\n"; String candidateVersions = "dubbo.version:2.7.7,3.0\n"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2\n\n"; candidateVersions += "spring-boot.version:1.5.13.RELEASE\n"; candidateVersions += "spring-boot.version:2.1.1.RELEASE"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.7 -Dspring-boot.version=2.1.1.RELEASE")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0 -Dspring-boot.version=2.1.1.RELEASE")); } @Test public void testVersionMatchIncludeSpecificVersion() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version=2.7*, 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.7,3.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.7 -Dspring-boot.version=2.0.8.RELEASE")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0 -Dspring-boot.version=2.0.8.RELEASE")); } @Test public void testExcludeMatch() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= 2.7*, !2.7.9*, 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.8 -Dspring-boot.version=2.0.8.RELEASE")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0 -Dspring-boot.version=2.0.8.RELEASE")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); } @Test public void testRangeMatch() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= >=2.7.7 <2.7.9, 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.8")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); } @Test public void testRangeMatch2() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= [ >= 2.7.7 < 2.7.9, 3.* ]\n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.8")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); } @Test public void testRangeMatch3() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= [ '<2.7.8', \">= 2.7.9\", 3.* ]\n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0.preview;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.8")); } @Test public void testRangeMatchException1() throws Exception { String matchRule = ">= 2.7.7 < 2.7 .9"; String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= " + matchRule + ", 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; try { getVersionMatrix(caseVersionRules, candidateVersions); Assert.fail("Invalid range match rule should not pass through"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Invalid range match rule: " + matchRule)); } } @Test public void testRangeMatchException2() throws Exception { String matchRule = "'>= 2.7.7 < 2.7.9"; String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= " + matchRule + ", 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; try { getVersionMatrix(caseVersionRules, candidateVersions); Assert.fail("Invalid range match rule should not pass through"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Version match rule is invalid: " + matchRule)); } } @Test public void testRangeMatchException3() throws Exception { String matchRule = "\">= 2.7.7 < 2.7.9"; String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= " + matchRule + ", 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; try { getVersionMatrix(caseVersionRules, candidateVersions); Assert.fail("Invalid range match rule should not pass through"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Version match rule is invalid: " + matchRule)); } } @Test public void testRangeMatchException4() throws Exception { String matchRule = "\">= 2.7.7 < 2.7.9'"; String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= " + matchRule + ", 3.* \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; try { getVersionMatrix(caseVersionRules, candidateVersions); Assert.fail("Invalid range match rule should not pass through"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Version match rule is invalid: " + matchRule)); } } @Test public void testGreaterThanOrEqualTo() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= >=2.7.9 \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.8")); } @Test public void testGreaterThan() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= >2.7.9 \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.8")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.9")); } @Test public void testLessThan() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= <2.7.9 \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.8")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=3.0.0")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=2.7.9")); } @Test public void testLessThanOrEqualTo() throws Exception { String caseVersionRules = "# SpringBoot app\n" + "dubbo.version= <=2.7.9 \n" + "spring-boot.version= 2.0.8.RELEASE \n\n\n"; String candidateVersions = "dubbo.version:2.7.8,2.7.9-SNAPSHOT,3.0.0;"; candidateVersions += "spring.version:4.1.13.RELEASE,5.3.2;"; candidateVersions += "spring-boot.version:1.5.13.RELEASE,2.1.1.RELEASE;"; String versionMatrix = getVersionMatrix(caseVersionRules, candidateVersions); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.8")); Assert.assertTrue(versionMatrix.contains("-Ddubbo.version=2.7.9-SNAPSHOT")); Assert.assertFalse(versionMatrix.contains("-Ddubbo.version=3.0.0")); } private String getVersionMatrix(String caseVersionRules, String candidateVersions) throws Exception { File caseVersionsFile = File.createTempFile("case-versions", ".conf"); File outputFile = File.createTempFile("case-version-matrix", ".txt"); caseVersionsFile.deleteOnExit(); outputFile.deleteOnExit(); writeToFile(caseVersionRules, caseVersionsFile); System.setProperty(CANDIDATE_VERSIONS, candidateVersions); System.setProperty(CASE_VERSIONS_FILE, caseVersionsFile.getAbsolutePath()); System.setProperty(OUTPUT_FILE, outputFile.getAbsolutePath()); VersionMatcher.main(new String[0]); return FileUtil.readFully(outputFile.getAbsolutePath()); } private void writeToFile(String content, File file) throws Exception { try (FileOutputStream fos = new FileOutputStream(file); DataOutputStream dos = new DataOutputStream(fos)) { dos.writeBytes(content); } } }
6,377
1,337
/* * Copyright (c) 2008-2017 Haulmont. * * 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.haulmont.cuba.web.widgets; import com.haulmont.cuba.web.widgets.grid.CubaEditorField; import com.vaadin.ui.Grid; /** * Factory that generates components for {@link CubaGrid} editor. */ public interface CubaGridEditorFieldFactory<T> { /** * Generates component for {@link CubaGrid} editor. * * @param bean the editing item * @param column the column for which the field is being created * @return generated component */ CubaEditorField<?> createField(T bean, Grid.Column<T, ?> column); }
345
1,380
/* * Image.h * * The MIT License (MIT) * * Copyright (c) 2013 ZhangYuanwei <<EMAIL>> * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS 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. */ #ifndef __NODE_IMAGE_H__ #define __NODE_IMAGE_H__ #include <node_api.h> #include <stdlib.h> #include <stdio.h> typedef enum { TYPE_PNG = 1, TYPE_JPEG, TYPE_GIF, TYPE_BMP, TYPE_RAW, TYPE_WEBP, } ImageType; typedef enum { FAIL = 0, SUCCESS, } ImageState; typedef struct Pixel { uint8_t R; uint8_t G; uint8_t B; uint8_t A; void Merge(struct Pixel *pixel); } Pixel; typedef enum { EMPTY = 0, ALPHA, SOLID, } PixelArrayType; typedef struct PixelArray { Pixel **data; size_t width; size_t height; PixelArrayType type; int32_t Size() { return (height * sizeof(Pixel **)) + (width * height * sizeof(Pixel)); } // Memory ImageState Malloc(size_t w, size_t h); ImageState CopyFrom(struct PixelArray *src, size_t x, size_t y, size_t w, size_t h); void Free(); // Draw void Draw(struct PixelArray *src, size_t x, size_t y); void Fill(Pixel *color); // Transform ImageState SetWidth(size_t w); ImageState SetHeight(size_t h); ImageState Resize(size_t w, size_t h, const char *filter); ImageState Rotate(size_t deg); void DetectTransparent(); } PixelArray; typedef struct { uint8_t *data; unsigned long length; unsigned long position; //ImageType type; } ImageData; typedef struct { char *data; unsigned long length; } ImageConfig; typedef ImageState (*ImageEncoder)(PixelArray *input, ImageData *output, ImageConfig *config); typedef ImageState (*ImageDecoder)(PixelArray *output, ImageData *input); typedef struct ImageCodec { ImageType type; ImageEncoder encoder; ImageDecoder decoder; struct ImageCodec *next; } ImageCodec; #define ENCODER(type) encode ## type #define ENCODER_FN(type) ImageState ENCODER(type)(PixelArray *input, ImageData *output, ImageConfig *config) #define DECODER(type) decode ## type #define DECODER_FN(type) ImageState DECODER(type)(PixelArray *output, ImageData *input) #define IMAGE_CODEC(type) DECODER_FN(type); ENCODER_FN(type) #ifdef HAVE_PNG IMAGE_CODEC(Png); #endif #ifdef HAVE_JPEG IMAGE_CODEC(Jpeg); #endif #ifdef HAVE_GIF IMAGE_CODEC(Gif); #endif #ifdef HAVE_BMP IMAGE_CODEC(Bmp); #endif #ifdef HAVE_RAW IMAGE_CODEC(Raw); #endif #ifdef HAVE_WEBP IMAGE_CODEC(Webp); #endif class Image { public: // static v8::Persistent<v8::Function> constructor; static napi_ref constructor; // static void Init(v8::Local<v8::Object> exports); static napi_value Init(napi_env env, napi_value exports); static void Destructor(napi_env env, void* nativeObject, void* finalize_hint); static napi_value New(napi_env env, napi_callback_info info); // Error Handle static void setError(const char *err); static napi_value getError(napi_env, napi_callback_info info); static bool isError(); // Size Limit static size_t maxWidth, maxHeight; static napi_value GetMaxWidth(napi_env env, napi_callback_info info); static napi_value SetMaxWidth(napi_env env, napi_callback_info info); static napi_value GetMaxHeight(napi_env env, napi_callback_info info); static napi_value SetMaxHeight(napi_env env, napi_callback_info info); // Memory static size_t usedMemory; static napi_value GetUsedMemory(napi_env env, napi_callback_info info); static napi_value GC(napi_env env, napi_callback_info info); // Image constructor // static void New(const v8::FunctionCallbackInfo<v8::Value> &args); // Image.prototype static napi_value GetWidth(napi_env env, napi_callback_info info); static napi_value SetWidth(napi_env env, napi_callback_info info); static napi_value GetHeight(napi_env env, napi_callback_info info); static napi_value SetHeight(napi_env env, napi_callback_info info); static napi_value GetTransparent(napi_env env, napi_callback_info info); static napi_value Resize(napi_env env, napi_callback_info info); static napi_value Rotate(napi_env env, napi_callback_info info); static napi_value FillColor(napi_env env, napi_callback_info info); static napi_value LoadFromBuffer(napi_env env, napi_callback_info info); static napi_value ToBuffer(napi_env env, napi_callback_info info); static napi_value CopyFromImage(napi_env env, napi_callback_info info); static napi_value DrawImage(napi_env env, napi_callback_info info); private: static const char *error; static int errno; static ImageCodec *codecs; static void regCodec(ImageDecoder decoder, ImageEncoder encoder, ImageType type); static void regAllCodecs() { codecs = NULL; #ifdef HAVE_WEBP regCodec(DECODER(Webp), ENCODER(Webp), TYPE_WEBP); #endif #ifdef HAVE_RAW regCodec(DECODER(Raw), ENCODER(Raw), TYPE_RAW); #endif #ifdef HAVE_BMP regCodec(DECODER(Bmp), ENCODER(Bmp), TYPE_BMP); #endif #ifdef HAVE_GIF regCodec(DECODER(Gif), ENCODER(Gif), TYPE_GIF); #endif #ifdef HAVE_JPEG regCodec(DECODER(Jpeg), ENCODER(Jpeg), TYPE_JPEG); #endif #ifdef HAVE_PNG regCodec(DECODER(Png), ENCODER(Png), TYPE_PNG); #endif } PixelArray *pixels; Image(); ~Image(); // napi env & wrapper napi_env env_; napi_ref wrapper_; }; #endif
2,674
334
{ "name": "liveblocks-examples-javascript-live-cursors", "version": "1.0.0", "description": "Liveblocks live cursors example with javascript", "scripts": { "build": "esbuild app.js --bundle --outfile=static/app.js" }, "author": "", "license": "Apache-2.0", "dependencies": { "@liveblocks/client": "^0.13.2" }, "devDependencies": { "dotenv": "^10.0.0", "esbuild": "^0.12.2" } }
178
482
<gh_stars>100-1000 #ifndef FONT4X6_h #define FONT4X6_h #include <avr/pgmspace.h> extern const unsigned char font4x6[]; #endif
66
1,091
/* * Copyright (c) 2015-2020, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Provides infrastructure for applying transformations to a {@link org.tribuo.Dataset}. * <p> * This package is the necessary infrastructure for transformations. The workflow is first to build a * {@link org.tribuo.transform.TransformationMap} which represents the * {@link org.tribuo.transform.Transformation}s and the order that they should be applied to the specified * {@link org.tribuo.Feature}s. This can be applied to a Dataset to produce a * {@link org.tribuo.transform.TransformerMap} which contains a fitted set of * {@link org.tribuo.transform.Transformer}s which can be used to apply the transformation to any * other Dataset (e.g., to apply the same transformation to training and test sets), or to be used at prediction * time to stream data through. * <p> * It also provides a {@link org.tribuo.transform.TransformTrainer} which accepts a * TransformationMap and an inner {@link org.tribuo.Trainer} and produces a * {@link org.tribuo.transform.TransformedModel} which automatically transforms it's input data at * prediction time. * <p> * Transformations don't produce new {@link org.tribuo.Feature}s - they only modify the values of existing ones. * When doing so they can be instructed to treat Features that are absent due to sparsity as zero or as * not existing at all. Independently, we can explicitly add zero-valued Features by densifying the dataset * before the transformation is fit or before it is applied. Once they exist these Features can be altered by * {@link org.tribuo.transform.Transformer}s and are visible to {@link org.tribuo.transform.Transformation}s which are * being fit. * <p> * The transformation fitting methods have two parameters which alter their behaviour: {@code includeImplicitZeroFeatures} * and {@code densify}. {@code includeImplicitZeroFeatures} controls if the transformation incorporates the implicit zero * valued features (i.e., the ones not present in the example but are present in the dataset's * {@link org.tribuo.FeatureMap}) when building the transformation statistics. This is * important when working with, e.g. {@link org.tribuo.transform.transformations.IDFTransformation} as it allows correct * computation of the inverse document frequency, but can be detrimental to features which are one-hot encodings of * categoricals (as they have many more implicit zeros). {@code densify} controls if the example or dataset should have * its implicit zero valued features converted into explicit zero valued features (i.e., it makes a sparse example into * a dense one which contains an explicit value for every feature known to the dataset) before the transformation is * applied, and transformations are only applied to feature values which are present. * <p> * These parameters interact to form 4 possibilities: * <ul> * <li>Both false: transformations are only fit on explicit feature values, and only applied to explicit feature values</li> * <li>Both true: transformations include explicit features and implicit zeros, and implicit zeros are converted into explicit zeros and transformed</li> * <li>{@code includeImplicitZeroFeatures} is true, {@code densify} is false: the implicit zeroes are used to fit * the transformation, but not modified when the transformation is applied. This is most useful when working with * text data where you want to compute IDF style statistics</li> * <li>{@code includeImplicitZeroFeatures} is false, {@code densify} is true: the implicit zeros are not used to * fit the transformation, but are converted to explicit zeros and transformed. This is less useful than the other * three combinations, but could be used to move the minimum value, or when zero is not appropriate for a missing * value and needs to be transformed.</li> * </ul> * One further option is to call {@link org.tribuo.MutableDataset#densify} before passing the data to * {@link org.tribuo.transform.TransformTrainer#train}, which is equivalent to setting {@code includeImplicitZeroFeatures} * to true and {@code densify} to true. To sum up, in the context of transformations {@code includeImplicitZeroFeatures} * determines whether (implicit) zero-values features are <i>measured</i> and {@code densify} determines whether * they can be <i>altered</i>. */ package org.tribuo.transform;
1,287
12,278
<filename>libs/outcome/meta/libraries.json { "key": "outcome", "name": "Outcome", "authors": [ "<NAME>" ], "maintainers": [ "<NAME>" ], "description": "A deterministic failure handling library partially simulating lightweight exceptions.", "std": [ "proposal" ], "category": [ "Patterns", "Emulation", "Programming" ] }
122
1,266
<gh_stars>1000+ // Copyright (c) 2019-2020 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMSCONSTANTS_H #define BITCOIN_CHAINPARAMSCONSTANTS_H /** * Chain params constants for each tracked chain. */ #include <primitives/blockhash.h> #include <uint256.h> namespace ChainParamsConstants { extern const BlockHash MAINNET_DEFAULT_ASSUME_VALID; extern const uint256 MAINNET_MINIMUM_CHAIN_WORK; extern const uint64_t MAINNET_ASSUMED_BLOCKCHAIN_SIZE; extern const uint64_t MAINNET_ASSUMED_CHAINSTATE_SIZE; extern const BlockHash TESTNET_DEFAULT_ASSUME_VALID; extern const uint256 TESTNET_MINIMUM_CHAIN_WORK; extern const uint64_t TESTNET_ASSUMED_BLOCKCHAIN_SIZE; extern const uint64_t TESTNET_ASSUMED_CHAINSTATE_SIZE; } // namespace ChainParamsConstants #endif // BITCOIN_CHAINPARAMSCONSTANTS_H
334
373
/* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. 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. Description: The adaptation control estimates the frequency-dependent signal-to-noise ratio (SNR) based on spatial information. A fixed beamformer is steered into the assumed target direction-of-arrival (DOA) yielding a rough estimate of the desired signal frequency-dependent energy. A complementary null beamformer with a spatial null in the assumed desired signal DOA yields a frequency-dependent estimate of the interference energy. The ratio of both energy estimates is taken as a frequnecy-dependent SNR estimate. If the SNR is greater than a predefined threshold value tabm, then the blocking matrix is adapted. If the SNR is less than another predefined threshold taic, then the adaptive interference canceller is adapted. Otherwise the adaptation is stalled in order to minimize target signal cancellation and interference leakage, and to obtain better robustness in turn. ==============================================================================*/ #include "dios_ssp_gsc_adaptctrl.h" void dios_ssp_gsc_gscadaptctrl_init(objFGSCadaptctrl *gscadaptctrl, const DWORD dwSampRate, const WORD wNumMic, const WORD wSyncDlyXref, const WORD wSyncDlyYfbf, const WORD wSyncDlyAic, const DWORD dwFftSize, const WORD wFftOverlap, const DWORD dwF0, const DWORD dwF1, const DWORD dwFc, const float corrThresAbm, const float corrThresAic, const int dwNumSubWindowsMinStat, const int dwSizeSubWindowsMinStat) { gscadaptctrl->m_pfBuffer = NULL; gscadaptctrl->m_ppXrefDline = NULL; gscadaptctrl->m_pXfbfDline = NULL; gscadaptctrl->m_ppcfXref = NULL; gscadaptctrl->m_pcfXfbf = NULL; gscadaptctrl->m_pcfXcfbf = NULL; gscadaptctrl->m_pfPref = NULL; gscadaptctrl->m_pfPfbf = NULL; gscadaptctrl->m_pfPcfbf = NULL; gscadaptctrl->m_pfBeta = NULL; gscadaptctrl->m_pfBetaC = NULL; gscadaptctrl->m_ppfCtrlAicDline = NULL; gscadaptctrl->m_dwSampRate = dwSampRate; gscadaptctrl->m_wNumMic = wNumMic; gscadaptctrl->m_wSyncDlyXref = wSyncDlyXref; gscadaptctrl->m_wSyncDlyYfbf = wSyncDlyYfbf; gscadaptctrl->m_wSyncDlyCtrlAic = wSyncDlyAic; gscadaptctrl->m_dwFftSize = dwFftSize; gscadaptctrl->m_wFftOverlap = wFftOverlap; gscadaptctrl->m_corrThresAbm = corrThresAbm; gscadaptctrl->m_corrThresAic = corrThresAic; gscadaptctrl->m_nCCSSize = (int)(gscadaptctrl->m_dwFftSize / 2 + 1); gscadaptctrl->m_dwIndF0 = (DWORD)floor(dwF0 * (float)gscadaptctrl->m_dwFftSize / gscadaptctrl->m_dwSampRate); gscadaptctrl->m_dwIndF1 = (DWORD)floor(dwF1 * (float)gscadaptctrl->m_dwFftSize / gscadaptctrl->m_dwSampRate); gscadaptctrl->m_dwIndFc = (DWORD)floor(dwFc * (float)gscadaptctrl->m_dwFftSize / gscadaptctrl->m_dwSampRate); gscadaptctrl->m_delta = 0.001f; gscadaptctrl->npsdosms1 = (objCNPsdOsMs*)calloc(1, sizeof(objCNPsdOsMs)); dios_ssp_gsc_rmnpsdosms_init(gscadaptctrl->npsdosms1, (float)(gscadaptctrl->m_dwSampRate), gscadaptctrl->m_nCCSSize, (int)(gscadaptctrl->m_dwFftSize / gscadaptctrl->m_wFftOverlap), dwNumSubWindowsMinStat, dwSizeSubWindowsMinStat); gscadaptctrl->npsdosms2 = (objCNPsdOsMs*)calloc(1, sizeof(objCNPsdOsMs)); dios_ssp_gsc_rmnpsdosms_init(gscadaptctrl->npsdosms2, (float)(gscadaptctrl->m_dwSampRate), gscadaptctrl->m_nCCSSize, (int)(gscadaptctrl->m_dwFftSize / gscadaptctrl->m_wFftOverlap), dwNumSubWindowsMinStat, dwSizeSubWindowsMinStat); gscadaptctrl->adapt_FFT = dios_ssp_share_rfft_init((int)gscadaptctrl->m_dwFftSize); gscadaptctrl->fft_out = (float*)calloc(gscadaptctrl->m_dwFftSize, sizeof(float)); gscadaptctrl->m_ppXrefDline = (float**)calloc(gscadaptctrl->m_wNumMic, sizeof(float*)); for (int i_mic = 0; i_mic < gscadaptctrl->m_wNumMic; i_mic++) { gscadaptctrl->m_ppXrefDline[i_mic] = (float*)calloc(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyXref, sizeof(float)); } gscadaptctrl->m_pXfbfDline = (float*)calloc(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyYfbf, sizeof(float)); gscadaptctrl->m_ppcfXref = (xcomplex**)calloc(gscadaptctrl->m_wNumMic, sizeof(xcomplex*)); for (int i_mic = 0; i_mic < gscadaptctrl->m_wNumMic; i_mic++) { gscadaptctrl->m_ppcfXref[i_mic] = (xcomplex*)calloc(gscadaptctrl->m_nCCSSize, sizeof(xcomplex)); } gscadaptctrl->m_pcfXfbf = (xcomplex*)calloc(gscadaptctrl->m_nCCSSize, sizeof(xcomplex)); gscadaptctrl->m_pcfXcfbf = (xcomplex*)calloc(gscadaptctrl->m_nCCSSize, sizeof(xcomplex)); gscadaptctrl->m_pfPcfbf = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_pfPfbf = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_pfPref = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_pfBeta = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_pfBetaC = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_pfBuffer = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); gscadaptctrl->m_ppfCtrlAicDline = (float**)calloc(gscadaptctrl->m_wSyncDlyCtrlAic + 1, sizeof(float*)); for (int i = 0; i < gscadaptctrl->m_wSyncDlyCtrlAic + 1; i++) { gscadaptctrl->m_ppfCtrlAicDline[i] = (float*)calloc(gscadaptctrl->m_nCCSSize, sizeof(float)); } } int dios_ssp_gsc_gscadaptctrl_reset(objFGSCadaptctrl *gscadaptctrl) { gscadaptctrl->m_delta = 0.001f; dios_ssp_gsc_rmnpsdosms_reset(gscadaptctrl->npsdosms1); dios_ssp_gsc_rmnpsdosms_reset(gscadaptctrl->npsdosms2); for (int m = 0; m < gscadaptctrl->m_wNumMic; m++) { memset(gscadaptctrl->m_ppXrefDline[m], 0, sizeof(float) * (gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyXref)); for (int n = 0; n < gscadaptctrl->m_nCCSSize; n++) { gscadaptctrl->m_ppcfXref[m][n].i = 0.0f; gscadaptctrl->m_ppcfXref[m][n].r = 0.0f; } } for (DWORD i = 0; i < gscadaptctrl->m_dwFftSize; i++) { gscadaptctrl->fft_out[i] = 0.0f; } for (int m = 0; m < gscadaptctrl->m_wSyncDlyCtrlAic + 1; m++) { memset(gscadaptctrl->m_ppfCtrlAicDline[m], 0, sizeof(float) * gscadaptctrl->m_nCCSSize); } for (int n = 0; n < gscadaptctrl->m_nCCSSize; n++) { gscadaptctrl->m_pcfXfbf[n].i = 0.0f; gscadaptctrl->m_pcfXfbf[n].r = 0.0f; gscadaptctrl->m_pcfXcfbf[n].i = 0.0f; gscadaptctrl->m_pcfXcfbf[n].r = 0.0f; } memset(gscadaptctrl->m_pXfbfDline, 0, sizeof(float) * (gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyYfbf)); memset(gscadaptctrl->m_pfPcfbf, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); memset(gscadaptctrl->m_pfPfbf, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); memset(gscadaptctrl->m_pfPref, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); memset(gscadaptctrl->m_pfBeta, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); memset(gscadaptctrl->m_pfBetaC, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); memset(gscadaptctrl->m_pfBuffer, 0, sizeof(float) * gscadaptctrl->m_nCCSSize); return 0; } int dios_ssp_gsc_gscadaptctrl_process(objFGSCadaptctrl *gscadaptctrl, float *pXfbf, float **ppXref, const DWORD dwIndXref, float *pfCtrlAbm, float *pfCtrlAic) { float meanBeta; /* value of mean energy ratio for f < f0 */ /* psd estimation of the fixed beamformer output */ /* delay line for the fixed beamformer output * 128 + 32 - 128 / (2 * 4) * FixBeamformer delay 32 samples */ delayline(pXfbf, gscadaptctrl->m_pXfbfDline, (int)(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyYfbf - gscadaptctrl->m_dwFftSize / (2 * gscadaptctrl->m_wFftOverlap)), (int)(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyYfbf)); /* perform FFT operations */ dios_ssp_share_rfft_process(gscadaptctrl->adapt_FFT, gscadaptctrl->m_pXfbfDline, gscadaptctrl->fft_out); for (DWORD i = 0; i < gscadaptctrl->m_dwFftSize / 2 + 1; i++) { gscadaptctrl->m_pcfXfbf[i].r = gscadaptctrl->fft_out[i]; } gscadaptctrl->m_pcfXfbf[0].i = gscadaptctrl->m_pcfXfbf[gscadaptctrl->m_dwFftSize / 2].i = 0.0f; for (DWORD i = 1; i < gscadaptctrl->m_dwFftSize / 2; i++) { gscadaptctrl->m_pcfXfbf[i].i = -gscadaptctrl->fft_out[gscadaptctrl->m_dwFftSize - i]; } /* instantaneous power spectrum estimation of output of fbf */ for (int k = 0; k < gscadaptctrl->m_nCCSSize; k++) { gscadaptctrl->m_pfPfbf[k] = gscadaptctrl->m_pcfXfbf[k].r * gscadaptctrl->m_pcfXfbf[k].r + gscadaptctrl->m_pcfXfbf[k].i * gscadaptctrl->m_pcfXfbf[k].i; } memset(gscadaptctrl->m_pfPcfbf, 0, gscadaptctrl->m_nCCSSize * sizeof(float)); for (int i = 0; i < gscadaptctrl->m_wNumMic; ++i) { /* synchronization of fbf output with reference mic signals * 128 + 32 - 128 / (2 * 4) * Input signals: delay 32 samples */ delayline(&ppXref[i][dwIndXref], gscadaptctrl->m_ppXrefDline[i], (int)(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyXref - gscadaptctrl->m_dwFftSize / (2 * gscadaptctrl->m_wFftOverlap)), (int)(gscadaptctrl->m_dwFftSize + gscadaptctrl->m_wSyncDlyXref)); dios_ssp_share_rfft_process(gscadaptctrl->adapt_FFT, gscadaptctrl->m_ppXrefDline[i], gscadaptctrl->fft_out); for (DWORD j = 0; j < gscadaptctrl->m_dwFftSize / 2 + 1; j++) { gscadaptctrl->m_ppcfXref[i][j].r = gscadaptctrl->fft_out[j]; } gscadaptctrl->m_ppcfXref[i][0].i = gscadaptctrl->m_ppcfXref[i][gscadaptctrl->m_dwFftSize / 2].i = 0.0; for (DWORD j = 1; j < gscadaptctrl->m_dwFftSize / 2; j++) { gscadaptctrl->m_ppcfXref[i][j].i = -gscadaptctrl->fft_out[gscadaptctrl->m_dwFftSize - j]; } for (int j = 0; j < gscadaptctrl->m_nCCSSize; j++) { /* 1.power spectrum estimation of reference mic signals */ gscadaptctrl->m_pfBuffer[j] = gscadaptctrl->m_ppcfXref[i][j].r * gscadaptctrl->m_ppcfXref[i][j].r + gscadaptctrl->m_ppcfXref[i][j].i * gscadaptctrl->m_ppcfXref[i][j].i; /* 2.summation over all channels */ gscadaptctrl->m_pfPref[j] += gscadaptctrl->m_pfBuffer[j]; } } /* instantaneous power spectrum estimate of reference mic signals */ for (int k = 0; k < gscadaptctrl->m_nCCSSize; k++) { gscadaptctrl->m_pfPref[k] /= (float)gscadaptctrl->m_wNumMic; } for (int i = 0; i < gscadaptctrl->m_wNumMic; i++) { /* complementary fbf */ for (int j = 0; j < gscadaptctrl->m_nCCSSize; j++) { gscadaptctrl->m_pcfXcfbf[j] = complex_sub(gscadaptctrl->m_ppcfXref[i][j], gscadaptctrl->m_pcfXfbf[j]); gscadaptctrl->m_pfBuffer[j] = gscadaptctrl->m_pcfXcfbf[j].r * gscadaptctrl->m_pcfXcfbf[j].r + gscadaptctrl->m_pcfXcfbf[j].i * gscadaptctrl->m_pcfXcfbf[j].i; gscadaptctrl->m_pfPcfbf[j] += gscadaptctrl->m_pfBuffer[j]; } } /* average power spectrum estimate of complementary beamformer */ for (int k = 0; k < gscadaptctrl->m_nCCSSize; k++) { gscadaptctrl->m_pfPcfbf[k] /= (float)gscadaptctrl->m_wNumMic; gscadaptctrl->m_pfPref[k] /= (float)gscadaptctrl->m_wNumMic; /* ratio of psd estimate of fbf output and psd estimate of complementary fbf output */ /* energy ratio in discrete frequency bins (FCR) */ if (gscadaptctrl->m_pfPcfbf[k] < gscadaptctrl->m_delta) { gscadaptctrl->m_pfBeta[k] = 1.0f / gscadaptctrl->m_delta; } else { gscadaptctrl->m_pfBeta[k] = 1.0f / gscadaptctrl->m_pfPcfbf[k]; } gscadaptctrl->m_pfBeta[k] *= gscadaptctrl->m_pfPfbf[k]; } /* mean energy ratio for f < fc, determined over the interval f0 < f < f1 */ meanBeta = 0.0; for (DWORD l = gscadaptctrl->m_dwIndF0; l < gscadaptctrl->m_dwIndF1; l++) { meanBeta += gscadaptctrl->m_pfBeta[l]; } meanBeta /= (gscadaptctrl->m_dwIndF1 - gscadaptctrl->m_dwIndF0); for (DWORD l = 0; l < gscadaptctrl->m_dwIndFc; l++) { gscadaptctrl->m_pfBeta[l] = meanBeta; } /* determine lower thresholds in decision variables */ dios_ssp_gsc_rmnpsdosms_process(gscadaptctrl->npsdosms1, gscadaptctrl->m_pfBeta); /* energy ratio in discrete frequency bins (CFR) */ for (int k = 0; k < gscadaptctrl->m_nCCSSize; k++) { if (gscadaptctrl->m_pfBeta[k] < gscadaptctrl->m_delta) { gscadaptctrl->m_pfBetaC[k] = 1.f / gscadaptctrl->m_delta; } else { gscadaptctrl->m_pfBetaC[k] = 1.f / gscadaptctrl->m_pfBeta[k]; } } /* determine lower thresholds in decision variables */ dios_ssp_gsc_rmnpsdosms_process(gscadaptctrl->npsdosms2, gscadaptctrl->m_pfBetaC); /* decision abm <-> aic adaptation */ memset(pfCtrlAbm, 0, gscadaptctrl->m_nCCSSize * sizeof(float)); memset(gscadaptctrl->m_pfBuffer, 0, gscadaptctrl->m_nCCSSize * sizeof(float)); gscadaptctrl->m_corrThresAic = 4.0f; gscadaptctrl->m_corrThresAbm = 0.8f; for (int k = 0; k < gscadaptctrl->m_nCCSSize; k++) { if(gscadaptctrl->npsdosms1->m_P[k] - gscadaptctrl->m_corrThresAic * gscadaptctrl->npsdosms1->m_N[k] < 0) { gscadaptctrl->m_pfBuffer[k] = 1; } if(gscadaptctrl->npsdosms2->m_P[k] - gscadaptctrl->m_corrThresAbm * gscadaptctrl->npsdosms2->m_N[k] < 0) { pfCtrlAbm[k] = 1; } if ((pfCtrlAbm[k] == 1) && (gscadaptctrl->m_pfBuffer[k] == 1)) { gscadaptctrl->m_pfBuffer[k] = 0; pfCtrlAbm[k] = 0; } } /* sync delay of aic control signal * m_wSyncDlyCtrlAic = 2 * aic control delay 2 block(2 frames) */ for(int k = 0; k < gscadaptctrl->m_wSyncDlyCtrlAic; k++) { memcpy(gscadaptctrl->m_ppfCtrlAicDline[k+1], gscadaptctrl->m_ppfCtrlAicDline[k], gscadaptctrl->m_nCCSSize * sizeof(float)); } memcpy(gscadaptctrl->m_ppfCtrlAicDline[0], gscadaptctrl->m_pfBuffer, gscadaptctrl->m_nCCSSize * sizeof(float)); memcpy(pfCtrlAic, gscadaptctrl->m_ppfCtrlAicDline[gscadaptctrl->m_wSyncDlyCtrlAic], gscadaptctrl->m_nCCSSize * sizeof(float)); return 0; } int dios_ssp_gsc_gscadaptctrl_delete(objFGSCadaptctrl *gscadaptctrl) { int ret = 0; dios_ssp_gsc_rmnpsdosms_delete(gscadaptctrl->npsdosms1); free(gscadaptctrl->npsdosms1); dios_ssp_gsc_rmnpsdosms_delete(gscadaptctrl->npsdosms2); free(gscadaptctrl->npsdosms2); free(gscadaptctrl->fft_out); ret = dios_ssp_share_rfft_uninit(gscadaptctrl->adapt_FFT); if (0 != ret) { gscadaptctrl->adapt_FFT = NULL; } for (int i_mic = 0; i_mic < gscadaptctrl->m_wNumMic; i_mic++) { free(gscadaptctrl->m_ppXrefDline[i_mic]); } free(gscadaptctrl->m_ppXrefDline); free(gscadaptctrl->m_pXfbfDline); for (int i_mic = 0; i_mic < gscadaptctrl->m_wNumMic; i_mic++) { free(gscadaptctrl->m_ppcfXref[i_mic]); } free(gscadaptctrl->m_ppcfXref); free(gscadaptctrl->m_pcfXfbf); free(gscadaptctrl->m_pcfXcfbf); free(gscadaptctrl->m_pfPref); free(gscadaptctrl->m_pfBuffer); free(gscadaptctrl->m_pfPfbf); free(gscadaptctrl->m_pfPcfbf); free(gscadaptctrl->m_pfBeta); free(gscadaptctrl->m_pfBetaC); for (int i_mic = 0; i_mic < gscadaptctrl->m_wSyncDlyCtrlAic + 1; i_mic++) { free(gscadaptctrl->m_ppfCtrlAicDline[i_mic]); } free(gscadaptctrl->m_ppfCtrlAicDline); return 0; }
6,900
892
{ "schema_version": "1.2.0", "id": "GHSA-h243-jxv9-h6mp", "modified": "2022-04-30T18:16:44Z", "published": "2022-04-30T18:16:44Z", "aliases": [ "CVE-2001-0789" ], "details": "Format string vulnerability in avpkeeper in Kaspersky KAV 3.5.135.2 for Sendmail allows remote attackers to cause a denial of service or possibly execute arbitrary code via a malformed mail message.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2001-0789" }, { "type": "WEB", "url": "http://archives.neohapsis.com/archives/bugtraq/2001-06/0274.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
345
854
__________________________________________________________________________________________________ sample 796 ms submission class Solution: def subarrayBitwiseORs(self, A: List[int]) -> int: Set = set() tmp = {0} for cur in A: tmp = {cur | ele for ele in tmp} tmp.add(cur) Set.update(tmp) return len(Set) __________________________________________________________________________________________________ sample 39212 kb submission class Solution: def subarrayBitwiseORs(self, A: List[int]) -> int: ans = set() cur = {0} for x in A: cur = {x | y for y in cur} | {x} ans |= cur return len(ans) __________________________________________________________________________________________________
310
304
<reponame>fduguet-nv/cunumeric # Copyright 2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np import pytest import cunumeric as num np.random.seed(0) def allclose(A, B): if B.dtype == np.float32 or B.dtype == np.complex64: l2 = (A - B) * np.conj(A - B) l2 = np.sqrt(np.sum(l2) / np.sum(A * np.conj(A))) return l2 < 1e-6 else: return np.allclose(A, B) def check_1d_hfft(N, dtype=np.float64): print(f"\n=== 1D Hermitian {dtype} ===") Z = np.random.rand(N).astype(dtype) + np.random.rand(N).astype(dtype) * 1j Z_num = num.array(Z) out = np.fft.hfft(Z) out_num = num.fft.hfft(Z_num) assert allclose(out, out_num) assert allclose(Z, Z_num) def check_1d_hfft_inverse(N, dtype=np.float64): print(f"\n=== 1D Hermitian inverse {dtype} ===") Z = np.random.rand(N).astype(dtype) Z_num = num.array(Z) out = np.fft.ihfft(Z) out_num = num.fft.ihfft(Z_num) assert allclose(out, out_num) assert allclose(Z, Z_num) def test_1d(): check_1d_hfft(N=110) check_1d_hfft(N=110, dtype=np.float32) def test_1d_inverse(): check_1d_hfft_inverse(N=110) check_1d_hfft_inverse(N=110, dtype=np.float32) if __name__ == "__main__": import sys sys.exit(pytest.main(sys.argv))
796
14,668
<reponame>zealoussnow/chromium // Copyright 2020 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. #ifndef CHROME_BROWSER_ENTERPRISE_SIGNALS_SIGNALS_COMMON_H_ #define CHROME_BROWSER_ENTERPRISE_SIGNALS_SIGNALS_COMMON_H_ #include "third_party/abseil-cpp/absl/types/optional.h" namespace enterprise_signals { enum class SettingValue { NONE, UNKNOWN, DISABLED, ENABLED, }; // Converts |setting_value| to an optional boolean value. ENABLED and DISABLED // will be converted to true and false respectively. Other values will be // treated as missing, and nullopt will be returned instead. absl::optional<bool> SettingValueToBool(SettingValue setting_value); } // namespace enterprise_signals #endif // CHROME_BROWSER_ENTERPRISE_SIGNALS_SIGNALS_COMMON_H_
286
335
<gh_stars>100-1000 { "word": "Kaftan", "definitions": [ "A man's long belted tunic, worn in countries of the Near East.", "A woman's long loose dress.", "A loose shirt or top." ], "parts-of-speech": "Noun" }
110
736
#include "StdAfx.h" #include "Sodium.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::AsymmetricKeys FSecure::Crypto::Sodium::GenerateAsymmetricKeys() { ByteVector publicKey(PublicKey::Size), privateKey(PrivateKey::Size); if (crypto_box_keypair(publicKey.data(), privateKey.data())) throw std::runtime_error{ OBF("Asymmetric keys generation failed.") }; return std::make_pair(privateKey, publicKey); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::SignatureKeys FSecure::Crypto::Sodium::GenerateSignatureKeys() { ByteVector publicSignature(PublicSignature::Size), privateSignature(PrivateSignature::Size); if (crypto_sign_keypair(publicSignature.data(), privateSignature.data())) throw std::runtime_error{ OBF("Signature keys generation failed.") }; return std::make_pair(privateSignature, publicSignature); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::SymmetricKey FSecure::Crypto::Sodium::GenerateSymmetricKey() noexcept { ByteVector key(SymmetricKey::Size); crypto_secretbox_keygen(key.data()); return key; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::EncryptAnonymously(ByteView plaintext, SymmetricKey const& key) { Nonce<true> nonce; ByteVector encryptedMessage(plaintext.size() + crypto_secretbox_MACBYTES + Nonce<true>::Size); // Perpend ciphertext with nonce. memcpy(encryptedMessage.data(), nonce, Nonce<true>::Size); if (crypto_secretbox_easy(encryptedMessage.data() + Nonce<true>::Size, plaintext.data(), plaintext.size(), nonce, key.data())) throw std::runtime_error{ OBF("Encryption failed.") }; return encryptedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::DecryptFromAnonymous(ByteView message, SymmetricKey const& key) { // Sanity check. if (message.size() < Nonce<true>::Size + crypto_secretbox_MACBYTES) throw std::invalid_argument{ OBF("Ciphertext too short.") }; // Retrieve nonce. auto nonce = message.SubString(0, Nonce<true>::Size), ciphertext = message.SubString(Nonce<true>::Size); // Decrypt. ByteVector decryptedMessage(ciphertext.size() - crypto_secretbox_MACBYTES); if (crypto_secretbox_open_easy(decryptedMessage.data(), ciphertext.data(), ciphertext.size(), nonce.data(), key.data())) throw std::runtime_error{ OBF("Message forged.") }; return decryptedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::EncryptAnonymously(ByteView plaintext, PublicKey const& encryptionKey) { ByteVector ciphertext(plaintext.size() + crypto_box_SEALBYTES); if (crypto_box_seal(ciphertext.data(), plaintext.data(), plaintext.size(), encryptionKey.data())) throw std::runtime_error{ OBF("Encryption failed.") }; return ciphertext; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::DecryptFromAnonymous(ByteView ciphertext, PublicKey const& myEncryptionKey, PrivateKey const& myDecryptionKey) { // Sanity check. if (ciphertext.size() < crypto_box_SEALBYTES) throw std::invalid_argument{ "Ciphertext too short." }; ByteVector decryptedMesage(ciphertext.size() - crypto_box_SEALBYTES); if (crypto_box_seal_open(decryptedMesage.data(), ciphertext.data(), ciphertext.size(), myEncryptionKey.data(), myDecryptionKey.data())) throw std::runtime_error{ OBF("Message corrupted or not intended for this recipient.") }; return decryptedMesage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::EncryptAndSign(ByteView plaintext, SymmetricKey const& key, PrivateSignature const& signature) { return EncryptAnonymously(SignMessage(plaintext, signature), key); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::DecryptAndVerify(ByteView ciphertext, SymmetricKey const& key, PublicSignature const& signature) { return VerifyMessage(DecryptFromAnonymous(ciphertext, key), signature); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::EncryptAndAuthenticate(ByteView plaintext, PublicKey const& theirPublicKey, PrivateKey const& myPrivateKey) { Nonce<false> nonce; ByteVector encryptedMessage(plaintext.size() + crypto_box_MACBYTES + Nonce<false>::Size); // Perpend ciphertext with nonce. memcpy(encryptedMessage.data(), nonce, Nonce<false>::Size); if (crypto_box_easy(encryptedMessage.data() + Nonce<false>::Size, plaintext.data(), plaintext.size(), nonce, theirPublicKey.data(), myPrivateKey.data())) throw std::runtime_error{ OBF("Encryption failed.") }; return encryptedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::DecryptAndAuthenticate(ByteView message, PublicKey const& theirPublicKey, PrivateKey const& myPrivateKey) { // Sanity check. if (message.size() < Nonce<false>::Size + crypto_box_MACBYTES) throw std::invalid_argument{ OBF("Ciphertext too short.") }; // Retrieve nonce. auto nonce = message.SubString(0, Nonce<false>::Size), ciphertext = message.SubString(Nonce<false>::Size); // Decrypt. ByteVector decryptedMessage(ciphertext.size() - crypto_box_MACBYTES); if (crypto_box_open_easy(decryptedMessage.data(), ciphertext.data(), ciphertext.size(), nonce.data(), theirPublicKey.data(), myPrivateKey.data())) throw std::runtime_error{ OBF("Message forged.") }; return decryptedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::SignMessage(ByteView message, PrivateSignature const& signature) { ByteVector signedMessage(message.size() + crypto_sign_BYTES); if (crypto_sign(signedMessage.data(), nullptr, message.data(), message.size(), signature.data())) throw std::runtime_error{ OBF("Couldn't sign message.") }; return signedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::Crypto::Sodium::VerifyMessage(ByteView signedMessage, PublicSignature const& signature) { // Sanity check. if (signedMessage.size() < crypto_sign_BYTES) throw std::invalid_argument{ OBF("Signed message too short.") }; // Verify. ByteVector verifiedMessage(signedMessage.size() - crypto_sign_BYTES); if (crypto_sign_open(verifiedMessage.data(), nullptr, signedMessage.data(), signedMessage.size(), signature.data())) throw std::runtime_error{ OBF("Signature verification failed.") }; // TODO: using crypto_sign_open_detached it could return a ByteView of signedMessage without copy. return verifiedMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::PublicKey FSecure::Crypto::Sodium::ConvertToKey(PublicSignature const& signature) { ByteVector convertedKey(crypto_scalarmult_curve25519_BYTES); if (crypto_sign_ed25519_pk_to_curve25519(convertedKey.data(), signature.data())) throw std::runtime_error{ OBF("Signature to Key (public) Conversion failed.") }; return convertedKey; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::PrivateKey FSecure::Crypto::Sodium::ConvertToKey(PrivateSignature const& signature) { ByteVector convertedKey(crypto_scalarmult_curve25519_BYTES); if (crypto_sign_ed25519_sk_to_curve25519(convertedKey.data(), signature.data())) throw std::runtime_error{ OBF("Signature to Key (secret) conversion failed.") }; return convertedKey; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::PublicSignature FSecure::Crypto::Sodium::ExtractPublic(PrivateSignature const& signature) { ByteVector publicSignature(crypto_scalarmult_curve25519_BYTES); if (crypto_sign_ed25519_sk_to_pk(publicSignature.data(), signature.data())) throw std::runtime_error{ OBF("Signature (secret to public) conversion failed.") }; return publicSignature; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::ExchangeKeys FSecure::Crypto::Sodium::GenerateExchangeKeys() { ByteVector publicKey(ExchangePublicKey::Size); ByteVector privateKey(ExchangePrivateKey::Size); if (crypto_kx_keypair(publicKey.data(), privateKey.data())) throw std::runtime_error{ OBF("Exchange keys generation failed.") }; return { privateKey, publicKey }; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::Crypto::Sodium::SessionKeys FSecure::Crypto::Sodium::GenerateClientSessionKeys(ExchangeKeys const& selfKeys, ExchangePublicKey const& serverKey) { ByteVector rxKey(SessionRxKey::Size); ByteVector txKey(SessionTxKey::Size); if(crypto_kx_client_session_keys(rxKey.data(), txKey.data(), selfKeys.second.data(), selfKeys.first.data(), serverKey.data())) throw std::runtime_error{ OBF("Session keys generation failed.") }; return { rxKey, txKey }; } FSecure::Crypto::Sodium::SessionKeys FSecure::Crypto::Sodium::GenerateServerSessionKeys(ExchangeKeys const& selfKeys, ExchangePublicKey const& clientKey) { ByteVector rxKey(SessionRxKey::Size); ByteVector txKey(SessionTxKey::Size); if (crypto_kx_server_session_keys(rxKey.data(), txKey.data(), selfKeys.second.data(), selfKeys.first.data(), clientKey.data())) throw std::runtime_error{ OBF("Session keys generation failed.") }; return { rxKey, txKey }; } FSecure::ByteVector FSecure::Crypto::Sodium::Encrypt(ByteView plaintext, SessionTxKey const& key) { Nonce<true> nonce; ByteVector encryptedMessage(plaintext.size() + crypto_secretbox_MACBYTES + Nonce<true>::Size); // Perpend ciphertext with nonce. memcpy(encryptedMessage.data(), nonce, Nonce<true>::Size); if (crypto_secretbox_easy(encryptedMessage.data() + Nonce<true>::Size, plaintext.data(), plaintext.size(), nonce, key.data())) throw std::runtime_error{ OBF("Encryption failed.") }; return encryptedMessage; } FSecure::ByteVector FSecure::Crypto::Sodium::Decrypt(ByteView message, SessionRxKey const& key) { // Sanity check. if (message.size() < Nonce<true>::Size + crypto_secretbox_MACBYTES) throw std::invalid_argument{ OBF("Ciphertext too short.") }; // Retrieve nonce. auto nonce = message.SubString(0, Nonce<true>::Size), ciphertext = message.SubString(Nonce<true>::Size); // Decrypt. ByteVector decryptedMessage(ciphertext.size() - crypto_secretbox_MACBYTES); if (crypto_secretbox_open_easy(decryptedMessage.data(), ciphertext.data(), ciphertext.size(), nonce.data(), key.data())) throw std::runtime_error{ OBF("Message forged.") }; return decryptedMessage; }
3,276
929
<filename>automation/services/watchdog/util.py import json import os from kubernetes import client, config, stream import sys import traceback import asyncio import uuid import time import math def get_kubernetes(): if os.environ.get('LOCAL_KUBERNETES') is not None: config.load_kube_config() namespace = os.environ.get('KUBERNETES_NAMESPACE') else: config.load_incluster_config() with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: namespace = f.read() v1 = client.CoreV1Api() return v1, namespace async def run_periodically(fn, seconds_between, error_counter): while True: try: fn() except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() trace = traceback.format_exc() error_counter.inc() print(trace) await asyncio.sleep(seconds_between) # =============================================================== # kubernetes has issues streaming big blobs over - this function runs a command, and then breaks the result up over multiple requests to ensure the result makes it over safely def exec_on_pod(v1, namespace, pod, container, command, request_timeout_seconds = 600): def exec_cmd(command, timeout): exec_command = [ '/bin/bash', '-c', command, ] result = stream.stream(v1.connect_get_namespaced_pod_exec, pod, namespace, command=exec_command, container=container, stderr=True, stdout=True, stdin=False, tty=False, _request_timeout=timeout) return result print('running command:', command) tmp_file = '/tmp/cns_command.' + str(uuid.uuid4()) + '.out' start = time.time() result = exec_cmd(command + ' &> ' + tmp_file, request_timeout_seconds) end = time.time() print('done running command') print('\tseconds to run:', end - start) file_len = int(exec_cmd('stat --printf="%s" ' + tmp_file, 10)) print('\tfile length:', str(file_len/(1024*1024)) + 'MB') read_segment = lambda start, size: exec_cmd('cat ' + tmp_file + ' | head -c ' + str(start + size) + ' | tail -c ' + str(size), 240) chunk_size = int(20e6) read_chunk = lambda i: read_segment(i*chunk_size, min((i+1)*chunk_size, file_len) - i*chunk_size) num_chunks = math.ceil(file_len/chunk_size) start = time.time() chunks = list(map(read_chunk, range(num_chunks))) result = ''.join(chunks) end = time.time() print('\tseconds to get result:', end - start) exec_cmd('rm ' + tmp_file, 10) received_len = len(result.encode('utf-8')) if file_len != received_len: print('\twarning, result length didn\'t match received length', file_len, received_len) # seems to fail frequently # assert(file_len - received_len == 0 or file_len - received_len == 1) return result
983
3,974
#include "utf8_source.h" unsigned char Utf8Source_read(Utf8Source* utf8_source) { return utf8_source->read(utf8_source); } void Utf8Source_delete(Utf8Source* utf8_source) { utf8_source->del(utf8_source); }
95
995
//---------------------------------------------------------------------------// // Copyright (c) 2014 Roshan <<EMAIL>> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_ALGORITHM_PARTITION_POINT_HPP #define BOOST_COMPUTE_ALGORITHM_PARTITION_POINT_HPP #include <boost/static_assert.hpp> #include <boost/compute/system.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/algorithm/detail/binary_find.hpp> #include <boost/compute/type_traits/is_device_iterator.hpp> namespace boost { namespace compute { /// /// \brief Partition point algorithm /// /// Finds the end of true values in the partitioned range [first, last) /// \return Iterator pointing to end of true values /// /// \param first Iterator pointing to start of range /// \param last Iterator pointing to end of range /// \param predicate Unary predicate to be applied on each element /// \param queue Queue on which to execute /// /// Space complexity: \Omega(1) /// /// \see partition() and stable_partition() /// template<class InputIterator, class UnaryPredicate> inline InputIterator partition_point(InputIterator first, InputIterator last, UnaryPredicate predicate, command_queue &queue = system::default_queue()) { BOOST_STATIC_ASSERT(is_device_iterator<InputIterator>::value); return detail::binary_find(first, last, not1(predicate), queue); } } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_ALGORITHM_PARTITION_POINT_HPP
676
575
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DATA_REDUCTION_PROXY_DATA_REDUCTION_PROXY_CHROME_SETTINGS_H_ #define CHROME_BROWSER_DATA_REDUCTION_PROXY_DATA_REDUCTION_PROXY_CHROME_SETTINGS_H_ #include <memory> #include <string> #include "base/macros.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_request_options.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/keyed_service/core/keyed_service.h" #include "net/http/http_response_headers.h" class PrefService; class Profile; namespace base { class SequencedTaskRunner; } // namespace base namespace content { class NavigationHandle; } namespace data_reduction_proxy { class DataReductionProxyData; class DataStore; } // namespace data_reduction_proxy namespace subresource_redirect { class OriginRobotsRulesCache; } class HttpsImageCompressionInfoBarDecider; class LitePagesServiceBypassDecider; class PrefService; // Data reduction proxy settings class suitable for use with a Chrome browser. // It is keyed to a browser context. class DataReductionProxyChromeSettings : public data_reduction_proxy::DataReductionProxySettings, public KeyedService { public: // Enum values that can be reported for the // DataReductionProxy.ProxyPrefMigrationResult histogram. These values must be // kept in sync with their counterparts in histograms.xml. Visible here for // testing purposes. enum ProxyPrefMigrationResult { PROXY_PREF_NOT_CLEARED = 0, PROXY_PREF_CLEARED_EMPTY, PROXY_PREF_CLEARED_MODE_SYSTEM, PROXY_PREF_CLEARED_DRP, PROXY_PREF_CLEARED_GOOGLEZIP, PROXY_PREF_CLEARED_PAC_GOOGLEZIP, PROXY_PREF_MAX }; // Constructs a settings object. Construction and destruction must happen on // the UI thread. explicit DataReductionProxyChromeSettings(bool is_off_the_record_profile); // Destructs the settings object. ~DataReductionProxyChromeSettings() override; // Overrides KeyedService::Shutdown: void Shutdown() override; // Initialize the settings object with the given profile, data store, and db // task runner. void InitDataReductionProxySettings( Profile* profile, std::unique_ptr<data_reduction_proxy::DataStore> store, const scoped_refptr<base::SequencedTaskRunner>& db_task_runner); // Gets the client type for the data reduction proxy. static data_reduction_proxy::Client GetClient(); // Public for testing. void MigrateDataReductionProxyOffProxyPrefs(PrefService* prefs); // Builds an instance of DataReductionProxyData from the given |handle| and // |headers|. std::unique_ptr<data_reduction_proxy::DataReductionProxyData> CreateDataFromNavigationHandle(content::NavigationHandle* handle, const net::HttpResponseHeaders* headers); HttpsImageCompressionInfoBarDecider* https_image_compression_infobar_decider() { return https_image_compression_infobar_decider_.get(); } LitePagesServiceBypassDecider* litepages_service_bypass_decider() const { return litepages_service_bypass_decider_.get(); } subresource_redirect::OriginRobotsRulesCache* origin_robots_rules_cache() const { return origin_robots_rules_cache_.get(); } private: // Helper method for migrating the Data Reduction Proxy away from using the // proxy pref. Returns the ProxyPrefMigrationResult value indicating the // migration action taken. ProxyPrefMigrationResult MigrateDataReductionProxyOffProxyPrefsHelper( PrefService* prefs); // Maintains the decider for this profile that decides whether to show infobar // before triggering https image compression. std::unique_ptr<HttpsImageCompressionInfoBarDecider> https_image_compression_infobar_decider_; // Maintains the decider for this profile to contain logic for LitePages // service bypass. std::unique_ptr<LitePagesServiceBypassDecider> litepages_service_bypass_decider_; // Maintains the cache of robots rules. std::unique_ptr<subresource_redirect::OriginRobotsRulesCache> origin_robots_rules_cache_; // Null before InitDataReductionProxySettings is called. Profile* profile_; DISALLOW_COPY_AND_ASSIGN(DataReductionProxyChromeSettings); }; #endif // CHROME_BROWSER_DATA_REDUCTION_PROXY_DATA_REDUCTION_PROXY_CHROME_SETTINGS_H_
1,456
3,269
<reponame>Priyansh2/LeetCode-Solutions // Time: O(n) // Space: O(1) class Solution { public: vector<double> sampleStats(vector<int>& count) { const double mi = distance(count.cbegin(), find_if(count.cbegin(), count.cend(), [](int x) { return x != 0; })); const double ma = count.size() - 1 - distance(count.crbegin(), find_if(count.crbegin(), count.crend(), [](int x) { return x != 0; })); const auto& n = accumulate(count.cbegin(), count.cend(), 0); double total = 0.0; for (int i = 0; i < count.size(); ++i) { total += double(i) * count[i]; } const double mean = total / n; const double mode = distance(count.cbegin(), max_element(count.cbegin(), count.cend())); for (int i = 1; i < count.size(); ++i) { count[i] += count[i - 1]; } const auto& median1 = distance(count.cbegin(), lower_bound(count.cbegin(), count.cend(), (n + 1) / 2)); const auto& median2 = distance(count.cbegin(), lower_bound(count.cbegin(), count.cend(), (n + 2) / 2)); const double median = (median1 + median2) / 2.0; return {mi, ma, mean, median, mode}; } };
644
1,115
# -*- coding: future_annotations -*- import pytest from ffsubsync.aligners import FFTAligner, MaxScoreAligner @pytest.mark.parametrize('s1, s2, true_offset', [ ('111001', '11001', -1), ('1001', '1001', 0), ('10010', '01001', 1) ]) def test_fft_alignment(s1, s2, true_offset): assert FFTAligner().fit_transform(s2, s1) == true_offset assert MaxScoreAligner(FFTAligner).fit_transform(s2, s1)[0][1] == true_offset assert MaxScoreAligner(FFTAligner()).fit_transform(s2, s1)[0][1] == true_offset
222
6,989
#pragma once #include "base.h" /** * Returns system uptime */ TDuration Uptime();
33
634
package com.intellij.diagnostic; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.vfs.VirtualFile; import consulo.logging.attachment.Attachment; import javax.annotation.Nonnull; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; /** * @author yole */ public class AttachmentFactory { private static final String ERROR_MESSAGE_PATTERN = "[[[Can't get file contents: {0}]]]"; public static Attachment createContext(@Nonnull Object start, Object... more) { StringBuilder builder = new StringBuilder(String.valueOf(start)); for (Object o : more) builder.append(",").append(o); return consulo.logging.attachment.AttachmentFactory.get().create("current-context.txt", builder.length() > 0 ? builder.toString() : "(unknown)"); } public static Attachment createAttachment(Document document) { VirtualFile file = FileDocumentManager.getInstance().getFile(document); return consulo.logging.attachment.AttachmentFactory.get().create(file != null ? file.getPath() : "unknown.txt", document.getText()); } public static Attachment createAttachment(@Nonnull VirtualFile file) { return consulo.logging.attachment.AttachmentFactory.get().create(file.getPresentableUrl(), getBytes(file), file.getFileType().isBinary() ? "File is binary" : LoadTextUtil.loadText(file).toString()); } private static byte[] getBytes(VirtualFile file) { try { return file.contentsToByteArray(); } catch (IOException e) { return MessageFormat.format(ERROR_MESSAGE_PATTERN, e.getMessage()).getBytes(StandardCharsets.UTF_8); } } }
593
190,993
<reponame>EricRemmerswaal/tensorflow<gh_stars>1000+ /* Copyright 2020 The TensorFlow 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. ==============================================================================*/ #include <Python.h> #include <memory> #include <string> #include "pybind11/detail/common.h" #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #include "tensorflow/core/framework/function.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/python/lib/core/pybind11_status.h" struct ProtoComparisonOptions; // Forward declaration namespace tensorflow { namespace { namespace py = pybind11; namespace tf = tensorflow; struct ProtoComparisonOptions { bool treat_nan_as_equal; }; bool EqualsGraphDef(string graphdef_string1, string graphdef_string2, const ProtoComparisonOptions& options) { GraphDef graph_def_1; if (!graph_def_1.ParseFromString(graphdef_string1)) { MaybeRaiseFromStatus(errors::InvalidArgument( "Couldn't interpret first argument as a GraphDef")); } GraphDef graph_def_2; if (!graph_def_2.ParseFromString(graphdef_string2)) { MaybeRaiseFromStatus(errors::InvalidArgument( "Couldn't interpret second argument as a GraphDef")); } tf::protobuf::util::MessageDifferencer differencer; // Order doesnt matter in node defs, or functions in the function library and // their nested nodes. differencer.TreatAsSet(GraphDef::descriptor()->FindFieldByName("node")); differencer.TreatAsSet( FunctionDefLibrary::descriptor()->FindFieldByName("function")); differencer.TreatAsSet( FunctionDefLibrary::descriptor()->FindFieldByName("gradient")); differencer.TreatAsSet( FunctionDef::descriptor()->FindFieldByName("node_def")); tf::protobuf::util::DefaultFieldComparator comparator; comparator.set_treat_nan_as_equal(options.treat_nan_as_equal); differencer.set_field_comparator(&comparator); return differencer.Compare(graph_def_1, graph_def_2); } PYBIND11_MODULE(_proto_comparators, m) { py::class_<tensorflow::ProtoComparisonOptions>(m, "ProtoComparisonOptions") .def(py::init<const bool&>()); m.def("EqualsGraphDef", &EqualsGraphDef, "GraphDef equality test taking comparison options."); } } // anonymous namespace } // namespace tensorflow
965
373
<gh_stars>100-1000 package com.dianrong.common.uniauth.common.bean.request; import com.dianrong.common.uniauth.common.bean.ThirdAccountType; import lombok.ToString; import java.util.Date; @ToString public class UserThirdAccountParam extends Operator { private static final long serialVersionUID = -383089391366171367L; private Long id; private Long userId; private String thirdAccount; private ThirdAccountType type; private Date lastLoginIp; private Date lastLoginTime; private Date createDate; private Date lastUpdate; public Long getId() { return id; } public UserThirdAccountParam setId(Long id) { this.id = id; return this; } public Long getUserId() { return userId; } public UserThirdAccountParam setUserId(Long userId) { this.userId = userId; return this; } public String getThirdAccount() { return thirdAccount; } public UserThirdAccountParam setThirdAccount(String thirdAccount) { this.thirdAccount = thirdAccount; return this; } public ThirdAccountType getType() { return type; } public UserThirdAccountParam setType(ThirdAccountType type) { this.type = type; return this; } public Date getLastLoginIp() { return lastLoginIp; } public UserThirdAccountParam setLastLoginIp(Date lastLoginIp) { this.lastLoginIp = lastLoginIp; return this; } public Date getLastLoginTime() { return lastLoginTime; } public UserThirdAccountParam setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; return this; } public Date getCreateDate() { return createDate; } public UserThirdAccountParam setCreateDate(Date createDate) { this.createDate = createDate; return this; } public Date getLastUpdate() { return lastUpdate; } public UserThirdAccountParam setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; return this; } }
648
5,169
<reponame>Gantios/Specs { "name": "CSCoreUtils", "version": "0.1.5", "summary": "A short description of CSCoreUtils.", "description": "常用工具整合框架", "homepage": "https://github.com/wleics/CSCoreUtils", "license": "MIT", "authors": { "wleics": "<EMAIL>" }, "source": { "git": "https://github.com/wleics/CSCoreUtils.git", "tag": "0.1.5" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "CSCoreUtils/Classes/**/*", "resource_bundles": { "CSCoreUtils": [ "CSCoreUtils/Assets/*" ] }, "public_header_files": "CSCoreUtils/Classes/**/*.h", "frameworks": [ "UIKit", "SystemConfiguration", "MobileCoreServices" ], "dependencies": { "AFNetworking": [ "~> 3.1" ], "MJExtension": [ ], "YYWebImage": [ ], "pop": [ "~> 1.0" ] } }
432
3,459
// // PVDolphin.h // PVDolphin // // Created by <NAME> on 9/5/21. // Copyright © 2021 Provenance. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for PVDolphin. FOUNDATION_EXPORT double PVDolphinVersionNumber; //! Project version string for PVDolphin. FOUNDATION_EXPORT const unsigned char PVDolphinVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <PVDolphin/PublicHeader.h> #import <PVDolphin/PVDolphinCore.h>
164
626
package org.jsmart.zerocode.parallel.restful; import org.jsmart.zerocode.core.domain.LoadWith; import org.jsmart.zerocode.core.domain.TestMapping; import org.jsmart.zerocode.core.domain.TestMappings; import org.jsmart.zerocode.core.runner.parallel.ZeroCodeMultiLoadRunner; import org.junit.runner.RunWith; @LoadWith("load_config_test.properties") @TestMappings({ @TestMapping(testClass = JunitRestTestSample.class, testMethod = "testGetCallToHome_pass"), @TestMapping(testClass = JunitRestTestSample.class, testMethod = "testGetCallToHome_pass"), // @TestMapping(testClass = JunitRestTestSample.class, testMethod = "testGetCallToHome_fail") }) @RunWith(ZeroCodeMultiLoadRunner.class) public class LoadRestEndPointMultiRunnerGroupTest { }
268
435
<reponame>amaajemyfren/data<filename>pycon-uk-2018/videos/pycon-uk-2018-monday-keynote-loek-van-gent.json { "copyright_text": null, "description": "Loek is Head of Engineering at `GoodUp <https://goodup.com>`__ in\nAmsterdam. He is also a long-time supporter of the Python in Africa\nmovement, and has taken part in several pioneering African PyCons.\n\nHis talk considers how social responsibility and software collaboration\nmeet, and why Python has a special place in this.\n", "duration": 3375, "language": "eng", "recorded": "2018-09-18", "related_urls": [ { "label": "Conference schedule", "url": "http://2018.pyconuk.org/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/nXVoxaOiT1c/maxresdefault.jpg", "title": "Keynote: Goes it a little good?", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=nXVoxaOiT1c" } ] }
380
12,252
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.console.page.realm.clientpolicies; import org.keycloak.testsuite.console.page.fragment.MultipleStringSelect2; import org.keycloak.testsuite.page.Form; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; import java.util.Set; /** * @author <NAME> <<EMAIL>> */ public class ConditionForm extends Form { @FindBy(xpath = ".//select[starts-with(@id, 'conditionType')]") private Select conditionTypeSelect; @FindBy(xpath = ".//*[starts-with(@id, 's2id_autogen')]") private MultipleStringSelect2 select2; public String getConditionType() { return conditionTypeSelect.getFirstSelectedOption().getText(); } public void setConditionType(String conditionType) { conditionTypeSelect.selectByVisibleText(conditionType); } public Set<String> getSelect2SelectedItems() { return select2.getSelected(); } public void selectSelect2Item(String item) { select2.select(item); } }
538
392
<reponame>mouthwater/rgb /* * Hashable interface. */ #ifndef INTERFACES__HASHABLE_HH #define INTERFACES__HASHABLE_HH namespace interfaces { /* * Template interface for hashable objects. * * If a class X extends hashable<T,H> then: * (1) X must be a T, and * (2) X must hash to an object of type H via its hash() method. * * Note that the interface is the same regardless of T's const qualifier. */ template <typename T, typename H> class hashable { public: /* * Destructor. */ virtual ~hashable(); /* * Function for hashing a hashable object. */ static H& hash(const hashable<T,H>&); /* * Hash method. */ virtual H& hash() const = 0; }; template <typename T, typename H> class hashable<const T,H> : public hashable<T,H> { }; /* * Destructor. */ template <typename T, typename H> hashable<T,H>::~hashable() { } /* * Function for hashing a hashable object. */ template <typename T, typename H> H& hashable<T,H>::hash(const hashable<T,H>& t) { return (t.hash()); } } /* namespace interfaces */ #endif
411
438
/* Char.java * ========================================================================= * This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net * * Copyright (C) 2004-2007 Universiteit Gent * Copyright (C) 2009 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * */ package org.scilab.forge.jlatexmath.core; import android.graphics.Typeface; /** * Represents a character together with its font, font ID and metric * information. */ public class Char { private final char c; private final Typeface font; private final Metrics m; private final int fontCode; public Char(char c, Typeface f, int fc, Metrics m) { font = f; fontCode = fc; this.c = c; this.m = m; } public CharFont getCharFont() { return new CharFont(c, fontCode); } public char getChar() { return c; } public Typeface getFont() { return font; } public int getFontCode() { return fontCode; } public float getWidth() { return m.getWidth(); } public float getItalic() { return m.getItalic(); } public float getHeight() { return m.getHeight(); } public float getDepth() { return m.getDepth(); } public Metrics getMetrics() { return m; } }
661
953
// Defines ArgTypeDef specialization for all fundamental types. #ifndef TRACING_FRAMEWORK_BINDINGS_CPP_INCLUDE_ARGTYPES_H_ #define TRACING_FRAMEWORK_BINDINGS_CPP_INCLUDE_ARGTYPES_H_ #include <string> #include "wtf/buffer.h" namespace wtf { namespace types { // ArgTypeDef for each supported type provides the WTF type name and a // function for emitting values of the type. template <typename ArgType> struct ArgTypeDef { static const size_t kSlotCount = 0; static const char* type_name() { return "unknown"; } static void Emit(EventBuffer* b, uint32_t* slots, ArgType value) {} }; // const char* -> ascii template <> struct ArgTypeDef<const char*> { static const size_t kSlotCount = 1; static const char* type_name() { return "ascii"; } static void Emit(EventBuffer* b, uint32_t* slots, const char* value) { int string_id = value ? b->string_table()->GetStringId(value) : StringTable::kEmptyStringId; slots[0] = string_id; } }; // const std::string -> ascii template <> struct ArgTypeDef<const std::string> { static const size_t kSlotCount = 1; static const char* type_name() { return "ascii"; } static void Emit(EventBuffer* b, uint32_t* slots, const std::string& value) { int string_id = value.empty() ? StringTable::kEmptyStringId : b->string_table()->GetStringId(value.c_str()); slots[0] = string_id; } }; template <typename T> struct Base32BitIntegralArgTypeDef { static const size_t kSlotCount = 1; static void Emit(EventBuffer* b, uint32_t* slots, T value) { slots[0] = static_cast<uint32_t>(value); } }; // uint8_t -> uint8 template <> struct ArgTypeDef<uint8_t> : Base32BitIntegralArgTypeDef<uint8_t> { static const char* type_name() { return "uint8"; } }; // uint16_t -> uint16 template <> struct ArgTypeDef<uint16_t> : Base32BitIntegralArgTypeDef<uint16_t> { static const char* type_name() { return "uint16"; } }; // uint32_t -> uint32 template <> struct ArgTypeDef<uint32_t> : Base32BitIntegralArgTypeDef<uint32_t> { static const char* type_name() { return "uint32"; } }; // int8_t -> int8 template <> struct ArgTypeDef<int8_t> : Base32BitIntegralArgTypeDef<int8_t> { static const char* type_name() { return "int8"; } }; // int16_t -> int16 template <> struct ArgTypeDef<int16_t> : Base32BitIntegralArgTypeDef<int16_t> { static const char* type_name() { return "int16"; } }; // int32_t -> int32 template <> struct ArgTypeDef<int32_t> : Base32BitIntegralArgTypeDef<int32_t> { static const char* type_name() { return "int32"; } }; template <typename T> struct Base64BitIntegralArgTypeDef { // TODO(laurenzo): WTF does not natively support 64 bit types. We just // truncate them until fixed. static const size_t kSlotCount = 1; static void Emit(EventBuffer* b, uint32_t* slots, T value) { slots[0] = static_cast<uint32_t>(value); } }; // uint64_t -> uint32 template <> struct ArgTypeDef<uint64_t> : Base64BitIntegralArgTypeDef<uint64_t> { static const char* type_name() { return "uint32"; } }; // int64_t -> int32 template <> struct ArgTypeDef<int64_t> : Base64BitIntegralArgTypeDef<int64_t> { static const char* type_name() { return "int32"; } }; // float -> float32 template <> struct ArgTypeDef<float> { static const char* type_name() { return "float32"; } static const size_t kSlotCount = 1; static void Emit(EventBuffer* b, uint32_t* slots, float value) { union { float float_value; uint32_t slot_value; } alias; alias.float_value = value; slots[0] = alias.slot_value; } }; // bool -> bool template <> struct ArgTypeDef<bool> { static const char* type_name() { return "bool"; } static const size_t kSlotCount = 1; static void Emit(EventBuffer* b, uint32_t* slots, bool value) { slots[0] = value ? 1 : 0; } }; // Does a compile time assert that the type is supported. template <typename T> struct AssertTypeDef { static constexpr bool Assert() { static_assert(ArgTypeDef<T>::kSlotCount > 0, "WTF does not support arguments of this type"); return true; } }; } // namespace types } // namespace wtf #endif // TRACING_FRAMEWORK_BINDINGS_CPP_INCLUDE_ARGTYPES_H_
1,614
2,542
<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Store { class ReplicatedStore::StateChangeAsyncOperation : public Common::AsyncOperation { public: StateChangeAsyncOperation( Store::ReplicatedStoreEvent::Enum event, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) : Common::AsyncOperation(callback, parent) , event_(event) { } __declspec(property(get=get_Event)) Store::ReplicatedStoreEvent::Enum Event; Store::ReplicatedStoreEvent::Enum get_Event() const { return event_; } void Complete(Store::ReplicatedStoreState::Enum state, Common::ErrorCode const & error) { state_ = state; this->TryComplete(this->shared_from_this(), error); } static Common::ErrorCode End(Common::AsyncOperationSPtr const & operation, __out Store::ReplicatedStoreState::Enum & result) { auto casted = AsyncOperation::End<StateChangeAsyncOperation>(operation); if (casted->Error.IsSuccess()) { result = casted->state_; } return casted->Error; } protected: virtual void OnStart(Common::AsyncOperationSPtr const &) { // intentional no-op: externally completed by ReplicatedStore::StateMachine } private: Store::ReplicatedStoreEvent::Enum event_; Store::ReplicatedStoreState::Enum state_; }; }
688
593
// class GxEPD : Base Class for Display Classes for e-Paper Displays from Dalian Good Display Co., Ltd.: www.good-display.com // // based on Demo Examples from Good Display, available here: http://www.good-display.com/download_list/downloadcategoryid=34&isMode=false.html // // Author : <NAME> // // Version : see library.properties // // License: GNU GENERAL PUBLIC LICENSE V3, see LICENSE // // Library: https://github.com/ZinggJM/GxEPD #ifndef _GxEPD_H_ #define _GxEPD_H_ #include <Arduino.h> #include <SPI.h> #include "GxIO/GxIO.h" #include "../../Adafruit-GFX-Library/Adafruit_GFX.h" // #include <Adafruit_GFX.h> #include "GxFont_GFX.h" // the only colors supported by any of these displays; mapping of other colors is class specific #define GxEPD_BLACK 0x0000 #define GxEPD_DARKGREY 0x7BEF /* 128, 128, 128 */ #define GxEPD_LIGHTGREY 0xC618 /* 192, 192, 192 */ #define GxEPD_WHITE 0xFFFF #define GxEPD_RED 0xF800 /* 255, 0, 0 */ //class GxEPD : public Adafruit_GFX class GxEPD : public GxFont_GFX { public: // bitmap presentation modes may be partially implemented by subclasses enum bm_mode { //BM_ModeSet bm_normal = 0, bm_default = 1, // for use for BitmapExamples // these potentially can be combined bm_invert = (1 << 1), bm_flip_x = (1 << 2), bm_flip_y = (1 << 3), bm_r90 = (1 << 4), bm_r180 = (1 << 5), bm_r270 = bm_r90 | bm_r180, bm_partial_update = (1 << 6), bm_invert_red = (1 << 7), bm_transparent = (1 << 8) }; public: //GxEPD(int16_t w, int16_t h) : Adafruit_GFX(w, h) {}; GxEPD(int16_t w, int16_t h) : GxFont_GFX(w, h) {}; virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; virtual void init(uint32_t serial_diag_bitrate = 0) = 0; // = 0 : disabled virtual void fillScreen(uint16_t color) = 0; // to buffer virtual void update(void) = 0; // to buffer, may be cropped, drawPixel() used, update needed, subclass may support some modes virtual void drawBitmap(const uint8_t *bitmap, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color, int16_t m = bm_normal) = 0; // to buffer, may be cropped, drawPixel() used, update needed, subclass may support some modes, default for example bitmaps virtual void drawExampleBitmap(const uint8_t *bitmap, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color, int16_t m = bm_default) { drawBitmap(bitmap, x, y, w, h, color, m); }; // monochrome or 4 gray or other to full screen, filled with white if size is less, no update needed virtual void drawPicture(const uint8_t *picture, uint32_t size) // b/w or grey is class specific { drawBitmap(picture, size); // default is monochrome }; // to full screen, filled with white if size is less, no update needed, black /white / red, for example bitmaps virtual void drawExamplePicture(const uint8_t *black_bitmap, const uint8_t *red_bitmap, uint32_t black_size, uint32_t red_size) {}; // to full screen, filled with white if size is less, no update needed, black /white / red, general version virtual void drawPicture(const uint8_t *black_bitmap, const uint8_t *red_bitmap, uint32_t black_size, uint32_t red_size, int16_t mode = bm_normal) {}; // monochrome to full screen, filled with white if size is less, no update needed virtual void drawBitmap(const uint8_t *bitmap, uint32_t size, int16_t m = bm_normal) = 0; // monochrome virtual void drawExampleBitmap(const uint8_t *bitmap, uint32_t size, int16_t m = bm_default) // monochrome { drawBitmap(bitmap, size, m); }; virtual void eraseDisplay(bool using_partial_update = false) {}; // partial update of rectangle from buffer to screen, does not power off virtual void updateWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h, bool using_rotation = true) {}; // partial update of rectangle at (xs,ys) from buffer to screen at (xd,yd), does not power off virtual void updateToWindow(uint16_t xs, uint16_t ys, uint16_t xd, uint16_t yd, uint16_t w, uint16_t h, bool using_rotation = true) {}; // terminate cleanly updateWindow or updateToWindow before removing power or long delays virtual void powerDown() = 0; protected: void drawBitmapBM(const uint8_t *bitmap, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color, int16_t m); static inline uint16_t gx_uint16_min(uint16_t a, uint16_t b) { return (a < b ? a : b); }; static inline uint16_t gx_uint16_max(uint16_t a, uint16_t b) { return (a > b ? a : b); }; }; #endif
1,960
506
<reponame>ghosty-be/Homepoint<filename>main/ui/ScreenNavigator.hpp<gh_stars>100-1000 #pragma once #include <ui/UIButton.h> #include <ui/UIWidget.hpp> #include <config/Icon.hpp> #include <ui/UIMosaicMenuWidget.hpp> #include <ui/UIPageButton.h> #include <util/stdextend.hpp> #include <algorithm> #include <functional> namespace gfx { template<typename NavigationDriver> class ScreenNavigator : public UIWidget { public: ScreenNavigator(ScreenDriver* screenptr, Frame frame, uint16_t tag) : UIWidget(screenptr, frame, tag) { }; ScreenNavigator(ScreenDriver* screenptr, std::weak_ptr<UIWidget> parent, Frame frame, uint16_t tag) : UIWidget(screenptr, parent, frame, tag) { }; void didTap(const TapEvent& tapEvt) override { if (mpSubViews.size() == 0) { return; } mpSubViews.at(mCurrentScreenPage)->didTap(tapEvt); } void draw() override { mpSubViews.at(mCurrentScreenPage)->draw(); } void pageUp() { mCurrentScreenPage = mCurrentScreenPage + 1 > (mpSubViews.size() - 1) ? 0 : mCurrentScreenPage + 1; mpSubViews.at(mCurrentScreenPage)->setRedrawSubviews(); } void pageDown() { mCurrentScreenPage = mCurrentScreenPage - 1 < 0 ? mpSubViews.size() - 1 : mCurrentScreenPage - 1; mpSubViews.at(mCurrentScreenPage)->setRedrawSubviews(); } void didTap(const ButtonEvent& btnEvt) override { int buttonInc = 0; switch (btnEvt.button) { case Button::A: buttonInc = -1; break; case Button::B: buttonInc = 1; break; case Button::C: handleSelectionEvent(btnEvt); return; default: buttonInc = 0; } auto& currentViews = mpSubViews.at(mCurrentScreenPage)->getSubViews(); mCurrentButtonSelected += buttonInc; std::for_each(currentViews.begin(), currentViews.end(), [](const auto& btn) { btn->setSelected(false); }); if (mCurrentButtonSelected > static_cast<int>(currentViews.size() - 1)) { pageUp(); mCurrentButtonSelected = 0; } else if (mCurrentButtonSelected < 0) { pageDown(); mCurrentButtonSelected = mpSubViews.at(mCurrentScreenPage)->getSubViews().size() - 1; } if (currentViews.size() == 0) { return; } mpSubViews.at(mCurrentScreenPage)->getSubViews().at(mCurrentButtonSelected)->setSelected(true); } void addSubviews(std::vector<WidgetPtr> widget, const bool needsDismissal = false) { const int buttonSpaces = needsDismissal ? 5 : 6; const auto needsPageButton = widget.size() > buttonSpaces; auto makeMosaicButton = [&]() { auto menuWidget = std::make_shared<UIMosaicMenuWidget>(mpScreen, shared_from_this(), mFrame, 3, 2, 998); menuWidget->setBackgroundColor(Color::BlackColor()); return menuWidget; }; auto makePageButton = [&]() { auto pageButton = std::make_shared<UIPageButton>(mpScreen, mFrame); // Capturing the class by reference causes // a segfault in the ESP32 toolchain pageButton->addPageUpAction([this](auto i){ this->pageUp(); }); pageButton->addPageDownAction([this](auto i){ this->pageDown(); }); return pageButton; }; if (needsPageButton) { const int widgetLimit = isTouchDriver ? 5 : 6; auto it = widget.begin(); while (std::distance(it, widget.end()) > widgetLimit) { auto menuWidget = makeMosaicButton(); auto nextIt = it; if (nextIt == widget.begin() && !isTouchDriver) { (*nextIt)->setSelected(true); } ::util::safe_advance(nextIt, widget.end(), widgetLimit); std::for_each(it, nextIt, [&](auto ele) { menuWidget->addSubview(ele); }); it = nextIt; if (isTouchDriver) { menuWidget->addSubview(makePageButton()); } mpSubViews.push_back(menuWidget); } // Add remaining views if (std::distance(it, widget.end()) > 0) { auto menuWidget = makeMosaicButton(); std::for_each(it, widget.end(), [&](auto ele) { menuWidget->addSubview(ele); }); if (isTouchDriver) { menuWidget->addSubview(makePageButton()); } mpSubViews.push_back(menuWidget); } } else { auto menuWidget = makeMosaicButton(); std::for_each(widget.begin(), widget.end(), [&](auto ele) { menuWidget->addSubview(ele); }); mpSubViews.push_back(menuWidget); } } void presentDismissalSubviews(std::vector<WidgetPtr> widget, ButtonCallback dismissCb) { if (!isTouchDriver) { (*widget.begin())->setSelected(true); } addSubviews(widget, true); auto& lastPage = mpSubViews.back(); auto backButton = std::make_shared<UIButton>(mpScreen, mFrame); backButton->setLabel("Back"); backButton->setTextColor(Color::WhiteColor()); backButton->setImage(util::GetIconFilePath("exit")); auto thisTag = mTag; backButton->addTargetAction([dismissCb, &thisTag](const uint16_t tag) { dismissCb(thisTag); }); if (lastPage->getNumSubviews() > 5) { auto menuWidget = std::make_shared<UIMosaicMenuWidget>(mpScreen, mFrame, 3, 2, 998); menuWidget->setBackgroundColor(Color::BlackColor()); menuWidget->addSubview(std::move(backButton)); UIWidget::addSubview(menuWidget); } else { lastPage->addSubview(backButton); } mIsPresenting = true; } void addSubview(WidgetPtr widget) { if ((mpSubViews.size() + 1) % 5 == 0) { // add Page button } UIWidget::addSubview(widget); } private: void handleSelectionEvent(const ButtonEvent& btnEvt) { auto& currentViews = mpSubViews.at(mCurrentScreenPage)->getSubViews(); auto selectedButton = std::find_if(currentViews.begin(), currentViews.end(), [](auto& btn) { return btn->isSelected(); }); if (selectedButton != currentViews.end()) { (*selectedButton)->didTap(btnEvt); } } int mCurrentScreenPage = 0; bool mIsPresenting{false}; // Check if we're using a TouchDriver at compile-time // to determine whether we need on-screen page buttons static constexpr bool isTouchDriver = std::is_same<NavigationDriver, gfx::TouchDriver<typename NavigationDriver::InnerDriver>>::value; int mCurrentButtonSelected = 0; }; } // namespace gfx
3,526
653
//===-- sanitizer_allocator_primary32.h -------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Part of the Sanitizer Allocator. // //===----------------------------------------------------------------------===// #ifndef SANITIZER_ALLOCATOR_H #error This file must be included inside sanitizer_allocator.h #endif template<class SizeClassAllocator> struct SizeClassAllocator32LocalCache; // SizeClassAllocator32 -- allocator for 32-bit address space. // This allocator can theoretically be used on 64-bit arch, but there it is less // efficient than SizeClassAllocator64. // // [kSpaceBeg, kSpaceBeg + kSpaceSize) is the range of addresses which can // be returned by MmapOrDie(). // // Region: // a result of a single call to MmapAlignedOrDieOnFatalError(kRegionSize, // kRegionSize). // Since the regions are aligned by kRegionSize, there are exactly // kNumPossibleRegions possible regions in the address space and so we keep // a ByteMap possible_regions to store the size classes of each Region. // 0 size class means the region is not used by the allocator. // // One Region is used to allocate chunks of a single size class. // A Region looks like this: // UserChunk1 .. UserChunkN <gap> MetaChunkN .. MetaChunk1 // // In order to avoid false sharing the objects of this class should be // chache-line aligned. struct SizeClassAllocator32FlagMasks { // Bit masks. enum { kRandomShuffleChunks = 1, kUseSeparateSizeClassForBatch = 2, }; }; template <class Params> class SizeClassAllocator32 { private: static const u64 kTwoLevelByteMapSize1 = (Params::kSpaceSize >> Params::kRegionSizeLog) >> 12; static const u64 kMinFirstMapSizeTwoLevelByteMap = 4; public: using AddressSpaceView = typename Params::AddressSpaceView; static const uptr kSpaceBeg = Params::kSpaceBeg; static const u64 kSpaceSize = Params::kSpaceSize; static const uptr kMetadataSize = Params::kMetadataSize; typedef typename Params::SizeClassMap SizeClassMap; static const uptr kRegionSizeLog = Params::kRegionSizeLog; typedef typename Params::MapUnmapCallback MapUnmapCallback; using ByteMap = typename conditional< (kTwoLevelByteMapSize1 < kMinFirstMapSizeTwoLevelByteMap), FlatByteMap<(Params::kSpaceSize >> Params::kRegionSizeLog), AddressSpaceView>, TwoLevelByteMap<kTwoLevelByteMapSize1, 1 << 12, AddressSpaceView>>::type; COMPILER_CHECK(!SANITIZER_SIGN_EXTENDED_ADDRESSES || (kSpaceSize & (kSpaceSize - 1)) == 0); static const bool kRandomShuffleChunks = Params::kFlags & SizeClassAllocator32FlagMasks::kRandomShuffleChunks; static const bool kUseSeparateSizeClassForBatch = Params::kFlags & SizeClassAllocator32FlagMasks::kUseSeparateSizeClassForBatch; struct TransferBatch { static const uptr kMaxNumCached = SizeClassMap::kMaxNumCachedHint - 2; void SetFromArray(void *batch[], uptr count) { DCHECK_LE(count, kMaxNumCached); count_ = count; for (uptr i = 0; i < count; i++) batch_[i] = batch[i]; } uptr Count() const { return count_; } void Clear() { count_ = 0; } void Add(void *ptr) { batch_[count_++] = ptr; DCHECK_LE(count_, kMaxNumCached); } void CopyToArray(void *to_batch[]) const { for (uptr i = 0, n = Count(); i < n; i++) to_batch[i] = batch_[i]; } // How much memory do we need for a batch containing n elements. static uptr AllocationSizeRequiredForNElements(uptr n) { return sizeof(uptr) * 2 + sizeof(void *) * n; } static uptr MaxCached(uptr size) { return Min(kMaxNumCached, SizeClassMap::MaxCachedHint(size)); } TransferBatch *next; private: uptr count_; void *batch_[kMaxNumCached]; }; static const uptr kBatchSize = sizeof(TransferBatch); COMPILER_CHECK((kBatchSize & (kBatchSize - 1)) == 0); COMPILER_CHECK(kBatchSize == SizeClassMap::kMaxNumCachedHint * sizeof(uptr)); static uptr ClassIdToSize(uptr class_id) { return (class_id == SizeClassMap::kBatchClassID) ? kBatchSize : SizeClassMap::Size(class_id); } typedef SizeClassAllocator32<Params> ThisT; typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache; void Init(s32 release_to_os_interval_ms, uptr heap_start = 0) { CHECK(!heap_start); possible_regions.Init(); internal_memset(size_class_info_array, 0, sizeof(size_class_info_array)); } s32 ReleaseToOSIntervalMs() const { return kReleaseToOSIntervalNever; } void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) { // This is empty here. Currently only implemented in 64-bit allocator. } void ForceReleaseToOS() { // Currently implemented in 64-bit allocator only. } void *MapWithCallback(uptr size) { void *res = MmapOrDie(size, PrimaryAllocatorName); MapUnmapCallback().OnMap((uptr)res, size); return res; } void UnmapWithCallback(uptr beg, uptr size) { MapUnmapCallback().OnUnmap(beg, size); UnmapOrDie(reinterpret_cast<void *>(beg), size); } static bool CanAllocate(uptr size, uptr alignment) { return size <= SizeClassMap::kMaxSize && alignment <= SizeClassMap::kMaxSize; } void *GetMetaData(const void *p) { CHECK(kMetadataSize); CHECK(PointerIsMine(p)); uptr mem = reinterpret_cast<uptr>(p); uptr beg = ComputeRegionBeg(mem); uptr size = ClassIdToSize(GetSizeClass(p)); u32 offset = mem - beg; uptr n = offset / (u32)size; // 32-bit division uptr meta = (beg + kRegionSize) - (n + 1) * kMetadataSize; return reinterpret_cast<void*>(meta); } NOINLINE TransferBatch *AllocateBatch(AllocatorStats *stat, AllocatorCache *c, uptr class_id) { DCHECK_LT(class_id, kNumClasses); SizeClassInfo *sci = GetSizeClassInfo(class_id); SpinMutexLock l(&sci->mutex); if (sci->free_list.empty()) { if (UNLIKELY(!PopulateFreeList(stat, c, sci, class_id))) return nullptr; DCHECK(!sci->free_list.empty()); } TransferBatch *b = sci->free_list.front(); sci->free_list.pop_front(); return b; } NOINLINE void DeallocateBatch(AllocatorStats *stat, uptr class_id, TransferBatch *b) { DCHECK_LT(class_id, kNumClasses); CHECK_GT(b->Count(), 0); SizeClassInfo *sci = GetSizeClassInfo(class_id); SpinMutexLock l(&sci->mutex); sci->free_list.push_front(b); } bool PointerIsMine(const void *p) { uptr mem = reinterpret_cast<uptr>(p); if (SANITIZER_SIGN_EXTENDED_ADDRESSES) mem &= (kSpaceSize - 1); if (mem < kSpaceBeg || mem >= kSpaceBeg + kSpaceSize) return false; return GetSizeClass(p) != 0; } uptr GetSizeClass(const void *p) const { return possible_regions[ComputeRegionId(reinterpret_cast<uptr>(p))]; } void *GetBlockBegin(const void *p) { CHECK(PointerIsMine(p)); uptr mem = reinterpret_cast<uptr>(p); uptr beg = ComputeRegionBeg(mem); uptr size = ClassIdToSize(GetSizeClass(p)); u32 offset = mem - beg; u32 n = offset / (u32)size; // 32-bit division uptr res = beg + (n * (u32)size); return reinterpret_cast<void*>(res); } uptr GetActuallyAllocatedSize(void *p) { CHECK(PointerIsMine(p)); return ClassIdToSize(GetSizeClass(p)); } static uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); } uptr TotalMemoryUsed() { // No need to lock here. uptr res = 0; for (uptr i = 0; i < kNumPossibleRegions; i++) if (possible_regions[i]) res += kRegionSize; return res; } void TestOnlyUnmap() { for (uptr i = 0; i < kNumPossibleRegions; i++) if (possible_regions[i]) UnmapWithCallback((i * kRegionSize), kRegionSize); } // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone // introspection API. void ForceLock() NO_THREAD_SAFETY_ANALYSIS { for (uptr i = 0; i < kNumClasses; i++) { GetSizeClassInfo(i)->mutex.Lock(); } } void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS { for (int i = kNumClasses - 1; i >= 0; i--) { GetSizeClassInfo(i)->mutex.Unlock(); } } // Iterate over all existing chunks. // The allocator must be locked when calling this function. void ForEachChunk(ForEachChunkCallback callback, void *arg) const { for (uptr region = 0; region < kNumPossibleRegions; region++) if (possible_regions[region]) { uptr chunk_size = ClassIdToSize(possible_regions[region]); uptr max_chunks_in_region = kRegionSize / (chunk_size + kMetadataSize); uptr region_beg = region * kRegionSize; for (uptr chunk = region_beg; chunk < region_beg + max_chunks_in_region * chunk_size; chunk += chunk_size) { // Too slow: CHECK_EQ((void *)chunk, GetBlockBegin((void *)chunk)); callback(chunk, arg); } } } void PrintStats() {} static uptr AdditionalSize() { return 0; } typedef SizeClassMap SizeClassMapT; static const uptr kNumClasses = SizeClassMap::kNumClasses; private: static const uptr kRegionSize = 1 << kRegionSizeLog; static const uptr kNumPossibleRegions = kSpaceSize / kRegionSize; struct ALIGNED(SANITIZER_CACHE_LINE_SIZE) SizeClassInfo { StaticSpinMutex mutex; IntrusiveList<TransferBatch> free_list; u32 rand_state; }; COMPILER_CHECK(sizeof(SizeClassInfo) % kCacheLineSize == 0); uptr ComputeRegionId(uptr mem) const { if (SANITIZER_SIGN_EXTENDED_ADDRESSES) mem &= (kSpaceSize - 1); const uptr res = mem >> kRegionSizeLog; CHECK_LT(res, kNumPossibleRegions); return res; } uptr ComputeRegionBeg(uptr mem) { return mem & ~(kRegionSize - 1); } uptr AllocateRegion(AllocatorStats *stat, uptr class_id) { DCHECK_LT(class_id, kNumClasses); const uptr res = reinterpret_cast<uptr>(MmapAlignedOrDieOnFatalError( kRegionSize, kRegionSize, PrimaryAllocatorName)); if (UNLIKELY(!res)) return 0; MapUnmapCallback().OnMap(res, kRegionSize); stat->Add(AllocatorStatMapped, kRegionSize); CHECK(IsAligned(res, kRegionSize)); possible_regions.set(ComputeRegionId(res), static_cast<u8>(class_id)); return res; } SizeClassInfo *GetSizeClassInfo(uptr class_id) { DCHECK_LT(class_id, kNumClasses); return &size_class_info_array[class_id]; } bool PopulateBatches(AllocatorCache *c, SizeClassInfo *sci, uptr class_id, TransferBatch **current_batch, uptr max_count, uptr *pointers_array, uptr count) { // If using a separate class for batches, we do not need to shuffle it. if (kRandomShuffleChunks && (!kUseSeparateSizeClassForBatch || class_id != SizeClassMap::kBatchClassID)) RandomShuffle(pointers_array, count, &sci->rand_state); TransferBatch *b = *current_batch; for (uptr i = 0; i < count; i++) { if (!b) { b = c->CreateBatch(class_id, this, (TransferBatch*)pointers_array[i]); if (UNLIKELY(!b)) return false; b->Clear(); } b->Add((void*)pointers_array[i]); if (b->Count() == max_count) { sci->free_list.push_back(b); b = nullptr; } } *current_batch = b; return true; } bool PopulateFreeList(AllocatorStats *stat, AllocatorCache *c, SizeClassInfo *sci, uptr class_id) { const uptr region = AllocateRegion(stat, class_id); if (UNLIKELY(!region)) return false; if (kRandomShuffleChunks) if (UNLIKELY(sci->rand_state == 0)) // The random state is initialized from ASLR (PIE) and time. sci->rand_state = reinterpret_cast<uptr>(sci) ^ NanoTime(); const uptr size = ClassIdToSize(class_id); const uptr n_chunks = kRegionSize / (size + kMetadataSize); const uptr max_count = TransferBatch::MaxCached(size); DCHECK_GT(max_count, 0); TransferBatch *b = nullptr; constexpr uptr kShuffleArraySize = 48; uptr shuffle_array[kShuffleArraySize]; uptr count = 0; for (uptr i = region; i < region + n_chunks * size; i += size) { shuffle_array[count++] = i; if (count == kShuffleArraySize) { if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count, shuffle_array, count))) return false; count = 0; } } if (count) { if (UNLIKELY(!PopulateBatches(c, sci, class_id, &b, max_count, shuffle_array, count))) return false; } if (b) { CHECK_GT(b->Count(), 0); sci->free_list.push_back(b); } return true; } ByteMap possible_regions; SizeClassInfo size_class_info_array[kNumClasses]; };
5,257
625
#include "libtrading/proto/xdp_message.h" #include "libtrading/buffer.h" #include <stdlib.h> #include <string.h> int xdp_message_decode(struct buffer *buf, struct xdp_message *msg, size_t size) { size_t available; u16 msg_size; available = buffer_size(buf); if (!available) return -1; msg_size = buffer_peek_le16(buf); if (msg_size > size) return -1; memcpy(msg, buffer_start(buf), msg_size); buffer_advance(buf, msg_size); return 0; }
189
335
{ "word": "Irregular", "definitions": [ "Not even or balanced in shape or arrangement.", "Occurring at uneven or varying rates or intervals.", "(of a flower) having the petals differing in size and shape; zygomorphic.", "Contrary to the rules or to that which is normal or established.", "(of troops) not belonging to regular or established army units.", "(of a verb or other word) having inflections that do not conform to the usual rules." ], "parts-of-speech": "Adjective" }
182
1,682
<gh_stars>1000+ /* Copyright (c) 2017 LinkedIn Corp. 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.linkedin.restli.client; import com.linkedin.common.callback.Callback; import com.linkedin.common.util.None; import com.linkedin.r2.message.RequestContext; import com.linkedin.restli.client.multiplexer.MultiplexedRequest; import com.linkedin.restli.client.multiplexer.MultiplexedResponse; /** * Rest.li client interface with overloading methods for sending Rest.li {@link Request} * * @author <NAME> */ public interface Client { /** * Resource name of {@link MultiplexedRequest} */ String MULTIPLEXER_RESOURCE = "mux"; /** * Batching strategy for partition and sticky routine support */ String SCATTER_GATHER_STRATEGY = "SCATTER_GATHER_STRATEGY"; /** * Shuts down the underlying {@link com.linkedin.r2.transport.common.Client} which this RestClient wraps. * @param callback */ void shutdown(Callback<None> callback); /** * Sends a type-bound REST request, returning a future. * * * @param request to send * @param requestContext context for the request * @return response future */ <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext); /** * Sends a type-bound REST request, returning a future. * * * @param request to send * @param requestContext context for the request * @param errorHandlingBehavior error handling behavior * @return response future */ <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext, ErrorHandlingBehavior errorHandlingBehavior); /** * Sends a type-bound REST request, returning a future. * * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @param requestContext context for the request * @return response future */ <T> ResponseFuture<T> sendRequest(RequestBuilder<? extends Request<T>> requestBuilder, RequestContext requestContext); /** * Sends a type-bound REST request, returning a future. * * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @param requestContext context for the request * @param errorHandlingBehavior error handling behavior * @return response future */ <T> ResponseFuture<T> sendRequest(RequestBuilder<? extends Request<T>> requestBuilder, RequestContext requestContext, ErrorHandlingBehavior errorHandlingBehavior); /** * Sends a type-bound REST request using a callback. * * @param request to send * @param requestContext context for the request * @param callback to call on request completion. In the event of an error, the callback * will receive a {@link com.linkedin.r2.RemoteInvocationException}. If a valid * error response was received from the remote server, the callback will receive * a {@link RestLiResponseException} containing the error details. */ <T> void sendRequest(Request<T> request, RequestContext requestContext, Callback<Response<T>> callback); /** * Sends a type-bound REST request using a callback. * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @param requestContext context for the request * @param callback to call on request completion. In the event of an error, the callback * will receive a {@link com.linkedin.r2.RemoteInvocationException}. If a valid * error response was received from the remote server, the callback will receive * a {@link RestLiResponseException} containing the error details. */ <T> void sendRequest(RequestBuilder<? extends Request<T>> requestBuilder, RequestContext requestContext, Callback<Response<T>> callback); /** * Sends a type-bound REST request, returning a future * @param request to send * @return response future */ <T> ResponseFuture<T> sendRequest(Request<T> request); /** * Sends a type-bound REST request, returning a future * @param request to send * @param errorHandlingBehavior error handling behavior * @return response future */ <T> ResponseFuture<T> sendRequest(Request<T> request, ErrorHandlingBehavior errorHandlingBehavior); /** * Sends a type-bound REST request, returning a future * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @return response future */ <T> ResponseFuture<T> sendRequest(RequestBuilder<? extends Request<T>> requestBuilder); /** * Sends a type-bound REST request, returning a future * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @param errorHandlingBehavior error handling behavior * @return response future */ <T> ResponseFuture<T> sendRequest(RequestBuilder<? extends Request<T>> requestBuilder, ErrorHandlingBehavior errorHandlingBehavior); /** * Sends a type-bound REST request using a callback. * * @param request to send * @param callback to call on request completion. In the event of an error, the callback * will receive a {@link com.linkedin.r2.RemoteInvocationException}. If a valid * error response was received from the remote server, the callback will receive * a {@link RestLiResponseException} containing the error details. */ <T> void sendRequest(Request<T> request, Callback<Response<T>> callback); /** * Sends a type-bound REST request using a callback. * * @param requestBuilder to invoke {@link RequestBuilder#build()} on to obtain the request * to send. * @param callback to call on request completion. In the event of an error, the callback * will receive a {@link com.linkedin.r2.RemoteInvocationException}. If a valid * error response was received from the remote server, the callback will receive * a {@link RestLiResponseException} containing the error details. */ <T> void sendRequest(RequestBuilder<? extends Request<T>> requestBuilder, Callback<Response<T>> callback); /** * Sends a multiplexed request. Responses are provided to individual requests' callbacks. * * The request is sent using the protocol version 2.0. * * @param multiplexedRequest the request to send. */ void sendRequest(MultiplexedRequest multiplexedRequest); /** * Sends a multiplexed request. Responses are provided to individual requests' callbacks. After all responses are * received the given aggregated callback is invoked. * * The request is sent using the protocol version 2.0. * * @param multiplexedRequest the multiplexed request to send. * @param callback the aggregated response callback. */ void sendRequest(MultiplexedRequest multiplexedRequest, Callback<MultiplexedResponse> callback); /** * Sends a multiplexed request. Responses are provided to individual requests' callbacks. After all responses are * received the given aggregated callback is invoked. * * The request is sent using the protocol version 2.0. * * @param multiplexedRequest the multiplexed request to send. * @param requestContext context for the request * @param callback the aggregated response callback. */ void sendRequest(MultiplexedRequest multiplexedRequest, RequestContext requestContext, Callback<MultiplexedResponse> callback); }
2,614
4,036
class A { class C { public: virtual void insert(void *) {} }; class C1 : public C { public: A *a; }; class C2 : public C { }; class B { public: C *c; B() {} B(C *c) { this->c = c; } void set(C *c) { this->c = c; } C *get() { return this->c; } static B *make(C *c) { return new B(c); } }; public: void f0() { C cc; C ct; cc.insert(nullptr); ct.insert(new C()); sink(&cc); // no flow sink(&ct); // $ ast MISSING: ir } void f1() { C *c = new C(); B *b = B::make(c); sink(b->c); // $ast MISSING: ir } void f2() { B *b = new B(); b->set(new C1()); sink(b->get()); // $ ast ir=55:12 sink((new B(new C()))->get()); // $ ast ir } void f3() { B *b1 = new B(); B *b2; b2 = setOnB(b1, new C2()); sink(b1->c); // no flow sink(b2->c); // $ ast MISSING: ir } void f4() { B *b1 = new B(); B *b2; b2 = setOnBWrap(b1, new C2()); sink(b1->c); // no flow sink(b2->c); // $ ast MISSING: ir } B *setOnBWrap(B *b1, C *c) { B *b2; b2 = setOnB(b1, c); return r() ? b1 : b2; } A::B *setOnB(B *b1, C *c) { if (r()) { B *b2 = new B(); b2->set(c); return b2; } return b1; } void f5() { A *a = new A(); C1 *c1 = new C1(); c1->a = a; f6(c1); } void f6(C *c) { if (C1 *c1 = dynamic_cast<C1 *>(c)) { sink(c1->a); // $ ast,ir } C *cc; if (C2 *c2 = dynamic_cast<C2 *>(c)) { cc = c2; } else { cc = new C1(); } if (C1 *c1 = dynamic_cast<C1 *>(cc)) { sink(c1->a); // $ SPURIOUS: ast } } void f7(B *b) { b->set(new C()); } void f8() { B *b = new B(); f7(b); sink(b->c); // $ ast,ir } class D { public: A::B *b; D(A::B *b, bool x) { b->c = new C(); this->b = x ? b : new B(); } }; void f9() { B *b = new B(); D *d = new D(b, r()); sink(d->b); // $ ast,ir=143:25 ast,ir=150:12 sink(d->b->c); // $ ast MISSING: ir sink(b->c); // $ ast,ir } void f10() { B *b = new B(); MyList *l1 = new MyList(b, new MyList(nullptr, nullptr)); MyList *l2 = new MyList(nullptr, l1); MyList *l3 = new MyList(nullptr, l2); sink(l3->head); // no flow, b is nested beneath at least one ->next sink(l3->next->head); // no flow sink(l3->next->next->head); // $ ast MISSING: ir sink(l3->next->next->next->head); // no flow for (MyList *l = l3; l != nullptr; l = l->next) { sink(l->head); // $ ast MISSING: ir } } static void sink(void *o) {} bool r() { return reinterpret_cast<long long>(this) % 10 > 5; } class MyList { public: B *head; MyList *next; MyList(B *newHead, MyList *next) { head = newHead; this->next = next; } }; };
1,632
7,158
<filename>modules/rgbd/include/opencv2/rgbd/kinfu.hpp // This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html // This code is also subject to the license terms in the LICENSE_KinectFusion.md file found in this module's directory #ifndef __OPENCV_RGBD_KINFU_HPP__ #define __OPENCV_RGBD_KINFU_HPP__ #include "opencv2/core.hpp" #include "opencv2/core/affine.hpp" #include <opencv2/rgbd/volume.hpp> namespace cv { namespace kinfu { //! @addtogroup kinect_fusion //! @{ struct CV_EXPORTS_W Params { CV_WRAP Params(){} /** * @brief Constructor for Params * Sets the initial pose of the TSDF volume. * @param volumeInitialPoseRot rotation matrix * @param volumeInitialPoseTransl translation vector */ CV_WRAP Params(Matx33f volumeInitialPoseRot, Vec3f volumeInitialPoseTransl) { setInitialVolumePose(volumeInitialPoseRot,volumeInitialPoseTransl); } /** * @brief Constructor for Params * Sets the initial pose of the TSDF volume. * @param volumeInitialPose 4 by 4 Homogeneous Transform matrix to set the intial pose of TSDF volume */ CV_WRAP Params(Matx44f volumeInitialPose) { setInitialVolumePose(volumeInitialPose); } /** * @brief Set Initial Volume Pose * Sets the initial pose of the TSDF volume. * @param R rotation matrix * @param t translation vector */ CV_WRAP void setInitialVolumePose(Matx33f R, Vec3f t); /** * @brief Set Initial Volume Pose * Sets the initial pose of the TSDF volume. * @param homogen_tf 4 by 4 Homogeneous Transform matrix to set the intial pose of TSDF volume */ CV_WRAP void setInitialVolumePose(Matx44f homogen_tf); /** * @brief Default parameters * A set of parameters which provides better model quality, can be very slow. */ CV_WRAP static Ptr<Params> defaultParams(); /** @brief Coarse parameters A set of parameters which provides better speed, can fail to match frames in case of rapid sensor motion. */ CV_WRAP static Ptr<Params> coarseParams(); /** @brief HashTSDF parameters A set of parameters suitable for use with HashTSDFVolume */ CV_WRAP static Ptr<Params> hashTSDFParams(bool isCoarse); /** @brief ColoredTSDF parameters A set of parameters suitable for use with ColoredTSDFVolume */ CV_WRAP static Ptr<Params> coloredTSDFParams(bool isCoarse); /** @brief frame size in pixels */ CV_PROP_RW Size frameSize; /** @brief rgb frame size in pixels */ CV_PROP_RW kinfu::VolumeType volumeType; /** @brief camera intrinsics */ CV_PROP_RW Matx33f intr; /** @brief rgb camera intrinsics */ CV_PROP_RW Matx33f rgb_intr; /** @brief pre-scale per 1 meter for input values Typical values are: * 5000 per 1 meter for the 16-bit PNG files of TUM database * 1000 per 1 meter for Kinect 2 device * 1 per 1 meter for the 32-bit float images in the ROS bag files */ CV_PROP_RW float depthFactor; /** @brief Depth sigma in meters for bilateral smooth */ CV_PROP_RW float bilateral_sigma_depth; /** @brief Spatial sigma in pixels for bilateral smooth */ CV_PROP_RW float bilateral_sigma_spatial; /** @brief Kernel size in pixels for bilateral smooth */ CV_PROP_RW int bilateral_kernel_size; /** @brief Number of pyramid levels for ICP */ CV_PROP_RW int pyramidLevels; /** @brief Resolution of voxel space Number of voxels in each dimension. */ CV_PROP_RW Vec3i volumeDims; /** @brief Size of voxel in meters */ CV_PROP_RW float voxelSize; /** @brief Minimal camera movement in meters Integrate new depth frame only if camera movement exceeds this value. */ CV_PROP_RW float tsdf_min_camera_movement; /** @brief initial volume pose in meters */ Affine3f volumePose; /** @brief distance to truncate in meters Distances to surface that exceed this value will be truncated to 1.0. */ CV_PROP_RW float tsdf_trunc_dist; /** @brief max number of frames per voxel Each voxel keeps running average of distances no longer than this value. */ CV_PROP_RW int tsdf_max_weight; /** @brief A length of one raycast step How much voxel sizes we skip each raycast step */ CV_PROP_RW float raycast_step_factor; // gradient delta in voxel sizes // fixed at 1.0f // float gradient_delta_factor; /** @brief light pose for rendering in meters */ CV_PROP_RW Vec3f lightPose; /** @brief distance theshold for ICP in meters */ CV_PROP_RW float icpDistThresh; /** angle threshold for ICP in radians */ CV_PROP_RW float icpAngleThresh; /** number of ICP iterations for each pyramid level */ CV_PROP_RW std::vector<int> icpIterations; /** @brief Threshold for depth truncation in meters All depth values beyond this threshold will be set to zero */ CV_PROP_RW float truncateThreshold; }; /** @brief KinectFusion implementation This class implements a 3d reconstruction algorithm described in @cite kinectfusion paper. It takes a sequence of depth images taken from depth sensor (or any depth images source such as stereo camera matching algorithm or even raymarching renderer). The output can be obtained as a vector of points and their normals or can be Phong-rendered from given camera pose. An internal representation of a model is a voxel cuboid that keeps TSDF values which are a sort of distances to the surface (for details read the @cite kinectfusion article about TSDF). There is no interface to that representation yet. KinFu uses OpenCL acceleration automatically if available. To enable or disable it explicitly use cv::setUseOptimized() or cv::ocl::setUseOpenCL(). This implementation is based on [kinfu-remake](https://github.com/Nerei/kinfu_remake). Note that the KinectFusion algorithm was patented and its use may be restricted by the list of patents mentioned in README.md file in this module directory. That's why you need to set the OPENCV_ENABLE_NONFREE option in CMake to use KinectFusion. */ class CV_EXPORTS_W KinFu { public: CV_WRAP static Ptr<KinFu> create(const Ptr<Params>& _params); virtual ~KinFu(); /** @brief Get current parameters */ virtual const Params& getParams() const = 0; /** @brief Renders a volume into an image Renders a 0-surface of TSDF using Phong shading into a CV_8UC4 Mat. Light pose is fixed in KinFu params. @param image resulting image */ CV_WRAP virtual void render(OutputArray image) const = 0; /** @brief Renders a volume into an image Renders a 0-surface of TSDF using Phong shading into a CV_8UC4 Mat. Light pose is fixed in KinFu params. @param image resulting image @param cameraPose pose of camera to render from. If empty then render from current pose which is a last frame camera pose. */ CV_WRAP virtual void render(OutputArray image, const Matx44f& cameraPose) const = 0; /** @brief Gets points and normals of current 3d mesh The order of normals corresponds to order of points. The order of points is undefined. @param points vector of points which are 4-float vectors @param normals vector of normals which are 4-float vectors */ CV_WRAP virtual void getCloud(OutputArray points, OutputArray normals) const = 0; /** @brief Gets points of current 3d mesh The order of points is undefined. @param points vector of points which are 4-float vectors */ CV_WRAP virtual void getPoints(OutputArray points) const = 0; /** @brief Calculates normals for given points @param points input vector of points which are 4-float vectors @param normals output vector of corresponding normals which are 4-float vectors */ CV_WRAP virtual void getNormals(InputArray points, OutputArray normals) const = 0; /** @brief Resets the algorithm Clears current model and resets a pose. */ CV_WRAP virtual void reset() = 0; /** @brief Get current pose in voxel space */ virtual const Affine3f getPose() const = 0; /** @brief Process next depth frame Integrates depth into voxel space with respect to its ICP-calculated pose. Input image is converted to CV_32F internally if has another type. @param depth one-channel image which size and depth scale is described in algorithm's parameters @return true if succeeded to align new frame with current scene, false if opposite */ CV_WRAP virtual bool update(InputArray depth) = 0; }; //! @} } } #endif
2,995
1,168
<filename>tools/build_rules/verifier_test/jvm_verifier_test.bzl # Copyright 2019 The Kythe 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. load( ":verifier_test.bzl", "KytheVerifierSources", "extract", "index_compilation", "verifier_test", ) def _invoke(rulefn, name, **kwargs): """Invoke rulefn with name and kwargs, returning the label of the rule.""" rulefn(name = name, **kwargs) return "//{}:{}".format(native.package_name(), name) def _jvm_extract_kzip_impl(ctx): jars = [] for dep in ctx.attr.deps: jars.append(dep[JavaInfo].full_compile_jars) jars = depset(transitive = jars) extract( srcs = jars, ctx = ctx, extractor = ctx.executable.extractor, kzip = ctx.outputs.kzip, mnemonic = "JvmExtractKZip", opts = ctx.attr.opts, vnames_config = ctx.file.vnames_config, ) return [KytheVerifierSources(files = depset())] jvm_extract_kzip = rule( attrs = { "extractor": attr.label( default = Label("//kythe/java/com/google/devtools/kythe/extractors/jvm:jar_extractor"), executable = True, cfg = "host", ), "opts": attr.string_list(), "vnames_config": attr.label( default = Label("//external:vnames_config"), allow_single_file = True, ), "deps": attr.label_list( providers = [JavaInfo], ), }, outputs = {"kzip": "%{name}.kzip"}, implementation = _jvm_extract_kzip_impl, ) def jvm_verifier_test( name, srcs, deps = [], size = "small", tags = [], indexer_opts = [], verifier_opts = ["--ignore_dups"], visibility = None): """Extract, analyze, and verify a JVM compilation. Args: srcs: Source files containing verifier goals for the JVM compilation deps: List of java/jvm verifier_test targets to be used as compilation dependencies indexer_opts: List of options passed to the indexer tool verifier_opts: List of options passed to the verifier tool """ kzip = _invoke( jvm_extract_kzip, name = name + "_kzip", testonly = True, tags = tags, visibility = visibility, # This is a hack to depend on the .jar producer. deps = [d + "_kzip" for d in deps], ) indexer = "//kythe/java/com/google/devtools/kythe/analyzers/jvm:class_file_indexer" entries = _invoke( index_compilation, name = name + "_entries", testonly = True, indexer = indexer, opts = indexer_opts, tags = tags, visibility = visibility, deps = [kzip], ) return _invoke( verifier_test, name = name, size = size, srcs = [entries] + srcs, opts = verifier_opts, tags = tags, visibility = visibility, deps = [entries], )
1,509
1,109
# -*- coding: utf-8 -*- from collections import defaultdict from datetime import datetime, date, timedelta import json import os import requests import uuid from decimal import * from delorean import Delorean from sqlalchemy import ForeignKey, Column, Integer, Unicode, DateTime, UnicodeText, Numeric from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import and_, func from gryphon.lib import gryphon_json_serialize from gryphon.lib.exchange.consts import Consts from gryphon.lib.exchange.exchange_factory import make_exchange_from_key from gryphon.lib.logger import get_logger from gryphon.lib.models.base import Base from gryphon.lib.money import Money from gryphon.lib.util.list import flatten logger = get_logger(__name__) metadata = Base.metadata class Transaction(Base): __tablename__ = 'transaction' #Transaction Types WITHDRAWL = 'WITHDRAWL' DEPOSIT = 'DEPOSIT' #Transaction Status' IN_TRANSIT = 'IN_TRANSIT' COMPLETED = 'COMPLETED' CANCELED = 'CANCELED' transaction_id = Column(Integer, primary_key=True) transaction_type = Column(Unicode(64)) transaction_status = Column(Unicode(64)) unique_id = Column(Unicode(64), nullable=False) time_created = Column(DateTime, nullable=False) time_completed = Column(DateTime, nullable=True) _amount = Column('amount', Numeric(precision=24, scale=14)) _amount_currency = Column('amount_currency', Unicode(3)) _fee = Column('fee', Numeric(precision=24, scale=14)) _fee_currency = Column('fee_currency', Unicode(3)) _transaction_details = Column('transaction_details', UnicodeText(length=2**31)) exchange_id = Column(Integer, ForeignKey('exchange.exchange_id')) # Some Transactions have BTC fees, which reduce our total BTC assets. Every once in a while # we create a "buyback" transaction where we buy back those fees outside our trading system. # We then mark the fee as "bought back" by setting the transaction's fee_buyback_transaction # This one is a bit complex because it is self-referential fee_buyback_transaction_id = Column(Integer, ForeignKey('transaction.transaction_id')) fee_buyback_transaction = relationship("Transaction", remote_side=[transaction_id], backref='fee_buyback_transactions') def __init__(self, transaction_type, transaction_status, amount, exchange, transaction_details, fee=None): self.unique_id = unicode(uuid.uuid4().hex) self.time_created = datetime.utcnow() self.transaction_type = transaction_type self.transaction_status = transaction_status self.amount = amount self.exchange = exchange self.transaction_details = transaction_details if fee: self.fee = fee def __unicode__(self): return u'[TRANSACTION:%s, EXCHANGE:%s, STATUS:%s] Amount:%s (%s) at %s' % ( self.transaction_type, self.exchange.name, self.transaction_status, self.amount, self.fee, self.time_created) def __repr__(self): return self.to_json() def to_json(self): return json.dumps({ 'transaction_id':self.transaction_id, 'transaction_type':self.transaction_type, 'transaction_status':self.transaction_status, 'time_created':unicode(self.time_created), 'unique_id':self.unique_id, 'exchange':self.exchange.name, 'amount':self.amount, 'fee': self.fee, 'transaction_details':self.transaction_details }, ensure_ascii=False) @property def transaction_details(self): return json.loads(self._transaction_details) @transaction_details.setter def transaction_details(self, value): self._transaction_details = json.dumps(value, ensure_ascii=False) @property def amount(self): return Money(self._amount, self._amount_currency) @amount.setter def amount(self, value): self._amount = value.amount self._amount_currency = value.currency @property def fee(self): if self._fee and self._fee_currency: return Money(self._fee, self._fee_currency) else: return None @fee.setter def fee(self, value): self._fee = value.amount self._fee_currency = value.currency @hybrid_property def has_outstanding_btc_fee(self): return self._fee_currency == 'BTC' and self.fee_buyback_transaction_id == None and self.transaction_status != self.CANCELED @has_outstanding_btc_fee.expression def has_outstanding_btc_fee(cls): return and_(cls._fee_currency == 'BTC', cls.fee_buyback_transaction_id == None, cls.transaction_status != cls.CANCELED) def complete(self): if self.transaction_status != self.IN_TRANSIT: raise ValueError("We can only complete an IN_TRANSIT transaction") self.transaction_status = self.COMPLETED self.time_completed = datetime.utcnow() if self.transaction_type == self.DEPOSIT: self.exchange.balance[self.amount.currency] += self.amount elif self.transaction_type == self.WITHDRAWL: self.exchange.balance[self.amount.currency] -= self.amount if self.fee: self.exchange.balance[self.fee.currency] -= self.fee def cancel(self): if self.transaction_status == self.IN_TRANSIT: self.transaction_status = self.CANCELED elif self.transaction_status == self.COMPLETED: self.transaction_status = self.CANCELED if self.transaction_type == self.DEPOSIT: self.exchange.balance[self.amount.currency] -= self.amount elif self.transaction_type == self.WITHDRAWL: self.exchange.balance[self.amount.currency] += self.amount if self.fee: self.exchange.balance[self.fee.currency] += self.fee else: raise ValueError("We can only cancel an IN_TRANSIT or COMPLETED transaction") def confirmations(self): if self.transaction_details and 'transaction_hash' in self.transaction_details: r = requests.get('https://api.blockcypher.com/v1/btc/main/txs/%s' % self.transaction_details['transaction_hash']) response = r.json() if 'confirmations' in response: return int(response['confirmations']) return None def already_has_tx_hash(self): return (self.transaction_details and 'transaction_hash' in self.transaction_details and self.transaction_details['transaction_hash']) def can_lookup_tx_hash(self): return (self.amount.currency == "BTC" and self.transaction_details and 'deposit_address' in self.transaction_details) def update_tx_hash(self): if not self.already_has_tx_hash() and self.can_lookup_tx_hash(): tx_hash = self.find_on_blockchain() logger.info("Found %s %s on the blockchain: %s" % (self.exchange.name, self.amount, tx_hash)) # can't directly update self.transaction_details because it is a json magic field tx_details = self.transaction_details tx_details['transaction_hash'] = tx_hash self.transaction_details = tx_details def find_on_blockchain(self): deposit_address = self.transaction_details['deposit_address'] satoshi_amount = int(self.amount * 10**8) r = requests.get('https://api.blockcypher.com/v1/btc/main/addrs/%s/full' % deposit_address) response = r.json() transactions = response['txs'] for transaction in transactions: for output in transaction['outputs']: if deposit_address in output['addresses'] and output['value'] == satoshi_amount: return transaction['hash'] return None # a transaction is stuck if it has been in transit for more than 3 hours def is_stuck(self): return self.amount.currency == "BTC" and \ self.transaction_status == self.IN_TRANSIT and \ Delorean(self.time_created, "UTC") < Delorean().last_hour(3) @property def position(self): from gryphon.lib.models.exchange import Position position = Position() if self.transaction_type == self.DEPOSIT: position[self.amount.currency] += self.amount elif self.transaction_type == self.WITHDRAWL: position[self.amount.currency] -= self.amount if self.fee: position[self.fee.currency] -= self.fee return position @hybrid_property def magic_time_completed(self): """ Regular property you can call on a loaded trade in python. Returns a USD Money object """ if self.time_completed: return self.time_completed else: return self.time_created @magic_time_completed.expression def magic_time_completed(cls): """ SQL Expression which lets us calculate and use USD prices in SQL. Must have Order joined in queries where it is used. Ex: db.query(func.sum(Trade.price_in_usd)).join(Order).scalar() This gives decimal results, since we don't have our Money objects in SQL """ return func.IF(cls.time_completed, cls.time_completed, cls.time_created)
3,860
461
<gh_stars>100-1000 class MapSum(object): # 设计成内部类,外部没有必要知道 class TrieNode: def __init__(self): self.val = 0 self.next = {} def __init__(self): """ Initialize your data structure here. """ self.root = MapSum.TrieNode() def insert(self, key: str, val: int) -> None: cur_node = self.root for c in key: if c not in cur_node.next.keys(): cur_node.next[c] = MapSum.TrieNode() cur_node = cur_node.next[c] cur_node.val = val def sum(self, prefix: str) -> int: cur_node = self.root for c in prefix: if c in cur_node.next.keys(): cur_node = cur_node.next[c] else: return 0 return self.__sum(cur_node) # 这里用到了递归 def __sum(self, node): res = node.val # 这里不能初始化为 0 for c in node.next.keys(): res += self.__sum(node.next[c]) return res # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)
627
1,723
/************************************************************************** * * Copyright 2016 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #pragma once #include <windows.h> #include "winsdk_compat.h" #include <dcomp.h> // These are necessary on MinGW because DECLSPEC_UUID(x) is a no-op #ifdef __MINGW32__ EXTERN_C CONST IID IID_IDCompositionDevice; EXTERN_C CONST IID IID_IDCompositionTarget; EXTERN_C CONST IID IID_IDCompositionVisual; EXTERN_C CONST IID IID_IDCompositionEffect; EXTERN_C CONST IID IID_IDCompositionTransform3D; EXTERN_C CONST IID IID_IDCompositionTransform; EXTERN_C CONST IID IID_IDCompositionTranslateTransform; EXTERN_C CONST IID IID_IDCompositionScaleTransform; EXTERN_C CONST IID IID_IDCompositionRotateTransform; EXTERN_C CONST IID IID_IDCompositionSkewTransform; EXTERN_C CONST IID IID_IDCompositionMatrixTransform; EXTERN_C CONST IID IID_IDCompositionEffectGroup; EXTERN_C CONST IID IID_IDCompositionTranslateTransform3D; EXTERN_C CONST IID IID_IDCompositionScaleTransform3D; EXTERN_C CONST IID IID_IDCompositionRotateTransform3D; EXTERN_C CONST IID IID_IDCompositionMatrixTransform3D; EXTERN_C CONST IID IID_IDCompositionClip; EXTERN_C CONST IID IID_IDCompositionRectangleClip; EXTERN_C CONST IID IID_IDCompositionSurface; EXTERN_C CONST IID IID_IDCompositionVirtualSurface; EXTERN_C CONST IID IID_IDCompositionDevice2; EXTERN_C CONST IID IID_IDCompositionDesktopDevice; EXTERN_C CONST IID IID_IDCompositionDeviceDebug; EXTERN_C CONST IID IID_IDCompositionSurfaceFactory; EXTERN_C CONST IID IID_IDCompositionVisual2; EXTERN_C CONST IID IID_IDCompositionVisualDebug; EXTERN_C CONST IID IID_IDCompositionDevice3; EXTERN_C CONST IID IID_IDCompositionFilterEffect; EXTERN_C CONST IID IID_IDCompositionGaussianBlurEffect; EXTERN_C CONST IID IID_IDCompositionBrightnessEffect; EXTERN_C CONST IID IID_IDCompositionColorMatrixEffect; EXTERN_C CONST IID IID_IDCompositionShadowEffect; EXTERN_C CONST IID IID_IDCompositionHueRotationEffect; EXTERN_C CONST IID IID_IDCompositionSaturationEffect; EXTERN_C CONST IID IID_IDCompositionTurbulenceEffect; EXTERN_C CONST IID IID_IDCompositionLinearTransferEffect; EXTERN_C CONST IID IID_IDCompositionTableTransferEffect; EXTERN_C CONST IID IID_IDCompositionCompositeEffect; EXTERN_C CONST IID IID_IDCompositionBlendEffect; EXTERN_C CONST IID IID_IDCompositionArithmeticCompositeEffect; EXTERN_C CONST IID IID_IDCompositionAffineTransform2DEffect; #endif
1,156
4,461
<reponame>p-christ/Deep-Reinforcement-Learning-PyTorch-Algorithms import random import torch import sys from contextlib import closing # # from pathos.multiprocessing import ProcessingPool as Pool from torch.multiprocessing import Pool from random import randint from utilities.OU_Noise import OU_Noise from utilities.Utility_Functions import create_actor_distribution class Parallel_Experience_Generator(object): """ Plays n episode in parallel using a fixed agent. Only works for PPO or DDPG type agents at the moment, not Q-learning agents""" def __init__(self, environment, policy, seed, hyperparameters, action_size, use_GPU=False, action_choice_output_columns=None): self.use_GPU = use_GPU self.environment = environment self.action_types = "DISCRETE" if self.environment.action_space.dtype in [int, 'int64'] else "CONTINUOUS" self.action_size = action_size self.policy = policy self.action_choice_output_columns = action_choice_output_columns self.hyperparameters = hyperparameters if self.action_types == "CONTINUOUS": self.noise = OU_Noise(self.action_size, seed, self.hyperparameters["mu"], self.hyperparameters["theta"], self.hyperparameters["sigma"]) def play_n_episodes(self, n, exploration_epsilon=None): """Plays n episodes in parallel using the fixed policy and returns the data""" self.exploration_epsilon = exploration_epsilon with closing(Pool(processes=n)) as pool: results = pool.map(self, range(n)) pool.terminate() states_for_all_episodes = [episode[0] for episode in results] actions_for_all_episodes = [episode[1] for episode in results] rewards_for_all_episodes = [episode[2] for episode in results] return states_for_all_episodes, actions_for_all_episodes, rewards_for_all_episodes def __call__(self, n): exploration = max(0.0, random.uniform(self.exploration_epsilon / 3.0, self.exploration_epsilon * 3.0)) return self.play_1_episode(exploration) def play_1_episode(self, epsilon_exploration): """Plays 1 episode using the fixed policy and returns the data""" state = self.reset_game() done = False episode_states = [] episode_actions = [] episode_rewards = [] while not done: action = self.pick_action(self.policy, state, epsilon_exploration) next_state, reward, done, _ = self.environment.step(action) if self.hyperparameters["clip_rewards"]: reward = max(min(reward, 1.0), -1.0) episode_states.append(state) episode_actions.append(action) episode_rewards.append(reward) state = next_state return episode_states, episode_actions, episode_rewards def reset_game(self): """Resets the game environment so it is ready to play a new episode""" seed = randint(0, sys.maxsize) torch.manual_seed(seed) # Need to do this otherwise each worker generates same experience state = self.environment.reset() if self.action_types == "CONTINUOUS": self.noise.reset() return state def pick_action(self, policy, state, epsilon_exploration=None): """Picks an action using the policy""" if self.action_types == "DISCRETE": if random.random() <= epsilon_exploration: action = random.randint(0, self.action_size - 1) return action state = torch.from_numpy(state).float().unsqueeze(0) actor_output = policy.forward(state) if self.action_choice_output_columns is not None: actor_output = actor_output[:, self.action_choice_output_columns] action_distribution = create_actor_distribution(self.action_types, actor_output, self.action_size) action = action_distribution.sample().cpu() if self.action_types == "CONTINUOUS": action += torch.Tensor(self.noise.sample()) else: action = action.item() return action
1,586
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <openvino/op/select.hpp> namespace ov { namespace op { namespace v1 { template <class T> void shape_infer(const Select* op, const std::vector<T>& input_shapes, std::vector<T>& output_shapes) { NODE_VALIDATION_CHECK(op, input_shapes.size() == 3 && output_shapes.size() == 1); const auto& broadcast_spec = op->get_auto_broadcast(); auto& result_shape = output_shapes[0]; if (broadcast_spec.m_type == op::AutoBroadcastType::PDPD) { result_shape = input_shapes[1]; // 'then' tensor // in PDPD type, Broacast-merging 'else' into 'then' one way not each other. NODE_VALIDATION_CHECK(op, T::broadcast_merge_into(result_shape, input_shapes[2], broadcast_spec), "'Else' tensor shape is not broadcastable."); NODE_VALIDATION_CHECK(op, T::broadcast_merge_into(result_shape, input_shapes[0], broadcast_spec), "'Cond' tensor shape is not broadcastable."); } else { result_shape = input_shapes[2]; for (int input_port = 1; input_port >= 0; input_port--) { if (broadcast_spec.m_type == op::AutoBroadcastType::NONE) { NODE_VALIDATION_CHECK(op, T::merge_into(result_shape, input_shapes[input_port]), "Argument shapes are inconsistent."); } else if (broadcast_spec.m_type == op::AutoBroadcastType::NUMPY) { NODE_VALIDATION_CHECK(op, T::broadcast_merge_into(result_shape, input_shapes[input_port], broadcast_spec), "Argument shapes are inconsistent."); } else { NODE_VALIDATION_CHECK(op, false, "Unsupported auto broadcast specification"); } } } } } // namespace v1 } // namespace op } // namespace ov
997
790
import warnings from django.test import TestCase class DummyTest(TestCase): def test_warn(self): warnings.warn("warning from test", DeprecationWarning)
56
1,056
/* * 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.netbeans.modules.git.ui.repository; import java.awt.EventQueue; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.text.DateFormat; import java.util.Date; import org.netbeans.modules.git.client.GitClient; import org.netbeans.libs.git.GitException; import org.netbeans.libs.git.GitRevisionInfo; import org.netbeans.libs.git.progress.ProgressMonitor; import org.netbeans.modules.git.Git; import org.netbeans.modules.git.client.GitClientExceptionHandler; import org.netbeans.modules.git.utils.GitUtils; import org.openide.util.Mutex; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor.Task; /** * * @author ondra */ public class RevisionInfoPanelController { private final RevisionInfoPanel panel; private static final String MSG_LOADING = NbBundle.getMessage(RevisionDialogController.class, "MSG_RevisionInfoPanel.loading"); //NOI18N private static final String MSG_UNKNOWN = NbBundle.getMessage(RevisionDialogController.class, "MSG_RevisionInfoPanel.unknown"); //NOI18N private final LoadInfoWorker loadInfoWorker = new LoadInfoWorker(); private final Task loadInfoTask; private String currentCommit; private final File repository; private boolean valid; private final PropertyChangeSupport support; public static final String PROP_VALID = "RevisionInfoPanelController.valid"; //NOI18N private String mergingInto; private Revision info; public RevisionInfoPanelController (File repository) { this.repository = repository; this.loadInfoTask = Git.getInstance().getRequestProcessor(null).create(loadInfoWorker); this.panel = new RevisionInfoPanel(); this.support = new PropertyChangeSupport(this); resetInfoFields(); } public RevisionInfoPanel getPanel () { return panel; } public void loadInfo (String revision) { loadInfoTask.cancel(); loadInfoWorker.monitor.cancel(); currentCommit = revision; setValid(false); if (revision == null || revision.isEmpty()) { setUnknownRevision(); } else { resetInfoFields(); loadInfoTask.schedule(100); } } void displayMergedStatus (String revision) { this.mergingInto = revision; } Revision getInfo () { return info; } private void resetInfoFields () { panel.taMessage.setText(MSG_LOADING); panel.tbAuthor.setText(MSG_LOADING); panel.tbDate.setText(MSG_LOADING); panel.tbRevisionId.setText(MSG_LOADING); } private void updateInfoFields (String revision, GitRevisionInfo info, Boolean revisionMerged) { assert EventQueue.isDispatchThread(); panel.tbAuthor.setText(info.getAuthor().toString()); if (!panel.tbAuthor.getText().isEmpty()) { panel.tbAuthor.setCaretPosition(0); } panel.tbDate.setText(DateFormat.getDateTimeInstance().format(new Date(info.getCommitTime()))); if (!panel.tbDate.getText().isEmpty()) { panel.tbDate.setCaretPosition(0); } String id = info.getRevision(); if (id.length() > 10) { id = id.substring(0, 10); } if (revision.equals(info.getRevision())) { panel.tbRevisionId.setText(new StringBuilder(id).append(getMergedStatus(revisionMerged)).toString()); this.info = new Revision(revision, revision, info.getShortMessage(), info.getFullMessage()); } else { this.info = new Revision(info.getRevision(), revision, info.getShortMessage(), info.getFullMessage()); if (revision.startsWith(GitUtils.PREFIX_R_HEADS)) { //NOI18N revision = revision.substring(GitUtils.PREFIX_R_HEADS.length()); } else if (revision.startsWith(GitUtils.PREFIX_R_REMOTES)) { //NOI18N revision = revision.substring(GitUtils.PREFIX_R_REMOTES.length()); } panel.tbRevisionId.setText(new StringBuilder(revision).append(getMergedStatus(revisionMerged)).append(" (").append(id).append(')').toString()); //NOI18N } if (!panel.tbRevisionId.getText().isEmpty()) { panel.tbRevisionId.setCaretPosition(0); } panel.taMessage.setText(info.getFullMessage()); if (!panel.taMessage.getText().isEmpty()) { panel.taMessage.setCaretPosition(0); } } private void setUnknownRevision () { panel.tbAuthor.setText(MSG_UNKNOWN); panel.tbRevisionId.setText(MSG_UNKNOWN); panel.taMessage.setText(MSG_UNKNOWN); } private void setValid (boolean flag) { boolean oldValue = valid; valid = flag; if (oldValue != valid) { support.firePropertyChange(PROP_VALID, oldValue, valid); } } public void addPropertyChangeListener (PropertyChangeListener list) { support.addPropertyChangeListener(list); } public void removePropertyChangeListener (PropertyChangeListener list) { support.removePropertyChangeListener(list); } @NbBundle.Messages("MSG_RevisionMerged.status= [merged]") private String getMergedStatus (Boolean revisionMerged) { if (Boolean.TRUE.equals(revisionMerged)) { return Bundle.MSG_RevisionMerged_status(); } else { return ""; } } private class LoadInfoWorker implements Runnable { ProgressMonitor.DefaultProgressMonitor monitor = new ProgressMonitor.DefaultProgressMonitor(); @Override public void run () { final String revision = currentCommit; GitRevisionInfo revisionInfo; GitClient client = null; Boolean mergedStatus = null; try { monitor = new ProgressMonitor.DefaultProgressMonitor(); if (Thread.interrupted()) { return; } client = Git.getInstance().getClient(repository); revisionInfo = client.log(revision, monitor); if (!monitor.isCanceled() && mergingInto != null) { GitRevisionInfo commonAncestor = client.getCommonAncestor(new String[] { mergingInto, revisionInfo.getRevision() }, monitor); mergedStatus = commonAncestor != null && commonAncestor.getRevision().equals(revisionInfo.getRevision()); } } catch (GitException ex) { if (!(ex instanceof GitException.MissingObjectException)) { GitClientExceptionHandler.notifyException(ex, true); } revisionInfo = null; } finally { if (client != null) { client.release(); } } final GitRevisionInfo info = revisionInfo; final Boolean fMergedStatus = mergedStatus; final ProgressMonitor.DefaultProgressMonitor m = monitor; if (!monitor.isCanceled()) { Mutex.EVENT.readAccess(new Runnable () { @Override public void run () { if (!m.isCanceled()) { if (info == null) { setUnknownRevision(); } else { updateInfoFields(revision, info, fMergedStatus); setValid(true); } } } }); } } } }
3,573
17,242
// Copyright 2021 The MediaPipe 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. #include <iterator> #include <memory> #include <string> #include <vector> #include "absl/memory/memory.h" #include "mediapipe/calculators/util/filter_detections_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/port/status.h" namespace mediapipe { const char kInputDetectionsTag[] = "INPUT_DETECTIONS"; const char kOutputDetectionsTag[] = "OUTPUT_DETECTIONS"; // // Calculator to filter out detections that do not meet the criteria specified // in options. // class FilterDetectionsCalculator : public CalculatorBase { public: static absl::Status GetContract(CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kInputDetectionsTag)); RET_CHECK(cc->Outputs().HasTag(kOutputDetectionsTag)); cc->Inputs().Tag(kInputDetectionsTag).Set<std::vector<Detection>>(); cc->Outputs().Tag(kOutputDetectionsTag).Set<std::vector<Detection>>(); return absl::OkStatus(); } absl::Status Open(CalculatorContext* cc) override { cc->SetOffset(TimestampDiff(0)); options_ = cc->Options<mediapipe::FilterDetectionsCalculatorOptions>(); return absl::OkStatus(); } absl::Status Process(CalculatorContext* cc) final { const auto& input_detections = cc->Inputs().Tag(kInputDetectionsTag).Get<std::vector<Detection>>(); auto output_detections = absl::make_unique<std::vector<Detection>>(); for (const Detection& detection : input_detections) { RET_CHECK_GT(detection.score_size(), 0); // Note: only score at index 0 supported. if (detection.score(0) >= options_.min_score()) { output_detections->push_back(detection); } } cc->Outputs() .Tag(kOutputDetectionsTag) .Add(output_detections.release(), cc->InputTimestamp()); return absl::OkStatus(); } private: mediapipe::FilterDetectionsCalculatorOptions options_; }; REGISTER_CALCULATOR(FilterDetectionsCalculator); } // namespace mediapipe
874
751
/* * Copyright (c) 2016 Cisco and/or its affiliates. * 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. */ #include "fib_entry.h" #include "fib_entry_src.h" /** * Source initialisation Function */ static void fib_entry_src_simple_init (fib_entry_src_t *src) { src->fes_flags = FIB_ENTRY_SRC_FLAG_NONE; } /** * Source deinitialisation Function */ static void fib_entry_src_simple_deinit (fib_entry_src_t *src) { } static void fib_entry_src_simple_remove (fib_entry_src_t *src) { src->fes_pl = FIB_NODE_INDEX_INVALID; } static void fib_entry_src_simple_add (fib_entry_src_t *src, const fib_entry_t *entry, fib_entry_flag_t flags, dpo_proto_t proto, const dpo_id_t *dpo) { src->fes_pl = fib_path_list_create_special(proto, fib_entry_src_flags_2_path_list_flags(flags), dpo); } static void fib_entry_src_simple_path_swap (fib_entry_src_t *src, const fib_entry_t *entry, fib_path_list_flags_t pl_flags, const fib_route_path_t *rpaths) { src->fes_pl = fib_path_list_create((FIB_PATH_LIST_FLAG_SHARED | pl_flags), rpaths); } const static fib_entry_src_vft_t simple_src_vft = { .fesv_init = fib_entry_src_simple_init, .fesv_deinit = fib_entry_src_simple_deinit, .fesv_add = fib_entry_src_simple_add, .fesv_remove = fib_entry_src_simple_remove, .fesv_path_swap = fib_entry_src_simple_path_swap, }; void fib_entry_src_simple_register (void) { fib_entry_src_behaviour_register(FIB_SOURCE_BH_SIMPLE, &simple_src_vft); }
1,051
13,162
<filename>unittests/test-contracts/kv_bios/kv_bios.cpp #include <eosio/contract.hpp> #include <eosio/name.hpp> #include <eosio/privileged.hpp> extern "C" __attribute__((eosio_wasm_import)) void set_resource_limit(int64_t, int64_t, int64_t); extern "C" __attribute__((eosio_wasm_import)) uint32_t get_kv_parameters_packed(void* params, uint32_t size, uint32_t max_version); extern "C" __attribute__((eosio_wasm_import)) void set_kv_parameters_packed(const char* params, uint32_t size); #ifdef USE_EOSIO_CDT_1_7_X extern "C" __attribute__((eosio_wasm_import)) uint32_t read_action_data( void* msg, uint32_t len ); extern "C" __attribute__((eosio_wasm_import)) uint32_t action_data_size(); #endif using namespace eosio; // Manages resources used by the kv-store class [[eosio::contract]] kv_bios : eosio::contract { public: using contract::contract; [[eosio::action]] void setramlimit(name account, int64_t limit) { set_resource_limit(account.value, "ram"_n.value, limit); } [[eosio::action]] void ramkvlimits(uint32_t k, uint32_t v, uint32_t i) { kvlimits_impl(k, v, i); } void kvlimits_impl(uint32_t k, uint32_t v, uint32_t i) { uint32_t limits[4]; limits[0] = 0; limits[1] = k; limits[2] = v; limits[3] = i; char limits_buf[sizeof(limits)]; memcpy(limits_buf, limits, sizeof(limits)); set_kv_parameters_packed(limits_buf, sizeof(limits)); int sz = get_kv_parameters_packed(nullptr, 0, 0); std::fill_n(limits, sizeof(limits)/sizeof(limits[0]), 0xFFFFFFFFu); check(sz == 16, "wrong kv parameters size"); sz = get_kv_parameters_packed(limits, sizeof(limits), 0); check(sz == 16, "wrong kv parameters result"); check(limits[0] == 0, "wrong version"); check(limits[1] == k, "wrong key"); check(limits[2] == v, "wrong value"); check(limits[3] == i, "wrong iter limit"); } };
821
1,273
package org.broadinstitute.hellbender.utils.runtime; import org.apache.commons.lang3.StringUtils; import org.broadinstitute.hellbender.utils.Utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.jar.Manifest; public final class RuntimeUtils { public static final String[] PATHS; static { String path = System.getenv("PATH"); if (path == null) path = System.getenv("path"); if (path == null) { PATHS = new String[0]; } else { PATHS = StringUtils.split(path, File.pathSeparatorChar); } } /** * Returns the path to an executable or null if it doesn't exist. * @param executable Relative path * @return The absolute file path. */ public static File which(String executable) { for (String path: PATHS) { File file = new File(path, executable); if (file.exists()) return file.getAbsoluteFile(); } return null; } /** * Given a Class that is a CommandLineProgram, either GATK or Picard, return a display name suitable for * presentation to the user that distinguishes GATK tools from Picard tools by including a " (Picard)" suffix; * @param toolClass A CommandLineProgram class object may not be null * @return tool display name */ public static String toolDisplayName(final Class<?> toolClass) { Utils.nonNull(toolClass, "A valid class is required to get a display name"); final String picardToolSuffix = " (Picard)"; final Class<?> picardCommandLineProgramClass = picard.cmdline.CommandLineProgram.class; return picardCommandLineProgramClass.isAssignableFrom(toolClass) ? toolClass.getSimpleName() + picardToolSuffix : toolClass.getSimpleName(); } /** * @param clazz class to use when looking up the Implementation-Title * @return The name of this toolkit, uses "Implementation-Title" from the * jar manifest of the given class, or (if that's not available) the package name. */ public static String getToolkitName(Class<?> clazz) { final String implementationTitle = clazz.getPackage().getImplementationTitle(); return implementationTitle != null ? implementationTitle : clazz.getPackage().getName(); } /** * @return load the manifest file associated with the given class or null if loading fails */ public static Manifest getManifest(Class<?> clazz) { final URL resourceURL = clazz.getResource(clazz.getSimpleName() + ".class"); if( resourceURL == null) { return null; } final String classPath = resourceURL.toString(); if (classPath.startsWith("jar")) { final String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; try ( final InputStream manifestStream = new URL(manifestPath).openStream() ) { return new Manifest(manifestStream); } catch (IOException e) { return null; } } else { return null; } } /** * @return get the implementation version of the given class */ public static String getVersion(Class<?> clazz){ String versionString = clazz.getPackage().getImplementationVersion(); return versionString != null ? versionString : "Unavailable"; } }
1,343
643
import java.util.Map; public abstract class C<K, V> implements Map.Entry<K, V> { }
30
1,140
# -*- coding: utf-8 -*- """ flaskbb.auth.forms ~~~~~~~~~~~~~~~~~~ It provides the forms that are needed for the auth views. :copyright: (c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import logging from flask_babelplus import lazy_gettext as _ from wtforms import ( BooleanField, HiddenField, PasswordField, SelectField, StringField, SubmitField, ) from wtforms.validators import ( DataRequired, Email, EqualTo, InputRequired, regexp, ) from flaskbb.utils.fields import RecaptchaField from flaskbb.utils.forms import FlaskBBForm logger = logging.getLogger(__name__) USERNAME_RE = r"^[\w.+-]+$" is_valid_username = regexp( USERNAME_RE, message=_("You can only use letters, numbers or dashes.") ) class LoginForm(FlaskBBForm): login = StringField( _("Username or Email address"), validators=[ DataRequired( message=_("Please enter your username or email address.") ) ], ) password = PasswordField( _("Password"), validators=[DataRequired(message=_("Please enter your password."))], ) remember_me = BooleanField(_("Remember me"), default=False) submit = SubmitField(_("Login")) recaptcha = HiddenField(_("Captcha")) class LoginRecaptchaForm(LoginForm): recaptcha = RecaptchaField(_("Captcha")) class RegisterForm(FlaskBBForm): username = StringField( _("Username"), validators=[ DataRequired(message=_("A valid username is required")), is_valid_username, ], ) email = StringField( _("Email address"), validators=[ DataRequired(message=_("A valid email address is required.")), Email(message=_("Invalid email address.")), ], ) password = PasswordField( _("Password"), validators=[ InputRequired(), EqualTo("confirm_password", message=_("Passwords must match.")), ], ) confirm_password = PasswordField(_("Confirm password")) recaptcha = RecaptchaField(_("Captcha")) language = SelectField(_("Language")) accept_tos = BooleanField( _("I accept the Terms of Service"), validators=[DataRequired(message=_("Please accept the TOS."))], default=True, ) submit = SubmitField(_("Register")) class ReauthForm(FlaskBBForm): password = PasswordField( _("Password"), validators=[DataRequired(message=_("Please enter your password."))], ) submit = SubmitField(_("Refresh Login")) class ForgotPasswordForm(FlaskBBForm): email = StringField( _("Email address"), validators=[ DataRequired(message=_("A valid email address is required.")), Email(), ], ) recaptcha = RecaptchaField(_("Captcha")) submit = SubmitField(_("Request Password")) class ResetPasswordForm(FlaskBBForm): token = HiddenField("Token") email = StringField( _("Email address"), validators=[ DataRequired(message=_("A valid email address is required.")), Email(), ], ) password = PasswordField( _("Password"), validators=[ InputRequired(), EqualTo("confirm_password", message=_("Passwords must match.")), ], ) confirm_password = PasswordField(_("<PASSWORD> password")) submit = SubmitField(_("Reset password")) class RequestActivationForm(FlaskBBForm): username = StringField( _("Username"), validators=[ DataRequired(message=_("A valid username is required.")), is_valid_username, ], ) email = StringField( _("Email address"), validators=[ DataRequired(message=_("A valid email address is required.")), Email(message=_("Invalid email address.")), ], ) submit = SubmitField(_("Send Confirmation Mail")) class AccountActivationForm(FlaskBBForm): token = StringField( _("Email confirmation token"), validators=[ DataRequired(_("Please enter the token we have sent to you.")) ], ) submit = SubmitField(_("Confirm Email"))
1,717
446
<reponame>quink-black/MediaInfoLib /* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_GRAPH_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Export/Export_Graph.h" #include "MediaInfo/File__Analyse_Automatic.h" #include "MediaInfo/MediaInfo_Config.h" #include "MediaInfo/OutputHelpers.h" #include <ctime> #include <cmath> #ifdef MEDIAINFO_GRAPHVIZ_YES #ifdef MEDIAINFO_GRAPHVIZ_DLL_RUNTIME #include "MediaInfo/Export/Export_Graph_gvc_Include.h" #else #include <gvc.h> #endif //MEDIAINFO_GRAPHVIZ_DLL_RUNTIME #endif //MEDIAINFO_GRAPHVIZ_YES using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Helpers //*************************************************************************** //--------------------------------------------------------------------------- Ztring NewLine(size_t Level) { return __T('\n')+Ztring(4*Level, __T(' ')); } //--------------------------------------------------------------------------- Ztring Element2Html(MediaInfo_Internal &MI, stream_t StreamKind, size_t StreamPos, Ztring Element, Ztring Format, Ztring FG, Ztring BG, Ztring HFG, Ztring HBG) { Ztring ToReturn; ToReturn+=__T("<table border='0' cellborder='0' cellspacing='0'>"); ToReturn+=__T("<tr>"); ToReturn+=__T("<td colspan='2' bgcolor='")+HBG+__T("'>"); ToReturn+=__T("<font color='")+HFG+__T("'>"); ToReturn+=__T("<b>")+XML_Encode(MI.Get(StreamKind, StreamPos, Element, Info_Name_Text))+__T("</b>"); ToReturn+=__T("<br/>"); Ztring Sub=XML_Encode(MI.Get(StreamKind, StreamPos, Element, Info_Text)); if (Sub.size() && Sub[Sub.size()-1]==__T(')')) { if (Sub.FindAndReplace(__T("("), __T("<br/>"), 0)) Sub.erase(Sub.size()-1); } Sub.FindAndReplace(__T(" / "), __T("<br/>"), 0, Ztring_Recursive); ToReturn+=Sub; ToReturn+=__T("</font>"); ToReturn+=__T("</td>"); ToReturn+=__T("</tr>"); for (size_t Pos=0; Pos<MI.Count_Get(StreamKind, StreamPos); Pos++) { Ztring Name=MI.Get(StreamKind, StreamPos, Pos, Info_Name); if (Name.find(Element+__T(" "))==0 && Name.SubString(Element+__T(" "), __T("")).find(__T(" "))==string::npos) { Ztring Text=XML_Encode(MI.Get(StreamKind, StreamPos, Pos, Info_Text)); Text.FindAndReplace(__T(" / "), __T("<br align='left'/>"), 0, Ztring_Recursive); if (Text.empty() || Name.find(Element+__T(" LinkedTo_"))==0 || Name.find(Element+__T(" Title"))==0 || (Format==__T("ED2") && Name.find(Element+__T(" Target"))==0) || (MI.Get(StreamKind, StreamPos, Pos, Info_Options)[InfoOption_ShowInInform]!=__T('Y') && !MediaInfoLib::Config.Complete_Get())) continue; ToReturn+=__T("<tr>"); ToReturn+=__T("<td align='text' bgcolor='")+BG+__T("' port='")+XML_Encode(Name.SubString(Element+__T(" "), __T("")))+__T("'>"); ToReturn+=__T("<font color='")+FG+__T("'>")+XML_Encode(MI.Get(StreamKind, StreamPos, Pos, Info_Name_Text))+=__T("</font><br align='left'/>"); ToReturn+=__T("</td>"); ToReturn+=__T("<td align='text' bgcolor='")+BG+__T("'>"); ToReturn+=__T("<font color='")+FG+__T("'>")+Text+=__T("</font><br align='left'/>"); ToReturn+=__T("</td>"); ToReturn+=__T("</tr>"); } } ToReturn+=__T("</table>"); return ToReturn; } //--------------------------------------------------------------------------- #ifdef MEDIAINFO_GRAPHVIZ_YES Ztring Dot2Svg(const Ztring& Dot) { Ztring ToReturn; GVC_t* Context=NULL; graph_t* Graph=NULL; char* Buffer=NULL; unsigned int Size; if (!Export_Graph::Load()) return ToReturn; if (Dot.empty()) return ToReturn; Context=gvContext(); if (!Context) return ToReturn; Graph=agmemread(Dot.To_UTF8().c_str()); if (!Graph) { gvFinalize(Context); gvFreeContext(Context); return ToReturn; } if (gvLayout(Context, Graph, "dot")!=0) { agclose(Graph); gvFinalize(Context); gvFreeContext(Context); return ToReturn; } gvRenderData(Context, Graph, "svg", &Buffer, &Size); if (Buffer && Size) ToReturn=Ztring().From_UTF8(Buffer); gvFreeRenderData(Buffer); gvFreeLayout(Context, Graph); agclose(Graph); gvFinalize(Context); gvFreeContext(Context); return ToReturn; } #endif //MEDIAINFO_GRAPHVIZ_YES //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- Export_Graph::Export_Graph () { } //--------------------------------------------------------------------------- Export_Graph::~Export_Graph () { } //*************************************************************************** // Dynamic load stuff //*************************************************************************** bool Export_Graph::Load() { //TODO: detect if graphviz library is usable #if defined(MEDIAINFO_GRAPHVIZ_DLL_RUNTIME) if (!gvc_Module) { DLOPEN(gvc_Module, GVCDLL_NAME) if (!gvc_Module) return false; bool Error=false; ASSIGN(gvc_Module, gvContext) ASSIGN(gvc_Module, gvFreeContext) ASSIGN(gvc_Module, gvLayout) ASSIGN(gvc_Module, gvFreeLayout) ASSIGN(gvc_Module, gvRenderData) ASSIGN(gvc_Module, gvFreeRenderData) ASSIGN(gvc_Module, gvFinalize) if (Error) { DLCLOSE(gvc_Module); return false; } } if (!cgraph_Module) { DLOPEN(cgraph_Module, CGRAPHDLL_NAME) if (!cgraph_Module) { DLCLOSE(gvc_Module); return false; } bool Error=false; ASSIGN(cgraph_Module, agmemread) ASSIGN(cgraph_Module, agclose) if (Error) { DLCLOSE(gvc_Module); DLCLOSE(cgraph_Module); return false; } } return true; #elif defined(MEDIAINFO_GRAPHVIZ_YES) return true; #else return false; #endif //defined(MEDIAINFO_GRAPHVIZ_DLL_RUNTIME) } //*************************************************************************** // Generators //*************************************************************************** #define OBJECT_START(NAME, COUNTER, FOREGROUND_COLOR, BACKGROUND_COLOR, TITLE_FOREGROUND_COLOR, TITLE_BACKGROUND_COLOR) \ {\ Temp+=NewLine(Level++)+__T("rank=same {"); \ size_t NAME##s=MI.Get(Stream_Audio, StreamPos, __T(COUNTER), Info_Text).To_int64u(); \ if (NAME##s) Empty=false; \ for (size_t NAME##Pos=NAME##s; NAME##Pos; NAME##Pos--) \ {\ Ztring Object=__T(#NAME)+Ztring().Ztring::ToZtring(NAME##Pos-1); \ Temp+=NewLine(Level++)+Stream+__T("_")+Object+__T(" ["); \ Temp+=NewLine(Level)+__T("shape=plaintext"); \ Temp+=NewLine(Level)+__T("label=<"); \ Temp+=Element2Html(MI, Stream_Audio, StreamPos, Object, Format, __T(FOREGROUND_COLOR), __T(BACKGROUND_COLOR), __T(TITLE_FOREGROUND_COLOR), __T(TITLE_BACKGROUND_COLOR)); \ Temp+=__T(">");\ Temp+=NewLine(--Level)+__T("]"); #define OBJECT_LINK_TO(NAME, COLOR) \ { \ ZtringList Linked##NAME##s; \ Linked##NAME##s.Separator_Set(0, __T(" + ")); \ Linked##NAME##s.Write(MI.Get(Stream_Audio, StreamPos, Object+__T(" LinkedTo_" #NAME "_Pos"), Info_Text)); \ for (size_t NAME##Pos=0; NAME##Pos<Linked##NAME##s.size(); NAME##Pos++) \ Relations.push_back(relation(Stream+__T("_")+Object, Stream+__T("_" #NAME)+Linked##NAME##s[NAME##Pos], __T("[color=\"" COLOR "\"]"))); \ } #define OBJECT_END() \ } \ Temp+=NewLine(--Level)+__T("}"); \ } //--------------------------------------------------------------------------- #if defined(MEDIAINFO_AC4_YES) Ztring Export_Graph::Ac4_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("AC-4")) return ToReturn; Ztring Format=__T("AC4"); vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); int8u Version=MI.Get(Stream_Audio, StreamPos, __T("Format_Version"), Info_Text).SubString(__T("Version "), __T("")).To_int8u(); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(Presentation, "NumberOfPresentations", "#000000", "#c5cae9", "#ffffff", "#303f9f") if (Version<2) OBJECT_LINK_TO(Substream, "#c5cae9") else OBJECT_LINK_TO(Group, "#c5cae9") OBJECT_END() if (Version>=2) { OBJECT_START(Group, "NumberOfGroups", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(Substream, "#bbdefb") OBJECT_END() } OBJECT_START(Substream, "NumberOfSubstreams", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_AC4_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_DOLBYE_YES) Ztring Export_Graph::Ed2_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("Dolby ED2")) return ToReturn; Ztring Format=__T("ED2"); vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(Presentation, "NumberOfPresentations", "#000000", "#c5cae9", "#ffffff", "#303f9f") OBJECT_END() // Targets { Temp+=NewLine(Level++)+__T("rank=same {"); size_t Presentations=MI.Get(Stream_Audio, StreamPos,__T("NumberOfPresentations"), Info_Text).To_int64u(); for (size_t PresentationPos=Presentations; PresentationPos; PresentationPos--) { Ztring Object=__T("Presentation")+Ztring().Ztring::ToZtring(PresentationPos-1); size_t Targets=MI.Get(Stream_Audio, StreamPos, Object+__T(" NumberOfTargets"), Info_Text).To_int64u(); for (size_t TargetPos=Targets; TargetPos; TargetPos--) { Ztring SubObject=__T("Target")+Ztring().Ztring::ToZtring(TargetPos-1); Temp+=NewLine(Level++)+Stream+__T("_")+Object+__T("_")+SubObject+__T(" ["); Temp+=NewLine(Level)+__T("shape=plaintext"); Temp+=NewLine(Level)+__T("label=<"); Temp+=Element2Html(MI, Stream_Audio, StreamPos, Object + __T(" ") + SubObject, __T("#000000"), Format, __T("#bbdefb"), __T("#ffffff"), __T("#1976d2")); Temp+=__T(">"); Temp+=NewLine(--Level)+__T("]"); Relations.push_back(relation(Stream+__T("_")+Object, Stream+__T("_")+Object+__T("_")+SubObject, __T("[color=\"#c5cae9\"]"))); ZtringList LinkedBeds; LinkedBeds.Separator_Set(0, __T(" + ")); LinkedBeds.Write(MI.Get(Stream_Audio, StreamPos, Object+__T(" ")+SubObject+__T(" LinkedTo_Bed_Pos"), Info_Text)); for (size_t BedPos=0; BedPos<LinkedBeds.size(); BedPos++) { if (LinkedBeds[BedPos].find(__T("-"), 0)==string::npos) Relations.push_back(relation(Stream+__T("_")+Object+__T("_")+SubObject, Stream+__T("_Bed")+LinkedBeds[BedPos], __T("[color=\"#bbdefb\"]"))); else { Ztring Bed=LinkedBeds[BedPos].SubString(__T(""), __T("-")); Ztring Alt=LinkedBeds[BedPos].SubString(__T("-"), __T("")); Relations.push_back(relation(Stream+__T("_")+Object+__T("_")+SubObject, Stream+__T("_Bed")+Bed+__T(":Alt")+Alt, __T("[color=\"#bbdefb\"]"))); } } ZtringList LinkedObjects; LinkedObjects.Separator_Set(0, __T(" + ")); LinkedObjects.Write(MI.Get(Stream_Audio, StreamPos, Object+__T(" ")+SubObject+__T(" LinkedTo_Object_Pos"), Info_Text)); for (size_t ObjectPos=0; ObjectPos<LinkedObjects.size(); ObjectPos++) { if (LinkedObjects[ObjectPos].find(__T("-"), 0)==string::npos) Relations.push_back(relation(Stream+__T("_")+Object+__T("_")+SubObject, Stream+__T("_Object")+LinkedObjects[ObjectPos], __T("[color=\"#bbdefb\"]"))); else { Ztring Obj=LinkedObjects[ObjectPos].SubString(__T(""), __T("-")); Ztring Alt=LinkedObjects[ObjectPos].SubString(__T("-"), __T("")); Relations.push_back(relation(Stream+__T("_")+Object+__T("_")+SubObject, Stream+__T("_Object")+Obj+__T(":Alt")+Alt, __T("[color=\"#bbdefb\"]"))); } } } } Temp+=NewLine(--Level)+__T("}"); } OBJECT_START(Bed, "NumberOfBeds", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() // Beds Alts { Temp+=NewLine(Level++)+__T("rank=same {"); size_t Beds=MI.Get(Stream_Audio, StreamPos,__T("NumberOfBeds"), Info_Text).To_int64u(); for (size_t BedPos=Beds; BedPos; BedPos--) { Ztring Object=__T("Bed")+Ztring().Ztring::ToZtring(BedPos-1); size_t Alts=MI.Get(Stream_Audio, StreamPos, Object+__T(" NumberOfAlts"), Info_Text).To_int64u(); for (size_t AltPos=Alts; AltPos; AltPos--) { Ztring SubObject=__T("Alt")+Ztring().Ztring::ToZtring(AltPos-1); Temp+=NewLine(Level++)+Stream+__T("_")+Object+__T("_")+SubObject+__T(" ["); Temp+=NewLine(Level)+__T("shape=plaintext"); Temp+=NewLine(Level)+__T("label=<"); Temp+=Element2Html(MI, Stream_Audio, StreamPos, Object + __T(" ") + SubObject, Format, __T("#000000"), __T("#b2ebf2"), __T("#ffffff"), __T("#00796b")); Temp+=__T(">"); Temp+=NewLine(--Level)+__T("]"); Relations.push_back(relation(Stream+__T("_")+Object, Stream+__T("_")+Object+__T("_")+SubObject, __T("[color=\"#b3e5fc\"]"))); } } Temp+=NewLine(--Level)+__T("}"); } OBJECT_START(Object, "NumberOfObjects", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() // Objects Alts { Temp+=NewLine(Level++)+__T("rank=same {"); size_t Objects=MI.Get(Stream_Audio, StreamPos,__T("NumberOfObjects"), Info_Text).To_int64u(); for (size_t ObjectPos=Objects; ObjectPos; ObjectPos--) { Ztring Object=__T("Object")+Ztring().Ztring::ToZtring(ObjectPos-1); size_t Alts=MI.Get(Stream_Audio, StreamPos, Object+__T(" NumberOfAlts"), Info_Text).To_int64u(); for (size_t AltPos=Alts; AltPos; AltPos--) { Ztring SubObject=__T("Alt")+Ztring().Ztring::ToZtring(AltPos-1); Temp+=NewLine(Level++)+Stream+__T("_")+Object+__T("_")+SubObject+__T(" ["); Temp+=NewLine(Level)+__T("shape=plaintext"); Temp+=NewLine(Level)+__T("label=<"); Temp+=Element2Html(MI, Stream_Audio, StreamPos, Object + __T(" ") + SubObject, Format, __T("#000000"), __T("#b2dfdb"), __T("#ffffff"), __T("#0288d1")); Temp+=__T(">"); Temp+=NewLine(--Level)+__T("]"); Relations.push_back(relation(Stream+__T("_")+Object, Stream+__T("_")+Object+__T("_")+SubObject, __T("[color=\"#b2ebf2\"]"))); } } Temp+=NewLine(--Level)+__T("}"); } for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_DOLBYE_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_ADM_YES) Ztring Export_Graph::Adm_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, __T("Metadata_Format")).find(__T("ADM, "), 0)!=0) return ToReturn; Ztring Format=__T("ADM"); vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(Programme, "NumberOfProgrammes", "#000000", "#c5cae9", "#ffffff", "#303f9f") OBJECT_LINK_TO(Content, "#c5cae9") OBJECT_END() OBJECT_START(Content, "NumberOfContents", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(Object, "#bbdefb") OBJECT_END() OBJECT_START(Object, "NumberOfObjects", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_LINK_TO(PackFormat, "#b3e5fc") if (MediaInfoLib::Config.Graph_Adm_ShowTrackUIDs_Get()) OBJECT_LINK_TO(TrackUID, "#b3e5fc") OBJECT_END() if (MediaInfoLib::Config.Graph_Adm_ShowTrackUIDs_Get()) { OBJECT_START(TrackUID, "NumberOfTrackUIDs", "#000000", "#b2ebf2", "#ffffff", "#0097a7") OBJECT_LINK_TO(PackFormat, "#b2ebf2") OBJECT_LINK_TO(TrackFormat, "#b2ebf2") OBJECT_END() OBJECT_START(TrackFormat, "NumberOfTrackFormats", "#000000", "#b2dfdb", "#ffffff", "#00796b") OBJECT_LINK_TO(StreamFormat, "#b2dfdb") OBJECT_END() OBJECT_START(StreamFormat, "NumberOfStreamFormats", "#000000", "#c8e6c9", "#ffffff", "#388e3c") OBJECT_LINK_TO(ChannelFormat, "#c8e6c9") OBJECT_LINK_TO(PackFormat, "#c8e6c9") OBJECT_LINK_TO(TrackFormat, "#c8e6c9") OBJECT_END() } OBJECT_START(PackFormat, "NumberOfPackFormats", "#000000", "#dcedc8", "#ffffff", "#689f38") if (MediaInfoLib::Config.Graph_Adm_ShowChannelFormats_Get()) OBJECT_LINK_TO(ChannelFormat, "#dcedc8") OBJECT_END() if (MediaInfoLib::Config.Graph_Adm_ShowChannelFormats_Get()) { OBJECT_START(ChannelFormat, "NumberOfChannelFormats", "#000000", "#f0f4c3", "#ffffff", "#afb42b") OBJECT_END() } for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_ADM_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_MPEGH3DA_YES) Ztring Export_Graph::Mpegh3da_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("MPEG-H 3D Audio")) return ToReturn; Ztring Format=__T("MPEG3DA"); vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(SwitchGroup, "SwitchGroupCount", "#000000", "#c5cae9", "#ffffff", "#303f9f") OBJECT_LINK_TO(Group, "#c5cae9") OBJECT_END() OBJECT_START(Group, "GroupCount", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(SignalGroup, "#bbdefb") OBJECT_END() OBJECT_START(SignalGroup, "SignalGroupCount", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_MPEGH3DA_YES) //*************************************************************************** // Input //*************************************************************************** //--------------------------------------------------------------------------- Ztring Export_Graph::Transform(MediaInfo_Internal &MI, Export_Graph::graph Graph, Export_Graph::format Format) { Ztring ToReturn; size_t Level=1; bool ExpandSub_Old=MI.Config.File_ExpandSubs_Get(); MI.Config.File_ExpandSubs_Set(false); Ztring FileName=XML_Encode(MI.Get(Stream_General, 0, General_FileNameExtension)); if (FileName.empty()) FileName=__T("&nbsp;"); ToReturn+=__T("graph {"); ToReturn+=NewLine(Level)+__T("color=\"#1565c0\""); ToReturn+=NewLine(Level)+__T("fontcolor=\"#1565c0\""); ToReturn+=NewLine(Level)+__T("labelloc=t"); ToReturn+=NewLine(Level)+__T("label=<<b>")+FileName+__T("</b>>"); Ztring Temp; for (size_t StreamPos=0; StreamPos<(size_t)MI.Count_Get(Stream_Audio); StreamPos++) { #if defined(MEDIAINFO_AC4_YES) if (Graph==Graph_All || Graph==Graph_Ac4) Temp+=Ac4_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_AC4_YES) #if defined(MEDIAINFO_DOLBYE_YES) if (Graph==Graph_All || Graph==Graph_Ed2) Temp+=Ed2_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_DOLBYE_YES) #if defined(MEDIAINFO_ADM_YES) if (Graph==Graph_All || Graph==Graph_Adm) Temp+=Adm_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_ADM_YES) #if defined(MEDIAINFO_MPEGH3DA_YES) if (Graph==Graph_All || Graph==Graph_Mpegh3da) Temp+=Mpegh3da_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_MPEGH3DA_YES) } if (!Temp.empty()) ToReturn+=Temp; else ToReturn+=NewLine(Level)+__T("message [shape=plaintext, fontcolor=\"#1565c0\", label=<<b>Graphs are currently available for AC-4, MPEG-H, Dolby ED2 and ADM formats.</b>>]"); ToReturn+=__T("\n}"); #ifdef MEDIAINFO_GRAPHVIZ_YES if (Format==Format_Svg) ToReturn=Dot2Svg(ToReturn); #endif //MEDIAINFO_GRAPHVIZ_YES MI.Config.File_ExpandSubs_Set(ExpandSub_Old); return ToReturn; } //*************************************************************************** // //*************************************************************************** } //NameSpace #endif
12,169
640
<reponame>jpoikela/z88dk<gh_stars>100-1000 #include "paranoia.h" void part7(VOID){ Milestone = 130; /*=============================================*/ Y = - FLOOR(Half - TwoForty * LOG(UfThold) / LOG(HInvrse)) / TwoForty; Y2 = Y + Y; printf("Since underflow occurs below the threshold\n"); printf("UfThold = (%.17e) ^ (%.17e)\nonly underflow ", HInvrse, Y); printf("should afflict the expression\n\t(%.17e) ^ (%.17e);\n", HInvrse, Y2); printf("actually calculating yields:"); if (setjmp(ovfl_buf)) { sigsave = 0; BadCond(Serious, "trap on underflow.\n"); } else { sigsave = sigfpe; V9 = POW(HInvrse, Y2); sigsave = 0; printf(" %.17e .\n", V9); if (! ((V9 >= Zero) && (V9 <= (Radix + Radix + E9) * UfThold))) { BadCond(Serious, "this is not between 0 and underflow\n"); printf(" threshold = %.17e .\n", UfThold); } else if (! (V9 > UfThold * (One + E9))) printf("This computed value is O.K.\n"); else { BadCond(Defect, "this is not between 0 and underflow\n"); printf(" threshold = %.17e .\n", UfThold); } } /*=============================================*/ Milestone = 140; /*=============================================*/ printf("\n"); /* ...calculate Exp2 == exp(2) == 7.389056099... */ X = Zero; I = 2; Y = Two * Three; Q = Zero; N = 0; do { Z = X; I = I + 1; Y = Y / (I + I); R = Y + Q; X = Z + R; Q = (Z - X) + R; } while(X > Z); Z = (OneAndHalf + One / Eight) + X / (OneAndHalf * ThirtyTwo); X = Z * Z; Exp2 = X * X; X = F9; Y = X - U1; printf("Testing X^((X + 1) / (X - 1)) vs. exp(2) = %.17e as X -> 1.\n", Exp2); for(I = 1;;) { Z = X - BInvrse; Z = (X + One) / (Z - (One - BInvrse)); Q = POW(X, Z) - Exp2; if (FABS(Q) > TwoForty * U2) { N = 1; V9 = (X - BInvrse) - (One - BInvrse); BadCond(Defect, "Calculated"); printf(" %.17e for\n", POW(X,Z)); printf("\t(1 + (%.17e) ^ (%.17e);\n", V9, Z); printf("\tdiffers from correct value by %.17e .\n", Q); printf("\tThis much error may spoil financial\n"); printf("\tcalculations involving tiny interest rates.\n"); break; } else { Z = (Y - X) * Two + Y; X = Y; Y = Z; Z = One + (X - F9)*(X - F9); if (Z > One && I < NoTrials) I++; else { if (X > One) { if (N == 0) printf("Accuracy seems adequate.\n"); break; } else { X = One + U2; Y = U2 + U2; Y += X; I = 1; } } } } /*=============================================*/ Milestone = 150; /*=============================================*/ printf("Testing powers Z^Q at four nearly extreme values.\n"); N = 0; Z = A1; Q = FLOOR(Half - LOG(C) / LOG(A1)); Break = False; do { X = CInvrse; Y = POW(Z, Q); IsYeqX(); Q = - Q; X = C; Y = POW(Z, Q); IsYeqX(); if (Z < One) Break = True; else Z = AInvrse; } while ( ! (Break)); PrintIfNPositive(); if (N == 0) printf(" ... no discrepancies found.\n"); printf("\n"); /*=============================================*/ Milestone = 160; /*=============================================*/ Pause(); printf("Searching for Overflow threshold:\n"); printf("This may generate an error.\n"); Y = - CInvrse; V9 = HInvrse * Y; sigsave = sigfpe; if (setjmp(ovfl_buf)) { I = 0; V9 = Y; goto overflow; } do { V = Y; Y = V9; V9 = HInvrse * Y; } while(V9 < Y); I = 1; overflow: sigsave = 0; Z = V9; printf("Can `Z = -Y' overflow?\n"); printf("Trying it on Y = %.17e .\n", Y); V9 = - Y; V0 = V9; if (V - Y == V + V0) printf("Seems O.K.\n"); else { printf("finds a "); BadCond(Flaw, "-(-Y) differs from Y.\n"); } if (Z != Y) { BadCond(Serious, ""); printf("overflow past %.17e\n\tshrinks to %.17e .\n", Y, Z); } if (I) { Y = V * (HInvrse * U2 - HInvrse); Z = Y + ((One - HInvrse) * U2) * V; if (Z < V0) Y = Z; if (Y < V0) V = Y; if (V0 - V < V0) V = V0; } else { V = Y * (HInvrse * U2 - HInvrse); V = V + ((One - HInvrse) * U2) * Y; } printf("Overflow threshold is V = %.17e .\n", V); if (I) printf("Overflow saturates at V0 = %.17e .\n", V0); else printf("There is no saturation value because \ the system traps on overflow.\n"); V9 = V * One; printf("No Overflow should be signaled for V * 1 = %.17e\n", V9); V9 = V / One; printf(" nor for V / 1 = %.17e .\n", V9); printf("Any overflow signal separating this * from the one\n"); printf("above is a DEFECT.\n"); /*=============================================*/ Milestone = 170; /*=============================================*/ if (!(-V < V && -V0 < V0 && -UfThold < V && UfThold < V)) { BadCond(Failure, "Comparisons involving "); printf("+-%g, +-%g\nand +-%g are confused by Overflow.", V, V0, UfThold); } /*=============================================*/ Milestone = 175; /*=============================================*/ printf("\n"); for(Indx = 1; Indx <= 3; ++Indx) { switch (Indx) { case 1: Z = UfThold; break; case 2: Z = E0; break; case 3: Z = PseudoZero; break; } if (Z != Zero) { V9 = SQRT(Z); Y = V9 * V9; if (Y / (One - Radix * E9) < Z || Y > (One + Radix * E9) * Z) { /* dgh: + E9 --> * E9 */ if (V9 > U1) BadCond(Serious, ""); else BadCond(Defect, ""); printf("Comparison alleges that what prints as Z = %.17e\n", Z); printf(" is too far from sqrt(Z) ^ 2 = %.17e .\n", Y); } } } /*=============================================*/ Milestone = 180; /*=============================================*/ for(Indx = 1; Indx <= 2; ++Indx) { if (Indx == 1) Z = V; else Z = V0; V9 = SQRT(Z); X = (One - Radix * E9) * V9; V9 = V9 * X; if (((V9 < (One - Two * Radix * E9) * Z) || (V9 > Z))) { Y = V9; if (X < W) BadCond(Serious, ""); else BadCond(Defect, ""); printf("Comparison alleges that Z = %17e\n", Z); printf(" is too far from sqrt(Z) ^ 2 (%.17e) .\n", Y); } } /*=============================================*/ }
2,740
1,602
/* gmp-mparam.h -- Compiler/machine parameter header file. Copyright 1991, 1993, 1994, 1999-2003, 2009, 2010 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * 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. or both in parallel, as here. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #define GMP_LIMB_BITS 32 #define GMP_LIMB_BYTES 4 /* 1193MHz ARM (gcc55.fsffrance.org) */ #define DIVREM_1_NORM_THRESHOLD 0 /* preinv always */ #define DIVREM_1_UNNORM_THRESHOLD 0 /* always */ #define MOD_1_NORM_THRESHOLD 0 /* always */ #define MOD_1_UNNORM_THRESHOLD 0 /* always */ #define MOD_1N_TO_MOD_1_1_THRESHOLD 56 #define MOD_1U_TO_MOD_1_1_THRESHOLD 11 #define MOD_1_1_TO_MOD_1_2_THRESHOLD 0 /* never mpn_mod_1_1p */ #define MOD_1_2_TO_MOD_1_4_THRESHOLD MP_SIZE_T_MAX #define PREINV_MOD_1_TO_MOD_1_THRESHOLD 71 #define USE_PREINV_DIVREM_1 1 /* preinv always */ #define DIVREM_2_THRESHOLD 0 /* preinv always */ #define DIVEXACT_1_THRESHOLD 0 /* always */ #define BMOD_1_TO_MOD_1_THRESHOLD 41 #define MUL_TOOM22_THRESHOLD 36 #define MUL_TOOM33_THRESHOLD 125 #define MUL_TOOM44_THRESHOLD 193 #define MUL_TOOM6H_THRESHOLD 303 #define MUL_TOOM8H_THRESHOLD 418 #define MUL_TOOM32_TO_TOOM43_THRESHOLD 125 #define MUL_TOOM32_TO_TOOM53_THRESHOLD 176 #define MUL_TOOM42_TO_TOOM53_THRESHOLD 114 #define MUL_TOOM42_TO_TOOM63_THRESHOLD 129 #define SQR_BASECASE_THRESHOLD 12 #define SQR_TOOM2_THRESHOLD 78 #define SQR_TOOM3_THRESHOLD 137 #define SQR_TOOM4_THRESHOLD 212 #define SQR_TOOM6_THRESHOLD 306 #define SQR_TOOM8_THRESHOLD 422 #define MULMOD_BNM1_THRESHOLD 20 #define SQRMOD_BNM1_THRESHOLD 26 #define MUL_FFT_MODF_THRESHOLD 436 /* k = 5 */ #define MUL_FFT_TABLE3 \ { { 436, 5}, { 27, 6}, { 28, 7}, { 15, 6}, \ { 32, 7}, { 17, 6}, { 35, 7}, { 19, 6}, \ { 39, 7}, { 29, 8}, { 15, 7}, { 35, 8}, \ { 19, 7}, { 41, 8}, { 23, 7}, { 49, 8}, \ { 27, 9}, { 15, 8}, { 31, 7}, { 63, 8}, \ { 256, 9}, { 512,10}, { 1024,11}, { 2048,12}, \ { 4096,13}, { 8192,14}, { 16384,15}, { 32768,16} } #define MUL_FFT_TABLE3_SIZE 28 #define MUL_FFT_THRESHOLD 5760 #define SQR_FFT_MODF_THRESHOLD 404 /* k = 5 */ #define SQR_FFT_TABLE3 \ { { 404, 5}, { 13, 4}, { 27, 5}, { 27, 6}, \ { 28, 7}, { 15, 6}, { 32, 7}, { 17, 6}, \ { 35, 7}, { 29, 8}, { 15, 7}, { 35, 8}, \ { 19, 7}, { 41, 8}, { 23, 7}, { 47, 8}, \ { 27, 9}, { 15, 8}, { 39, 9}, { 512,10}, \ { 1024,11}, { 2048,12}, { 4096,13}, { 8192,14}, \ { 16384,15}, { 32768,16} } #define SQR_FFT_TABLE3_SIZE 26 #define SQR_FFT_THRESHOLD 3776 #define MULLO_BASECASE_THRESHOLD 0 /* always */ #define MULLO_DC_THRESHOLD 137 #define MULLO_MUL_N_THRESHOLD 11479 #define DC_DIV_QR_THRESHOLD 150 #define DC_DIVAPPR_Q_THRESHOLD 494 #define DC_BDIV_QR_THRESHOLD 148 #define DC_BDIV_Q_THRESHOLD 345 #define INV_MULMOD_BNM1_THRESHOLD 70 #define INV_NEWTON_THRESHOLD 474 #define INV_APPR_THRESHOLD 478 #define BINV_NEWTON_THRESHOLD 542 #define REDC_1_TO_REDC_N_THRESHOLD 117 #define MU_DIV_QR_THRESHOLD 2089 #define MU_DIVAPPR_Q_THRESHOLD 2172 #define MUPI_DIV_QR_THRESHOLD 225 #define MU_BDIV_QR_THRESHOLD 1528 #define MU_BDIV_Q_THRESHOLD 2089 #define MATRIX22_STRASSEN_THRESHOLD 16 #define HGCD_THRESHOLD 197 #define GCD_DC_THRESHOLD 902 #define GCDEXT_DC_THRESHOLD 650 #define JACOBI_BASE_METHOD 2 #define GET_STR_DC_THRESHOLD 20 #define GET_STR_PRECOMPUTE_THRESHOLD 39 #define SET_STR_DC_THRESHOLD 1045 #define SET_STR_PRECOMPUTE_THRESHOLD 2147
2,811
1,553
# coding=utf-8 import traceback def dispatch_migrate(): try: migrate() except: Log.Error("Migration failed: %s" % traceback.format_exc()) del Dict["subs"] Dict.Save() def migrate(): """ some Dict/Data migrations here, no need for a more in-depth migration path for now :return: """ # migrate subtitle history from Dict to Data if "history" in Dict and Dict["history"].get("history_items"): Log.Debug("Running migration for history data") from support.history import get_history history = get_history() for item in reversed(Dict["history"]["history_items"]): history.add(item.item_title, item.rating_key, item.section_title, subtitle=item.subtitle, mode=item.mode, time=item.time) del Dict["history"] history.destroy() Dict.Save() # migrate subtitle storage from Dict to Data if "subs" in Dict: from support.storage import get_subtitle_storage from subzero.subtitle_storage import StoredSubtitle from support.plex_media import get_item subtitle_storage = get_subtitle_storage() for video_id, parts in Dict["subs"].iteritems(): try: item = get_item(video_id) except: continue if not item: continue stored_subs = subtitle_storage.load_or_new(item) stored_subs.version = 1 Log.Debug(u"Migrating %s" % video_id) stored_any = False for part_id, lang_dict in parts.iteritems(): part_id = str(part_id) Log.Debug(u"Migrating %s, %s" % (video_id, part_id)) for lang, subs in lang_dict.iteritems(): lang = str(lang) if "current" in subs: current_key = subs["current"] provider_name, subtitle_id = current_key sub = subs.get(current_key) if sub and sub.get("title") and sub.get("mode"): # ditch legacy data without sufficient info stored_subs.title = sub["title"] new_sub = StoredSubtitle(sub["score"], sub["storage"], sub["hash"], provider_name, subtitle_id, date_added=sub["date_added"], mode=sub["mode"]) if part_id not in stored_subs.parts: stored_subs.parts[part_id] = {} if lang not in stored_subs.parts[part_id]: stored_subs.parts[part_id][lang] = {} Log.Debug(u"Migrating %s, %s, %s" % (video_id, part_id, current_key)) stored_subs.parts[part_id][lang][current_key] = new_sub stored_subs.parts[part_id][lang]["current"] = current_key stored_any = True if stored_any: subtitle_storage.save(stored_subs) subtitle_storage.destroy() del Dict["subs"] Dict.Save()
1,640
1,391
<gh_stars>1000+ #include "mplot.h" void rvec(double xx, double yy){ e1->copyx += xx; e1->copyy += yy; vec(e1->copyx, e1->copyy); }
68
10,225
<reponame>CraigMcDonaldCodes/quarkus<gh_stars>1000+ package io.quarkus.it.virtual; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.microsoft.azure.functions.ExecutionContext; import com.microsoft.azure.functions.HttpMethod; import com.microsoft.azure.functions.HttpResponseMessage; import com.microsoft.azure.functions.HttpStatus; import io.quarkus.azure.functions.resteasy.runtime.Function; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; /** * Unit test for Function class. */ @QuarkusTest public class FunctionTest { @Test public void testSwagger() { final HttpRequestMessageMock req = new HttpRequestMessageMock(); req.setUri(URI.create("https://foo.com/q/swagger-ui/")); req.setHttpMethod(HttpMethod.GET); // Invoke final HttpResponseMessage ret = new Function().run(req, createContext()); // Verify Assertions.assertEquals(ret.getStatus(), HttpStatus.OK); String body = new String((byte[]) ret.getBody(), StandardCharsets.UTF_8); Assertions.assertTrue(body.contains("OpenAPI UI")); } private ExecutionContext createContext() { return new ExecutionContext() { @Override public Logger getLogger() { return null; } @Override public String getInvocationId() { return null; } @Override public String getFunctionName() { return null; } }; } @Test public void testJaxrs() throws Exception { String uri = "https://foo.com/hello"; testGET(uri); testPOST(uri); } @Test public void testNotFound() { final HttpRequestMessageMock req = new HttpRequestMessageMock(); req.setUri(URI.create("https://nowhere.com/badroute")); req.setHttpMethod(HttpMethod.GET); // Invoke final HttpResponseMessage ret = new Function().run(req, createContext()); // Verify Assertions.assertEquals(ret.getStatus(), HttpStatus.NOT_FOUND); } @Test public void testHttp() { // assure that socket is created in dev/test mode RestAssured.when().get("/hello").then() .contentType("text/plain") .body(equalTo("hello")); RestAssured.given().contentType("text/plain").body("Bill").post("/hello").then() .contentType("text/plain") .body(containsString("hello Bill")); } private void testGET(String uri) { final HttpRequestMessageMock req = new HttpRequestMessageMock(); req.setUri(URI.create(uri)); req.setHttpMethod(HttpMethod.GET); // Invoke final HttpResponseMessage ret = new Function().run(req, createContext()); // Verify Assertions.assertEquals(ret.getStatus(), HttpStatus.OK); Assertions.assertEquals("hello", new String((byte[]) ret.getBody(), StandardCharsets.UTF_8)); String contentType = ret.getHeader("Content-Type"); Assertions.assertNotNull(contentType); Assertions.assertTrue(MediaType.valueOf(contentType).isCompatible(MediaType.TEXT_PLAIN_TYPE)); } private void testPOST(String uri) { final HttpRequestMessageMock req = new HttpRequestMessageMock(); req.setUri(URI.create(uri)); req.setHttpMethod(HttpMethod.POST); req.setBody("Bill"); req.getHeaders().put("Content-Type", "text/plain"); // Invoke final HttpResponseMessage ret = new Function().run(req, createContext()); // Verify Assertions.assertEquals(ret.getStatus(), HttpStatus.OK); Assertions.assertEquals("hello Bill", new String((byte[]) ret.getBody(), StandardCharsets.UTF_8)); String contentType = ret.getHeader("Content-Type"); Assertions.assertNotNull(contentType); Assertions.assertTrue(MediaType.valueOf(contentType).isCompatible(MediaType.TEXT_PLAIN_TYPE)); } }
1,778
347
package org.ovirt.engine.core.bll.snapshots; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.ImageStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.DiskImageDao; @ExtendWith(MockitoExtension.class) public class SnapshotVmConfigurationHelperTest { @Mock private DiskImageDao diskImageDaoMock; private Guid existingSnapshotId = Guid.newGuid(); private Guid existingVmId = Guid.newGuid(); private Guid existingImageId = Guid.newGuid(); private Guid existingImageGroupId = Guid.newGuid(); private Snapshot existingSnapshot; private VM existingVm = null; private DiskImage existingDiskImage; @InjectMocks @Spy private SnapshotVmConfigurationHelper snapshotVmConfigurationHelper; private static final String EXISTING_VM_NAME = "Dummy configuration"; @BeforeEach public void setUp() { existingSnapshot = createSnapshot(existingSnapshotId); existingVm = createVm(existingVmId); existingSnapshot.setVmConfiguration(EXISTING_VM_NAME); // Dummy configuration existingDiskImage = createDiskImage(existingImageId, existingImageGroupId); } private VM createVm(Guid existingVmId) { VM vm = new VM(); vm.setId(existingVmId); return vm; } private Snapshot createSnapshot(Guid existingSnapshotId) { Snapshot snapshot = new Snapshot(); snapshot.setId(existingSnapshotId); snapshot.setVmId(existingVmId); snapshot.setVmConfiguration(EXISTING_VM_NAME); return snapshot; } private DiskImage createDiskImage(Guid diskImageId, Guid imageGroupId) { DiskImage diskImage = new DiskImage(); diskImage.setImageId(diskImageId); diskImage.setId(imageGroupId); return diskImage; } @Test public void testIllegalImageReturnedByQuery() { existingVm.getDiskMap().put(existingDiskImage.getId(), existingDiskImage); existingVm.getImages().add(existingDiskImage); snapshotVmConfigurationHelper.markImagesIllegalIfNotInDb(existingVm, existingSnapshotId); for (Disk diskImage : existingVm.getDiskMap().values()) { assertEquals(ImageStatus.ILLEGAL, ((DiskImage)diskImage).getImageStatus()); } } }
1,056
575
// Copyright 2016 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. #ifndef IOS_CHROME_BROWSER_UI_HISTORY_IOS_BROWSING_HISTORY_DRIVER_H_ #define IOS_CHROME_BROWSER_UI_HISTORY_IOS_BROWSING_HISTORY_DRIVER_H_ #include <vector> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/history/core/browser/browsing_history_driver.h" #include "components/history/core/browser/browsing_history_service.h" #include "url/gurl.h" class ChromeBrowserState; namespace history { class HistoryService; } @protocol HistoryConsumer; // A simple implementation of BrowsingHistoryServiceHandler that delegates to // objective-c object HistoryConsumer for most actions. class IOSBrowsingHistoryDriver : public history::BrowsingHistoryDriver { public: IOSBrowsingHistoryDriver(ChromeBrowserState* browser_state, id<HistoryConsumer> consumer); ~IOSBrowsingHistoryDriver() override; private: // history::BrowsingHistoryDriver implementation. void OnQueryComplete( const std::vector<history::BrowsingHistoryService::HistoryEntry>& results, const history::BrowsingHistoryService::QueryResultsInfo& query_results_info, base::OnceClosure continuation_closure) override; void OnRemoveVisitsComplete() override; void OnRemoveVisitsFailed() override; void OnRemoveVisits( const std::vector<history::ExpireHistoryArgs>& expire_list) override; void HistoryDeleted() override; void HasOtherFormsOfBrowsingHistory(bool has_other_forms, bool has_synced_results) override; bool AllowHistoryDeletions() override; bool ShouldHideWebHistoryUrl(const GURL& url) override; history::WebHistoryService* GetWebHistoryService() override; void ShouldShowNoticeAboutOtherFormsOfBrowsingHistory( const syncer::SyncService* sync_service, history::WebHistoryService* history_service, base::OnceCallback<void(bool)> callback) override; // The current browser state. ChromeBrowserState* browser_state_; // weak // Consumer for IOSBrowsingHistoryDriver. Serves as client for HistoryService. __weak id<HistoryConsumer> consumer_; DISALLOW_COPY_AND_ASSIGN(IOSBrowsingHistoryDriver); }; #endif // IOS_CHROME_BROWSER_UI_HISTORY_IOS_BROWSING_HISTORY_DRIVER_H_
802
1,006
<reponame>eenurkka/incubator-nuttx<filename>boards/arm/tms570/launchxl-tms57004/src/launchxl-tms57004.h /**************************************************************************** * boards/arm/tms570/launchxl-tms57004/src/launchxl-tms57004.h * * 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. * ****************************************************************************/ #ifndef __BOARDS_ARM_TMS570_LAUNCHXL_TMS57004_SRC_LAUNCHXL_TMS57004_H #define __BOARDS_ARM_TMS570_LAUNCHXL_TMS57004_SRC_LAUNCHXL_TMS57004_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* LEDs * * The launchpad has several LEDs: * * - LEd D1 (white) that connects to the USB +5V supply, * - LED D10 (red) that connects to the TMS570's NERROR pin, * - D5 (blue), D6 (blue), and D8 (blue) connect to the XDS100 FT2322, * - D7 (blue) connects to the XSD100 CPLD, and * - Two white, user LEDs labeled D12 that connects to the NHET08 * pin and D11 that connects to GIOA2. * * NHET08 is one of 32 N2HET pins than can be available to the user if not * used by N2HET. This implementation, however, uses only the single LED * driven by GIOA2. That LED is tied to ground and illuminated with a high * level output value. */ #define GIO_LED_D11 (GIO_OUTPUT | GIO_CFG_DEFAULT | GIO_OUTPUT_SET | \ GIO_PORT_GIOA | GIO_PIN2) /* Buttons * * The launchpad has three mechanical buttons. Two of these are reset * buttons: One button is labeled PORRST performs a power-on reset and one * labeled RST performs an MCU reset. Only one button is available for * general software usage. That button is labeled GIOA7 and is, obviously, * sensed on GIOA7. * * GIOA7 is tied to ground, but will be pulled high if the GIOA7 button is * depressed. */ #define GIO_BUTTON (GIO_INPUT | GIO_CFG_PULLUP | GIO_INT_BOTHEDGES | \ GIO_PORT_GIOA | GIO_PIN7) #define IRQ_BUTTON TMS570_IRQ_GIOA7 /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: tms570_bringup * * Description: * Bring up simulated board features * ****************************************************************************/ int tms570_bringup(void); #endif /* __BOARDS_ARM_TMS570_LAUNCHXL_TMS57004_SRC_LAUNCHXL_TMS57004_H */
1,031
545
int main() { double dval; int ival; int *pi; //dval = ival = pi = 0; // the type of `pi` is `int *` which cannot be converted to `int` dval = ival = 0; pi = 0; return 0; }
82
550
<reponame>cclauss/traceback_with_variables >>> from traceback_with_variables import print_exc >>> def f(n): .... return 1 / n .... >>> f(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f ZeroDivisionError: division by zero >>> print_exc() >>> # you might want to import activate_[in_ipython]by_import to automate this step
132
372
<reponame>mdbloice/systemds # ------------------------------------------------------------- # # 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. # # ------------------------------------------------------------- # Autogenerated By : src/main/python/generator/generator.py from .builtin.WoE import WoE from .builtin.WoEApply import WoEApply from .builtin.abstain import abstain from .builtin.als import als from .builtin.alsCG import alsCG from .builtin.alsDS import alsDS from .builtin.alsPredict import alsPredict from .builtin.alsTopkPredict import alsTopkPredict from .builtin.apply_pipeline import apply_pipeline from .builtin.arima import arima from .builtin.autoencoder_2layer import autoencoder_2layer from .builtin.bandit import bandit from .builtin.bivar import bivar from .builtin.components import components from .builtin.confusionMatrix import confusionMatrix from .builtin.cor import cor from .builtin.correctTypos import correctTypos from .builtin.correctTyposApply import correctTyposApply from .builtin.cox import cox from .builtin.cspline import cspline from .builtin.csplineCG import csplineCG from .builtin.csplineDS import csplineDS from .builtin.cvlm import cvlm from .builtin.dbscan import dbscan from .builtin.dbscanApply import dbscanApply from .builtin.decisionTree import decisionTree from .builtin.decisionTreePredict import decisionTreePredict from .builtin.deepWalk import deepWalk from .builtin.denialConstraints import denialConstraints from .builtin.discoverFD import discoverFD from .builtin.dist import dist from .builtin.dmv import dmv from .builtin.ema import ema from .builtin.executePipeline import executePipeline from .builtin.ffPredict import ffPredict from .builtin.ffTrain import ffTrain from .builtin.fit_pipeline import fit_pipeline from .builtin.fixInvalidLengths import fixInvalidLengths from .builtin.fixInvalidLengthsApply import fixInvalidLengthsApply from .builtin.frameSort import frameSort from .builtin.frequencyEncode import frequencyEncode from .builtin.frequencyEncodeApply import frequencyEncodeApply from .builtin.garch import garch from .builtin.gaussianClassifier import gaussianClassifier from .builtin.getAccuracy import getAccuracy from .builtin.glm import glm from .builtin.glmPredict import glmPredict from .builtin.gmm import gmm from .builtin.gmmPredict import gmmPredict from .builtin.gnmf import gnmf from .builtin.gridSearch import gridSearch from .builtin.hospitalResidencyMatch import hospitalResidencyMatch from .builtin.hyperband import hyperband from .builtin.img_brightness import img_brightness from .builtin.img_crop import img_crop from .builtin.img_cutout import img_cutout from .builtin.img_invert import img_invert from .builtin.img_mirror import img_mirror from .builtin.img_posterize import img_posterize from .builtin.img_rotate import img_rotate from .builtin.img_sample_pairing import img_sample_pairing from .builtin.img_shear import img_shear from .builtin.img_transform import img_transform from .builtin.img_translate import img_translate from .builtin.impurityMeasures import impurityMeasures from .builtin.imputeByFD import imputeByFD from .builtin.imputeByFDApply import imputeByFDApply from .builtin.imputeByMean import imputeByMean from .builtin.imputeByMeanApply import imputeByMeanApply from .builtin.imputeByMedian import imputeByMedian from .builtin.imputeByMedianApply import imputeByMedianApply from .builtin.imputeByMode import imputeByMode from .builtin.imputeByModeApply import imputeByModeApply from .builtin.intersect import intersect from .builtin.km import km from .builtin.kmeans import kmeans from .builtin.kmeansPredict import kmeansPredict from .builtin.knn import knn from .builtin.knnGraph import knnGraph from .builtin.knnbf import knnbf from .builtin.l2svm import l2svm from .builtin.l2svmPredict import l2svmPredict from .builtin.lasso import lasso from .builtin.lenetPredict import lenetPredict from .builtin.lenetTrain import lenetTrain from .builtin.lm import lm from .builtin.lmCG import lmCG from .builtin.lmDS import lmDS from .builtin.lmPredict import lmPredict from .builtin.logSumExp import logSumExp from .builtin.matrixProfile import matrixProfile from .builtin.mcc import mcc from .builtin.mdedup import mdedup from .builtin.mice import mice from .builtin.miceApply import miceApply from .builtin.msvm import msvm from .builtin.msvmPredict import msvmPredict from .builtin.multiLogReg import multiLogReg from .builtin.multiLogRegPredict import multiLogRegPredict from .builtin.na_locf import na_locf from .builtin.naiveBayes import naiveBayes from .builtin.naiveBayesPredict import naiveBayesPredict from .builtin.normalize import normalize from .builtin.normalizeApply import normalizeApply from .builtin.outlier import outlier from .builtin.outlierByArima import outlierByArima from .builtin.outlierByIQR import outlierByIQR from .builtin.outlierByIQRApply import outlierByIQRApply from .builtin.outlierBySd import outlierBySd from .builtin.outlierBySdApply import outlierBySdApply from .builtin.pca import pca from .builtin.pcaInverse import pcaInverse from .builtin.pcaTransform import pcaTransform from .builtin.pnmf import pnmf from .builtin.ppca import ppca from .builtin.randomForest import randomForest from .builtin.scale import scale from .builtin.scaleApply import scaleApply from .builtin.scaleMinMax import scaleMinMax from .builtin.selectByVarThresh import selectByVarThresh from .builtin.setdiff import setdiff from .builtin.sherlock import sherlock from .builtin.sherlockPredict import sherlockPredict from .builtin.shortestPath import shortestPath from .builtin.sigmoid import sigmoid from .builtin.slicefinder import slicefinder from .builtin.smote import smote from .builtin.softmax import softmax from .builtin.split import split from .builtin.splitBalanced import splitBalanced from .builtin.stableMarriage import stableMarriage from .builtin.statsNA import statsNA from .builtin.steplm import steplm from .builtin.stratstats import stratstats from .builtin.symmetricDifference import symmetricDifference from .builtin.tSNE import tSNE from .builtin.toOneHot import toOneHot from .builtin.tomeklink import tomeklink from .builtin.topk_cleaning import topk_cleaning from .builtin.underSampling import underSampling from .builtin.union import union from .builtin.unique import unique from .builtin.univar import univar from .builtin.vectorToCsv import vectorToCsv from .builtin.winsorize import winsorize from .builtin.winsorizeApply import winsorizeApply from .builtin.xdummy1 import xdummy1 from .builtin.xdummy2 import xdummy2 from .builtin.xgboost import xgboost from .builtin.xgboostPredictClassification import xgboostPredictClassification from .builtin.xgboostPredictRegression import xgboostPredictRegression __all__ = ['WoE', 'WoEApply', 'abstain', 'als', 'alsCG', 'alsDS', 'alsPredict', 'alsTopkPredict', 'apply_pipeline', 'arima', 'autoencoder_2layer', 'bandit', 'bivar', 'components', 'confusionMatrix', 'cor', 'correctTypos', 'correctTyposApply', 'cox', 'cspline', 'csplineCG', 'csplineDS', 'cvlm', 'dbscan', 'dbscanApply', 'decisionTree', 'decisionTreePredict', 'deepWalk', 'denialConstraints', 'discoverFD', 'dist', 'dmv', 'ema', 'executePipeline', 'ffPredict', 'ffTrain', 'fit_pipeline', 'fixInvalidLengths', 'fixInvalidLengthsApply', 'frameSort', 'frequencyEncode', 'frequencyEncodeApply', 'garch', 'gaussianClassifier', 'getAccuracy', 'glm', 'glmPredict', 'gmm', 'gmmPredict', 'gnmf', 'gridSearch', 'hospitalResidencyMatch', 'hyperband', 'img_brightness', 'img_crop', 'img_cutout', 'img_invert', 'img_mirror', 'img_posterize', 'img_rotate', 'img_sample_pairing', 'img_shear', 'img_transform', 'img_translate', 'impurityMeasures', 'imputeByFD', 'imputeByFDApply', 'imputeByMean', 'imputeByMeanApply', 'imputeByMedian', 'imputeByMedianApply', 'imputeByMode', 'imputeByModeApply', 'intersect', 'km', 'kmeans', 'kmeansPredict', 'knn', 'knnGraph', 'knnbf', 'l2svm', 'l2svmPredict', 'lasso', 'lenetPredict', 'lenetTrain', 'lm', 'lmCG', 'lmDS', 'lmPredict', 'logSumExp', 'matrixProfile', 'mcc', 'mdedup', 'mice', 'miceApply', 'msvm', 'msvmPredict', 'multiLogReg', 'multiLogRegPredict', 'na_locf', 'naiveBayes', 'naiveBayesPredict', 'normalize', 'normalizeApply', 'outlier', 'outlierByArima', 'outlierByIQR', 'outlierByIQRApply', 'outlierBySd', 'outlierBySdApply', 'pca', 'pcaInverse', 'pcaTransform', 'pnmf', 'ppca', 'randomForest', 'scale', 'scaleApply', 'scaleMinMax', 'selectByVarThresh', 'setdiff', 'sherlock', 'sherlockPredict', 'shortestPath', 'sigmoid', 'slicefinder', 'smote', 'softmax', 'split', 'splitBalanced', 'stableMarriage', 'statsNA', 'steplm', 'stratstats', 'symmetricDifference', 'tSNE', 'toOneHot', 'tomeklink', 'topk_cleaning', 'underSampling', 'union', 'unique', 'univar', 'vectorToCsv', 'winsorize', 'winsorizeApply', 'xdummy1', 'xdummy2', 'xgboost', 'xgboostPredictClassification', 'xgboostPredictRegression']
3,417
831
<reponame>qq1056779951/android<filename>android/src/com/android/tools/idea/startup/AndroidSdkInitializer.java /* * Copyright (C) 2015 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.android.tools.idea.startup; import static com.android.tools.idea.util.PropertiesFiles.getProperties; import static com.intellij.openapi.util.io.FileUtil.toCanonicalPath; import static com.intellij.openapi.util.text.StringUtil.isEmpty; import static org.jetbrains.android.sdk.AndroidSdkUtils.DEFAULT_JDK_NAME; import static org.jetbrains.android.sdk.AndroidSdkUtils.createNewAndroidPlatform; import static org.jetbrains.android.sdk.AndroidSdkUtils.isAndroidSdkManagerEnabled; import com.android.SdkConstants; import com.android.repository.io.FileOpUtils; import com.android.sdklib.repository.AndroidSdkHandler; import com.android.tools.idea.io.FilePaths; import com.android.tools.idea.sdk.AndroidSdks; import com.android.tools.idea.sdk.IdeSdks; import com.android.tools.idea.sdk.SystemInfoStatsMonitor; import com.android.tools.idea.sdk.install.patch.PatchInstallingRestarter; import com.android.tools.idea.ui.GuiTestingService; import com.android.tools.idea.welcome.config.FirstRunWizardMode; import com.android.tools.idea.welcome.wizard.AndroidStudioWelcomeScreenProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkModificator; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.SystemProperties; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import org.jetbrains.android.sdk.AndroidSdkAdditionalData; import org.jetbrains.android.sdk.AndroidSdkType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; public class AndroidSdkInitializer implements Runnable { private static final Logger LOG = Logger.getInstance(AndroidSdkInitializer.class); // Paths relative to the IDE installation folder where the Android SDK may be present. @NonNls private static final String ANDROID_SDK_FOLDER_NAME = "sdk"; private static final String[] ANDROID_SDK_RELATIVE_PATHS = { ANDROID_SDK_FOLDER_NAME, File.separator + ".." + File.separator + ANDROID_SDK_FOLDER_NAME }; // Default install location from users home dir. @NonNls private static final String ANDROID_SDK_DEFAULT_INSTALL_DIR = (SystemInfo.isWindows ? System.getenv("LOCALAPPDATA") : SystemProperties.getUserHome()) + File.separator + "Android" + File.separator + "Sdk"; @Override public void run() { if (!isAndroidSdkManagerEnabled()) { return; } // If running in a GUI test we don't want the "Select SDK" dialog to show up when running GUI tests. // In unit tests, we only want to set up SDKs which are set up explicitly by the test itself, whereas initialisers // might lead to unexpected SDK leaks because having not set up the SDKs, the test will consequently not release them either. if (GuiTestingService.getInstance().isGuiTestingMode() || ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment()) { // This is good enough. Later on in the GUI test we'll validate the given SDK path. return; } IdeSdks ideSdks = IdeSdks.getInstance(); File androidSdkPath = ideSdks.getAndroidSdkPath(); if (androidSdkPath == null) { try { // Setup JDK and Android SDK if necessary setUpSdks(); androidSdkPath = ideSdks.getAndroidSdkPath(); } catch (Exception e) { LOG.error("Unexpected error while setting up SDKs: ", e); } } if (androidSdkPath != null) { AndroidSdkHandler handler = AndroidSdkHandler.getInstance(androidSdkPath); new PatchInstallingRestarter(handler, FileOpUtils.create()).restartAndInstallIfNecessary(); // We need to start the system info monitoring even in case when user never // runs a single emulator instance: e.g., incompatible hypervisor might be // the reason why emulator is never run, and that's exactly the data // SystemInfoStatsMonitor collects new SystemInfoStatsMonitor().start(); } } private static void setUpSdks() { Sdk sdk = findFirstAndroidSdk(); if (sdk != null) { String sdkHomePath = sdk.getHomePath(); assert sdkHomePath != null; IdeSdks.getInstance().createAndroidSdkPerAndroidTarget(FilePaths.stringToFile(sdkHomePath)); return; } // Called in a 'invokeLater' block, otherwise file chooser will hang forever. ApplicationManager.getApplication().invokeLater(() -> { File androidSdkPath = findOrGetAndroidSdkPath(); if (androidSdkPath == null) { return; } FirstRunWizardMode wizardMode = AndroidStudioWelcomeScreenProvider.getWizardMode(); // Only show "Select SDK" dialog if the "First Run" wizard is not displayed. boolean promptSdkSelection = wizardMode == null; Sdk newSdk = createNewAndroidPlatform(androidSdkPath.getPath(), promptSdkSelection); if (newSdk != null) { // Rename the SDK to fit our default naming convention. String sdkNamePrefix = AndroidSdks.SDK_NAME_PREFIX; if (newSdk.getName().startsWith(sdkNamePrefix)) { SdkModificator sdkModificator = newSdk.getSdkModificator(); sdkModificator.setName(sdkNamePrefix + newSdk.getName().substring(sdkNamePrefix.length())); sdkModificator.commitChanges(); // Rename the JDK that goes along with this SDK. AndroidSdkAdditionalData additionalData = AndroidSdks.getInstance().getAndroidSdkAdditionalData(newSdk); if (additionalData != null) { Sdk jdk = additionalData.getJavaSdk(); if (jdk != null) { sdkModificator = jdk.getSdkModificator(); sdkModificator.setName(DEFAULT_JDK_NAME); sdkModificator.commitChanges(); } } // Fill out any missing build APIs for this new SDK. IdeSdks.getInstance().createAndroidSdkPerAndroidTarget(androidSdkPath); } } }); } @Nullable private static Sdk findFirstAndroidSdk() { List<Sdk> sdks = AndroidSdks.getInstance().getAllAndroidSdks(); return !sdks.isEmpty() ? sdks.get(0) : null; } @Nullable public static File findOrGetAndroidSdkPath() { String studioHome = PathManager.getHomePath(); if (isEmpty(studioHome)) { LOG.info("Unable to find Studio home directory"); } else { LOG.info(String.format("Found Studio home directory at: '%1$s'", studioHome)); for (String path : ANDROID_SDK_RELATIVE_PATHS) { File dir = new File(studioHome, path); String absolutePath = toCanonicalPath(dir.getAbsolutePath()); LOG.info(String.format("Looking for Android SDK at '%1$s'", absolutePath)); if (AndroidSdkType.getInstance().isValidSdkHome(absolutePath)) { LOG.info(String.format("Found Android SDK at '%1$s'", absolutePath)); return new File(absolutePath); } } } LOG.info("Unable to locate SDK within the Android studio installation."); // The order of insertion matters as it defines SDK locations precedence. Map<String, Callable<String>> sdkLocationCandidates = new LinkedHashMap<>(); sdkLocationCandidates.put(SdkConstants.ANDROID_HOME_ENV + " environment variable", () -> System.getenv(SdkConstants.ANDROID_HOME_ENV)); sdkLocationCandidates.put(SdkConstants.ANDROID_SDK_ROOT_ENV + " environment variable", () -> System.getenv(SdkConstants.ANDROID_SDK_ROOT_ENV)); sdkLocationCandidates.put("Last SDK used by Android tools", () -> getLastSdkPathUsedByAndroidTools()); sdkLocationCandidates.put("Default install directory", () -> ANDROID_SDK_DEFAULT_INSTALL_DIR); for (Map.Entry<String, Callable<String>> locationCandidate : sdkLocationCandidates.entrySet()) { try { String pathDescription = locationCandidate.getKey(); String sdkPath = locationCandidate.getValue().call(); String msg; if (!isEmpty(sdkPath) && AndroidSdkType.getInstance().isValidSdkHome(sdkPath)) { msg = String.format("%1$s: '%2$s'", pathDescription, sdkPath); } else { msg = String.format("Examined and not found a valid Android SDK path: %1$s", pathDescription); sdkPath = null; } LOG.info(msg); if (sdkPath != null) { return FilePaths.stringToFile(sdkPath); } } catch (Exception e) { LOG.info("Exception during SDK lookup", e); } } return null; } /** * Returns the value for property 'lastSdkPath' as stored in the properties file at $HOME/.android/ddms.cfg, or {@code null} if the file * or property doesn't exist. * <p> * This is only useful in a scenario where existing users of ADT/Eclipse get Studio, but without the bundle. This method duplicates some * functionality of {@link com.android.prefs.AndroidLocation} since we don't want any file system writes to happen during this process. */ @Nullable private static String getLastSdkPathUsedByAndroidTools() { String userHome = SystemProperties.getUserHome(); if (userHome == null) { return null; } File file = new File(new File(userHome, ".android"), "ddms.cfg"); if (!file.exists()) { return null; } try { Properties properties = getProperties(file); return properties.getProperty("lastSdkPath"); } catch (IOException e) { return null; } } }
3,826
8,805
/*============================================================================= Copyright (c) 2001-2011 <NAME> Copyright (c) 2001-2011 <NAME> http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_QI_CORE #define BOOST_SPIRIT_INCLUDE_QI_CORE #if defined(_MSC_VER) #pragma once #endif #include <boost/spirit/home/qi/parser.hpp> #include <boost/spirit/home/qi/parse.hpp> #include <boost/spirit/home/qi/what.hpp> #include <boost/spirit/home/qi/action.hpp> #include <boost/spirit/home/qi/char.hpp> #include <boost/spirit/home/qi/directive.hpp> #include <boost/spirit/home/qi/nonterminal.hpp> #include <boost/spirit/home/qi/numeric.hpp> #include <boost/spirit/home/qi/operator.hpp> #include <boost/spirit/home/qi/string.hpp> #endif
376
1,350
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.customvision.training.models; import java.util.UUID; import org.joda.time.DateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * result of an image classification request. */ public class StoredImagePrediction { /** * The URI to the (resized) prediction image. */ @JsonProperty(value = "resizedImageUri", access = JsonProperty.Access.WRITE_ONLY) private String resizedImageUri; /** * The URI to the thumbnail of the original prediction image. */ @JsonProperty(value = "thumbnailUri", access = JsonProperty.Access.WRITE_ONLY) private String thumbnailUri; /** * The URI to the original prediction image. */ @JsonProperty(value = "originalImageUri", access = JsonProperty.Access.WRITE_ONLY) private String originalImageUri; /** * Domain used for the prediction. */ @JsonProperty(value = "domain", access = JsonProperty.Access.WRITE_ONLY) private UUID domain; /** * Prediction Id. */ @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) private UUID id; /** * Project Id. */ @JsonProperty(value = "project", access = JsonProperty.Access.WRITE_ONLY) private UUID project; /** * Iteration Id. */ @JsonProperty(value = "iteration", access = JsonProperty.Access.WRITE_ONLY) private UUID iteration; /** * Date this prediction was created. */ @JsonProperty(value = "created", access = JsonProperty.Access.WRITE_ONLY) private DateTime created; /** * List of predictions. */ @JsonProperty(value = "predictions", access = JsonProperty.Access.WRITE_ONLY) private List<Prediction> predictions; /** * Get the resizedImageUri value. * * @return the resizedImageUri value */ public String resizedImageUri() { return this.resizedImageUri; } /** * Get the thumbnailUri value. * * @return the thumbnailUri value */ public String thumbnailUri() { return this.thumbnailUri; } /** * Get the originalImageUri value. * * @return the originalImageUri value */ public String originalImageUri() { return this.originalImageUri; } /** * Get the domain value. * * @return the domain value */ public UUID domain() { return this.domain; } /** * Get the id value. * * @return the id value */ public UUID id() { return this.id; } /** * Get the project value. * * @return the project value */ public UUID project() { return this.project; } /** * Get the iteration value. * * @return the iteration value */ public UUID iteration() { return this.iteration; } /** * Get the created value. * * @return the created value */ public DateTime created() { return this.created; } /** * Get the predictions value. * * @return the predictions value */ public List<Prediction> predictions() { return this.predictions; } }
1,359
437
<gh_stars>100-1000 // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- /*********************************************************************** * * common/kvstore.cc: * Simple versioned key-value store * * Copyright 2015 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************/ #include "store/common/backend/kvstore.h" using namespace std; KVStore::KVStore() { } KVStore::~KVStore() { } bool KVStore::get(const string &key, string &value) { // check for existence of key in store if (store.find(key) == store.end() || store[key].empty()) { return false; } else { value = store[key].back(); return true; } } bool KVStore::put(const string &key, const string &value) { store[key].push_back(value); return true; } /* Delete the latest version of this key. */ bool KVStore::remove(const string &key, string &value) { if (store.find(key) == store.end() || store[key].empty()) { return false; } store[key].pop_back(); return true; }
662
1,279
<gh_stars>1000+ /* * Copyright (c) 2012-2021 <NAME> et al. * License: https://github.com/dbartolini/crown/blob/master/LICENSE */ #include "core/guid.h" #include "core/strings/string_stream.h" #include "core/types.h" #include "world/types.h" #if CROWN_PLATFORM_WINDOWS #undef RELATIVE #undef ABSOLUTE #endif // CROWN_PLATFORM_WINDOWS namespace crown { namespace tool { struct ToolType { enum Enum { PLACE, MOVE, ROTATE, SCALE }; }; struct SnapMode { enum Enum { RELATIVE, ABSOLUTE }; }; struct ReferenceSystem { enum Enum { LOCAL, WORLD }; }; const char* lua_bool(const bool b); void lua_vector2(StringStream& out, const Vector2& v); void lua_vector3(StringStream& out, const Vector3& v); void lua_quaternion(StringStream& out, const Quaternion& q); void device_quit(StringStream& out); void set_mouse_state(StringStream& out, f32 x, f32 y, bool left, bool middle, bool right); void mouse_down(StringStream& out, f32 x, f32 y); void mouse_up(StringStream& out, f32 x, f32 y); void mouse_wheel(StringStream& out, f32 delta); void key_down(StringStream& out, const char* key); void key_up(StringStream& out, const char* key); void set_grid_size(StringStream& out, f32 size); void set_rotation_snap(StringStream& out, f32 degrees); void enable_show_grid(StringStream& out, bool enable); void enable_snap_to_grid(StringStream& out, bool enable); void enable_debug_render_world(StringStream& out, bool enable); void enable_debug_physics_world(StringStream& out, bool enable); void set_tool_type(StringStream& out, const ToolType::Enum tt); void set_snap_mode(StringStream& out, const SnapMode::Enum sm); void set_reference_system(StringStream& out, const ReferenceSystem::Enum rs); void spawn_unit(StringStream& out , const Guid& id , const char* name , const Vector3& pos , const Quaternion& rot , const Vector3& scl ); void spawn_empty_unit(StringStream& /*out*/, Guid& /*id*/); void spawn_sound(StringStream& /*out*/ , const Guid& /*id*/ , const char* /*name*/ , const Vector3& /*pos*/ , const Quaternion& /*rot*/ , const f64 /*vol*/ , const bool /*loop*/ ); void add_tranform_component(StringStream& /*out*/ , const Guid& /*id*/ , const Guid& /*component_id*/ , const Vector3& /*pos*/ , const Quaternion& /*rot*/ , const Vector3& /*scl*/ ); void add_mesh_component(StringStream& /*out*/ , const Guid& /*id*/ , const Guid& /*component_id*/ , const char* /*mesh_resource*/ , const char* /*geometry_name*/ , const char* /*material_resource*/ , const bool /*visible*/ ); void add_material_component(StringStream& /*out*/ , const Guid& /*id*/ , const Guid& /*component_id*/ , const char* /*sprite_resource*/ , const char* /*material_resource*/ , const bool /*visible*/ ); void add_camera_content(StringStream& /*out*/ , const Guid& /*id*/ , const Guid& /*component_id*/ , const ProjectionType::Enum /*projection*/ , const f64 /*fov*/ , const f64 /*far_range*/ , const f64 /*near_range*/ ); void add_light_component(StringStream& /*out*/ , const Guid& /*id*/ , const Guid& /*component_id*/ , const LightType::Enum /*type*/ , const f64 /*range*/ , const f64 /*intensity*/ , const f64 /*spot_angle*/ , const Vector3& /*color*/ ); void move_object(StringStream& /*out*/ , const Guid& /*id*/ , const Vector3& /*pos*/ , const Quaternion& /*rot*/ , const Vector3& /*scl*/ ); void set_light(StringStream& /*out*/ , const Guid& /*id*/ , const LightType::Enum /*type*/ , const f64 /*range*/ , const f64 /*intensity*/ , const f64 /*spot_angle*/ , const Vector3& /*color*/ ); void set_sound_range(StringStream& /*out*/ , const Guid& /*id*/ , f64 /*range*/ ); void set_placeable(StringStream& out , const char* type , const char* name ); void selection_set(StringStream& /*out*/, const Array<Guid>& /*ids*/); void camera_view_perspective(StringStream& out); void camera_view_front(StringStream& out); void camera_view_back(StringStream& out); void camera_view_right(StringStream& out); void camera_view_left(StringStream& out); void camera_view_top(StringStream& out); void camera_view_bottom(StringStream& out); } // namespace tool } // namespace crown
1,522
385
<filename>src/websrv.c /* * WebSrv - Simple, buggy web server * * (c) 2015 <NAME> */ #define _GNU_SOURCE #include <stdio.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <unistd.h> #include <sys/wait.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define PORT 80 #define TIMEOUT 120 #define CRLF "\r\n" #define CRLF2 "\r\n\r\n" #define WEBROOT "webroot/" struct sockaddr_in client; char buf[2048]; ssize_t bufsz; int die(const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); exit(-1); } void wait_for_child(int sig) { while (waitpid(-1, NULL, WNOHANG) > 0); } void handle_alarm(int sig) { puts("Client timed out..."); exit(0); } void http_send(int socket, const char *fmt, ...) { char msg[2048], *pos; va_list args; memset(msg, 0, sizeof(msg)); va_start(args, fmt); vsprintf(msg, fmt, args); va_end(args); send(socket, msg, strlen(msg), 0); } int send_error(int socket, int code, const char* msg) { char* body = "" "<html>\n" " <head>\n" " <title>No.</title>\n" " </head>\n" " <body>\n" " <center><h1>%d %s</h1></center>\n" " <hr><center>Super Secure Web Server v.172.16.58.3</center>\n" " </body>\n" "</html>"; http_send(socket, "HTTP/1.1 %d %s" CRLF, code, msg); http_send(socket, "Content-Type: text/html" CRLF); http_send(socket, "Content-Length: %d" CRLF2, strlen(body) + 3 + strlen(msg) - 4); http_send(socket, body, code, msg); return code; } int handle_led_cmd(int socket, char* cmd) { if (strcmp(cmd, "ledon") == 0) system("./led on"); else system("./led off"); char* body = "OK"; http_send(socket, "HTTP/1.1 200 OK" CRLF); http_send(socket, "Content-Length: %d" CRLF2, strlen(body)); http_send(socket, "%s", body); return 200; } int handle_req(int socket, char* request, size_t len) { FILE* f; long fsize; char buf[2048], *file, *fend; if (memcmp(request, "GET", 3) != 0) { return send_error(socket, 501, "Not Implemented"); } /* * Determine requested file */ file = request + 4; fend = memchr(file, ' ', len-4); if (!fend) return send_error(socket, 400, "Bad Request"); *fend = 0; if (strcmp(file, "/") == 0) file = "index.html"; if (strcmp(file, "/ledon") == 0 || strcmp(file, "/ledoff") == 0) return handle_led_cmd(socket, file+1); printf("%s:%d request for file '%s'\n", inet_ntoa(client.sin_addr), htons(client.sin_port), file); strcpy(buf, WEBROOT); strcat(buf, file); /* * Open file */ f = fopen(buf, "r"); if (!f) return send_error(socket, 404, "Not Found"); fseek(f, 0, SEEK_END); fsize = ftell(f); fseek(f, 0, 0); /* * Send header */ http_send(socket, "HTTP/1.1 200 OK" CRLF); http_send(socket, "Content-Type: text/html" CRLF); http_send(socket, "Content-Length: %d" CRLF2, fsize); /* * Send body */ while ((len = fread(buf, 1, sizeof(buf), f)) > 0) { send(socket, buf, len, 0); } fclose(f); return 200; } int handle_single_request(int socket) { ssize_t len, cntlen; char req[4096]; char *ptr, *pos; /* * Read Header */ ptr = req; while (1) { // we could write directly into 'ptr', but this makes reversing a bit more interesting I guess if (bufsz == 0) { bufsz = recv(socket, buf, sizeof(buf), 0); if (bufsz <= 0) return -1; } memcpy(ptr, buf, bufsz); ptr += bufsz; bufsz = 0; pos = memmem(req, ptr - req, CRLF2, 4); if (pos) { bufsz = ptr - (pos + 4); ptr = pos + 4; memcpy(buf, ptr, bufsz); *ptr = 0; // make it a c string break; } } /* * Read Body */ pos = strcasestr(req, "Content-Length:"); if (pos) { pos += 15; while (isspace(*pos)) pos++; cntlen = atoi(pos); while (cntlen > 0) { if (bufsz == 0) { len = recv(socket, ptr, cntlen, 0); if (len <= 0) return -1; cntlen -= len; ptr += len; } else { len = min(bufsz, cntlen); memcpy(ptr, buf, len); ptr += len; cntlen -= len; bufsz -= len; if (bufsz != 0) { memmove(buf, buf + len, bufsz); } } } } /* * Process Request */ return handle_req(socket, req, ptr - req); } void handle_client(int socket) { int code, reqcount = 0; while (1) { reqcount++; code = handle_single_request(socket); if (code < 0) return; printf("%s:%d request #%d => %d\n", inet_ntoa(client.sin_addr), htons(client.sin_port), reqcount, code); } } int main() { int sockfd, clientfd, pid; unsigned int clilen; struct sockaddr_in serv_addr; struct sigaction sa; /* * Set up the signal handlers */ sa.sa_handler = wait_for_child; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) die("sigaction() failed: %s\n", strerror(errno)); sa.sa_handler = handle_alarm; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGALRM, &sa, NULL) == -1) die("sigaction() failed: %s\n", strerror(errno)); /* * Set up socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) die("socket() failed: %s\n", strerror(errno)); int val = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) == -1) die("setsockopt() failed with %s\n", strerror(errno)); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(PORT); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) die("bind() failed: %s\n", strerror(errno)); if (listen(sockfd, 5) == -1) die("listen() failed: %s\n", strerror(errno)); /* * Server loop */ while (1) { clilen = sizeof(client); clientfd = accept(sockfd, (struct sockaddr*)&client, &clilen); if (clientfd < 0) die("accept() failed: %s\n", strerror(errno)); printf("New connection from %s on port %d\n", inet_ntoa(client.sin_addr), htons(client.sin_port)); pid = fork(); if (pid < 0) { die("fork() failed: %s\n", strerror(errno)); } else if (pid == 0) { /* * TODO: Even though we use CAP_NET_BIND_SERVICE we might still want to drop privs so child can't interfere with parent */ close(sockfd); alarm(TIMEOUT); handle_client(clientfd); printf("%s:%d disconnected\n", inet_ntoa(client.sin_addr), htons(client.sin_port)); close(clientfd); exit(0); } else { close(clientfd); } } return 0; }
3,690
2,094
<filename>libraries/utilities/include/IntegerList.h<gh_stars>1000+ //////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: IntegerList.h (utilities) // Authors: <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <cstddef> #include <vector> namespace ell { namespace utilities { /// <summary> A non-decreasing list of nonegative integers, with a forward Iterator. </summary> class IntegerList { public: /// <summary> Defines an alias representing the vector iterator. </summary> typedef std::vector<size_t>::const_iterator vector_iterator; /// <summary> A read-only forward iterator for the IntegerList. </summary> class Iterator { public: Iterator(const Iterator&) = default; Iterator(Iterator&&) = default; /// <summary> Returns true if the iterator is currently pointing to a valid iterate. </summary> /// /// <returns> true if it succeeds, false if it fails. </returns> bool IsValid() const { return _begin < _end; } /// <summary> Proceeds to the Next iterate. </summary> void Next() { ++_begin; } /// <summary> Returns the value of the current iterate. </summary> /// /// <returns> An size_t. </returns> size_t Get() const { return *_begin; } private: // private ctor, can only be called from IntegerList class. Iterator(const vector_iterator& begin, const vector_iterator& end); friend class IntegerList; // members vector_iterator _begin; vector_iterator _end; }; IntegerList() = default; IntegerList(IntegerList&& other) = default; IntegerList(const IntegerList&) = default; ~IntegerList() = default; void operator=(const IntegerList&) = delete; /// <summary> Gets the number of entries in the list. </summary> /// /// <returns> An size_t. </returns> size_t Size() const { return (size_t)_list.size(); } /// <summary> Allocates a specified number of entires to the list. </summary> /// /// <param name="size"> The size. </param> void Reserve(size_t size); /// <summary> Gets the maximal integer in the list. </summary> /// /// <returns> The maximum value. </returns> size_t Max() const; /// <summary> Appends an integer to the end of the list. </summary> /// /// <param name="value"> The value. </param> void Append(size_t value); /// <summary> Deletes all of the vector content and sets its Size to zero. </summary> void Reset() { _list.resize(0); } /// <summary> Gets Iterator that points to the beginning of the list. </summary> /// /// <returns> The iterator. </returns> Iterator GetIterator() const; private: // The list std::vector<size_t> _list; }; } // namespace utilities } // namespace ell
1,249
377
//===-- ARMEliminatePrologEpilog.cpp ----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the implementation of ARMMachineInstructionRaiser class // for use by llvm-mctoll. // //===----------------------------------------------------------------------===// #include "ARMMachineInstructionRaiser.h" #include "ARMArgumentRaiser.h" #include "ARMCreateJumpTable.h" #include "ARMEliminatePrologEpilog.h" #include "ARMFrameBuilder.h" #include "ARMFunctionPrototype.h" #include "ARMInstructionSplitting.h" #include "ARMMIRevising.h" #include "ARMModuleRaiser.h" #include "ARMSelectionDAGISel.h" using namespace llvm; ARMMachineInstructionRaiser::ARMMachineInstructionRaiser( MachineFunction &machFunc, const ModuleRaiser *mr, MCInstRaiser *mcir) : MachineInstructionRaiser(machFunc, mr, mcir), machRegInfo(MF.getRegInfo()) {} bool ARMMachineInstructionRaiser::raiseMachineFunction() { const ARMModuleRaiser *amr = dyn_cast<ARMModuleRaiser>(MR); assert(amr != nullptr && "The ARM module raiser is not initialized!"); ARMModuleRaiser &rmr = const_cast<ARMModuleRaiser &>(*amr); ARMMIRevising mir(rmr); mir.init(&MF, raisedFunction); mir.setMCInstRaiser(mcInstRaiser); mir.revise(); ARMEliminatePrologEpilog epe(rmr); epe.init(&MF, raisedFunction); epe.eliminate(); ARMCreateJumpTable cjt(rmr); cjt.init(&MF, raisedFunction); cjt.setMCInstRaiser(mcInstRaiser); cjt.create(); cjt.getJTlist(jtList); ARMArgumentRaiser ar(rmr); ar.init(&MF, raisedFunction); ar.raiseArgs(); ARMFrameBuilder fb(rmr); fb.init(&MF, raisedFunction); fb.build(); ARMInstructionSplitting ispl(rmr); ispl.init(&MF, raisedFunction); ispl.split(); ARMSelectionDAGISel sdis(rmr); sdis.init(&MF, raisedFunction); sdis.setjtList(jtList); sdis.doSelection(); return true; } bool ARMMachineInstructionRaiser::raise() { raiseMachineFunction(); return true; } int ARMMachineInstructionRaiser::getArgumentNumber(unsigned PReg) { // NYI assert(false && "Unimplemented ARMMachineInstructionRaiser::getArgumentNumber()"); return -1; } bool ARMMachineInstructionRaiser::buildFuncArgTypeVector( const std::set<MCPhysReg> &PhysRegs, std::vector<Type *> &ArgTyVec) { // NYI assert(false && "Unimplemented ARMMachineInstructionRaiser::buildFuncArgTypeVector()"); return false; } Value *ARMMachineInstructionRaiser::getRegOrArgValue(unsigned PReg, int MBBNo) { assert(false && "Unimplemented ARMMachineInstructionRaiser::getRegOrArgValue()"); return nullptr; } FunctionType *ARMMachineInstructionRaiser::getRaisedFunctionPrototype() { ARMFunctionPrototype AFP; raisedFunction = AFP.discover(MF); Function *ori = const_cast<Function *>(&MF.getFunction()); // Insert the map of raised function to tempFunctionPointer. const_cast<ModuleRaiser *>(MR)->insertPlaceholderRaisedFunctionMap( raisedFunction, ori); return raisedFunction->getFunctionType(); } // Create a new MachineFunctionRaiser object and add it to the list of // MachineFunction raiser objects of this module. MachineFunctionRaiser *ARMModuleRaiser::CreateAndAddMachineFunctionRaiser( Function *f, const ModuleRaiser *mr, uint64_t start, uint64_t end) { MachineFunctionRaiser *mfRaiser = new MachineFunctionRaiser( *M, mr->getMachineModuleInfo()->getOrCreateMachineFunction(*f), mr, start, end); mfRaiser->setMachineInstrRaiser(new ARMMachineInstructionRaiser( mfRaiser->getMachineFunction(), mr, mfRaiser->getMCInstRaiser())); mfRaiserVector.push_back(mfRaiser); return mfRaiser; }
1,336
557
from nose.tools import istest, assert_equal from mammoth.docx.xmlparser import element as xml_element from mammoth.docx.relationships_xml import read_relationships_xml_element @istest def relationship_targets_can_be_found_by_id(): element = xml_element("relationships:Relationships", {}, [ xml_element("relationships:Relationship", { "Id": "rId8", "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "Target": "http://example.com", }), xml_element("relationships:Relationship", { "Id": "rId2", "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "Target": "http://example.net", }), ]) relationships = read_relationships_xml_element(element) assert_equal( "http://example.com", relationships.find_target_by_relationship_id("rId8"), ) @istest def relationship_targets_can_be_found_by_type(): element = xml_element("relationships:Relationships", {}, [ xml_element("relationships:Relationship", { "Id": "rId2", "Target": "docProps/core.xml", "Type": "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", }), xml_element("relationships:Relationship", { "Id": "rId1", "Target": "word/document.xml", "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", }), xml_element("relationships:Relationship", { "Id": "rId3", "Target": "word/document2.xml", "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", }), ]) relationships = read_relationships_xml_element(element) assert_equal( ["word/document.xml", "word/document2.xml"], relationships.find_targets_by_type("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"), ) @istest def when_there_are_no_relationships_of_requested_type_then_empty_list_is_returned(): element = xml_element("relationships:Relationships", {}, []) relationships = read_relationships_xml_element(element) assert_equal( [], relationships.find_targets_by_type("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"), )
1,009
764
<reponame>dchain01/token-profile { "symbol": "SCDS", "address": "0xb72c794effb775197287d767cA80C22ae9094cB5", "overview": { "en": "SCDS is a distributed private cloud storage ecological application encryption digital asset of shine cloud blockchain. Users share cloud storage space. It aims to build a new blockchain storage system based on the SSP agreement, which takes blockchain encryption technology as the core, solves the decentralized storage of private files such as individual users, enterprises and institutions.", "zh": "SCDS是Shine Cloud区块链分布式私有云存储生态应用加密数字资产,由用户共享云存储空间,旨在构建以区块链加密技术为核心,解决个人用户、企业、机构等私密文件去中心化存储,首创“SSP”协议基础上搭建的全新区块链存储系统。" }, "email": "<EMAIL>", "website": "http://www.thescds.com", "whitepaper": "https://res.thescds.com/cn.pdf", "links": { "金色财经": "https://m.jinse.com/lives/125719.htm" } }
476
2,023
<filename>recipes/Python/442459_Email_pretty_tracebacks_yourself_or_someone_you_/recipe-442459.py # --------------------------------------------------------------- def createMail(sender, recipient, subject, html, text): ''' A slightly modified version of Recipe #67083, included here for completeness ''' import MimeWriter, mimetools, cStringIO out = cStringIO.StringIO() htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) writer.addheader("From", sender) writer.addheader("To", recipient) writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") writer.startmultipartbody("alternative") writer.flushheaders() subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() writer.lastpart() msg = out.getvalue() out.close() return msg # --------------------------------------------------------------- def sendMail(sender, recipient, subject, html, text): import smtplib message = createMail(sender, recipient, subject, html, text) server = smtplib.SMTP("localhost") server.sendmail(sender, recipient, message) server.quit() # --------------------------------------------------------------- def main(): ''' the main body of your program ''' print x # will raise an exception # --------------------------------------------------------------- if __name__ == '__main__': try: main() except: import sys, cgitb sendMail('<EMAIL>', '<EMAIL>', 'Error on yourdomain.com', cgitb.html(sys.exc_info()), cgitb.text(sys.exc_info())) # handle the error gracefully, perhaps doing a # http redirect if this is a cgi application or # otherwise letting the user know something happened # but that, hey, you are all over it
871
622
""" Example code to sort sequences. """ import random # Easily create a list of numbers data = list(range(10)) print("range data:", data) # Randomly shuffle those numbers random.shuffle(data) print("shuffled data:", data) # Sort the list of numbers data.sort() print("sorted data:", data) # Shuffle it again random.shuffle(data) print("shuffled data:", data) # Use sorted to sort the list newdata = sorted(data) print("data after sorted:", data) print("returned from sorted:", newdata) # Convert to a tuple datatup = tuple(data) print("data tuple:", datatup) # Sort the tuple of numbers # datatup.sort() print("tuple after sort:", datatup) # Use sorted to sort the tuple newdatatup = sorted(datatup) print("returned from sorted:", newdatatup) # Create a dictionary of squares (dictionary comprehension) datamap = {key: key ** 2 for key in datatup} print("data dictionary:", datamap) # Use sorted to sort the dictionary sortmap = sorted(datamap) print("returned from sorted:", sortmap)
322
402
<filename>allennlp_models/modelcards/generation-bart.json { "id": "generation-bart", "registered_model_name": "bart", "registered_predictor_name": null, "display_name": "BART", "model_details": { "description": "The BART model here uses a language modeling head, and therefore can be used for generation. The BART encoder, implemented as a `Seq2SeqEncoder`, which assumes it operates on already embedded inputs. This means that we remove the token and position embeddings from BART in this module. For the typical use case of using BART to encode inputs to your model (where we include the token and position embeddings from BART), you should use `PretrainedTransformerEmbedder(bart_model_name, sub_module=\"encoder\")` instead of this.", "short_description": "BART with a language model head for generation.", "developed_by": "Lewis et al", "contributed_by": "<NAME>", "date": "2020-07-25", "version": "1", "model_type": "BART", "paper": { "citation": "\n@inproceedings{Lewis2020BARTDS,\ntitle={BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension},\nauthor={<NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>},\nbooktitle={ACL},\nyear={2020}}\n", "title": "BART: Denosing Sequence-to-Sequence Pre-training for Natural Language Generation,Translation, and Comprehension", "url": "https://api.semanticscholar.org/CorpusID:204960716" }, "license": null, "contact": "<EMAIL>" }, "intended_use": { "primary_uses": null, "primary_users": null, "out_of_scope_use_cases": null }, "factors": { "relevant_factors": null, "evaluation_factors": null }, "metrics": { "model_performance_measures": "ROUGE and BLEU", "decision_thresholds": null, "variation_approaches": null }, "evaluation_data": { "dataset": { "name": "CNN/DailyMail", "url": "https://github.com/abisee/cnn-dailymail", "notes": "Please download the data from the url provided." }, "motivation": null, "preprocessing": null }, "training_data": { "dataset": { "name": "CNN/DailyMail", "url": "https://github.com/abisee/cnn-dailymail", "notes": "Please download the data from the url provided." }, "motivation": null, "preprocessing": null }, "quantitative_analyses": { "unitary_results": null, "intersectional_results": null }, "model_caveats_and_recommendations": { "caveats_and_recommendations": null }, "model_ethical_considerations": { "ethical_considerations": null }, "model_usage": { "archive_file": "bart-2020.07.25.tar.gz", "training_config": "generation/bart_cnn_dm.jsonnet", "install_instructions": "pip install allennlp==1.0.0 allennlp-models==1.0.0" } }
1,278
1,233
/* * Copyright 2017 <NAME> * * 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.zhuinden.simplestack; import java.util.List; /** * Represents the state that will be available once state change is complete. */ class PendingStateChange { enum Status { ENQUEUED, IN_PROGRESS, COMPLETED } final List<?> newHistory; final int direction; final boolean initialization; final boolean isTerminal; final boolean isForceEnqueued; private Status status = Status.ENQUEUED; StateChanger.Callback completionCallback; boolean didForceExecute = false; PendingStateChange(List<?> newHistory, @StateChange.StateChangeDirection int direction, boolean initialization, boolean isTerminal, boolean isForceEnqueued) { this.newHistory = newHistory; this.direction = direction; this.initialization = initialization; this.isTerminal = isTerminal; this.isForceEnqueued = isForceEnqueued; } Status getStatus() { return status; } void setStatus(Status status) { if(status == null) { throw new NullPointerException("Status of pending state change cannot be null!"); } if(status.ordinal() < this.status.ordinal()) { throw new IllegalStateException("A pending state change cannot go to one of its previous states: [" + this.status + "] to [" + status + "]"); } this.status = status; } }
666
2,151
<reponame>zipated/src // Copyright (c) 2011 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 "chrome/browser/printing/printer_manager_dialog.h" #include <windows.h> #include <shellapi.h> #include "base/bind.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread.h" namespace { // A helper callback that opens the printer management dialog. void OpenPrintersDialogCallback() { base::FilePath sys_dir; base::PathService::Get(base::DIR_SYSTEM, &sys_dir); base::FilePath rundll32 = sys_dir.Append(L"rundll32.exe"); base::FilePath shell32dll = sys_dir.Append(L"shell32.dll"); std::wstring args(shell32dll.value()); args.append(L",SHHelpShortcuts_RunDLL PrintersFolder"); ShellExecute(nullptr, L"open", rundll32.value().c_str(), args.c_str(), nullptr, SW_SHOWNORMAL); } } // namespace namespace printing { void PrinterManagerDialog::ShowPrinterManagerDialog() { base::PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::Bind(OpenPrintersDialogCallback)); } } // namespace printing
453
403
package com.camunda.consulting.bpmn_db_exporter; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DbExporter { public static final String TARGET_DIR = "target" + File.separator + "export-prod" + File.separator; public static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String DB_URL = "YOUR_JDBC_URL"; public static final String USERNAME = "YOUR_USERNAME"; public static final String PASSWORD = "<PASSWORD>"; public static void main( String[] args ) { new File(TARGET_DIR).mkdirs(); Connection conn = null; Statement statement = null; System.out.println("Connecting to DB ..."); try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); statement = conn.createStatement(); String sql = "select ACT_RE_PROCDEF.ID_ as PROCDEF_ID, ACT_GE_BYTEARRAY.ID_ as BYTEARRAY_ID, ACT_GE_BYTEARRAY.BYTES_ "+ "from ACT_GE_BYTEARRAY join ACT_RE_PROCDEF on ACT_RE_PROCDEF.DEPLOYMENT_ID_= ACT_GE_BYTEARRAY.DEPLOYMENT_ID_ and ACT_RE_PROCDEF.RESOURCE_NAME_ = ACT_GE_BYTEARRAY.NAME_ "+ "where ACT_GE_BYTEARRAY.NAME_ LIKE '%.bpmn'"; ResultSet rs = statement.executeQuery(sql); while(rs.next()) { Path file = Paths.get(TARGET_DIR + rs.getString("PROCDEF_ID").replaceAll(":", "#") + "#" + rs.getString("BYTEARRAY_ID") + ".bpmn"); Files.write(file, rs.getBytes("BYTES_"),StandardOpenOption.CREATE_NEW); } rs.close(); }catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Disconnecting from DB ..."); if(statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } System.out.println("Goodbye"); } }
1,126
405
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tflib.ops.layers import *
38
4,002
package me.zeroX150.cornos.features.command.impl; import me.zeroX150.cornos.Cornos; import me.zeroX150.cornos.etc.helper.STL; import me.zeroX150.cornos.features.command.Command; import me.zeroX150.cornos.gui.screen.DocsScreen; public class Help extends Command { public Help() { super("Help", "Shows all commands and modules", new String[]{"h", "help", "man", "?", "commands", "modules"}); } @Override public void onExecute(String[] args) { new Thread(() -> { STL.sleep(10); Cornos.minecraft.openScreen(new DocsScreen(true)); }).start(); super.onExecute(args); } }
265
777
// Copyright 2016 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 "components/data_reduction_proxy/core/common/data_reduction_proxy_server.h" namespace data_reduction_proxy { DataReductionProxyServer::DataReductionProxyServer( const net::ProxyServer& proxy_server, ProxyServer_ProxyType proxy_type) : proxy_server_(proxy_server), proxy_type_(proxy_type) {} bool DataReductionProxyServer::operator==( const DataReductionProxyServer& other) const { return proxy_server_ == other.proxy_server_ && proxy_type_ == other.proxy_type_; } // static std::vector<net::ProxyServer> DataReductionProxyServer::ConvertToNetProxyServers( const std::vector<DataReductionProxyServer>& data_reduction_proxy_servers) { std::vector<net::ProxyServer> net_proxy_servers; for (auto data_reduction_proxy_server : data_reduction_proxy_servers) net_proxy_servers.push_back(data_reduction_proxy_server.proxy_server()); return net_proxy_servers; } ProxyServer_ProxyType DataReductionProxyServer::GetProxyTypeForTesting() const { return proxy_type_; } } // namespace data_reduction_proxy
391