max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,738
/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/detail/plane.hpp * * 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. */ #pragma once #ifndef EOS_RENDER_DETAIL_PLANE_HPP #define EOS_RENDER_DETAIL_PLANE_HPP #include "glm/glm.hpp" #include <cmath> /** * The detail namespace contains implementations of internal functions, not part of the API we expose and not * meant to be used by a user. */ namespace eos { namespace render { namespace detail { class plane { public: plane() {} plane(float a, float b, float c, float d) { this->a = a; this->b = b; this->c = c; this->d = d; } plane(const glm::vec3& normal, float d = 0.0f) { this->a = normal[0]; this->b = normal[1]; this->c = normal[2]; this->d = d; } plane(const glm::vec3& point, const glm::vec3& normal) { a = normal[0]; b = normal[1]; c = normal[2]; d = -glm::dot(point, normal); } template <typename T, glm::precision P = glm::defaultp> plane(const glm::tvec3<T, P>& point1, const glm::tvec3<T, P>& point2, const glm::tvec3<T, P>& point3) { const glm::tvec3<T, P> v1 = point2 - point1; const glm::tvec3<T, P> v2 = point3 - point1; glm::tvec3<T, P> normal = glm::cross(v1, v2); normal = glm::normalize(normal); a = normal[0]; b = normal[1]; c = normal[2]; d = -glm::dot(point1, normal); } void normalize() { const float length = std::sqrt(a * a + b * b + c * c); a /= length; b /= length; c /= length; } float getSignedDistanceFromPoint(const glm::vec3& point) const { return a * point[0] + b * point[1] + c * point[2] + d; } float getSignedDistanceFromPoint(const glm::vec4& point) const { return a * point[0] + b * point[1] + c * point[2] + d; } public: float a, b, c; float d; }; } /* namespace detail */ } /* namespace render */ } /* namespace eos */ #endif /* EOS_RENDER_DETAIL_PLANE_HPP */
1,142
930
package com.zone.weixin4j.util; import java.io.Serializable; /** * aes & token * * @className AesToken * @author jinyu(<EMAIL>) * @date 2015年5月6日 * @since JDK 1.6 * @see */ public class AesToken implements Serializable { private static final long serialVersionUID = -6001008896414323534L; /** * 账号ID(原始id/appid/corpid) */ private String weixinId; /** * 开发者的token */ private String token; /** * 安全模式下的加密密钥 */ private String aesKey; /** * 一般为明文模式 * * @param token * 开发者的Token */ public AesToken(String token) { this(null, token, null); } /** * 一般为AES加密模式 * * @param weixinId * 公众号的应用ID(原始id/appid/corpid) * @param token * 开发者Token * @param aesKey * 解密的EncodingAESKey */ public AesToken(String weixinId, String token, String aesKey) { this.weixinId = weixinId; this.token = token; this.aesKey = aesKey; } public String getWeixinId() { return weixinId; } public String getToken() { return token; } public String getAesKey() { return aesKey; } @Override public String toString() { return "AesToken [weixinId=" + weixinId + ", token=" + token + ", aesKey=" + aesKey + "]"; } }
614
2,338
<reponame>acidburn0zzz/llvm-project // RUN: %clang_cc1 -triple spir64 -aux-triple x86_64-unknown-linux-gnu \ // RUN: -fsycl-is-device -verify -fsyntax-only %s typedef __uint128_t BIGTY; template <class T> class Z { public: // expected-note@+1 {{'field' defined here}} T field; // expected-note@+1 2{{'field1' defined here}} __int128 field1; using BIGTYPE = __int128; // expected-note@+1 {{'bigfield' defined here}} BIGTYPE bigfield; }; void host_ok(void) { __int128 A; int B = sizeof(__int128); Z<__int128> C; C.field1 = A; } void usage() { // expected-note@+1 3{{'A' defined here}} __int128 A; Z<__int128> C; // expected-error@+2 {{'A' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} // expected-error@+1 {{'field1' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} C.field1 = A; // expected-error@+1 {{'bigfield' requires 128 bit size 'Z::BIGTYPE' (aka '__int128') type support, but device 'spir64' does not support it}} C.bigfield += 1.0; // expected-error@+1 {{'A' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} auto foo1 = [=]() { __int128 AA; // expected-note@+2 {{'BB' defined here}} // expected-error@+1 {{'A' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} auto BB = A; // expected-error@+1 {{'BB' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} BB += 1; }; // expected-note@+1 {{called by 'usage'}} foo1(); } template <typename t> void foo2(){}; // expected-note@+3 {{'P' defined here}} // expected-error@+2 {{'P' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} // expected-note@+1 2{{'foo' defined here}} __int128 foo(__int128 P) { return P; } void foobar() { // expected-note@+1 {{'operator __int128' defined here}} struct X { operator __int128() const; } x; bool a = false; // expected-error@+1 {{'operator __int128' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} a = x == __int128(0); } template <typename Name, typename Func> __attribute__((sycl_kernel)) void kernel(Func kernelFunc) { // expected-note@+1 6{{called by 'kernel}} kernelFunc(); } int main() { // expected-note@+1 {{'CapturedToDevice' defined here}} __int128 CapturedToDevice = 1; host_ok(); kernel<class variables>([=]() { decltype(CapturedToDevice) D; // expected-error@+1 {{'CapturedToDevice' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} auto C = CapturedToDevice; Z<__int128> S; // expected-error@+1 {{'field1' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} S.field1 += 1; // expected-error@+1 {{'field' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} S.field = 1; }); kernel<class functions>([=]() { // expected-note@+1 2{{called by 'operator()'}} usage(); // expected-note@+1 {{'BBBB' defined here}} BIGTY BBBB; // expected-error@+3 {{'BBBB' requires 128 bit size 'BIGTY' (aka 'unsigned __int128') type support, but device 'spir64' does not support it}} // expected-error@+2 2{{'foo' requires 128 bit size '__int128' type support, but device 'spir64' does not support it}} // expected-note@+1 1{{called by 'operator()'}} auto A = foo(BBBB); // expected-note@+1 {{called by 'operator()'}} foobar(); }); kernel<class ok>([=]() { Z<__int128> S; foo2<__int128>(); auto A = sizeof(CapturedToDevice); }); return 0; } // no error expected BIGTY zoo(BIGTY h) { h = 1; return h; } namespace PR12964 { struct X { operator __int128() const; } x; bool a = x == __int128(0); }
1,436
7,737
/** * This file is part of the Zephir. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. If you did not receive * a copy of the license it is available through the world-wide-web at the * following url: https://docs.zephir-lang.com/en/latest/license */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ext.h" #include "php_main.h" #include "ext/standard/php_string.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/operators.h" #include "Zend/zend_exceptions.h" /** * Throws a zval object as exception */ void zephir_throw_exception_debug(zval *object, const char *file, uint32_t line) { zend_class_entry *default_exception_ce; zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL; int ZEPHIR_LAST_CALL_STATUS = 0; zval curline; zval object_copy; ZVAL_UNDEF(&curline); ZEPHIR_MM_GROW(); if (Z_TYPE_P(object) != IS_OBJECT) { ZVAL_COPY_VALUE(&object_copy, object); object_init_ex(object, zend_exception_get_default()); ZEPHIR_CALL_METHOD(NULL, object, "__construct", NULL, 0, &object_copy); zval_ptr_dtor(&object_copy); } Z_ADDREF_P(object); if (line > 0) { ZEPHIR_CALL_METHOD(&curline, object, "getline", NULL, 0); zephir_check_call_status(); if (ZEPHIR_IS_LONG(&curline, 0)) { default_exception_ce = zend_exception_get_default(); #if PHP_VERSION_ID >= 80000 zend_update_property_string(default_exception_ce, Z_OBJ_P(object), SL("file"), file); zend_update_property_long(default_exception_ce, Z_OBJ_P(object), SL("line"), line); #else zend_update_property_string(default_exception_ce, object, SL("file"), file); zend_update_property_long(default_exception_ce, object, SL("line"), line); #endif } } if (ZEPHIR_LAST_CALL_STATUS != FAILURE) { zend_throw_exception_object(object); } ZEPHIR_MM_RESTORE(); } /** * Throws an exception with a single string parameter + debug info */ void zephir_throw_exception_string_debug(zend_class_entry *ce, const char *message, uint32_t message_len, const char *file, uint32_t line) { zval object, msg; int ZEPHIR_LAST_CALL_STATUS = 0; zend_class_entry *default_exception_ce; object_init_ex(&object, ce); ZVAL_STRINGL(&msg, message, message_len); ZEPHIR_CALL_METHOD_WITHOUT_OBSERVE(NULL, &object, "__construct", NULL, 0, &msg); if (line > 0) { default_exception_ce = zend_exception_get_default(); #if PHP_VERSION_ID >= 80000 zend_update_property_string(default_exception_ce, Z_OBJ(object), "file", sizeof("file")-1, file); zend_update_property_long(default_exception_ce, Z_OBJ(object), "line", sizeof("line")-1, line); #else zend_update_property_string(default_exception_ce, &object, "file", sizeof("file")-1, file); zend_update_property_long(default_exception_ce, &object, "line", sizeof("line")-1, line); #endif } if (ZEPHIR_LAST_CALL_STATUS != FAILURE) { zend_throw_exception_object(&object); } zval_ptr_dtor(&msg); } /** * Throws an exception with a single string parameter */ void zephir_throw_exception_string(zend_class_entry *ce, const char *message, uint32_t message_len) { zval object, msg; int ZEPHIR_LAST_CALL_STATUS = 0; object_init_ex(&object, ce); ZVAL_STRINGL(&msg, message, message_len); ZEPHIR_CALL_METHOD_WITHOUT_OBSERVE(NULL, &object, "__construct", NULL, 0, &msg); if (ZEPHIR_LAST_CALL_STATUS != FAILURE) { zend_throw_exception_object(&object); } zval_ptr_dtor(&msg); } /** * Throws an exception with a string format as parameter */ void zephir_throw_exception_format(zend_class_entry *ce, const char *format, ...) { zval object, msg; int ZEPHIR_LAST_CALL_STATUS = 0, len; char *buffer; va_list args; object_init_ex(&object, ce); va_start(args, format); len = vspprintf(&buffer, 0, format, args); va_end(args); ZVAL_STRINGL(&msg, buffer, len); efree(buffer); ZEPHIR_CALL_METHOD_WITHOUT_OBSERVE(NULL, &object, "__construct", NULL, 0, &msg); if (ZEPHIR_LAST_CALL_STATUS != FAILURE) { zend_throw_exception_object(&object); } zval_ptr_dtor(&msg); }
1,667
5,169
<reponame>Gantios/Specs<gh_stars>1000+ { "name": "Azetone", "version": "5.0.1", "summary": "Azetone UX Analytics, A/B Testing and Personalization for iOS", "description": "Azetone: Next generation Mobile UX Analytics, A/B Testing and Personalization\nWhat makes Azetone so unique? Because it is built from the ground-up for Mobile Apps, we chose the best architecture possible, we build on the latest mobile technologies for best performance and reliability and we tightly integrate with your key third party mobile and CRM solutions.\nThe result? A world-class Mobile UX Analytics, A/B Testing and Personalization solution that:\n- Leverages our integrated UX Analytics, delivering unique insights on how user interact with your App and pointing at where to setup your A/B tests\n- Offers marketers the easiest solution to make visual changes in your App in real time with no code tinkering and no App Store re-submission\n- Gives advanced users and developers the ability to go deep into the App and activate or deactivate code blocks or entire features of an App.\n- Delivers the best conversion improvements by leveraging existing customer segments from your CRM or Push Notification platforms\n- Provides breakthrough personalization capabilities to transform your static native code into a dynamic App that instantly adapts your entire user experience based on user context and profile.", "homepage": "http://www.azetone.com", "screenshots": [ "https://www.azetone.com/wp-content/img/abtesting/azetone-abtesting.png", "https://www.azetone.com/wp-content/img/heatmaps/profile-user-mobile-heatmaps.png" ], "license": { "type": "Commercial", "text": "Azetone: Copyright 2016 Azetone. All Rights Reserved. Use of this software is subject to the terms and conditions of the Azetone Software and Services Agreement located at http://www.azetone.com/azetone-terms-of-service.html" }, "authors": { "Azetone": "<EMAIL>" }, "social_media_url": "https://twitter.com/azetonemobile", "documentation_url": "http://docs.azetone.com/index", "platforms": { "ios": "8.0" }, "requires_arc": true, "libraries": "sqlite3", "source": { "git": "https://github.com/azetone/ios_sdk_pod.git", "tag": "5.0.1" }, "vendored_frameworks": "Azetone/Azetone.framework" }
675
651
<filename>prov/src/main/java/org/spongycastle/jcajce/provider/util/AsymmetricAlgorithmProvider.java package org.spongycastle.jcajce.provider.util; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.jcajce.provider.config.ConfigurableProvider; public abstract class AsymmetricAlgorithmProvider extends AlgorithmProvider { protected void addSignatureAlgorithm( ConfigurableProvider provider, String digest, String algorithm, String className, ASN1ObjectIdentifier oid) { String mainName = digest + "WITH" + algorithm; String jdk11Variation1 = digest + "with" + algorithm; String jdk11Variation2 = digest + "With" + algorithm; String alias = digest + "/" + algorithm; provider.addAlgorithm("Signature." + mainName, className); provider.addAlgorithm("Alg.Alias.Signature." + jdk11Variation1, mainName); provider.addAlgorithm("Alg.Alias.Signature." + jdk11Variation2, mainName); provider.addAlgorithm("Alg.Alias.Signature." + alias, mainName); provider.addAlgorithm("Alg.Alias.Signature." + oid, mainName); provider.addAlgorithm("Alg.Alias.Signature.OID." + oid, mainName); } protected void registerOid(ConfigurableProvider provider, ASN1ObjectIdentifier oid, String name, AsymmetricKeyInfoConverter keyFactory) { provider.addAlgorithm("Alg.Alias.KeyFactory." + oid, name); provider.addAlgorithm("Alg.Alias.KeyPairGenerator." + oid, name); provider.addKeyInfoConverter(oid, keyFactory); } protected void registerOidAlgorithmParameters(ConfigurableProvider provider, ASN1ObjectIdentifier oid, String name) { provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + oid, name); } protected void registerOidAlgorithmParameterGenerator(ConfigurableProvider provider, ASN1ObjectIdentifier oid, String name) { provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + oid, name); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + oid, name); } }
779
330
import os import pathlib import glob pybamm_data = [] for file_ext in ["*.csv", "*.py", "*.md"]: # Get all the files ending in file_ext in pybamm/input dir. # list_of_files = [ # 'pybamm/input/drive_cycles/car_current.csv', # 'pybamm/input/drive_cycles/US06.csv', # ... list_of_files = glob.glob("pybamm/input/**/" + file_ext, recursive=True) # Add these files to pybamm_data. # The path must be relative to the package dir (pybamm/), so # must process the content of list_of_files to take out the top # pybamm/ dir, i.e.: # ['input/drive_cycles/car_current.csv', # 'input/drive_cycles/US06.csv', # ... pybamm_data.extend( [os.path.join(*pathlib.Path(filename).parts[1:]) for filename in list_of_files] ) pybamm_data.append("./version") pybamm_data.append("./CITATIONS.txt") with open("MANIFEST.in", "w") as manifest: for data_file in pybamm_data: manifest.write(data_file + "\n")
406
448
<reponame>vlro/terracotta import pytest from click.testing import CliRunner @pytest.fixture(scope='session') def toml_file(tmpdir_factory): content = """ DEFAULT_TILE_SIZE = [64, 64] """ outfile = tmpdir_factory.mktemp('config').join('tc-config.toml') with open(outfile, 'w') as f: f.write(content) return outfile def test_serve_from_pattern(raster_file): from terracotta.scripts import cli input_pattern = str(raster_file.dirpath('{name}.tif')) runner = CliRunner() result = runner.invoke(cli.cli, ['serve', '-r', input_pattern]) assert result.exit_code == 0 def test_serve_from_database(testdb): from terracotta.scripts import cli runner = CliRunner() result = runner.invoke(cli.cli, ['serve', '-d', str(testdb)]) assert result.exit_code == 0 def test_serve_no_args(testdb): from terracotta.scripts import cli runner = CliRunner() result = runner.invoke(cli.cli, ['serve']) assert result.exit_code != 0 def test_serve_with_config(testdb, toml_file): from terracotta.scripts import cli runner = CliRunner() result = runner.invoke(cli.cli, ['--config', str(toml_file), 'serve', '-d', str(testdb)]) assert result.exit_code == 0 def test_serve_rgb_key(raster_file): from terracotta.scripts import cli input_pattern = str(raster_file.dirpath('{rgb}m{foo}.tif')) runner = CliRunner() result = runner.invoke( cli.cli, ['serve', '-r', input_pattern, '--rgb-key', 'rgb'] ) assert result.exit_code == 0 def test_serve_invalid_rgb_key(raster_file): from terracotta.scripts import cli input_pattern = str(raster_file.dirpath('{rgb}m{foo}.tif')) runner = CliRunner() result = runner.invoke( cli.cli, ['serve', '-r', input_pattern, '--rgb-key', 'bar'] ) assert result.exit_code != 0 def test_serve_find_socket(raster_file): import socket from contextlib import closing from terracotta.scripts import cli input_pattern = str(raster_file.dirpath('{name}.tif')) host = '127.0.0.1' port = 5000 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind((host, port)) runner = CliRunner() result = runner.invoke( cli.cli, ['serve', '-r', input_pattern, '--port', '5000'] ) assert result.exit_code != 0 assert 'Could not find open port to bind to' in result.output runner = CliRunner() result = runner.invoke(cli.cli, ['serve', '-r', input_pattern]) assert result.exit_code == 0
1,101
471
<filename>examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/include/wx/cocoa/evtloop.h /////////////////////////////////////////////////////////////////////////////// // Name: wx/cocoa/evtloop.h // Purpose: declaration of wxGUIEventLoop for wxCocoa // Author: <NAME> // Created: 2008-12-28 // Copyright: (c) 2008 <NAME> <<EMAIL>> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_COCOA_EVTLOOP_H_ #define _WX_COCOA_EVTLOOP_H_ // ---------------------------------------------------------------------------- // wxGUIEventLoop for wxCocoa // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxGUIEventLoop : public wxEventLoopBase { public: wxGUIEventLoop() { m_exitcode = 0; } virtual void ScheduleExit(int rc = 0); virtual bool Pending() const; virtual bool Dispatch(); virtual int DispatchTimeout(unsigned long timeout); virtual void WakeUp() { } virtual bool YieldFor(long eventsToProcess); protected: virtual int DoRun(); int m_exitcode; wxDECLARE_NO_COPY_CLASS(wxGUIEventLoop); }; #endif // _WX_COCOA_EVTLOOP_H_
402
2,769
<gh_stars>1000+ { "AutoDeployParam": { "Description": "Don't change this unless you forked your own copy of the repos. And want to have auto deployment for changes in code that you made in your repos. If you set Yes, then the CodePipeline setup will get a Webhook resource, otherwise skipped, since you don't have access to our repos, and can't add a web hook entry in our repos.", "Type": "String", "AllowedValues" : ["No", "Yes"], "Default": "No" } }
143
2,329
<reponame>alimate/spring-loaded<gh_stars>1000+ package basic; public interface DefaultMethodsI2A { }
35
310
{ "name": "TrueCraft", "description": "An implementation of a MineCraft client.", "url": "https://github.com/ddevault/TrueCraft" }
46
1,685
# -*- coding: utf-8 -*- # Copyright (c) 2015, <NAME>, <NAME> # Licensed under the BSD 3-clause license (see LICENSE.txt) """ Classes in this module enhance several stationary covariance functions with the Stochastic Differential Equation (SDE) functionality. """ from .rbf import RBF from .stationary import Exponential from .stationary import RatQuad import numpy as np import scipy as sp try: from scipy.linalg import solve_continuous_lyapunov as lyap except ImportError: from scipy.linalg import solve_lyapunov as lyap import warnings class sde_RBF(RBF): """ Class provide extra functionality to transfer this covariance function into SDE form. Radial Basis Function kernel: .. math:: k(r) = \sigma^2 \exp \\bigg(- \\frac{1}{2} r^2 \\bigg) \\ \\ \\ \\ \text{ where } r = \sqrt{\sum_{i=1}^{input dim} \frac{(x_i-y_i)^2}{\ell_i^2} } """ def __init__(self, *args, **kwargs): """ Init constructior. Two optinal extra parameters are added in addition to the ones in RBF kernel. :param approx_order: approximation order for the RBF covariance. (Default 10) :type approx_order: int :param balance: Whether to balance this kernel separately. (Defaulf True). Model has a separate parameter for balancing. :type balance: bool """ if 'balance' in kwargs: self.balance = bool( kwargs.get('balance') ) del kwargs['balance'] else: self.balance = True if 'approx_order' in kwargs: self.approx_order = kwargs.get('approx_order') del kwargs['approx_order'] else: self.approx_order = 6 super(sde_RBF, self).__init__(*args, **kwargs) def sde_update_gradient_full(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ self.variance.gradient = gradients[0] self.lengthscale.gradient = gradients[1] def sde(self): """ Return the state space representation of the covariance. Note! For Sparse GP inference too small or two high values of lengthscale lead to instabilities. This is because Qc are too high or too low and P_inf are not full rank. This effect depends on approximatio order. For N = 10. lengthscale must be in (0.8,8). For other N tests must be conducted. N=6: (0.06,31) Variance should be within reasonable bounds as well, but its dependence is linear. The above facts do not take into accout regularization. """ #import pdb; pdb.set_trace() if self.approx_order is not None: N = self.approx_order else: N = 10# approximation order ( number of terms in exponent series expansion) roots_rounding_decimals = 6 fn = np.math.factorial(N) p_lengthscale = float( self.lengthscale ) p_variance = float(self.variance) kappa = 1.0/2.0/p_lengthscale**2 Qc = np.array( ((p_variance*np.sqrt(np.pi/kappa)*fn*(4*kappa)**N,),) ) eps = 1e-12 if (float(Qc) > 1.0/eps) or (float(Qc) < eps): warnings.warn("""sde_RBF kernel: the noise variance Qc is either very large or very small. It influece conditioning of P_inf: {0:e}""".format(float(Qc)) ) pp1 = np.zeros((2*N+1,)) # array of polynomial coefficients from higher power to lower for n in range(0, N+1): # (2N+1) - number of polynomial coefficients pp1[2*(N-n)] = fn*(4.0*kappa)**(N-n)/np.math.factorial(n)*(-1)**n pp = sp.poly1d(pp1) roots = sp.roots(pp) neg_real_part_roots = roots[np.round(np.real(roots) ,roots_rounding_decimals) < 0] aa = sp.poly1d(neg_real_part_roots, r=True).coeffs F = np.diag(np.ones((N-1,)),1) F[-1,:] = -aa[-1:0:-1] L= np.zeros((N,1)) L[N-1,0] = 1 H = np.zeros((1,N)) H[0,0] = 1 # Infinite covariance: Pinf = lyap(F, -np.dot(L,np.dot( Qc[0,0],L.T))) Pinf = 0.5*(Pinf + Pinf.T) # Allocating space for derivatives dF = np.empty([F.shape[0],F.shape[1],2]) dQc = np.empty([Qc.shape[0],Qc.shape[1],2]) dPinf = np.empty([Pinf.shape[0],Pinf.shape[1],2]) # Derivatives: dFvariance = np.zeros(F.shape) dFlengthscale = np.zeros(F.shape) dFlengthscale[-1,:] = -aa[-1:0:-1]/p_lengthscale * np.arange(-N,0,1) dQcvariance = Qc/p_variance dQclengthscale = np.array(( (p_variance*np.sqrt(2*np.pi)*fn*2**N*p_lengthscale**(-2*N)*(1-2*N),),)) dPinf_variance = Pinf/p_variance lp = Pinf.shape[0] coeff = np.arange(1,lp+1).reshape(lp,1) + np.arange(1,lp+1).reshape(1,lp) - 2 coeff[np.mod(coeff,2) != 0] = 0 dPinf_lengthscale = -1/p_lengthscale*Pinf*coeff dF[:,:,0] = dFvariance dF[:,:,1] = dFlengthscale dQc[:,:,0] = dQcvariance dQc[:,:,1] = dQclengthscale dPinf[:,:,0] = dPinf_variance dPinf[:,:,1] = dPinf_lengthscale P0 = Pinf.copy() dP0 = dPinf.copy() if self.balance: # Benefits of this are not very sound. Helps only in one case: # SVD Kalman + RBF kernel import GPy.models.state_space_main as ssm (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf,dP0) = ssm.balance_ss_model(F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0 ) return (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0) class sde_Exponential(Exponential): """ Class provide extra functionality to transfer this covariance function into SDE form. Exponential kernel: .. math:: k(r) = \sigma^2 \exp \\bigg(- \\frac{1}{2} r \\bigg) \\ \\ \\ \\ \text{ where } r = \sqrt{\sum_{i=1}^{input dim} \frac{(x_i-y_i)^2}{\ell_i^2} } """ def sde_update_gradient_full(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ self.variance.gradient = gradients[0] self.lengthscale.gradient = gradients[1] def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc = np.array( ((2.0*variance/lengthscale,),) ) H = np.array(((1.0,),)) Pinf = np.array(((variance,),)) P0 = Pinf.copy() dF = np.zeros((1,1,2)); dQc = np.zeros((1,1,2)); dPinf = np.zeros((1,1,2)); dF[:,:,0] = 0.0 dF[:,:,1] = 1.0/lengthscale**2 dQc[:,:,0] = 2.0/lengthscale dQc[:,:,1] = -2.0*variance/lengthscale**2 dPinf[:,:,0] = 1.0 dPinf[:,:,1] = 0.0 dP0 = dPinf.copy() return (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0) class sde_RatQuad(RatQuad): """ Class provide extra functionality to transfer this covariance function into SDE form. Rational Quadratic kernel: .. math:: k(r) = \sigma^2 \\bigg( 1 + \\frac{r^2}{2} \\bigg)^{- \alpha} \\ \\ \\ \\ \text{ where } r = \sqrt{\sum_{i=1}^{input dim} \frac{(x_i-y_i)^2}{\ell_i^2} } """ def sde(self): """ Return the state space representation of the covariance. """ assert False, 'Not Implemented' # Params to use: # self.lengthscale # self.variance #self.power #return (F, L, Qc, H, Pinf, dF, dQc, dPinf)
3,862
364
<reponame>akawalsky/hapi-fhir package ca.uhn.fhir.cql.dstu3.listener; /*- * #%L * HAPI FHIR JPA Server - Clinical Quality Language * %% * Copyright (C) 2014 - 2021 Smile CDR, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.Collection; import java.util.List; import java.util.Map; import org.cqframework.cql.elm.execution.Library; import org.cqframework.cql.elm.execution.VersionedIdentifier; import org.hl7.fhir.instance.model.api.IIdType; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.cache.IResourceChangeEvent; import ca.uhn.fhir.jpa.cache.IResourceChangeListener; public class ElmCacheResourceChangeListener implements IResourceChangeListener { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ElmCacheResourceChangeListener.class); private IFhirResourceDao<org.hl7.fhir.dstu3.model.Library> libraryDao; private Map<VersionedIdentifier, Library> globalLibraryCache; public ElmCacheResourceChangeListener(IFhirResourceDao<org.hl7.fhir.dstu3.model.Library> libraryDao, Map<VersionedIdentifier, Library> globalLibraryCache) { this.libraryDao = libraryDao; this.globalLibraryCache = globalLibraryCache; } @Override public void handleInit(Collection<IIdType> theResourceIds) { // Intentionally empty. Only cache ELM on eval request } @Override public void handleChange(IResourceChangeEvent theResourceChangeEvent) { if (theResourceChangeEvent == null) { return; } this.invalidateCacheByIds(theResourceChangeEvent.getDeletedResourceIds()); this.invalidateCacheByIds(theResourceChangeEvent.getUpdatedResourceIds()); } private void invalidateCacheByIds(List<IIdType> theIds) { if (theIds == null) { return; } for (IIdType id : theIds) { this.invalidateCacheById(id); } } private void invalidateCacheById(IIdType theId) { if (!theId.getResourceType().equals("Library")) { return; } try { org.hl7.fhir.dstu3.model.Library library = this.libraryDao.read(theId); this.globalLibraryCache.remove(new VersionedIdentifier().withId(library.getName()).withVersion(library.getVersion())); } // This happens when a Library is deleted entirely so it's impossible to look up name and version. catch (Exception e) { // TODO: This needs to be smarter... the issue is that ELM is cached with library name and version as the key since // that's the access path the CQL engine uses, but change notifications occur with the resource Id, which is not // necessarily tied to the resource name. In any event, if a unknown resource is deleted, clear all libraries as a workaround. // One option is to maintain a cache with multiple indices. ourLog.debug("Failed to locate resource {} to look up name and version. Clearing all libraries from cache.", theId.getValueAsString()); this.globalLibraryCache.clear(); } } }
1,109
407
/* * Copyright (c) 2016-2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NVDLA_PRIV_TEST_POINT_PARAMETER_H #define NVDLA_PRIV_TEST_POINT_PARAMETER_H #include <vector> #include "dlatypes.h" #define GEN_ENUM(X, N) X = N, #define GEN_STR(X, N) #X, #include "priv/TestPointParameterEnum.h" namespace nvdla { namespace priv { // // A "setting" is a specific value as applied to a given "parameter". // // Wrapper class to represent parameters made up of enumerations. // Here the enumerations are required to be unsigned contiguous // sequences beginning at 0. E.g. 0, 1, 2... not flags (0, 1, 2, 4) // or booleans (flags) // template <typename EnumClass, typename UnderlyingType = NvU8 > class TestPointEnumParameter { public: typedef UnderlyingType underlying_type; protected: underlying_type m_e; TestPointEnumParameter(underlying_type v) : m_e(v) { } static const char * s_c_str; // class name str static const char * const s_c_strs[]; // class enum strs static const size_t s_num_elements; public: static const char * parameter_name_c_str() { return s_c_str; } const char *c_str() { return s_c_strs[ m_e ]; } underlying_type v() { return m_e; } EnumClass e() { return EnumClass(m_e); } bool valid() { return m_e < s_num_elements; } TestPointEnumParameter(EnumClass p) : m_e(p) { } }; class BatchMode { public: enum Enum { BATCH_MODE_ENUMS(GEN_ENUM) }; }; typedef TestPointEnumParameter<BatchMode::Enum> BatchModeParameter; class CVSRamSize { public: enum Enum { CVSRAM_SIZE_ENUMS(GEN_ENUM) }; }; typedef TestPointEnumParameter<CVSRamSize::Enum> CVSRamSizeParameter; class HWLayerTuning { public: enum Enum { HW_LAYER_TUNING_ENUMS(GEN_ENUM) }; }; class MappingWeights { public: enum Enum { MAPPING_WEIGHTS_ENUMS(GEN_ENUM) }; }; class Padding { public: enum Enum { PADDING_ENUMS(GEN_ENUM) }; }; class OutputSequence { public: enum Enum { OUTPUT_SEQUENCE_ENUMS(GEN_ENUM) }; }; class Dilation { public: enum Enum { DILATION_ENUMS(GEN_ENUM) }; }; class WeightDensity { public: enum Enum { WEIGHT_DENSITY_ENUMS(GEN_ENUM) }; }; class FeatureDensity { public: enum Enum { FEATURE_DENSITY_ENUMS(GEN_ENUM) }; }; class ChannelExtension { public: enum Enum { CHANNEL_EXTENSION_ENUMS(GEN_ENUM) }; }; class ConvMACRedundancy { public: enum Enum { CONV_MAC_REDUNDANCY_ENUMS(GEN_ENUM) }; }; class ConvBufBankMgmt { public: enum Enum { CONV_BUF_BANK_MGMT_ENUMS(GEN_ENUM) }; }; class PDPOpMode { public: enum Enum { PDP_OP_MODE_ENUMS(GEN_ENUM) }; }; class OffFlyingOpMode { public: enum Enum { OFF_FLYING_OP_MODE_ENUMS(GEN_ENUM) }; }; class SDPOpMode { public: enum Enum { SDP_OP_MODE_ENUMS(GEN_ENUM) }; }; class AXIFSched { public: enum Enum { AXIF_SCHED_ENUMS(GEN_ENUM) }; }; class PixelDataFormat { public: enum Enum { PIXEL_DATA_FORMAT_ENUMS(GEN_ENUM) }; }; class NetworkForks { public: enum Enum { NETWORK_FORKS_ENUMS(GEN_ENUM) }; }; typedef TestPointEnumParameter<HWLayerTuning::Enum> HWLayerTuningParameter; typedef TestPointEnumParameter<MappingWeights::Enum> MappingWeightsParameter; typedef TestPointEnumParameter<Padding::Enum> PaddingParameter; typedef TestPointEnumParameter<OutputSequence::Enum> OutputSequenceParameter; typedef TestPointEnumParameter<Dilation::Enum> DilationParameter; typedef TestPointEnumParameter<WeightDensity::Enum> WeightDensityParameter; typedef TestPointEnumParameter<FeatureDensity::Enum> FeatureDensityParameter; typedef TestPointEnumParameter<ChannelExtension::Enum> ChannelExtensionParameter; typedef TestPointEnumParameter<ConvMACRedundancy::Enum> ConvMACRedundancyParameter; typedef TestPointEnumParameter<ConvBufBankMgmt::Enum> ConvBufBankMgmtParameter; typedef TestPointEnumParameter<PDPOpMode::Enum> PDPOpModeParameter; typedef TestPointEnumParameter<OffFlyingOpMode::Enum> OffFlyingOpModeParameter; typedef TestPointEnumParameter<SDPOpMode::Enum> SDPOpModeParameter; typedef TestPointEnumParameter<AXIFSched::Enum> AXIFSchedParameter; typedef TestPointEnumParameter<PixelDataFormat::Enum> PixelDataFormatParameter; typedef TestPointEnumParameter<NetworkForks::Enum> NetworkForksParameter; // global (system) parameters/constraints // e.g.: // dla0 - use cvsram // dla1 - no cvsram // class GlobalParameters { public: CVSRamSizeParameter m_cvsram_size[2]; // ... }; // these show up in the description of the network somewhere class LayerSettings { // i.e. move these to the network layer? public: // PaddingParameter m_padding; DilationParameter m_dilation; PixelDataFormatParameter m_pixel_data_format; }; class LocalParameters { public: BatchModeParameter m_batch_mode; PaddingParameter m_padding; // packed vs. padded stride or alignment choices instead? CVSRamSizeParameter m_cvsram_size; // discrete set of choices ChannelExtensionParameter m_channel_extension; HWLayerTuningParameter m_hw_layer_tuning; MappingWeightsParameter m_mapping_weights; OutputSequenceParameter m_output_sequence; WeightDensityParameter m_weight_density; FeatureDensityParameter m_feature_density; ConvMACRedundancyParameter m_conv_mac_redundancy; ConvBufBankMgmtParameter m_conv_buf_bank_mgmt; PDPOpModeParameter m_pdp_op_mode; OffFlyingOpModeParameter m_off_flying_op_mode; SDPOpModeParameter m_sdp_op_mode; AXIFSchedParameter m_axif_sched; NetworkForksParameter m_network_forks; }; } // nvdla::priv } // nvdla #endif // NVDLA_PRIV_TEST_POINT_PARAMETER_H
2,861
412
union union_tag_name { int x; float y; }; int main() { const union union_tag_name my_union_var = {.y = 3.15}; const double z = 4; return 0; }
67
1,813
<reponame>scc2758/Just-Another-Android-App<filename>app/src/main/java/com/example/tools/dagger/scopes/ActivityScope.java package com.example.tools.dagger.scopes; import javax.inject.Scope; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Scope @Documented @Retention(RUNTIME) public @interface ActivityScope { }
141
936
/* * Copyright 2021, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.datastores.jms.websocket; import com.yahoo.elide.graphql.ExecutionResultSerializer; import com.yahoo.elide.graphql.GraphQLErrorSerializer; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.Complete; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.ConnectionInit; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.Error; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.MessageType; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.Next; import com.yahoo.elide.graphql.subscriptions.websocket.protocol.Subscribe; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import graphql.ExecutionResult; import graphql.GraphQLError; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.websocket.ClientEndpoint; import javax.websocket.CloseReason; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; /** * Test client for GraphQL subscriptions. This class makes it simpler to write integration tests. */ @ClientEndpoint @Slf4j public class SubscriptionWebSocketTestClient { private CountDownLatch sessionLatch; private CountDownLatch subscribeLatch; private ObjectMapper mapper; private List<ExecutionResult> results; private Session session; private List<String> queries; private int expectedNumberOfMessages; private int expectedNumberOfSubscribes; boolean isOpen = false; /** * Constructor. * @param expectedNumberOfMessages The number of expected messages before notifying the test driver. * @param queries The subscription queries to run. */ public SubscriptionWebSocketTestClient(int expectedNumberOfMessages, List<String> queries) { sessionLatch = new CountDownLatch(1); subscribeLatch = new CountDownLatch(1); results = new ArrayList<>(); this.queries = queries; this.expectedNumberOfMessages = expectedNumberOfMessages; this.expectedNumberOfSubscribes = queries.size(); this.mapper = new ObjectMapper(); GraphQLErrorSerializer errorSerializer = new GraphQLErrorSerializer(); SimpleModule module = new SimpleModule("ExecutionResultSerializer", Version.unknownVersion()); module.addSerializer(ExecutionResult.class, new ExecutionResultSerializer(errorSerializer)); module.addSerializer(GraphQLError.class, errorSerializer); mapper.registerModule(module); } @OnOpen public void onOpen(Session session) throws Exception { this.session = session; log.debug("WebSocket opened: " + session.getId()); isOpen = true; session.getBasicRemote().sendText(mapper.writeValueAsString(new ConnectionInit())); } @OnMessage public void onMessage(String text) throws Exception { JsonNode type = mapper.readTree(text).get("type"); MessageType messageType = MessageType.valueOf(type.textValue().toUpperCase(Locale.ROOT)); switch (messageType) { case CONNECTION_ACK: { Integer id = 1; for (String query : queries) { Subscribe subscribe = Subscribe.builder() .id(id.toString()) .payload(Subscribe.Payload.builder() .query(query) .build()) .build(); session.getBasicRemote().sendText(mapper.writeValueAsString(subscribe)); id++; } break; } case NEXT: { Next next = mapper.readValue(text, Next.class); results.add(next.getPayload()); expectedNumberOfMessages--; if (expectedNumberOfMessages <= 0) { sessionLatch.countDown(); } break; } case PING: { expectedNumberOfSubscribes--; if (expectedNumberOfSubscribes <= 0) { subscribeLatch.countDown(); } break; } case ERROR: { Error error = mapper.readValue(text, Error.class); log.error("ERROR: {}", error.getPayload()); sessionLatch.countDown(); break; } default: { break; } } } @OnClose public void onClose(CloseReason reason) throws Exception { log.debug("Session closed: " + reason.getCloseCode() + " " + reason.getReasonPhrase()); isOpen = false; sessionLatch.countDown(); } @OnError public void onError(Throwable t) throws Exception { log.error("Session error: " + t.getMessage()); isOpen = false; sessionLatch.countDown(); } public void sendClose() throws Exception { if (isOpen) { Integer id = 1; for (String query : queries) { session.getBasicRemote().sendText(mapper.writeValueAsString(new Complete(id.toString()))); id++; } isOpen = false; } } /** * Wait for the subscription to deliver N messages and return them. * @param waitInSeconds The number of seconds to wait before giving up. * @return The messages received. * @throws InterruptedException */ public List<ExecutionResult> waitOnClose(int waitInSeconds) throws InterruptedException { sessionLatch.await(waitInSeconds, TimeUnit.SECONDS); return results; } /** * Wait for the subscription to be setup. * @param waitInSeconds The number of seconds to wait before giving up. * @throws InterruptedException */ public void waitOnSubscribe(int waitInSeconds) throws InterruptedException { subscribeLatch.await(waitInSeconds, TimeUnit.SECONDS); } }
2,723
2,728
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AcceptOwnership(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The accept ownership state of the resource. """ PENDING = "Pending" COMPLETED = "Completed" EXPIRED = "Expired" class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The type of identity that created the resource. """ USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The provisioning state of the resource. """ ACCEPTED = "Accepted" SUCCEEDED = "Succeeded" FAILED = "Failed" class Workload(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """The workload type of the subscription. It can be either Production or DevTest. """ PRODUCTION = "Production" DEV_TEST = "DevTest"
668
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "data_inst.h" #include "non_max_suppression_inst.h" #include "primitive_base.hpp" #include "impls/implementation_map.hpp" #include "kernel_selector_helper.h" #include "non_max_suppression/non_max_suppression_kernel_selector.h" #include "non_max_suppression/non_max_suppression_kernel_ref.h" namespace cldnn { namespace ocl { struct non_max_suppression_impl : typed_primitive_impl_ocl<non_max_suppression> { using parent = typed_primitive_impl_ocl<non_max_suppression>; using parent::parent; std::unique_ptr<primitive_impl> clone() const override { return make_unique<non_max_suppression_impl>(*this); } protected: kernel_arguments_data get_arguments(typed_primitive_inst<non_max_suppression>& instance, int32_t) const override { kernel_arguments_data args; for (size_t i = 0; i < instance.inputs_memory_count(); i++) { args.inputs.push_back(instance.input_memory_ptr(i)); } if (instance.has_num_select_per_class() && !instance.node.num_select_per_class_node().is_constant()) { args.inputs.push_back(instance.num_select_per_class_mem()); } if (instance.has_iou_threshold() && !instance.node.iou_threshold_node().is_constant()) { args.inputs.push_back(instance.iou_threshold_mem()); } if (instance.has_score_threshold() && !instance.node.score_threshold_node().is_constant()) { args.inputs.push_back(instance.score_threshold_mem()); } if (instance.has_soft_nms_sigma() && !instance.node.soft_nms_sigma_node().is_constant()) { args.inputs.push_back(instance.soft_nms_sigma_mem()); } args.outputs = { instance.output_memory_ptr() }; if (instance.has_second_output()) args.inputs.push_back(instance.second_output_mem()); if (instance.has_third_output()) args.inputs.push_back(instance.third_output_mem()); return args; } public: static primitive_impl* create(const non_max_suppression_node& arg) { auto params = get_default_params<kernel_selector::non_max_suppression_params>(arg); auto optional_params = get_default_optional_params<kernel_selector::non_max_suppression_optional_params>(arg.get_program()); const auto& primitive = arg.get_primitive(); params.inputs.push_back(convert_data_tensor(arg.input_scores().get_output_layout())); if (arg.has_num_select_per_class()) { cldnn::program_node& node = arg.num_select_per_class_node(); if (node.is_type<data>()) { params.num_select_per_class_type = kernel_selector::NmsArgType::Constant; params.num_select_per_class = get_value<int>(node); } else { params.num_select_per_class_type = kernel_selector::NmsArgType::Input; params.inputs.push_back(convert_data_tensor(node.get_output_layout())); } } if (arg.has_iou_threshold()) { cldnn::program_node& node = arg.iou_threshold_node(); if (node.is_type<data>()) { params.iou_threshold_type = kernel_selector::NmsArgType::Constant; params.iou_threshold = get_value<float>(node); } else { params.iou_threshold_type = kernel_selector::NmsArgType::Input; params.inputs.push_back(convert_data_tensor(node.get_output_layout())); } } if (arg.has_score_threshold()) { cldnn::program_node& node = arg.score_threshold_node(); if (node.is_type<data>()) { params.score_threshold_type = kernel_selector::NmsArgType::Constant; params.score_threshold = get_value<float>(node); } else { params.score_threshold_type = kernel_selector::NmsArgType::Input; params.inputs.push_back(convert_data_tensor(node.get_output_layout())); } } if (arg.has_soft_nms_sigma()) { cldnn::program_node& node = arg.soft_nms_sigma_node(); if (node.is_type<data>()) { params.soft_nms_sigma_type = kernel_selector::NmsArgType::Constant; params.soft_nms_sigma = get_value<float>(node); } else { params.soft_nms_sigma_type = kernel_selector::NmsArgType::Input; params.inputs.push_back(convert_data_tensor(node.get_output_layout())); } } if (arg.has_second_output()) { params.inputs.push_back(convert_data_tensor(arg.second_output_node().get_output_layout())); params.has_second_output = true; } if (arg.has_third_output()) { params.inputs.push_back(convert_data_tensor(arg.third_output_node().get_output_layout())); params.has_third_output = true; } params.sort_result_descending = primitive->sort_result_descending; params.box_encoding = primitive->center_point_box ? kernel_selector::BoxEncodingType::BOX_ENCODING_CENTER : kernel_selector::BoxEncodingType::BOX_ENCODING_CORNER; auto& kernel_selector = kernel_selector::non_max_suppression_kernel_selector::Instance(); auto best_kernels = kernel_selector.GetBestKernels(params, optional_params); CLDNN_ERROR_BOOL(arg.id(), "Best_kernel.empty()", best_kernels.empty(), "Cannot find a proper kernel with this arguments"); auto non_max_suppression_node = new non_max_suppression_impl(arg, best_kernels[0]); return non_max_suppression_node; } private: template <class T> static T get_value(cldnn::program_node& node) { T retValue; auto mem = node.as<data>().get_attached_memory_ptr(); auto& stream = node.get_program().get_stream(); switch (mem->get_layout().data_type) { case data_types::f16: { mem_lock<half_t> lock(mem, stream); auto mem_value = static_cast<half_t*>(lock.data()); retValue = static_cast<T>(*mem_value); } break; case data_types::f32: { mem_lock<float> lock(mem, stream); auto mem_value = static_cast<float*>(lock.data()); retValue = static_cast<T>(*mem_value); } break; case data_types::i32: { mem_lock<int32_t> lock(mem, stream); auto mem_value = static_cast<int32_t*>(lock.data()); retValue = static_cast<T>(*mem_value); } break; case data_types::i64: { mem_lock<int64_t> lock(mem, stream); auto mem_value = static_cast<int64_t*>(lock.data()); retValue = static_cast<T>(*mem_value); } break; default: throw std::runtime_error("Not supported data type."); } return retValue; } }; namespace detail { attach_non_max_suppression_impl::attach_non_max_suppression_impl() { implementation_map<non_max_suppression>::add(impl_types::ocl, non_max_suppression_impl::create, { std::make_tuple(data_types::i32, format::bfyx), std::make_tuple(data_types::f16, format::bfyx), std::make_tuple(data_types::f32, format::bfyx), }); } } // namespace detail } // namespace ocl } // namespace cldnn
3,443
2,137
package com.publiccms.logic.dao.sys; import java.util.Collections; import java.util.List; import org.springframework.stereotype.Repository; import com.publiccms.common.base.BaseDao; import com.publiccms.common.handler.QueryHandler; import com.publiccms.common.tools.CommonUtils; import com.publiccms.entities.sys.SysExtendField; /** * * SysExtendFieldDao * */ @Repository public class SysExtendFieldDao extends BaseDao<SysExtendField> { /** * @param extendId * @param inputType * @param searchable * @return results page */ @SuppressWarnings("unchecked") public List<SysExtendField> getList(Integer extendId, String[] inputType, Boolean searchable) { if (CommonUtils.notEmpty(extendId)) { QueryHandler queryHandler = getQueryHandler("from SysExtendField bean"); queryHandler.condition("bean.id.extendId = :extendId").setParameter("extendId", extendId); if (CommonUtils.notEmpty(inputType)) { queryHandler.condition("bean.inputType in (:inputType)").setParameter("inputType", inputType); } if (null != searchable) { queryHandler.condition("bean.searchable = :searchable").setParameter("searchable", searchable); } queryHandler.order("bean.sort asc"); return (List<SysExtendField>) getList(queryHandler); } return Collections.emptyList(); } @Override protected SysExtendField init(SysExtendField entity) { return entity; } }
661
1,738
#! /usr/bin/env python3 """ combinerefs path A helper for analyzing PYTHONDUMPREFS output. When the PYTHONDUMPREFS envar is set in a debug build, at Python shutdown time Py_FinalizeEx() prints the list of all live objects twice: first it prints the repr() of each object while the interpreter is still fully intact. After cleaning up everything it can, it prints all remaining live objects again, but the second time just prints their addresses, refcounts, and type names (because the interpreter has been torn down, calling repr methods at this point can get into infinite loops or blow up). Save all this output into a file, then run this script passing the path to that file. The script finds both output chunks, combines them, then prints a line of output for each object still alive at the end: address refcnt typename repr address is the address of the object, in whatever format the platform C produces for a %p format code. refcnt is of the form "[" ref "]" when the object's refcount is the same in both PYTHONDUMPREFS output blocks, or "[" ref_before "->" ref_after "]" if the refcount changed. typename is object->ob_type->tp_name, extracted from the second PYTHONDUMPREFS output block. repr is repr(object), extracted from the first PYTHONDUMPREFS output block. CAUTION: If object is a container type, it may not actually contain all the objects shown in the repr: the repr was captured from the first output block, and some of the containees may have been released since then. For example, it's common for the line showing the dict of interned strings to display strings that no longer exist at the end of Py_FinalizeEx; this can be recognized (albeit painfully) because such containees don't have a line of their own. The objects are listed in allocation order, with most-recently allocated printed first, and the first object allocated printed last. Simple examples: 00857060 [14] str '__len__' The str object '__len__' is alive at shutdown time, and both PYTHONDUMPREFS output blocks said there were 14 references to it. This is probably due to C modules that intern the string "__len__" and keep a reference to it in a file static. 00857038 [46->5] tuple () 46-5 = 41 references to the empty tuple were removed by the cleanup actions between the times PYTHONDUMPREFS produced output. 00858028 [1025->1456] str '<dummy key>' The string '<dummy key>', which is used in dictobject.c to overwrite a real key that gets deleted, grew several hundred references during cleanup. It suggests that stuff did get removed from dicts by cleanup, but that the dicts themselves are staying alive for some reason. """ import re import sys # Generate lines from fileiter. If whilematch is true, continue reading # while the regexp object pat matches line. If whilematch is false, lines # are read so long as pat doesn't match them. In any case, the first line # that doesn't match pat (when whilematch is true), or that does match pat # (when whilematch is false), is lost, and fileiter will resume at the line # following it. def read(fileiter, pat, whilematch): for line in fileiter: if bool(pat.match(line)) == whilematch: yield line else: break def combine(fname): f = open(fname) fi = iter(f) for line in read(fi, re.compile(r'^Remaining objects:$'), False): pass crack = re.compile(r'([a-zA-Z\d]+) \[(\d+)\] (.*)') addr2rc = {} addr2guts = {} before = 0 for line in read(fi, re.compile(r'^Remaining object addresses:$'), False): m = crack.match(line) if m: addr, addr2rc[addr], addr2guts[addr] = m.groups() before += 1 else: print('??? skipped:', line) after = 0 for line in read(fi, crack, True): after += 1 m = crack.match(line) assert m addr, rc, guts = m.groups() # guts is type name here if addr not in addr2rc: print('??? new object created while tearing down:', line.rstrip()) continue print(addr, end=' ') if rc == addr2rc[addr]: print('[%s]' % rc, end=' ') else: print('[%s->%s]' % (addr2rc[addr], rc), end=' ') print(guts, addr2guts[addr]) f.close() print("%d objects before, %d after" % (before, after)) if __name__ == '__main__': combine(sys.argv[1])
1,489
432
/* Language-independent diagnostic subroutines for the GNU Compiler Collection that are only for use in the compilers proper and not the driver or other programs. Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. This file is part of GCC. GCC 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 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tree.h" #include "diagnostic.h" #include "tree-diagnostic.h" #include "langhooks.h" #include "langhooks-def.h" #include "vec.h" /* Prints out, if necessary, the name of the current function that caused an error. Called from all error and warning functions. */ void diagnostic_report_current_function (diagnostic_context *context, diagnostic_info *diagnostic) { diagnostic_report_current_module (context, diagnostic->location); lang_hooks.print_error_function (context, input_filename, diagnostic); } void default_tree_diagnostic_starter (diagnostic_context *context, diagnostic_info *diagnostic) { diagnostic_report_current_function (context, diagnostic); pp_set_prefix (context->printer, diagnostic_build_prefix (context, diagnostic)); } /* This is a pair made of a location and the line map it originated from. It's used in the maybe_unwind_expanded_macro_loc function below. */ typedef struct { const struct line_map *map; source_location where; } loc_map_pair; DEF_VEC_O (loc_map_pair); DEF_VEC_ALLOC_O (loc_map_pair, heap); /* Unwind the different macro expansions that lead to the token which location is WHERE and emit diagnostics showing the resulting unwound macro expansion trace. Let's look at an example to see how the trace looks like. Suppose we have this piece of code, artificially annotated with the line numbers to increase legibility: $ cat -n test.c 1 #define OPERATE(OPRD1, OPRT, OPRD2) \ 2 OPRD1 OPRT OPRD2; 3 4 #define SHIFTL(A,B) \ 5 OPERATE (A,<<,B) 6 7 #define MULT(A) \ 8 SHIFTL (A,1) 9 10 void 11 g () 12 { 13 MULT (1.0);// 1.0 << 1; <-- so this is an error. 14 } Here is the diagnostic that we want the compiler to generate: test.c: In function 'g': test.c:5:14: error: invalid operands to binary << (have 'double' and 'int') test.c:2:9: note: in expansion of macro 'OPERATE' test.c:5:3: note: expanded from here test.c:5:14: note: in expansion of macro 'SHIFTL' test.c:8:3: note: expanded from here test.c:8:3: note: in expansion of macro 'MULT2' test.c:13:3: note: expanded from here The part that goes from the third to the eighth line of this diagnostic (the lines containing the 'note:' string) is called the unwound macro expansion trace. That's the part generated by this function. If FIRST_EXP_POINT_MAP is non-null, *FIRST_EXP_POINT_MAP is set to the map of the location in the source that first triggered the macro expansion. This must be an ordinary map. */ static void maybe_unwind_expanded_macro_loc (diagnostic_context *context, diagnostic_info *diagnostic, source_location where, const struct line_map **first_exp_point_map) { const struct line_map *map; VEC(loc_map_pair,heap) *loc_vec = NULL; unsigned ix; loc_map_pair loc, *iter; map = linemap_lookup (line_table, where); if (!linemap_macro_expansion_map_p (map)) return; /* Let's unwind the macros that got expanded and led to the token which location is WHERE. We are going to store these macros into LOC_VEC, so that we can later walk it at our convenience to display a somewhat meaningful trace of the macro expansion history to the user. Note that the first macro of the trace (which is OPERATE in the example above) is going to be stored at the beginning of LOC_VEC. */ do { loc.where = where; loc.map = map; VEC_safe_push (loc_map_pair, heap, loc_vec, &loc); /* WHERE is the location of a token inside the expansion of a macro. MAP is the map holding the locations of that macro expansion. Let's get the location of the token inside the context that triggered the expansion of this macro. This is basically how we go "down" in the trace of macro expansions that led to WHERE. */ where = linemap_unwind_toward_expansion (line_table, where, &map); } while (linemap_macro_expansion_map_p (map)); if (first_exp_point_map) *first_exp_point_map = map; /* Walk LOC_VEC and print the macro expansion trace, unless the first macro which expansion triggered this trace was expanded inside a system header. */ if (!LINEMAP_SYSP (map)) FOR_EACH_VEC_ELT (loc_map_pair, loc_vec, ix, iter) { source_location resolved_def_loc = 0, resolved_exp_loc = 0; diagnostic_t saved_kind; const char *saved_prefix; source_location saved_location; /* Okay, now here is what we want. For each token resulting from macro expansion we want to show: 1/ where in the definition of the macro the token comes from; 2/ where the macro got expanded. */ /* Resolve the location iter->where into the locus 1/ of the comment above. */ resolved_def_loc = linemap_resolve_location (line_table, iter->where, LRK_MACRO_DEFINITION_LOCATION, NULL); /* Resolve the location of the expansion point of the macro which expansion gave the token represented by def_loc. This is the locus 2/ of the earlier comment. */ resolved_exp_loc = linemap_resolve_location (line_table, MACRO_MAP_EXPANSION_POINT_LOCATION (iter->map), LRK_MACRO_DEFINITION_LOCATION, NULL); saved_kind = diagnostic->kind; saved_prefix = context->printer->prefix; saved_location = diagnostic->location; diagnostic->kind = DK_NOTE; diagnostic->location = resolved_def_loc; pp_base_set_prefix (context->printer, diagnostic_build_prefix (context, diagnostic)); pp_newline (context->printer); pp_printf (context->printer, "in expansion of macro '%s'", linemap_map_get_macro_name (iter->map)); pp_destroy_prefix (context->printer); diagnostic->location = resolved_exp_loc; pp_base_set_prefix (context->printer, diagnostic_build_prefix (context, diagnostic)); pp_newline (context->printer); pp_printf (context->printer, "expanded from here"); pp_destroy_prefix (context->printer); diagnostic->kind = saved_kind; diagnostic->location = saved_location; context->printer->prefix = saved_prefix; } VEC_free (loc_map_pair, heap, loc_vec); } /* This is a diagnostic finalizer implementation that is aware of virtual locations produced by libcpp. It has to be called by the diagnostic finalizer of front ends that uses libcpp and wish to get diagnostics involving tokens resulting from macro expansion. For a given location, if said location belongs to a token resulting from a macro expansion, this starter prints the context of the token. E.g, for multiply nested macro expansion, it unwinds the nested macro expansions and prints them in a manner that is similar to what is done for function call stacks, or template instantiation contexts. */ void virt_loc_aware_diagnostic_finalizer (diagnostic_context *context, diagnostic_info *diagnostic) { maybe_unwind_expanded_macro_loc (context, diagnostic, diagnostic->location, NULL); }
3,282
2,032
<reponame>huayl/phxqueue /* Tencent is pleased to support the open source community by making PhxQueue available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <https://opensource.org/licenses/BSD-3-Clause> 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. */ /* store_server_config.cpp Generated by phxrpc_pb2server from store.proto */ #include "store_server_config.h" #include "store.pb.h" StoreServerConfig::StoreServerConfig() {} StoreServerConfig::~StoreServerConfig() {} bool StoreServerConfig::Read(const char *config_file) { bool ret = ep_server_config_.Read(config_file); if (0 == strlen(ep_server_config_.GetPackageName())) { ep_server_config_.SetPackageName("phxqueue_phxrpc.store"); } // read extra phxrpc::Config config; if (!config.InitConfig(config_file)) { return false; } ret &= config.ReadItem("Store", "Topic", topic_, sizeof(topic_)); ret &= config.ReadItem("Store", "DataDirPath", data_dir_path_, sizeof(data_dir_path_)); ret &= config.ReadItem("Store", "PhxQueueGlobalConfigPath", phxqueue_global_config_path_, sizeof(phxqueue_global_config_path_)); ret &= config.ReadItem("Store", "PaxosPort", &paxos_port_); ret &= config.ReadItem("Store", "NPaxosIOThread", &npaxos_iothread_, 3); config.ReadItem("Store", "NGroup", &ngroup_, 100); return ret; } phxrpc::HshaServerConfig &StoreServerConfig::GetHshaServerConfig() { return ep_server_config_; } const char *StoreServerConfig::GetTopic() const { return topic_; } const char *StoreServerConfig::GetDataDirPath() const { return data_dir_path_; } const char *StoreServerConfig::GetPhxQueueGlobalConfigPath() const { return phxqueue_global_config_path_; } int StoreServerConfig::GetPaxosPort() const { return paxos_port_; } int StoreServerConfig::GetNPaxosIOThread() const { return npaxos_iothread_; } int StoreServerConfig::GetNGroup() const { return ngroup_; }
836
1,985
<reponame>onlyrico/lightseq #pragma once #include <cuda.h> #include <cuda_fp16.h> namespace lightseq { namespace cuda { void launch_split_multilg_request(const int *req, int *src_lang_id, int *trg_lang_id, int *src_token_id, int batch_size, int req_len, cudaStream_t &stream); template <typename T> void launch_enc_emb(const T *token_emb, const T *pos_emb, const int *tokens, T *output, int *pad_mask, int pad_id, int batch_size, int seq_len, int hidden_dim, cudaStream_t stream, const T *lang_emb, const int *lang_id, int multilg_type); template <typename T> void launch_dec_emb(const T *token_emb, const T *pos_emb, int *tokens, const T *lang_emb, const int *lang_id, T *output, int batch_size, int beam_size, int hidden_dim, int vocab_size, int step, int max_step, int multilg_type, cudaStream_t stream); } // namespace cuda } // namespace lightseq
564
981
/******************************************************************* * File automatically generated by rebuild_wrappers.py (v2.1.0.16) * *******************************************************************/ #ifndef __wrappedgthread2UNDEFS_H_ #define __wrappedgthread2UNDEFS_H_ #endif // __wrappedgthread2UNDEFS_H_
82
1,165
<filename>commons/pac-batch-commons/src/main/java/com/tmobile/pacman/commons/azure/clients/AzureCredentialManager.java<gh_stars>1000+ package com.tmobile.pacman.commons.azure.clients; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.microsoft.azure.AzureEnvironment; import com.microsoft.azure.credentials.ApplicationTokenCredentials; import com.microsoft.azure.management.Azure; import com.tmobile.pacman.commons.utils.CommonUtils; public class AzureCredentialManager { /** The Constant logger. */ static final Logger logger = LoggerFactory.getLogger(AzureCredentialManager.class); public static Azure authenticate(String subscription) { return Azure.authenticate(getCredentials()).withSubscription(subscription); } public static String getAuthToken() throws Exception { String url = "https://login.microsoftonline.com/%s/oauth2/token"; String clientId = System.getProperty("azure.clientId"); String domain = System.getProperty("azure.domain"); String secret = System.getProperty("azure.secret"); Map<String,String> params = new HashMap<>(); params.put("client_id", clientId); params.put("client_secret", secret); params.put("resource", "https://management.azure.com"); params.put("grant_type", "client_credentials"); url = String.format(url, domain); try { String jsonResponse = CommonUtils.doHttpPost(url, params); Map<String,String> respMap = new Gson().fromJson(jsonResponse, new TypeToken<Map<String, String>>() {}.getType() ); return respMap.get("access_token"); } catch (Exception e) { logger.error("Error getting mangement API token from Azure",e); throw e; } } public static String getGraphApiAuthToken() throws Exception { String url = "https://login.microsoftonline.com/%s/oauth2/v2.0/token"; String clientId = System.getProperty("azure.clientId"); String domain = System.getProperty("azure.domain"); String secret = System.getProperty("azure.secret"); Map<String,String> params = new HashMap<>(); params.put("client_id", clientId); params.put("client_secret", secret); params.put("scope", "https://graph.microsoft.com/.default"); params.put("grant_type", "client_credentials"); url = String.format(url, domain); try { String jsonResponse = CommonUtils.doHttpPost(url, params); Map<String,String> respMap = new Gson().fromJson(jsonResponse, new TypeToken<Map<String, String>>() {}.getType() ); return respMap.get("access_token"); } catch (Exception e) { logger.error("Error getting Grpah API token from Azure",e); throw e; } } private static ApplicationTokenCredentials getCredentials(){ String clientId = System.getProperty("azure.clientId"); String domain = System.getProperty("azure.domain"); String secret = System.getProperty("azure.secret"); return new ApplicationTokenCredentials(clientId, domain, secret, AzureEnvironment.AZURE); } }
1,039
469
#include <emscripten.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <mono/metadata/assembly.h> #include <mono/mini/jit.h> #include <mono/utils/mono-logger.h> #include <mono/utils/mono-embed.h> #include <mono/utils/mono-dl-fallback.h> #include <windows.h> #include <GdiPlusFlat.h> //JS funcs extern MonoObject* mono_wasm_invoke_js_with_args (int js_handle, MonoString *method, MonoArray *args, int *is_exception); extern MonoObject* mono_wasm_get_object_property (int js_handle, MonoString *method, int *is_exception); extern MonoObject* mono_wasm_set_object_property (int js_handle, MonoString *method, MonoObject *value, int createIfNotExist, int hasOwnProperty, int *is_exception); extern MonoObject* mono_wasm_get_global_object (MonoString *globalName, int *is_exception); // Blazor specific custom routines - see dotnet_support.js for backing code extern void* mono_wasm_invoke_js_marshalled (MonoString **exceptionMessage, void *asyncHandleLongPtr, MonoString *funcName, MonoString *argsJson); extern void* mono_wasm_invoke_js_unmarshalled (MonoString **exceptionMessage, MonoString *funcName, void* arg0, void* arg1, void* arg2); void mono_wasm_enable_debugging (void); void mono_ee_interp_init (const char *opts); void mono_marshal_ilgen_init (void); void mono_method_builder_ilgen_init (void); void mono_sgen_mono_ilgen_init (void); void mono_icall_table_init (void); void mono_aot_register_module (void **aot_info); char *monoeg_g_getenv(const char *variable); int monoeg_g_setenv(const char *variable, const char *value, int overwrite); void mono_free (void*); int mono_regression_test_step (int verbose_level, char *image, char *method_name); void mono_trace_init (void); typedef struct _MonoStringBuilder MonoStringBuilder; MonoStringBuilder *mono_string_utf16_to_builder2 (const gunichar2 *text); static char* m_strdup (const char *str) { if (!str) return NULL; int len = strlen (str) + 1; char *res = malloc (len); memcpy (res, str, len); return res; } static MonoDomain *root_domain; static MonoString* mono_wasm_invoke_js (MonoString *str, int *is_exception) { if (str == NULL) return NULL; char *native_val = mono_string_to_utf8 (str); mono_unichar2 *native_res = (mono_unichar2*)EM_ASM_INT ({ var str = UTF8ToString ($0); try { var res = eval (str); if (res === null || res == undefined) return 0; res = res.toString (); setValue ($1, 0, "i32"); } catch (e) { res = e.toString (); setValue ($1, 1, "i32"); if (res === null || res === undefined) res = "unknown exception"; } var buff = Module._malloc((res.length + 1) * 2); stringToUTF16 (res, buff, (res.length + 1) * 2); return buff; }, (int)native_val, is_exception); mono_free (native_val); if (native_res == NULL) return NULL; MonoString *res = mono_string_from_utf16 (native_res); free (native_res); return res; } static void wasm_logger (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data) { if (fatal) { EM_ASM( var err = new Error(); console.log ("Stacktrace: \n"); console.log (err.stack); ); fprintf (stderr, "%s", message); abort (); } else { fprintf (stdout, "%s\n", message); } } #ifdef ENABLE_AOT #include "driver-gen.c" #endif typedef struct WasmAssembly_ WasmAssembly; struct WasmAssembly_ { MonoBundledAssembly assembly; WasmAssembly *next; }; static WasmAssembly *assemblies; static int assembly_count; EMSCRIPTEN_KEEPALIVE void mono_wasm_add_assembly (const char *name, const unsigned char *data, unsigned int size) { int len = strlen (name); if (!strcasecmp (".pdb", &name [len - 4])) { char *new_name = m_strdup (name); //FIXME handle debugging assemblies with .exe extension strcpy (&new_name [len - 3], "dll"); mono_register_symfile_for_assembly (new_name, data, size); return; } WasmAssembly *entry = (WasmAssembly *)malloc(sizeof (MonoBundledAssembly)); entry->assembly.name = m_strdup (name); entry->assembly.data = data; entry->assembly.size = size; entry->next = assemblies; assemblies = entry; ++assembly_count; } EMSCRIPTEN_KEEPALIVE void mono_wasm_setenv (const char *name, const char *value) { monoeg_g_setenv (strdup (name), strdup (value), 1); } extern int WINAPI invoke_WinMain_Start(int ac, char **av); int WINAPI WinMain_Start(int ac, char **av){ //printf("inside driver.c -- Hi from inside..\n"); return invoke_WinMain_Start(ac,av); } #pragma pack(1) typedef struct { DWORD dwExStyle; MonoString *lpClassName; MonoString *lpWindowName; DWORD dwStyle; int x; int y; int nWidth; int nHeight; HWND hwndParent; HMENU hMenu; HINSTANCE hInstance; LPVOID lpParam; } WinCreateClass; #pragma pack() /*HWND WINAPI Win32CreateWindowEx(WinCreateClass *wincreate) { HWND result; result = CreateWindowEx(wincreate->dwExStyle,mono_string_to_utf8 ((MonoString*)wincreate->lpClassName),mono_string_to_utf8 ((MonoString*)wincreate->lpWindowName),wincreate->dwStyle,wincreate->x,wincreate->y, wincreate->nWidth, wincreate->nHeight, wincreate->hwndParent, wincreate->hMenu, wincreate->hInstance, wincreate->lpParam); printf ("Win32CreateWindowEx classname : %s Windowname: %s \n", mono_string_to_utf8 ((MonoString*)wincreate->lpClassName), mono_string_to_utf8 ((MonoString*)wincreate->lpWindowName)); return result; }*/ EMSCRIPTEN_KEEPALIVE int mono_unbox_int (MonoObject *obj); LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { void *args[4]; int val1 = hwnd; int val2 = msg; int val3 = wp; int val4 = lp; args[0] = &val1; args[1] = &val2; args[2] = &val3; args[3] = &val4; WNDPROC prevregiwndclass = GetWindowLong(hwnd, GWL_WNDPROCBRIDGE); int result = 0; //printf("inside driver.c -- WndProc hwnd=%d msg=%d \n", hwnd, msg); if (prevregiwndclass != NULL) { //printf("inside driver.c -- Running C# delegate for WndProc hwnd=%d msg=%d \n", hwnd, msg); MonoObject* resultObject = mono_runtime_delegate_invoke(prevregiwndclass, args, NULL); result = mono_unbox_int(resultObject); //printf("inside driver.c -- result of Running C# delegate for WndProc (hwnd=%d msg=%d) : %d \n", hwnd, msg, result); } return result; } ATOM WINAPI WasmRegisterClass(WNDCLASS *lpWndClass) { //printf("inside driver.c -- WasmRegisterClass\n"); WNDCLASS newclass = *lpWndClass; newclass.lpszClassName = mono_string_to_utf8 ((MonoString*)lpWndClass->lpszClassName); newclass.lpszMenuName = mono_string_to_utf8 ((MonoString*)lpWndClass->lpszMenuName); newclass.lpfnWndProc = WndProc; newclass.lpfnWndProcBridge = lpWndClass->lpfnWndProc; return RegisterClass(&newclass); } LONG WINAPI WasmSetWindowLong(HWND hwnd, int nIndex, LONG lNewLong) { SetWindowLong(hwnd, nIndex, lNewLong); if (nIndex == GWL_WNDPROC) { //printf("inside driver.c -- Win32SetWindowLong with GWL_WNDPROC from managed \n"); SetWindowLong(hwnd, GWL_WNDPROC, WndProc); SetWindowLong(hwnd, GWL_WNDPROCBRIDGE, lNewLong); } } extern HWND GetAncestor(HWND hwnd, UINT type); struct dll_list_node { char *dll_name; MonoDlMapping *dll_mapping; struct dll_list_node *next; }; struct dll_list_node *dll_list = NULL; /*mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32CreateWindowEx", Win32CreateWindowEx); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::invoke_WinMain_Start", WinMain_Start); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetSystemMetrics", Win32GetSystemMetrics); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32AdjustWindowRectEx", Win32AdjustWindowRectEx); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32RegisterClass", Win32RegisterClass); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32SetWindowLong", Win32SetWindowLong); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32EnableWindow", Win32EnableWindow); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetAncestor", Win32GetAncestor); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetDesktopWindow", Win32GetDesktopWindow); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetWindowRect", Win32GetWindowRect); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetClientRect", Win32GetClientRect); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32ScreenToClient", Win32ScreenToClient); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32ClientToScreen", Win32ClientToScreen); mono_add_internal_call ("System.Windows.Forms.XplatUINanoX::Win32GetParent", Win32GetParent);*/ extern HWND SetParent(HWND hwnd, HWND parent); extern BOOL WINAPI SetLayeredWindowAttributes(HWND hwnd, COLORREF crKey,BYTE bAlpha, DWORD dwFlags); extern BOOL WINAPI GetLayeredWindowAttributes(HWND hwnd, COLORREF *pcrKey, BYTE *pbAlpha, DWORD *pdwFlags); MonoDlMapping nanox_library_mappings [] = { { "CreateWindowEx", CreateWindowEx }, { "invoke_WinMain_Start", invoke_WinMain_Start }, { "GetSystemMetrics", GetSystemMetrics }, { "AdjustWindowRectEx", AdjustWindowRectEx }, { "EnableWindow", EnableWindow }, { "GetAncestor", GetAncestor }, { "GetDesktopWindow", GetDesktopWindow }, { "GetWindowRect", GetWindowRect }, { "GetClientRect", GetClientRect }, { "ScreenToClient", ScreenToClient }, { "ClientToScreen", ClientToScreen }, { "GetParent", GetParent }, { "GetDC", GetDC }, { "ReleaseDC", ReleaseDC }, { "SelectObject", SelectObject }, { "DeleteObject", DeleteObject }, { "BitBlt", BitBlt }, { "GetSysColor", GetSysColor }, { "CreateFontIndirect", CreateFontIndirect }, { "CreateFontIndirectA", CreateFontIndirect }, { "CreateFontIndirectW", CreateFontIndirectW }, { "DrawTextA", DrawTextA }, { "SetTextColor", SetTextColor }, { "SetBkColor", SetBkColor }, { "SetBkMode", SetBkMode }, { "SelectClipRgn", SelectClipRgn }, { "MoveWindow", MoveWindow }, { "SetWindowPos", SetWindowPos }, { "DispatchMessage", DispatchMessage }, { "TranslateMessage", TranslateMessage }, { "GetMessage", GetMessage }, { "PeekMessage", PeekMessage }, { "DestroyWindow", DestroyWindow }, { "GetLastError", GetLastError }, { "SetWindowText", SetWindowText }, { "GetWindowText", GetWindowText }, { "SetParent", SetParent }, { "DefWindowProc", DefWindowProc }, { "PostQuitMessage", PostQuitMessage }, { "UpdateWindow", UpdateWindow }, { "GetUpdateRect", GetUpdateRect }, { "BeginPaint", BeginPaint }, { "ValidateRect", ValidateRect }, { "EndPaint", EndPaint }, { "GetWindowDC", GetWindowDC }, { "InvalidateRect", InvalidateRect }, { "SetActiveWindow", SetActiveWindow }, { "CreateSolidBrush", CreateSolidBrush }, { "ShowWindow", ShowWindow }, { "GetWindowLong", GetWindowLong}, { "GetFocus", GetFocus }, { "SetFocus", SetFocus }, { "SetTimer", SetTimer }, { "KillTimer", KillTimer }, { "SendMessageA", SendMessage }, { "SendMessageW", SendMessage }, { "PostMessageW", PostMessage }, { "GetActiveWindow", GetActiveWindow }, { "PostMessageA", PostMessage }, { "SetLayeredWindowAttributes", SetLayeredWindowAttributes }, { "GetLayeredWindowAttributes", GetLayeredWindowAttributes }, { "SetCapture", SetCapture }, { "GetCapture", GetCapture }, { "ReleaseCapture", ReleaseCapture }, { "SystemParametersInfoA", SystemParametersInfoA }, { "SystemParametersInfoW", SystemParametersInfoW }, { "CreateCaret", CreateCaret }, { "SetCaretPos", SetCaretPos }, { "GetCaretPos", GetCaretPos }, { "ShowCaret", ShowCaret }, { "HideCaret", HideCaret }, { "DestroyCaret", DestroyCaret }, { "GetCursorPos", GetCursorPos }, { NULL, NULL } }; /*mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipSetStringFormatLineAlign", Win32GdipSetStringFormatLineAlign); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdiplusStartup", Win32GdiplusStartup); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipCreateStringFormat", Win32GdipCreateStringFormat); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipSetStringFormatAlign", Win32GdipSetStringFormatAlign); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipSetStringFormatHotkeyPrefix", Win32GdipSetStringFormatHotkeyPrefix); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetStringFormatFlags", Win32GdipGetStringFormatFlags); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetGenericFontFamilySansSerif", Win32GdipGetGenericFontFamilySansSerif); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetFamilyName", Win32GdipGetFamilyName); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipCreateFont", Win32GdipCreateFont); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipCreateFromHWND", Win32GdipCreateFromHWND); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipCreateBitmapFromScan0", Win32GdipCreateBitmapFromScan0); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetImagePixelFormat", Win32GdipGetImagePixelFormat); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetImageGraphicsContext", Win32GdipGetImageGraphicsContext); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetDpiX", Win32GdipGetDpiX); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetDpiY", Win32GdipGetDpiY); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetFontHeightGivenDPI", Win32GdipGetFontHeightGivenDPI); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetFontHeight", Win32GdipGetFontHeight); mono_add_internal_call ("System.Drawing.GDIPlus::Win32GdipGetDC", Win32GdipGetDC);*/ MonoDlMapping libgdi_library_mappings [] = { { "GdipSetStringFormatLineAlign", GdipSetStringFormatLineAlign }, { "GdiplusStartup", GdiplusStartup }, { "GdipCreateStringFormat", GdipCreateStringFormat }, { "GdipSetStringFormatAlign", GdipSetStringFormatAlign }, { "GdipSetStringFormatHotkeyPrefix", GdipSetStringFormatHotkeyPrefix }, { "GdipGetStringFormatFlags", GdipGetStringFormatFlags }, { "GdipGetGenericFontFamilySansSerif", GdipGetGenericFontFamilySansSerif }, { "GdipGetFamilyName", GdipGetFamilyName }, { "GdipCreateFont", GdipCreateFont }, { "GdipCreateFromHWND", GdipCreateFromHWND }, { "GdipCreateBitmapFromScan0", GdipCreateBitmapFromScan0 }, { "GdipGetImagePixelFormat", GdipGetImagePixelFormat }, { "GdipGetImageGraphicsContext", GdipGetImageGraphicsContext }, { "GdipGetDpiX", GdipGetDpiX }, { "GdipGetDpiY", GdipGetDpiY }, { "GdipGetFontHeightGivenDPI", GdipGetFontHeightGivenDPI }, { "GdipGetFontHeight", GdipGetFontHeight }, { "GdipSetStringFormatFlags", GdipSetStringFormatFlags }, { "GdipSetStringFormatTrimming", GdipSetStringFormatTrimming }, { "GdipGetStringFormatTrimming", GdipGetStringFormatTrimming }, { "GdipGetDC", GdipGetDC }, { "GdipReleaseDC", GdipReleaseDC }, { "GdipDrawString", GdipDrawString }, { "GdipFillRectangles", GdipFillRectangles }, { "GdipCreateFromHDC", GdipCreateFromHDC }, { "GdipDeleteGraphics", GdipDeleteGraphics }, { "GdipRestoreGraphics", GdipRestoreGraphics }, { "GdipGetLogFontA", GdipGetLogFontA }, { "GdipGetLogFontW", GdipGetLogFontW }, { "GdipDeleteFont", GdipDeleteFont }, { "CreateFontIndirect", CreateFontIndirect }, { "GdipCreateFontFromLogfontA", GdipCreateFontFromLogfontA }, { "GdipCreateFontFromLogfontW", GdipCreateFontFromLogfontW }, { "GdipCreateSolidFill", GdipCreateSolidFill }, { "GdipFillRectangleI", GdipFillRectangleI }, { "GdipSetClipRectI", GdipSetClipRectI }, /**/{ "GdipCreatePen1", GdipCreatePen1 }, { "GdipDrawLineI", GdipDrawLineI }, { "GdipDrawLine", GdipDrawLine }, { "GdipDrawRectangleI", GdipDrawRectangleI }, { "GdipDrawRectangle", GdipDrawRectangle }, { "GdipDrawPolygon", GdipDrawPolygon }, { "GdipDrawPolygonI", GdipDrawPolygonI }, { "GdipCreateMatrix", GdipCreateMatrix }, { "GdipCreateMatrix2", GdipCreateMatrix2 }, { "GdipCreateMatrix3", GdipCreateMatrix3 }, { "GdipCreateMatrix3I", GdipCreateMatrix3I }, { "GdipDeleteMatrix", GdipDeleteMatrix }, { "GdipCloneMatrix", GdipCloneMatrix }, { "GdipSetMatrixElements", GdipSetMatrixElements }, { "GdipGetMatrixElements", GdipGetMatrixElements }, { "GdipTranslateMatrix", GdipTranslateMatrix }, { "GdipScaleMatrix", GdipScaleMatrix }, { "GdipRotateMatrix", GdipRotateMatrix }, { "GdipIsMatrixEqual", GdipIsMatrixEqual }, { "GdipIsMatrixIdentity", GdipIsMatrixIdentity }, { "GdipIsMatrixInvertible", GdipIsMatrixInvertible }, { "GdipVectorTransformMatrixPoints", GdipVectorTransformMatrixPoints }, { "GdipTransformMatrixPointsI", GdipTransformMatrixPointsI }, { "GdipTransformMatrixPoints", GdipTransformMatrixPoints }, { "GdipInvertMatrix", GdipInvertMatrix }, { "GdipGetWorldTransform", GdipGetWorldTransform }, { "GdipSetWorldTransform", GdipSetWorldTransform }, { "GdipResetWorldTransform", GdipResetWorldTransform }, { "GdipScaleWorldTransform", GdipScaleWorldTransform }, { "GdipCreateHatchBrush", GdipCreateHatchBrush }, { "GdipCreatePen2", GdipCreatePen2 }, { "GdipDeletePen", GdipDeletePen }, { "GdipClonePen", GdipClonePen }, { "GdipSetPenBrushFill", GdipSetPenBrushFill }, { "GdipGetPenFillType", GdipGetPenFillType }, { "GdipSetPenColor", GdipSetPenColor }, { "GdipGetPenColor", GdipGetPenColor }, { "GdipSetPenWidth", GdipSetPenWidth }, { "GdipGetPenWidth", GdipGetPenWidth }, { "GdipSetPenMode", GdipSetPenMode }, { "GdipGetPenMode", GdipGetPenMode }, { "GdipSetPenTransform", GdipSetPenTransform }, { "GdipGetPenTransform", GdipGetPenTransform }, { "GdipStringFormatGetGenericTypographic", GdipStringFormatGetGenericTypographic }, { "GdipCloneStringFormat", GdipCloneStringFormat }, { "GdipMeasureString", GdipMeasureString }, { "GdipSetStringFormatMeasurableCharacterRanges", GdipSetStringFormatMeasurableCharacterRanges }, { "GdipGetStringFormatMeasurableCharacterRangeCount", GdipGetStringFormatMeasurableCharacterRangeCount }, { "GdipCreateRegion", GdipCreateRegion }, { "GdipCreateRegionRect", GdipCreateRegionRect }, { "GdipCreateRegionRectI", GdipCreateRegionRectI }, { "GdipCreateRegionPath", GdipCreateRegionPath }, { "GdipCreateRegionRgnData", GdipCreateRegionRgnData }, { "GdipCloneRegion", GdipCloneRegion }, { "GdipDeleteRegion", GdipDeleteRegion }, { "GdipCombineRegionRect", GdipCombineRegionRect }, { "GdipGetRegionBounds", GdipGetRegionBounds }, { "GdipMeasureCharacterRanges", GdipMeasureCharacterRanges }, { "GdipFillPolygon2", GdipFillPolygon2 }, { "GdipCreateFontFamilyFromName", GdipCreateFontFamilyFromName }, { "GdipGetGenericFontFamilySerif", GdipGetGenericFontFamilySerif }, { "GdipGetGenericFontFamilyMonospace", GdipGetGenericFontFamilyMonospace }, { "GdipFlush", GdipFlush }, { "GdipFillPolygonI", GdipFillPolygonI }, { "GdipDeleteStringFormat", GdipDeleteStringFormat }, { "GdipGetClip", GdipGetClip }, { "GdipSetClipRegion", GdipSetClipRegion }, { "GdipFillEllipseI", GdipFillEllipseI }, { "GdipFillPie", GdipFillPie }, { "GdipDrawArc", GdipDrawArc }, { "GdipDrawArcI", GdipDrawArcI }, { "GdipCombineRegionRectI", GdipCombineRegionRectI }, { "GdipIsVisibleRegionRectI", GdipIsVisibleRegionRectI }, { "GdipIsVisibleRegionRect", GdipIsVisibleRegionRect }, { "GdipIsVisibleRegionPointI", GdipIsVisibleRegionPointI }, { "GdipIsVisibleRegionPoint", GdipIsVisibleRegionPoint }, { "GdipCreateLineBrushFromRectI", GdipCreateLineBrushFromRectI }, { "GdipDeleteBrush", GdipDeleteBrush }, { "GdipTranslateWorldTransform", GdipTranslateWorldTransform }, { "GdipRotateWorldTransform", GdipRotateWorldTransform }, { "GdipMultiplyWorldTransform", GdipMultiplyWorldTransform }, { "GdipGraphicsClear", GdipGraphicsClear }, { "GdipDrawLinesI", GdipDrawLinesI }, { "GdipFillPie", GdipFillPie }, { "GdipFillPie", GdipFillPie }, { NULL, NULL } }; static void * dl_mapping_open (const char *file, int flags, char **err, void *user_data) { printf("dl_mapping_open %s -",file); MonoDlMapping *mappings; struct dll_list_node* current = dll_list; if (current == NULL) { printf(" dll_list were empty \n"); return NULL; } while (strcmp(file,current->dll_name) != 0) { current = current->next; if (current == NULL) { printf("%s could not be found in my dl_mapping \n",file); return NULL; } } printf("%s matched and found!\n", file); mappings = current->dll_mapping; *err = g_strdup (mappings == NULL ? "File not registered" : ""); return mappings; } static void * dl_mapping_symbol (void *handle, const char *symbol, char **err, void *user_data) { printf("dl_mapping_symbol %s - ",symbol); MonoDlMapping *mappings = (MonoDlMapping *) handle; for (;mappings->name; mappings++){ if (strcmp (symbol, mappings->name) == 0){ *err = g_strdup (""); printf("proc name %s matched\n",symbol); return mappings->addr; } } printf("proc name %s not matched\n", symbol); *err = g_strdup ("Symbol not found"); return NULL; } void mono_dl_register_library (const char *name, MonoDlMapping *mappings) { printf("mono_dl_register_library %s\n",name); struct dll_list_node *node; node = malloc(sizeof(struct dll_list_node)); node->dll_name = strdup (name); node->dll_mapping = mappings; if (dll_list == NULL){ dll_list = node; mono_dl_fallback_register (dl_mapping_open, dl_mapping_symbol, NULL, NULL); return ; } struct dll_list_node* current = dll_list; while (current) { if (!current->next){ current->next = node; return; } current = current->next; } } EMSCRIPTEN_KEEPALIVE void mono_wasm_load_runtime (const char *managed_path, int enable_debugging) { monoeg_g_setenv ("MONO_LOG_LEVEL", "debug", 0); monoeg_g_setenv ("MONO_LOG_MASK", "gc", 0); #ifdef ENABLE_AOT // Defined in driver-gen.c register_aot_modules (); mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY); #else mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP_LLVMONLY); if (enable_debugging) mono_wasm_enable_debugging (); #endif #ifndef ENABLE_AOT mono_icall_table_init (); mono_ee_interp_init (""); mono_marshal_ilgen_init (); mono_method_builder_ilgen_init (); mono_sgen_mono_ilgen_init (); #endif if (assembly_count) { MonoBundledAssembly **bundle_array = (MonoBundledAssembly **)calloc (1, sizeof (MonoBundledAssembly*) * (assembly_count + 1)); WasmAssembly *cur = assemblies; bundle_array [assembly_count] = NULL; int i = 0; while (cur) { bundle_array [i] = &cur->assembly; cur = cur->next; ++i; } mono_register_bundled_assemblies ((const MonoBundledAssembly**)bundle_array); } mono_trace_init (); mono_trace_set_log_handler (wasm_logger, NULL); root_domain = mono_jit_init_version ("mono", "v4.0.30319"); mono_add_internal_call ("WebAssembly.Runtime::InvokeJS", mono_wasm_invoke_js); mono_add_internal_call ("WebAssembly.Runtime::InvokeJSWithArgs", mono_wasm_invoke_js_with_args); mono_add_internal_call ("WebAssembly.Runtime::GetObjectProperty", mono_wasm_get_object_property); mono_add_internal_call ("WebAssembly.Runtime::SetObjectProperty", mono_wasm_set_object_property); mono_add_internal_call ("WebAssembly.Runtime::GetGlobalObject", mono_wasm_get_global_object); // Blazor specific custom routines - see dotnet_support.js for backing code mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJSMarshalled", mono_wasm_invoke_js_marshalled); mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJSUnmarshalled", mono_wasm_invoke_js_unmarshalled); mono_add_internal_call ("System.Windows.Forms.InternalCalls::WasmRegisterClass", WasmRegisterClass); mono_add_internal_call ("System.Windows.Forms.InternalCalls::WasmSetWindowLong", WasmSetWindowLong); mono_dl_register_library ("libmwin.dll", nanox_library_mappings); mono_dl_register_library ("libgdiplus.dll", libgdi_library_mappings); setenv("FONTCONFIG_PATH","/etc", 1); } EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_assembly_load (const char *name) { MonoImageOpenStatus status; MonoAssemblyName* aname = mono_assembly_name_new (name); if (!name) return NULL; MonoAssembly *res = mono_assembly_load (aname, NULL, &status); mono_assembly_name_free (aname); return res; } EMSCRIPTEN_KEEPALIVE MonoClass* mono_wasm_assembly_find_class (MonoAssembly *assembly, const char *namespace, const char *name) { return mono_class_from_name (mono_assembly_get_image (assembly), namespace, name); } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_find_method (MonoClass *klass, const char *name, int arguments) { return mono_class_get_method_from_name (klass, name, arguments); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_invoke_method (MonoMethod *method, MonoObject *this_arg, void *params[], int* got_exception) { MonoObject *exc = NULL; MonoObject *res = mono_runtime_invoke (method, this_arg, params, &exc); *got_exception = 0; if (exc) { *got_exception = 1; MonoObject *exc2 = NULL; res = (MonoObject*)mono_object_to_string (exc, &exc2); if (exc2) res = (MonoObject*) mono_string_new (root_domain, "Exception Double Fault"); return res; } return res; } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_get_entry_point (MonoAssembly *assembly) { MonoImage *image; MonoMethod *method; image = mono_assembly_get_image (assembly); uint32_t entry = mono_image_get_entry_point (image); if (!entry) return NULL; return mono_get_method (image, entry, NULL); } EMSCRIPTEN_KEEPALIVE char * mono_wasm_string_get_utf8 (MonoString *str) { return mono_string_to_utf8 (str); //XXX JS is responsible for freeing this } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_string_from_js (const char *str) { return mono_string_new (root_domain, str); } static int class_is_task (MonoClass *klass) { if (!strcmp ("System.Threading.Tasks", mono_class_get_namespace (klass)) && (!strcmp ("Task", mono_class_get_name (klass)) || !strcmp ("Task`1", mono_class_get_name (klass)))) return 1; return 0; } #define MARSHAL_TYPE_INT 1 #define MARSHAL_TYPE_FP 2 #define MARSHAL_TYPE_STRING 3 #define MARSHAL_TYPE_VT 4 #define MARSHAL_TYPE_DELEGATE 5 #define MARSHAL_TYPE_TASK 6 #define MARSHAL_TYPE_OBJECT 7 #define MARSHAL_TYPE_BOOL 8 #define MARSHAL_TYPE_ENUM 9 // typed array marshalling #define MARSHAL_ARRAY_BYTE 11 #define MARSHAL_ARRAY_UBYTE 12 #define MARSHAL_ARRAY_SHORT 13 #define MARSHAL_ARRAY_USHORT 14 #define MARSHAL_ARRAY_INT 15 #define MARSHAL_ARRAY_UINT 16 #define MARSHAL_ARRAY_FLOAT 17 #define MARSHAL_ARRAY_DOUBLE 18 EMSCRIPTEN_KEEPALIVE int mono_wasm_get_obj_type (MonoObject *obj) { if (!obj) return 0; MonoClass *klass = mono_object_get_class (obj); MonoType *type = mono_class_get_type (klass); switch (mono_type_get_type (type)) { // case MONO_TYPE_CHAR: prob should be done not as a number? case MONO_TYPE_BOOLEAN: return MARSHAL_TYPE_BOOL; case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: return MARSHAL_TYPE_INT; case MONO_TYPE_R4: case MONO_TYPE_R8: return MARSHAL_TYPE_FP; case MONO_TYPE_STRING: return MARSHAL_TYPE_STRING; case MONO_TYPE_SZARRAY: { // simple zero based one-dim-array MonoClass *eklass = mono_class_get_element_class(klass); MonoType *etype = mono_class_get_type (eklass); switch (mono_type_get_type (etype)) { case MONO_TYPE_U1: return MARSHAL_ARRAY_UBYTE; case MONO_TYPE_I1: return MARSHAL_ARRAY_BYTE; case MONO_TYPE_U2: return MARSHAL_ARRAY_USHORT; case MONO_TYPE_I2: return MARSHAL_ARRAY_SHORT; case MONO_TYPE_U4: return MARSHAL_ARRAY_UINT; case MONO_TYPE_I4: return MARSHAL_ARRAY_INT; case MONO_TYPE_R4: return MARSHAL_ARRAY_FLOAT; case MONO_TYPE_R8: return MARSHAL_ARRAY_DOUBLE; default: return MARSHAL_TYPE_OBJECT; } } default: if (mono_class_is_enum (klass)) return MARSHAL_TYPE_ENUM; if (!mono_type_is_reference (type)) //vt return MARSHAL_TYPE_VT; if (mono_class_is_delegate (klass)) return MARSHAL_TYPE_DELEGATE; if (class_is_task(klass)) return MARSHAL_TYPE_TASK; return MARSHAL_TYPE_OBJECT; } } EMSCRIPTEN_KEEPALIVE int mono_unbox_int (MonoObject *obj) { if (!obj) return 0; MonoType *type = mono_class_get_type (mono_object_get_class(obj)); void *ptr = mono_object_unbox (obj); switch (mono_type_get_type (type)) { case MONO_TYPE_I1: case MONO_TYPE_BOOLEAN: return *(signed char*)ptr; case MONO_TYPE_U1: return *(unsigned char*)ptr; case MONO_TYPE_I2: return *(short*)ptr; case MONO_TYPE_U2: return *(unsigned short*)ptr; case MONO_TYPE_I4: return *(int*)ptr; case MONO_TYPE_U4: return *(unsigned int*)ptr; // WASM doesn't support returning longs to JS // case MONO_TYPE_I8: // case MONO_TYPE_U8: default: printf ("Invalid type %d to mono_unbox_int\n", mono_type_get_type (type)); return 0; } } EMSCRIPTEN_KEEPALIVE double mono_wasm_unbox_float (MonoObject *obj) { if (!obj) return 0; MonoType *type = mono_class_get_type (mono_object_get_class(obj)); void *ptr = mono_object_unbox (obj); switch (mono_type_get_type (type)) { case MONO_TYPE_R4: return *(float*)ptr; case MONO_TYPE_R8: return *(double*)ptr; default: printf ("Invalid type %d to mono_wasm_unbox_float\n", mono_type_get_type (type)); return 0; } } EMSCRIPTEN_KEEPALIVE int mono_wasm_array_length (MonoArray *array) { return mono_array_length (array); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_array_get (MonoArray *array, int idx) { return mono_array_get (array, MonoObject*, idx); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_obj_array_new (int size) { return mono_array_new (root_domain, mono_get_object_class (), size); } EMSCRIPTEN_KEEPALIVE void mono_wasm_obj_array_set (MonoArray *array, int idx, MonoObject *obj) { mono_array_setref (array, idx, obj); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_string_array_new (int size) { return mono_array_new (root_domain, mono_get_string_class (), size); } // Int8Array | int8_t | byte or SByte (signed byte) // Uint8Array | uint8_t | byte or Byte (unsigned byte) // Uint8ClampedArray| uint8_t | byte or Byte (unsigned byte) // Int16Array | int16_t | short (signed short) // Uint16Array | uint16_t | ushort (unsigned short) // Int32Array | int32_t | int (signed integer) // Uint32Array | uint32_t | uint (unsigned integer) // Float32Array | float | float // Float64Array | double | double EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_typed_array_new (char *arr, int length, int size, int type) { MonoClass *typeClass = mono_get_byte_class(); // default is Byte switch (type) { case MARSHAL_ARRAY_BYTE: typeClass = mono_get_sbyte_class(); break; case MARSHAL_ARRAY_SHORT: typeClass = mono_get_int16_class(); break; case MARSHAL_ARRAY_USHORT: typeClass = mono_get_uint16_class(); break; case MARSHAL_ARRAY_INT: typeClass = mono_get_int32_class(); break; case MARSHAL_ARRAY_UINT: typeClass = mono_get_uint32_class(); break; case MARSHAL_ARRAY_FLOAT: typeClass = mono_get_single_class(); break; case MARSHAL_ARRAY_DOUBLE: typeClass = mono_get_double_class(); break; } MonoArray *buffer; buffer = mono_array_new (root_domain, typeClass, length); memcpy(mono_array_addr_with_size(buffer, sizeof(char), 0), arr, length * size); return buffer; } EMSCRIPTEN_KEEPALIVE void mono_wasm_array_to_heap (MonoArray *src, char *dest) { int element_size; void *source_addr; int arr_length; element_size = mono_array_element_size ( mono_object_get_class((MonoObject*)src)); //DBG("mono_wasm_to_heap element size %i / length %i\n",element_size, mono_array_length(src)); // get our src address source_addr = mono_array_addr_with_size (src, element_size, 0); // copy the array memory to heap via ptr dest memcpy (dest, source_addr, mono_array_length(src) * element_size); } EMSCRIPTEN_KEEPALIVE int mono_wasm_exec_regression (int verbose_level, char *image) { return mono_regression_test_step (verbose_level, image, NULL) ? 0 : 1; } EMSCRIPTEN_KEEPALIVE int mono_wasm_unbox_enum (MonoObject *obj) { if (!obj) return 0; MonoType *type = mono_class_get_type (mono_object_get_class(obj)); void *ptr = mono_object_unbox (obj); switch (mono_type_get_type(mono_type_get_underlying_type (type))) { case MONO_TYPE_I1: case MONO_TYPE_U1: return *(unsigned char*)ptr; case MONO_TYPE_I2: return *(short*)ptr; case MONO_TYPE_U2: return *(unsigned short*)ptr; case MONO_TYPE_I4: return *(int*)ptr; case MONO_TYPE_U4: return *(unsigned int*)ptr; // WASM doesn't support returning longs to JS // case MONO_TYPE_I8: // case MONO_TYPE_U8: default: printf ("Invalid type %d to mono_unbox_enum\n", mono_type_get_type(mono_type_get_underlying_type (type))); return 0; } } EMSCRIPTEN_KEEPALIVE int mono_wasm_exit (int exit_code) { exit (exit_code); }
13,807
742
<filename>OpenTESArena/src/Media/TextCinematicDefinition.h<gh_stars>100-1000 #ifndef TEXT_CINEMATIC_DEFINITION_H #define TEXT_CINEMATIC_DEFINITION_H #include <string> #include <vector> #include "Color.h" // Intended for text cinematics with speech. class TextCinematicDefinition { public: enum class Type { Death, MainQuest }; struct DeathDefinition { enum class Type { Good, Bad }; DeathDefinition::Type type; void init(DeathDefinition::Type type); }; struct MainQuestDefinition { int progress; // Current point in main quest. void init(int progress); }; private: Type type; int templateDatKey; // Maps to TEMPLATE.DAT text and used with .VOC filenames. std::string animFilename; Color fontColor; // @todo: maybe some isFloppyVersion bool to support floppy/CD endings. union { DeathDefinition death; MainQuestDefinition mainQuest; }; void init(Type type, int templateDatKey, std::string &&animFilename, const Color &fontColor); public: void initDeath(int templateDatKey, std::string &&animFilename, const Color &fontColor, DeathDefinition::Type type); void initMainQuest(int templateDatKey, std::string &&animFilename, const Color &fontColor, int progress); Type getType() const; int getTemplateDatKey() const; const std::string &getAnimationFilename() const; const Color &getFontColor() const; const DeathDefinition &getDeathDefinition() const; const MainQuestDefinition &getMainQuestDefinition() const; }; #endif
485
1,034
/* * Copyright 2019 NXP * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #include "fsl_codec_i2c.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Variables ******************************************************************************/ /******************************************************************************* * Code ******************************************************************************/ /*! * brief Codec i2c bus initilization. * * param handle i2c master handle. * param i2CInstance instance number of the i2c bus, such as 0 is corresponding to I2C0. * param i2cBaudrate i2c baudrate. * param i2cSourceClockHz i2c source clock frequency. * return kStatus_HAL_I2cSuccess is success, else initial failed. */ status_t CODEC_I2C_Init(void *handle, uint32_t i2cInstance, uint32_t i2cBaudrate, uint32_t i2cSourceClockHz) { hal_i2c_master_config_t masterConfig; masterConfig.enableMaster = true; masterConfig.baudRate_Bps = i2cBaudrate; masterConfig.srcClock_Hz = i2cSourceClockHz; masterConfig.instance = i2cInstance; return HAL_I2cMasterInit((hal_i2c_master_handle_t *)handle, &masterConfig); } /*! * brief Codec i2c de-initilization. * * param handle i2c master handle. * return kStatus_HAL_I2cSuccess is success, else deinitial failed. */ status_t CODEC_I2C_Deinit(void *handle) { return HAL_I2cMasterDeinit((hal_i2c_master_handle_t *)handle); } /*! * brief codec i2c send function. * * param handle i2c master handle. * param deviceAddress codec device address. * param subAddress register address. * param subaddressSize register address width. * param txBuff tx buffer pointer. * param txBuffSize tx buffer size. * return kStatus_HAL_I2cSuccess is success, else send failed. */ status_t CODEC_I2C_Send(void *handle, uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint8_t *txBuff, uint8_t txBuffSize) { hal_i2c_master_transfer_t masterXfer; masterXfer.slaveAddress = deviceAddress; masterXfer.direction = kHAL_I2cWrite; masterXfer.subaddress = (uint32_t)subAddress; masterXfer.subaddressSize = subaddressSize; masterXfer.data = txBuff; masterXfer.dataSize = txBuffSize; masterXfer.flags = kHAL_I2cTransferDefaultFlag; return HAL_I2cMasterTransferBlocking((hal_i2c_master_handle_t *)handle, &masterXfer); } /*! * brief codec i2c receive function. * * param handle i2c master handle. * param deviceAddress codec device address. * param subAddress register address. * param subaddressSize register address width. * param rxBuff rx buffer pointer. * param rxBuffSize rx buffer size. * return kStatus_HAL_I2cSuccess is success, else receive failed. */ status_t CODEC_I2C_Receive(void *handle, uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint8_t *rxBuff, uint8_t rxBuffSize) { hal_i2c_master_transfer_t masterXfer; masterXfer.slaveAddress = deviceAddress; masterXfer.direction = kHAL_I2cRead; masterXfer.subaddress = (uint32_t)subAddress; masterXfer.subaddressSize = subaddressSize; masterXfer.data = rxBuff; masterXfer.dataSize = rxBuffSize; masterXfer.flags = kHAL_I2cTransferDefaultFlag; return HAL_I2cMasterTransferBlocking((hal_i2c_master_handle_t *)handle, &masterXfer); }
1,591
1,127
// Copyright (C) 2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <subgraph_tests/multi_crops_to_concat.hpp> #include "common_test_utils/test_constants.hpp" namespace SubgraphTestsDefinitions { namespace { const std::vector<std::vector<size_t>> input_shapes = { {1, 48}, {1, 64} }; const std::vector<std::vector<std::pair<int64_t, int64_t>>> offsets = { { {0, 16}, {33, 48} }, { {17, 32}, {33, 48} }, { {5, 14}, {17, 26} }, { {1, 8}, {9, 16}, {17, 24} } }; const std::vector<std::map<std::string, std::string>> additional_config = { { {"GNA_DEVICE_MODE", "GNA_SW_EXACT"} }, { {"GNA_DEVICE_MODE", "GNA_SW_FP32"} } }; } // namespace INSTANTIATE_TEST_SUITE_P(smoke_multi_crop_to_concat, MultiCropsToConcatTest, ::testing::Combine( ::testing::Values(InferenceEngine::Precision::FP32), ::testing::Values(CommonTestUtils::DEVICE_GNA), ::testing::ValuesIn(input_shapes), ::testing::ValuesIn(offsets), ::testing::ValuesIn(additional_config)), MultiCropsToConcatTest::getTestCaseName); } // namespace SubgraphTestsDefinitions
585
1,127
/* * 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 com.alipay.sofa.jraft.storage; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alipay.sofa.jraft.conf.Configuration; import com.alipay.sofa.jraft.conf.ConfigurationEntry; import com.alipay.sofa.jraft.conf.ConfigurationManager; import com.alipay.sofa.jraft.entity.EnumOutter; import com.alipay.sofa.jraft.entity.EnumOutter.EntryType; import com.alipay.sofa.jraft.entity.LogEntry; import com.alipay.sofa.jraft.entity.LogId; import com.alipay.sofa.jraft.entity.codec.LogEntryDecoder; import com.alipay.sofa.jraft.entity.codec.LogEntryEncoder; import com.alipay.sofa.jraft.option.LogStorageOptions; import com.alipay.sofa.jraft.option.StoreOptions; import com.alipay.sofa.jraft.storage.db.AbstractDB; import com.alipay.sofa.jraft.storage.db.AbstractDB.LogEntryIterator; import com.alipay.sofa.jraft.storage.db.ConfDB; import com.alipay.sofa.jraft.storage.db.IndexDB; import com.alipay.sofa.jraft.storage.db.SegmentLogDB; import com.alipay.sofa.jraft.storage.factory.LogStoreFactory; import com.alipay.sofa.jraft.storage.file.FileHeader; import com.alipay.sofa.jraft.storage.file.assit.FirstLogIndexCheckpoint; import com.alipay.sofa.jraft.storage.file.index.IndexFile.IndexEntry; import com.alipay.sofa.jraft.storage.file.index.IndexType; import com.alipay.sofa.jraft.util.OnlyForTest; import com.alipay.sofa.jraft.util.Pair; import com.alipay.sofa.jraft.util.Requires; import com.alipay.sofa.jraft.util.Utils; /** * A logStorage implemented by java * @author hzh (<EMAIL>) */ public class LogitLogStorage implements LogStorage { private static final Logger LOG = LoggerFactory.getLogger(LogitLogStorage.class); private static final String INDEX_STORE_PATH = "LogIndex"; private static final String SEGMENT_STORE_PATH = "LogSegment"; private static final String CONF_STORE_PATH = "LogConf"; private static final String FIRST_INDEX_CHECKPOINT = "FirstLogIndexCheckpoint"; private final FirstLogIndexCheckpoint firstLogIndexCheckpoint; private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock readLock = this.readWriteLock.readLock(); private final Lock writeLock = this.readWriteLock.writeLock(); private final StoreOptions storeOptions; private final String indexStorePath; private final String segmentStorePath; private final String confStorePath; private ConfigurationManager configurationManager; private LogEntryEncoder logEntryEncoder; private LogEntryDecoder logEntryDecoder; private SegmentLogDB segmentLogDB; private IndexDB indexDB; private ConfDB confDB; private LogStoreFactory logStoreFactory; public LogitLogStorage(final String path, final StoreOptions storeOptions) { this.indexStorePath = Paths.get(path, INDEX_STORE_PATH).toString(); this.segmentStorePath = Paths.get(path, SEGMENT_STORE_PATH).toString(); this.confStorePath = Paths.get(path, CONF_STORE_PATH).toString(); this.storeOptions = storeOptions; final String checkPointPath = Paths.get(path, FIRST_INDEX_CHECKPOINT).toString(); this.firstLogIndexCheckpoint = new FirstLogIndexCheckpoint(checkPointPath); } @Override public boolean init(final LogStorageOptions opts) { Requires.requireNonNull(opts.getConfigurationManager(), "Null conf manager"); Requires.requireNonNull(opts.getLogEntryCodecFactory(), "Null log entry codec factory"); this.writeLock.lock(); try { this.logEntryDecoder = opts.getLogEntryCodecFactory().decoder(); this.logEntryEncoder = opts.getLogEntryCodecFactory().encoder(); this.configurationManager = opts.getConfigurationManager(); // Create dbs and recover this.logStoreFactory = new LogStoreFactory(this.storeOptions); this.indexDB = new IndexDB(this.indexStorePath); this.segmentLogDB = new SegmentLogDB(this.segmentStorePath); this.confDB = new ConfDB(this.confStorePath); if (!(this.indexDB.init(this.logStoreFactory) && this.segmentLogDB.init(this.logStoreFactory) && this.confDB .init(this.logStoreFactory))) { LOG.warn("Init dbs failed when startup logitLogStorage"); return false; } this.firstLogIndexCheckpoint.load(); return recoverAndLoad(); } catch (final IOException e) { LOG.error("Error on load firstLogIndexCheckPoint", e); } finally { this.writeLock.unlock(); } return false; } public boolean recoverAndLoad() { this.writeLock.lock(); try { this.indexDB.recover(); this.segmentLogDB.recover(); this.confDB.recover(); // Check consistency if (!checkConsistencyAndAlignLog()) { LOG.warn("Check the consistency and align log failed"); return false; } // Load configuration to conf manager loadConfiguration(); // Set first log index if (!this.firstLogIndexCheckpoint.isInit()) { saveFirstLogIndex(this.indexDB.getFirstLogIndex()); } LOG.info("Recover dbs and start timingServer success, last recover index:{}", this.indexDB.getLastLogIndex()); return true; } catch (final Exception e) { LOG.error("Error on recover db", e); return false; } finally { this.writeLock.unlock(); } } /** * Check db's consistency and align the log; * @return true if align success; */ private boolean checkConsistencyAndAlignLog() { final long lastIndex = this.indexDB.getLastLogIndex(); final long lastSegmentIndex = this.segmentLogDB.getLastLogIndex(); final long lastConfIndex = this.confDB.getLastLogIndex(); if (lastIndex == lastSegmentIndex || lastIndex == lastConfIndex) { return true; } final long maxLogIndex = Math.max(lastSegmentIndex, lastConfIndex); if (lastIndex > maxLogIndex) { // In this case, just align indexDB to the index of max(lastSegmentIndex, lastConfIndex) return this.indexDB.truncateSuffix(maxLogIndex, 0); } else { // In this case, we should generate indexEntry array sorted by index from segmentDB and confDB, then // store indexEntry array to indexDB // Step1, lookup last (segment/conf) index in indexDB final Pair<IndexEntry, IndexEntry> lastIndexPair = this.indexDB.lookupLastLogIndexAndPosFromTail(); IndexEntry lastSegmentIndexInfo = lastIndexPair.getFirst(); IndexEntry lastConfIndexInfo = lastIndexPair.getSecond(); /** * There exists a bad case, for example * The index db has index entries 1 ~ 12, but all of the index entries are log index, don't contain conf index * The segmentLog db has logs 1 ~ 12 and 16 ~ 19, the conf db has logs 13 ~ 15. * So in this case, the lastConfIndexInfo will be null, but we should set it to the first log position */ if (lastSegmentIndexInfo == null) { lastSegmentIndexInfo = new IndexEntry(this.segmentLogDB.getFirstLogIndex(), FileHeader.HEADER_SIZE, IndexType.IndexSegment.getType()); } if (lastConfIndexInfo == null) { lastConfIndexInfo = new IndexEntry(this.confDB.getFirstLogIndex(), FileHeader.HEADER_SIZE, IndexType.IndexConf.getType()); } // Step2, Using two-way merging algorithm to construct ordered index entry array final LogEntryIterator segmentLogIterator = this.segmentLogDB.iterator(this.logEntryDecoder, lastSegmentIndexInfo.getLogIndex(), lastSegmentIndexInfo.getPosition()); final LogEntryIterator confLogIterator = this.confDB.iterator(this.logEntryDecoder, lastConfIndexInfo.getLogIndex(), lastConfIndexInfo.getPosition()); final List<IndexEntry> indexArray = generateOrderedIndexArrayByMergingLogIterator(segmentLogIterator, confLogIterator); // Step3, store array to indexDB long maxFlushPosition = this.indexDB.appendBatchIndexAsync(indexArray); // Step4, wait for flushing indexDB return this.indexDB.waitForFlush(maxFlushPosition, this.storeOptions.getMaxFlushTimes()); } } /** * Generate ordered index entry array by using tow-way merging algorithm * @param segmentLogIterator segment log iterator * @param confLogIterator conf log iterator * @return ordered index entry array */ public List<IndexEntry> generateOrderedIndexArrayByMergingLogIterator(final LogEntryIterator segmentLogIterator, final LogEntryIterator confLogIterator) { LogEntry segmentEntry = null, confEntry = null; int segmentPosition = -1, confPosition = -1; final List<IndexEntry> indexEntries = new ArrayList<>(); while (true) { // Pull next entry if (segmentEntry == null && segmentLogIterator != null && segmentLogIterator.hasNext()) { segmentEntry = segmentLogIterator.next(); segmentPosition = segmentLogIterator.getReadPosition(); } if (confEntry == null && confLogIterator != null && confLogIterator.hasNext()) { confEntry = confLogIterator.next(); confPosition = confLogIterator.getReadPosition(); } if (segmentEntry == null && confEntry == null) { break; } // Merge if (segmentEntry != null && confEntry != null) { if (segmentEntry.getId().getIndex() < confEntry.getId().getIndex()) { indexEntries.add(new IndexEntry(segmentEntry.getId().getIndex(), segmentPosition, IndexType.IndexSegment.getType())); segmentEntry = null; } else { indexEntries.add(new IndexEntry(confEntry.getId().getIndex(), confPosition, IndexType.IndexConf .getType())); confEntry = null; } } else { indexEntries.add(segmentEntry != null ? new IndexEntry(segmentEntry.getId().getIndex(), segmentPosition, IndexType.IndexSegment.getType()) : new IndexEntry(confEntry.getId().getIndex(), confPosition, IndexType.IndexConf.getType())); segmentEntry = confEntry = null; } } return indexEntries; } private boolean saveFirstLogIndex(final long logIndex) { try { this.firstLogIndexCheckpoint.setFirstLogIndex(logIndex); return this.firstLogIndexCheckpoint.save(); } catch (final IOException e) { LOG.error("Error when save first log index", e); return false; } } /** * Load configuration logEntries in confDB to configurationManager */ public void loadConfiguration() { final LogEntryIterator confIterator = this.confDB.iterator(this.logEntryDecoder); LogEntry entry; while ((entry = confIterator.next()) != null) { if (entry.getType() == EntryType.ENTRY_TYPE_CONFIGURATION) { final ConfigurationEntry confEntry = new ConfigurationEntry(); confEntry.setId(new LogId(entry.getId().getIndex(), entry.getId().getTerm())); confEntry.setConf(new Configuration(entry.getPeers(), entry.getLearners())); if (entry.getOldPeers() != null) { confEntry.setOldConf(new Configuration(entry.getOldPeers(), entry.getOldLearners())); } if (this.configurationManager != null) { this.configurationManager.add(confEntry); } } } } /**************************** Implementation ********************************/ @Override public long getFirstLogIndex() { this.readLock.lock(); try { if (this.firstLogIndexCheckpoint.firstLogIndex >= 0) { return this.firstLogIndexCheckpoint.firstLogIndex; } else if (this.indexDB.getFirstLogIndex() >= 0) { return this.indexDB.getFirstLogIndex(); } else { return 1L; } } finally { this.readLock.unlock(); } } @Override public long getLastLogIndex() { this.readLock.lock(); try { if (this.indexDB.getLastLogIndex() >= 0) { // Just use indexDB to get lastLogIndex return this.indexDB.getLastLogIndex(); } else { return 0; } } finally { this.readLock.unlock(); } } @Override public LogEntry getEntry(final long index) { this.readLock.lock(); try { if (index < getFirstLogIndex() || index > getLastLogIndex()) { return null; } final IndexEntry indexEntry = this.indexDB.lookupIndex(index); final int phyPosition = indexEntry.getPosition(); final byte logType = indexEntry.getLogType(); if (phyPosition != -1) { byte[] logBytes; if (logType == IndexType.IndexSegment.getType()) { logBytes = this.segmentLogDB.lookupLog(index, phyPosition); } else { logBytes = this.confDB.lookupLog(index, phyPosition); } if (logBytes != null) { return this.logEntryDecoder.decode(logBytes); } } } finally { this.readLock.unlock(); } return null; } @Override public long getTerm(final long index) { final LogEntry entry = getEntry(index); if (entry != null) { return entry.getId().getTerm(); } return 0; } @Override public boolean appendEntry(final LogEntry entry) { this.readLock.lock(); try { final long logIndex = entry.getId().getIndex(); final byte[] logData = this.logEntryEncoder.encode(entry); if (entry.getType() == EntryType.ENTRY_TYPE_CONFIGURATION) { return doAppendEntry(logIndex, logData, this.confDB, IndexType.IndexConf, true); } else { return doAppendEntry(logIndex, logData, this.segmentLogDB, IndexType.IndexSegment, true); } } finally { this.readLock.unlock(); } } @Override public int appendEntries(final List<LogEntry> entries) { this.readLock.lock(); try { int appendCount = 0; final int size = entries.size(); // Find last log and last conf log int lastLogIndex = -1; int lastConfIndex = -1; for (int i = entries.size() - 1; i >= 0; i--) { final LogEntry entry = entries.get(i); final boolean isConfEntry = (entry.getType() == EntryType.ENTRY_TYPE_CONFIGURATION); if (isConfEntry && lastConfIndex == -1) { lastConfIndex = i; } else if (!isConfEntry && lastLogIndex == -1) { lastLogIndex = i; } if (lastConfIndex >= 0 && lastLogIndex >= 0) { break; } } for (int i = 0; i < size; i++) { final boolean isWaitingFlush = (i == lastLogIndex || i == lastConfIndex); final LogEntry entry = entries.get(i); final long logIndex = entry.getId().getIndex(); final byte[] logData = this.logEntryEncoder.encode(entry); if (entry.getType() == EntryType.ENTRY_TYPE_CONFIGURATION) { if (doAppendEntry(logIndex, logData, this.confDB, IndexType.IndexConf, isWaitingFlush)) { appendCount++; } } else { if (doAppendEntry(logIndex, logData, this.segmentLogDB, IndexType.IndexSegment, isWaitingFlush)) { appendCount++; } } } return appendCount; } finally { this.readLock.unlock(); } } private boolean doAppendEntry(final long logIndex, final byte[] data, final AbstractDB logDB, final IndexType indexType, final boolean isWaitingFlush) { this.readLock.lock(); try { if (logDB == null || this.indexDB == null) { return false; } // Append log async , get position infos final Pair<Integer, Long> logPair = logDB.appendLogAsync(logIndex, data); if (logPair.getFirst() < 0 || logPair.getSecond() < 0) { return false; } final Pair<Integer, Long> indexPair = this.indexDB .appendIndexAsync(logIndex, logPair.getFirst(), indexType); if (indexPair.getFirst() < 0 || indexPair.getSecond() < 0) { return false; } // Save first log index if (!this.firstLogIndexCheckpoint.isInit()) { saveFirstLogIndex(logIndex); } if (isWaitingFlush) { return waitForFlush(logDB, logPair.getSecond(), indexPair.getSecond()); } return true; } finally { this.readLock.unlock(); } } private boolean waitForFlush(final AbstractDB logDB, final long exceptedLogPosition, final long exceptedIndexPosition) { final int maxFlushTimes = this.storeOptions.getMaxFlushTimes(); // We should flush log db first, because even If the power fails after flushing the log db // we can restore the index db based on the log db. if (!logDB.waitForFlush(exceptedLogPosition, maxFlushTimes)) { return false; } return this.indexDB.waitForFlush(exceptedIndexPosition, maxFlushTimes); } @Override public boolean truncatePrefix(final long firstIndexKept) { this.readLock.lock(); try { final boolean ret = saveFirstLogIndex(firstIndexKept); if (ret) { Utils.runInThread(() -> { this.indexDB.truncatePrefix(firstIndexKept); this.segmentLogDB.truncatePrefix(firstIndexKept); this.confDB.truncatePrefix(firstIndexKept); }); } return ret; } finally { this.readLock.unlock(); } } @Override public boolean truncateSuffix(final long lastIndexKept) { final Pair<Integer, Integer> posPair = this.indexDB.lookupFirstLogPosFromLogIndex(lastIndexKept + 1); final int SegmentTruncatePos = posPair.getFirst(); final int ConfLogTruncatePos = posPair.getSecond(); final int lastIndexKeptPos = this.indexDB.lookupIndex(lastIndexKept).getPosition(); if (lastIndexKeptPos != -1) { // Truncate indexDB this.indexDB.truncateSuffix(lastIndexKept, 0); // Truncate segmentDB this.segmentLogDB.truncateSuffix(lastIndexKept, SegmentTruncatePos); // Truncate confDB this.confDB.truncateSuffix(lastIndexKept, ConfLogTruncatePos); return this.indexDB.getLastLogIndex() == lastIndexKept; } return false; } @Override public boolean reset(final long nextLogIndex) { this.writeLock.lock(); try { LogEntry entry = getEntry(nextLogIndex); this.indexDB.reset(nextLogIndex); this.segmentLogDB.reset(nextLogIndex); this.confDB.reset(nextLogIndex); if (entry == null) { entry = new LogEntry(); entry.setType(EnumOutter.EntryType.ENTRY_TYPE_NO_OP); entry.setId(new LogId(nextLogIndex, 0)); } saveFirstLogIndex(-1); return appendEntry(entry); } finally { this.writeLock.unlock(); } } @Override public void shutdown() { this.writeLock.lock(); try { this.indexDB.shutdown(); this.segmentLogDB.shutdown(); this.confDB.shutdown(); } catch (final Exception e) { LOG.error("Error on shutdown dbs", e); } finally { this.writeLock.unlock(); } } @OnlyForTest public IndexDB getIndexDB() { return indexDB; } @OnlyForTest public ConfDB getConfDB() { return confDB; } @OnlyForTest public SegmentLogDB getSegmentLogDB() { return segmentLogDB; } }
10,240
1,502
#ifndef BOOST_NETWORK_UTILS_ITERATORS_TRANSFORM_WIDTH_WITH_STATE_HPP #define BOOST_NETWORK_UTILS_ITERATORS_TRANSFORM_WIDTH_WITH_STATE_HPP #include <boost/serialization/pfto.hpp> #include <boost/iterator/iterator_adaptor.hpp> #include <boost/iterator/iterator_traits.hpp> #include <algorithm> // The class transform_width_with_state works like transform_width from // boost/archive/iterators if the collection of input values can be converted // to the output without padding the input with zeros. (The total input bit // count is divisible by the bit size of an output value.) It it cannot, the // partially encoded last value, which would have to be padded with zero, // is stored to the transform_width_state, which can be used later to // continue the encoding when another chunk of input values is available. // The end iterator is needed to detect the end transformation. // // The encoding state and the end iterator are owned by the transforming // iterator and they have to be passed to its constructor. Iterator adaptors // need to propagate the state and the end iterator to the transforming // iterator's constructor, which is inconvenient. namespace boost { namespace network { namespace utils { namespace iterators { template <class Value, int BitsOut, int BitsIn> class transform_width_state { public: typedef Value value_type; transform_width_state() : m_displacement(0) {} transform_width_state(transform_width_state const &source) : m_displacement(source.m_displacement), m_buffer(source.m_buffer) {} bool empty() const { return bit_count() == 0; } void clear() { m_displacement = 0; } protected: unsigned short bit_count() const { return m_displacement > 0 ? BitsIn - m_displacement : 0; } private: unsigned short m_displacement; value_type m_buffer; template <class Base, int BitsOut2, int BitsIn2, class Char, class State> friend class transform_width_with_state; }; template <class Base, int BitsOut, int BitsIn, class Char = typename boost::iterator_value<Base>::type, // output character class State = transform_width_state< typename iterator_value<Base>::type, BitsOut, BitsIn> > class transform_width_with_state : public boost::iterator_adaptor< transform_width_with_state<Base, BitsOut, BitsIn, Char>, Base, Char, single_pass_traversal_tag, Char> { friend class boost::iterator_core_access; typedef typename boost::iterator_adaptor< transform_width_with_state<Base, BitsOut, BitsIn, Char>, Base, Char, single_pass_traversal_tag, Char> super_t; typedef transform_width_with_state<Base, BitsOut, BitsIn, Char> this_t; typedef typename iterator_value<Base>::type base_value_type; Char fill(); Char dereference_impl() { if (!m_full) { m_current_value = fill(); m_full = true; } return m_current_value; } Char dereference() const { return const_cast<this_t *>(this)->dereference_impl(); } bool equal(const this_t &rhs) const { return this->base_reference() == rhs.base_reference(); } void increment() { m_displacement += BitsOut; while (m_displacement >= BitsIn) { m_displacement -= BitsIn; if (0 == m_displacement) m_bufferfull = false; if (!m_bufferfull) ++this->base_reference(); } // detect if the number of bits in the m_buffer is not enough // to encode a full 6-bit unit - read the next byte from the input if (m_displacement >= 0 && BitsIn - m_displacement < BitsOut) { // the following condition is compilable only with this variable typename this_t::base_type const &end_ = this->end(); if (this->base_reference() != end_) { // read the next byte from the input or make it zero to // provide padding to encode th elast byte m_next_buffer = ++this->base_reference() != end_ ? *this->base_reference() : 0; m_nextfull = true; } // store the encoding state if we encountered the last byte if (this->base_reference() == end_) { State &state = this->state(); state.m_displacement = m_displacement; state.m_buffer = m_buffer; } } m_full = false; } Base const &end() const { return m_end; } State const &state() const { return *m_state; } State &state() { return *m_state; } // iterator end for the iterator start sent to the constructor Base m_end; // encoding state to use and update State *m_state; // the most recent encoded character Char m_current_value; // number of bits left in current input character buffer unsigned int m_displacement; // value to be just encoded and a next value to be encoded base_value_type m_buffer, m_next_buffer; // flag to current output character is ready - just used to save time bool m_full; // flag to indicate that m_buffer and/or m_nextbuffer have data bool m_bufferfull, m_nextfull; public: template <class T> transform_width_with_state(BOOST_PFTO_WRAPPER(T) start, BOOST_PFTO_WRAPPER(T) end, State &state) : super_t(Base(BOOST_MAKE_PFTO_WRAPPER(static_cast<T>(start)))), m_end(end), m_state(&state), m_displacement(0), m_full(false), m_bufferfull(false), m_nextfull(false) {} template <class T> transform_width_with_state(BOOST_PFTO_WRAPPER(T) start) : super_t(Base(BOOST_MAKE_PFTO_WRAPPER(static_cast<T>(start)))), m_displacement(0), m_full(false), m_bufferfull(false), m_nextfull(false) {} transform_width_with_state(const transform_width_with_state &rhs) : super_t(rhs.base_reference()), m_end(rhs.m_end), m_state(rhs.m_state), m_current_value(rhs.m_current_value), m_displacement(rhs.m_displacement), m_buffer(rhs.m_buffer), m_next_buffer(rhs.m_next_buffer), m_full(rhs.m_full), m_bufferfull(rhs.m_bufferfull), m_nextfull(rhs.m_nextfull) {} }; template <class Base, int BitsOut, int BitsIn, class Char, class State> Char transform_width_with_state<Base, BitsOut, BitsIn, Char, State>::fill() { State &state = this->state(); if (!state.empty()) { // initialize the m_buffer from the state and put the current input // byte to the m_next_buffer to make it follow right after m_displacement = state.m_displacement; m_buffer = state.m_buffer; m_bufferfull = true; m_next_buffer = *this->base_reference(); m_nextfull = true; state.clear(); } Char retval = 0; unsigned int missing_bits = BitsOut; for (;;) { unsigned int bcount; if (!m_bufferfull) { // fill the current m_buffer firstly from m_next_buffer if // available then read the input sequence if (m_nextfull) { m_buffer = m_next_buffer; m_nextfull = false; } else { m_buffer = *this->base_reference(); } m_bufferfull = true; bcount = BitsIn; } else bcount = BitsIn - m_displacement; unsigned int i = (std::min)(bcount, missing_bits); // shift interesting bits to least significant position unsigned int j = m_buffer >> (bcount - i); // strip off uninteresting bits // (note presumption of two's complement arithmetic) j &= ~(-(1 << i)); // append then interesting bits to the output value retval <<= i; retval |= j; missing_bits -= i; if (0 == missing_bits) break; // if we used a byte from the input sequence and not from the // prepared m_next_buffer, advance the input sequence iterator if (!m_nextfull) ++this->base_reference(); m_bufferfull = false; } return retval; } } // namespace iterators } // namespace utils } // namespace network } // namespace boost #endif // BOOST_NETWORK_UTILS_ITERATORS_TRANSFORM_WIDTH_WITH_STATE_HPP
2,933
3,631
<filename>drools-examples/src/main/java/org/drools/benchmark/waltzdb/EdgeLabel.java /* * Copyright 2010 Red Hat, Inc. 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. */ package org.drools.benchmark.waltzdb; //(literalize edge_label p1 p2 l_name l_id) public class EdgeLabel { private int p1; private int p2; private String labelName; private String labelId; public EdgeLabel() { super(); } public EdgeLabel(int p1, int p2, String labelName, String labelId) { super(); this.p1 = p1; this.p2 = p2; this.labelName = labelName; this.labelId = labelId; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((labelId == null) ? 0 : labelId.hashCode()); result = PRIME * result + ((labelName == null) ? 0 : labelName.hashCode()); result = PRIME * result + p1; result = PRIME * result + p2; return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final EdgeLabel other = (EdgeLabel) obj; if (labelId == null) { if (other.labelId != null) return false; } else if (!labelId.equals(other.labelId)) return false; if (labelName == null) { if (other.labelName != null) return false; } else if (!labelName.equals(other.labelName)) return false; if (p1 != other.p1) return false; if (p2 != other.p2) return false; return true; } public String getLabelId() { return labelId; } public void setLabelId(String labelId) { this.labelId = labelId; } public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } public int getP1() { return p1; } public void setP1(int p1) { this.p1 = p1; } public int getP2() { return p2; } public void setP2(int p2) { this.p2 = p2; } }
1,202
432
<filename>app/src/main/java/tk/wasdennnoch/androidn_ify/systemui/qs/tiles/BaseTile.java package tk.wasdennnoch.androidn_ify.systemui.qs.tiles; import android.annotation.CallSuper; import android.content.Context; import android.view.View; import de.robv.android.xposed.XposedHelpers; import tk.wasdennnoch.androidn_ify.XposedHook; import tk.wasdennnoch.androidn_ify.systemui.qs.KeyguardMonitor; import tk.wasdennnoch.androidn_ify.systemui.qs.QSTileHostHooks; import tk.wasdennnoch.androidn_ify.systemui.qs.TilesManager; public abstract class BaseTile implements KeyguardMonitor.Callback { private static final String TAG = "BaseTile"; public static final String TILE_KEY_NAME = "customTileKey"; public static final String CLASS_TILE_STATE = "com.android.systemui.qs.QSTile.State"; private TilesManager mTilesManager; Object mHost; protected Context mContext; KeyguardMonitor mKeyguard; String mKey; Object mTile; boolean mSecure = false; /** * ALWAYS CALL {@link #registerCallbacks()} AS THHE LAST LINE OF THE OVERRIDDEN CONSTRUCTOR * If for some reason the tile creation fails the callbacks will already be registered leading to * a ghost tile which eats memory and logs a crash when a callback is received. Add the callbacks * last so they won't get registered if something crashes. */ BaseTile(TilesManager tilesManager, Object host, String key) { mTilesManager = tilesManager; mHost = host; mContext = (Context) XposedHelpers.callMethod(mHost, "getContext"); mKeyguard = QSTileHostHooks.mKeyguard; mKey = key; } /** * ALWAYS CALL THIS METHOD AS THHE LAST LINE OF THE OVERRIDDEN CONSTRUCTOR */ void registerCallbacks() { mKeyguard.addCallback(this); mTilesManager.registerTile(this); } public Object getTile() { return mTile; } public String getKey() { return mKey; } public abstract void handleUpdateState(Object state, Object arg); public void onCreateTileView(View tileView) { XposedHelpers.setAdditionalInstanceField(tileView, TILE_KEY_NAME, mKey); } public View onCreateIcon() { return null; } @CallSuper public void handleDestroy() { setListening(false); mTilesManager.unregisterTile(this); mTilesManager = null; mTile = null; mHost = null; mContext = null; mKeyguard.removeCallback(this); mKeyguard = null; } public Object getDetailAdapter() { return null; } public boolean handleClickInner() { handleClick(); return false; } public void handleClick() { } public void handleLongClick() { } public void setListening(boolean listening) { } public void setSecure(boolean secure) { mSecure = secure; } @Override public void onKeyguardChanged() { refreshState(); } void refreshState() { try { XposedHelpers.callMethod(mTile, "refreshState"); } catch (Throwable t) { XposedHook.logE(TAG, "Error refreshing tile state: ", t); } } }
1,248
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Vexatious", "definitions": [ "Causing or tending to cause annoyance, frustration, or worry.", "Denoting an action or the bringer of an action that is brought without sufficient grounds for winning, purely to cause annoyance to the defendant." ], "parts-of-speech": "Adjective" }
122
765
<gh_stars>100-1000 """ Test lldb breakpoint command for CPP methods & functions in a namespace. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class CPPBreakpointCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def make_breakpoint(self, name, type, expected_num_locations): bkpt = self.target.BreakpointCreateByName(name, type, self.a_out_module, self.nested_comp_unit) num_locations = bkpt.GetNumLocations() self.assertTrue( num_locations == expected_num_locations, "Wrong number of locations for '%s', expected: %d got: %d" % (name, expected_num_locations, num_locations)) return bkpt def test_cpp_breakpoint_cmds(self): """Test a sequence of breakpoint command add, list, and delete.""" self.build() exe = self.getBuildArtifact("a.out") # Create a target from the debugger. self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) self.a_out_module = lldb.SBFileSpecList() self.a_out_module.Append(lldb.SBFileSpec(exe)) self.nested_comp_unit = lldb.SBFileSpecList() self.nested_comp_unit.Append(lldb.SBFileSpec("nested.cpp")) # First provide ONLY the method name. This should get everybody... self.make_breakpoint("Function", lldb.eFunctionNameTypeAuto, 5) # Now add the Baz class specifier. This should get the version contained in Bar, # AND the one contained in :: self.make_breakpoint("Baz::Function", lldb.eFunctionNameTypeAuto, 2) # Then add the Bar::Baz specifier. This should get the version # contained in Bar only self.make_breakpoint("Bar::Baz::Function", lldb.eFunctionNameTypeAuto, 1) self.make_breakpoint("Function", lldb.eFunctionNameTypeMethod, 3) self.make_breakpoint("Baz::Function", lldb.eFunctionNameTypeMethod, 2) self.make_breakpoint("Bar::Baz::Function", lldb.eFunctionNameTypeMethod, 1) self.make_breakpoint("Function", lldb.eFunctionNameTypeBase, 2) self.make_breakpoint("Bar::Function", lldb.eFunctionNameTypeBase, 1)
1,550
2,538
""" The Gumbell distribution, results ================================= Generate the exercise results on the Gumbell distribution """ import numpy as np import matplotlib.pyplot as plt years_nb = 21 wspeeds = np.load('sprog-windspeeds.npy') max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) plt.figure() plt.bar(np.arange(years_nb) + 1, max_speeds) plt.axis('tight') plt.xlabel('Year') plt.ylabel('Annual wind speed maxima [$m/s$]')
172
739
import subprocess import os import sys if __name__ == "__main__": # Until below works sys.exit(0) cmd = ["python", "-m", "tox", "-c", "tox-performance.ini"] uri = "%s://%s:%s" % ( os.environ["TEST_NEO4J_SCHEME"], os.environ["TEST_NEO4J_HOST"], os.environ["TEST_NEO4J_PORT"]) env = { "NEO4J_USER": os.environ["TEST_NEO4J_USER"], "NEO4J_PASSWORD": os.environ["TEST_NEO4J_PASS"], "NEO4J_URI": uri} subprocess.check_call(cmd, universal_newlines=True, stderr=subprocess.STDOUT, env=env)
332
1,953
<gh_stars>1000+ #include <wil/com.h> #include <wil/result.h> #if (NTDDI_VERSION >= NTDDI_WIN8) #include <wil/result_originate.h> #endif #include <roerrorapi.h> #include "common.h" static volatile long objectCount = 0; struct SharedObject { SharedObject() { ::InterlockedIncrement(&objectCount); } ~SharedObject() { ::InterlockedDecrement(&objectCount); } void ProcessShutdown() { } int value{}; }; TEST_CASE("ResultTests::SemaphoreValue", "[result]") { auto TestValue = [&](auto start, auto end) { wil::details_abi::SemaphoreValue semaphore; for (auto index = start; index <= end; index++) { semaphore.Destroy(); REQUIRE(SUCCEEDED(semaphore.CreateFromValue(L"test", index))); auto num1 = index; auto num2 = index; REQUIRE(SUCCEEDED(semaphore.TryGetValue(L"test", &num1))); REQUIRE(SUCCEEDED(semaphore.TryGetValue(L"test", &num2))); REQUIRE(num1 == index); REQUIRE(num2 == index); } }; // Test 32-bit values (edge cases) TestValue(0u, 10u); TestValue(250u, 260u); TestValue(0x7FFFFFF0u, 0x7FFFFFFFu); // Test 64-bit values (edge cases) TestValue(0ull, 10ull); TestValue(250ull, 260ull); TestValue(0x000000007FFFFFF0ull, 0x000000008000000Full); TestValue(0x00000000FFFFFFF0ull, 0x000000010000000Full); TestValue(0x00000000FFFFFFF0ull, 0x000000010000000Full); TestValue(0x3FFFFFFFFFFFFFF0ull, 0x3FFFFFFFFFFFFFFFull); // Test pointer values wil::details_abi::SemaphoreValue semaphore; void* address = &semaphore; REQUIRE(SUCCEEDED(semaphore.CreateFromPointer(L"test", address))); void* ptr; REQUIRE(SUCCEEDED(semaphore.TryGetPointer(L"test", &ptr))); REQUIRE(ptr == address); } TEST_CASE("ResultTests::ProcessLocalStorage", "[result]") { // Test process local storage memory and ref-counting { wil::details_abi::ProcessLocalStorage<SharedObject> obj1("ver1"); wil::details_abi::ProcessLocalStorage<SharedObject> obj2("ver1"); auto& o1 = *obj1.GetShared(); auto& o2 = *obj2.GetShared(); REQUIRE(o1.value == 0); REQUIRE(o2.value == 0); o1.value = 42; REQUIRE(o2.value == 42); REQUIRE(objectCount == 1); wil::details_abi::ProcessLocalStorage<SharedObject> obj3("ver3"); auto& o3 = *obj3.GetShared(); REQUIRE(o3.value == 0); REQUIRE(objectCount == 2); } REQUIRE(objectCount == 0); } #ifdef WIL_ENABLE_EXCEPTIONS #pragma warning(push) #pragma warning(disable: 4702) // Unreachable code TEST_CASE("ResultTests::ExceptionHandling", "[result]") { witest::TestFailureCache failures; SECTION("Test 'what()' implementation on ResultException") { auto swap = witest::AssignTemporaryValue(&wil::g_fResultThrowPlatformException, false); try { THROW_HR(E_INVALIDARG); FAIL("Expected an exception"); } catch (const std::exception& exception) { REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == E_INVALIDARG); auto what = exception.what(); REQUIRE((what && *what)); REQUIRE(strstr(what, "Exception") != nullptr); } } failures.clear(); SECTION("Test messaging from an unhandled std exception") { // #pragma warning(suppress: 28931) // unused assignment -- it IS being used... seems like a tool issue. auto hr = []() { try { throw std::runtime_error("runtime"); } catch (...) { RETURN_CAUGHT_EXCEPTION(); } }(); REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION)); REQUIRE(wcsstr(failures[0].pszMessage, L"runtime") != nullptr); // should get the exception what() string... REQUIRE(hr == HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION)); } failures.clear(); SECTION("Test messaging from bad_alloc") { auto hr = []() -> HRESULT { try { throw std::bad_alloc(); } catch (...) { RETURN_CAUGHT_EXCEPTION(); } }(); REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == E_OUTOFMEMORY); REQUIRE(wcsstr(failures[0].pszMessage, L"alloc") != nullptr); // should get the exception what() string... REQUIRE(hr == E_OUTOFMEMORY); } failures.clear(); SECTION("Test messaging from a WIL exception") { auto hr = []() -> HRESULT { try { THROW_HR(E_INVALIDARG); } catch (...) { RETURN_CAUGHT_EXCEPTION(); } return S_OK; }(); REQUIRE(failures.size() == 2); REQUIRE(failures[0].hr == E_INVALIDARG); REQUIRE(failures[0].pszMessage == nullptr); REQUIRE(failures[1].hr == E_INVALIDARG); REQUIRE(wcsstr(failures[1].pszMessage, L"Exception") != nullptr); // should get the exception debug string... REQUIRE(hr == E_INVALIDARG); } failures.clear(); SECTION("Fail fast an unknown exception") { REQUIRE(witest::DoesCodeCrash([]() { try { throw E_INVALIDARG; // bad throw... (long) } catch (...) { RETURN_CAUGHT_EXCEPTION(); } })); } failures.clear(); SECTION("Log test (returns hr)") { HRESULT hr = S_OK; try { throw std::bad_alloc(); } catch (...) { hr = LOG_CAUGHT_EXCEPTION(); auto hrDirect = wil::ResultFromCaughtException(); REQUIRE(hr == hrDirect); } REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == E_OUTOFMEMORY); REQUIRE(wcsstr(failures[0].pszMessage, L"alloc") != nullptr); // should get the exception what() string... REQUIRE(hr == E_OUTOFMEMORY); } failures.clear(); SECTION("Fail-fast test") { REQUIRE_CRASH([]() { try { throw std::bad_alloc(); } catch (...) { FAIL_FAST_CAUGHT_EXCEPTION(); } }()); } failures.clear(); SECTION("Exception test (different exception type thrown...)") { auto swap = witest::AssignTemporaryValue(&wil::g_fResultThrowPlatformException, false); size_t line = 0; try { try { throw std::bad_alloc(); } catch (...) { line = __LINE__; THROW_NORMALIZED_CAUGHT_EXCEPTION(); } } catch (const wil::ResultException& exception) { REQUIRE(exception.GetFailureInfo().uLineNumber == line); // should have thrown new, so we should have the rethrow line number REQUIRE(exception.GetErrorCode() == E_OUTOFMEMORY); } catch (...) { FAIL(); } REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == E_OUTOFMEMORY); REQUIRE(wcsstr(failures[0].pszMessage, L"alloc") != nullptr); // should get the exception what() string... } failures.clear(); SECTION("Exception test (rethrow same exception type...)") { auto swap = witest::AssignTemporaryValue(&wil::g_fResultThrowPlatformException, false); size_t line = 0; try { try { line = __LINE__; THROW_HR(E_OUTOFMEMORY); } catch (...) { THROW_NORMALIZED_CAUGHT_EXCEPTION(); } } catch (const wil::ResultException& exception) { REQUIRE(exception.GetFailureInfo().uLineNumber == line); // should have re-thrown the original exception (with the original line number) } catch (...) { FAIL(); } } failures.clear(); SECTION("Test catch message") { try { throw std::bad_alloc(); } catch (...) { LOG_CAUGHT_EXCEPTION_MSG("train: %d", 42); } REQUIRE(failures.size() == 1); REQUIRE(failures[0].hr == E_OUTOFMEMORY); REQUIRE(wcsstr(failures[0].pszMessage, L"alloc") != nullptr); // should get the exception what() string... REQUIRE(wcsstr(failures[0].pszMessage, L"train") != nullptr); // should *also* get the message... REQUIRE(wcsstr(failures[0].pszMessage, L"42") != nullptr); } failures.clear(); SECTION("Test messaging from a WIL exception") { auto hr = []() -> HRESULT { try { throw std::bad_alloc(); } catch (...) { RETURN_CAUGHT_EXCEPTION_EXPECTED(); } }(); REQUIRE(failures.size() == 0); REQUIRE(hr == E_OUTOFMEMORY); } failures.clear(); SECTION("Test ResultFromException...") { auto hrOk = wil::ResultFromException([&] { }); REQUIRE(hrOk == S_OK); auto hr = wil::ResultFromException([&] { throw std::bad_alloc(); }); REQUIRE(failures.size() == 0); REQUIRE(hr == E_OUTOFMEMORY); } failures.clear(); SECTION("Explicit failfast for unrecognized") { REQUIRE_CRASH(wil::ResultFromException([&] { throw E_FAIL; })); } failures.clear(); SECTION("Manual debug-only validation of the SEH failfast") { auto hr1 = wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, [&]() { // Uncomment to test SEH fail-fast // throw E_FAIL; }); REQUIRE(hr1 == S_OK); auto hr2 = wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, wil::SupportedExceptions::Thrown, [&] { // Uncomment to test SEH fail-fast // throw std::range_error("range"); }); REQUIRE(hr2 == S_OK); wil::FailFastException(WI_DIAGNOSTICS_INFO, [&] { // Uncomment to test SEH fail-fast // THROW_HR(E_FAIL); }); } failures.clear(); SECTION("Standard") { auto line = __LINE__; auto hr = wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, [&] { THROW_HR(E_INVALIDARG); }); REQUIRE(failures.size() == 2); REQUIRE(static_cast<decltype(line)>(failures[1].uLineNumber) == line); REQUIRE(hr == E_INVALIDARG); } failures.clear(); SECTION("bad_alloc") { auto hr = wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, [&] { throw std::bad_alloc(); }); REQUIRE(failures.size() == 1); REQUIRE(hr == E_OUTOFMEMORY); } failures.clear(); SECTION("std::exception") { auto hr = wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, [&] { throw std::range_error("range"); }); REQUIRE(failures.size() == 1); REQUIRE(wcsstr(failures[0].pszMessage, L"range") != nullptr); REQUIRE(hr == HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION)); } } void ExceptionHandlingCompilationTest() { []{ try { throw std::bad_alloc(); } CATCH_RETURN(); }(); []{ try { throw std::bad_alloc(); } CATCH_RETURN_MSG("train: %d", 42); }(); []{ try { throw std::bad_alloc(); } CATCH_RETURN_EXPECTED(); }(); []{ try { throw std::bad_alloc(); } catch (...) { RETURN_CAUGHT_EXCEPTION(); } }(); []{ try { throw std::bad_alloc(); } catch (...) { RETURN_CAUGHT_EXCEPTION_MSG("train: %d", 42); } }(); []{ try { throw std::bad_alloc(); } catch (...) { RETURN_CAUGHT_EXCEPTION_EXPECTED(); } }(); try { throw std::bad_alloc(); } CATCH_LOG(); try { throw std::bad_alloc(); } CATCH_LOG_MSG("train: %d", 42); try { throw std::bad_alloc(); } catch (...) { LOG_CAUGHT_EXCEPTION(); } try { throw std::bad_alloc(); } catch (...) { LOG_CAUGHT_EXCEPTION_MSG("train: %d", 42); } try { throw std::bad_alloc(); } CATCH_FAIL_FAST(); try { throw std::bad_alloc(); } CATCH_FAIL_FAST_MSG("train: %d", 42); try { throw std::bad_alloc(); } catch (...) { FAIL_FAST_CAUGHT_EXCEPTION(); } try { throw std::bad_alloc(); } catch (...) { FAIL_FAST_CAUGHT_EXCEPTION_MSG("train: %d", 42); } try { try { throw std::bad_alloc(); } CATCH_THROW_NORMALIZED(); } catch (...) {} try { try { throw std::bad_alloc(); } CATCH_THROW_NORMALIZED_MSG("train: %d", 42); } catch (...) {} try { try { throw std::bad_alloc(); } catch (...) { THROW_NORMALIZED_CAUGHT_EXCEPTION(); } } catch (...) {} try { try { throw std::bad_alloc(); } catch (...) { THROW_NORMALIZED_CAUGHT_EXCEPTION_MSG("train: %d", 42); } } catch (...) {} wil::ResultFromExceptionDebug(WI_DIAGNOSTICS_INFO, wil::SupportedExceptions::All, [&] { THROW_HR(E_FAIL); }); wil::ResultFromException(WI_DIAGNOSTICS_INFO, wil::SupportedExceptions::None, [&] { }); wil::ResultFromException([&] { }); wil::FailFastException(WI_DIAGNOSTICS_INFO, [&] { }); } #pragma warning(pop) #endif TEST_CASE("ResultTests::ErrorMacros", "[result]") { REQUIRE_ERROR(FAIL_FAST()); REQUIRE_ERROR(FAIL_FAST_IF(true)); REQUIRE_ERROR(FAIL_FAST_IF_NULL(nullptr)); REQUIRE_NOERROR(FAIL_FAST_IF(false)); REQUIRE_NOERROR(FAIL_FAST_IF_NULL(_ReturnAddress())); REQUIRE_ERROR(FAIL_FAST_MSG("%d", 42)); REQUIRE_ERROR(FAIL_FAST_IF_MSG(true, "%d", 42)); REQUIRE_ERROR(FAIL_FAST_IF_NULL_MSG(nullptr, "%d", 42)); REQUIRE_NOERROR(FAIL_FAST_IF_MSG(false, "%d", 42)); REQUIRE_NOERROR(FAIL_FAST_IF_NULL_MSG(_ReturnAddress(), "%d", 42)); //wil::g_pfnResultLoggingCallback = ResultMacrosLoggingCallback; SetLastError(ERROR_PRINTER_ALREADY_EXISTS); REQUIRE_ERROR(__FAIL_FAST_ASSERT_WIN32_BOOL_FALSE__(FALSE)); REQUIRE_NOERROR(__FAIL_FAST_ASSERT_WIN32_BOOL_FALSE__(TRUE)); } // The originate helper isn't compatible with CX so don't test it in that mode. #if !defined(__cplusplus_winrt) && (NTDDI_VERSION >= NTDDI_WIN8) TEST_CASE("ResultTests::NoOriginationByDefault", "[result]") { ::wil::SetOriginateErrorCallback(nullptr); wil::com_ptr_nothrow<IRestrictedErrorInfo> restrictedErrorInformation; // We can't guarantee test order, so clear the error payload prior to starting SetRestrictedErrorInfo(nullptr); []() -> HRESULT { RETURN_HR(S_OK); }(); REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); #ifdef WIL_ENABLE_EXCEPTIONS try { THROW_HR(E_FAIL); } catch (...) {} REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); #endif // WIL_ENABLE_EXCEPTIONS []() -> HRESULT { RETURN_HR(E_FAIL); }(); REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); []() -> HRESULT { RETURN_IF_FAILED_EXPECTED(E_ACCESSDENIED); return S_OK; }(); REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); } TEST_CASE("ResultTests::AutomaticOriginationOnFailure", "[result]") { ::wil::SetOriginateErrorCallback(::wil::details::RaiseRoOriginateOnWilExceptions); wil::com_ptr_nothrow<IRestrictedErrorInfo> restrictedErrorInformation; // Make sure we don't start with an error payload SetRestrictedErrorInfo(nullptr); // Success codes shouldn't originate. []() { RETURN_HR(S_OK); }(); REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); auto validateOriginatedError = [&](HRESULT hrExpected) { wil::unique_bstr descriptionUnused; HRESULT existingHr = S_OK; wil::unique_bstr restrictedDescriptionUnused; wil::unique_bstr capabilitySidUnused; REQUIRE_SUCCEEDED(restrictedErrorInformation->GetErrorDetails(&descriptionUnused, &existingHr, &restrictedDescriptionUnused, &capabilitySidUnused)); REQUIRE(hrExpected == existingHr); }; #ifdef WIL_ENABLE_EXCEPTIONS // Throwing an error should originate. constexpr HRESULT thrownErrorCode = TYPE_E_ELEMENTNOTFOUND; try { THROW_HR(thrownErrorCode); } catch (...) {} REQUIRE(S_OK == GetRestrictedErrorInfo(&restrictedErrorInformation)); validateOriginatedError(thrownErrorCode); #endif // WIL_ENABLE_EXCEPTIONS // Returning an error code should originate. static constexpr HRESULT returnedErrorCode = REGDB_E_CLASSNOTREG; []() { RETURN_HR(returnedErrorCode); }(); REQUIRE(S_OK == GetRestrictedErrorInfo(&restrictedErrorInformation)); validateOriginatedError(returnedErrorCode); // _EXPECTED errors should NOT originate. static constexpr HRESULT expectedErrorCode = E_ACCESSDENIED; []() { RETURN_IF_FAILED_EXPECTED(expectedErrorCode); return S_OK; }(); REQUIRE(S_FALSE == GetRestrictedErrorInfo(&restrictedErrorInformation)); } #endif
8,787
1,056
<filename>profiler/profiler.ppoints/src/org/netbeans/modules/profiler/ppoints/ui/icons/ProfilingPointsIconsProviderImpl.java /* * 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.profiler.ppoints.ui.icons; import java.util.Map; import org.netbeans.modules.profiler.spi.IconsProvider; import org.openide.util.lookup.ServiceProvider; /** * * @author <NAME> */ @ServiceProvider(service=IconsProvider.class) public final class ProfilingPointsIconsProviderImpl extends IconsProvider.Basic { @Override protected final void initStaticImages(Map<String, String> cache) { cache.put(ProfilingPointsIcons.CODE, "codeProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.GLOBAL, "globalProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.LOAD_GENERATOR, "loadgenProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.LOAD_GENERATOR_DISABLED, "loadgenProfilingPointD.png"); // NOI18N cache.put(ProfilingPointsIcons.PPOINT, "ppoint.png"); // NOI18N cache.put(ProfilingPointsIcons.ADD, "ppointAdd.png"); // NOI18N cache.put(ProfilingPointsIcons.EDIT, "ppointEdit.png"); // NOI18N cache.put(ProfilingPointsIcons.ENABLE_DISABLE, "ppointEnableDisable.png"); // NOI18N cache.put(ProfilingPointsIcons.REMOVE, "ppointRemove.png"); // NOI18N cache.put(ProfilingPointsIcons.RESET_RESULTS, "resetResultsProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.RESET_RESULTS_DISABLED, "resetResultsProfilingPointD.png"); // NOI18N cache.put(ProfilingPointsIcons.STOPWATCH, "stopwatchProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.STOPWATCH_DISABLED, "stopwatchProfilingPointD.png"); // NOI18N cache.put(ProfilingPointsIcons.TAKE_SNAPSHOT, "takeSnapshotProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.TAKE_SNAPSHOT_DISABLED, "takeSnapshotProfilingPointD.png"); // NOI18N cache.put(ProfilingPointsIcons.TAKE_SNAPSHOT_TIMED, "timedTakeSnapshotProfilingPoint.png"); // NOI18N cache.put(ProfilingPointsIcons.TAKE_SNAPSHOT_TRIGGERED, "triggeredTakeSnapshotProfilingPoint.png"); // NOI18N } }
1,047
190,993
<filename>tensorflow/core/framework/logging.cc /* Copyright 2019 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 "tensorflow/core/framework/logging.h" #include <iostream> #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" namespace tensorflow { namespace logging { typedef std::vector<void (*)(const char*)> Listeners; Listeners* GetListeners() { static Listeners* listeners = new Listeners; return listeners; } bool RegisterListener(void (*listener)(const char*)) { GetListeners()->push_back(listener); return true; } bool LogToListeners(string msg, string end) { auto listeners = logging::GetListeners(); if (listeners->empty()) { return false; } string ended_msg = strings::StrCat(msg, end); for (auto& listener : *listeners) { listener(ended_msg.c_str()); } return true; } } // end namespace logging } // end namespace tensorflow
451
3,301
<reponame>starburst-project/Alink<filename>core/src/main/java/com/alibaba/alink/operator/common/tensorflow/TFSavedModelConstants.java package com.alibaba.alink.operator.common.tensorflow; public class TFSavedModelConstants { public static final String MODEL_PATH_KEY = "model_path"; public static final String GRAPH_DEF_TAG_KEY = "graph_def_tag"; public static final String SIGNATURE_DEF_KEY_KEY = "signature_def_key"; public static final String INPUT_SIGNATURE_DEFS_KEY = "input_signature_defs"; public static final String OUTPUT_SIGNATURE_DEFS_KEY = "output_signature_defs"; public static final String OUTPUT_TYPE_CLASSES = "output_type_classes"; public static final String INTRA_OP_PARALLELISM_KEY = "intra_op_parallelism"; public static final String INTER_OP_PARALLELISM_KEY = "inter_op_parallelism"; public static final String OUTPUT_BATCH_AXES = "output_batch_axes"; }
294
682
/**CFile**************************************************************** FileName [fraMan.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [New FRAIG package.] Synopsis [Starts the FRAIG manager.] Author [<NAME>] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 30, 2007.] Revision [$Id: fraMan.c,v 1.00 2007/06/30 00:00:00 alanmi Exp $] ***********************************************************************/ #include "fra.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Sets the default solving parameters.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ParamsDefault( Fra_Par_t * pPars ) { memset( pPars, 0, sizeof(Fra_Par_t) ); pPars->nSimWords = 32; // the number of words in the simulation info pPars->dSimSatur = 0.005; // the ratio of refined classes when saturation is reached pPars->fPatScores = 0; // enables simulation pattern scoring pPars->MaxScore = 25; // max score after which resimulation is used pPars->fDoSparse = 1; // skips sparse functions // pPars->dActConeRatio = 0.05; // the ratio of cone to be bumped // pPars->dActConeBumpMax = 5.0; // the largest bump of activity pPars->dActConeRatio = 0.3; // the ratio of cone to be bumped pPars->dActConeBumpMax = 10.0; // the largest bump of activity pPars->nBTLimitNode = 100; // conflict limit at a node pPars->nBTLimitMiter = 500000; // conflict limit at an output pPars->nFramesK = 0; // the number of timeframes to unroll pPars->fConeBias = 1; pPars->fRewrite = 0; } /**Function************************************************************* Synopsis [Sets the default solving parameters.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ParamsDefaultSeq( Fra_Par_t * pPars ) { memset( pPars, 0, sizeof(Fra_Par_t) ); pPars->nSimWords = 1; // the number of words in the simulation info pPars->dSimSatur = 0.005; // the ratio of refined classes when saturation is reached pPars->fPatScores = 0; // enables simulation pattern scoring pPars->MaxScore = 25; // max score after which resimulation is used pPars->fDoSparse = 1; // skips sparse functions pPars->dActConeRatio = 0.3; // the ratio of cone to be bumped pPars->dActConeBumpMax = 10.0; // the largest bump of activity pPars->nBTLimitNode = 10000000; // conflict limit at a node pPars->nBTLimitMiter = 500000; // conflict limit at an output pPars->nFramesK = 1; // the number of timeframes to unroll pPars->fConeBias = 0; pPars->fRewrite = 0; pPars->fLatchCorr = 0; } /**Function************************************************************* Synopsis [Starts the fraiging manager.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Fra_Man_t * Fra_ManStart( Aig_Man_t * pManAig, Fra_Par_t * pPars ) { Fra_Man_t * p; Aig_Obj_t * pObj; int i; // allocate the fraiging manager p = ABC_ALLOC( Fra_Man_t, 1 ); memset( p, 0, sizeof(Fra_Man_t) ); p->pPars = pPars; p->pManAig = pManAig; p->nSizeAlloc = Aig_ManObjNumMax( pManAig ); p->nFramesAll = pPars->nFramesK + 1; // allocate storage for sim pattern p->nPatWords = Abc_BitWordNum( (Aig_ManCiNum(pManAig) - Aig_ManRegNum(pManAig)) * p->nFramesAll + Aig_ManRegNum(pManAig) ); p->pPatWords = ABC_ALLOC( unsigned, p->nPatWords ); p->vPiVars = Vec_PtrAlloc( 100 ); // equivalence classes p->pCla = Fra_ClassesStart( pManAig ); // allocate other members p->pMemFraig = ABC_ALLOC( Aig_Obj_t *, p->nSizeAlloc * p->nFramesAll ); memset( p->pMemFraig, 0, sizeof(Aig_Obj_t *) * p->nSizeAlloc * p->nFramesAll ); // set random number generator // srand( 0xABCABC ); Aig_ManRandom(1); // set the pointer to the manager Aig_ManForEachObj( p->pManAig, pObj, i ) pObj->pData = p; return p; } /**Function************************************************************* Synopsis [Starts the fraiging manager.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ManClean( Fra_Man_t * p, int nNodesMax ) { int i; // remove old arrays for ( i = 0; i < p->nMemAlloc; i++ ) if ( p->pMemFanins[i] && p->pMemFanins[i] != (void *)1 ) Vec_PtrFree( p->pMemFanins[i] ); // realloc for the new size if ( p->nMemAlloc < nNodesMax ) { int nMemAllocNew = nNodesMax + 5000; p->pMemFanins = ABC_REALLOC( Vec_Ptr_t *, p->pMemFanins, nMemAllocNew ); p->pMemSatNums = ABC_REALLOC( int, p->pMemSatNums, nMemAllocNew ); p->nMemAlloc = nMemAllocNew; } // prepare for the new run memset( p->pMemFanins, 0, sizeof(Vec_Ptr_t *) * p->nMemAlloc ); memset( p->pMemSatNums, 0, sizeof(int) * p->nMemAlloc ); } /**Function************************************************************* Synopsis [Prepares the new manager to begin fraiging.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Fra_ManPrepareComb( Fra_Man_t * p ) { Aig_Man_t * pManFraig; Aig_Obj_t * pObj; int i; assert( p->pManFraig == NULL ); // start the fraig package pManFraig = Aig_ManStart( Aig_ManObjNumMax(p->pManAig) ); pManFraig->pName = Abc_UtilStrsav( p->pManAig->pName ); pManFraig->pSpec = Abc_UtilStrsav( p->pManAig->pSpec ); pManFraig->nRegs = p->pManAig->nRegs; pManFraig->nAsserts = p->pManAig->nAsserts; // set the pointers to the available fraig nodes Fra_ObjSetFraig( Aig_ManConst1(p->pManAig), 0, Aig_ManConst1(pManFraig) ); Aig_ManForEachCi( p->pManAig, pObj, i ) Fra_ObjSetFraig( pObj, 0, Aig_ObjCreateCi(pManFraig) ); // set the pointers to the manager Aig_ManForEachObj( pManFraig, pObj, i ) pObj->pData = p; // allocate memory for mapping FRAIG nodes into SAT numbers and fanins p->nMemAlloc = p->nSizeAlloc; p->pMemFanins = ABC_ALLOC( Vec_Ptr_t *, p->nMemAlloc ); memset( p->pMemFanins, 0, sizeof(Vec_Ptr_t *) * p->nMemAlloc ); p->pMemSatNums = ABC_ALLOC( int, p->nMemAlloc ); memset( p->pMemSatNums, 0, sizeof(int) * p->nMemAlloc ); // make sure the satisfying assignment is node assigned assert( pManFraig->pData == NULL ); return pManFraig; } /**Function************************************************************* Synopsis [Finalizes the combinational miter after fraiging.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ManFinalizeComb( Fra_Man_t * p ) { Aig_Obj_t * pObj; int i; // add the POs Aig_ManForEachCo( p->pManAig, pObj, i ) Aig_ObjCreateCo( p->pManFraig, Fra_ObjChild0Fra(pObj,0) ); // postprocess Aig_ManCleanMarkB( p->pManFraig ); } /**Function************************************************************* Synopsis [Stops the fraiging manager.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ManStop( Fra_Man_t * p ) { if ( p->pPars->fVerbose ) Fra_ManPrint( p ); // save mapping from original nodes into FRAIG nodes if ( p->pManAig ) { if ( p->pManAig->pObjCopies ) ABC_FREE( p->pManAig->pObjCopies ); p->pManAig->pObjCopies = p->pMemFraig; p->pMemFraig = NULL; } Fra_ManClean( p, 0 ); if ( p->vTimeouts ) Vec_PtrFree( p->vTimeouts ); if ( p->vPiVars ) Vec_PtrFree( p->vPiVars ); if ( p->pSat ) sat_solver_delete( p->pSat ); if ( p->pCla ) Fra_ClassesStop( p->pCla ); if ( p->pSml ) Fra_SmlStop( p->pSml ); if ( p->vCex ) Vec_IntFree( p->vCex ); if ( p->vOneHots ) Vec_IntFree( p->vOneHots ); ABC_FREE( p->pMemFraig ); ABC_FREE( p->pMemFanins ); ABC_FREE( p->pMemSatNums ); ABC_FREE( p->pPatWords ); ABC_FREE( p ); } /**Function************************************************************* Synopsis [Prints stats for the fraiging manager.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Fra_ManPrint( Fra_Man_t * p ) { double nMemory = 1.0*Aig_ManObjNumMax(p->pManAig)*(p->pSml->nWordsTotal*sizeof(unsigned)+6*sizeof(void*))/(1<<20); printf( "SimWord = %d. Round = %d. Mem = %0.2f MB. LitBeg = %d. LitEnd = %d. (%6.2f %%).\n", p->pPars->nSimWords, p->pSml->nSimRounds, nMemory, p->nLitsBeg, p->nLitsEnd, 100.0*p->nLitsEnd/(p->nLitsBeg?p->nLitsBeg:1) ); printf( "Proof = %d. Cex = %d. Fail = %d. FailReal = %d. C-lim = %d. ImpRatio = %6.2f %%\n", p->nSatProof, p->nSatCallsSat, p->nSatFails, p->nSatFailsReal, p->pPars->nBTLimitNode, Fra_ImpComputeStateSpaceRatio(p) ); printf( "NBeg = %d. NEnd = %d. (Gain = %6.2f %%). RBeg = %d. REnd = %d. (Gain = %6.2f %%).\n", p->nNodesBeg, p->nNodesEnd, 100.0*(p->nNodesBeg-p->nNodesEnd)/(p->nNodesBeg?p->nNodesBeg:1), p->nRegsBeg, p->nRegsEnd, 100.0*(p->nRegsBeg-p->nRegsEnd)/(p->nRegsBeg?p->nRegsBeg:1) ); if ( p->pSat ) Sat_SolverPrintStats( stdout, p->pSat ); if ( p->pPars->fUse1Hot ) Fra_OneHotEstimateCoverage( p, p->vOneHots ); ABC_PRT( "AIG simulation ", p->pSml->timeSim ); ABC_PRT( "AIG traversal ", p->timeTrav ); if ( p->timeRwr ) { ABC_PRT( "AIG rewriting ", p->timeRwr ); } ABC_PRT( "SAT solving ", p->timeSat ); ABC_PRT( " Unsat ", p->timeSatUnsat ); ABC_PRT( " Sat ", p->timeSatSat ); ABC_PRT( " Fail ", p->timeSatFail ); ABC_PRT( "Class refining ", p->timeRef ); ABC_PRT( "TOTAL RUNTIME ", p->timeTotal ); if ( p->time1 ) { ABC_PRT( "time1 ", p->time1 ); } if ( p->nSpeculs ) printf( "Speculations = %d.\n", p->nSpeculs ); fflush( stdout ); } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
4,894
12,252
/* * Copyright 2019 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.migration.migrators; import org.jboss.logging.Logger; import org.keycloak.migration.ModelVersion; import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.ClientModel; import org.keycloak.models.Constants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.representations.idm.RealmRepresentation; import java.util.Collections; import java.util.stream.Collectors; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class MigrateTo8_0_0 implements Migration { public static final ModelVersion VERSION = new ModelVersion("8.0.0"); private static final Logger LOG = Logger.getLogger(MigrateTo8_0_0.class); @Override public ModelVersion getVersion() { return VERSION; } @Override public void migrate(KeycloakSession session) { // Perform basic realm migration first (non multi-factor authentication) session.realms().getRealmsStream().forEach(this::migrateRealmCommon); // Moreover, for multi-factor authentication migrate optional execution of realm flows to subflows session.realms().getRealmsStream().forEach(realm -> migrateRealmMFA(realm)); } @Override public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) { migrateRealmCommon(realm); // No-additional-op for multi-factor authentication besides the basic migrateRealmCommon() in previous statement // Migration of optional authentication executions was already handled in RepresentationToModel.importRealm } protected void migrateRealmCommon(RealmModel realm) { ClientModel adminConsoleClient = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID); if (adminConsoleClient != null) { adminConsoleClient.setRootUrl(Constants.AUTH_ADMIN_URL_PROP); String adminConsoleBaseUrl = "/admin/" + realm.getName() + "/console/"; adminConsoleClient.setBaseUrl(adminConsoleBaseUrl); adminConsoleClient.setRedirectUris(Collections.singleton(adminConsoleBaseUrl + "*")); adminConsoleClient.setWebOrigins(Collections.singleton("+")); } ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID); if (accountClient != null) { accountClient.setRootUrl(Constants.AUTH_BASE_URL_PROP); String accountClientBaseUrl = "/realms/" + realm.getName() + "/account/"; accountClient.setBaseUrl(accountClientBaseUrl); accountClient.setRedirectUris(Collections.singleton(accountClientBaseUrl + "*")); } } protected void migrateRealmMFA(RealmModel realm) { realm.getAuthenticationFlowsStream().collect(Collectors.toList()) .forEach(authFlow -> realm.getAuthenticationExecutionsStream(authFlow.getId()) .filter(exe -> exe.getRequirement() == AuthenticationExecutionModel.Requirement.CONDITIONAL) .collect(Collectors.toList()) .forEach(exe -> migrateOptionalAuthenticationExecution(realm, authFlow, exe, true))); } public static void migrateOptionalAuthenticationExecution(RealmModel realm, AuthenticationFlowModel parentFlow, AuthenticationExecutionModel optionalExecution, boolean updateOptionalExecution) { LOG.debugf("Migrating optional execution '%s' of flow '%s' of realm '%s' to subflow", optionalExecution.getAuthenticator(), parentFlow.getAlias(), realm.getName()); AuthenticationFlowModel conditionalOTP = new AuthenticationFlowModel(); conditionalOTP.setTopLevel(false); conditionalOTP.setBuiltIn(parentFlow.isBuiltIn()); conditionalOTP.setAlias(parentFlow.getAlias() + " - " + optionalExecution.getAuthenticator() + " - Conditional"); conditionalOTP.setDescription("Flow to determine if the " + optionalExecution.getAuthenticator() + " authenticator should be used or not."); conditionalOTP.setProviderId("basic-flow"); conditionalOTP = realm.addAuthenticationFlow(conditionalOTP); AuthenticationExecutionModel execution = new AuthenticationExecutionModel(); execution.setParentFlow(parentFlow.getId()); execution.setRequirement(AuthenticationExecutionModel.Requirement.CONDITIONAL); execution.setFlowId(conditionalOTP.getId()); execution.setPriority(optionalExecution.getPriority()); execution.setAuthenticatorFlow(true); realm.addAuthenticatorExecution(execution); execution = new AuthenticationExecutionModel(); execution.setParentFlow(conditionalOTP.getId()); execution.setRequirement(AuthenticationExecutionModel.Requirement.REQUIRED); execution.setAuthenticator("conditional-user-configured"); execution.setPriority(10); execution.setAuthenticatorFlow(false); realm.addAuthenticatorExecution(execution); // Move optionalExecution as child of newly created parent flow optionalExecution.setParentFlow(conditionalOTP.getId()); optionalExecution.setRequirement(AuthenticationExecutionModel.Requirement.REQUIRED); optionalExecution.setPriority(20); // In case of DB migration, we're updating existing execution, which is already in DB. // In case of JSON migration, the execution is not yet in DB and will be added later if (updateOptionalExecution) { realm.updateAuthenticatorExecution(optionalExecution); } } }
2,168
348
{"nom":"Rauville-la-Bigot","circ":"3ème circonscription","dpt":"Manche","inscrits":847,"abs":495,"votants":352,"blancs":3,"nuls":29,"exp":320,"res":[{"nuance":"REM","nom":"<NAME>","voix":207},{"nuance":"LR","nom":"<NAME>","voix":113}]}
94
1,350
<reponame>Shashi-rk/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.monitor.opentelemetry.exporter; import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpPipelineNextPolicy; import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.data.appconfiguration.ConfigurationClient; import com.azure.data.appconfiguration.ConfigurationClientBuilder; import com.azure.data.appconfiguration.models.ConfigurationSetting; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static com.azure.core.util.tracing.Tracer.DISABLE_TRACING_KEY; import static org.junit.jupiter.api.Assertions.assertTrue; public class AppConfigurationExporterIntegrationTest extends AzureMonitorTraceExporterTestBase { @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); Tracer tracer = configureAzureMonitorExporter(new ValidationPolicy(exporterCountDown, "AppConfig.setKey")); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("set-config-exporter-testing").startSpan(); final Scope scope = span.makeCurrent(); try { // Thread bound (sync) calls will automatically pick up the parent span and you don't need to pass it explicitly. ConfigurationSetting configurationSetting = client.setConfigurationSetting("hello", "text", "World"); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } @Disabled("Multiple tests fail to trigger end span - https://github.com/Azure/azure-sdk-for-java/issues/23567") @Test public void testDisableTracing() throws InterruptedException { CountDownLatch appConfigCountDown = new CountDownLatch(1); CountDownLatch exporterCountDown = new CountDownLatch(1); Tracer tracer = configureAzureMonitorExporter(new ValidationPolicy(exporterCountDown, "disable-config-exporter-testing")); ConfigurationClient client = getConfigurationClient(appConfigCountDown); Span span = tracer.spanBuilder("disable-config-exporter-testing").startSpan(); final Scope scope = span.makeCurrent(); try { ConfigurationSetting configurationSetting = new ConfigurationSetting() .setKey("hello") .setLabel("text") .setValue("World"); client.setConfigurationSettingWithResponse(configurationSetting, false, Context.NONE.addData(DISABLE_TRACING_KEY, true)); } finally { span.end(); scope.close(); } assertTrue(appConfigCountDown.await(60, TimeUnit.SECONDS)); assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } private ConfigurationClient getConfigurationClient(CountDownLatch appConfigCountDown) { ConfigurationClient client = new ConfigurationClientBuilder() .connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) .addPolicy((context, next) -> { Optional<Object> data = context.getData(com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY); if (data.isPresent() && data.get().equals("Microsoft.AppConfiguration")) { appConfigCountDown.countDown(); } return next.process(); }) .buildClient(); return client; } static class ValidationPolicy implements HttpPipelinePolicy { private final CountDownLatch countDown; private final String expectedSpanName; ValidationPolicy(CountDownLatch countDown, String expectedSpanName) { this.countDown = countDown; this.expectedSpanName = expectedSpanName; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Mono<String> asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); asyncString.subscribe(value -> { if (value.contains(expectedSpanName)) { countDown.countDown(); } }); return next.process(); } } }
1,981
370
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.util.formatting.component; import com.google.common.collect.Iterables; import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.event.ClickEvent; import com.sk89q.worldedit.util.formatting.text.event.HoverEvent; import com.sk89q.worldedit.util.formatting.text.format.TextDecoration; import org.enginehub.piston.Command; import org.enginehub.piston.CommandParameters; import org.enginehub.piston.config.ColorConfig; import org.enginehub.piston.util.HelpGenerator; import javax.annotation.Nullable; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.sk89q.worldedit.internal.command.CommandUtil.getSubCommands; /** * A box to describe usage of a command. */ public class CommandUsageBox extends TextComponentProducer { /** * Create a new usage box. * * @param commands the commands to describe * @param commandString the commands that were used, such as "/we" or "/brush sphere" * @param helpRootCommand the command used to get subcommand help */ public CommandUsageBox(List<Command> commands, String commandString, String helpRootCommand) throws InvalidComponentException { this(commands, commandString, helpRootCommand, null); } /** * Create a new usage box. * * @param commands the commands to describe * @param commandString the commands that were used, such as "/we" or "/brush sphere" * @param helpRootCommand the command used to get subcommand help * @param parameters list of parameters to use */ public CommandUsageBox( List<Command> commands, String commandString, String helpRootCommand, @Nullable CommandParameters parameters ) throws InvalidComponentException { checkNotNull(commands); checkNotNull(commandString); checkNotNull(helpRootCommand); attachCommandUsage(commands, commandString, helpRootCommand); } private void attachCommandUsage(List<Command> commands, String commandString, String helpRootCommand) { TextComponentProducer boxContent = new TextComponentProducer() .append(HelpGenerator.create(commands).getFullHelp()); if (getSubCommands(Iterables.getLast(commands)).size() > 0) { boxContent.append(TextComponent.newline()) .append(ColorConfig.helpText().wrap(TextComponent.builder("> ") .append(ColorConfig.mainText().wrap(TextComponent.builder("List Subcommands") .decoration(TextDecoration.ITALIC, true) .clickEvent(ClickEvent.runCommand(helpRootCommand + " -s " + commandString)) .hoverEvent(HoverEvent.showText(TextComponent.of("List all subcommands of this command"))) .build())) .build())); } MessageBox box = new MessageBox( "Help for " + commandString, boxContent ); append(box.create()); } }
1,459
1,168
<reponame>wcalandro/kythe // Checks that we can generate a generates edge. #pragma kythe_metadata "single.meta.h" //- vname(gsig, gcorp, groot, gpath, glang) generates VFoo //- @foo defines/binding VFoo int foo;
81
1,001
# 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. from aliyunsdkcore.request import RpcRequest class ListNotaryOrdersRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Trademark', '2018-07-24', 'ListNotaryOrders','trademark') def get_SortKeyType(self): return self.get_query_params().get('SortKeyType') def set_SortKeyType(self,SortKeyType): self.add_query_param('SortKeyType',SortKeyType) def get_SortByType(self): return self.get_query_params().get('SortByType') def set_SortByType(self,SortByType): self.add_query_param('SortByType',SortByType) def get_StartOrderDate(self): return self.get_query_params().get('StartOrderDate') def set_StartOrderDate(self,StartOrderDate): self.add_query_param('StartOrderDate',StartOrderDate) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_BizId(self): return self.get_query_params().get('BizId') def set_BizId(self,BizId): self.add_query_param('BizId',BizId) def get_NotaryType(self): return self.get_query_params().get('NotaryType') def set_NotaryType(self,NotaryType): self.add_query_param('NotaryType',NotaryType) def get_EndOrderDate(self): return self.get_query_params().get('EndOrderDate') def set_EndOrderDate(self,EndOrderDate): self.add_query_param('EndOrderDate',EndOrderDate) def get_AliyunOrderId(self): return self.get_query_params().get('AliyunOrderId') def set_AliyunOrderId(self,AliyunOrderId): self.add_query_param('AliyunOrderId',AliyunOrderId) def get_PageNum(self): return self.get_query_params().get('PageNum') def set_PageNum(self,PageNum): self.add_query_param('PageNum',PageNum) def get_NotaryStatus(self): return self.get_query_params().get('NotaryStatus') def set_NotaryStatus(self,NotaryStatus): self.add_query_param('NotaryStatus',NotaryStatus)
979
2,606
<gh_stars>1000+ package weixin.popular.bean.paymch; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="xml") @XmlAccessorType(XmlAccessType.FIELD) public class QueryCouponResult extends MchBase{ private String sub_mch_id; private String device_info; private String coupon_stock_id; private Integer coupon_stock_type; private String coupon_id; private Integer coupon_value; private Integer coupon_mininumn; private String coupon_name; private Integer coupon_state; private Integer coupon_type; private String coupon_desc; private Integer coupon_use_value; private Integer coupon_remain_value; private String begin_time; private String end_time; private String send_time; private String use_time; private String trade_no; private String consumer_mch_id; private String consumer_mch_name; private String consumer_mch_appid; private String send_source; private String is_partial_use; public String getSub_mch_id() { return sub_mch_id; } public void setSub_mch_id(String sub_mch_id) { this.sub_mch_id = sub_mch_id; } public String getDevice_info() { return device_info; } public void setDevice_info(String device_info) { this.device_info = device_info; } public String getCoupon_stock_id() { return coupon_stock_id; } public void setCoupon_stock_id(String coupon_stock_id) { this.coupon_stock_id = coupon_stock_id; } public Integer getCoupon_stock_type() { return coupon_stock_type; } public void setCoupon_stock_type(Integer coupon_stock_type) { this.coupon_stock_type = coupon_stock_type; } public String getCoupon_id() { return coupon_id; } public void setCoupon_id(String coupon_id) { this.coupon_id = coupon_id; } public Integer getCoupon_value() { return coupon_value; } public void setCoupon_value(Integer coupon_value) { this.coupon_value = coupon_value; } public Integer getCoupon_mininumn() { return coupon_mininumn; } public void setCoupon_mininumn(Integer coupon_mininumn) { this.coupon_mininumn = coupon_mininumn; } public String getCoupon_name() { return coupon_name; } public void setCoupon_name(String coupon_name) { this.coupon_name = coupon_name; } public Integer getCoupon_state() { return coupon_state; } public void setCoupon_state(Integer coupon_state) { this.coupon_state = coupon_state; } public Integer getCoupon_type() { return coupon_type; } public void setCoupon_type(Integer coupon_type) { this.coupon_type = coupon_type; } public String getCoupon_desc() { return coupon_desc; } public void setCoupon_desc(String coupon_desc) { this.coupon_desc = coupon_desc; } public Integer getCoupon_use_value() { return coupon_use_value; } public void setCoupon_use_value(Integer coupon_use_value) { this.coupon_use_value = coupon_use_value; } public Integer getCoupon_remain_value() { return coupon_remain_value; } public void setCoupon_remain_value(Integer coupon_remain_value) { this.coupon_remain_value = coupon_remain_value; } public String getBegin_time() { return begin_time; } public void setBegin_time(String begin_time) { this.begin_time = begin_time; } public String getEnd_time() { return end_time; } public void setEnd_time(String end_time) { this.end_time = end_time; } public String getSend_time() { return send_time; } public void setSend_time(String send_time) { this.send_time = send_time; } public String getUse_time() { return use_time; } public void setUse_time(String use_time) { this.use_time = use_time; } public String getTrade_no() { return trade_no; } public void setTrade_no(String trade_no) { this.trade_no = trade_no; } public String getConsumer_mch_id() { return consumer_mch_id; } public void setConsumer_mch_id(String consumer_mch_id) { this.consumer_mch_id = consumer_mch_id; } public String getConsumer_mch_name() { return consumer_mch_name; } public void setConsumer_mch_name(String consumer_mch_name) { this.consumer_mch_name = consumer_mch_name; } public String getConsumer_mch_appid() { return consumer_mch_appid; } public void setConsumer_mch_appid(String consumer_mch_appid) { this.consumer_mch_appid = consumer_mch_appid; } public String getSend_source() { return send_source; } public void setSend_source(String send_source) { this.send_source = send_source; } public String getIs_partial_use() { return is_partial_use; } public void setIs_partial_use(String is_partial_use) { this.is_partial_use = is_partial_use; } }
2,059
1,673
<gh_stars>1000+ /*****************************************************************************/ /* */ /* segnames.h */ /* */ /* Default segment names */ /* */ /* */ /* */ /* (C) 2003 <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "chartype.h" #include "segnames.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int ValidSegName (const char* Name) /* Return true if the given segment name is valid, return false otherwise */ { /* Must start with '_' or a letter */ if ((*Name != '_' && !IsAlpha(*Name)) || strlen(Name) > 80) { return 0; } /* Can have letters, digits or the underline */ while (*++Name) { if (*Name != '_' && !IsAlNum(*Name)) { return 0; } } /* Name is ok */ return 1; }
1,904
1,042
/* * Copyright (c) scott.cgi All Rights Reserved. * * This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub. * The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion. * * License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE * GitHub : https://github.com/scottcgi/Mojoc * CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md * * Since : 2013-3-12 * Update : 2019-2-23 * Author : scott.cgi */ #ifndef EGL_TOOL_H #define EGL_TOOL_H #include "Engine/Toolkit/Platform/Platform.h" //------------------------ #ifdef IS_PLATFORM_ANDROID //------------------------ #include <stdbool.h> #include "Engine/Graphics/OpenGL/Platform/egl.h" struct AEGLTool { /** * Creates an EGL rendering context and all associated elements. */ void (*CreateEGL) ( EGLNativeWindowType window, EGLDisplay* outDisplay, EGLContext* outContext, EGLSurface* outSurface, EGLConfig* outConfig ); /** * Destroy EGL context and all associated elements. */ void (*DestroyEGL) (EGLDisplay* display, EGLContext* context, EGLSurface* surface); /** * When native window resized, we need reset surface, * the surface will destroyed and create new one and make current. */ void (*ResetSurface)( EGLNativeWindowType window, EGLDisplay display, EGLContext context, EGLConfig config, EGLSurface* surface ); }; extern struct AEGLTool AEGLTool[1]; //--------------------------- #endif // IS_PLATFORM_ANDROID //--------------------------- #endif
942
321
// Copyright 2019 DeepMind Technologies Limited. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 SPIRAL_ENVIRONMENTS_LIBMYPAINT_WRAPPER_SURFACE_H_ #define SPIRAL_ENVIRONMENTS_LIBMYPAINT_WRAPPER_SURFACE_H_ #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "libmypaint/mypaint-config.h" #include "libmypaint/mypaint-glib-compat.h" #include "libmypaint/mypaint-tiled-surface.h" namespace spiral { namespace libmypaint { struct Surface : MyPaintTiledSurface { // Size (in bytes) of single tile. std::size_t surface_tile_size; // Size (in elements) of single tile. std::size_t tile_n_elems; // Stores tiles in a linear chunk of memory (16bpc RGBA). std::unique_ptr<std::uint16_t[]> tile_buffer; // Single tile that we hand out and ignore writes to. std::unique_ptr<std::uint16_t[]> null_tile; // Background color value. std::uint16_t background_value; // Width in tiles. int tiles_width; // Height in tiles. int tiles_height; // Width in pixels. int width; // Height in pixels int height; }; class SurfaceWrapper { public: enum Background { kWhite, kBlack }; SurfaceWrapper(int width, int height, Background color = kWhite); ~SurfaceWrapper(); SurfaceWrapper(const SurfaceWrapper&) = delete; void operator=(const SurfaceWrapper&) = delete; void BeginAtomic(); void EndAtomic(); void Clear(); MyPaintSurface* GetInterface(); uint16_t* GetBuffer(); std::vector<int> GetBufferDims() const; private: Surface* const surface_; }; } // namespace libmypaint } // namespace spiral #endif // SPIRAL_ENVIRONMENTS_LIBMYPAINT_WRAPPER_SURFACE_H_
708
780
<reponame>yaoandrew/synthetix [ { "name": "sETH", "rewardsToken": "Synt<PASSWORD>" }, { "name": "sBTC", "rewardsToken": "Synt<PASSWORD>" } ]
83
14,668
<reponame>zealoussnow/chromium // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/geolocation/network_location_provider.h" #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/task/task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/device/geolocation/position_cache.h" #include "services/device/public/cpp/geolocation/geoposition.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #if defined(OS_MAC) #include "services/device/public/cpp/device_features.h" #endif namespace device { namespace { // The maximum period of time we'll wait for a complete set of wifi data // before sending the request. const int kDataCompleteWaitSeconds = 2; // The maximum age of a cached network location estimate before it can no longer // be returned as a fresh estimate. This should be at least as long as the // longest polling interval used by the WifiDataProvider. const int kLastPositionMaxAgeSeconds = 10 * 60; // 10 minutes } // namespace // NetworkLocationProvider NetworkLocationProvider::NetworkLocationProvider( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, GeolocationManager* geolocation_manager, const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, const std::string& api_key, PositionCache* position_cache) : wifi_data_provider_manager_(nullptr), wifi_data_update_callback_( base::BindRepeating(&NetworkLocationProvider::OnWifiDataUpdate, base::Unretained(this))), is_wifi_data_complete_(false), position_cache_(position_cache), is_permission_granted_(false), is_new_data_available_(false), request_(new NetworkLocationRequest( std::move(url_loader_factory), api_key, base::BindRepeating(&NetworkLocationProvider::OnLocationResponse, base::Unretained(this)))) { DCHECK(position_cache_); #if defined(OS_MAC) geolocation_manager_ = geolocation_manager; permission_observers_ = geolocation_manager->GetObserverList(); permission_observers_->AddObserver(this); main_task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GeolocationManager::GetSystemPermission, base::Unretained(geolocation_manager)), base::BindOnce(&NetworkLocationProvider::OnSystemPermissionUpdated, weak_factory_.GetWeakPtr())); #endif } NetworkLocationProvider::~NetworkLocationProvider() { DCHECK(thread_checker_.CalledOnValidThread()); #if defined(OS_MAC) permission_observers_->RemoveObserver(this); #endif if (IsStarted()) StopProvider(); } void NetworkLocationProvider::SetUpdateCallback( const LocationProvider::LocationProviderUpdateCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); location_provider_update_callback_ = callback; } void NetworkLocationProvider::OnPermissionGranted() { const bool was_permission_granted = is_permission_granted_; is_permission_granted_ = true; if (!was_permission_granted && IsStarted()) RequestPosition(); } void NetworkLocationProvider::OnSystemPermissionUpdated( LocationSystemPermissionStatus new_status) { is_awaiting_initial_permission_status_ = false; const bool was_permission_granted = is_system_permission_granted_; is_system_permission_granted_ = (new_status == LocationSystemPermissionStatus::kAllowed); if (!is_system_permission_granted_ && location_provider_update_callback_) { mojom::Geoposition error_position; error_position.error_code = mojom::Geoposition::ErrorCode::PERMISSION_DENIED; error_position.error_message = "User has not allowed access to system location."; location_provider_update_callback_.Run(this, error_position); } if (!was_permission_granted && is_system_permission_granted_ && IsStarted()) { wifi_data_provider_manager_->ForceRescan(); OnWifiDataUpdate(); } } void NetworkLocationProvider::OnWifiDataUpdate() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(IsStarted()); #if defined(OS_MAC) if (!is_system_permission_granted_) { if (!is_awaiting_initial_permission_status_) { mojom::Geoposition error_position; error_position.error_code = mojom::Geoposition::ErrorCode::PERMISSION_DENIED; error_position.error_message = "User has not allowed access to system location."; location_provider_update_callback_.Run(this, error_position); } return; } #endif is_wifi_data_complete_ = wifi_data_provider_manager_->GetData(&wifi_data_); if (is_wifi_data_complete_) { wifi_timestamp_ = base::Time::Now(); is_new_data_available_ = true; } // When RequestPosition is called, the most recent wifi data is sent to the // geolocation service. If the wifi data is incomplete but a cached estimate // is available, the cached estimate may be returned instead. // // If no wifi data is available or the data is incomplete, it may mean the // provider is still performing the wifi scan. In this case we should wait // for the scan to complete rather than return cached data. // // A lack of wifi data may also mean the scan is delayed due to the wifi // scanning policy. This delay can vary based on how frequently the wifi // data changes, but is on the order of a few seconds to several minutes. // In this case it is better to call RequestPosition and return a cached // position estimate if it is available. bool delayed = wifi_data_provider_manager_->DelayedByPolicy(); if (is_wifi_data_complete_ || delayed) RequestPosition(); } void NetworkLocationProvider::OnLocationResponse( const mojom::Geoposition& position, bool server_error, const WifiData& wifi_data) { DCHECK(thread_checker_.CalledOnValidThread()); // Record the position and update our cache. position_cache_->SetLastUsedNetworkPosition(position); if (ValidateGeoposition(position)) position_cache_->CachePosition(wifi_data, position); // Let listeners know that we now have a position available. if (!location_provider_update_callback_.is_null()) { location_provider_update_callback_.Run(this, position); } } void NetworkLocationProvider::StartProvider(bool high_accuracy) { DCHECK(thread_checker_.CalledOnValidThread()); if (IsStarted()) return; // Registers a callback with the data provider. The first call to Register() // will create a singleton data provider that will be deleted on Unregister(). wifi_data_provider_manager_ = WifiDataProviderManager::Register(&wifi_data_update_callback_); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&NetworkLocationProvider::RequestPosition, weak_factory_.GetWeakPtr()), base::Seconds(kDataCompleteWaitSeconds)); OnWifiDataUpdate(); } void NetworkLocationProvider::StopProvider() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(IsStarted()); wifi_data_provider_manager_->Unregister(&wifi_data_update_callback_); wifi_data_provider_manager_ = nullptr; weak_factory_.InvalidateWeakPtrs(); } const mojom::Geoposition& NetworkLocationProvider::GetPosition() { return position_cache_->GetLastUsedNetworkPosition(); } void NetworkLocationProvider::RequestPosition() { DCHECK(thread_checker_.CalledOnValidThread()); #if defined(OS_MAC) if (!is_system_permission_granted_) { return; } #endif // The wifi polling policy may require us to wait for several minutes before // fresh wifi data is available. To ensure we can return a position estimate // quickly when the network location provider is the primary provider, allow // a cached value to be returned under certain conditions. // // If we have a sufficiently recent network location estimate and we do not // expect to receive a new one soon (i.e., no new wifi data is available and // there is no pending network request), report the last network position // estimate as if it were a fresh estimate. const mojom::Geoposition& last_position = position_cache_->GetLastUsedNetworkPosition(); if (!is_new_data_available_ && !request_->is_request_pending() && ValidateGeoposition(last_position)) { base::Time now = base::Time::Now(); base::TimeDelta last_position_age = now - last_position.timestamp; if (last_position_age.InSeconds() < kLastPositionMaxAgeSeconds && !location_provider_update_callback_.is_null()) { // Update the timestamp to the current time. mojom::Geoposition position = last_position; position.timestamp = now; location_provider_update_callback_.Run(this, position); } } if (!is_new_data_available_ || !is_wifi_data_complete_) return; DCHECK(!wifi_timestamp_.is_null()) << "|wifi_timestamp_| must be set before looking up position"; const mojom::Geoposition* cached_position = position_cache_->FindPosition(wifi_data_); UMA_HISTOGRAM_BOOLEAN("Geolocation.PositionCache.CacheHit", cached_position != nullptr); UMA_HISTOGRAM_COUNTS_100("Geolocation.PositionCache.CacheSize", position_cache_->GetPositionCacheSize()); if (cached_position) { mojom::Geoposition position(*cached_position); DCHECK(ValidateGeoposition(position)); // The timestamp of a position fix is determined by the timestamp // of the source data update. (The value of position.timestamp from // the cache could be from weeks ago!) position.timestamp = wifi_timestamp_; is_new_data_available_ = false; // Record the position. position_cache_->SetLastUsedNetworkPosition(position); // Let listeners know that we now have a position available. if (!location_provider_update_callback_.is_null()) location_provider_update_callback_.Run(this, position); return; } // Don't send network requests until authorized. http://crbug.com/39171 if (!is_permission_granted_) return; is_new_data_available_ = false; // TODO(joth): Rather than cancel pending requests, we should create a new // NetworkLocationRequest for each and hold a set of pending requests. DLOG_IF(WARNING, request_->is_request_pending()) << "NetworkLocationProvider - pre-empting pending network request " "with new data. Wifi APs: " << wifi_data_.access_point_data.size(); net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = net::DefinePartialNetworkTrafficAnnotation("network_location_provider", "network_location_request", R"( semantics { sender: "Network Location Provider" } policy { setting: "Users can control this feature via the Location setting under " "'Privacy', 'Content Settings', 'Location'." chrome_policy { DefaultGeolocationSetting { DefaultGeolocationSetting: 2 } } })"); request_->MakeRequest(wifi_data_, wifi_timestamp_, partial_traffic_annotation); } bool NetworkLocationProvider::IsStarted() const { return wifi_data_provider_manager_ != nullptr; } } // namespace device
4,037
568
<filename>piano-hero/mobile/src/main/java/com/novoda/pianohero/CompositePiano.java package com.novoda.pianohero; import java.util.Arrays; import java.util.List; class CompositePiano implements Piano { private final List<Piano> pianos; CompositePiano(Piano... pianos) { this.pianos = Arrays.asList(pianos); } @Override public void attachListener(NoteListener noteListener) { for (Piano piano : pianos) { piano.attachListener(noteListener); } } }
204
1,001
<filename>blockchain/v2/__init__.py from . import ( receive )
27
4,283
<filename>hazelcast/src/test/java/com/hazelcast/aws/XmlNodeTest.java<gh_stars>1000+ /* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.aws; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; public class XmlNodeTest { @Test public void parse() { // given //language=XML String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<root xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">\n" + " <parent>\n" + " <item>\n" + " <key>value</key>\n" + " </item>\n" + " <item>\n" + " <key>second-value</key>\n" + " </item>\n" + " </parent>\n" + "</root>"; // when List<String> itemValues = XmlNode.create(xml) .getSubNodes("parent").stream() .flatMap(e -> e.getSubNodes("item").stream()) .map(item -> item.getValue("key")) .collect(Collectors.toList()); // then assertThat(itemValues, hasItems("value", "second-value")); } @Test(expected = RuntimeException.class) public void parseError() { // given String xml = "malformed-xml"; // when XmlNode.create(xml); // then // throws exception } }
908
2,023
<reponame>tdiprima/code """Indentable rlcompleter Extend standard rlcompleter module to let tab key can indent and also completing valid Python identifiers and keywords.""" import readline,rlcompleter class irlcompleter(rlcompleter.Completer): def complete(self, text, state): if text == "": #you could replace \t to 4 or 8 spaces if you prefer indent via spaces return ['\t',None][state] else: return rlcompleter.Completer.complete(self,text,state) #you could change this line to bind another key instead tab. readline.parse_and_bind("tab: complete") readline.set_completer(irlcompleter().complete)
298
852
<filename>HLTrigger/Configuration/python/Tools/dasFileQuery.py import sys import json import das_client def dasFileQuery(dataset): query = 'dataset dataset=%s' % dataset host = 'https://cmsweb.cern.ch' # default idx = 0 # default limit = 0 # unlimited debug = 0 # default thr = 300 # default ckey = "" # default cert = "" # default jsondict = das_client.get_data(host, query, idx, limit, debug, thr, ckey, cert) # check if the pattern matches none, many, or one dataset if not jsondict['data'] or not jsondict['data'][0]['dataset']: sys.stderr.write('Error: the pattern "%s" does not match any dataset\n' % dataset) sys.exit(1) return [] elif len(jsondict['data']) > 1: sys.stderr.write('Error: the pattern "%s" matches multiple datasets\n' % dataset) for d in jsondict['data']: sys.stderr.write(' %s\n' % d['dataset'][0]['name']) sys.exit(1) return [] else: # expand the dataset name dataset = jsondict['data'][0]['dataset'][0]['name'] query = 'file dataset=%s' % dataset jsondict = das_client.get_data(host, query, idx, limit, debug, thr, ckey, cert) # parse the results in JSON format, and extract the list of files files = sorted( f['file'][0]['name'] for f in jsondict['data'] ) return files
682
5,169
{ "name": "Customized-Popup", "version": "0.1.0", "summary": "Customized-Popup. Hello this is my first project in cocoapod.", "description": "Customized popup : One of the most customized popup with custom view inside the popup. You can show map, image and texts inside your popup. Easy to maintain", "homepage": "https://github.com/dsrijan/Customized-Popup", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "dsrijan": "<EMAIL>" }, "source": { "git": "https://github.com/dsrijan/Customized-Popup.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "source_files": "CustomizedPopup/**/*.swift" }
256
335
<filename>Q/Qualifier_noun.json { "word": "Qualifier", "definitions": [ "A person or team that qualifies for a competition or its final rounds.", "A match or contest to decide which individuals or teams qualify for a competition or its final rounds.", "A word or phrase, especially an adjective, used to attribute a quality to another word, especially a noun.", "(in systemic grammar) a word or phrase added after a noun to qualify its meaning." ], "parts-of-speech": "Noun" }
164
997
<reponame>mkannwischer/PQClean #ifndef PQCLEAN_MCELIECE6960119F_VEC_UTIL_H #define PQCLEAN_MCELIECE6960119F_VEC_UTIL_H /* This file is for loading/storing data in a little-endian fashion */ #include "vec.h" #include <stdint.h> void PQCLEAN_MCELIECE6960119F_VEC_store_i(unsigned char *out, uint64_t in, int i); void PQCLEAN_MCELIECE6960119F_VEC_store2(unsigned char *dest, uint16_t a); uint16_t PQCLEAN_MCELIECE6960119F_VEC_load2(const unsigned char *src); uint32_t PQCLEAN_MCELIECE6960119F_VEC_load4(const unsigned char *src); void PQCLEAN_MCELIECE6960119F_VEC_irr_load(vec out[][GFBITS], const unsigned char *in); void PQCLEAN_MCELIECE6960119F_VEC_store8(unsigned char *out, uint64_t in); uint64_t PQCLEAN_MCELIECE6960119F_VEC_load8(const unsigned char *in); #endif
359
2,605
// solution 1, O(n*q + q^2) #include "bits/stdc++.h" using namespace std; int main() { int n, q; scanf("%d%d", &n, &q); vector<pair<int,int>> intervals(q); vector<int> cnt(n); for(pair<int,int>& p : intervals) { scanf("%d%d", &p.first, &p.second); --p.first; --p.second; for(int i = p.first; i <= p.second; ++i) { ++cnt[i]; } } int answer = 0; for(int A = 0; A < q; ++A) { int count_positive = 0; vector<int> ones(n); for(int i = intervals[A].first; i <= intervals[A].second; ++i) { --cnt[i]; } for(int i = 0; i < n; ++i) { if(cnt[i] > 0) { ++count_positive; } if(cnt[i] == 1) { ++ones[i]; } } // prefix sums on 'ones' for(int i = 1; i < n; ++i) { ones[i] += ones[i-1]; } auto get_sum = [&](int L, int R) { // sum of interval [L,R] return ones[R] - (L ? ones[L-1] : 0); }; for(int B = A + 1; B < q; ++B) { int lost_ones = get_sum(intervals[B].first, intervals[B].second); answer = max(answer, count_positive - lost_ones); } // roll back the decreases of 'cnt' for(int i = intervals[A].first; i <= intervals[A].second; ++i) { ++cnt[i]; } } printf("%d\n", answer); }
842
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. // ------------------------------------------------------------ #include "stdafx.h" namespace Reliability { namespace ReplicationComponent { using Common::AcquireReadLock; using Common::AcquireWriteLock; using Common::Assert; using Common::AsyncCallback; using Common::AsyncOperation; using Common::AsyncOperationSPtr; using Common::ErrorCode; SecondaryReplicator::UpdateEpochAsyncOperation::UpdateEpochAsyncOperation( __in SecondaryReplicator & parent, __in FABRIC_EPOCH const & epoch, AsyncCallback const & callback, AsyncOperationSPtr const & state) : AsyncOperation(callback, state, true), parent_(parent), epoch_(epoch) { } // This runs under a lock, so do minimal work here void SecondaryReplicator::UpdateEpochAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr) { if (parent_.CheckReportedFault()) { TryComplete(thisSPtr, Common::ErrorCodeValue::OperationFailed); return; } bool shouldComplete = true; ErrorCode error; { AcquireWriteLock lock(parent_.queuesLock_); if (epoch_ < parent_.minAllowedEpoch_) { ReplicatorEventSource::Events->SecondaryUpdateEpochError( parent_.partitionId_, parent_.endpointUniqueId_, epoch_.DataLossNumber, epoch_.ConfigurationNumber, parent_.minAllowedEpoch_.DataLossNumber, parent_.minAllowedEpoch_.ConfigurationNumber); error = Common::ErrorCodeValue::REInvalidEpoch; } else if (parent_.minAllowedEpoch_ < epoch_) { shouldComplete = false; parent_.replicationReceiver_.DiscardOutOfOrderOperations(); ReplicatorEventSource::Events->SecondaryUpdateEpoch( parent_.partitionId_, parent_.endpointUniqueId_, parent_.minAllowedEpoch_.DataLossNumber, parent_.minAllowedEpoch_.ConfigurationNumber, epoch_.DataLossNumber, epoch_.ConfigurationNumber, parent_.replicationReceiver_.GetNextToBeCompleted()); parent_.minAllowedEpoch_ = epoch_; if (parent_.copyReceiver_.IsCopyInProgress()) { // If copy is in progress, it indicates that the primary is down and failover's view of this replica is still "Idle" (Even though all copy operations // could have possibly been received). // So rather than waiting for a new primary to try building this replica and then reporting fault, pro-actively report fault here. parent_.SetReportedFault( ErrorCode(Common::ErrorCodeValue::InvalidState), L"Secondary received UpdateEpoch while copy is in progress"); shouldComplete = true; error = Common::ErrorCodeValue::InvalidState; } } // Else duplicate call, complete immediately. } if (shouldComplete) { TryComplete(thisSPtr, error); } else { WaitForReplicationQueueToDrain(thisSPtr); } } void SecondaryReplicator::UpdateEpochAsyncOperation::WaitForReplicationQueueToDrain( AsyncOperationSPtr const & thisSPtr) { AsyncOperationSPtr drainReplOp; { AcquireWriteLock grab(parent_.queuesLock_); drainReplOp = AsyncOperation::CreateAndStart<DrainQueueAsyncOperation>( parent_, parent_.requireServiceAck_, parent_.replicationReceiver_.DispatchQueue, false /* isCopyQueue*/, Constants::ReplOperationTrace, Constants::UpdateEpochDrainQueue, [this](AsyncOperationSPtr const & asyncOperation) { this->WaitForReplicationQueueToDrainCallback(asyncOperation, false); }, thisSPtr); ASSERT_IF(parent_.drainReplOperationAsyncOperation_, "SecondaryReplicator drainReplOperationAsyncOperation_ should be null"); parent_.drainReplOperationAsyncOperation_ = drainReplOp; } AsyncOperation::Get<DrainQueueAsyncOperation>(drainReplOp)->ResumeOutsideLock(drainReplOp); WaitForReplicationQueueToDrainCallback(drainReplOp, true); } void SecondaryReplicator::UpdateEpochAsyncOperation::WaitForReplicationQueueToDrainCallback( AsyncOperationSPtr const & asyncOperation, bool completedSynchronously) { if (completedSynchronously == asyncOperation->CompletedSynchronously) { auto casted = AsyncOperation::End<DrainQueueAsyncOperation>(asyncOperation); ErrorCode error = casted->Error; { AcquireWriteLock grab(parent_.queuesLock_); ASSERT_IFNOT(asyncOperation == parent_.drainReplOperationAsyncOperation_, "SecondaryReplicator drainReplOperationAsyncOperation_ mismatch"); parent_.drainReplOperationAsyncOperation_ = nullptr; } if (error.IsError(Common::ErrorCodeValue::OperationCanceled)) { // Report fault to indicate that the replicator is in a bad state (Queues not drained but epoch is updated in OnStart) parent_.SetReportedFault( ErrorCode(Common::ErrorCodeValue::InvalidState), L"Cancelling update epoch on secondary while waiting for dispatch queues to drain will result in an invalid state"); } asyncOperation->Parent->TryComplete(asyncOperation->Parent, error); } } ErrorCode SecondaryReplicator::UpdateEpochAsyncOperation::End( AsyncOperationSPtr const & asyncOperation) { auto casted = AsyncOperation::End<UpdateEpochAsyncOperation>(asyncOperation); return casted->Error; } } // end namespace ReplicationComponent } // end namespace Reliability
2,388
14,668
<filename>third_party/blink/renderer/modules/websockets/websocket_message_chunk_accumulator.h // Copyright 2019 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 THIRD_PARTY_BLINK_RENDERER_MODULES_WEBSOCKETS_WEBSOCKET_MESSAGE_CHUNK_ACCUMULATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBSOCKETS_WEBSOCKET_MESSAGE_CHUNK_ACCUMULATOR_H_ #include <memory> #include "base/containers/span.h" #include "base/memory/scoped_refptr.h" #include "base/time/time.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/timer.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" namespace blink { class SingleThreadTaskRunner; // WebSocketMessageChunkAccumulator stores chunks for one WebSocket message. A // user can call Append() to append bytes, and call GetView() to get a list of // base::spans of data previously stored. // We don't use SharedBuffer due to an observed performance problem of FastFree. // TODO(yhirano): Remove this once the performance problem is fixed in a general // manner. class MODULES_EXPORT WebSocketMessageChunkAccumulator final { DISALLOW_NEW(); public: explicit WebSocketMessageChunkAccumulator( scoped_refptr<base::SingleThreadTaskRunner> task_runner); ~WebSocketMessageChunkAccumulator(); // Appends |data| to this instance. void Append(base::span<const char> data); // Returns the number of bytes stored in this instance. size_t GetSize() const { return size_; } // Clears the stored data. Memory regions for chunks may be kept for future // uses for certain amount of time. void Clear(); // Clear all stored data and cancel timers. void Reset(); // The regions will be available until Clear() is called. Vector<base::span<const char>> GetView() const; wtf_size_t GetPoolSizeForTesting() const { return pool_.size(); } bool IsTimerActiveForTesting() const { return timer_.IsActive(); } static constexpr size_t kSegmentSize = 16 * 1024; static constexpr base::TimeDelta kFreeDelay = base::Milliseconds(100); private: struct SegmentDeleter { void operator()(char* p) const { WTF::Partitions::FastFree(p); } }; using SegmentPtr = std::unique_ptr<char[], SegmentDeleter>; static SegmentPtr CreateSegment() { return SegmentPtr(static_cast<char*>(WTF::Partitions::FastMalloc( kSegmentSize, "blink::WebSocketMessageChunkAccumulator::Segment"))); } void OnTimerFired(TimerBase*); size_t GetLastSegmentSize() const { DCHECK(!segments_.IsEmpty()); return size_ % kSegmentSize > 0 ? size_ % kSegmentSize : kSegmentSize; } Vector<SegmentPtr> segments_; Vector<SegmentPtr> pool_; size_t size_ = 0; wtf_size_t num_pooled_segments_to_be_removed_ = 0; TaskRunnerTimer<WebSocketMessageChunkAccumulator> timer_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBSOCKETS_WEBSOCKET_MESSAGE_CHUNK_ACCUMULATOR_H_
1,078
860
<reponame>msgilligan/groovy-core<filename>src/main/org/codehaus/groovy/control/customizers/ImportCustomizer.java /** * 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.codehaus.groovy.control.customizers; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import java.util.*; /** * This compilation customizer allows addiing various types of imports to the compilation unit. Supports adding : * <ul> * <li>standard imports thanks to {@link #addImport(String)}, {@link #addImport(String, String)} or {@link #addImports(String...)}</li> * <li>star imports thanks to {@link #addStarImport(String)} or {@link #addStarImports(String...)}</li> * <li>static imports thanks to {@link #addStaticImport(String, String)} or {@link #addStaticImport(String, String, String)}</li> * <li>static star imports thanks to {@link #addStaticStar(String)} or {@link #addStaticStars(String...)}</li> * </ul> * * @author <NAME> * * @since 1.8.0 * */ public class ImportCustomizer extends CompilationCustomizer { private final List<Import> imports = new LinkedList<Import>(); public ImportCustomizer() { super(CompilePhase.CONVERSION); } @Override public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException { final ModuleNode ast = source.getAST(); for (Import anImport : imports) { switch (anImport.type) { case regular: ast.addImport(anImport.alias, anImport.classNode); break; case staticImport: ast.addStaticImport(anImport.classNode, anImport.field, anImport.alias); break; case staticStar: ast.addStaticStarImport(anImport.alias, anImport.classNode); break; case star: ast.addStarImport(anImport.star); break; } } } public ImportCustomizer addImport(final String alias, final String className) { imports.add(new Import(ImportType.regular, alias, ClassHelper.make(className))); return this; } public ImportCustomizer addStaticImport(final String className, final String fieldName) { final ClassNode node = ClassHelper.make(className); imports.add(new Import(ImportType.staticImport, fieldName, node, fieldName)); return this; } public ImportCustomizer addStaticStars(final String... classNames) { for (String className : classNames) { addStaticStar(className); } return this; } public ImportCustomizer addStaticImport(final String alias, final String className, final String fieldName) { imports.add(new Import(ImportCustomizer.ImportType.staticImport, alias, ClassHelper.make(className), fieldName)); return this; } public ImportCustomizer addImports(final String... imports) { for (String anImport : imports) { addImport(anImport); } return this; } public ImportCustomizer addStarImports(final String... packageNames) { for (String packageName : packageNames) { addStarImport(packageName); } return this; } private void addImport(final String className) { final ClassNode node = ClassHelper.make(className); imports.add(new Import(ImportType.regular, node.getNameWithoutPackage(), node)); } private void addStaticStar(final String className) { imports.add(new Import(ImportCustomizer.ImportType.staticStar, className, ClassHelper.make(className))); } private void addStarImport(final String packagename) { final String packageNameEndingWithDot = packagename.endsWith(".")?packagename:packagename+'.'; imports.add(new Import(ImportType.star,packageNameEndingWithDot)); } // -------------------- Helper classes ------------------------- /** * Represents imports which are possibly aliased. */ private static class Import { final ImportType type; final ClassNode classNode; final String alias; final String field; final String star; // only used for star imports private Import(final ImportType type, final String alias, final ClassNode classNode, final String field) { this.alias = alias; this.classNode = classNode; this.field = field; this.type = type; this.star = null; } private Import(final ImportType type, final String alias, final ClassNode classNode) { this.alias = alias; this.classNode = classNode; this.type = type; this.field = null; this.star = null; } private Import(final ImportType type, final String star) { this.type = type; this.star = star; this.alias = null; this.classNode = null; this.field = null; } } private enum ImportType { regular, staticImport, staticStar, star } }
2,387
965
class ATL_NO_VTABLE CPolyProp : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CPolyProp, &CLSID_PolyProp>, public IPropertyPageImpl<CPolyProp>, public CDialogImpl<CPolyProp> { public: BEGIN_COM_MAP(CPolyProp) COM_INTERFACE_ENTRY(IPropertyPage) END_COM_MAP() BEGIN_MSG_MAP(CPolyProp) COMMAND_HANDLER(IDC_SIDES, EN_CHANGE, OnEnChangeSides) CHAIN_MSG_MAP(IPropertyPageImpl<CPolyProp>) END_MSG_MAP() // When a CPolyProp object receives a WM_COMMAND message identified // by IDC_SIDES and EN_CHANGE, the message is directed to // CPolyProp::OnEnChangeSides for the actual processing. LRESULT OnEnChangeSides(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
296
1,292
<reponame>saripaisley/TabPy<filename>tests/unit/server_tests/test_pwd_file.py import os import unittest from tempfile import NamedTemporaryFile from tabpy.tabpy_server.app.app import TabPyApp class TestPasswordFile(unittest.TestCase): def setUp(self): self.config_file = NamedTemporaryFile(mode="w", delete=False) self.config_file.close() self.pwd_file = NamedTemporaryFile(mode="w", delete=False) self.pwd_file.close() def tearDown(self): os.remove(self.config_file.name) self.config_file = None os.remove(self.pwd_file.name) self.pwd_file = None def _set_file(self, file_name, value): with open(file_name, "w") as f: f.write(value) def test_given_no_pwd_file_expect_empty_credentials_list(self): self._set_file( self.config_file.name, "[TabPy]\n" "TABPY_TRANSFER_PROTOCOL = http" ) app = TabPyApp(self.config_file.name) self.assertDictEqual( app.credentials, {}, "Expected no credentials with no password file provided", ) def test_given_empty_pwd_file_expect_app_fails(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) self._set_file(self.pwd_file.name, "# just a comment") with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_missing_pwd_file_expect_app_fails(self): self._set_file(self.config_file.name, "[TabPy]\n" "TABPY_PWD_FILE = foo") with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_one_password_in_pwd_file_expect_one_credentials_entry(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) login = "user_name_123" pwd = "<PASSWORD>" self._set_file(self.pwd_file.name, "# passwords\n" "\n" f"{login} {pwd}") app = TabPyApp(self.config_file.name) self.assertEqual(len(app.credentials), 1) self.assertIn(login, app.credentials) self.assertEqual(app.credentials[login], pwd) def test_given_username_but_no_password_expect_parsing_fails(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) login = "user_name_123" pwd = "" self._set_file(self.pwd_file.name, "# passwords\n" "\n" f"{login} {pwd}") with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_duplicate_usernames_expect_parsing_fails(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) login = "user_name_123" pwd = "<PASSWORD>" self._set_file( self.pwd_file.name, "# passwords\n" "\n" f"{login} {pwd}\n{login} {pwd}" ) with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_one_line_with_too_many_params_expect_app_fails(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) self._set_file( self.pwd_file.name, "# passwords\n" "user1 pwd1\n" "user_2 pwd#2" "user1 pwd@3", ) with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_different_cases_in_pwd_file_expect_app_fails(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) self._set_file( self.pwd_file.name, "# passwords\n" "user1 pwd1\n" "user_2 pwd#2" "UseR1 pwd@3", ) with self.assertRaises(RuntimeError) as cm: TabPyApp(self.config_file.name) ex = cm.exception self.assertEqual( f"Failed to read password file {self.pwd_file.name}", ex.args[0] ) def test_given_multiple_credentials_expect_all_parsed(self): self._set_file( self.config_file.name, "[TabPy]\n" f"TABPY_PWD_FILE = {self.pwd_file.name}" ) creds = {"user_1": "<PASSWORD>", "user@2": "<PASSWORD>", "user#3": "<PASSWORD>"} pwd_file_context = "" for login in creds: pwd_file_context += f"{login} {creds[login]}\n" self._set_file(self.pwd_file.name, pwd_file_context) app = TabPyApp(self.config_file.name) self.assertCountEqual(creds, app.credentials) for login in creds: self.assertIn(login, app.credentials) self.assertEqual(creds[login], app.credentials[login])
3,081
1,779
package com.exadel.frs.core.trainservice.cache; import com.exadel.frs.core.trainservice.dto.CacheActionDto; import com.exadel.frs.core.trainservice.service.EmbeddingService; import com.exadel.frs.core.trainservice.service.NotificationSenderService; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static com.exadel.frs.core.trainservice.system.global.Constants.SERVER_UUID; @Component @Slf4j @RequiredArgsConstructor public class EmbeddingCacheProvider { private static final long CACHE_EXPIRATION = 60 * 60 * 24L; private static final long CACHE_MAXIMUM_SIZE = 10; private final EmbeddingService embeddingService; private final NotificationSenderService notificationSenderService; private static final Cache<String, EmbeddingCollection> cache = CacheBuilder.newBuilder() .expireAfterAccess(CACHE_EXPIRATION, TimeUnit.SECONDS) .maximumSize(CACHE_MAXIMUM_SIZE) .build(); public EmbeddingCollection getOrLoad(final String apiKey) { var result = cache.getIfPresent(apiKey); if (result == null) { result = embeddingService.doWithEmbeddingsStream(apiKey, EmbeddingCollection::from); cache.put(apiKey, result); notifyCacheEvent("UPDATE", apiKey); } return result; } public void ifPresent(String apiKey, Consumer<EmbeddingCollection> consumer) { Optional.ofNullable(cache.getIfPresent(apiKey)) .ifPresent(consumer); EmbeddingCollection dd = cache.getIfPresent(apiKey); notifyCacheEvent("UPDATE", apiKey); } public void invalidate(final String apiKey) { cache.invalidate(apiKey); notifyCacheEvent("DELETE", apiKey); } public void receivePutOnCache(String apiKey) { var result = embeddingService.doWithEmbeddingsStream(apiKey, EmbeddingCollection::from); cache.put(apiKey, result); } public void receiveInvalidateCache(final String apiKey) { cache.invalidate(apiKey); } private void notifyCacheEvent(String event, String apiKey) { CacheActionDto cacheActionDto = new CacheActionDto(event, apiKey, SERVER_UUID); notificationSenderService.notifyCacheChange(cacheActionDto); } }
973
435
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division from tempfile import NamedTemporaryFile import io from petl.test.helpers import eq_ from petl.io.html import tohtml def test_tohtml(): # exercise function table = (('foo', 'bar'), ('a', 1), ('b', (1, 2)), ('c', False)) f = NamedTemporaryFile(delete=False) tohtml(table, f.name, encoding='ascii', lineterminator='\n') # check what it did with io.open(f.name, mode='rt', encoding='ascii', newline='') as o: actual = o.read() expect = ( u"<table class='petl'>\n" u"<thead>\n" u"<tr>\n" u"<th>foo</th>\n" u"<th>bar</th>\n" u"</tr>\n" u"</thead>\n" u"<tbody>\n" u"<tr>\n" u"<td>a</td>\n" u"<td style='text-align: right'>1</td>\n" u"</tr>\n" u"<tr>\n" u"<td>b</td>\n" u"<td>(1, 2)</td>\n" u"</tr>\n" u"<tr>\n" u"<td>c</td>\n" u"<td>False</td>\n" u"</tr>\n" u"</tbody>\n" u"</table>\n" ) eq_(expect, actual) def test_tohtml_caption(): # exercise function table = (('foo', 'bar'), ('a', 1), ('b', (1, 2))) f = NamedTemporaryFile(delete=False) tohtml(table, f.name, encoding='ascii', caption='my table', lineterminator='\n') # check what it did with io.open(f.name, mode='rt', encoding='ascii', newline='') as o: actual = o.read() expect = ( u"<table class='petl'>\n" u"<caption>my table</caption>\n" u"<thead>\n" u"<tr>\n" u"<th>foo</th>\n" u"<th>bar</th>\n" u"</tr>\n" u"</thead>\n" u"<tbody>\n" u"<tr>\n" u"<td>a</td>\n" u"<td style='text-align: right'>1</td>\n" u"</tr>\n" u"<tr>\n" u"<td>b</td>\n" u"<td>(1, 2)</td>\n" u"</tr>\n" u"</tbody>\n" u"</table>\n" ) eq_(expect, actual) def test_tohtml_with_style(): # exercise function table = (('foo', 'bar'), ('a', 1)) f = NamedTemporaryFile(delete=False) tohtml(table, f.name, encoding='ascii', lineterminator='\n', tr_style='text-align: right', td_styles='text-align: center') # check what it did with io.open(f.name, mode='rt', encoding='ascii', newline='') as o: actual = o.read() expect = ( u"<table class='petl'>\n" u"<thead>\n" u"<tr>\n" u"<th>foo</th>\n" u"<th>bar</th>\n" u"</tr>\n" u"</thead>\n" u"<tbody>\n" u"<tr style='text-align: right'>\n" u"<td style='text-align: center'>a</td>\n" u"<td style='text-align: center'>1</td>\n" u"</tr>\n" u"</tbody>\n" u"</table>\n" ) eq_(expect, actual)
1,950
1,235
#include <iostream> #include <map> using namespace std; void updateMap1(map<char,int> cmap) { cmap['O'] = 100; } void updateMap2(map<char,int>& cmap) { cmap['O'] = 100; } void updateMap3(map<char,int>* cmap) { // (X) cmap['O'] = 1000; (*cmap)['O'] = 1000; } int main() { map<char,int> cmap; cmap['A'] = 100; cmap['B'] = 200; cmap['C'] = 300; cout << "cmap['X']: " << cmap['X'] << endl; // 0 updateMap1(cmap); cout << "cmap['O']: " << cmap['O'] << endl; // 0 updateMap2(cmap); cout << "cmap['O']: " << cmap['O'] << endl; // 100 updateMap3(&cmap); cout << "cmap['O']: " << cmap['O'] << endl; // 1000 for (map<char,int>::iterator it=cmap.begin(); it!=cmap.end(); ++it) cout << it->first << " => " << it->second << '\n'; cout << endl; map<string,int> smap; smap["Hello"] = -100; smap["World"] = 200; smap["C++"] = 300; smap["Hello"] = 100; map<string,int>::iterator iter = smap.find("NOT"); cout << (iter == smap.end()) << endl; // 1 // 'NOT' does not exist in the map cout << endl; for (map<string,int>::iterator it=smap.begin(); it!=smap.end(); ++it) cout << it->first << " => " << it->second << '\n'; cout << '\n'; iter = smap.find("World"); if (iter != smap.end()) smap.erase(iter); cout << "Deleted" << endl; for (map<string,int>::iterator it=smap.begin(); it!=smap.end(); ++it) cout << it->first << " => " << it->second << '\n'; } /* A => 100 B => 200 C => 300 1 C++ => 300 Hello => 100 World => 200 Deleted C++ => 300 Hello => 100 */
677
1,146
/* * 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 com.aliyun.oss.crypto; import static com.aliyun.oss.crypto.SdkRuntime.shouldAbort; import java.io.IOException; import java.io.InputStream; import com.aliyun.oss.ClientErrorCode; import com.aliyun.oss.ClientException; /** * Reads only a specific range of bytes from the underlying input stream. */ public class AdjustedRangeInputStream extends InputStream { private InputStream decryptedContents; private long virtualAvailable; private boolean closed; /** * Creates a new DecryptedContentsInputStream object. * * @param objectContents * The input stream containing the object contents retrieved from OSS * @param rangeBeginning * The position of the left-most byte desired by the user * @param rangeEnd * The position of the right-most byte desired by the user * @throws IOException * If there are errors skipping to the left-most byte desired by the user. */ public AdjustedRangeInputStream(InputStream objectContents, long rangeBeginning, long rangeEnd) throws IOException { this.decryptedContents = objectContents; this.closed = false; initializeForRead(rangeBeginning, rangeEnd); } /** * Aborts the inputstream operation if thread is interrupted. * interrupted status of the thread is cleared by this method. * * @throws ClientException with ClientErrorCode INPUTSTREAM_READING_ABORTED if thread aborted. */ protected final void abortIfNeeded() { if (shouldAbort()) { abort(); throw new ClientException("Thread aborted, inputStream aborted...", ClientErrorCode.INPUTSTREAM_READING_ABORTED, null); } } private void abort() { } /** * Skip to the start location of the range of bytes desired by the user. */ private void initializeForRead(long rangeBeginning, long rangeEnd) throws IOException { int numBytesToSkip; if (rangeBeginning < CryptoScheme.BLOCK_SIZE) { numBytesToSkip = (int) rangeBeginning; } else { int offsetIntoBlock = (int) (rangeBeginning % CryptoScheme.BLOCK_SIZE); numBytesToSkip = offsetIntoBlock; } if (numBytesToSkip != 0) { while (numBytesToSkip > 0) { this.decryptedContents.read(); numBytesToSkip--; } } this.virtualAvailable = (rangeEnd - rangeBeginning) + 1; } @Override public int read() throws IOException { abortIfNeeded(); int result; if (this.virtualAvailable <= 0) { result = -1; } else { result = this.decryptedContents.read(); } if (result != -1) { this.virtualAvailable--; } else { this.virtualAvailable = 0; close(); } return result; } @Override public int read(byte[] buffer, int offset, int length) throws IOException { abortIfNeeded(); int numBytesRead; if (this.virtualAvailable <= 0) { numBytesRead = -1; } else { if (length > this.virtualAvailable) { length = (this.virtualAvailable < Integer.MAX_VALUE) ? (int) this.virtualAvailable : Integer.MAX_VALUE; } numBytesRead = this.decryptedContents.read(buffer, offset, length); } if (numBytesRead != -1) { this.virtualAvailable -= numBytesRead; } else { this.virtualAvailable = 0; close(); } return numBytesRead; } @Override public int available() throws IOException { abortIfNeeded(); int available = this.decryptedContents.available(); if (available < this.virtualAvailable) { return available; } else { return (int) this.virtualAvailable; } } @Override public void close() throws IOException { if (!this.closed) { this.closed = true; if (this.virtualAvailable == 0) { drainInputStream(decryptedContents); } this.decryptedContents.close(); } abortIfNeeded(); } private static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } public InputStream getWrappedInputStream() { return decryptedContents; } }
2,115
307
<filename>riptable/rt_csv.py from typing import Optional, List __all__ = ['load_csv_as_dataset', ] import csv import numpy as np from .rt_dataset import Dataset def load_csv_as_dataset(path_or_file, column_names: Optional[List[str]] = None, converters: Optional[dict] = None, skip_rows: int = 0, version: Optional[int] = None, encoding: str = 'utf-8', **kwargs) -> Dataset: """ Load a Dataset from a comma-separated value (CSV) file. Parameters ---------- path_or_file A filename or a file-like object (from open() or StringIO()); if you need a non-standard encoding, do the open yourself. column_names : list of str, optional List of column names (must be legal python var names), or None for 'use first row read from file'. Defaults to None. converters : dict {column_name -> str2type-converters}, do your own error handling, should return uniform types, and handle bad/missing data as desired missing converter will default to 'leave as string'. skip_rows : int Number of rows to skip before processing, defaults to 0. version : int, optional Selects the implementation of the CSV parser used to read the input file. Defaults to None, in which case the function chooses the best available implementation. encoding : str The text encoding of the CSV file, defaults to 'utf-8'. kwargs Any csv 'dialect' params you like. Returns ------- Dataset Notes ----- For a dataset of shape (459302, 15) (all strings) the timings are roughly: (version=0) 6.195947s (version=1) 5.605156s (default if pandas not available) (version=2) 8.370234s (version=3) 6.994191s (version=4) 3.642205s (only available if pandas is available, default if so) """ try: import pandas as pd from .Utils.pandas_utils import dataset_from_pandas_df except ImportError: pd = None if converters is None: converters = dict() if version is None: version = 4 if pd is not None else 1 if pd is None and version == 4: raise RuntimeError('load_csv_as_dataset(version=4) is not allowed if pandas is not available.') if version == 4: # BUG: pd.read_csv does some sort of import that breaks the unit tester. the csv test succeeds but the next test that runs will raise an error. return _load_rows_via_pandas(pd, path_or_file, column_names, converters, skip_rows, encoding=encoding) if hasattr(path_or_file, 'read'): infile = path_or_file else: infile = open(path_or_file, 'r', encoding=encoding) for _ in range(skip_rows): _ = infile.readline() reader = csv.reader(infile, **kwargs) if column_names is None or len(column_names) == 0: column_names = list(next(reader)) if not all(_k.isidentifier() for _k in column_names): raise ValueError('load_csv_as_dataset: column names must be legal python identifiers') if version == 0: data = _load_rows_to_dict_conv_by_col(reader, column_names, converters) elif version == 1: data = _load_rows_to_dict_conv_by_row(reader, column_names, converters) elif version == 2: data = _load_rows_to_tagged_rows(reader, column_names, converters) elif version == 3: data = _load_rows_to_rows_and_cols(reader, column_names, converters) else: raise NotImplementedError('load_csv_as_dataset(version=[0|1|2|3|4]) only.') if infile != path_or_file: infile.close() return data def _load_rows_to_dict_conv_by_col(reader, column_names, converters): # 865ms, all strings rawd = [_r for _r in reader] data = {} for _i, _cname in enumerate(column_names): _conv = converters.get(_cname) if _conv is None or type(_conv) is str: data[_cname] = np.array([_e[_i] for _e in rawd]) else: data[_cname] = np.array([_conv(_e[_i]) for _e in rawd]) return Dataset(data) def _load_rows_to_dict_conv_by_row(reader, column_names, converters): # 1930ms, all strings _ident = lambda _x: _x convs = [converters.get(_cname, _ident) for _cname in column_names] rawd = [[] for _ in column_names] for _r in reader: for _v, _c, _l in zip(_r, convs, rawd): _l.append(_c(_v)) data = {_k: np.array(rawd[_i]) for _i, _k in enumerate(column_names)} return Dataset(data) def _load_rows_to_tagged_rows(reader, column_names, converters): # 1930ms, all strings _ident = lambda _x: _x convs = [converters.get(_cname, _ident) for _cname in column_names] rawd = [] for _r in reader: rawd.append({_n: _c(_v) for _v, _c, _n in zip(_r, convs, column_names)}) ds = Dataset.from_tagged_rows(rawd) ds.col_move_to_front(column_names) return ds def _load_rows_to_rows_and_cols(reader, column_names, converters): # 1930ms, all strings _ident = lambda _x: _x convs = [converters.get(_cname, _ident) for _cname in column_names] rawd = [] for _r in reader: rawd.append([_c(_v) for _v, _c in zip(_r, convs)]) return Dataset.from_rows(rawd, column_names) def _load_rows_via_pandas(pd, fname, column_names, converters, skip_rows, encoding='utf-8'): if column_names is None or len(column_names) == 0: column_names = None convs = converters else: _ident = lambda _x: _x convs = {_cname: converters.get(_cname, _ident) for _cname in column_names} df = pd.read_csv(fname, converters=convs, names=column_names, skiprows=skip_rows, encoding=encoding) return Dataset(df)
2,455
748
<reponame>Ayansam1152/translate #!/usr/bin/env python3 import importlib import os # automatically import any Python files in the models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(".py") and not file.startswith("_"): model_name = file[: file.find(".py")] importlib.import_module("pytorch_translate.models." + model_name)
145
6,132
import angr import logging l = logging.getLogger(name=__name__) #l.setLevel("DEBUG") """ BOOL GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR lpProcessAffinityMask, PDWORD_PTR lpSystemAffinityMask ); """ class GetProcessAffinityMask(angr.SimProcedure): paffinity_mask = None saffinity_mask = None def run(self, _, lpProcessAffinityMask, lpSystemAffinityMask): #pylint:disable=arguments-differ self.fill_symbolic() l.info("Setting symbolic memory at %s %s", str(lpProcessAffinityMask), str(lpSystemAffinityMask)) self.state.mem[lpProcessAffinityMask].dword = self.paffinity_mask self.state.mem[lpSystemAffinityMask].dword = self.saffinity_mask return 1 def fill_symbolic(self): self.paffinity_mask = self.state.solver.BVS('lpProcessAffinityMask', 32, key=('api', 'lpProcessAffinityMask')) self.saffinity_mask = self.state.solver.BVS('lpSystemAffinityMask', 32, key=('api', 'lpSystemAffinityMask')) def fill_concrete(self): self.paffinity_mask = self.state.solver.BVV(3, 32) self.saffinity_mask = self.state.solver.BVV(3, 32)
467
947
/*------------------------------------------------------------------------- * * o_opclass.h * Routines for orioledb operator classes list. * * Copyright (c) 2021-2022, Oriole DB Inc. * * IDENTIFICATION * contrib/orioledb/include/catalog/o_opclass.h * *------------------------------------------------------------------------- */ #ifndef __O_OPCLASS_H__ #define __O_OPCLASS_H__ #include "catalog/o_tables.h" #include "catalog/sys_trees.h" extern void o_opclass_init(void); extern void o_opclass_add_all(OTable *o_table); extern OOpclass *o_opclass_get(Oid datoid, Oid opclass); #endif /* __O_OPCLASS_H__ */
218
634
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.libraries; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; /** * @author nik */ public abstract class LibraryDetectionManager { public static LibraryDetectionManager getInstance() { return ServiceManager.getService(LibraryDetectionManager.class); } public abstract boolean processProperties(@Nonnull List<VirtualFile> files, @Nonnull LibraryPropertiesProcessor processor); @Nullable public abstract Pair<LibraryType<?>, LibraryProperties<?>> detectType(@Nonnull List<VirtualFile> files); public interface LibraryPropertiesProcessor { <P extends LibraryProperties> boolean processProperties(@Nonnull LibraryKind kind, @Nonnull P properties); } }
416
3,459
/* * Copyright 2016 requery.io * * 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 io.requery.processor; import io.requery.ReferentialAction; import javax.lang.model.element.TypeElement; import java.util.Objects; /** * Defines a reference to another type element from one entity into another. * * @author <NAME> */ class AssociativeReference { private final String name; private final ReferentialAction deleteAction; private final ReferentialAction updateAction; private final TypeElement referenceType; private final String referencedColumn; AssociativeReference(String name, TypeElement referenceType, String referencedColumn, ReferentialAction deleteAction, ReferentialAction updateAction) { this.name = name; this.referencedColumn = referencedColumn; this.referenceType = referenceType; this.deleteAction = deleteAction; this.updateAction = updateAction; } String name() { return name; } ReferentialAction deleteAction() { return deleteAction; } ReferentialAction updateAction() { return updateAction; } TypeElement referencedType() { return referenceType; } String referencedColumn() { return referencedColumn; } @Override public boolean equals(Object obj) { if (obj instanceof AssociativeReference) { AssociativeReference other = (AssociativeReference) obj; return Objects.equals(name, other.name) && Objects.equals(deleteAction, other.deleteAction) && Objects.equals(updateAction, other.updateAction) && Objects.equals(referenceType, other.referenceType) && Objects.equals(referencedColumn, other.referencedColumn); } return false; } @Override public int hashCode() { return Objects.hash(name, deleteAction, updateAction, referenceType, referencedColumn); } }
926
14,668
// Copyright 2021 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 COMPONENTS_UI_DEVTOOLS_VIEWS_UI_ELEMENT_WITH_METADATA_H_ #define COMPONENTS_UI_DEVTOOLS_VIEWS_UI_ELEMENT_WITH_METADATA_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "components/ui_devtools/ui_element.h" #include "ui/base/metadata/metadata_types.h" #include "ui/compositor/layer.h" #include "ui/gfx/geometry/rect.h" namespace ui_devtools { class UIElementWithMetaData : public UIElement { public: UIElementWithMetaData(const UIElementWithMetaData&) = delete; UIElementWithMetaData& operator=(const UIElementWithMetaData&) = delete; ~UIElementWithMetaData() override; // UIElement: std::vector<UIElement::ClassProperties> GetCustomPropertiesForMatchedStyle() const override; void GetVisible(bool* visible) const override; void SetVisible(bool visible) override; bool SetPropertiesFromString(const std::string& text) override; void InitSources() override; protected: UIElementWithMetaData(const UIElementType type, UIElementDelegate* delegate, UIElement* parent); // Returns the metadata for the class instance type for this specific element. virtual ui::metadata::ClassMetaData* GetClassMetaData() const = 0; // Returns an opaque pointer for the actual instance which this element // represents. virtual void* GetClassInstance() const = 0; // Returns the layer for the given element if one exists. Returns null if no // layer is currently available. virtual ui::Layer* GetLayer() const; }; } // namespace ui_devtools #endif // COMPONENTS_UI_DEVTOOLS_VIEWS_UI_ELEMENT_WITH_METADATA_H_
611
777
<reponame>google-ar/chromium // 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. // This file has been auto-generated by code_generator_v8.py. // DO NOT MODIFY! // This file has been generated from the Jinja2 template in // third_party/WebKit/Source/bindings/templates/union_container.cpp.tmpl // clang-format off #include "ArrayBufferOrArrayBufferViewOrDictionary.h" #include "bindings/core/v8/Dictionary.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8ArrayBuffer.h" #include "bindings/core/v8/V8ArrayBufferView.h" #include "core/dom/FlexibleArrayBufferView.h" namespace blink { ArrayBufferOrArrayBufferViewOrDictionary::ArrayBufferOrArrayBufferViewOrDictionary() : m_type(SpecificTypeNone) {} TestArrayBuffer* ArrayBufferOrArrayBufferViewOrDictionary::getAsArrayBuffer() const { DCHECK(isArrayBuffer()); return m_arrayBuffer; } void ArrayBufferOrArrayBufferViewOrDictionary::setArrayBuffer(TestArrayBuffer* value) { DCHECK(isNull()); m_arrayBuffer = value; m_type = SpecificTypeArrayBuffer; } ArrayBufferOrArrayBufferViewOrDictionary ArrayBufferOrArrayBufferViewOrDictionary::fromArrayBuffer(TestArrayBuffer* value) { ArrayBufferOrArrayBufferViewOrDictionary container; container.setArrayBuffer(value); return container; } TestArrayBufferView* ArrayBufferOrArrayBufferViewOrDictionary::getAsArrayBufferView() const { DCHECK(isArrayBufferView()); return m_arrayBufferView; } void ArrayBufferOrArrayBufferViewOrDictionary::setArrayBufferView(TestArrayBufferView* value) { DCHECK(isNull()); m_arrayBufferView = value; m_type = SpecificTypeArrayBufferView; } ArrayBufferOrArrayBufferViewOrDictionary ArrayBufferOrArrayBufferViewOrDictionary::fromArrayBufferView(TestArrayBufferView* value) { ArrayBufferOrArrayBufferViewOrDictionary container; container.setArrayBufferView(value); return container; } Dictionary ArrayBufferOrArrayBufferViewOrDictionary::getAsDictionary() const { DCHECK(isDictionary()); return m_dictionary; } void ArrayBufferOrArrayBufferViewOrDictionary::setDictionary(Dictionary value) { DCHECK(isNull()); m_dictionary = value; m_type = SpecificTypeDictionary; } ArrayBufferOrArrayBufferViewOrDictionary ArrayBufferOrArrayBufferViewOrDictionary::fromDictionary(Dictionary value) { ArrayBufferOrArrayBufferViewOrDictionary container; container.setDictionary(value); return container; } ArrayBufferOrArrayBufferViewOrDictionary::ArrayBufferOrArrayBufferViewOrDictionary(const ArrayBufferOrArrayBufferViewOrDictionary&) = default; ArrayBufferOrArrayBufferViewOrDictionary::~ArrayBufferOrArrayBufferViewOrDictionary() = default; ArrayBufferOrArrayBufferViewOrDictionary& ArrayBufferOrArrayBufferViewOrDictionary::operator=(const ArrayBufferOrArrayBufferViewOrDictionary&) = default; DEFINE_TRACE(ArrayBufferOrArrayBufferViewOrDictionary) { visitor->trace(m_arrayBuffer); visitor->trace(m_arrayBufferView); } void V8ArrayBufferOrArrayBufferViewOrDictionary::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, ArrayBufferOrArrayBufferViewOrDictionary& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) { if (v8Value.IsEmpty()) return; if (conversionMode == UnionTypeConversionMode::Nullable && isUndefinedOrNull(v8Value)) return; if (v8Value->IsArrayBuffer()) { TestArrayBuffer* cppValue = V8ArrayBuffer::toImpl(v8::Local<v8::Object>::Cast(v8Value)); impl.setArrayBuffer(cppValue); return; } if (v8Value->IsArrayBufferView()) { TestArrayBufferView* cppValue = V8ArrayBufferView::toImpl(v8::Local<v8::Object>::Cast(v8Value)); impl.setArrayBufferView(cppValue); return; } if (isUndefinedOrNull(v8Value) || v8Value->IsObject()) { Dictionary cppValue = Dictionary(isolate, v8Value, exceptionState); if (exceptionState.hadException()) return; impl.setDictionary(cppValue); return; } exceptionState.throwTypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or Dictionary)'"); } v8::Local<v8::Value> ToV8(const ArrayBufferOrArrayBufferViewOrDictionary& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) { switch (impl.m_type) { case ArrayBufferOrArrayBufferViewOrDictionary::SpecificTypeNone: return v8::Null(isolate); case ArrayBufferOrArrayBufferViewOrDictionary::SpecificTypeArrayBuffer: return ToV8(impl.getAsArrayBuffer(), creationContext, isolate); case ArrayBufferOrArrayBufferViewOrDictionary::SpecificTypeArrayBufferView: return ToV8(impl.getAsArrayBufferView(), creationContext, isolate); case ArrayBufferOrArrayBufferViewOrDictionary::SpecificTypeDictionary: return impl.getAsDictionary().v8Value(); default: NOTREACHED(); } return v8::Local<v8::Value>(); } ArrayBufferOrArrayBufferViewOrDictionary NativeValueTraits<ArrayBufferOrArrayBufferViewOrDictionary>::nativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { ArrayBufferOrArrayBufferViewOrDictionary impl; V8ArrayBufferOrArrayBufferViewOrDictionary::toImpl(isolate, value, impl, UnionTypeConversionMode::NotNullable, exceptionState); return impl; } } // namespace blink
1,659
2,151
<gh_stars>1000+ // Copyright 2017 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/common/media/cdm_host_file_path.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_version.h" #if defined(OS_MACOSX) #include "base/mac/bundle_locations.h" #include "chrome/common/chrome_constants.h" #endif #if defined(GOOGLE_CHROME_BUILD) namespace { // TODO(xhwang): Move this to a common place if needed. const base::FilePath::CharType kSignatureFileExtension[] = FILE_PATH_LITERAL(".sig"); // Returns the signature file path given the |file_path|. This function should // only be used when the signature file and the file are located in the same // directory. base::FilePath GetSigFilePath(const base::FilePath& file_path) { return file_path.AddExtension(kSignatureFileExtension); } } // namespace void AddCdmHostFilePaths( std::vector<media::CdmHostFilePath>* cdm_host_file_paths) { DVLOG(1) << __func__; DCHECK(cdm_host_file_paths); DCHECK(cdm_host_file_paths->empty()); #if defined(OS_WIN) static const base::FilePath::CharType* const kUnversionedFiles[] = { FILE_PATH_LITERAL("chrome.exe")}; static const base::FilePath::CharType* const kVersionedFiles[] = { FILE_PATH_LITERAL("chrome.dll"), FILE_PATH_LITERAL("chrome_child.dll")}; // Find where chrome.exe is installed. base::FilePath chrome_exe_dir; if (!base::PathService::Get(base::DIR_EXE, &chrome_exe_dir)) NOTREACHED(); base::FilePath version_dir(chrome_exe_dir.AppendASCII(CHROME_VERSION_STRING)); cdm_host_file_paths->reserve(arraysize(kUnversionedFiles) + arraysize(kVersionedFiles)); // Signature files are always in the version directory. for (size_t i = 0; i < arraysize(kUnversionedFiles); ++i) { base::FilePath file_path = chrome_exe_dir.Append(kUnversionedFiles[i]); base::FilePath sig_path = GetSigFilePath(version_dir.Append(kUnversionedFiles[i])); DVLOG(2) << __func__ << ": unversioned file " << i << " at " << file_path.value() << ", signature file " << sig_path.value(); cdm_host_file_paths->emplace_back(file_path, sig_path); } for (size_t i = 0; i < arraysize(kVersionedFiles); ++i) { base::FilePath file_path = version_dir.Append(kVersionedFiles[i]); DVLOG(2) << __func__ << ": versioned file " << i << " at " << file_path.value(); cdm_host_file_paths->emplace_back(file_path, GetSigFilePath(file_path)); } #elif defined(OS_MACOSX) base::FilePath chrome_framework_path = base::mac::FrameworkBundlePath().Append(chrome::kFrameworkExecutableName); // Framework signature is in the "Widevine Resources.bundle" next to the // framework directory, not next to the actual framework executable. static const base::FilePath::CharType kWidevineResourcesPath[] = FILE_PATH_LITERAL("Widevine Resources.bundle/Contents/Resources"); base::FilePath widevine_signature_path = base::mac::FrameworkBundlePath().DirName().Append(kWidevineResourcesPath); base::FilePath chrome_framework_sig_path = GetSigFilePath( widevine_signature_path.Append(chrome::kFrameworkExecutableName)); DVLOG(2) << __func__ << ": chrome_framework_path=" << chrome_framework_path.value() << ", signature_path=" << chrome_framework_sig_path.value(); cdm_host_file_paths->emplace_back(chrome_framework_path, chrome_framework_sig_path); #elif defined(OS_LINUX) base::FilePath chrome_exe_dir; if (!base::PathService::Get(base::DIR_EXE, &chrome_exe_dir)) NOTREACHED(); base::FilePath chrome_path = chrome_exe_dir.Append(FILE_PATH_LITERAL("chrome")); DVLOG(2) << __func__ << ": chrome_path=" << chrome_path.value(); cdm_host_file_paths->emplace_back(chrome_path, GetSigFilePath(chrome_path)); #endif // defined(OS_WIN) } #else // defined(GOOGLE_CHROME_BUILD) void AddCdmHostFilePaths( std::vector<media::CdmHostFilePath>* cdm_host_file_paths) { NOTIMPLEMENTED() << "CDM host file paths need to be provided for the CDM to " "verify the host."; } #endif // defined(GOOGLE_CHROME_BUILD)
1,688
614
<filename>sample/src/main/java/com/androidwind/androidquick/demo/features/design_patterns/observer/Server.java package com.androidwind.androidquick.demo.features.design_patterns.observer; import java.util.Observable; /** * @author ddnosh * @website http://blog.csdn.net/ddnosh */ public class Server extends Observable { private int time; public Server(int time) { this.time = time; } public void setTime(int time) { if (this.time == time) { setChanged();//一定要标注, 表明有数据变更, 需要通知订阅者 notifyObservers(time); } } }
270
5,964
<filename>experimental/PdfViewer/pdfparser/native/pdfapi/SkPdfCIDSystemInfoDictionary_autogen.cpp /* * Copyright 2013 Google Inc. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPdfCIDSystemInfoDictionary_autogen.h" #include "SkPdfNativeDoc.h" SkString SkPdfCIDSystemInfoDictionary::Registry(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Registry", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isAnyString()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->stringValue2(); // TODO(edisonn): warn about missing required field, assert for known good pdfs return SkString(); } bool SkPdfCIDSystemInfoDictionary::has_Registry() const { return get("Registry", "") != NULL; } SkString SkPdfCIDSystemInfoDictionary::Ordering(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Ordering", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isAnyString()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->stringValue2(); // TODO(edisonn): warn about missing required field, assert for known good pdfs return SkString(); } bool SkPdfCIDSystemInfoDictionary::has_Ordering() const { return get("Ordering", "") != NULL; } int64_t SkPdfCIDSystemInfoDictionary::Supplement(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Supplement", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isInteger()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->intValue(); // TODO(edisonn): warn about missing required field, assert for known good pdfs return 0; } bool SkPdfCIDSystemInfoDictionary::has_Supplement() const { return get("Supplement", "") != NULL; }
589
809
/** * @file * @brief Common array utilities and spread arrays. * @details * TODO array_foreach general overview. -- Eldar * <b>Spread array</b> is statically allocated array, which is initialized * (populated) in multiple compilation units. In other words you can define the * array itself in one unit and add elements to it in another unit. Except for * the way of definition and initialization, spread array is usual array, so * it can be declared and used at run time in regular manner. * * Just alike for usual arrays there are two general approaches for * iterating over (or determining size of) spread array. * - At compile time using the array name. See #ARRAY_SPREAD_SIZE(). * - At run time for those array which has a special element at the end of * array so-called terminator element (e.g. @c NULL). See * #ARRAY_SPREAD_DEF_TERMINATED(). * * Considering current use cases and some implementation issues, spread * arrays are always allocated in read-only data section as if you have defined * a regular array with @c const modifier (although you might not have to). To * prevent confusion and to take advantage of compiler type checking <b>always * include @c const modifier to element type</b> when defining spread array * with #ARRAY_SPREAD_DEF() and its derivatives or when declaring it using * @c extern. * * @date 13.06.10 * @author <NAME> */ #ifndef UTIL_ARRAY_H_ #define UTIL_ARRAY_H_ #include <module/embox/util/Array.h> /* Foreach iterators for generic arrays: with given size or null-terminated. */ /** * Iterates over the specified @a array of scalar values with given number of * elements. * * @param element * Iteration variable which takes a value of each element of the target * array one by one, up to the [@a size - 1]'th element. * @param array * The array to iterate over. * Evaluated only once that allows the argument to have side effects. * @param size * The array size. * Alike @a array the argument is evaluated only once too. */ #define array_foreach(element, array, size) \ __array_foreach(element, array, size) /** * Iterates over the specified array of (possibly) non-scalar values with given * number of elements using a pointer to access the elements. * * @param element_ptr * Iteration variable which takes a value pointing to each element of the * target array, starting from the value of the @a array head end advancing * up to the pointer to [@a size - 1]'th element. * @param array * The array to iterate over. * @param size * The array size. Evaluated once. * * @see array_foreach() */ #define array_foreach_ptr(element_ptr, array, size) \ __array_foreach_ptr(element_ptr, array, size) /** * Iterates over the specified @a array of scalar values until @c NULL is * reached. * * @param element * Iteration variable which takes a value of each element of the target * array one by one. * @param array * The array to iterate over. * Evaluated only once that allows the argument to have side effects. */ #define array_nullterm_foreach(element, array) \ __array_nullterm_foreach(element, array) /** * Iterates over an array starting at @a array_begin and advancing until * @a array_end is reached. * * @param element * Iteration variable which takes a value of each element of the target * array one by one. * @param array_begin * The pointer to start the iteration from. * Evaluated only once allowing the argument to have side effects. * @param array_end * The pointer denoting the array bound. * Alike @a array_begin it is evaluated only once too. */ #define array_range_foreach(element, array_begin, array_end) \ __array_range_foreach(element, array_begin, array_end) /** * Iterates over an array using a pointer to access its elements, starting at * @a array_begin and advancing until @a array_end is reached. * * @param element_ptr * Iteration variable which takes a value pointing to each element of the * target array one by one. * @param array_begin * The pointer to start the iteration from. Evaluated once. * @param array_end * The pointer denoting the array bound. Evaluated once. * * @see array_range_foreach() */ #define array_range_foreach_ptr(element_ptr, array_begin, array_end) \ __array_range_foreach_ptr(element_ptr, array_begin, array_end) /** * Analogs for spread array. */ #define array_spread_foreach(element, array) \ __array_spread_foreach(element, array) #define array_spread_foreach_ptr(element_ptr, array) \ __array_spread_foreach_ptr(element_ptr, array) #define array_spread_nullterm_foreach(element, array) \ __array_spread_nullterm_foreach(element, array) /* Static arrays with their size known at the compile-time. */ /** * Gets the length of the specified @a array. * The macro can be used only if the array length is known at the compile-time. * * @param array * The array to check size for. * @return * Number of array elements. * * @note * The array must be statically defined/declared, otherwise an incorrect * result is returned without any error or warning. */ #define ARRAY_SIZE(array) \ (sizeof(array) / sizeof(*(array))) /* Spread arrays and spread-specific iterators. */ /** * Defines a new spread array. * * @param element_type * The type of array elements with optional modifiers. * To control the scope of array definition the standard visibility modifiers * may be used. Thus, without any modifier the array is defined in the global * scope and could be referenced inside other compilation units. * @c static modifier forces the array to be defined in the file scope * and prevents any global symbol to be emitted to the resulting object. * Static spread array cannot be referenced outside the definition file, but * it remains accessible from other compilation units for elements addition * using #ARRAY_SPREAD_ADD() macro and its @link #ARRAY_SPREAD_ADD_NAMED * named derivative @endlink. * Do not forget to specify @c const modifier explicitly (see general docs). * @param name * The array name which is used to refer the array itself and to populate it * using #ARRAY_SPREAD_ADD(). * * @note * This command should be used in the file scope, outside of any block. * @note * The @a element_type must include @c const modifier (see general docs). */ #define ARRAY_SPREAD_DEF(element_type, name) \ __ARRAY_SPREAD_DEF(element_type, name) /** * Defines a new spread array ended up by the specified @a terminator element. * * @param element_type * The type of array elements with optional modifiers. * @param name * The array name which is used to refer the array itself and to populate it * using #ARRAY_SPREAD_ADD(). * @param terminator * An element indicating the array end (e.g. @c NULL pointer). * * @note * This command should be used in the file scope, outside of any block. * @note * The @a element_type must include @c const modifier (see general docs). * * @see ARRAY_SPREAD_DEF() * More detailed explanation of macro arguments. */ #define ARRAY_SPREAD_DEF_TERMINATED(element_type, name, terminator) \ __ARRAY_SPREAD_DEF_TERMINATED(element_type, name, terminator) /** * Array spread declaration */ #define ARRAY_SPREAD_DECLARE(element_type, name) \ __ARRAY_SPREAD_DECLARE(element_type, name) /** * Adds elements to the specified spread array. * * @param array_name * The name of the spread array to which to add elements. * @param ... * The elements to add. * * @note * This command should be used in the file scope, outside of any block. */ #define ARRAY_SPREAD_ADD(array_name, ...) \ __ARRAY_SPREAD_ADD(array_name, __VA_ARGS__) /** * Does the same as #ARRAY_SPREAD_ADD() but also puts a pointer to head of the * added sub-array into a variable with the specified name. * * @param array_name * The name of the spread array to which to add elements. * @param ptr_name * The variable name used to refer to the added sub-array. * @param ... * The elements to add. * * @note * This command should be used in the file scope, outside of any block. */ #define ARRAY_SPREAD_ADD_NAMED(array_name, ptr_name, ...) \ __ARRAY_SPREAD_ADD_NAMED(array_name, ptr_name, __VA_ARGS__) /** * Gets the length of the specified spread array. * * @param array_name * The array to check size for (must be a literal symbol). * @return * Actual number of array elements including terminator element (if any). */ #define ARRAY_SPREAD_SIZE(array_name) \ __ARRAY_SPREAD_SIZE(array_name) /** * Gets the length of the specified spread array without taking into an * account a terminator element (if any). * * @param array_name * The array to check size for (must be a literal symbol). * @return * Number of array elements except terminating (if any). If the target array * is not terminated then the result is the same as of #ARRAY_SPREAD_SIZE(). */ #define ARRAY_SPREAD_SIZE_IGNORE_TERMINATING(array_name) \ __ARRAY_SPREAD_SIZE_IGNORE_TERMINATING(array_name) #endif /* UTIL_ARRAY_H_ */
2,728
395
<reponame>jonathan-stein/timely package timely.store.compaction.util; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.OptionalLong; import java.util.concurrent.TimeUnit; import org.apache.hadoop.io.Text; import timely.store.compaction.TabletRowAdapter; public class MetadataAccumulator { private final List<Entry> list; private Entry currentEntry; public MetadataAccumulator() { this.list = new LinkedList<>(); } public Entry checkEntryState(Text tablet) { // entry may be null on initial invocation or after the pushOrDiscard operation // check to see if the tablet has changed, if so then // push or discard the current state if (currentEntry != null && !tablet.equals(currentEntry.getTablet())) { pushOrDiscardEntry(); } if (currentEntry == null) { currentEntry = new Entry(tablet); } return currentEntry; } public Collection<Entry> getEntries() { return Collections.unmodifiableCollection(list); } public void ensureState() { pushOrDiscardEntry(); } private void pushOrDiscardEntry() { if (currentEntry != null && currentEntry.hasFiles()) { list.add(currentEntry); } currentEntry = null; } public static class Entry { private final Text tablet; private final String tabletPrefix; private final boolean hasTabletOffset; private final long tabletOffset; private Text tabletPrev; private long milliseconds; private long totalBytes; private int totalFiles; public Entry(Text tablet) { this.tablet = tablet; Optional<String> prefixOptional = TabletRowAdapter.decodeRowPrefix(tablet); OptionalLong offsetOptional = TabletRowAdapter.decodeRowOffset(tablet); tabletPrefix = prefixOptional.orElseGet(tablet::toString); if (offsetOptional.isPresent()) { hasTabletOffset = true; tabletOffset = offsetOptional.getAsLong(); } else { hasTabletOffset = false; tabletOffset = -1; } } public String getTabletPrefix() { return tabletPrefix; } public Text getTablet() { return tablet; } public Text getTabletPrev() { return tabletPrev; } public long getMilliseconds() { return milliseconds; } public long getTotalFileBytes() { return totalBytes; } public int getTotalFiles() { return totalFiles; } public OptionalLong getTabletOffset() { return hasTabletOffset ? OptionalLong.of(tabletOffset) : OptionalLong.empty(); } public boolean hasFiles() { return totalFiles > 0; } public void addFile(long size) { totalFiles++; totalBytes += size; } public void setTablePrev(Text prev) { tabletPrev = prev; } public void setMilliseconds(long val) { milliseconds = val; } @Override public String toString() { return String.format("metadata.entry {tablet: %s, millis: %d, offset-ms: %d, age-days: %d, files %d}", tablet, milliseconds, tabletOffset, (hasTabletOffset ? TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - tabletOffset) : -1), totalFiles); } } }
1,607
643
// Generated automatically from okhttp3.Authenticator for testing purposes package okhttp3; import okhttp3.Request; import okhttp3.Response; import okhttp3.Route; public interface Authenticator { Request authenticate(Route p0, Response p1); static Authenticator JAVA_NET_AUTHENTICATOR = null; static Authenticator NONE = null; static Authenticator.Companion Companion = null; static public class Companion { protected Companion() {} } }
150
988
<filename>platform/api.search/test/unit/src/org/netbeans/modules/search/SearchScopeListTest.java /* * 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.search; import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.search.provider.SearchInfo; import org.netbeans.junit.MockServices; import org.netbeans.junit.NbTestCase; import org.netbeans.spi.search.SearchScopeDefinition; import org.netbeans.spi.search.SearchScopeDefinitionProvider; import org.openide.util.Mutex; /** * * @author jhavlin */ public class SearchScopeListTest extends NbTestCase { public SearchScopeListTest(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); MockServices.setServices(CustomSearchScopeDefinitionProvider.class); } /** * Test for bug 204118 - [71cat] AssertionError at * org.netbeans.modules.search.SearchScopeRegistry.addChangeListener. */ public void testAddChangeListener() throws InterruptedException, InvocationTargetException { final CustomChangeListener cl = new CustomChangeListener(); final CustomChangeListener cl2 = new CustomChangeListener(); final SearchScopeList ssl = new SearchScopeList(); ssl.addChangeListener(cl); ssl.addChangeListener(cl2); Mutex.EVENT.writeAccess((Mutex.Action<Boolean>) () -> { for (SearchScopeDefinition ssd : ssl.getSeachScopeDefinitions()) { if (ssd instanceof CustomSearchScope) { ((CustomSearchScope) ssd).fireChangeEvent(); } } return true; }); assertEquals(3, cl.getCounter()); assertEquals(3, cl.getCounter()); } public void testSearchScopesNotifiedAboutChangesInEDT() throws InterruptedException { CustomSearchScope css = new CustomSearchScope(true, 1); SearchScopeList ssl = new SearchScopeList(css); final Semaphore s = new Semaphore(0); final AtomicBoolean notifiedInEDT = new AtomicBoolean(false); ssl.addChangeListener((ChangeEvent e) -> { notifiedInEDT.set(EventQueue.isDispatchThread()); s.release(); }); css.fireChangeEvent(); boolean acqrd = s.tryAcquire(10, TimeUnit.SECONDS); assertTrue("Should be notified in EDT", acqrd && notifiedInEDT.get()); } /** * Change listener implementation for the tests above. */ private class CustomChangeListener implements ChangeListener { int counter = 0; @Override public void stateChanged(ChangeEvent e) { counter ++; } public int getCounter() { return counter; } } public void testSorting() { SearchScopeList ssl = new SearchScopeList(); List<SearchScopeDefinition> defs = ssl.getSeachScopeDefinitions(); assertEquals(1, defs.get(0).getPriority()); assertEquals(2, defs.get(1).getPriority()); assertEquals(3, defs.get(2).getPriority()); ssl.clean(); } /** * Search scope implementation for the tests above. */ public static class CustomSearchScope extends SearchScopeDefinition { private boolean applicable = true; private int priority; private Set<ChangeListener> listeners = new HashSet<>(); public CustomSearchScope(boolean applicable, int priority) { this.applicable = applicable; this.priority = priority; } @Override public String getTypeId() { return "TEST"; } @Override public String getDisplayName() { return "Test Search Scope"; } @Override public synchronized boolean isApplicable() { return applicable; } @Override public SearchInfo getSearchInfo() { throw new UnsupportedOperationException("Not supported yet."); } public void setApplicable(boolean applicable) { Set<ChangeListener> listenersCopy = null; synchronized (this) { boolean oldVal = this.applicable; this.applicable = applicable; if (applicable != oldVal) { listenersCopy = new HashSet<>(listeners); } } for (ChangeListener l : listenersCopy) { l.stateChanged(new ChangeEvent(this)); } } @Override public int getPriority() { return priority; } @Override public void clean() { } public void fireChangeEvent() { notifyListeners(); } } public static class CustomSearchScopeDefinitionProvider extends SearchScopeDefinitionProvider { @Override public List<SearchScopeDefinition> createSearchScopeDefinitions() { List<SearchScopeDefinition> list = new LinkedList<>(); list.add(new CustomSearchScope(true, 2)); list.add(new CustomSearchScope(true, 1)); list.add(new CustomSearchScope(false, 3)); return list; } } }
2,533
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Transport; using namespace Client; using namespace ClientServerTransport; using namespace ServiceModel; using namespace SystemServices; using namespace Management::ResourceManager; /* Resource Registration */ unordered_map<wstring, ResourceManagerMessage::ResourceRegistration const> const ResourceManagerMessage::resourceRegistrationMap_{ // Secret from Central Secret Store { *ResourceTypes::Secret, ResourceRegistration(Actor::CSS, CreateSecretRequestMessage) } }; GlobalWString ResourceManagerMessage::ClaimResourceAction = make_global<wstring>(L"ClaimResourceAction"); GlobalWString ResourceManagerMessage::ReleaseResourceAction = make_global<wstring>(L"ReleaseResourceAction"); ResourceManagerMessage::ResourceManagerMessage( wstring const & action, Actor::Enum const & actor, unique_ptr<ClientServerMessageBody> && body, Common::ActivityId const & activityId) : ClientServerRequestMessage(action, actor, std::move(body), activityId) { } ResourceManagerMessage::ResourceManagerMessage( wstring const & action, Actor::Enum const & actor, Common::ActivityId const & activityId) : ClientServerRequestMessage(action, actor, activityId) { } ClientServerRequestMessageUPtr ResourceManagerMessage::CreateRequestMessage( wstring const & action, ResourceIdentifier const & resourceId, unique_ptr<ClientServerMessageBody> && body, Common::ActivityId const & activityId) { auto element = resourceRegistrationMap_.find(resourceId.ResourceType); if (element == resourceRegistrationMap_.end()) { Assert::CodingError("Unknown resource type: {0}, ResourceIdentifier = {1}.", resourceId.ResourceType, resourceId); } return element->second.MessageConstructor(action, element->second.Actor, resourceId, move(body), activityId); } ResourceManagerMessage::ResourceRegistration::ResourceRegistration( Actor::Enum const & actor, ResourceManagerRequestMessageConstructor const & messageConstructor) : Actor(actor) , MessageConstructor(messageConstructor) { } /** * Resource Message Constructors */ /* Default Resource Manager Request Message Constructor */ ClientServerRequestMessageUPtr ResourceManagerMessage::CreateDefaultRequestMessage( wstring const & action, Actor::Enum const & actor, ResourceIdentifier const & resourceId, unique_ptr<ClientServerMessageBody> && body, Common::ActivityId const & activityId) { UNREFERENCED_PARAMETER(resourceId); return make_unique<ResourceManagerMessage>(action, actor, move(body), activityId); } /* Secret Store Service Request Message Constructor */ ClientServerRequestMessageUPtr ResourceManagerMessage::CreateSecretRequestMessage( wstring const & action, Actor::Enum const & actor, ResourceIdentifier const & resourceId, unique_ptr<ClientServerMessageBody> && body, Common::ActivityId const & activityId) { UNREFERENCED_PARAMETER(actor); UNREFERENCED_PARAMETER(resourceId); return CentralSecretServiceMessage::CreateRequestMessage(action, move(body), activityId); }
928
432
<gh_stars>100-1000 #include <stdio.h> int close_stream (FILE *stream);
28
628
_BASIC_META(DRM_IOCTL_LIMA_GET_PARAM) _BASIC_META(DRM_IOCTL_LIMA_GEM_CREATE) _BASIC_META(DRM_IOCTL_LIMA_GEM_INFO) _BASIC_META(DRM_IOCTL_LIMA_GEM_SUBMIT) _BASIC_META(DRM_IOCTL_LIMA_GEM_WAIT) _BASIC_META(DRM_IOCTL_LIMA_CTX_CREATE) _BASIC_META(DRM_IOCTL_LIMA_CTX_FREE)
180
2,542
<reponame>gridgentoo/ServiceFabricAzure //------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace Naming; using namespace ServiceModel; using namespace std; using namespace Management::FaultAnalysisService; StringLiteral const TraceComponent("ChaosScheduleJobActiveDays"); ChaosScheduleJobActiveDays::ChaosScheduleJobActiveDays() : sunday_() , monday_() , tuesday_() , wednesday_() , thursday_() , friday_() , saturday_() { } ErrorCode ChaosScheduleJobActiveDays::FromPublicApi( FABRIC_CHAOS_SCHEDULE_JOB_ACTIVE_DAYS const & publicDays) { sunday_ = publicDays.Sunday; monday_ = publicDays.Monday; tuesday_ = publicDays.Tuesday; wednesday_ = publicDays.Wednesday; thursday_ = publicDays.Thursday; friday_ = publicDays.Friday; saturday_ = publicDays.Saturday; return ErrorCodeValue::Success; } ErrorCode ChaosScheduleJobActiveDays::ToPublicApi( __in Common::ScopedHeap & heap, __out FABRIC_CHAOS_SCHEDULE_JOB_ACTIVE_DAYS & result) const { UNREFERENCED_PARAMETER(heap); result.Sunday = sunday_; result.Monday = monday_; result.Tuesday = tuesday_; result.Wednesday = wednesday_; result.Thursday = thursday_; result.Friday = friday_; result.Saturday = saturday_; return ErrorCodeValue::Success; }
513
672
// Copyright(c) 2015-present, <NAME> & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include <spdlog/common.h> #include <tuple> namespace spdlog { namespace details { // Helper class for file sinks. // When failing to open a file, retry several times(5) with a delay interval(10 ms). // Throw spdlog_ex exception on errors. class SPDLOG_API file_helper { public: explicit file_helper() = default; file_helper(const file_helper &) = delete; file_helper &operator=(const file_helper &) = delete; ~file_helper(); void open(const filename_t &fname, bool truncate = false); void reopen(bool truncate); void flush(); void close(); void write(const memory_buf_t &buf); size_t size() const; const filename_t &filename() const; // // return file path and its extension: // // "mylog.txt" => ("mylog", ".txt") // "mylog" => ("mylog", "") // "mylog." => ("mylog.", "") // "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt") // // the starting dot in filenames is ignored (hidden files): // // ".mylog" => (".mylog". "") // "my_folder/.mylog" => ("my_folder/.mylog", "") // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname); private: const int open_tries_ = 5; const unsigned int open_interval_ = 10; std::FILE *fd_{nullptr}; filename_t filename_; }; } // namespace details } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY # include "file_helper-inl.h" #endif
628
1,041
// Generated from /home/rob/github/ebean-dir/ebean/src/test/resources/EQL.g4 by ANTLR 4.8 package io.ebeaninternal.server.grammer.antlr; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link EQLParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface EQLVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link EQLParser#select_statement}. * @param ctx the parse tree * @return the visitor result */ T visitSelect_statement(EQLParser.Select_statementContext ctx); /** * Visit a parse tree produced by {@link EQLParser#select_properties}. * @param ctx the parse tree * @return the visitor result */ T visitSelect_properties(EQLParser.Select_propertiesContext ctx); /** * Visit a parse tree produced by {@link EQLParser#select_clause}. * @param ctx the parse tree * @return the visitor result */ T visitSelect_clause(EQLParser.Select_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#distinct}. * @param ctx the parse tree * @return the visitor result */ T visitDistinct(EQLParser.DistinctContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_clause}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_clause(EQLParser.Fetch_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#where_clause}. * @param ctx the parse tree * @return the visitor result */ T visitWhere_clause(EQLParser.Where_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#orderby_clause}. * @param ctx the parse tree * @return the visitor result */ T visitOrderby_clause(EQLParser.Orderby_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#orderby_property}. * @param ctx the parse tree * @return the visitor result */ T visitOrderby_property(EQLParser.Orderby_propertyContext ctx); /** * Visit a parse tree produced by {@link EQLParser#nulls_firstlast}. * @param ctx the parse tree * @return the visitor result */ T visitNulls_firstlast(EQLParser.Nulls_firstlastContext ctx); /** * Visit a parse tree produced by {@link EQLParser#asc_desc}. * @param ctx the parse tree * @return the visitor result */ T visitAsc_desc(EQLParser.Asc_descContext ctx); /** * Visit a parse tree produced by {@link EQLParser#limit_clause}. * @param ctx the parse tree * @return the visitor result */ T visitLimit_clause(EQLParser.Limit_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#offset_clause}. * @param ctx the parse tree * @return the visitor result */ T visitOffset_clause(EQLParser.Offset_clauseContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_path}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_path(EQLParser.Fetch_pathContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_property_set}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_property_set(EQLParser.Fetch_property_setContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_property_group}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_property_group(EQLParser.Fetch_property_groupContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_path_path}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_path_path(EQLParser.Fetch_path_pathContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_property}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_property(EQLParser.Fetch_propertyContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_query_hint}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_query_hint(EQLParser.Fetch_query_hintContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_lazy_hint}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_lazy_hint(EQLParser.Fetch_lazy_hintContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_option}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_option(EQLParser.Fetch_optionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_query_option}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_query_option(EQLParser.Fetch_query_optionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_lazy_option}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_lazy_option(EQLParser.Fetch_lazy_optionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#fetch_batch_size}. * @param ctx the parse tree * @return the visitor result */ T visitFetch_batch_size(EQLParser.Fetch_batch_sizeContext ctx); /** * Visit a parse tree produced by {@link EQLParser#conditional_expression}. * @param ctx the parse tree * @return the visitor result */ T visitConditional_expression(EQLParser.Conditional_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#conditional_term}. * @param ctx the parse tree * @return the visitor result */ T visitConditional_term(EQLParser.Conditional_termContext ctx); /** * Visit a parse tree produced by {@link EQLParser#conditional_factor}. * @param ctx the parse tree * @return the visitor result */ T visitConditional_factor(EQLParser.Conditional_factorContext ctx); /** * Visit a parse tree produced by {@link EQLParser#conditional_primary}. * @param ctx the parse tree * @return the visitor result */ T visitConditional_primary(EQLParser.Conditional_primaryContext ctx); /** * Visit a parse tree produced by {@link EQLParser#any_expression}. * @param ctx the parse tree * @return the visitor result */ T visitAny_expression(EQLParser.Any_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#inOrEmpty_expression}. * @param ctx the parse tree * @return the visitor result */ T visitInOrEmpty_expression(EQLParser.InOrEmpty_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#in_expression}. * @param ctx the parse tree * @return the visitor result */ T visitIn_expression(EQLParser.In_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#in_value}. * @param ctx the parse tree * @return the visitor result */ T visitIn_value(EQLParser.In_valueContext ctx); /** * Visit a parse tree produced by {@link EQLParser#between_expression}. * @param ctx the parse tree * @return the visitor result */ T visitBetween_expression(EQLParser.Between_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#inrange_expression}. * @param ctx the parse tree * @return the visitor result */ T visitInrange_expression(EQLParser.Inrange_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#inrange_op}. * @param ctx the parse tree * @return the visitor result */ T visitInrange_op(EQLParser.Inrange_opContext ctx); /** * Visit a parse tree produced by {@link EQLParser#propertyBetween_expression}. * @param ctx the parse tree * @return the visitor result */ T visitPropertyBetween_expression(EQLParser.PropertyBetween_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#isNull_expression}. * @param ctx the parse tree * @return the visitor result */ T visitIsNull_expression(EQLParser.IsNull_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#isNotNull_expression}. * @param ctx the parse tree * @return the visitor result */ T visitIsNotNull_expression(EQLParser.IsNotNull_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#isEmpty_expression}. * @param ctx the parse tree * @return the visitor result */ T visitIsEmpty_expression(EQLParser.IsEmpty_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#isNotEmpty_expression}. * @param ctx the parse tree * @return the visitor result */ T visitIsNotEmpty_expression(EQLParser.IsNotEmpty_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#like_expression}. * @param ctx the parse tree * @return the visitor result */ T visitLike_expression(EQLParser.Like_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#like_op}. * @param ctx the parse tree * @return the visitor result */ T visitLike_op(EQLParser.Like_opContext ctx); /** * Visit a parse tree produced by {@link EQLParser#comparison_expression}. * @param ctx the parse tree * @return the visitor result */ T visitComparison_expression(EQLParser.Comparison_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#comparison_operator}. * @param ctx the parse tree * @return the visitor result */ T visitComparison_operator(EQLParser.Comparison_operatorContext ctx); /** * Visit a parse tree produced by {@link EQLParser#value_expression}. * @param ctx the parse tree * @return the visitor result */ T visitValue_expression(EQLParser.Value_expressionContext ctx); /** * Visit a parse tree produced by {@link EQLParser#literal}. * @param ctx the parse tree * @return the visitor result */ T visitLiteral(EQLParser.LiteralContext ctx); }
3,168
431
#ifndef TST_FILTERCHAIN_H #define TST_FILTERCHAIN_H #include <QtTest> #include <cwf/filterchain.h> class TST_FilterChain : public QObject { Q_OBJECT private slots: void test(); }; #endif // TST_FILTERCHAIN_H
111
631
/***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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.openni; /** * Enables a node to report that it is in "Error" status. <BR><BR> * * This capability is normally accessed by requesting it with the GetErrorStateCapability(), a * member function of the ProductionNode class. <BR><BR> * * Provides the following events: * errorStateChanged: Triggered when the error state of the node changes * */ public class ErrorStateCapability extends CapabilityBase { /** * Creates a new ErrorStateCapability object for a given node * @param node Node to create the capability for * @throws StatusException If underlying native code returns errors, Status Exception is thrown by this function */ public ErrorStateCapability(ProductionNode node) throws StatusException { super(node); this.errorStateChanged = new StateChangedObservable() { @Override protected int registerNative(String cb, OutArg<Long> phCallback) { return NativeMethods.xnRegisterToNodeErrorStateChange(toNative(), this, cb, phCallback); } @Override protected void unregisterNative(long hCallback) { NativeMethods.xnUnregisterFromNodeErrorStateChange(toNative(), hCallback); } }; } /** * Provides access to the current error state of the node associated with this capability * @return Current error state */ public String getErrorState() { int status = NativeMethods.xnGetNodeErrorState(toNative()); if (status == 0) { return null; } else { return NativeMethods.xnGetStatusString(status); } } /** * Provides access to the Error State Changed event * @return */ public IStateChangedObservable getErrorStateChangedEvent() { return this.errorStateChanged; } private StateChangedObservable errorStateChanged; }
1,569
338
package fr.lteconsulting.pomexplorer.depanalyze; import fr.lteconsulting.pomexplorer.PomSection; import fr.lteconsulting.pomexplorer.Project; import fr.lteconsulting.pomexplorer.graph.relation.Scope; import fr.lteconsulting.pomexplorer.model.Gav; public class GavLocation extends Location { private final PomSection section; private Gav gav; private Gav unresolvedGav; private Scope scope; private String classifier; private String type; public GavLocation( Project project, PomSection section, Gav gav ) { this( project, section, gav, gav ); } public GavLocation( Project project, PomSection section, Gav resolvedGav, Gav unresolvedGav ) { this( project, section, resolvedGav, unresolvedGav, null, null, "jar" ); } public GavLocation( Project project, PomSection section, Gav resolvedGav, Gav unresolvedGav, String scope, String classifier, String type ) { super( project, null ); this.section = section; this.gav = resolvedGav; this.unresolvedGav = unresolvedGav; this.scope = Scope.fromString( scope ); this.classifier = classifier; this.type = type; } public Scope getScope() { return scope; } public String getClassifier() { return classifier; } public PomSection getSection() { return section; } public String getType() { return type; } public Gav getGav() { if( gav != null ) return gav; return unresolvedGav; } public Gav getResolvedGav() { return gav; } public Gav getUnresolvedGav() { return unresolvedGav; } @Override public String toString() { String res = "[" + section + "] "; if( gav != null && unresolvedGav != null ) { if( gav.equals( unresolvedGav ) ) res += gav.toString(); else res += "[*] " + gav + " / " + unresolvedGav; } else { if( gav != null ) res = gav.toString(); else if( unresolvedGav != null ) res += "[unresolved]" + unresolvedGav; else res += "[!!!] NULL"; } return res; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((gav == null) ? 0 : gav.hashCode()); result = prime * result + ((section == null) ? 0 : section.hashCode()); result = prime * result + ((unresolvedGav == null) ? 0 : unresolvedGav.hashCode()); return result; } @Override public boolean equals( Object obj ) { if( this == obj ) return true; if( !super.equals( obj ) ) return false; if( getClass() != obj.getClass() ) return false; GavLocation other = (GavLocation) obj; if( gav == null ) { if( other.gav != null ) return false; } else if( !gav.equals( other.gav ) ) return false; if( section != other.section ) return false; if( unresolvedGav == null ) { if( other.unresolvedGav != null ) return false; } else if( !unresolvedGav.equals( other.unresolvedGav ) ) return false; return true; } }
1,124
683
package cn.byhieg.threadtutorial.char01; /** * Created by shiqifeng on 2016/12/27. * Mail <EMAIL> */ public class ExampleCurrentThread extends Thread{ public ExampleCurrentThread(){ System.out.println("构造方法的打印:" + Thread.currentThread().getName()); } @Override public void run() { super.run(); System.out.println("run方法的打印:" + Thread.currentThread().getName()); } }
176
455
<filename>app/src/main/java/com/jecelyin/editor/v2/adapter/IntentChooserAdapter.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * 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.jecelyin.editor.v2.adapter; import android.content.Context; import android.content.pm.ResolveInfo; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.jecelyin.editor.v2.R; import java.util.List; /** * @author <NAME> <<EMAIL>> */ public class IntentChooserAdapter extends RecyclerView.Adapter<IntentChooserAdapter.IntentViewHolder> { private final Context context; private final List<ResolveInfo> apps; private OnIntentItemSelectedListener onIntentItemSelectedListener; public interface OnIntentItemSelectedListener { void onItemSelected(ResolveInfo ri); } public IntentChooserAdapter(Context context, List<ResolveInfo> apps) { this.context = context; this.apps = apps; } public void setOnIntentItemSelectedListener(OnIntentItemSelectedListener onIntentItemSelectedListener) { this.onIntentItemSelectedListener = onIntentItemSelectedListener; } @Override public IntentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new IntentViewHolder(LayoutInflater.from(context).inflate(R.layout.intent_chooser_listitem, parent, false)); } @Override public void onBindViewHolder(IntentViewHolder holder, int position) { final ResolveInfo info = apps.get(position); holder.titleTextView.setText(info.activityInfo.loadLabel(context.getPackageManager())); holder.iconImageView.setImageDrawable(info.activityInfo.loadIcon(context.getPackageManager())); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onIntentItemSelectedListener != null) { onIntentItemSelectedListener.onItemSelected(info); } } }); } @Override public long getItemId(int position) { return 0; } @Override public int getItemCount() { return apps == null ? 0 : apps.size(); } static class IntentViewHolder extends RecyclerView.ViewHolder { ImageView iconImageView; TextView titleTextView; public IntentViewHolder(View itemView) { super(itemView); iconImageView = (ImageView) itemView.findViewById(R.id.iconImageView); titleTextView = (TextView) itemView.findViewById(R.id.title_text_view); } } }
1,191