max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,286
#include "pdbimpl.h" #include "pdbcommon.h" #include "locator.h" #ifdef _DEBUG // Do some support for devenv and other processes for using vsassert instead of this typedef BOOL (__stdcall *PfnVsAssert)( SZ_CONST szMsg, SZ_CONST szAssert, SZ_CONST szFile, UINT line, BOOL * pfDisableAssert ); // List of process names we try to use VsAssert for const wchar_t * const rgszVsAssertProcesses[] = { L"concordeetest", L"devenv", L"glass2", L"glass3", L"msvsmon", L"natvisvalidator", L"pdbexplorer", L"rascal", L"rascalpro", L"vpdexpress", L"vswinexpress", L"wdexpress", NULL }; const wchar_t * const rgszVsAssertDlls[] = { L"diasymreader", L"shmetapdb", L"cpde", NULL }; const wchar_t szVsAssertDll[] = L"vsassert.dll"; const char szVsAssertProc[] = "_VsAssert@20"; extern "C" const IMAGE_DOS_HEADER __ImageBase; static void BaseName(__inout_ecount_z(cchModule) wchar_t *szModule, size_t cchModule) { // generate the base name of the filename back into the same buffer wchar_t szFile[_MAX_PATH]; _wsplitpath_s(szModule, NULL, 0, NULL, 0, szFile, _countof(szFile), NULL, 0); wcscpy_s(szModule, cchModule, szFile); } template <size_t cchModule> static void BaseName(wchar_t (&szModule)[cchModule]) { BaseName(szModule, cchModule); } static bool fVsAssertDllOrProcess() { HMODULE hmodMe = HMODULE(&__ImageBase); // Check for various executables wchar_t szProcessName[_MAX_PATH]; wchar_t szMyName[_MAX_PATH]; if (GetModuleFileNameW(hmodMe, szMyName, _countof(szMyName))) { BaseName(szMyName); unsigned isz; for (isz = 0; rgszVsAssertDlls[isz] != NULL; isz++) { if (_wcsicmp(szMyName, rgszVsAssertDlls[isz]) == 0) { break; } } if (rgszVsAssertDlls[isz] != NULL) { return true; } } if (GetModuleFileNameW(NULL, szProcessName, _countof(szProcessName))) { BaseName(szProcessName); unsigned isz; for (isz = 0; rgszVsAssertProcesses[isz] != NULL; isz++) { if (_wcsicmp(szProcessName, rgszVsAssertProcesses[isz]) == 0) { break; } } if (rgszVsAssertProcesses[isz] != NULL) { return true; } } return false; } static bool fVsAssert(SZ_CONST szAssertFile, SZ_CONST szFunc, int line, SZ_CONST szCond) { bool fRet = false; // vsassert did/did not handle the assert if (fVsAssertDllOrProcess()) { HMODULE hmodVsAssert = GetModuleHandleW(szVsAssertDll); if (hmodVsAssert == NULL) { // Try LoadLibrary() hmodVsAssert = LoadLibraryExW(szVsAssertDll, NULL, 0); } if (hmodVsAssert != NULL) { PfnVsAssert pfn = PfnVsAssert(GetProcAddress(hmodVsAssert, szVsAssertProc)); if (pfn) { char szMessage[1024] = ""; char szCondition[] = ""; if (szFunc) { _snprintf_s( szMessage, _countof(szMessage), _TRUNCATE, "Failure in function %s", szFunc ); } if (!szCond) { szCond = szCondition; } BOOL fDisable = FALSE; pfn(szMessage, szCond, szAssertFile, UINT(line), &fDisable); fRet = true; } } } return fRet; } extern "C" void failAssertion(SZ_CONST szAssertFile, int line) { if (fVsAssert(szAssertFile, NULL, line, NULL)) { } else { fprintf(stderr, "assertion failure: file %s, line %d\n", szAssertFile, line); fflush(stderr); DebugBreak(); } } extern "C" void failExpect(SZ_CONST szFile, int line) { fprintf(stderr, "expectation failure: file %s, line %d\n", szFile, line); fflush(stderr); } extern "C" void failAssertionFunc(SZ_CONST szAssertFile, SZ_CONST szFunction, int line, SZ_CONST szCond) { if (fVsAssert(szAssertFile, szFunction, line, szCond)) { } // Still don't know what to do with mspdbsrv.exe yet. else { fprintf( stderr, "assertion failure:\n\tfile: %s,\n\tfunction: %s,\n\tline: %d,\n\tcondition(%s)\n\n", szAssertFile, szFunction, line, szCond ); fflush(stderr); DebugBreak(); } } extern "C" void failExpectFunc(SZ_CONST szFile, SZ_CONST szFunction, int line, SZ_CONST szCond) { fprintf( stderr, "expectation failure:\n\tfile: %s,\n\tfunction: %s,\n\tline: %d,\n\tcondition(%s)\n\n", szFile, szFunction, line, szCond ); fflush(stderr); } #endif extern const long cbPgPdbDef = 1024; BOOL PDBCommon::Open2W(const wchar_t *wszPDB, const char *szMode, OUT EC *pec, __out_ecount_opt(cchErrMax) wchar_t *wszError, size_t cchErrMax, OUT PDB **pppdb) { PDBLOG_FUNC(); dassert(wszPDB); dassert(szMode); dassert(pec); dassert(pppdb); return OpenEx2W(wszPDB, szMode, ::cbPgPdbDef, pec, wszError, cchErrMax, pppdb); } BOOL PDBCommon::OpenValidate5(const wchar_t *wszExecutable, const wchar_t *wszSearchPath, void *pvClient, PfnPDBQueryCallback pfnQueryCallback, OUT EC *pec, __out_ecount_opt(cchErrMax) wchar_t *wszError, size_t cchErrMax, OUT PDB **pppdb) { PDBLOG_FUNC(); dassert(wszExecutable); dassert(pec); dassert(pppdb); *pppdb = NULL; LOCATOR locator; locator.SetPvClient(pvClient); locator.SetPfnQueryCallback(pfnQueryCallback); if (!locator.FCrackExeOrDbg(wszExecutable) || !locator.FLocateDbg(wszSearchPath)) { HandleError: setError(pec, locator.Ec(), wszError, cchErrMax, locator.WszError()); return FALSE; } if (!locator.FLocatePdb(wszSearchPath)) { goto HandleError; } *pppdb = locator.Ppdb(); *pec = EC_OK; #ifdef PDB_TYPESERVER ((PDBCommon *) *pppdb)->setExeNameW(wszExecutable); #endif return TRUE; } EC PDBCommon::QueryLastError(char szErr[cbErrMax]) { PDBLOG_FUNC(); wchar_t wszErrLast[cbErrMax]; EC ecLast = QueryLastErrorExW(wszErrLast, cbErrMax); if (szErr != NULL) { if (WideCharToMultiByte(CP_ACP, 0, wszErrLast, -1, szErr, cbErrMax, NULL, NULL) == 0) { // Conversion failed szErr[0] = '\0'; } } return ecLast; } BOOL PDBCommon::CopyTo(const char *szPdbOut, DWORD dwCopyFilter, DWORD dwReserved) { wchar_t wszPdbOut[_MAX_PATH]; if (MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szPdbOut, -1, wszPdbOut, _MAX_PATH) == 0) { // If we can't convert then the file will not be found //setLastError(EC_NOT_FOUND, szPdbOut); return FALSE; } return CopyToW2(wszPdbOut, dwCopyFilter, NULL, NULL); } BOOL PDBCommon::CopyToW(const wchar_t *wszPdbOut, DWORD dwCopyFilter, DWORD dwReserved) { return CopyToW2(wszPdbOut, dwCopyFilter, NULL, NULL); } BOOL PDBCommon::OpenStream(SZ_CONST sz, OUT Stream** ppstream) { return OpenStreamEx(sz, pdbRead pdbWriteShared, ppstream); } BOOL PDBCommon::OpenStreamW(const wchar_t * wszStream, OUT Stream** ppstream) { USES_STACKBUFFER(0x400); SZ utf8szStream = GetSZUTF8FromSZUnicode(wszStream); if (!utf8szStream) return FALSE; return OpenStream(utf8szStream, ppstream); }
3,926
390
<reponame>fengjixuchui/RHSocketKit // // NSMutableDictionary+RHExtends.h // Pods // // Created by zhuruhong on 2019/10/1. // #import <Foundation/Foundation.h> //NS_ASSUME_NONNULL_BEGIN @interface NSDictionary (RHExtends) - (NSString *)rh_stringForKey:(id)key; - (NSString *)rh_stringForKey:(id)key defaultValue:(NSString *)defaultValue; - (NSNumber *)rh_numberForKey:(id)key; - (NSString *)rh_JSONString; - (NSString *)rh_JSONStringWithOptions:(NSJSONWritingOptions)opt; @end @interface NSMutableDictionary (RHExtends) /** 安全使用value */ - (void)rh_setValue:(id)value forKey:(NSString *)key; /** 在aValue为nil时,删除原来的key */ - (void)rh_setValueEx:(id)aValue forKey:(NSString *)aKey; @end //NS_ASSUME_NONNULL_END
306
424
<filename>vertx-sql-client-templates/src/test/java/io/vertx/sqlclient/templates/wrappers/StringWrapper.java package io.vertx.sqlclient.templates.wrappers; public class StringWrapper extends WrapperBase<String> { public StringWrapper(String value) { super(value); } }
94
2,023
// Copyright 2019 Google 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. #ifndef SLING_NLP_PARSER_TRANSITION_GENERATOR_H_ #define SLING_NLP_PARSER_TRANSITION_GENERATOR_H_ #include <functional> #include "sling/nlp/document/document.h" #include "sling/nlp/parser/parser-action.h" namespace sling { namespace nlp { // Generates transition sequences for [begin, end) token range in 'document', // calling 'callback' for every transition. void Generate(const Document &document, int begin, int end, std::function<void(const ParserAction &)> callback); // Generates transition sequences for all tokens in 'document', calling // 'callback' for every transition. void Generate(const Document &document, std::function<void(const ParserAction &)> callback); } // namespace nlp } // namespace sling #endif // SLING_NLP_PARSER_TRANSITION_GENERATOR_H_
440
818
/* * Copyright 2020 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.kie.kogito.test.resources; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ConditionHolderTest { private static final String RESOURCE_NAME = "my-test-resource"; private static final String RESOURCE_PROPERTY = String.format(ConditionHolder.TEST_CATEGORY_PROPERTY, RESOURCE_NAME); private ConditionHolder condition; @BeforeEach public void setup() { condition = new ConditionHolder(RESOURCE_NAME); } @Test public void shouldBeEnabledByDefault() { assertTrue(condition.isEnabled()); } @Test public void shouldBeDisabledIfSystemPropertyDoesNotExist() { System.clearProperty(RESOURCE_PROPERTY); condition.enableConditional(); assertFalse(condition.isEnabled()); } @Test public void shouldBeDisabledIfSystemPropertyIsNotTrue() { System.setProperty(RESOURCE_PROPERTY, "anything"); condition.enableConditional(); assertFalse(condition.isEnabled()); } @Test public void shouldBeEnabledIfSystemPropertyIsTrue() { System.setProperty(RESOURCE_PROPERTY, "true"); condition.enableConditional(); assertTrue(condition.isEnabled()); } }
652
310
<filename>nncf/common/hardware/config.py<gh_stars>100-1000 """ Copyright (c) 2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from abc import ABC from abc import abstractmethod from collections import OrderedDict from enum import Enum from pathlib import Path from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Set from typing import Type import addict as ad import jstyleson as json from nncf.common.graph.operator_metatypes import OperatorMetatype from nncf.common.quantization import quantizers as quant from nncf.common.quantization.structs import QuantizationMode from nncf.common.quantization.structs import QuantizerConfig from nncf.common.utils.helpers import product_dict from nncf.common.utils.os import safe_open from nncf.definitions import HW_CONFIG_RELATIVE_DIR from nncf.definitions import NNCF_PACKAGE_ROOT_DIR from nncf.common.utils.logger import logger as nncf_logger class HWConfigType(Enum): CPU = 'CPU' GPU = 'GPU' VPU = 'VPU' @staticmethod def from_str(config_value: str) -> 'HWConfigType': if config_value == HWConfigType.CPU.value: return HWConfigType.CPU if config_value == HWConfigType.GPU.value: return HWConfigType.GPU if config_value == HWConfigType.VPU.value: return HWConfigType.VPU raise RuntimeError('Unknown HW config type string') HW_CONFIG_TYPE_TARGET_DEVICE_MAP = { 'ANY': HWConfigType.CPU.value, 'CPU': HWConfigType.CPU.value, 'VPU': HWConfigType.VPU.value, 'GPU': HWConfigType.GPU.value, 'TRIAL': None } HWConfigOpName = str class HWConfig(list, ABC): QUANTIZATION_ALGORITHM_NAME = 'quantization' ATTRIBUTES_NAME = 'attributes' SCALE_ATTRIBUTE_NAME = 'scales' UNIFIED_TYPE_NAME = 'unified' ADJUST_PADDING_ATTRIBUTE_NAME = 'adjust_padding' TYPE_TO_CONF_NAME_DICT = { HWConfigType.CPU: 'cpu.json', HWConfigType.VPU: 'vpu.json', HWConfigType.GPU: 'gpu.json' } def __init__(self): super().__init__() self.registered_algorithm_configs = {} self.target_device = None @abstractmethod def _get_available_operator_metatypes_for_matching(self) -> List[Type[OperatorMetatype]]: pass @staticmethod def get_path_to_hw_config(hw_config_type: HWConfigType): return '/'.join([NNCF_PACKAGE_ROOT_DIR, HW_CONFIG_RELATIVE_DIR, HWConfig.TYPE_TO_CONF_NAME_DICT[hw_config_type]]) @classmethod def from_dict(cls, dct: dict): # pylint:disable=too-many-nested-blocks,too-many-branches hw_config = cls() hw_config.target_device = dct['target_device'] for algorithm_name, algorithm_configs in dct.get('config', {}).items(): hw_config.registered_algorithm_configs[algorithm_name] = {} for algo_config_alias, algo_config in algorithm_configs.items(): for key, val in algo_config.items(): if not isinstance(val, list): algo_config[key] = [val] hw_config.registered_algorithm_configs[algorithm_name][algo_config_alias] = list( product_dict(algo_config)) for op_dict in dct.get('operations', []): for algorithm_name in op_dict: if algorithm_name not in hw_config.registered_algorithm_configs: continue tmp_config = {} for algo_and_op_specific_field_name, algorithm_configs in op_dict[algorithm_name].items(): if not isinstance(algorithm_configs, list): algorithm_configs = [algorithm_configs] tmp_config[algo_and_op_specific_field_name] = [] for algorithm_config in algorithm_configs: if isinstance(algorithm_config, str): # Alias was supplied tmp_config[algo_and_op_specific_field_name].extend( hw_config.registered_algorithm_configs[algorithm_name][algorithm_config]) else: for key, val in algorithm_config.items(): if not isinstance(val, list): algorithm_config[key] = [val] tmp_config[algo_and_op_specific_field_name].extend(list(product_dict(algorithm_config))) op_dict[algorithm_name] = tmp_config hw_config.append(ad.Dict(op_dict)) return hw_config @classmethod def from_json(cls, path): file_path = Path(path).resolve() with safe_open(file_path) as f: json_config = json.load(f, object_pairs_hook=OrderedDict) return cls.from_dict(json_config) @staticmethod def get_quantization_mode_from_config_value(str_val: str): if str_val == 'symmetric': return QuantizationMode.SYMMETRIC if str_val == 'asymmetric': return QuantizationMode.ASYMMETRIC raise RuntimeError('Invalid quantization type specified in HW config') @staticmethod def get_is_per_channel_from_config_value(str_val: str): if str_val == 'perchannel': return True if str_val == 'pertensor': return False raise RuntimeError('Invalid quantization granularity specified in HW config') @staticmethod def get_qconf_from_hw_config_subdict(quantization_subdict: Dict): bits = quantization_subdict['bits'] mode = HWConfig.get_quantization_mode_from_config_value(quantization_subdict['mode']) is_per_channel = HWConfig.get_is_per_channel_from_config_value(quantization_subdict['granularity']) signedness_to_force = None if 'level_low' in quantization_subdict and 'level_high' in quantization_subdict: signedness_to_force = False if mode == QuantizationMode.SYMMETRIC: if quantization_subdict['level_low'] < 0 < quantization_subdict['level_high']: signedness_to_force = True true_level_low, true_level_high, _ = quant.calculate_symmetric_level_ranges(bits, signed=True) else: signedness_to_force = True true_level_low, true_level_high, _ = quant.calculate_asymmetric_level_ranges(bits) assert quantization_subdict['level_low'] == true_level_low, \ 'Invalid value of quantizer parameter `level_low`.\ The parameter must be consistent with other parameters!' assert quantization_subdict['level_high'] == true_level_high, \ 'Invalid value of quantizer parameter `level_high`.\ The parameter must be consistent with other parameters!' return QuantizerConfig(num_bits=bits, mode=mode, per_channel=is_per_channel, signedness_to_force=signedness_to_force) @staticmethod def is_qconf_list_corresponding_to_unspecified_op(qconf_list: Optional[List[QuantizerConfig]]): return qconf_list is None @staticmethod def is_wildcard_quantization(qconf_list: Optional[List[QuantizerConfig]]): # Corresponds to an op itself being specified in the HW config, but having no associated quantization # configs specified return qconf_list is not None and len(qconf_list) == 0 def get_metatype_vs_quantizer_configs_map(self, for_weights=False) -> Dict[Type[OperatorMetatype], Optional[List[QuantizerConfig]]]: # 'None' for ops unspecified in HW config, empty list for wildcard quantization ops retval = {k: None for k in self._get_available_operator_metatypes_for_matching()} config_key = 'weights' if for_weights else 'activations' for op_dict in self: hw_config_op_name = op_dict.type metatypes = self._get_metatypes_for_hw_config_op(hw_config_op_name) if not metatypes: nncf_logger.debug( 'Operation name {} in HW config is not registered in NNCF under any supported operation ' 'metatype - will be ignored'.format(hw_config_op_name)) if self.QUANTIZATION_ALGORITHM_NAME in op_dict: allowed_qconfs = op_dict[self.QUANTIZATION_ALGORITHM_NAME][config_key] else: allowed_qconfs = [] qconf_list_with_possible_duplicates = [] for hw_config_qconf_dict in allowed_qconfs: qconf_list_with_possible_duplicates.append( self.get_qconf_from_hw_config_subdict(hw_config_qconf_dict)) qconf_list = list(OrderedDict.fromkeys(qconf_list_with_possible_duplicates)) for meta in metatypes: retval[meta] = qconf_list return retval def _get_operations_with_attribute_values(self, attribute_name_vs_required_value: Dict[str, Any]) -> \ Set[Type[OperatorMetatype]]: result = set() for op_dict in self: if self.ATTRIBUTES_NAME not in op_dict: continue for attr_name, attr_value in attribute_name_vs_required_value.items(): is_value_matched = op_dict[self.ATTRIBUTES_NAME][attr_name] == attr_value is_attr_set = attr_name in op_dict[self.ATTRIBUTES_NAME] if is_value_matched and is_attr_set: hw_config_op_name = op_dict.type metatypes = self._get_metatypes_for_hw_config_op(hw_config_op_name) if not metatypes: nncf_logger.debug( 'Operation name {} in HW config is not registered in NNCF under any supported ' 'operation metatype - will be ignored'.format(hw_config_op_name)) result.update(metatypes) return result def get_operations_with_unified_scales(self) -> Set[Type[OperatorMetatype]]: return self._get_operations_with_attribute_values({self.SCALE_ATTRIBUTE_NAME: self.UNIFIED_TYPE_NAME}) def get_operations_with_adjusted_paddings(self) -> Set[Type[OperatorMetatype]]: return self._get_operations_with_attribute_values({self.ADJUST_PADDING_ATTRIBUTE_NAME: True}) def _get_metatypes_for_hw_config_op(self, hw_config_op: HWConfigOpName) -> Set[Type[OperatorMetatype]]: metatypes = set() for op_meta in self._get_available_operator_metatypes_for_matching(): if hw_config_op in op_meta.hw_config_names: metatypes.add(op_meta) if not metatypes: nncf_logger.debug( 'Operation name {} in HW config is not registered in NNCF under any supported ' 'operation metatype - will be ignored'.format(hw_config_op)) return metatypes
5,207
3,395
<gh_stars>1000+ package com.airbnb.android.react.navigation; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; final class AndroidVersion { static boolean isAtLeastJellyBeanMR1() { return VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1; } static boolean isAtLeastJellyBeanMR2() { return VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2; } static boolean isAtLeastKitKat() { return VERSION.SDK_INT >= VERSION_CODES.KITKAT; } static boolean isAtLeastLollipop() { return VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP; } static boolean isAtLeastMarshmallow() { return VERSION.SDK_INT >= VERSION_CODES.M; } static boolean isAtLeastLollipopMR1() { return VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1; } static boolean isJellyBean() { return VERSION.SDK_INT == VERSION_CODES.JELLY_BEAN; } static boolean isAtLeastNougat() { return VERSION.SDK_INT >= VERSION_CODES.N; } private AndroidVersion() { // Prevent users from instantiating this class. } }
420
5,169
{ "name": "AZPeerToPeerConnection", "version": "0.1.1", "summary": "Wrapper on top of Apple iOS Multipeer Connectivity framework", "description": "AZPeerToPeerConnectivity is a wrapper on top of Apple iOS Multipeer Connectivity framework. It provides an easier way to create and manage sessions. Easy to integrate", "homepage": "https://github.com/AfrozZaheer/AZPeerToPeerConnection", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "AfrozZaheer": "<EMAIL>" }, "source": { "git": "https://github.com/AfrozZaheer/AZPeerToPeerConnection.git" }, "platforms": { "ios": "10.0" }, "source_files": "Source/**/*.{swift}" }
259
387
<filename>Chapter 13/code/background_subtraction.py import cv2 import numpy as np # Define a function to get the current frame from the webcam def get_frame(cap, scaling_factor): # Read the current frame from the video capture object _, frame = cap.read() # Resize the image frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) return frame if __name__=='__main__': # Define the video capture object cap = cv2.VideoCapture(0) # Define the background subtractor object bg_subtractor = cv2.createBackgroundSubtractorMOG2() # Define the number of previous frames to use to learn. # This factor controls the learning rate of the algorithm. # The learning rate refers to the rate at which your model # will learn about the background. Higher value for # ‘history’ indicates a slower learning rate. You can # play with this parameter to see how it affects the output. history = 100 # Define the learning rate learning_rate = 1.0/history # Keep reading the frames from the webcam # until the user hits the 'Esc' key while True: # Grab the current frame frame = get_frame(cap, 0.5) # Compute the mask mask = bg_subtractor.apply(frame, learningRate=learning_rate) # Convert grayscale image to RGB color image mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) # Display the images cv2.imshow('Input', frame) cv2.imshow('Output', mask & frame) # Check if the user hit the 'Esc' key c = cv2.waitKey(10) if c == 27: break # Release the video capture object cap.release() # Close all the windows cv2.destroyAllWindows()
683
11,356
// Boost.Geometry (aka GGL, Generic Geometry Library) // This file is manually converted from PROJ4 // Copyright (c) 2008-2012 <NAME>, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017, 2018. // Modifications copyright (c) 2017-2018, Oracle and/or its affiliates. // Contributed and/or modified by <NAME>, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by <NAME> (then of the USGS) // PROJ4 is maintained by <NAME> // PROJ4 is converted to Geometry Library by <NAME> (Geodan, Amsterdam) // Original copyright notice: // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. /* meridional distance for ellipsoid and inverse ** 8th degree - accurate to < 1e-5 meters when used in conjunction ** with typical major axis values. ** Inverse determines phi to EPS (1e-11) radians, about 1e-6 seconds. */ #ifndef BOOST_GEOMETRY_PROJECTIONS_PJ_MLFN_HPP #define BOOST_GEOMETRY_PROJECTIONS_PJ_MLFN_HPP #include <cstdlib> #include <boost/geometry/util/math.hpp> namespace boost { namespace geometry { namespace projections { namespace detail { template <typename T> struct en { static const std::size_t size = 5; T const& operator[](size_t i) const { return data[i]; } T & operator[](size_t i) { return data[i]; } private: T data[5]; }; template <typename T> inline en<T> pj_enfn(T const& es) { static const T C00 = 1.; static const T C02 = .25; static const T C04 = .046875; static const T C06 = .01953125; static const T C08 = .01068115234375; static const T C22 = .75; static const T C44 = .46875; static const T C46 = .01302083333333333333; static const T C48 = .00712076822916666666; static const T C66 = .36458333333333333333; static const T C68 = .00569661458333333333; static const T C88 = .3076171875; T t; detail::en<T> en; { en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08))); en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08))); en[2] = (t = es * es) * (C44 - es * (C46 + es * C48)); en[3] = (t *= es) * (C66 - es * C68); en[4] = t * es * C88; } return en; } template <typename T> inline T pj_mlfn(T const& phi, T sphi, T cphi, detail::en<T> const& en) { cphi *= sphi; sphi *= sphi; return(en[0] * phi - cphi * (en[1] + sphi*(en[2] + sphi*(en[3] + sphi*en[4])))); } template <typename T> inline T pj_inv_mlfn(T const& arg, T const& es, detail::en<T> const& en) { static const T EPS = 1e-11; static const int MAX_ITER = 10; T s, t, phi, k = 1./(1.-es); int i; phi = arg; for (i = MAX_ITER; i ; --i) { /* rarely goes over 2 iterations */ s = sin(phi); t = 1. - es * s * s; phi -= t = (pj_mlfn(phi, s, cos(phi), en) - arg) * (t * sqrt(t)) * k; if (geometry::math::abs(t) < EPS) return phi; } BOOST_THROW_EXCEPTION( projection_exception(error_non_conv_inv_meri_dist) ); return phi; } } // namespace detail }}} // namespace boost::geometry::projections #endif
1,629
1,618
package com.xiaojuchefu.prism; import android.app.Application; import com.xiaojuchefu.prism.monitor.PrismMonitor; import com.xiaojuchefu.prism.playback.PrismPlayback; public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); PrismMonitor.getInstance().init(this); PrismPlayback.getInstance().init(this); } }
145
3,459
<gh_stars>1000+ /**************************************************************************** * gx_video.c * * Genesis Plus GX video support * * Copyright Eke-Eke (2007-2013), based on original work from Softdev (2006) * * Redistribution and use of this code or any derivative works are permitted * provided that the following conditions are met: * * - Redistributions may not be sold, nor may they be used in a commercial * product or activity. * * - Redistributions that are modified from the original source must include the * complete source code, including the source code for all components used by a * binary built from the modified sources. However, as a special exception, the * source code distributed need not include anything that is normally distributed * (in either source or binary form) with the major components (compiler, kernel, * and so on) of the operating system on which the executable runs, unless that * component itself accompanies the executable. * * - Redistributions must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************************/ #ifndef _GC_VIDEO_H_ #define _GC_VIDEO_H_ /* EFB colors */ #define BLACK {0x00,0x00,0x00,0xff} #define DARK_GREY {0x22,0x22,0x22,0xff} #define LIGHT_BLUE {0xb8,0xc7,0xda,0xff} #define SKY_BLUE {0x99,0xcc,0xff,0xff} #define LIGHT_GREEN {0xa9,0xc7,0xc6,0xff} #define WHITE {0xff,0xff,0xff,0xff} /* Directly fill a RGB565 texture */ /* One tile is 32 byte = 4x4 pixels */ /* Tiles are stored continuously in texture memory */ #define CUSTOM_BLITTER(line, width, table, in) \ width >>= 2; \ u16 *out = (u16 *) (texturemem + (((width << 5) * (line >> 2)) + ((line & 3) << 3))); \ do \ { \ *out++ = table[*in++]; \ *out++ = table[*in++]; \ *out++ = table[*in++]; \ *out++ = table[*in++]; \ out += 12; \ } \ while (--width); /* image texture */ typedef struct { u8 *data; u16 width; u16 height; u8 format; } gx_texture; /* Global variables */ extern GXRModeObj *vmode; extern u8 *texturemem; extern u32 gc_pal; /* GX rendering */ extern void gxDrawRectangle(s32 x, s32 y, s32 w, s32 h, u8 alpha, GXColor color); extern void gxDrawTexture(gx_texture *texture, s32 x, s32 y, s32 w, s32 h, u8 alpha); extern void gxDrawTextureRepeat(gx_texture *texture, s32 x, s32 y, s32 w, s32 h, u8 alpha); extern void gxDrawTextureRotate(gx_texture *texture, s32 x, s32 y, s32 w, s32 h, f32 angle, u8 alpha); extern void gxDrawScreenshot(u8 alpha); extern void gxCopyScreenshot(gx_texture *texture); extern void gxSaveScreenshot(char *filename); extern void gxClearScreen(GXColor color); extern void gxSetScreen(void); /* PNG textures */ extern gx_texture *gxTextureOpenPNG(const u8 *png_data, FILE *png_file); extern void gxTextureWritePNG(gx_texture *p_texture, FILE *png_file); extern void gxTextureClose(gx_texture **p_texture); /* GX video engine */ extern void gx_video_Init(void); extern void gx_video_Shutdown(void); extern void gx_video_Start(void); extern void gx_video_Stop(void); extern int gx_video_Update(void); #endif
1,525
852
<filename>Alignment/MuonAlignment/src/AlignableGEMRing.cc /* AlignableGEMRing * \author <NAME> - TAMU */ #include "Alignment/MuonAlignment/interface/AlignableGEMRing.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" AlignableGEMRing::AlignableGEMRing(const std::vector<AlignableGEMSuperChamber*>& GEMSuperChambers) : AlignableComposite(GEMSuperChambers[0]->id(), align::AlignableGEMRing) { theGEMSuperChambers.insert(theGEMSuperChambers.end(), GEMSuperChambers.begin(), GEMSuperChambers.end()); for (const auto& chamber : GEMSuperChambers) { const auto mother = chamber->mother(); this->addComponent(chamber); chamber->setMother(mother); } setSurface(computeSurface()); compConstraintType_ = Alignable::CompConstraintType::POSITION_Z; } AlignableGEMSuperChamber& AlignableGEMRing::superChamber(int i) { if (i >= size()) throw cms::Exception("LogicError") << "GEM Super Chamber index (" << i << ") out of range"; return *theGEMSuperChambers[i]; } AlignableSurface AlignableGEMRing::computeSurface() { return AlignableSurface(computePosition(), computeOrientation()); } AlignableGEMRing::PositionType AlignableGEMRing::computePosition() { float zz = 0.; for (std::vector<AlignableGEMSuperChamber*>::iterator ichamber = theGEMSuperChambers.begin(); ichamber != theGEMSuperChambers.end(); ichamber++) zz += (*ichamber)->globalPosition().z(); zz /= static_cast<float>(theGEMSuperChambers.size()); return PositionType(0.0, 0.0, zz); } AlignableGEMRing::RotationType AlignableGEMRing::computeOrientation() { return RotationType(); } std::ostream& operator<<(std::ostream& os, const AlignableGEMRing& b) { os << "This GEM Ring contains " << b.theGEMSuperChambers.size() << " GEM Super chambers" << std::endl; os << "(phi, r, z) = (" << b.globalPosition().phi() << "," << b.globalPosition().perp() << "," << b.globalPosition().z(); os << "), orientation:" << std::endl << b.globalRotation() << std::endl; return os; } void AlignableGEMRing::dump(void) const { edm::LogInfo("AlignableDump") << (*this); for (std::vector<AlignableGEMSuperChamber*>::const_iterator iChamber = theGEMSuperChambers.begin(); iChamber != theGEMSuperChambers.end(); iChamber++) edm::LogInfo("AlignableDump") << (**iChamber); }
859
45,293
<filename>compiler/testData/compileJavaAgainstKotlin/targets/getter.java package test; @getter class My { @getter int foo() { return 1; } }
66
335
<reponame>Safal08/Hacktoberfest-1<gh_stars>100-1000 { "word": "Brainchild", "definitions": [ "An idea or invention which is considered to be a particular person's creation." ], "parts-of-speech": "Noun" }
92
692
<filename>ports/esp32/modules/urequests.py ../../../../micropython-lib/urequests/urequests.py
35
14,668
// Copyright 2018 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 "base/rand_util.h" #include "mojo/public/cpp/base/big_buffer_mojom_traits.h" #include "mojo/public/cpp/test_support/test_utils.h" #include "mojo/public/mojom/base/big_string.mojom-blink.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/mojo/big_string_mojom_traits.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { TEST(BigStringMojomTraitsTest, BigString_Null) { String str; String output; ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( str, output)); ASSERT_EQ(str, output); } TEST(BigStringMojomTraitsTest, BigString_Empty) { String str = String::FromUTF8(""); String output; ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( str, output)); ASSERT_EQ(str, output); } TEST(BigStringMojomTraitsTest, BigString_Short) { String str = String::FromUTF8("hello world"); ASSERT_TRUE(str.Is8Bit()); String output; ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( str, output)); ASSERT_EQ(str, output); // Replace the "o"s in "hello world" with "o"s with acute, so that |str| is // 16-bit. str = String::FromUTF8("hell\xC3\xB3 w\xC3\xB3rld"); ASSERT_FALSE(str.Is8Bit()); ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( str, output)); ASSERT_EQ(str, output); } TEST(BigStringMojomTraitsTest, BigString_Long) { WTF::Vector<char> random_latin1_string(1024 * 1024); base::RandBytes(random_latin1_string.data(), random_latin1_string.size()); String str(random_latin1_string.data(), random_latin1_string.size()); String output; ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( str, output)); ASSERT_EQ(str, output); } } // namespace blink
862
369
<filename>tests/test_geometry.py # coding=utf-8 import ee from geetools.tools.geometry import getRegion ee.Initialize() l8SR = ee.Image("LANDSAT/LC8_SR/LC82310772014043") p_l8SR_cloud = ee.Geometry.Point([-65.8109, -25.0185]) p_l8SR_no_cloud = ee.Geometry.Point([-66.0306, -24.9338]) list1 = ee.List([1, 2, 3, 4, 5]) list2 = ee.List([4, 5, 6, 7]) def test_getRegion(): expected = [[0.0,0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [0.0, 0.0]] pol = ee.Geometry.Polygon(expected) feat = ee.Feature(pol) region_geom = getRegion(pol) region_feat = getRegion(feat) assert region_geom == [expected] assert region_feat == [expected]
310
348
{"nom":"Aubenton","circ":"3ème circonscription","dpt":"Aisne","inscrits":448,"abs":241,"votants":207,"blancs":3,"nuls":2,"exp":202,"res":[{"nuance":"FN","nom":"<NAME>","voix":70},{"nuance":"SOC","nom":"<NAME>","voix":39},{"nuance":"LR","nom":"<NAME>","voix":37},{"nuance":"MDM","nom":"<NAME>","voix":33},{"nuance":"FI","nom":"Mme <NAME>","voix":14},{"nuance":"COM","nom":"<NAME>","voix":3},{"nuance":"ECO","nom":"M. <NAME>","voix":3},{"nuance":"DLF","nom":"M. <NAME>","voix":3},{"nuance":"EXG","nom":"Mme <NAME>","voix":0},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
232
338
{ "Telechips TCC890": { "type": "tablet", "properties": { "Device_Name": "Wince 6.0", "Device_Code_Name": "TCC890", "Device_Maker": "Telechips", "Device_Pointing_Method": "touchscreen", "Device_Brand_Name": "Telechips" }, "standard": true } }
140
3,227
#include <CGAL/Polynomial.h> #include <CGAL/Polynomial_traits_d.h> #include <CGAL/Polynomial_type_generator.h> #include <CGAL/use.h> #include <CGAL/assertions.h> int main(){ typedef CGAL::Polynomial<int> Poly_int_1; typedef CGAL::Polynomial<Poly_int_1> Poly_int_2; typedef CGAL::Polynomial<Poly_int_2> Poly_int_3; { typedef CGAL::Polynomial_type_generator<int,1>::Type Polynomial; CGAL_static_assertion((::boost::is_same<Polynomial, Poly_int_1>::value)); } { typedef CGAL::Polynomial_type_generator<int,2>::Type Polynomial; CGAL_static_assertion((::boost::is_same<Polynomial, Poly_int_2>::value)); } { typedef CGAL::Polynomial_type_generator<int,3>::Type Polynomial; CGAL_static_assertion((::boost::is_same<Polynomial, Poly_int_3>::value)); } }
350
4,538
/* File generated automatically by the QuickJS compiler. */ #include <inttypes.h> const uint32_t jslib_checksum_size = 332; const uint8_t jslib_checksum[332] = { 0x01, 0x08, 0x1e, 0x73, 0x72, 0x63, 0x2f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x2e, 0x6a, 0x73, 0x10, 0x43, 0x48, 0x45, 0x43, 0x4b, 0x53, 0x55, 0x4d, 0x06, 0x6d, 0x64, 0x35, 0x0a, 0x63, 0x72, 0x63, 0x31, 0x36, 0x0a, 0x63, 0x72, 0x63, 0x33, 0x32, 0x06, 0x6f, 0x62, 0x6a, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x0e, 0x72, 0x61, 0x77, 0x44, 0x61, 0x74, 0x61, 0x0f, 0x9c, 0x03, 0x01, 0x9e, 0x03, 0x03, 0x00, 0x01, 0xa0, 0x03, 0x00, 0x02, 0xa2, 0x03, 0x00, 0x03, 0xa4, 0x03, 0x00, 0x01, 0x00, 0xf8, 0x01, 0x00, 0x0e, 0x00, 0x06, 0x01, 0xa0, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x03, 0x0a, 0x00, 0x9e, 0x03, 0x00, 0x0d, 0xa0, 0x03, 0x00, 0x01, 0xa2, 0x03, 0x01, 0x01, 0xa4, 0x03, 0x02, 0x01, 0xbf, 0x00, 0xe1, 0xbf, 0x01, 0xe2, 0xbf, 0x02, 0xe3, 0x29, 0x9c, 0x03, 0x01, 0x04, 0x01, 0x00, 0x09, 0x2c, 0x0e, 0x43, 0x06, 0x01, 0xa0, 0x03, 0x01, 0x00, 0x01, 0x03, 0x01, 0x00, 0x1f, 0x01, 0xa6, 0x03, 0x00, 0x01, 0x00, 0x9e, 0x03, 0x00, 0x0c, 0xd0, 0x97, 0xe9, 0x10, 0x38, 0x8d, 0x00, 0x00, 0x00, 0x11, 0x04, 0xd4, 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x2f, 0x65, 0x00, 0x00, 0x42, 0xd0, 0x00, 0x00, 0x00, 0xd0, 0x25, 0x01, 0x00, 0x9c, 0x03, 0x03, 0x04, 0x03, 0x17, 0x49, 0x08, 0x0e, 0x43, 0x06, 0x01, 0xa2, 0x03, 0x01, 0x00, 0x01, 0x03, 0x01, 0x00, 0x1f, 0x01, 0xaa, 0x03, 0x00, 0x01, 0x00, 0x9e, 0x03, 0x00, 0x0c, 0xd0, 0x97, 0xe9, 0x10, 0x38, 0x8d, 0x00, 0x00, 0x00, 0x11, 0x04, 0xd4, 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x2f, 0x65, 0x00, 0x00, 0x42, 0xd1, 0x00, 0x00, 0x00, 0xd0, 0x25, 0x01, 0x00, 0x9c, 0x03, 0x0a, 0x04, 0x03, 0x17, 0x49, 0x08, 0x0e, 0x43, 0x06, 0x01, 0xa4, 0x03, 0x01, 0x00, 0x01, 0x03, 0x01, 0x00, 0x1f, 0x01, 0xaa, 0x03, 0x00, 0x01, 0x00, 0x9e, 0x03, 0x00, 0x0c, 0xd0, 0x97, 0xe9, 0x10, 0x38, 0x8d, 0x00, 0x00, 0x00, 0x11, 0x04, 0xd4, 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x2f, 0x65, 0x00, 0x00, 0x42, 0xd2, 0x00, 0x00, 0x00, 0xd0, 0x25, 0x01, 0x00, 0x9c, 0x03, 0x11, 0x04, 0x03, 0x17, 0x49, 0x08, };
1,478
4,140
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.optimizer.calcite.reloperators; import java.util.ArrayList; import java.util.List; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexBiVisitor; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexVisitor; import org.apache.hadoop.hive.ql.plan.ExprNodeColumnListDesc; /** * This class represents the equivalent to {@link ExprNodeColumnListDesc} * in a Calcite expression. It is not supposed to be used through planning * and should be immediately expanded after it has been generated by * the parser. */ public class HiveRexExprList extends RexNode { final List<RexNode> expressions = new ArrayList<>(); public void addExpression(RexNode expression) { expressions.add(expression); } public List<RexNode> getExpressions() { return expressions; } @Override public RelDataType getType() { throw new UnsupportedOperationException(); } @Override public <R> R accept(RexVisitor<R> visitor) { throw new UnsupportedOperationException(); } @Override public <R, P> R accept(RexBiVisitor<R, P> visitor, P arg) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object obj) { if (obj instanceof HiveRexExprList) { return this.expressions.equals(((HiveRexExprList) obj).expressions); } return false; } @Override public int hashCode() { return expressions.hashCode(); } }
674
399
<reponame>PranavPurwar/procyon /* * TypeVisitor.java * * Copyright (c) 2013 <NAME> * * This source code is based on Mono.Cecil from Jb Evain, Copyright (c) <NAME>; * and ILSpy/ICSharpCode from SharpDevelop, Copyright (c) AlphaSierraPapa. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. * A copy of the license can be found in the License.html file at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. */ package com.strobel.assembler.metadata; import com.strobel.assembler.ir.ConstantPool; import com.strobel.assembler.ir.attributes.SourceAttribute; import com.strobel.assembler.metadata.annotations.CustomAnnotation; /** * @author <NAME> */ public interface TypeVisitor { void visitParser(final MetadataParser parser); void visit( final int majorVersion, final int minorVersion, final long flags, final String name, final String genericSignature, final String baseTypeName, final String[] interfaceNames); void visitDeclaringMethod(final MethodReference method); void visitOuterType(final TypeReference type); void visitInnerType(final TypeDefinition type); void visitAttribute(final SourceAttribute attribute); void visitAnnotation(final CustomAnnotation annotation, final boolean visible); FieldVisitor visitField( final long flags, final String name, final TypeReference fieldType); MethodVisitor visitMethod( final long flags, final String name, final IMethodSignature signature, final TypeReference... thrownTypes); ConstantPool.Visitor visitConstantPool(); void visitEnd(); }
667
372
<filename>dcerpc/libdcethread/dcethread_select.c /* Clean */ #include <config.h> #include "dcethread-private.h" #include "dcethread-util.h" #include "dcethread-debug.h" #include "dcethread-exception.h" #ifdef API int dcethread_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { DCETHREAD_SYSCALL(int, select(nfds, readfds, writefds, exceptfds, timeout)); } #endif /* API */
199
666
import sys sys.path.append("../../") from appJar import gui def launch(win): app.showSubWindow(win) app=gui() # this is a pop-up app.startSubWindow("one", modal=True) app.addLabel("l1", "SubWindow One") app.stopSubWindow() # this is another pop-up app.startSubWindow("two") app.setLocation(20,20) app.addLabel("l2", "SubWindow Two") app.stopSubWindow() # these go in the main window app.addButtons(["one", "two"], launch) app.go()
168
3,807
/* * Copyright 2017 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #import <Foundation/Foundation.h> @class FPath; @interface FPruneForest : NSObject + (FPruneForest *)empty; - (BOOL)prunesAnything; - (BOOL)shouldPruneUnkeptDescendantsAtPath:(FPath *)path; - (BOOL)shouldKeepPath:(FPath *)path; - (BOOL)affectsPath:(FPath *)path; - (FPruneForest *)child:(NSString *)childKey; - (FPruneForest *)childAtPath:(FPath *)childKey; - (FPruneForest *)prunePath:(FPath *)path; - (FPruneForest *)keepPath:(FPath *)path; - (FPruneForest *)keepAll:(NSSet *)children atPath:(FPath *)path; - (FPruneForest *)pruneAll:(NSSet *)children atPath:(FPath *)path; - (void)enumarateKeptNodesUsingBlock:(void (^)(FPath *path))block; @end
403
480
/* * Copyright [2013-2021], Alibaba Group Holding 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 * * 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.alibaba.polardbx.executor.ddl.job.task.basic; import com.alibaba.polardbx.common.properties.ConnectionParams; import com.alibaba.polardbx.common.utils.Pair; import com.alibaba.polardbx.executor.ddl.job.meta.CommonMetaChanger; import com.alibaba.polardbx.executor.ddl.job.task.BaseGmsTask; import com.alibaba.polardbx.executor.ddl.job.task.util.TaskName; import com.alibaba.polardbx.executor.scaleout.ScaleOutUtils; import com.alibaba.polardbx.executor.utils.failpoint.FailPoint; import com.alibaba.polardbx.gms.listener.impl.MetaDbDataIdBuilder; import com.alibaba.polardbx.optimizer.context.ExecutionContext; import lombok.Getter; import java.sql.Connection; import java.util.List; import java.util.Map; @Getter @TaskName(name = "InitNewStorageInstTask") public class InitNewStorageInstTask extends BaseGmsTask { /* * key:instId * value:list<group->phyDb> * */ Map<String, List<Pair<String, String>>> instGroupDbInfos; public InitNewStorageInstTask(String schemaName, Map<String, List<Pair<String, String>>> instGroupDbInfos) { super(schemaName, ""); this.instGroupDbInfos = instGroupDbInfos; } @Override public void executeImpl(Connection metaDbConnection, ExecutionContext executionContext) { for (Map.Entry<String, List<Pair<String, String>>> entry : instGroupDbInfos.entrySet()) { for (Pair<String, String> pair : entry.getValue()) { ScaleOutUtils.doAddNewGroupIntoDb(schemaName, pair.getKey(), pair.getValue(), entry.getKey(), LOGGER, metaDbConnection); FailPoint.injectRandomExceptionFromHint(executionContext); FailPoint.injectRandomSuspendFromHint(executionContext); } } } @Override protected void rollbackImpl(Connection metaDbConnection, ExecutionContext executionContext) { Long socketTimeout = executionContext.getParamManager().getLong(ConnectionParams.SOCKET_TIMEOUT); long socketTimeoutVal = socketTimeout != null ? socketTimeout : -1; for (Map.Entry<String, List<Pair<String, String>>> entry : instGroupDbInfos.entrySet()) { for (Pair<String, String> pair : entry.getValue()) { ScaleOutUtils.doRemoveNewGroupFromDb(schemaName, pair.getKey(), pair.getValue(), entry.getKey(), socketTimeoutVal, LOGGER, metaDbConnection); FailPoint.injectRandomExceptionFromHint(executionContext); FailPoint.injectRandomSuspendFromHint(executionContext); } } } @Override protected void duringTransaction(Connection metaDbConnection, ExecutionContext executionContext) { executeImpl(metaDbConnection, executionContext); } @Override protected void onExecutionSuccess(ExecutionContext executionContext) { CommonMetaChanger.sync(MetaDbDataIdBuilder.getDbTopologyDataId(schemaName)); } @Override protected void duringRollbackTransaction(Connection metaDbConnection, ExecutionContext executionContext) { rollbackImpl(metaDbConnection, executionContext); } @Override protected void onRollbackSuccess(ExecutionContext executionContext) { CommonMetaChanger.sync(MetaDbDataIdBuilder.getDbTopologyDataId(schemaName)); } }
1,403
10,225
package io.quarkus.qute.deployment.i18n; import static io.quarkus.qute.i18n.Message.UNDERSCORED_ELEMENT_NAME; import io.quarkus.qute.i18n.Message; import io.quarkus.qute.i18n.MessageBundle; @MessageBundle public interface AppMessages { @Message("Hello world!") String hello(); @Message("Hello {name}!") String hello_name(String name); @Message("Hello {name} {surname}!") String hello_fullname(String name, String surname); // key=hello_with_if_section @Message(key = UNDERSCORED_ELEMENT_NAME, value = "{#if count eq 1}" + "{msg:hello_name('you guy')}" + "{#else}" + "{msg:hello_name('you guys')}" + "{/if}") String helloWithIfSection(int count); @Message("Item name: {item.name}, age: {item.age}") String itemDetail(Item item); @Message(key = "dot.test", value = "Dot test!") String dotTest(); @Message("There {msg:fileStrings(numberOfFiles)} on {disk}.") String files(int numberOfFiles, String disk); @Message("{#when numberOfFiles}" + "{#is 0}are no files" + "{#is 1}is one file" + "{#else}are {numberOfFiles} files" + "{/when}") String fileStrings(int numberOfFiles); }
539
549
from torch.nn.parallel import DataParallel, DistributedDataParallel from mmcv.utils import Registry MODULE_WRAPPERS = Registry('module wrapper') MODULE_WRAPPERS.register_module(module=DataParallel) MODULE_WRAPPERS.register_module(module=DistributedDataParallel)
79
319
<filename>alligator-compiler/src/main/java/me/aartikov/alligatorcompiler/ProcessingException.java package me.aartikov.alligatorcompiler; import javax.lang.model.element.Element; public class ProcessingException extends Exception { private Element element; public ProcessingException(Element element, String message, Object... args) { super(String.format(message, args)); this.element = element; } public Element getElement() { return element; } }
137
1,144
<filename>backend/de.metas.adempiere.adempiere/base/src/test/java/de/metas/dataentry/data/DataEntryRecordTest.java<gh_stars>1000+ package de.metas.dataentry.data; import static de.metas.dataentry.data.DataEntryRecordTestConstants.DATE; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigDecimal; import org.adempiere.exceptions.AdempiereException; import org.adempiere.test.AdempiereTestHelper; import org.adempiere.util.lang.impl.TableRecordReference; import org.compiere.model.I_M_Product; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import de.metas.dataentry.DataEntryFieldId; import de.metas.dataentry.DataEntrySubTabId; import de.metas.user.UserId; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class DataEntryRecordTest { @Before public void init() { AdempiereTestHelper.get().init(); } @Test public void setRecordField() { final DataEntrySubTabId dataEntrySubTabId = DataEntrySubTabId.ofRepoId(10); final DataEntryRecord dataEntryRecord = DataEntryRecord.builder() .dataEntrySubTabId(dataEntrySubTabId) .mainRecord(TableRecordReference.of(I_M_Product.Table_Name, 41)) .build(); final DataEntryFieldId fieldId1 = DataEntryFieldId.ofRepoId(1); final DataEntryFieldId fieldId2 = DataEntryFieldId.ofRepoId(2); final DataEntryFieldId fieldId3 = DataEntryFieldId.ofRepoId(3); final DataEntryFieldId fieldId4 = DataEntryFieldId.ofRepoId(4); final DataEntryFieldId fieldId5 = DataEntryFieldId.ofRepoId(5); final DataEntryFieldId fieldId6 = DataEntryFieldId.ofRepoId(6); // invoke method under test dataEntryRecord.setRecordField(fieldId1, UserId.ofRepoId(20), null); dataEntryRecord.setRecordField(fieldId2, UserId.ofRepoId(20), "text"); dataEntryRecord.setRecordField(fieldId3, UserId.ofRepoId(20), "longText"); dataEntryRecord.setRecordField(fieldId4, UserId.ofRepoId(20), true); dataEntryRecord.setRecordField(fieldId5, UserId.ofRepoId(20), new BigDecimal("15")); dataEntryRecord.setRecordField(fieldId6, UserId.ofRepoId(20), DATE); assertThat(dataEntryRecord.getFields()).isNotEmpty(); assertThat(dataEntryRecord.getFields()).doesNotContainNull(); final ImmutableMap<DataEntryFieldId, DataEntryRecordField<?>> resultMap = Maps.uniqueIndex(dataEntryRecord.getFields(), DataEntryRecordField::getDataEntryFieldId); assertThat(resultMap.get(fieldId1)).isNull(); assertThat(resultMap.get(fieldId2).getValue()).isEqualTo("text"); assertThat(resultMap.get(fieldId3).getValue()).isEqualTo("longText"); assertThat(resultMap.get(fieldId4).getValue()).isEqualTo(true); assertThat(resultMap.get(fieldId5).getValue()).isEqualTo(new BigDecimal("15")); assertThat(resultMap.get(fieldId6).getValue()).isEqualTo(DATE); } @Test public void changeRecordFieldValueToNull() { final DataEntrySubTabId dataEntrySubTabId = DataEntrySubTabId.ofRepoId(10); final DataEntryRecord dataEntryRecord = DataEntryRecord.builder() .dataEntrySubTabId(dataEntrySubTabId) .mainRecord(TableRecordReference.of(I_M_Product.Table_Name, 41)) .build(); final DataEntryFieldId fieldId1 = DataEntryFieldId.ofRepoId(1); assertThat(dataEntryRecord.getFieldValue(fieldId1).orElse(null)).isNull(); // IMPORTANT: first we are setting it to something not null and then to null. // If we would set it directly to null, there would be no change... dataEntryRecord.setRecordField(fieldId1, UserId.ofRepoId(20), "text"); assertThat(dataEntryRecord.getFieldValue(fieldId1).orElse(null)).isEqualTo("text"); dataEntryRecord.setRecordField(fieldId1, UserId.ofRepoId(20), null); assertThat(dataEntryRecord.getFieldValue(fieldId1).orElse(null)).isNull(); } @Test public void testImmutable() { final DataEntryRecord dataEntryRecord = DataEntryRecord.builder() .dataEntrySubTabId(DataEntrySubTabId.ofRepoId(10)) .mainRecord(TableRecordReference.of(I_M_Product.Table_Name, 41)) .build() // .copyAsImmutable(); final DataEntryFieldId fieldId1 = DataEntryFieldId.ofRepoId(1); final UserId updatedBy = UserId.ofRepoId(1); assertThatThrownBy(() -> dataEntryRecord.setRecordField(fieldId1, updatedBy, "bla")) .isInstanceOf(AdempiereException.class) .hasMessageStartingWith("Changing readonly instance is not allowed: "); } }
1,779
488
<filename>projects/SATIrE/src/analyzer/support/satire/satire_file_utils.h // A few functions to take care of annoying file naming and creation issues. #ifndef H_SATIRE_FILE_UTILS #define H_SATIRE_FILE_UTILS #include <vector> #include <string> #include <fstream> namespace SATIrE { // Split a path name: "a//b/c" -> ["a", "b", "c"] // special case: leading / is kept as separate component std::vector<std::string> pathNameComponents(std::string pathName); // Construct path name from components: ["a", "b", "c"] -> "a/b/c" std::string pathName(const std::vector<std::string> &components); // Prefix a file name: "a/b", "prx" -> "a/prx_b"; as a special case, // prefixing with the empty string does nothing. std::string prefixedFileName(std::string fileName, std::string prefix); // Create a possibly nested directory. void createDirectoryHierarchy(const std::vector<std::string> &components); // Open a file for writing; if the file name refers to a subdirectory that // does not exist, this creates all required directories (true on success). bool openFileForWriting(std::ofstream &file, std::string fileName); } // namespace SATIrE #endif
370
1,139
package com.journaldev.androidrssfeedtutorial; import android.app.ListActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; public class RSSFeedActivity extends ListActivity { private ProgressBar pDialog; ArrayList<HashMap<String, String>> rssItemList = new ArrayList<>(); RSSParser rssParser = new RSSParser(); Toolbar toolbar; List<RSSItem> rssItems = new ArrayList<>(); private static String TAG_TITLE = "title"; private static String TAG_LINK = "link"; private static String TAG_PUB_DATE = "pubDate"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rss_feed); String rss_link = getIntent().getStringExtra("rssLink"); new LoadRSSFeedItems().execute(rss_link); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent in = new Intent(getApplicationContext(), BrowserActivity.class); String page_url = ((TextView) view.findViewById(R.id.page_url)).getText().toString().trim(); in.putExtra("url", page_url); startActivity(in); } }); } public class LoadRSSFeedItems extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressBar(RSSFeedActivity.this, null, android.R.attr.progressBarStyleLarge); RelativeLayout relativeLayout = findViewById(R.id.relativeLayout); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ); lp.addRule(RelativeLayout.CENTER_IN_PARENT); pDialog.setLayoutParams(lp); pDialog.setVisibility(View.VISIBLE); relativeLayout.addView(pDialog); } @Override protected String doInBackground(String... args) { // rss link url String rss_url = args[0]; // list of rss items rssItems = rssParser.getRSSFeedItems(rss_url); // looping through each item for (RSSItem item : rssItems) { // creating new HashMap if (item.link.toString().equals("")) break; HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value String givenDateString = item.pubdate.trim(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); try { Date mDate = sdf.parse(givenDateString); SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, dd MMMM yyyy - hh:mm a", Locale.US); item.pubdate = sdf2.format(mDate); } catch (ParseException e) { e.printStackTrace(); } map.put(TAG_TITLE, item.title); map.put(TAG_LINK, item.link); map.put(TAG_PUB_DATE, item.pubdate); // If you want parse the date // adding HashList to ArrayList rssItemList.add(map); } // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { ListAdapter adapter = new SimpleAdapter( RSSFeedActivity.this, rssItemList, R.layout.rss_item_list_row, new String[]{TAG_LINK, TAG_TITLE, TAG_PUB_DATE}, new int[]{R.id.page_url, R.id.title, R.id.pub_date}); // updating listview setListAdapter(adapter); } }); return null; } protected void onPostExecute(String args) { pDialog.setVisibility(View.GONE); } } }
2,235
577
package org.apache.commons.cli; import java.math.BigDecimal; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; public class OptionBuilderTest extends TestCase { public OptionBuilderTest( String name ) { super( name ); } public static Test suite() { return new TestSuite( OptionBuilderTest.class ); } public static void main( String args[] ) { TestRunner.run( suite() ); } public void testCompleteOption( ) { OptionBuilder.withLongOpt( "simple option"); OptionBuilder.hasArg( ); OptionBuilder.isRequired( ); OptionBuilder.hasArgs( ); OptionBuilder.withType( new BigDecimal( "10" ) ); OptionBuilder.withDescription( "this is a simple option" ); Option simple = OptionBuilder.create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), BigDecimal.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); } public void testTwoCompleteOptions( ) { OptionBuilder.withLongOpt( "simple option"); OptionBuilder.hasArg( ); OptionBuilder.isRequired( ); OptionBuilder.hasArgs( ); OptionBuilder.withType( new BigDecimal( "10" ) ); OptionBuilder.withDescription( "this is a simple option" ); Option simple = OptionBuilder.create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), BigDecimal.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); OptionBuilder.withLongOpt( "dimple option"); OptionBuilder.hasArg( ); OptionBuilder.withDescription( "this is a dimple option" ); simple = OptionBuilder.create( 'd' ); assertEquals( "d", simple.getOpt() ); assertEquals( "dimple option", simple.getLongOpt() ); assertEquals( "this is a dimple option", simple.getDescription() ); assertNull( simple.getType() ); assertTrue( simple.hasArg() ); assertTrue( !simple.isRequired() ); assertTrue( !simple.hasArgs() ); } public void testBaseOptionCharOpt() { OptionBuilder.withDescription( "option description"); Option base = OptionBuilder.create( 'o' ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testBaseOptionStringOpt() { OptionBuilder.withDescription( "option description"); Option base = OptionBuilder.create( "o" ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testSpecialOptChars() { // '?' try { OptionBuilder.withDescription( "help options" ); Option opt = OptionBuilder.create( '?' ); assertEquals( "?", opt.getOpt() ); } catch( IllegalArgumentException arg ) { fail( "IllegalArgumentException caught" ); } // '@' try { OptionBuilder.withDescription( "read from stdin" ); Option opt = OptionBuilder.create( '@' ); assertEquals( "@", opt.getOpt() ); } catch( IllegalArgumentException arg ) { fail( "IllegalArgumentException caught" ); } } public void testOptionArgNumbers() { OptionBuilder.withDescription( "option description" ); OptionBuilder.hasArgs( 2 ); Option opt = OptionBuilder.create( 'o' ); assertEquals( 2, opt.getArgs() ); } public void testIllegalOptions() { // bad single character option try { OptionBuilder.withDescription( "option description" ); OptionBuilder.create( '"' ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // bad character in option string try { OptionBuilder.create( "opt`" ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // null option try { OptionBuilder.create( null ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // valid option try { OptionBuilder.create( "opt" ); // success } catch( IllegalArgumentException exp ) { fail( "IllegalArgumentException caught" ); } } }
2,134
311
<reponame>80952556400/java-language-server<gh_stars>100-1000 package org.javacs.debug.proto; public class StoppedEventBody { /** * The reason for the event. For backward compatibility this string is shown in the UI if the 'description' * attribute is missing (but it must not be translated). Values: 'step', 'breakpoint', 'exception', 'pause', * 'entry', 'goto', 'function breakpoint', 'data breakpoint', etc. */ public String reason; /** * The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be * translated. */ public String description; /** The thread which was stopped. */ public Long threadId; /** A value of true hints to the frontend that this event should not change the focus. */ public Boolean preserveFocusHint; /** * Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in * the UI. */ public String text; /** * If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped. - The client should * use this information to enable that all threads can be expanded to access their stacktraces. - If the attribute * is missing or false, only the thread with the given threadId can be expanded. */ public Boolean allThreadsStopped; }
436
1,197
/** * Copyright (c) 2013, 2015, ControlsFX * 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 ControlsFX, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.controlsfx.control; import impl.org.controlsfx.skin.RatingSkin; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Orientation; import javafx.scene.control.Skin; /** * A control for allowing users to provide a rating. This control supports * {@link #partialRatingProperty() partial ratings} (i.e. not whole numbers and * dependent upon where the user clicks in the control) and * {@link #updateOnHoverProperty() updating the rating on hover}. Read on for * more examples! * * <h3>Examples</h3> * It can be hard to appreciate some of the features of the Rating control, so * hopefully the following screenshots will help. Firstly, here is what the * standard (horizontal) Rating control looks like when it has five stars, and a * rating of two: * * <br> * <center> * <img src="rating-horizontal.png" alt="Screenshot of horizontal Rating"> * </center> * * <p>To create a Rating control that looks like this is simple: * * <pre> * {@code * final Rating rating = new Rating();}</pre> * * <p>This creates a default horizontal rating control. To create a vertical * Rating control, simply change the orientation, as such: * * <pre> * {@code * final Rating rating = new Rating(); * rating.setOrientation(Orientation.VERTICAL);}</pre> * * <p>The end result of making this one line change is shown in the screenshot * below: * * <br> * <center> * <img src="rating-vertical.png" alt="Screenshot of vertical Rating"> * </center> * * <p>One of the features of the Rating control is that it doesn't just allow * for 'integer' ratings: it also allows for the user to click anywhere within * the rating area to set a 'float' rating. This is hard to describe, but easy * to show in a picture: * * <br> * <center> * <img src="rating-partial.png" alt="Screenshot of partial Rating"> * </center> * * <p>In essence, in the screenshot above, the user clicked roughly in the * middle of the third star. This results in a rating of approximately 2.44. * To enable {@link #partialRatingProperty() partial ratings}, simply do the * following when instantiating the Rating control: * * <pre> * {@code * final Rating rating = new Rating(); * rating.setPartialRating(true);}</pre> * * <p>So far all of the Rating controls demonstrated above have * required the user to click on the stars to register their rating. This may not * be the preferred user interaction - often times the preferred approach is to * simply allow for the rating to be registered by the user hovering their mouse * over the rating stars. This mode is also supported by the Rating control, * using the {@link #updateOnHoverProperty() update on hover} property, as such: * * <pre> * {@code * final Rating rating = new Rating(); * rating.setUpdateOnHover(true);}</pre> * * <p>It is also allowable to have a Rating control that both updates on hover * and allows for partial values: the 'golden fill' of the default graphics will * automatically follow the users mouse as they move it along the Rating scale. * To enable this, just set both properties to true. */ public class Rating extends ControlsFXControl { /*************************************************************************** * * Constructors * **************************************************************************/ /** * Creates a default instance with a minimum rating of 0 and a maximum * rating of 5. */ public Rating() { this(5); } /** * Creates a default instance with a minimum rating of 0 and a maximum rating * as provided by the argument. * * @param max The maximum allowed rating value. */ public Rating(int max) { this(max, -1); } /** * Creates a Rating instance with a minimum rating of 0, a maximum rating * as provided by the {@code max} argument, and a current rating as provided * by the {@code rating} argument. * * @param max The maximum allowed rating value. */ public Rating(int max, int rating) { getStyleClass().setAll("rating"); //$NON-NLS-1$ setMax(max); setRating(rating == -1 ? (int) Math.floor(max / 2.0) : rating); } /*************************************************************************** * * Overriding public API * **************************************************************************/ /** {@inheritDoc} */ @Override protected Skin<?> createDefaultSkin() { return new RatingSkin(this); } /** {@inheritDoc} */ @Override public String getUserAgentStylesheet() { return getUserAgentStylesheet(Rating.class, "rating.css"); } /*************************************************************************** * * Properties * **************************************************************************/ // --- Rating /** * The current rating value. */ public final DoubleProperty ratingProperty() { return rating; } private DoubleProperty rating = new SimpleDoubleProperty(this, "rating", 3); //$NON-NLS-1$ /** * Sets the current rating value. */ public final void setRating(double value) { ratingProperty().set(value); } /** * Returns the current rating value. */ public final double getRating() { return rating == null ? 3 : rating.get(); } // --- Max /** * The maximum-allowed rating value. */ public final IntegerProperty maxProperty() { return max; } private IntegerProperty max = new SimpleIntegerProperty(this, "max", 5); //$NON-NLS-1$ /** * Sets the maximum-allowed rating value. */ public final void setMax(int value) { maxProperty().set(value); } /** * Returns the maximum-allowed rating value. */ public final int getMax() { return max == null ? 5 : max.get(); } // --- Orientation /** * The {@link Orientation} of the {@code Rating} - this can either be * horizontal or vertical. */ public final ObjectProperty<Orientation> orientationProperty() { if (orientation == null) { orientation = new SimpleObjectProperty<>(this, "orientation", Orientation.HORIZONTAL); //$NON-NLS-1$ } return orientation; } private ObjectProperty<Orientation> orientation; /** * Sets the {@link Orientation} of the {@code Rating} - this can either be * horizontal or vertical. */ public final void setOrientation(Orientation value) { orientationProperty().set(value); }; /** * Returns the {@link Orientation} of the {@code Rating} - this can either * be horizontal or vertical. */ public final Orientation getOrientation() { return orientation == null ? Orientation.HORIZONTAL : orientation.get(); } // --- partial rating /** * If true this allows for users to set a rating as a floating point value. * In other words, the range of the rating 'stars' can be thought of as a * range between [0, max], and whereever the user clicks will be calculated * as the new rating value. If this is false the more typical approach is used * where the selected 'star' is used as the rating. */ public final BooleanProperty partialRatingProperty() { return partialRating; } private BooleanProperty partialRating = new SimpleBooleanProperty(this, "partialRating", false); //$NON-NLS-1$ /** * Sets whether {@link #partialRatingProperty() partial rating} support is * enabled or not. */ public final void setPartialRating(boolean value) { partialRatingProperty().set(value); } /** * Returns whether {@link #partialRatingProperty() partial rating} support is * enabled or not. */ public final boolean isPartialRating() { return partialRating == null ? false : partialRating.get(); } // --- update on hover /** * If true this allows for the {@link #ratingProperty() rating property} to * be updated simply by the user hovering their mouse over the control. If * false the user is required to click on their preferred rating to register * the new rating with this control. */ public final BooleanProperty updateOnHoverProperty() { return updateOnHover; } private BooleanProperty updateOnHover = new SimpleBooleanProperty(this, "updateOnHover", false); //$NON-NLS-1$ /** * Sets whether {@link #updateOnHoverProperty() update on hover} support is * enabled or not. */ public final void setUpdateOnHover(boolean value) { updateOnHoverProperty().set(value); } /** * Returns whether {@link #updateOnHoverProperty() update on hover} support is * enabled or not. */ public final boolean isUpdateOnHover() { return updateOnHover == null ? false : updateOnHover.get(); } }
3,581
316
<filename>plugins/k8s/resoto_plugin_k8s/resources/replica_set.py from kubernetes import client from .common import KubernetesResource from resotolib.baseresources import ( BaseResource, ) from typing import ClassVar, Dict from dataclasses import dataclass @dataclass(eq=False) class KubernetesReplicaSet(KubernetesResource, BaseResource): kind: ClassVar[str] = "kubernetes_replica_set" api: ClassVar[object] = client.AppsV1Api list_method: ClassVar[str] = "list_replica_set_for_all_namespaces" attr_map: ClassVar[Dict] = {"replicas": lambda r: r.spec.replicas} replicas: int = 0
224
1,134
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ import six from cfnlint.rules import CloudFormationLintRule, RuleMatch class SubNotJoin(CloudFormationLintRule): """Check if Join is being used with no join characters""" id = 'I1022' shortdesc = 'Use Sub instead of Join' description = 'Prefer a sub instead of Join when using a join delimiter that is empty' source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' tags = ['functions', 'sub', 'join'] def match(self, cfn): matches = [] join_objs = cfn.search_deep_keys('Fn::Join') for join_obj in join_objs: if isinstance(join_obj[-1], list): join_operator = join_obj[-1][0] if isinstance(join_operator, six.string_types): if join_operator == '': matches.append(RuleMatch( join_obj[0:-1], 'Prefer using Fn::Sub over Fn::Join with an empty delimiter')) return matches
464
574
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.legacy.unittest; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; import com.alibaba.druid.sql.parser.ParserException; import com.alibaba.druid.sql.parser.Token; import com.amazon.opendistroforelasticsearch.sql.legacy.domain.Select; import com.amazon.opendistroforelasticsearch.sql.legacy.exception.SqlParseException; import com.amazon.opendistroforelasticsearch.sql.legacy.rewriter.nestedfield.NestedFieldProjection; import com.amazon.opendistroforelasticsearch.sql.legacy.parser.ElasticSqlExprParser; import com.amazon.opendistroforelasticsearch.sql.legacy.parser.SqlParser; import com.amazon.opendistroforelasticsearch.sql.legacy.query.DefaultQueryAction; import com.amazon.opendistroforelasticsearch.sql.legacy.query.maker.QueryMaker; import com.amazon.opendistroforelasticsearch.sql.legacy.rewriter.nestedfield.NestedFieldRewriter; import com.amazon.opendistroforelasticsearch.sql.legacy.util.HasFieldWithValue; import org.elasticsearch.action.search.SearchAction; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.NestedQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; import java.util.function.Function; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.anything; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; public class NestedFieldProjectionTest { @Test public void regression() { assertThat(query("SELECT region FROM team"), is(anything())); assertThat(query("SELECT region FROM team WHERE nested(employees.age) = 30"), is(anything())); assertThat(query("SELECT * FROM team WHERE region = 'US'"), is(anything())); } @Test public void nestedFieldSelectAll() { assertThat( query("SELECT nested(employees.*) FROM team"), source( boolQuery( filter( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.*") ) ) ) ) ) ) ); } @Test public void nestedFieldInSelect() { assertThat( query("SELECT nested(employees.firstname) FROM team"), source( boolQuery( filter( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.firstname") ) ) ) ) ) ) ); } @Test public void regularAndNestedFieldInSelect() { assertThat( query("SELECT region, nested(employees.firstname) FROM team"), source( boolQuery( filter( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.firstname") ) ) ) ) ), fetchSource("region") ) ); } /* // Should be integration test @Test public void nestedFieldInWhereSelectAll() {} */ @Test public void nestedFieldInSelectAndWhere() { assertThat( query("SELECT nested(employees.firstname) " + " FROM team " + " WHERE nested(employees.age) = 30"), source( boolQuery( filter( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.firstname") ) ) ) ) ) ) ); } @Test public void regularAndNestedFieldInSelectAndWhere() { assertThat( query("SELECT region, nested(employees.firstname) " + " FROM team " + " WHERE nested(employees.age) = 30"), source( boolQuery( filter( boolQuery( must( nestedQuery( innerHits("employees.firstname") ) ) ) ) ), fetchSource("region") ) ); } @Test public void multipleSameNestedFields() { assertThat( query("SELECT nested(employees.firstname), nested(employees.lastname) " + " FROM team " + " WHERE nested(\"employees\", employees.age = 30 AND employees.firstname LIKE 'John')"), source( boolQuery( filter( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.firstname", "employees.lastname") ) ) ) ) ) ) ); } @Test public void multipleDifferentNestedFields() { assertThat( query("SELECT region, nested(employees.firstname), nested(manager.name) " + " FROM team " + " WHERE nested(employees.age) = 30 AND nested(manager.age) = 50"), source( boolQuery( filter( boolQuery( must( boolQuery( must( nestedQuery( path("employees"), innerHits("employees.firstname") ), nestedQuery( path("manager"), innerHits("manager.name") ) ) ) ) ) ) ), fetchSource("region") ) ); } @Test public void leftJoinWithSelectAll() { assertThat( query("SELECT * FROM team AS t LEFT JOIN t.projects AS p "), source( boolQuery( filter( boolQuery( should( boolQuery( mustNot( nestedQuery( path("projects") ) ) ), nestedQuery( path("projects"), innerHits("projects.*") ) ) ) ) ) ) ); } @Test public void leftJoinWithSpecificFields() { assertThat( query("SELECT t.name, p.name, p.started_year FROM team AS t LEFT JOIN t.projects AS p "), source( boolQuery( filter( boolQuery( should( boolQuery( mustNot( nestedQuery( path("projects") ) ) ), nestedQuery( path("projects"), innerHits("projects.name", "projects.started_year") ) ) ) ) ), fetchSource("name") ) ); } private Matcher<SearchSourceBuilder> source(Matcher<QueryBuilder> queryMatcher) { return featureValueOf("query", queryMatcher, SearchSourceBuilder::query); } private Matcher<SearchSourceBuilder> source(Matcher<QueryBuilder> queryMatcher, Matcher<FetchSourceContext> fetchSourceMatcher) { return allOf( featureValueOf("query", queryMatcher, SearchSourceBuilder::query), featureValueOf("fetchSource", fetchSourceMatcher, SearchSourceBuilder::fetchSource) ); } /** Asserting instanceOf and continue other chained matchers of subclass requires explicity cast */ @SuppressWarnings("unchecked") private Matcher<QueryBuilder> boolQuery(Matcher<BoolQueryBuilder> matcher) { return (Matcher) allOf(instanceOf(BoolQueryBuilder.class), matcher); } @SafeVarargs @SuppressWarnings("unchecked") private final Matcher<QueryBuilder> nestedQuery(Matcher<NestedQueryBuilder>... matchers) { return (Matcher) both(is(Matchers.<NestedQueryBuilder>instanceOf(NestedQueryBuilder.class))). and(allOf(matchers)); } @SafeVarargs private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> filter(Matcher<QueryBuilder>... matchers) { return hasClauses("filter", BoolQueryBuilder::filter, matchers); } @SafeVarargs private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> must(Matcher<QueryBuilder>... matchers) { return hasClauses("must", BoolQueryBuilder::must, matchers); } @SafeVarargs private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> mustNot(Matcher<QueryBuilder>... matchers) { return hasClauses("must_not", BoolQueryBuilder::mustNot, matchers); } @SafeVarargs private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> should(Matcher<QueryBuilder>... matchers) { return hasClauses("should", BoolQueryBuilder::should, matchers); } /** Hide contains() assertion to simplify */ @SafeVarargs private final FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>> hasClauses(String name, Function<BoolQueryBuilder, List<QueryBuilder>> func, Matcher<QueryBuilder>... matchers) { return new FeatureMatcher<BoolQueryBuilder, List<QueryBuilder>>(contains(matchers), name, name) { @Override protected List<QueryBuilder> featureValueOf(BoolQueryBuilder query) { return func.apply(query); } }; } private Matcher<NestedQueryBuilder> path(String expected) { return HasFieldWithValue.hasFieldWithValue("path", "path", is(equalTo(expected))); } /** Skip intermediate property along the path. Hide arrayContaining assertion to simplify. */ private FeatureMatcher<NestedQueryBuilder, String[]> innerHits(String... expected) { return featureValueOf("innerHits", arrayContaining(expected), (nestedQuery -> nestedQuery.innerHit().getFetchSourceContext().includes())); } @SuppressWarnings("unchecked") private Matcher<FetchSourceContext> fetchSource(String... expected) { if (expected.length == 0) { return anyOf(is(nullValue()), featureValueOf("includes", is(nullValue()), FetchSourceContext::includes), featureValueOf("includes", is(emptyArray()), FetchSourceContext::includes)); } return featureValueOf("includes", contains(expected), fetchSource -> Arrays.asList(fetchSource.includes())); } private <T, U> FeatureMatcher<T, U> featureValueOf(String name, Matcher<U> subMatcher, Function<T, U> getter) { return new FeatureMatcher<T, U>(subMatcher, name, name) { @Override protected U featureValueOf(T actual) { return getter.apply(actual); } }; } private SearchSourceBuilder query(String sql) { SQLQueryExpr expr = parseSql(sql); if (sql.contains("nested")) { return translate(expr).source(); } expr = rewrite(expr); return translate(expr).source(); } private SearchRequest translate(SQLQueryExpr expr) { try { Client mockClient = Mockito.mock(Client.class); SearchRequestBuilder request = new SearchRequestBuilder(mockClient, SearchAction.INSTANCE); Select select = new SqlParser().parseSelect(expr); DefaultQueryAction action = new DefaultQueryAction(mockClient, select); action.initialize(request); action.setFields(select.getFields()); if (select.getWhere() != null) { request.setQuery(QueryMaker.explain(select.getWhere(), select.isQuery)); } new NestedFieldProjection(request).project(select.getFields(), select.getNestedJoinType()); return request.request(); } catch (SqlParseException e) { throw new ParserException("Illegal sql expr: " + expr.toString()); } } private SQLQueryExpr parseSql(String sql) { ElasticSqlExprParser parser = new ElasticSqlExprParser(sql); SQLExpr expr = parser.expr(); if (parser.getLexer().token() != Token.EOF) { throw new ParserException("Illegal sql: " + sql); } return (SQLQueryExpr) expr; } private SQLQueryExpr rewrite(SQLQueryExpr expr) { expr.accept(new NestedFieldRewriter()); return expr; } }
8,702
1,958
package com.freetymekiyan.algorithms.level.easy; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * 405. Convert A Number To Hexidecimal * <p> * Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is * used. * <p> * Note: * <p> * All letters in hexadecimal (a-f) must be in lowercase. * The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero * character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. * The given number is guaranteed to fit within the range of a 32-bit signed integer. * You must not use any method provided by the library which converts/formats the number to hex directly. * Example 1: * <p> * Input: * 26 * <p> * Output: * "1a" * Example 2: * <p> * Input: * -1 * <p> * Output: * "ffffffff" * <p> * Related Topics: Bit Manipulation * <p> * Companies: Microsoft */ public class ConvertANumberToHexadecimal { private ConvertANumberToHexadecimal c; /** * Math * Given a number and a base, convert the number */ public String convert(int num, int base) { // Deal with negative numbers boolean isNegative = false; if (num < 0 && base == 10) { isNegative = true; num = -num; } // Process individual digits final StringBuilder sb = new StringBuilder(); while (num != 0) { int rem = num % base; char c = (char) ((rem > 9) ? (rem - 10) + 'a' : rem + '0'); sb.insert(0, c); num = num / base; } // If number is negative, append '-' if (isNegative) sb.insert(0, '-'); return sb.toString(); } @Before public void setUp() { c = new ConvertANumberToHexadecimal(); } @Test public void testPositiveNumbers() { String res = c.convert(80, 16); Assert.assertEquals("50", res); res = c.convert(3200, 16); Assert.assertEquals("c80", res); } @After public void tearDown() { c = null; } }
761
344
<reponame>jsaynysa/Ksiazka //=============================================================================== // @ Player.cpp // ------------------------------------------------------------------------------ // Player // // Copyright (C) 2008-2015 by <NAME> and <NAME>. // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // // //=============================================================================== //------------------------------------------------------------------------------- //-- Dependencies --------------------------------------------------------------- //------------------------------------------------------------------------------- #include <IvRenderer.h> #include <IvEventHandler.h> #include <IvMatrix33.h> #include <IvMatrix44.h> #include <IvRendererHelp.h> #include "Game.h" #include "Player.h" //------------------------------------------------------------------------------- //-- Static Members ------------------------------------------------------------- //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- //-- Methods -------------------------------------------------------------------- //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- // @ Player::Player() //------------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------------- Player::Player() { IvVector3* samplePositions = new IvVector3[5]; samplePositions[0].Set( -6.0f, 3.0f, -5.0f ); samplePositions[1].Set( 0.0f, 0.0f, 0.0f ); samplePositions[2].Set( -3.0f, -1.0f, 5.0f ); samplePositions[3].Set( 6.0f, 1.0f, 2.0f ); samplePositions[4].Set( 12.0f, -3.0, -1.0f ); float* sampleTimes = new float[5]; sampleTimes[0] = 0.0f; sampleTimes[1] = 3.0f; sampleTimes[2] = 6.0f; sampleTimes[3] = 9.0f; sampleTimes[4] = 12.0f; mCurve.InitializeNatural( samplePositions, sampleTimes, 5 ); delete [] samplePositions; delete [] sampleTimes; mTime = 0.0f; mRun = true; mMode = 0; } // End of Player::Player() //------------------------------------------------------------------------------- // @ Player::~Player() //------------------------------------------------------------------------------- // Destructor //------------------------------------------------------------------------------- Player::~Player() { } // End of Player::~Player() //------------------------------------------------------------------------------- // @ Player::Update() //------------------------------------------------------------------------------- // Main update loop //------------------------------------------------------------------------------- void Player::Update( float dt ) { // update based on input if (IvGame::mGame->mEventHandler->IsKeyPressed(' ')) { if (mRun) { mTime = 0.0f; mRun = false; } else { mRun = true; } } if (IvGame::mGame->mEventHandler->IsKeyPressed('m')) { mMode = (mMode + 1)%4; } if (mRun) { mTime += dt; // stop just before end so we don't end up with zero vector // when we look ahead if ( mTime > 11.5f ) mTime = 11.5f; } // now we set up the camera // get eye position IvVector3 eye = mCurve.Evaluate( mTime ); IvVector3 viewDir; IvVector3 viewSide; IvVector3 viewUp; // set parameters depending on what mode we're in // Frenet frame if ( mMode == 3 ) { IvVector3 T = mCurve.Velocity( mTime ); IvVector3 a = mCurve.Acceleration( mTime ); IvVector3 B = T.Cross( a ); B.Normalize(); T.Normalize(); IvVector3 N = B.Cross( T ); viewDir = T; viewSide = -N; // have to negate to get from RH frame to LH frame viewUp = B; } else { IvVector3 lookAt; // look same direction all the time if ( mMode == 2 ) { viewDir = IvVector3::xAxis; } // look along tangent else if ( mMode == 1 ) { viewDir = mCurve.Velocity( mTime ); } // look ahead .5 in parameter else if ( mMode == 0 ) { viewDir = mCurve.Evaluate( mTime+0.5f ) - eye; } // compute view vectors viewDir.Normalize(); viewUp = IvVector3::zAxis - IvVector3::zAxis.Dot(viewDir)*viewDir; viewUp.Normalize(); viewSide = viewDir.Cross(viewUp); } // now set up matrices // build transposed rotation matrix IvMatrix33 rotate; if ( IvRenderer::mRenderer->GetAPI() == kOpenGL ) { rotate.SetRows( viewSide, viewUp, -viewDir ); } else { rotate.SetRows( viewSide, viewUp, viewDir ); } // transform translation IvVector3 eyeInv = -(rotate*eye); // build 4x4 matrix IvMatrix44 matrix(rotate); matrix(0,3) = eyeInv.x; matrix(1,3) = eyeInv.y; matrix(2,3) = eyeInv.z; ::IvSetViewMatrix( matrix ); } // End of Player::Update() //------------------------------------------------------------------------------- // @ Player::Render() //------------------------------------------------------------------------------- // Render the curve //------------------------------------------------------------------------------- void Player::Render() { IvMatrix44 mat; ::IvSetWorldMatrix( mat ); mCurve.Render(); }
1,984
386
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_CUBICBASIS_INL #define IECORE_CUBICBASIS_INL #include "IECore/CubicBasis.h" #include "IECore/Exception.h" namespace IECore { template<typename T> CubicBasis<T>::CubicBasis( const MatrixType &m, unsigned s ) : matrix( m ), step( s ) { } template<typename T> CubicBasis<T>::CubicBasis( StandardCubicBasis standardBasis ) { switch( standardBasis ) { case StandardCubicBasis::Linear: *this = CubicBasis<T>::linear(); break; case StandardCubicBasis::Bezier: *this = CubicBasis<T>::bezier(); break; case StandardCubicBasis::BSpline: *this = CubicBasis<T>::bSpline(); break; case StandardCubicBasis::CatmullRom: *this = CubicBasis<T>::catmullRom(); break; case StandardCubicBasis::Unknown: throw IECore::Exception( "CubicBasis::CubicBasis - Invalid basis"); } } template<typename T> template<class S> inline void CubicBasis<T>::coefficients( S t, S &c0, S &c1, S &c2, S &c3 ) const { S t2 = t * t; S t3 = t2 * t; c0 = matrix[0][0] * t3 + matrix[1][0] * t2 + matrix[2][0] * t + matrix[3][0]; c1 = matrix[0][1] * t3 + matrix[1][1] * t2 + matrix[2][1] * t + matrix[3][1]; c2 = matrix[0][2] * t3 + matrix[1][2] * t2 + matrix[2][2] * t + matrix[3][2]; c3 = matrix[0][3] * t3 + matrix[1][3] * t2 + matrix[2][3] * t + matrix[3][3]; } template<typename T> template<class S> inline void CubicBasis<T>::coefficients( S t, S c[4] ) const { coefficients( t, c[0], c[1], c[2], c[3] ); } template<typename T> template<class S> inline S CubicBasis<T>::operator() ( S t, S p0, S p1, S p2, S p3 ) const { S c0, c1, c2, c3; coefficients( t, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> template<class S> inline S CubicBasis<T>::operator() ( S t, const S p[4] ) const { S c0, c1, c2, c3; coefficients( t, c0, c1, c2, c3 ); return c0 * p[0] + c1 * p[1] + c2 * p[2] + c3 * p[3]; } template<typename T> template<class S> inline S CubicBasis<T>::operator() ( typename S::BaseType t, const S &p0, const S &p1, const S &p2, const S &p3 ) const { typename S::BaseType c0, c1, c2, c3; coefficients( t, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> inline int CubicBasis<T>::numCoefficients() const { int result = 0; for( int i = 0; i < 4; ++i ) { if( matrix[0][i] != 0 || matrix[1][i] != 0 || matrix[2][i] != 0 || matrix[3][i] != 0 ) { result = i + 1; } } return result; } template<typename T> template<class S> inline S CubicBasis<T>::operator() ( typename S::BaseType t, const S p[4] ) const { return operator()<S>( t, p[0], p[1], p[2], p[3] ); } template<typename T> template<class S> inline void CubicBasis<T>::derivativeCoefficients( S t, S &c0, S &c1, S &c2, S &c3 ) const { S twoT = 2.0 * t; S threeT2 = 3.0 * t * t; c0 = matrix[0][0] * threeT2 + matrix[1][0] * twoT + matrix[2][0]; c1 = matrix[0][1] * threeT2 + matrix[1][1] * twoT + matrix[2][1]; c2 = matrix[0][2] * threeT2 + matrix[1][2] * twoT + matrix[2][2]; c3 = matrix[0][3] * threeT2 + matrix[1][3] * twoT + matrix[2][3]; } template<typename T> template<class S> inline void CubicBasis<T>::derivativeCoefficients( S t, S c[4] ) const { derivativeCoefficients( t, c[0], c[1], c[2], c[3] ); } template<typename T> template<class S> inline S CubicBasis<T>::derivative( S t, S p0, S p1, S p2, S p3 ) const { S c0, c1, c2, c3; derivativeCoefficients( t, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> template<class S> inline S CubicBasis<T>::derivative( S t, const S p[4] ) const { S c0, c1, c2, c3; derivativeCoefficients( t, c0, c1, c2, c3 ); return c0 * p[0] + c1 * p[1] + c2 * p[2] + c3 * p[3]; } template<typename T> template<class S> inline S CubicBasis<T>::derivative( typename S::BaseType t, const S &p0, const S &p1, const S &p2, const S &p3 ) const { typename S::BaseType c0, c1, c2, c3; derivativeCoefficients( t, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> template<class S> inline S CubicBasis<T>::derivative( typename S::BaseType t, const S p[4] ) const { return derivative( t, p[0], p[1], p[2], p[3] ); } template<typename T> template<class S> inline void CubicBasis<T>::integralCoefficients( S t0, S t1, S &c0, S &c1, S &c2, S &c3 ) const { S t02 = t0 * t0; S t03 = t02 * t0; S t04 = t03 * t0; S t12 = t1 * t1; S t13 = t12 * t1; S t14 = t13 * t1; t02 /= 2.0f; t03 /= 3.0f; t04 /= 4.0f; t12 /= 2.0f; t13 /= 3.0f; t14 /= 4.0f; c0 = matrix[0][0] * t14 + matrix[1][0] * t13 + matrix[2][0] * t12 + matrix[3][0] * t1; c1 = matrix[0][1] * t14 + matrix[1][1] * t13 + matrix[2][1] * t12 + matrix[3][1] * t1; c2 = matrix[0][2] * t14 + matrix[1][2] * t13 + matrix[2][2] * t12 + matrix[3][2] * t1; c3 = matrix[0][3] * t14 + matrix[1][3] * t13 + matrix[2][3] * t12 + matrix[3][3] * t1; c0 -= matrix[0][0] * t04 + matrix[1][0] * t03 + matrix[2][0] * t02 + matrix[3][0] * t0; c1 -= matrix[0][1] * t04 + matrix[1][1] * t03 + matrix[2][1] * t02 + matrix[3][1] * t0; c2 -= matrix[0][2] * t04 + matrix[1][2] * t03 + matrix[2][2] * t02 + matrix[3][2] * t0; c3 -= matrix[0][3] * t04 + matrix[1][3] * t03 + matrix[2][3] * t02 + matrix[3][3] * t0; } template<typename T> template<class S> inline void CubicBasis<T>::integralCoefficients( S t0, S t1, S c[4] ) const { integralCoefficients( t0, t1, c[0], c[1], c[2], c[3] ); } template<typename T> template<class S> inline S CubicBasis<T>::integral( S t0, S t1, S p0, S p1, S p2, S p3 ) const { S c0, c1, c2, c3; integralCoefficients( t0, t1, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> template<class S> inline S CubicBasis<T>::integral( S t0, S t1, const S p[4] ) const { S c0, c1, c2, c3; integralCoefficients( t0, t1, c0, c1, c2, c3 ); return c0 * p[0] + c1 * p[1] + c2 * p[2] + c3 * p[3]; } template<typename T> template<class S> inline S CubicBasis<T>::integral( typename S::BaseType t0, typename S::BaseType t1, const S &p0, const S &p1, const S &p2, const S &p3 ) const { typename S::BaseType c0, c1, c2, c3; integralCoefficients( t0, t1, c0, c1, c2, c3 ); return c0 * p0 + c1 * p1 + c2 * p2 + c3 * p3; } template<typename T> template<class S> inline S CubicBasis<T>::integral( typename S::BaseType t0, typename S::BaseType t1, const S p[4] ) const { return integral( t0, t1, p[0], p[1], p[2], p[3] ); } template<typename T> template<class S> inline bool CubicBasis<T>::criticalPoints( const S p[4], S &out0, S &out1 ) const { // Quadratic formula applied to derivatives S a = S(3.0) * ( p[0] * matrix[0][0] + p[1] * matrix[0][1] + p[2] * matrix[0][2] + p[3] * matrix[0][3] ); S b = S(2.0) * ( p[0] * matrix[1][0] + p[1] * matrix[1][1] + p[2] * matrix[1][2] + p[3] * matrix[1][3] ); S c = p[0] * matrix[2][0] + p[1] * matrix[2][1] + p[2] * matrix[2][2] + p[3] * matrix[2][3]; S determinant = b * b - S(4.0) * a * c; if( determinant < 0 ) return false; S sqrtDet = sqrt( determinant ); out0 = ( -b - ( a > S(0.0) ? S(1.0) : S(-1.0) ) * sqrtDet ) / ( S(2.0) * a ); out1 = ( -b + ( a > S(0.0) ? S(1.0) : S(-1.0) ) * sqrtDet ) / ( S(2.0) * a ); return true; } template<typename T> bool CubicBasis<T>::operator==( const CubicBasis &rhs ) const { return step==rhs.step && matrix==rhs.matrix; } template<typename T> bool CubicBasis<T>::operator!=( const CubicBasis &rhs ) const { return step!=rhs.step || matrix!=rhs.matrix; } template<typename T> const CubicBasis<T> &CubicBasis<T>::linear() { static CubicBasis<T> m( MatrixType( 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, 0, 0, 0 ), 1 ); return m; } template<typename T> const CubicBasis<T> &CubicBasis<T>::bezier() { static CubicBasis<T> m( MatrixType( -1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0 ), 3 ); return m; } template<typename T> const CubicBasis<T> &CubicBasis<T>::bSpline() { static CubicBasis<T> m( MatrixType( -1/6.0f, 3/6.0f, -3/6.0f, 1/6.0f, 3/6.0f, -6/6.0f, 3/6.0f, 0, -3/6.0f, 0, 3/6.0f, 0, 1/6.0f, 4/6.0f, 1/6.0f, 0 ), 1 ); return m; } template<typename T> const CubicBasis<T> &CubicBasis<T>::catmullRom() { static CubicBasis<T> m( MatrixType( -1/2.0f, 3/2.0f, -3/2.0f, 1/2.0f, 2/2.0f, -5/2.0f, 4/2.0f, -1/2.0f, -1/2.0f, 0, 1/2.0f, 0, 0, 2/2.0f, 0, 0 ), 1 ); return m; } template<typename T> StandardCubicBasis CubicBasis<T>::standardBasis() const { if( *this == CubicBasis<T>::linear() ) { return StandardCubicBasis::Linear; } else if( *this == CubicBasis<T>::bezier() ) { return StandardCubicBasis::Bezier; } else if( *this == CubicBasis<T>::bSpline() ) { return StandardCubicBasis::BSpline; } else if( *this == CubicBasis<T>::catmullRom() ) { return StandardCubicBasis::CatmullRom; } return StandardCubicBasis::Unknown; } } // namespace IECore #endif // IECORE_CUBICBASIS_INL
5,012
1,189
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.exporter.otlp.internal.metrics; import io.opentelemetry.exporter.otlp.internal.MarshalerUtil; import io.opentelemetry.exporter.otlp.internal.MarshalerWithSize; import io.opentelemetry.exporter.otlp.internal.ProtoEnumInfo; import io.opentelemetry.exporter.otlp.internal.Serializer; import io.opentelemetry.proto.metrics.v1.internal.Sum; import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.data.SumData; import java.io.IOException; final class SumMarshaler extends MarshalerWithSize { private final NumberDataPointMarshaler[] dataPoints; private final ProtoEnumInfo aggregationTemporality; private final boolean isMonotonic; static SumMarshaler create(SumData<? extends PointData> sum) { NumberDataPointMarshaler[] dataPointMarshalers = NumberDataPointMarshaler.createRepeated(sum.getPoints()); return new SumMarshaler( dataPointMarshalers, MetricsMarshalerUtil.mapToTemporality(sum.getAggregationTemporality()), sum.isMonotonic()); } private SumMarshaler( NumberDataPointMarshaler[] dataPoints, ProtoEnumInfo aggregationTemporality, boolean isMonotonic) { super(calculateSize(dataPoints, aggregationTemporality, isMonotonic)); this.dataPoints = dataPoints; this.aggregationTemporality = aggregationTemporality; this.isMonotonic = isMonotonic; } @Override public void writeTo(Serializer output) throws IOException { output.serializeRepeatedMessage(Sum.DATA_POINTS, dataPoints); output.serializeEnum(Sum.AGGREGATION_TEMPORALITY, aggregationTemporality); output.serializeBool(Sum.IS_MONOTONIC, isMonotonic); } private static int calculateSize( NumberDataPointMarshaler[] dataPoints, ProtoEnumInfo aggregationTemporality, boolean isMonotonic) { int size = 0; size += MarshalerUtil.sizeRepeatedMessage(Sum.DATA_POINTS, dataPoints); size += MarshalerUtil.sizeEnum(Sum.AGGREGATION_TEMPORALITY, aggregationTemporality); size += MarshalerUtil.sizeBool(Sum.IS_MONOTONIC, isMonotonic); return size; } }
768
376
<filename>Lib/Chip/MKV45F15.hpp #pragma once #include <Chip/CM4/Freescale/MKV45F15/FTFL_FlashConfig.hpp> #include <Chip/CM4/Freescale/MKV45F15/AIPS.hpp> #include <Chip/CM4/Freescale/MKV45F15/DMA.hpp> #include <Chip/CM4/Freescale/MKV45F15/FMC.hpp> #include <Chip/CM4/Freescale/MKV45F15/FTFA.hpp> #include <Chip/CM4/Freescale/MKV45F15/DMAMUX.hpp> #include <Chip/CM4/Freescale/MKV45F15/CAN0.hpp> #include <Chip/CM4/Freescale/MKV45F15/CAN1.hpp> #include <Chip/CM4/Freescale/MKV45F15/FTM0.hpp> #include <Chip/CM4/Freescale/MKV45F15/FTM1.hpp> #include <Chip/CM4/Freescale/MKV45F15/FTM3.hpp> #include <Chip/CM4/Freescale/MKV45F15/SPI.hpp> #include <Chip/CM4/Freescale/MKV45F15/PDB0.hpp> #include <Chip/CM4/Freescale/MKV45F15/PDB1.hpp> #include <Chip/CM4/Freescale/MKV45F15/CRC.hpp> #include <Chip/CM4/Freescale/MKV45F15/PWMA.hpp> #include <Chip/CM4/Freescale/MKV45F15/PIT.hpp> #include <Chip/CM4/Freescale/MKV45F15/LPTMR.hpp> #include <Chip/CM4/Freescale/MKV45F15/SIM.hpp> #include <Chip/CM4/Freescale/MKV45F15/PORTA.hpp> #include <Chip/CM4/Freescale/MKV45F15/PORTB.hpp> #include <Chip/CM4/Freescale/MKV45F15/PORTC.hpp> #include <Chip/CM4/Freescale/MKV45F15/PORTD.hpp> #include <Chip/CM4/Freescale/MKV45F15/PORTE.hpp> #include <Chip/CM4/Freescale/MKV45F15/WDOG.hpp> #include <Chip/CM4/Freescale/MKV45F15/ENC.hpp> #include <Chip/CM4/Freescale/MKV45F15/XBARA.hpp> #include <Chip/CM4/Freescale/MKV45F15/XBARB.hpp> #include <Chip/CM4/Freescale/MKV45F15/AOI.hpp> #include <Chip/CM4/Freescale/MKV45F15/ADC.hpp> #include <Chip/CM4/Freescale/MKV45F15/EWM.hpp> #include <Chip/CM4/Freescale/MKV45F15/MCG.hpp> #include <Chip/CM4/Freescale/MKV45F15/OSC.hpp> #include <Chip/CM4/Freescale/MKV45F15/I2C.hpp> #include <Chip/CM4/Freescale/MKV45F15/UART0.hpp> #include <Chip/CM4/Freescale/MKV45F15/UART1.hpp> #include <Chip/CM4/Freescale/MKV45F15/CMP0.hpp> #include <Chip/CM4/Freescale/MKV45F15/CMP1.hpp> #include <Chip/CM4/Freescale/MKV45F15/CMP2.hpp> #include <Chip/CM4/Freescale/MKV45F15/CMP3.hpp> #include <Chip/CM4/Freescale/MKV45F15/LLWU.hpp> #include <Chip/CM4/Freescale/MKV45F15/PMC.hpp> #include <Chip/CM4/Freescale/MKV45F15/SMC.hpp> #include <Chip/CM4/Freescale/MKV45F15/RCM.hpp> #include <Chip/CM4/Freescale/MKV45F15/GPIOA.hpp> #include <Chip/CM4/Freescale/MKV45F15/GPIOB.hpp> #include <Chip/CM4/Freescale/MKV45F15/GPIOC.hpp> #include <Chip/CM4/Freescale/MKV45F15/GPIOD.hpp> #include <Chip/CM4/Freescale/MKV45F15/GPIOE.hpp> #include <Chip/CM4/Freescale/MKV45F15/SystemControl.hpp> #include <Chip/CM4/Freescale/MKV45F15/SysTick.hpp> #include <Chip/CM4/Freescale/MKV45F15/NVIC.hpp> #include <Chip/CM4/Freescale/MKV45F15/MCM.hpp>
1,374
368
<filename>plugin_vc/game_vc/NodeName.cpp /* Plugin-SDK (Grand Theft Auto Vice City) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "NodeName.h" PLUGIN_SOURCE_FILE PLUGIN_VARIABLE int &gPluginOffset = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0x77F470, 0x77F470, 0x77E470)); int addrof(GetFrameNodeName) = ADDRESS_BY_VERSION(0x580600, 0x580620, 0x580430); int gaddrof(GetFrameNodeName) = GLOBAL_ADDRESS_BY_VERSION(0x580600, 0x580620, 0x580430); char *GetFrameNodeName(RwFrame *frame) { return plugin::CallAndReturnDynGlobal<char *, RwFrame *>(gaddrof(GetFrameNodeName), frame); } int addrof(NodeNamePluginAttach) = ADDRESS_BY_VERSION(0x580620, 0x580640, 0x580450); int gaddrof(NodeNamePluginAttach) = GLOBAL_ADDRESS_BY_VERSION(0x580620, 0x580640, 0x580450); RwBool NodeNamePluginAttach() { return plugin::CallAndReturnDynGlobal<RwBool>(gaddrof(NodeNamePluginAttach)); } int addrof(NodeNameStreamGetSize) = ADDRESS_BY_VERSION(0x580670, 0x580690, 0x5804A0); int gaddrof(NodeNameStreamGetSize) = GLOBAL_ADDRESS_BY_VERSION(0x580670, 0x580690, 0x5804A0); RwInt32 NodeNameStreamGetSize(void const *object, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<RwInt32, void const *, RwInt32, RwInt32>(gaddrof(NodeNameStreamGetSize), object, offsetInObject, sizeInObject); } int addrof(NodeNameStreamRead) = ADDRESS_BY_VERSION(0x5806A0, 0x5806C0, 0x5804D0); int gaddrof(NodeNameStreamRead) = GLOBAL_ADDRESS_BY_VERSION(0x5806A0, 0x5806C0, 0x5804D0); RwStream *NodeNameStreamRead(RwStream *stream, RwInt32 binaryLength, void *object, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<RwStream *, RwStream *, RwInt32, void *, RwInt32, RwInt32>(gaddrof(NodeNameStreamRead), stream, binaryLength, object, offsetInObject, sizeInObject); } int addrof(NodeNameStreamWrite) = ADDRESS_BY_VERSION(0x5806D0, 0x5806F0, 0x580500); int gaddrof(NodeNameStreamWrite) = GLOBAL_ADDRESS_BY_VERSION(0x5806D0, 0x5806F0, 0x580500); RwStream *NodeNameStreamWrite(RwStream *stream, RwInt32 binaryLength, void const *object, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<RwStream *, RwStream *, RwInt32, void const *, RwInt32, RwInt32>(gaddrof(NodeNameStreamWrite), stream, binaryLength, object, offsetInObject, sizeInObject); } int addrof(NodeNameCopy) = ADDRESS_BY_VERSION(0x580700, 0x580720, 0x580530); int gaddrof(NodeNameCopy) = GLOBAL_ADDRESS_BY_VERSION(0x580700, 0x580720, 0x580530); void *NodeNameCopy(void *dstObject, void const *srcObject, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<void *, void *, void const *, RwInt32, RwInt32>(gaddrof(NodeNameCopy), dstObject, srcObject, offsetInObject, sizeInObject); } int addrof(NodeNameDestructor) = ADDRESS_BY_VERSION(0x580730, 0x580750, 0x580560); int gaddrof(NodeNameDestructor) = GLOBAL_ADDRESS_BY_VERSION(0x580730, 0x580750, 0x580560); void *NodeNameDestructor(void *object, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<void *, void *, RwInt32, RwInt32>(gaddrof(NodeNameDestructor), object, offsetInObject, sizeInObject); } int addrof(NodeNameConstructor) = ADDRESS_BY_VERSION(0x580740, 0x580760, 0x580570); int gaddrof(NodeNameConstructor) = GLOBAL_ADDRESS_BY_VERSION(0x580740, 0x580760, 0x580570); void *NodeNameConstructor(void *object, RwInt32 offsetInObject, RwInt32 sizeInObject) { return plugin::CallAndReturnDynGlobal<void *, void *, RwInt32, RwInt32>(gaddrof(NodeNameConstructor), object, offsetInObject, sizeInObject); }
1,454
910
/* * Copyright (c) 2021 VMware, Inc. * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.dbsp.circuits.operators; import org.dbsp.circuits.Circuit; import org.dbsp.circuits.Scheduler; import org.dbsp.circuits.Wire; import org.dbsp.algebraic.dynamicTyping.types.Type; import org.dbsp.lib.Pair; import org.dbsp.lib.Utilities; /** * An operator that contains inside a circuit with a single output. */ public class CircuitOperator extends Operator implements Latch { public final Circuit circuit; /** * If true we usually don't want to see inside the circuit. */ public final boolean basic; public CircuitOperator(Circuit circuit, boolean basic) { super(circuit.getInputTypes(), circuit.getOutputTypes().get(0)); this.basic = basic; this.circuit = circuit; if (this.circuit.getOutputTypes().size() != 1) throw new RuntimeException("Operators must have only 1 output wire, not " + this.circuit.getOutputWires().size() + ": " + circuit); if (circuit.getOutputWires().size() < 1) throw new RuntimeException("Circuit " + this + " does not have an output wire"); this.output = circuit.getOutputWires().get(0); } public CircuitOperator(Circuit circuit) { this(circuit, false); } @Override public Object evaluate(Scheduler scheduler) { for (int i = 0; i < this.inputCount(); i++) { Wire w = this.inputs.get(i); Object ii = w.getValue(scheduler); this.circuit.getInputPort(i).setValue(ii); } this.circuit.step(scheduler); return this.outputWire().getValue(scheduler); } @Override public void reset(Scheduler scheduler) { this.circuit.reset(scheduler); } @Override public void latch(Scheduler scheduler) { this.circuit.latch(scheduler); } @Override public void push(Scheduler scheduler) { this.circuit.push(scheduler); } @Override public void toGraphvizNodes(boolean deep, int indent, StringBuilder builder) { if (deep || !this.basic) this.circuit.toGraphvizNodes(deep, indent, builder); else { Utilities.indent(indent, builder); builder.append(this.graphvizId()) .append(" [label=\"").append(this.circuit.toString()) .append(" (").append(this.id).append(")\"]\n"); } } @SuppressWarnings("ConstantConditions") @Override public void toGraphvizWires(boolean deep, int indent, StringBuilder builder) { if (deep || !this.basic) this.circuit.toGraphvizWires(deep, indent, builder); else { this.outputWire().toGraphviz(this, deep, indent, builder); } } public void setInput(int index, Wire source) { this.circuit.setInput(index, source); } public void checkConnected() { this.circuit.checkConnected(); } protected Pair<Operator, Integer> getActualConsumer(int input) { return new Pair<Operator, Integer>(this.circuit.getInputPort(input), 0); } private static Operator getDelay(Type type, boolean nested) { if (nested) return new OuterDelayOperator(type); else return new DelayOperator(type); } /** * Return an operator that performs integration over a stream of values of type @{type}. * @param type Type of values in the stream. * @param nested If true we want the delay operator to be an OuterDelayOperator. */ public static CircuitOperator integrationOperator(Type type, boolean nested) { Circuit circuit = new Circuit("I", Utilities.list(type), Utilities.list(type)); PlusOperator plus = new PlusOperator(type); circuit.addOperator(plus); Operator delay = getDelay(type, nested); circuit.addOperator(delay); plus.connectTo(delay, 0); delay.connectTo(plus, 1); circuit.addOutputWireFromOperator(plus); Operator input = circuit.getInputPort(0); input.connectTo(plus, 0); return new CircuitOperator(circuit.seal(), true); } public static CircuitOperator integrationOperator(Type type) { return CircuitOperator.integrationOperator(type, false); } /** * Return an operator that performs differentiation over a stream of values of type @{type}. * @param type Type of values in the stream. * @param nested If true we want the delay operator to be an OuterDelayOperator. */ public static CircuitOperator derivativeOperator(Type type, boolean nested) { Circuit circuit = new Circuit("D", Utilities.list(type), Utilities.list(type)); PlusOperator plus = new PlusOperator(type); circuit.addOperator(plus); Operator delay = getDelay(type, nested); circuit.addOperator(delay); NegateOperator neg = new NegateOperator(type); circuit.addOperator(neg); Operator port = circuit.getInputPort(0); port.connectTo(plus, 0); port.connectTo(delay, 0); delay.connectTo(neg, 0); neg.connectTo(plus, 1); circuit.addOutputWireFromOperator(plus); return new CircuitOperator(circuit.seal(), true); } public static CircuitOperator derivativeOperator(Type type) { return CircuitOperator.derivativeOperator(type, false); } @Override public String graphvizId() { return "circuit" + this.id; } @Override public String getName() { return "Op:" + this.circuit.getName(); } @Override public String toString() { return super.toString() + "{" + this.circuit.toString() + "}"; } /** * Creates a bracketed operator by putting a delta in front and an int at the back of this operator. * The operator must be unary. */ public CircuitOperator bracket() { if (this.inputCount() != 1) throw new RuntimeException("Only unary operators can be bracketed"); Circuit circuit = new Circuit("[" + this + "]", Utilities.list(this.getInputType(0)), Utilities.list(this.getOutputType())); DeltaOperator delta = new DeltaOperator(this.getInputType(0)); circuit.addOperator(delta); circuit.getInputPort(0).connectTo(delta, 0); circuit.addOperator(this); delta.connectTo(this, 0); Operator intOp = circuit.addOperator(new IntOperator(this.getOutputType(), delta, this)); this.connectTo(intOp, 0); circuit.addOutputWireFromOperator(intOp); return new CircuitOperator(circuit.seal()); } }
2,905
400
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt #pragma once #include "GMesh.h" #include "Set.h" #include "Queue.h" #include "MeshOp.h" // triangulate_face() #include "Stat.h" #include "PArray.h" #include "SGrid.h" #if 0 { auto func_eval = [](const Vec3<float>& p) { return p[0]<.3f ? k_Contour_undefined : dist(p, Point(.6f, .6f, .6f))-.4f; }; if (1) { GMesh mesh; { Contour3DMesh<decltype(func_eval)> contour(50, &mesh, func_eval); contour.march_near(Point(.9f, .6f, .6f)); } mesh.write(std::cout); } else { struct func_contour { void operator()(const Array<Vec3<float>>&) { ... }; }; auto func_border = [](const Array<Vec3<float>>&) { ... }; Contour3D<decltype(func_eval), func_contour, decltype(func_border)> contour(50, func_eval, func_contour(), func_border); contour.march_from(Point(.9f, .6f, .6f)); } } #endif namespace hh { // Contour2D/Contour3DMesh/Contour3D compute a piecewise linear approximation to the zeroset of a scalar function: // - surface triangle mesh in the unit cube (Contour3DMesh) // - surface triangle stream in the unit cube (Contour3D) // - curve polyline stream in the unit square (Contour2D) // TODO: improving efficiency/generality: // - use 64-bit encoding to allow larger grid sizes. // - perhaps distinguish Set<unsigned> cubes_visited and Map<unsigned,Node> cube_vertices? and edge_vertices too? // - somehow remove _en from Node? // - somehow remove mapsucc // - Contour2D: directly extract joined polylines; no need to check degen constexpr float k_Contour_undefined = 1e31f; // represents undefined distance, to introduce surface boundaries // Protected content in this class just factors functions common to Contour2D, Contour3DMesh, and Contour3D. template<int D, typename VertexData = Vec0<int>> class ContourBase { public: void set_ostream(std::ostream* os) { _os = os; } // for summary text output; may be set to nullptr void set_vertex_tolerance(float tol) { // if nonzero, do binary search; tol is absolute distance in domain _vertex_tol = tol; _vertex_tol = getenv_float("CONTOUR_VERTEX_TOL", _vertex_tol, true); // override } protected: static constexpr float k_not_yet_evaled = BIGFLOAT; using DPoint = Vec<float,D>; // domain point using IPoint = Vec<int,D>; // grid point static_assert(D==2 || D==3, ""); static constexpr int k_max_gn = D==3 ? 1024 : 65536; // bits/coordinate==10 for 3D, 16 for 2D (max 32 bits total) ContourBase(int gn) : _gn(gn), _gni(1.f/gn) { assertx(_gn>0); assertx(_gn<k_max_gn); // must leave room for [0.._gn] inclusive set_vertex_tolerance(_vertex_tol); } ~ContourBase() { assertx(_queue.empty()); if (_os) { *_os << sform("%sMarch:\n", g_comment_prefix_string); *_os << sform("%svisited %d cubes (%d were undefined, %d contained nothing)\n", g_comment_prefix_string, _ncvisited, _ncundef, _ncnothing); *_os << sform("%sevaluated %d vertices (%d were zero, %d were undefined)\n", g_comment_prefix_string, _nvevaled, _nvzero, _nvundef); *_os << sform("%sencountered %d tough edges\n", g_comment_prefix_string, _nedegen); } } int _gn; float _gni; // 1.f/_gn std::ostream* _os {&std::cerr}; float _vertex_tol {0.f}; // note: 0.f is special: infinite tolerance // Model: the domain [0.f, 1.f]^D is partitioned into _gn^D cubes. // These cubes are indexed by nodes with indices [0, _gn-1]. // The cube vertices are indexed by nodes with indices [0, _gn]. See get_point(). // So there are no "+.5f" roundings anywhere in the code. struct Node : VertexData { explicit Node(unsigned pen) : _en(pen) { } enum class ECubestate { nothing, queued, visited }; unsigned _en; // encoded vertex index ECubestate _cubestate {ECubestate::nothing}; // cube info float _val {k_not_yet_evaled}; // vertex value DPoint _p; // vertex point position in grid // Note that for 3D, base class contains Vec3<Vertex> _verts. }; struct hash_Node { size_t operator()(const Node& n) const { return n._en; } }; struct equal_Node { bool operator()(const Node& n1, const Node& n2) const { return n1._en==n2._en; } }; Set<Node, hash_Node, equal_Node> _m; // (std::unordered_set<> : References and pointers to key stored in the container are only // invalidated by erasing that element. So it's OK to keep pointers to Node* even as more are added.) Queue<unsigned> _queue; // cubes queued to be visited int _ncvisited {0}; int _ncundef {0}; int _ncnothing {0}; int _nvevaled {0}; int _nvzero {0}; int _nvundef {0}; int _nedegen {0}; Array<DPoint> _tmp_poly; // bool cube_inbounds(const IPoint& ci) const { return in_bounds(ci, ntimes<D>(_gn)); } DPoint get_point(const IPoint& ci) const { // Note: less strict than cube_inbounds() because ci[c]==_gn is OK for a vertex. // DPoint dp; for_int(c, D) { ASSERTX(ci[c]>=0 && ci[c]<=_gn); dp[c] = min(ci[c]*_gni, 1.f); } DPoint dp; for_int(c, D) { ASSERTX(ci[c]>=0 && ci[c]<=_gn); dp[c] = ci[c]<_gn ? ci[c]*_gni : 1.f; } return dp; } template<bool avoid_degen, typename Eval = float(const DPoint&)> DPoint compute_point(const DPoint& pp, const DPoint& pn, float vp, float vn, Eval& eval) { DPoint pm; float fm; if (!_vertex_tol) { fm = vp/(vp-vn); pm = interp(pn, pp, fm); } else { float v0 = vp, v1 = vn; DPoint p0 = pp, p1 = pn; float f0 = 0.f, f1 = 1.f; int neval = 0; for (;;) { ASSERTX(v0>=0.f && v1<0.f && f0<f1); float b1 = v0/(v0-v1); b1 = clamp(b1, .05f, .95f); // guarantee quick convergence fm = f0*(1.f-b1)+f1*b1; pm = interp(p1, p0, b1); float vm = eval(pm); neval++; if (neval>20) break; if (vm<0.f) { f1 = fm; p1 = pm; v1 = vm; } else { f0 = fm; p0 = pm; v0 = vm; } if (dist2(p0, p1)<=square(_vertex_tol)) break; } HH_SSTAT(SContneval, neval); } if (avoid_degen) { // const float fs = _gn>500 ? .05f : _gn >100 ? .01f : .001f; const float fs = 2e-5f*_gn; // sufficient precision for HashFloat with default nignorebits==8 if (fm<fs) { _nedegen++; pm = interp(pn, pp, fs); } else if (fm>1.f-fs) { _nedegen++; pm = interp(pp, pn, fs); } } return pm; } }; // *** Contour3D struct Contour3D_NoBorder { // special type to indicate that no border ouput is desired float operator()(const Array<Vec3<float>>&) const { assertnever_ret(""); return 0.f; } }; struct VertexData3DMesh { Vec3<Vertex> _verts {ntimes<3>(Vertex(nullptr))}; }; template<typename VertexData = Vec0<int>, typename Derived = void, // for contour_cube() typename Eval = float(const Vec3<float>&), typename Border = Contour3D_NoBorder> class Contour3DBase : public ContourBase<3, VertexData> { protected: static constexpr int D = 3; using base = ContourBase<D, VertexData>; using typename base::DPoint; using typename base::IPoint; using typename base::Node; using base::get_point; using base::cube_inbounds; using base::_gn; using base::k_max_gn; using base::_queue; using base::_m; using base::_tmp_poly; using base::_ncvisited; using base::_ncundef; using base::_ncnothing; using base::_nvevaled; using base::_nvzero; using base::_nvundef; Derived& derived() { return *static_cast<Derived*>(this); } const Derived& derived() const { return *static_cast<const Derived*>(this); } public: Contour3DBase(int gn, Eval eval, Border border) : base(gn), _eval(eval), _border(border) { } ~Contour3DBase() { } // ret number of new cubes visited: 0=revisit_cube, 1=no_surf, >1=new int march_from(const DPoint& startp) { return march_from_i(startp); } // call march_from() on all cells near startp; ret num new cubes visited int march_near(const DPoint& startp) { return march_near_i(startp); } protected: Eval _eval; Border _border; static constexpr bool b_no_border = std::is_same<Border, Contour3D_NoBorder>::value; using Node222 = SGrid<Node*, 2, 2, 2>; using base::k_not_yet_evaled; // unsigned encode(const IPoint& ci) const { static_assert(k_max_gn<=1024, ""); return (((unsigned(ci[0])<<10) | unsigned(ci[1]))<<10) | unsigned(ci[2]); } IPoint decode(unsigned en) const { static_assert(k_max_gn<=1024, ""); return IPoint(int(en>>20), int((en>>10)&((1u<<10)-1)), int(en&((1u<<10)-1))); } void check_ok() { /* assertx(!(_pmesh && _contour)); */ } int march_from_i(const DPoint& startp) { check_ok(); for_int(d, D) ASSERTX(startp[d]>=0.f && startp[d]<=1.f); IPoint cc; for_int(d, D) { cc[d] = min(int(startp[d]*_gn), _gn-1); } return march_from_aux(cc); } int march_near_i(const DPoint& startp) { check_ok(); for_int(d, D) ASSERTX(startp[d]>=0.f && startp[d]<=1.f); IPoint cc; for_int(d, D) { cc[d] = min(int(startp[d]*_gn), _gn-1); } int ret = 0; IPoint ci; for_intL(i, -1, 2) { ci[0] = cc[0]+i; if (ci[0]<0 || ci[0]>=_gn) continue; for_intL(j, -1, 2) { ci[1] = cc[1]+j; if (ci[1]<0 || ci[1]>=_gn) continue; for_intL(k, -1, 2) { ci[2] = cc[2]+k; if (ci[2]<0 || ci[2]>=_gn) continue; ret += march_from_aux(ci); } } } return ret; } int march_from_aux(const IPoint& cc) { int oncvisited = _ncvisited; { unsigned en = encode(cc); bool is_new; Node* n = const_cast<Node*>(&_m.enter(Node(en), is_new)); // un-const OK if not modify n->_en // "base::" required when accessing ECubestate for mingw32 gcc 4.8.1 if (n->_cubestate==base::Node::ECubestate::visited) return 0; ASSERTX(n->_cubestate==base::Node::ECubestate::nothing); _queue.enqueue(en); n->_cubestate = base::Node::ECubestate::queued; } while (!_queue.empty()) { unsigned en = _queue.dequeue(); consider_cube(en); } int cncvisited = _ncvisited-oncvisited; if (cncvisited==1) _ncnothing++; return cncvisited; } void consider_cube(unsigned encube) { _ncvisited++; IPoint cc = decode(encube); Node222 na; bool cundef = false; for_int(i, 2) for_int(j, 2) for_int(k, 2) { IPoint cd(i, j, k); IPoint ci = cc+cd; unsigned en = encode(ci); bool is_new; Node* n = const_cast<Node*>(&_m.enter(Node(en), is_new)); na[i][j][k] = n; if (n->_val==k_not_yet_evaled) { n->_p = get_point(ci); n->_val = _eval(n->_p); _nvevaled++; if (!n->_val) _nvzero++; if (n->_val==k_Contour_undefined) _nvundef++; } if (n->_val==k_Contour_undefined) cundef = true; } Node* n = na[0][0][0]; ASSERTX(n->_cubestate==base::Node::ECubestate::queued); n->_cubestate = base::Node::ECubestate::visited; if (cundef) { _ncundef++; } else { derived().contour_cube(cc, na); } for_int(d, D) for_int(i, 2) { // push neighbors int d1 = (d+1)%D, d2 = (d+2)%D; IPoint cd; cd[d] = i; float vmin = BIGFLOAT, vmax = -BIGFLOAT; for (cd[d1] = 0; cd[d1]<2; cd[d1]++) { for (cd[d2] = 0; cd[d2]<2; cd[d2]++) { float v = na[cd[0]][cd[1]][cd[2]]->_val; ASSERTX(v!=k_not_yet_evaled); if (v<vmin) vmin = v; if (v>vmax) vmax = v; } } cd[d] = i ? 1 : -1; cd[d1] = cd[d2] = 0; IPoint ci = cc+cd; // indices of node for neighboring cube; // note: vmin<0 since 0 is arbitrarily taken to be positive if (vmax!=k_Contour_undefined && vmin<0 && vmax>=0 && cube_inbounds(ci)) { unsigned en = encode(ci); bool is_new; Node* n2 = const_cast<Node*>(&_m.enter(Node(en), is_new)); if (n2->_cubestate==base::Node::ECubestate::nothing) { n2->_cubestate = base::Node::ECubestate::queued; _queue.enqueue(en); } } else if (!b_no_border) { // output boundary cd[d] = i; auto& poly = _tmp_poly; poly.init(0); for (cd[d1] = 0; cd[d1]<2; cd[d1]++) { int sw = cd[d]^cd[d1]; // 0 or 1 for (cd[d2] = sw; cd[d2]==0||cd[d2]==1; cd[d2] += (sw ? -1 : 1)) poly.push(get_point(cc+cd)); } _border(poly); } } } }; template<typename Eval = float(const Vec3<float>&), typename Border = Contour3D_NoBorder> class Contour3DMesh : public Contour3DBase<VertexData3DMesh, Contour3DMesh<Eval, Border>, Eval, Border> { using base = Contour3DBase<VertexData3DMesh, Contour3DMesh<Eval, Border>, Eval, Border>; public: Contour3DMesh(int gn, GMesh* pmesh, Eval eval = Eval(), Border border = Border()) : base(gn, eval, border), _pmesh(pmesh) { assertx(_pmesh); } void big_mesh_faces() { _big_mesh_faces = true; } private: // Need to friend base class for callback access to contour_cube(). friend base; using typename base::IPoint; using typename base::Node222; using typename base::Node; using base::D; using base::compute_point; using base::_eval; using base::decode; GMesh* _pmesh; bool _big_mesh_faces {false}; static int mod4(int j) { ASSERTX(j>=0); return j&0x3; } void contour_cube(const IPoint& cc, const Node222& na) { // Based on Wyvill et al. dummy_use(cc); Map<Vertex,Vertex> mapsucc; for_int(d, D) for_int(v, 2) { // examine each of 6 cube faces Vec4<Node*> naf; { int d1 = (d+1)%D, d2 = (d+2)%D; IPoint cd; cd[d] = v; int i = 0; // Gather 4 cube vertices in a consistent order for (cd[d1] = 0; cd[d1]<2; cd[d1]++) { int sw = cd[d]^cd[d1]; // 0 or 1 for (cd[d2] = sw; cd[d2]==0||cd[d2]==1; cd[d2] += (sw ? -1 : 1)) { naf[i++] = na[cd[0]][cd[1]][cd[2]]; } } } int nneg = 0; double sumval = 0.; for_int(i, 4) { float val = naf[i]->_val; if (val<0) nneg++; sumval += val; // If pedantic, could sort the vals before summing. } for_int(i, 4) { int i1 = mod4(i+1), i2 = mod4(i+2), i3 = mod4(i+3); if (!(naf[i]->_val<0 && naf[i1]->_val>=0)) continue; // have start of edge ASSERTX(nneg>=1 && nneg<=3); int ie; // end of edge if (nneg==1) { ie = i3; } else if (nneg==3) { ie = i1; } else if (naf[i2]->_val>=0) { ie = i2; } else if (sumval<0) { ie = i1; } else { ie = i3; } Vertex v1 = get_vertex_onedge(naf[i1], naf[i]); Vertex v2 = get_vertex_onedge(naf[ie], naf[mod4(ie+1)]); mapsucc.enter(v2, v1); // to get face order correct } } Vec<Vertex,12> va; while (!mapsucc.empty()) { Vertex vf = nullptr; int minvi = INT_MAX; // find min to be portable for (Vertex v : mapsucc.keys()) { int vi = _pmesh->vertex_id(v); if (vi<minvi) { minvi = vi; vf = v; } } int nv = 0; for (Vertex v = vf; ; ) { va[nv++] = v; v = assertx(mapsucc.remove(v)); if (v==vf) break; } Face f = _pmesh->create_face(CArrayView<Vertex>(va.data(), nv)); if (nv>3 && !_big_mesh_faces) { // If 6 or more edges, may have 2 edges on same cube face, then must introduce new vertex to be safe. if (nv>=6) _pmesh->center_split_face(f); else assertx(triangulate_face(*_pmesh, f)); } } } Vertex get_vertex_onedge(Node* n1, Node* n2) { bool is_new; Vertex* pv; { IPoint cc1 = decode(n1->_en); IPoint cc2 = decode(n2->_en); int d = -1; for_int(c, D) { if (cc1[c]!=cc2[c]) { ASSERTX(d<0); d = c; } } ASSERTX(d>=0); ASSERTX(abs(cc1[d]-cc2[d])==1); Node* n = (cc1[d]<cc2[d]) ? n1 : n2; pv = &n->_verts[d]; is_new = !*pv; } Vertex& v = *pv; if (is_new) { v = _pmesh->create_vertex(); _pmesh->set_point(v, this->template compute_point<false>(n1->_p, n2->_p, n1->_val, n2->_val, _eval)); } return v; } }; template<typename Eval = float(const Vec3<float>&), typename Contour = float(const Array<Vec3<float>>&), typename Border = Contour3D_NoBorder> class Contour3D : public Contour3DBase<Vec0<int>, Contour3D<Eval, Contour, Border>, Eval, Border> { using base = Contour3DBase<Vec0<int>, Contour3D<Eval, Contour, Border>, Eval, Border>; public: Contour3D(int gn, Contour contour = Contour(), Eval eval = Eval(), Border border = Border()) : base(gn, eval, border), _contour(contour) { } private: // Need to friend base class for callback access to contour_cube(). // friend base; // somehow insufficient on mingw and clang (whereas somehow sufficient in Contour3DMesh) template<typename, typename, typename, typename> friend class Contour3DBase; Contour _contour; using typename base::DPoint; using typename base::IPoint; using typename base::Node222; using typename base::Node; using base::_tmp_poly; using base::_eval; using base::compute_point; void contour_cube(const IPoint& cc, const Node222& na) { dummy_use(cc); // do Kuhn 6-to-1 triangulation of cube contour_tetrahedron(V(na[0][0][0], na[0][0][1], na[1][0][1], na[0][1][0])); contour_tetrahedron(V(na[0][0][0], na[1][0][1], na[1][0][0], na[0][1][0])); contour_tetrahedron(V(na[1][0][1], na[1][1][0], na[1][0][0], na[0][1][0])); contour_tetrahedron(V(na[0][1][0], na[0][1][1], na[0][0][1], na[1][0][1])); contour_tetrahedron(V(na[1][1][1], na[0][1][1], na[0][1][0], na[1][0][1])); contour_tetrahedron(V(na[1][1][1], na[0][1][0], na[1][1][0], na[1][0][1])); } void contour_tetrahedron(Vec4<Node*> n4) { int nposi = 0; for_int(i, 4) { if (n4[i]->_val>=0) nposi++; } if (nposi==0 || nposi==4) return; for (int i = 0, j = 3; i<j; ) { if (n4[i]->_val>=0) { i++; continue; } if (n4[j]->_val<0) { --j; continue; } std::swap(n4[i], n4[j]); i++; --j; } switch (nposi) { bcase 1: output_triangle(V(V(n4[0], n4[1]), V(n4[0], n4[2]), V(n4[0], n4[3]))); bcase 2: output_triangle(V(V(n4[0], n4[2]), V(n4[0], n4[3]), V(n4[1], n4[3]))); output_triangle(V(V(n4[0], n4[2]), V(n4[1], n4[3]), V(n4[1], n4[2]))); bcase 3: output_triangle(V(V(n4[0], n4[3]), V(n4[1], n4[3]), V(n4[2], n4[3]))); bdefault: assertnever(""); } } void output_triangle(const SGrid<Node*, 3, 2>& n3) { auto& poly = _tmp_poly; poly.init(3); for_int(i, 3) { Node* np = n3[i][0]; Node* nn = n3[i][1]; poly[i] = this->template compute_point<true>(np->_p, nn->_p, np->_val, nn->_val, _eval); } Vector normal = cross(poly[0], poly[1], poly[2]); // swap might be unnecessary if we carefully swapped above? if (dot(normal, n3[0][0]->_p-n3[0][1]->_p)<0.f) std::swap(poly[0], poly[1]); _contour(poly); } }; // *** Contour2D struct Contour2D_NoBorder { // special type to indicate that no border ouput is desired float operator()(const Array<Vec2<float>>&) const { if (1) assertnever(""); return 0.f; } }; template<typename Eval = float(const Vec2<float>&), typename Contour = void(const Array<Vec2<float>>&), typename Border = Contour2D_NoBorder> class Contour2D : public ContourBase<2> { static constexpr int D = 2; using base = ContourBase<D>; public: Contour2D(int gn, Eval eval = Eval(), Contour contour = Contour(), Border border = Border()) : base(gn), _eval(eval), _contour(contour), _border(border) { } ~Contour2D() { } // ret number of new cubes visited: 0=revisit_cube, 1=no_surf, >1=new int march_from(const DPoint& startp) { return march_from_i(startp); } // call march_from() on all cells near startp; ret num new cubes visited int march_near(const DPoint& startp) { return march_near_i(startp); } private: Eval _eval; Contour _contour; Border _border; static constexpr bool b_no_border = std::is_same<Border, Contour2D_NoBorder>::value; using Node22 = SGrid<Node*, 2, 2>; using base::k_not_yet_evaled; // unsigned encode(const IPoint& ci) const { static_assert(k_max_gn<=65536, ""); return (unsigned(ci[0])<<16) | unsigned(ci[1]); } IPoint decode(unsigned en) const { static_assert(k_max_gn<=65536, ""); return IPoint(int(en>>16), int(en&((1u<<16)-1))); } void check_ok() { } int march_from_i(const DPoint& startp) { check_ok(); for_int(d, D) ASSERTX(startp[d]>=0.f && startp[d]<=1.f); IPoint cc; for_int(d, D) { cc[d] = min(int(startp[d]*_gn), _gn-1); } return march_from_aux(cc); } int march_near_i(const DPoint& startp) { check_ok(); for_int(d, D) ASSERTX(startp[d]>=0.f && startp[d]<=1.f); IPoint cc; for_int(d, D) { cc[d] = min(int(startp[d]*_gn), _gn-1); } int ret = 0; IPoint ci; for_intL(i, -1, 2) { ci[0] = cc[0]+i; if (ci[0]<0 || ci[0]>=_gn) continue; for_intL(j, -1, 2) { ci[1] = cc[1]+j; if (ci[1]<0 || ci[1]>=_gn) continue; ret += march_from_aux(ci); } } return ret; } int march_from_aux(const IPoint& cc) { int oncvisited = _ncvisited; { unsigned en = encode(cc); bool is_new; Node* n = const_cast<Node*>(&_m.enter(Node(en), is_new)); if (n->_cubestate==Node::ECubestate::visited) return 0; ASSERTX(n->_cubestate==Node::ECubestate::nothing); _queue.enqueue(en); n->_cubestate = Node::ECubestate::queued; } while (!_queue.empty()) { unsigned en = _queue.dequeue(); consider_square(en); } int cncvisited = _ncvisited-oncvisited; if (cncvisited==1) _ncnothing++; return cncvisited; } void consider_square(unsigned encube) { _ncvisited++; IPoint cc = decode(encube); Node22 na; { bool cundef = false; IPoint cd; for (cd[0] = 0; cd[0]<2; cd[0]++) { for (cd[1] = 0; cd[1]<2; cd[1]++) { IPoint ci = cc+cd; unsigned en = encode(ci); bool is_new; Node* n = const_cast<Node*>(&_m.enter(Node(en), is_new)); na[cd[0]][cd[1]] = n; if (n->_val==k_not_yet_evaled) { n->_p = get_point(ci); n->_val = _eval(n->_p); _nvevaled++; if (!n->_val) _nvzero++; if (n->_val==k_Contour_undefined) _nvundef++; } if (n->_val==k_Contour_undefined) cundef = true; } } Node* n = na[0][0]; ASSERTX(n->_cubestate==Node::ECubestate::queued); n->_cubestate = Node::ECubestate::visited; if (cundef) { _ncundef++; } else { contour_square(na); } } for_int(d, D) for_int(i, 2) { // push neighbors int d1 = (d+1)%D; IPoint cd; cd[d] = i; float vmin = BIGFLOAT, vmax = -BIGFLOAT; for (cd[d1] = 0; cd[d1]<2; cd[d1]++) { float v = na[cd[0]][cd[1]]->_val; ASSERTX(v!=k_not_yet_evaled); if (v<vmin) vmin = v; if (v>vmax) vmax = v; } cd[d] = i ? 1 : -1; cd[d1] = 0; IPoint ci = cc+cd; // indices of node for neighboring cube; // note: vmin<0 since 0 is arbitrarily taken to be positive if (vmax!=k_Contour_undefined && vmin<0 && vmax>=0 && cube_inbounds(ci)) { unsigned en = encode(ci); bool is_new; Node* n = const_cast<Node*>(&_m.enter(Node(en), is_new)); if (n->_cubestate==Node::ECubestate::nothing) { n->_cubestate = Node::ECubestate::queued; _queue.enqueue(en); } } else if (!b_no_border) { // output boundary cd[d] = i; auto& poly = _tmp_poly; poly.init(0); for (cd[d1] = 0; cd[d1]<2; cd[d1]++) poly.push(get_point(cc+cd)); _border(poly); } } } void contour_square(const Node22& na) { contour_triangle(V(na[0][0], na[1][1], na[0][1])); contour_triangle(V(na[0][0], na[1][0], na[1][1])); } void contour_triangle(Vec3<Node*> n3) { int nposi = 0; for_int(i, 3) { if (n3[i]->_val>=0) nposi++; } if (nposi==0 || nposi==3) return; for (int i = 0, j = 2; i<j; ) { if (n3[i]->_val>=0) { i++; continue; } if (n3[j]->_val<0) { --j; continue; } std::swap(n3[i], n3[j]); i++; --j; } switch (nposi) { bcase 1: output_line(V(V(n3[0], n3[1]), V(n3[0], n3[2]))); bcase 2: output_line(V(V(n3[0], n3[2]), V(n3[1], n3[2]))); bdefault: assertnever(""); } } void output_line(const Node22& n2) { auto& poly = _tmp_poly; poly.init(2); for_int(i, 2) { Node* np = n2[i][0]; Node* nn = n2[i][1]; poly[i] = compute_point<true>(np->_p, nn->_p, np->_val, nn->_val, _eval); } Vec2<float> v = poly[1]-poly[0]; Vec2<float> normal(-v[1], v[0]); // 90 degree rotation if (dot(normal, n2[0][0]->_p-n2[0][1]->_p)<0.) std::swap(poly[0], poly[1]); _contour(poly); } }; } // namespace hh
15,020
1,837
<filename>zebra-client/src/main/java/com/dianping/zebra/shard/jdbc/ShardConnection.java /* * Copyright (c) 2011-2018, <NAME>. All Rights Reserved. * * 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.dianping.zebra.shard.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.dianping.zebra.filter.JdbcFilter; import com.dianping.zebra.shard.jdbc.unsupport.UnsupportedShardConnection; import com.dianping.zebra.shard.router.ShardRouter; import com.dianping.zebra.util.JDBCUtils; /** * @author <NAME> * @author hao.zhu * */ public class ShardConnection extends UnsupportedShardConnection implements Connection { private ShardRouter router; private DataSourceRepository dataSourceRepository; private Map<String, Connection> actualConnections = new HashMap<String, Connection>(); private Set<Statement> attachedStatements = new HashSet<Statement>(); private Map<String, List<Connection>> concurrentConnections = new HashMap<String, List<Connection>>(); private Map<String, Integer> concurrentConnectionIndexes = new HashMap<String, Integer>(); private boolean closed = false; private boolean readOnly; private boolean autoCommit = true; private int transactionIsolation = -1; private final List<JdbcFilter> filters; private int concurrencyLevel = 1; // 单库并发度 public ShardConnection(List<JdbcFilter> filters) { this.filters = filters; } public ShardConnection(String username, String password, List<JdbcFilter> filters) { this.filters = filters; } public ShardConnection(String username, String password, List<JdbcFilter> filters, int concurrencyLevel) { this.filters = filters; this.concurrencyLevel = concurrencyLevel; } private void checkClosed() throws SQLException { if (closed) { throw new SQLException("No operations allowed after connection closed."); } } @Override public void close() throws SQLException { if (closed) { return; } List<SQLException> innerExceptions = new ArrayList<SQLException>(); try { for (Statement stmt : attachedStatements) { try { stmt.close(); } catch (SQLException e) { innerExceptions.add(e); } } for (Map.Entry<String, Connection> entry : actualConnections.entrySet()) { try { entry.getValue().close(); } catch (SQLException e) { innerExceptions.add(e); } } // table concurrent connection for (List<Connection> connections : concurrentConnections.values()) { if (connections != null) { for (Connection connection : connections) { try { connection.close(); } catch (SQLException e) { innerExceptions.add(e); } } } } } finally { closed = true; attachedStatements.clear(); actualConnections.clear(); concurrentConnections.clear(); } JDBCUtils.throwSQLExceptionIfNeeded(innerExceptions); } @Override public void commit() throws SQLException { checkClosed(); if (autoCommit) { return; } List<SQLException> innerExceptions = new ArrayList<SQLException>(); for (Map.Entry<String, Connection> entry : actualConnections.entrySet()) { try { entry.getValue().commit(); } catch (SQLException e) { innerExceptions.add(e); } } // table concurrent connection for (List<Connection> connections : concurrentConnections.values()) { if (connections != null) { for (Connection connection : connections) { try { connection.commit(); } catch (SQLException e) { innerExceptions.add(e); } } } } JDBCUtils.throwSQLExceptionIfNeeded(innerExceptions); } @Override public Statement createStatement() throws SQLException { checkClosed(); ShardStatement stmt = new ShardStatement(filters); stmt.setRouter(router); stmt.setAutoCommit(autoCommit); stmt.setReadOnly(readOnly); stmt.setConnection(this); stmt.setConcurrencyLevel(concurrencyLevel); attachedStatements.add(stmt); return stmt; } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { ShardStatement stmt = (ShardStatement) createStatement(); stmt.setResultSetType(resultSetType); stmt.setResultSetConcurrency(resultSetConcurrency); return stmt; } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { ShardStatement stmt = (ShardStatement) createStatement(resultSetType, resultSetConcurrency); stmt.setResultSetHoldability(resultSetHoldability); return stmt; } Connection getRealConnection(String jdbcRef, boolean autoCommit) throws SQLException { Connection conn = actualConnections.get(jdbcRef); if (conn == null) { conn = dataSourceRepository.getDataSource(jdbcRef).getConnection(); conn.setAutoCommit(autoCommit); if (transactionIsolation > 0) { conn.setTransactionIsolation(transactionIsolation); } actualConnections.put(jdbcRef, conn); } return conn; } // Each call returns a new connection Connection getRealConcurrentConnection(String jdbcRef, boolean autoCommit) throws SQLException { List<Connection> connections = concurrentConnections.get(jdbcRef); Integer index = concurrentConnectionIndexes.get(jdbcRef); if (connections == null) { connections = new ArrayList<Connection>(); concurrentConnections.put(jdbcRef, connections); } if (index == null) { index = 0; } Connection conn = null; if (index < connections.size()) { conn = connections.get(index); } else { conn = dataSourceRepository.getDataSource(jdbcRef).getConnection(); conn.setAutoCommit(autoCommit); connections.add(conn); } concurrentConnectionIndexes.put(jdbcRef, index + 1); return conn; } public Set<Statement> getAttachedStatements() { return attachedStatements; } @Override public boolean getAutoCommit() throws SQLException { return autoCommit; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new ShardDatabaseMetaData(); } public ShardRouter getRouter() { return router; } @Override public int getTransactionIsolation() throws SQLException { return transactionIsolation; } @Override public boolean isClosed() throws SQLException { return closed; } @Override public boolean isReadOnly() throws SQLException { return readOnly; } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { checkClosed(); ShardPreparedStatement stmt = new ShardPreparedStatement(filters); stmt.setRouter(router); stmt.setAutoCommit(autoCommit); stmt.setReadOnly(readOnly); stmt.setConnection(this); stmt.setSql(sql); stmt.setConcurrencyLevel(concurrencyLevel); attachedStatements.add(stmt); return stmt; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { ShardPreparedStatement stmt = (ShardPreparedStatement) prepareStatement(sql); stmt.setAutoGeneratedKeys(autoGeneratedKeys); return stmt; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { ShardPreparedStatement stmt = (ShardPreparedStatement) prepareStatement(sql); stmt.setResultSetType(resultSetType); stmt.setResultSetConcurrency(resultSetConcurrency); return stmt; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { ShardPreparedStatement stmt = (ShardPreparedStatement) prepareStatement(sql, resultSetType, resultSetConcurrency); stmt.setResultSetHoldability(resultSetHoldability); return stmt; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { ShardPreparedStatement stmt = (ShardPreparedStatement) prepareStatement(sql); stmt.setColumnIndexes(columnIndexes); return stmt; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { ShardPreparedStatement stmt = (ShardPreparedStatement) prepareStatement(sql); stmt.setColumnNames(columnNames); return stmt; } @Override public void rollback() throws SQLException { checkClosed(); if (autoCommit) { return; } List<SQLException> exceptions = new ArrayList<SQLException>(); for (Map.Entry<String, Connection> entry : actualConnections.entrySet()) { try { entry.getValue().rollback(); } catch (SQLException e) { exceptions.add(e); } } // table concurrent connection for (List<Connection> connections : concurrentConnections.values()) { if (connections != null) { for (Connection connection : connections) { try { connection.rollback(); } catch (SQLException e) { exceptions.add(e); } } } } JDBCUtils.throwSQLExceptionIfNeeded(exceptions); } public void setActualConnections(Map<String, Connection> actualConnections) { this.actualConnections = actualConnections; } public void setAttachedStatements(Set<Statement> attachedStatements) { this.attachedStatements = attachedStatements; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); this.autoCommit = autoCommit; } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); this.readOnly = readOnly; } public void setRouter(ShardRouter router) { this.router = router; } public void setDataSourceRepository(DataSourceRepository dataSourceRepository) { this.dataSourceRepository = dataSourceRepository; } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); this.transactionIsolation = level; } public void resetConcurrentConnectionIndexes() { this.concurrentConnectionIndexes.clear(); } }
4,150
45,293
public final class Prop /* Prop*/ { @org.jetbrains.annotations.NotNull() private final java.lang.Object someProp; public Prop();// .ctor() } final class null /* null*/ { private ();// .ctor() } final class C /* C*/ { @org.jetbrains.annotations.NotNull() private final kotlin.jvm.functions.Function0<java.lang.Object> initChild; private final int y; @org.jetbrains.annotations.NotNull() public final kotlin.jvm.functions.Function0<java.lang.Object> getInitChild();// getInitChild() public C(int);// .ctor(int) public final int getY();// getY() } final class null /* null*/ { @org.jetbrains.annotations.NotNull() public java.lang.String toString();// toString() private ();// .ctor() } public final class ValidPublicSupertype /* ValidPublicSupertype*/ { @org.jetbrains.annotations.NotNull() private final java.lang.Runnable x; @org.jetbrains.annotations.NotNull() public final java.lang.Runnable bar();// bar() @org.jetbrains.annotations.NotNull() public final java.lang.Runnable getX();// getX() public ValidPublicSupertype();// .ctor() } final class null /* null*/ implements java.lang.Runnable { private ();// .ctor() public void run();// run() } final class null /* null*/ implements java.lang.Runnable { private ();// .ctor() public void run();// run() } public abstract interface I /* I*/ { } public final class InvalidPublicSupertype /* InvalidPublicSupertype*/ { @org.jetbrains.annotations.NotNull() private final java.lang.Runnable x; @org.jetbrains.annotations.NotNull() public final java.lang.Runnable bar();// bar() @org.jetbrains.annotations.NotNull() public final java.lang.Runnable getX();// getX() public InvalidPublicSupertype();// .ctor() } final class null /* null*/ implements I, java.lang.Runnable { private ();// .ctor() public void run();// run() } final class null /* null*/ implements I, java.lang.Runnable { private ();// .ctor() public void run();// run() }
690
708
from numpy import array from scipy.cluster.vq import vq, kmeans, whiten from dml.CLUSTER.spectralCluster import SCC import matplotlib.pyplot as plt ''' features = array([ [1,6,11.05], [1,7.35,10.6], [1,8.35,8.35], [1,10.1,7.8], [1,10.2,8.7], [1,9.25,10], [1,8.05,10.8], [1,6.6,11.6], [1,6.4,9.15], [1,8.35,8.25], [1,9.5,7.05], [1,9.05,8.85], [1,8.2,9.45], [1,7.15,9.4], [1,7.3,7.75], [1,8.2,6.7], [1,15.45,17.3], [1,16.35,16.35], [1,17.45,16.5], [1,18.05,17.45], [1,17.5,18.6], [1,16.1,18.9], [1,16.75,17.5], [1,17.55,17.45], [1,15.95,18.35], [1,15.2,18], [1,15,17.45], [1,19.75,8.25], [1,20.75,7.9], [1,25.65,8.2], [1,25.05,10.5], [1,22.85,11.2], [1,21.6,9.9], [1,23.05,8.3], [1,24.65,8.8], [1,23.55,10.1], [1,23.05,9.45], [1,23.2,8.35], [1,24.2,7.95], [1,22.15,7.1], [1,21.6,7.8], [1,21.7,8.2]]) ''' features=array([ [13.45,11.95], [14.15,11.75], [14.8,11.25], [15.35,10.35], [15,9.55], [14.05,9.3], [13.05,10.2], [13.5,11.3], [14.4,10.95], [14.85,10.05], [13.75,9.65], [13.85,10.65], [14.15,10.6], [14.3,9.95], [13.85,9.5], [13.3,10.6], [13.25,11.45], [12.8,11], [13.95,9.2], [14.85,9.65], [10.4,13.95], [10.05,13.9], [9.55,12.75], [9.3,11.75], [9.3,10.5], [9.7,9.1], [10.4,8.25], [11.65,7.05], [12.9,6.45], [13.85,6.35], [15.3,6.65], [16.7,7.4], [17.5,8.25], [18.25,9.05], [18.75,10.2], [18.65,11.35], [18.25,12.5], [17.4,13.75], [16.6,14.75], [15.05,15.35], [12.7,15.25], [10.55,14.55], [9.95,13.95], [9.3,12.65], [9.1,11], [9.2,10], [10.2,8.65], [10.85,7.7], [12,7], [13.2,6.55], [14.45,6.6], [15.4,6.8], [16.9,7.15], [17.35,7.55], [18.05,8.45], [18.35,9.2], [18.75,9.8], [18.9,10.35], [18.9,11.05], [18.8,12.15], [18.3,12.65], [17.8,13.4], [16.95,14.15], [16.1,14.8], [14.8,15.35], [13.55,15.35], [11.6,15], [10.4,14.25], [11.3,14.4], [12.2,15.15], [12.45,15.35], [13.05,15.4], [13.85,15.25]] ) a=SCC(features,2) a.train(maxiter=180) print a.labels for i in range(features.shape[0]): if a.labels[i]==0: plt.plot(features[i][0],features[i][1],'or') else: plt.plot(features[i][0],features[i][1],'ob') plt.show() #print a.result() #print a.bfWhiteCen()
1,412
432
<reponame>ewie/activej<filename>extra/cloud-dataflow/src/main/java/io/activej/dataflow/node/AbstractNode.java package io.activej.dataflow.node; import io.activej.dataflow.DataflowException; import io.activej.dataflow.stats.NodeStat; import org.jetbrains.annotations.Nullable; import java.time.Instant; public abstract class AbstractNode implements Node { private final int index; protected @Nullable Instant finished = null; protected @Nullable Exception error = null; protected AbstractNode(int index) { this.index = index; } @Override public void finish(@Nullable Exception e) { if (e != null && !(e instanceof DataflowException)) { e = new DataflowException(e); } error = e; finished = Instant.now(); } @Override public @Nullable Instant getFinished() { return finished; } @Override public @Nullable Exception getError() { return error; } @Override public @Nullable NodeStat getStats() { return null; } @Override public int getIndex() { return index; } }
336
3,227
// Copyright (c) 1999 // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : <NAME> #ifndef CGAL_ENUM_H #define CGAL_ENUM_H #include <CGAL/config.h> #include <CGAL/Kernel/Same_uncertainty.h> #include <CGAL/Origin.h> // If you add/change one type here, please update Is_a_predicate.h as well. namespace CGAL { enum Sign { NEGATIVE = -1, ZERO = 0, POSITIVE = 1, // Orientation constants: RIGHT_TURN = -1, LEFT_TURN = 1, CLOCKWISE = -1, COUNTERCLOCKWISE = 1, COLLINEAR = 0, COPLANAR = 0, DEGENERATE = 0, // Oriented_side constants: ON_NEGATIVE_SIDE = -1, ON_ORIENTED_BOUNDARY = 0, ON_POSITIVE_SIDE = 1, // Comparison_result constants: SMALLER = -1, EQUAL = 0, LARGER = 1 }; typedef Sign Orientation; typedef Sign Oriented_side; typedef Sign Comparison_result; enum Bounded_side { ON_UNBOUNDED_SIDE = -1, ON_BOUNDARY, ON_BOUNDED_SIDE }; enum Angle { OBTUSE = -1, RIGHT, ACUTE }; template <class T> inline T opposite(const T& t) { return -t; } inline Sign operator-(Sign o) { return static_cast<Sign>( - static_cast<int>(o)); } inline Bounded_side opposite(Bounded_side bs) { return static_cast<Bounded_side>( - static_cast<int>(bs)); } inline Angle opposite(Angle a) { return static_cast<Angle>( - static_cast<int>(a)); } inline Sign operator* (Sign s1, Sign s2) { return static_cast<Sign> (static_cast<int> (s1) * static_cast<int> (s2)); } enum Box_parameter_space_2 { LEFT_BOUNDARY = 0, RIGHT_BOUNDARY, BOTTOM_BOUNDARY, TOP_BOUNDARY, INTERIOR, EXTERIOR }; template < typename T, typename U > inline T enum_cast(const U& u) { return static_cast<T>(u); } } //namespace CGAL #endif // CGAL_ENUM_H
935
575
<gh_stars>100-1000 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_ #define COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_ #include <stddef.h> #include <memory> #include <utility> #include <vector> #include "base/callback.h" #include "base/hash/hash.h" #include "base/macros.h" #include "base/util/type_safety/id_type.h" #include "cc/base/list_container.h" #include "cc/paint/filter_operations.h" #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/largest_draw_quad.h" #include "components/viz/common/quads/quad_list.h" #include "components/viz/common/quads/render_pass_internal.h" #include "components/viz/common/viz_common_export.h" #include "ui/gfx/display_color_spaces.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/rrect_f.h" #include "ui/gfx/transform.h" namespace viz { class AggregatedRenderPass; class CompositorRenderPassDrawQuad; class AggregatedRenderPassDrawQuad; using AggregatedRenderPassId = util::IdTypeU64<AggregatedRenderPass>; // This class represents a render pass that is a result of aggregating render // passes from all of the relevant surfaces. It is _not_ mojo-serializable since // it is local to the viz process. It has a unique AggregatedRenderPassId across // all of the AggregatedRenderPasses. class VIZ_COMMON_EXPORT AggregatedRenderPass : public RenderPassInternal { public: ~AggregatedRenderPass(); AggregatedRenderPass(); AggregatedRenderPass(size_t shared_quad_state_size, size_t draw_quad_size); void SetNew(AggregatedRenderPassId id, const gfx::Rect& output_rect, const gfx::Rect& damage_rect, const gfx::Transform& transform_to_root_target); void SetAll(AggregatedRenderPassId id, const gfx::Rect& output_rect, const gfx::Rect& damage_rect, const gfx::Transform& transform_to_root_target, const cc::FilterOperations& filters, const cc::FilterOperations& backdrop_filters, const base::Optional<gfx::RRectF>& backdrop_filter_bounds, gfx::ContentColorUsage content_color_usage, bool has_transparent_background, bool cache_render_pass, bool has_damage_from_contributing_content, bool generate_mipmap); AggregatedRenderPassDrawQuad* CopyFromAndAppendRenderPassDrawQuad( const CompositorRenderPassDrawQuad* quad, AggregatedRenderPassId render_pass_id); AggregatedRenderPassDrawQuad* CopyFromAndAppendRenderPassDrawQuad( const AggregatedRenderPassDrawQuad* quad); DrawQuad* CopyFromAndAppendDrawQuad(const DrawQuad* quad); // A shallow copy of the render pass, which does not include its quads or copy // requests. std::unique_ptr<AggregatedRenderPass> Copy( AggregatedRenderPassId new_id) const; // A deep copy of the render pass that includes quads. std::unique_ptr<AggregatedRenderPass> DeepCopy() const; template <typename DrawQuadType> DrawQuadType* CreateAndAppendDrawQuad() { static_assert( !std::is_same<DrawQuadType, CompositorRenderPassDrawQuad>::value, "cannot create CompositorRenderPassDrawQuad in AggregatedRenderPass"); return quad_list.AllocateAndConstruct<DrawQuadType>(); } // Uniquely identifies the render pass in the aggregated frame. AggregatedRenderPassId id; // The type of color content present in this RenderPass. gfx::ContentColorUsage content_color_usage = gfx::ContentColorUsage::kSRGB; // Indicates current RenderPass is a color conversion pass. bool is_color_conversion_pass = false; private: template <typename DrawQuadType> DrawQuadType* CopyFromAndAppendTypedDrawQuad(const DrawQuad* quad) { static_assert( !std::is_same<DrawQuadType, CompositorRenderPassDrawQuad>::value, "cannot copy CompositorRenderPassDrawQuad type into " "AggregatedRenderPass"); return quad_list.AllocateAndCopyFrom(DrawQuadType::MaterialCast(quad)); } DISALLOW_COPY_AND_ASSIGN(AggregatedRenderPass); }; using AggregatedRenderPassList = std::vector<std::unique_ptr<AggregatedRenderPass>>; } // namespace viz #endif // COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_
1,632
5,169
{ "name": "ICENewSecondPod", "version": "0.1.0", "summary": "My new Pod", "description": "TODO: This is my second Pod , I use new cocoapods. I hope is success.", "homepage": "https://github.com/My-Pod/ICENewSecondPod", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "gumengxiao": "<EMAIL>" }, "source": { "git": "https://github.com/My-Pod/ICENewSecondPod.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "source_files": "ICENewSecondPod/Classes/**/*" }
235
2,338
// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve \ // RUN: -emit-llvm -o - %s -debug-info-kind=limited 2>&1 | FileCheck %s void test_locals(void) { // CHECK-DAG: name: "__clang_svint8x2_t",{{.*}}, baseType: ![[CT8:[0-9]+]] // CHECK-DAG: ![[CT8]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY8:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS8x2:[0-9]+]]) // CHECK-DAG: ![[ELTTY8]] = !DIBasicType(name: "signed char", size: 8, encoding: DW_ATE_signed_char) // CHECK-DAG: ![[ELTS8x2]] = !{![[REALELTS8x2:[0-9]+]]} // CHECK-DAG: ![[REALELTS8x2]] = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 16, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus)) __clang_svint8x2_t s8; // CHECK-DAG: name: "__clang_svuint8x2_t",{{.*}}, baseType: ![[CT8:[0-9]+]] // CHECK-DAG: ![[CT8]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY8:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS8x2]]) // CHECK-DAG: ![[ELTTY8]] = !DIBasicType(name: "unsigned char", size: 8, encoding: DW_ATE_unsigned_char) __clang_svuint8x2_t u8; // CHECK-DAG: name: "__clang_svint16x2_t",{{.*}}, baseType: ![[CT16:[0-9]+]] // CHECK-DAG: ![[CT16]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY16:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS16x2:[0-9]+]]) // CHECK-DAG: ![[ELTTY16]] = !DIBasicType(name: "short", size: 16, encoding: DW_ATE_signed) // CHECK-DAG: ![[ELTS16x2]] = !{![[REALELTS16x2:[0-9]+]]} // CHECK-DAG: ![[REALELTS16x2]] = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 8, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus)) __clang_svint16x2_t s16; // CHECK-DAG: name: "__clang_svuint16x2_t",{{.*}}, baseType: ![[CT16:[0-9]+]] // CHECK-DAG: ![[CT16]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY16:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS16x2]]) // CHECK-DAG: ![[ELTTY16]] = !DIBasicType(name: "unsigned short", size: 16, encoding: DW_ATE_unsigned) __clang_svuint16x2_t u16; // CHECK-DAG: name: "__clang_svint32x2_t",{{.*}}, baseType: ![[CT32:[0-9]+]] // CHECK-DAG: ![[CT32]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY32:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS32x2:[0-9]+]]) // CHECK-DAG: ![[ELTTY32]] = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) // CHECK-DAG: ![[ELTS32x2]] = !{![[REALELTS32x2:[0-9]+]]} // CHECK-DAG: ![[REALELTS32x2]] = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 4, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus)) __clang_svint32x2_t s32; // CHECK-DAG: name: "__clang_svuint32x2_t",{{.*}}, baseType: ![[CT32:[0-9]+]] // CHECK-DAG: ![[CT32]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY32:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS32x2]]) // CHECK-DAG: ![[ELTTY32]] = !DIBasicType(name: "unsigned int", size: 32, encoding: DW_ATE_unsigned) __clang_svuint32x2_t u32; // CHECK-DAG: name: "__clang_svint64x2_t",{{.*}}, baseType: ![[CT64:[0-9]+]] // CHECK-DAG: ![[CT64]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY64:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS1x2_64:[0-9]+]]) // CHECK-DAG: ![[ELTTY64]] = !DIBasicType(name: "long int", size: 64, encoding: DW_ATE_signed) // CHECK-DAG: ![[ELTS1x2_64]] = !{![[REALELTS1x2_64:[0-9]+]]} // CHECK-DAG: ![[REALELTS1x2_64]] = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 2, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus)) __clang_svint64x2_t s64; // CHECK-DAG: name: "__clang_svuint64x2_t",{{.*}}, baseType: ![[CT64:[0-9]+]] // CHECK-DAG: ![[CT64]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY64:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS1x2_64]]) // CHECK-DAG: ![[ELTTY64]] = !DIBasicType(name: "long unsigned int", size: 64, encoding: DW_ATE_unsigned) __clang_svuint64x2_t u64; // CHECK: name: "__clang_svfloat16x2_t",{{.*}}, baseType: ![[CT16:[0-9]+]] // CHECK-DAG: ![[CT16]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY16:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS16x2]]) // CHECK-DAG: ![[ELTTY16]] = !DIBasicType(name: "__fp16", size: 16, encoding: DW_ATE_float) __clang_svfloat16x2_t f16; // CHECK: name: "__clang_svfloat32x2_t",{{.*}}, baseType: ![[CT32:[0-9]+]] // CHECK-DAG: ![[CT32]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY32:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS32x2]]) // CHECK-DAG: ![[ELTTY32]] = !DIBasicType(name: "float", size: 32, encoding: DW_ATE_float) __clang_svfloat32x2_t f32; // CHECK: name: "__clang_svfloat64x2_t",{{.*}}, baseType: ![[CT64:[0-9]+]] // CHECK-DAG: ![[CT64]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[ELTTY64:[0-9]+]], flags: DIFlagVector, elements: ![[ELTS1x2_64]]) // CHECK-DAG: ![[ELTTY64]] = !DIBasicType(name: "double", size: 64, encoding: DW_ATE_float) __clang_svfloat64x2_t f64; }
2,407
1,442
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """This model adds noise/rir to signal and writes it to file.""" import delta.compat as tf from delta.utils.hparam import HParams from delta.data.frontend.read_wav import ReadWav from delta.data.frontend.add_rir_noise_aecres import Add_rir_noise_aecres from delta.data.frontend.write_wav import WriteWav from delta.data.frontend.base_frontend import BaseFrontend class AddNoiseEndToEnd(BaseFrontend): """ Add a random signal-to-noise ratio noise or impulse response to clean speech, and write it to wavfile. """ def __init__(self, config: dict): super().__init__(config) self.add_noise = Add_rir_noise_aecres(config) self.read_wav = ReadWav(config) self.write_wav = WriteWav(config) @classmethod def params(cls, config=None): """ Set params. :param config: contains ten optional parameters: --sample_rate : Sample frequency of waveform data. (int, default = 16000) --if_add_rir : If true, add rir to audio data. (bool, default = False) --rir_filelist : FileList path of rir.(string, default = 'rirlist.scp') --if_add_noise : If true, add random noise to audio data. (bool, default = False) --snr_min : Minimum SNR adds to signal. (float, default = 0) --snr_max : Maximum SNR adds to signal. (float, default = 30) --noise_filelist : FileList path of noise.(string, default = 'noiselist.scp') --if_add_aecres : If true, add aecres to audio data. (bool, default = False) --aecres_filelist : FileList path of aecres.(string, default = 'aecreslist.scp') --speed : Speed of sample channels wanted. (float, default=1.0) :return: An object of class HParams, which is a set of hyperparameters as name-value pairs. """ sample_rate = 16000 if_add_rir = False rir_filelist = 'rirlist.scp' if_add_noise = False noise_filelist = 'noiselist.scp' snr_min = 0 snr_max = 30 if_add_aecres = False aecres_filelist = 'aecreslist.scp' audio_channels = 1 speed = 1.0 hparams = HParams(cls=cls) hparams.add_hparam('sample_rate', sample_rate) hparams.add_hparam('speed', speed) hparams.add_hparam('if_add_rir', if_add_rir) hparams.add_hparam('if_add_noise', if_add_noise) hparams.add_hparam('rir_filelist', rir_filelist) hparams.add_hparam('noise_filelist', noise_filelist) hparams.add_hparam('snr_min', snr_min) hparams.add_hparam('snr_max', snr_max) hparams.add_hparam('if_add_aecres', if_add_aecres) hparams.add_hparam('aecres_filelist', aecres_filelist) hparams.add_hparam('audio_channels', audio_channels) if config is not None: hparams.override_from_dict(config) return hparams def call(self, in_wavfile, out_wavfile): """ Read a clean wav return a noisy wav. :param in_wavfile: clean wavfile path. :param out_wavfile: noisy wavfile path. :return: write wav opration. """ with tf.name_scope('add_noise_end_to_end'): input_data, sample_rate = self.read_wav(in_wavfile) noisy_data = self.add_noise(input_data, sample_rate) / 32768 write_op = self.write_wav(out_wavfile, noisy_data, sample_rate) return write_op
1,612
3,562
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.doris.common.publish; import org.apache.doris.system.Backend; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; // Handler which will be call back by processor. public class ResponseHandler { private Set<Backend> nodes; private CountDownLatch latch; public ResponseHandler(Collection<Backend> nodes) { this.nodes = Sets.newConcurrentHashSet(nodes); latch = new CountDownLatch(nodes.size()); } public void onResponse(Backend node) { if (nodes.remove(node)) { latch.countDown(); } } public void onFailure(Backend node, Throwable t) { if (nodes.remove(node)) { latch.countDown(); } } public boolean awaitAllInMs(long millions) throws InterruptedException { return latch.await(millions, TimeUnit.MILLISECONDS); } public Backend[] pendingNodes() { return nodes.toArray(new Backend[0]); } }
606
16,461
<filename>ios/versioned-react-native/ABI41_0_0/Expo/ExpoKit/Core/UniversalModules/ABI41_0_0EXScopedSegment.h // Copyright © 2019-present 650 Industries. All rights reserved. #if __has_include(<ABI41_0_0EXSegment/ABI41_0_0EXSegment.h>) #import <ABI41_0_0EXSegment/ABI41_0_0EXSegment.h> #import <ABI41_0_0UMCore/ABI41_0_0UMModuleRegistryConsumer.h> NS_ASSUME_NONNULL_BEGIN @interface ABI41_0_0EXScopedSegment : ABI41_0_0EXSegment <ABI41_0_0UMModuleRegistryConsumer> @end NS_ASSUME_NONNULL_END #endif
226
3,151
package com.rarchives.ripme.tst.ripper.rippers; import java.io.IOException; import java.net.URL; import com.rarchives.ripme.ripper.rippers.FooktubeRipper; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class FooktubeRipperTest extends RippersTest { @Test @Disabled("test or ripper broken") public void testFooktubeVideo() throws IOException { FooktubeRipper ripper = new FooktubeRipper(new URL("https://fooktube.com/video/641/in-the-cinema")); //pick any video from the front page testRipper(ripper); } }
219
331
<reponame>Lauzy/TicktockMusic package com.freedom.lauzy.ticktockmusic.contract; import android.content.Context; import android.graphics.Bitmap; import com.freedom.lauzy.ticktockmusic.base.IBaseView; import com.freedom.lauzy.ticktockmusic.model.SongEntity; import com.lauzy.freedom.librarys.widght.music.lrc.Lrc; import java.util.List; /** * Desc : * Author : Lauzy * Date : 2017/9/7 * Blog : http://www.jianshu.com/u/e76853f863a9 * Email : <EMAIL> */ public interface PlayContract { interface View extends IBaseView { Context getContext(); void setCoverBackground(Bitmap background); void addFavoriteSong(); void deleteFavoriteSong(); void setViewBgColor(int paletteColor); void setPlayView(Bitmap resource); void showLightViews(boolean isFavorite); void showDarkViews(boolean isFavorite); void startDownloadLrc(); void downloadLrcSuccess(List<Lrc> lrcs); void downloadFailed(Throwable e); } interface Presenter { void setCoverImgUrl(long songId, Object url); void addFavoriteSong(SongEntity entity); void deleteFavoriteSong(long songId); void loadLrc(SongEntity entity); void setRepeatMode(int mode); int getRepeatMode(int defautMode); } }
510
4,036
<gh_stars>1000+ package com.semmle.js.extractor.test; import com.semmle.js.ast.Node; import com.semmle.js.extractor.ExtractionMetrics; import com.semmle.js.extractor.ExtractorConfig; import com.semmle.js.extractor.ExtractorConfig.SourceType; import com.semmle.js.extractor.NodeJSDetector; import com.semmle.js.parser.JSParser; import com.semmle.js.parser.JSParser.Result; import org.junit.Assert; import org.junit.Test; public class NodeJSDetectorTests { private static final ExtractorConfig CONFIG = new ExtractorConfig(false); private void isNodeJS(String src, boolean expected) { Result res = JSParser.parse(CONFIG, SourceType.SCRIPT, src, new ExtractionMetrics()); Node ast = res.getAST(); Assert.assertNotNull(ast); Assert.assertTrue(NodeJSDetector.looksLikeNodeJS(ast) == expected); } @Test public void testBareRequire() { isNodeJS("require('fs');", true); } @Test public void testRequireInit() { isNodeJS("var fs = require('fs');", true); } @Test public void testRequireInit2() { isNodeJS("var foo, fs = require('fs');", true); } @Test public void testDirective() { isNodeJS("\"use strict\"; require('fs');", true); } @Test public void testComment() { isNodeJS( "/** My awesome package.\n" + "* (C) me.\n" + "*/\n" + "\n" + "var isArray = require(\"isArray\");", true); } @Test public void testInitialExport() { isNodeJS("exports.foo = 0; console.log('Hello, world!');", true); } @Test public void testInitialModuleExport() { isNodeJS("module.exports.foo = 0; console.log('Hello, world!');", true); } @Test public void testInitialBulkExport() { isNodeJS("module.exports = {}; console.log('Hello, world!');", true); } @Test public void testTrailingExport() { isNodeJS("console.log('Hello, world!'); exports.foo = 0;", true); } @Test public void testTrailingModuleExport() { isNodeJS("console.log('Hello, world!'); module.exports.foo = 0;", true); } @Test public void testTrailingBulkExport() { isNodeJS("console.log('Hello, world!'); module.exports = {};", true); } @Test public void testInitialNestedExport() { isNodeJS("mystuff = module.exports = {}; mystuff.foo = 0;", true); } @Test public void testInitialNestedExportInit() { isNodeJS("var mystuff = module.exports = exports = {}; mystuff.foo = 0;", true); } @Test public void testTrailingRequire() { isNodeJS("console.log('Hello, world!'); var fs = require('fs');", true); } @Test public void testSandwichedExport() { isNodeJS("console.log('Hello'); exports.foo = 0; console.log('world!');", true); } @Test public void umd() { isNodeJS( "(function(define) {\n" + " define(function (require, exports, module) {\n" + " var b = require('b');\n" + " return function () {};\n" + " });\n" + "}(\n" + " typeof module === 'object' && module.exports && typeof define !== 'function' ?\n" + " function (factory) { module.exports = factory(require, exports, module); } :\n" + " define\n" + "));", false); } @Test public void testRequirePropAccess() { isNodeJS("var foo = require('./b').foo;", true); } @Test public void testReExport() { isNodeJS("module.exports = require('./e');", true); } @Test public void testSeparateVar() { isNodeJS("var fs; fs = require('fs');", true); } @Test public void testLet() { isNodeJS("let fs = require('fs');", true); } @Test public void testSeparateLet() { isNodeJS("let fs; fs = require('fs');", true); } @Test public void testConst() { isNodeJS("const fs = require('fs');", true); } @Test public void testIife() { isNodeJS(";(function() { require('fs'); })()", true); } @Test public void testIife2() { isNodeJS("!function() { require('fs'); }()", true); } @Test public void testUMD() { isNodeJS("(function(require) { require('fs'); })(myRequire);", false); } @Test public void amdefine() { isNodeJS( "if (typeof define !== 'function') define = require('amdefine')(module, require);", true); } @Test public void requireAndReadProp() { isNodeJS("var readFileSync = require('fs').readFileSync;", true); } @Test public void toplevelAMDRequire() { isNodeJS("require(['foo'], function(foo) { });", false); } @Test public void requireInTry() { isNodeJS( "var fs;" + "try {" + " fs = require('graceful-fs');" + "} catch(e) {" + " fs = require('fs');" + "}", true); } @Test public void requireInIf() { isNodeJS( "var fs;" + "if (useGracefulFs) {" + " fs = require('graceful-fs');" + "} else {" + " fs = require('fs');" + "}", true); } @Test public void requireAndCall() { isNodeJS("var foo = require('foo')();", true); } @Test public void requireAndCallMethod() { isNodeJS("var foo = require('foo').bar();", true); } }
2,156
921
package sqlancer.mysql.ast; public class MySQLUnaryPostfixOperation implements MySQLExpression { private final MySQLExpression expression; private final UnaryPostfixOperator operator; private boolean negate; public enum UnaryPostfixOperator { IS_NULL, IS_TRUE, IS_FALSE; } public MySQLUnaryPostfixOperation(MySQLExpression expr, UnaryPostfixOperator op, boolean negate) { this.expression = expr; this.operator = op; this.setNegate(negate); } public MySQLExpression getExpression() { return expression; } public UnaryPostfixOperator getOperator() { return operator; } public boolean isNegated() { return negate; } public void setNegate(boolean negate) { this.negate = negate; } @Override public MySQLConstant getExpectedValue() { boolean val; MySQLConstant expectedValue = expression.getExpectedValue(); switch (operator) { case IS_NULL: val = expectedValue.isNull(); break; case IS_FALSE: val = !expectedValue.isNull() && !expectedValue.asBooleanNotNull(); break; case IS_TRUE: val = !expectedValue.isNull() && expectedValue.asBooleanNotNull(); break; default: throw new AssertionError(operator); } if (negate) { val = !val; } return MySQLConstant.createIntConstant(val ? 1 : 0); } }
655
497
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.quarkus.deployment.internal; import com.datastax.oss.quarkus.runtime.api.session.QuarkusCqlSession; import io.quarkus.builder.item.SimpleBuildItem; import io.quarkus.runtime.RuntimeValue; import java.util.concurrent.CompletionStage; public final class CassandraClientBuildItem extends SimpleBuildItem { private final RuntimeValue<CompletionStage<QuarkusCqlSession>> cqlSession; public CassandraClientBuildItem(RuntimeValue<CompletionStage<QuarkusCqlSession>> cqlSession) { this.cqlSession = cqlSession; } @SuppressWarnings("unused") public RuntimeValue<CompletionStage<QuarkusCqlSession>> getCqlSession() { return cqlSession; } }
370
1,473
<filename>Core/src/org/sleuthkit/autopsy/commandlineingest/UserPreferences.java /* * Autopsy Forensic Browser * * Copyright 2019-2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.commandlineingest; /** * Provides convenient access to a UserPreferences node for user preferences * with default values. */ public final class UserPreferences { private static final String COMMAND_LINE_MODE_CONTEXT_STRING = "CommandLineModeContext"; // NON-NLS /** * Get context string for command line mode ingest module settings. * * @return String Context string for command line mode ingest module * settings. */ public static String getCommandLineModeIngestModuleContextString() { return COMMAND_LINE_MODE_CONTEXT_STRING; } }
394
2,206
/* * * Copyright (c) 2006-2020, Speedment, 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.speedment.common.json; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.ThrowingSupplier; import java.util.concurrent.atomic.AtomicLong; final class JsonSyntaxExceptionTest { @Test void constructor() { assertDoesNotThrow((ThrowingSupplier<JsonSyntaxException>) JsonSyntaxException::new); assertDoesNotThrow(() -> new JsonSyntaxException("message")); final AtomicLong row = new AtomicLong(1); final AtomicLong col = new AtomicLong(1); final Throwable throwable = new RuntimeException(); assertDoesNotThrow(() -> new JsonSyntaxException(row, col)); assertDoesNotThrow(() -> new JsonSyntaxException(row, col, throwable)); assertDoesNotThrow(() -> new JsonSyntaxException(row, col, "message")); assertDoesNotThrow(() -> new JsonSyntaxException(row, col, "message", throwable)); } @Test void getMessage() { assertNotNull(new JsonSyntaxException().getMessage()); } }
549
43,677
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp.regression; import androidx.test.ext.junit.runners.AndroidJUnit4; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Simple test adaptable to show a failure in older versions of OkHttp * or Android SDKs. */ @RunWith(AndroidJUnit4.class) public class IssueReproductionTest { @Test public void getFailsWithoutAdditionalCert() throws IOException { OkHttpClient client = new OkHttpClient(); sendRequest(client, "https://google.com/robots.txt"); } private void sendRequest(OkHttpClient client, String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { assertTrue(response.code() == 200 || response.code() == 404); assertEquals(Protocol.HTTP_2, response.protocol()); for (Certificate c: response.handshake().peerCertificates()) { X509Certificate x = (X509Certificate) c; System.out.println(x.getSubjectDN()); } } } }
619
511
/**************************************************************************** * * Copyright 2019 Samsung Electronics 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <debug.h> #include <errno.h> #include <fcntl.h> #include <mqueue.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <messaging/messaging.h> #include "messaging_internal.h" #define MSG_REPLY_PRIO 10 /**************************************************************************** * private functions ****************************************************************************/ static int messaging_send_param_validation(const char *port_name, msg_send_data_t *send_data) { if (port_name == NULL) { msgdbg("[Messaging] unicast send sync fail : no port name.\n"); return ERROR; } if (send_data == NULL || send_data->msg == NULL || send_data->msglen <= 0 || send_data->priority < 0) { msgdbg("[Messaging] unicast send sync fail : invalid param of send data.\n"); return ERROR; } return OK; } static int messaging_sync_recv(const char *port_name, msg_recv_buf_t *reply_buf) { int ret = OK; mqd_t sync_mqdes; char *sync_portname; struct mq_attr internal_attr; char *reply_data; int reply_size; int msg_type; reply_size = reply_buf->buflen + MSG_HEADER_SIZE; internal_attr.mq_maxmsg = CONFIG_MESSAGING_MAXMSG; internal_attr.mq_msgsize = reply_size; internal_attr.mq_flags = 0; /* sender waits the reply with "port_name + sender_pid + _r". */ MSG_ASPRINTF(&sync_portname, "%s%d%s", port_name, getpid(), "_r"); if (sync_portname == NULL) { msgdbg("message send fail : sync portname allocation fail.\n"); return ERROR; } sync_mqdes = mq_open(sync_portname, O_RDONLY | O_CREAT, 0666, &internal_attr); if (sync_mqdes == (mqd_t)ERROR) { msgdbg("message send fail : sync open fail %d.\n", errno); MSG_FREE(sync_portname); return ERROR; } reply_data = (char *)MSG_ALLOC(reply_size); if (reply_data == NULL) { msgdbg("message send fail : out of memory for including header\n"); mq_close(sync_mqdes); mq_unlink(sync_portname); return ERROR; } ret = mq_receive(sync_mqdes, reply_data, reply_size, 0); if (ret < 0) { msgdbg("message send fail : sync recv fail %d.\n", errno); ret = ERROR; } else { ret = messaging_parse_packet(reply_data, reply_buf->buf, reply_buf->buflen, &reply_buf->sender_pid, &msg_type); if (ret != OK) { ret = ERROR; } } mq_close(sync_mqdes); mq_unlink(sync_portname); MSG_FREE(reply_data); MSG_FREE(sync_portname); return ret; } /**************************************************************************** * public functions ****************************************************************************/ /**************************************************************************** * messaging_send_sync ****************************************************************************/ int messaging_send_sync(const char *port_name, msg_send_data_t *send_data, msg_recv_buf_t *reply_buf) { int ret; ret = messaging_send_param_validation(port_name, send_data); if (ret == ERROR) { return ERROR; } if (reply_buf == NULL || reply_buf->buf == NULL || reply_buf->buflen <= 0) { msgdbg("[Messaging] unicast send sync fail : invalid param of reply buf\n"); return ERROR; } ret = messaging_send_internal(port_name, MSG_SEND_SYNC, send_data, NULL, NULL); if (ret == ERROR) { return ERROR; } ret = messaging_sync_recv(port_name, reply_buf); if (ret != OK) { return ERROR; } return OK; } /**************************************************************************** * messaging_send_async ****************************************************************************/ int messaging_send_async(const char *port_name, msg_send_data_t *send_data, msg_recv_buf_t *reply_buf, msg_callback_info_t *cb_info) { int ret; ret = messaging_send_param_validation(port_name, send_data); if (ret == ERROR) { return ERROR; } if (reply_buf == NULL || reply_buf->buf == NULL || reply_buf->buflen <= 0) { msgdbg("[Messaging] unicast send async fail : invalid param of reply buffer.\n"); return ERROR; } if (cb_info == NULL || cb_info->cb_func == NULL) { msgdbg("[Messaging] unicast send asyc fail : invalid callback info.\n"); return ERROR; } ret = messaging_send_internal(port_name, MSG_SEND_ASYNC, send_data, reply_buf, cb_info); if (ret == ERROR) { return ERROR; } return OK; } /**************************************************************************** * messaging_send ****************************************************************************/ int messaging_send(const char *port_name, msg_send_data_t *send_data) { int ret; if (port_name == NULL) { msgdbg("[Messaging] unicast send async fail : no port name.\n"); return ERROR; } if (send_data == NULL || send_data->msg == NULL || send_data->msglen <= 0 || send_data->priority < 0) { msgdbg("[Messaging] unicast send async fail : invalid param of send data.\n"); return ERROR; } ret = messaging_send_internal(port_name, MSG_SEND_NOREPLY, send_data, NULL, NULL); if (ret == ERROR) { return ERROR; } return OK; } /**************************************************************************** * messaging_reply ****************************************************************************/ int messaging_reply(const char *port_name, pid_t sender_pid, msg_send_data_t *reply_data) { int ret = OK; char *reply_portname; msg_send_data_t reply; if (port_name == NULL || sender_pid < 0 || reply_data == NULL || reply_data->msg == NULL || reply_data->msglen <= 0) { msgdbg("[Messaging] unicast reply fail : invalid param.\n"); return ERROR; } /* Sender waits the reply with "port_name + sender_pid + _r". */ MSG_ASPRINTF(&reply_portname, "%s%d%s", port_name, sender_pid, "_r"); if (reply_portname == NULL) { msgdbg("[Messaging] unicast reply fail : out of memory.\n"); return ERROR; } reply.msg = reply_data->msg; reply.msglen = reply_data->msglen; reply.priority = MSG_REPLY_PRIO; ret = messaging_send_packet(reply_portname, MSG_SEND_REPLY, &reply, NULL); MSG_FREE(reply_portname); return ret; }
2,244
482
/** * Copyright (c) 2013, <EMAIL> * 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 impossibl.com nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.impossibl.postgres.system.procs; import com.impossibl.postgres.system.Context; import com.impossibl.postgres.system.ConversionException; import com.impossibl.postgres.system.ServerInfo; import com.impossibl.postgres.types.Type; import static com.impossibl.postgres.system.procs.DatesTimes.JAVA_DATE_NEGATIVE_INFINITY_MSECS; import static com.impossibl.postgres.system.procs.DatesTimes.JAVA_DATE_POSITIVE_INFINITY_MSECS; import static com.impossibl.postgres.system.procs.DatesTimes.NEG_INFINITY; import static com.impossibl.postgres.system.procs.DatesTimes.POS_INFINITY; import static com.impossibl.postgres.system.procs.DatesTimes.javaEpochToPg; import static com.impossibl.postgres.system.procs.DatesTimes.pgEpochToJava; import java.io.IOException; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAccessor; import java.util.Calendar; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import io.netty.buffer.ByteBuf; public class TimestampsWithoutTZ extends SettingSelectProcProvider { public TimestampsWithoutTZ() { super(ServerInfo::hasIntegerDateTimes, new TxtEncoder(), new TxtDecoder(), new BinEncoder(), new BinDecoder(), new TxtEncoder(), new TxtDecoder(), null, null, "timestamp_"); } private static LocalDateTime convertInput(Context context, Type type, Object value, Calendar sourceCalendar) throws ConversionException { if (value instanceof LocalDateTime) { return (LocalDateTime) value; } if (value instanceof CharSequence) { CharSequence chars = (CharSequence) value; if (value.equals(POS_INFINITY)) return LocalDateTime.MAX; if (value.equals(NEG_INFINITY)) return LocalDateTime.MIN; TemporalAccessor parsed = context.getClientTimestampFormat().getParser().parse(chars); return LocalDateTime.from(parsed); } if (value instanceof Timestamp) { Timestamp ts = (Timestamp) value; if (ts.getTime() == JAVA_DATE_POSITIVE_INFINITY_MSECS) return LocalDateTime.MAX; if (ts.getTime() == JAVA_DATE_NEGATIVE_INFINITY_MSECS) return LocalDateTime.MIN; return ts.toInstant().atZone(sourceCalendar.getTimeZone().toZoneId()).toLocalDateTime(); } else if (value instanceof Time) { Time t = (Time) value; if (t.getTime() == JAVA_DATE_POSITIVE_INFINITY_MSECS) return LocalDateTime.MAX; if (t.getTime() == JAVA_DATE_NEGATIVE_INFINITY_MSECS) return LocalDateTime.MIN; return Instant.ofEpochMilli(t.getTime()).atZone(sourceCalendar.getTimeZone().toZoneId()).toLocalDateTime(); } else if (value instanceof Date) { Date d = (Date) value; if (d.getTime() == JAVA_DATE_POSITIVE_INFINITY_MSECS) return LocalDateTime.MAX; if (d.getTime() == JAVA_DATE_NEGATIVE_INFINITY_MSECS) return LocalDateTime.MIN; return Instant.ofEpochMilli(d.getTime()).atZone(sourceCalendar.getTimeZone().toZoneId()).toLocalDateTime(); } throw new ConversionException(value.getClass(), type); } private static Object convertInfinityOutput(boolean positive, Type type, Class<?> targetClass) throws ConversionException { if (targetClass == LocalDateTime.class) { return positive ? LocalDateTime.MAX : LocalDateTime.MIN; } if (targetClass == LocalDate.class) { return positive ? LocalDate.MAX : LocalDate.MIN; } if (targetClass == String.class) { return positive ? POS_INFINITY : NEG_INFINITY; } if (targetClass == Time.class) { return new Time(positive ? JAVA_DATE_POSITIVE_INFINITY_MSECS : JAVA_DATE_NEGATIVE_INFINITY_MSECS); } if (targetClass == Date.class) { return new Date(positive ? JAVA_DATE_POSITIVE_INFINITY_MSECS : JAVA_DATE_NEGATIVE_INFINITY_MSECS); } if (targetClass == Timestamp.class) { return new Timestamp(positive ? JAVA_DATE_POSITIVE_INFINITY_MSECS : JAVA_DATE_NEGATIVE_INFINITY_MSECS); } throw new ConversionException(type, targetClass); } private static Object convertOutput(Context context, Type type, LocalDateTime dateTime, Class<?> targetClass, Calendar targetCalendar) throws ConversionException { if (targetClass == LocalDateTime.class) { return dateTime; } if (targetClass == LocalDate.class) { return dateTime.toLocalDate(); } if (targetClass == String.class) { return context.getClientTimestampFormat().getPrinter().format(dateTime); } ZoneId targetZoneId = targetCalendar.getTimeZone().toZoneId(); ZonedDateTime zonedDateTime = dateTime.atOffset(ZoneOffset.UTC).atZoneSimilarLocal(targetZoneId); if (targetClass == Time.class) { return new Time(zonedDateTime.withYear(1970).withDayOfYear(1).toInstant().toEpochMilli()); } if (targetClass == Date.class) { return new Date(zonedDateTime.truncatedTo(ChronoUnit.DAYS).toInstant().toEpochMilli()); } if (targetClass == Timestamp.class) { return Timestamp.from(zonedDateTime.toInstant()); } throw new ConversionException(type, targetClass); } private static class BinDecoder extends BaseBinaryDecoder { BinDecoder() { super(8); } @Override public Class<?> getDefaultClass() { return Timestamp.class; } @Override protected Object decodeValue(Context context, Type type, Short typeLength, Integer typeModifier, ByteBuf buffer, Class<?> targetClass, Object targetContext) throws IOException { Calendar calendar = targetContext != null ? (Calendar) targetContext : Calendar.getInstance(); long micros = buffer.readLong(); if (micros == Long.MAX_VALUE || micros == Long.MIN_VALUE) { return convertInfinityOutput(micros == Long.MAX_VALUE, type, targetClass); } micros = pgEpochToJava(micros, MICROSECONDS); long secs = MICROSECONDS.toSeconds(micros); long nanos = MICROSECONDS.toNanos(micros % SECONDS.toMicros(1)); if (nanos < 0) { nanos += SECONDS.toNanos(1); secs--; } LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(secs, (int) nanos, ZoneOffset.UTC); return convertOutput(context, type, localDateTime, targetClass, calendar); } } private static class BinEncoder extends BaseBinaryEncoder { BinEncoder() { super(8); } @Override protected void encodeValue(Context context, Type type, Object value, Object sourceContext, ByteBuf buffer) throws IOException { Calendar calendar = sourceContext != null ? (Calendar) sourceContext : Calendar.getInstance(); LocalDateTime dateTime = convertInput(context, type, value, calendar); long micros; if (dateTime.equals(LocalDateTime.MAX)) { micros = Long.MAX_VALUE; } else if (dateTime.equals(LocalDateTime.MIN)) { micros = Long.MIN_VALUE; } else { long seconds = javaEpochToPg(dateTime.toEpochSecond(ZoneOffset.UTC), SECONDS); // Convert to micros rounding nanoseconds micros = SECONDS.toMicros(seconds) + NANOSECONDS.toMicros(dateTime.getNano() + 500); } buffer.writeLong(micros); } } private static class TxtDecoder extends BaseTextDecoder { public Class<?> getDefaultClass() { return Timestamp.class; } @Override protected Object decodeValue(Context context, Type type, Short typeLength, Integer typeModifier, CharSequence buffer, Class<?> targetClass, Object targetContext) throws IOException { Calendar calendar = targetContext != null ? (Calendar) targetContext : Calendar.getInstance(); if (buffer.equals(POS_INFINITY) || buffer.equals(NEG_INFINITY)) { return convertInfinityOutput(buffer.equals(POS_INFINITY), type, targetClass); } TemporalAccessor parsed = context.getServerTimestampFormat().getParser().parse(buffer); LocalDateTime localDateTime = LocalDateTime.from(parsed); return convertOutput(context, type, localDateTime, targetClass, calendar); } } private static class TxtEncoder extends BaseTextEncoder { @Override protected void encodeValue(Context context, Type type, Object value, Object sourceContext, StringBuilder buffer) throws IOException { Calendar calendar = sourceContext != null ? (Calendar) sourceContext : Calendar.getInstance(); LocalDateTime dateTime = convertInput(context, type, value, calendar); if (dateTime.equals(LocalDateTime.MAX)) { buffer.append(POS_INFINITY); } else if (dateTime.equals(LocalDateTime.MIN)) { buffer.append(NEG_INFINITY); } else { String strVal = context.getServerTimestampFormat().getPrinter().format(dateTime); buffer.append(strVal); } } } }
3,755
14,668
#!/usr/bin/env python # Copyright 2018 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. import os import sys import unittest import PRESUBMIT sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../../../..')) from PRESUBMIT_test_mocks import MockFile, MockInputApi, MockOutputApi class CheckNotificationConstructors(unittest.TestCase): """Test the _CheckNotificationConstructors presubmit check.""" def testTruePositives(self): """Examples of when Notification.Builder use is correctly flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['new Notification.Builder()']), MockFile('path/Two.java', ['new NotificationCompat.Builder()']), ] errors = PRESUBMIT._CheckNotificationConstructors( mock_input, MockOutputApi()) self.assertEqual(1, len(errors)) self.assertEqual(2, len(errors[0].items)) self.assertIn('One.java', errors[0].items[0]) self.assertIn('Two.java', errors[0].items[1]) def testFalsePositives(self): """Examples of when Notification.Builder should not be flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile( 'chrome/android/java/src/org/chromium/chrome/browser/notifications/' 'ChromeNotificationWrapperBuilder.java', ['new Notification.Builder()']), MockFile( 'chrome/android/java/src/org/chromium/chrome/browser/notifications/' 'ChromeNotificationWrapperCompatBuilder.java', ['new NotificationCompat.Builder()']), MockFile('path/One.java', ['Notification.Builder']), MockFile('path/Two.java', ['// do not: new Notification.Builder()']), MockFile('path/Three.java', ['/** NotificationWrapperBuilder', ' * replaces: new Notification.Builder()']), MockFile('path/PRESUBMIT.py', ['new Notification.Builder()']), MockFile('path/Four.java', ['new NotificationCompat.Builder()'], action='D'), ] errors = PRESUBMIT._CheckNotificationConstructors( mock_input, MockOutputApi()) self.assertEqual(0, len(errors)) class CheckAlertDialogBuilder(unittest.TestCase): """Test the _CheckAlertDialogBuilder presubmit check.""" def testTruePositives(self): """Examples of when AlertDialog.Builder use is correctly flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['new AlertDialog.Builder()']), MockFile('path/Two.java', ['new AlertDialog.Builder(context);']), ] errors = PRESUBMIT._CheckAlertDialogBuilder(mock_input, MockOutputApi()) self.assertEqual(1, len(errors)) self.assertEqual(2, len(errors[0].items)) self.assertIn('One.java', errors[0].items[0]) self.assertIn('Two.java', errors[0].items[1]) def testFalsePositives(self): """Examples of when AlertDialog.Builder should not be flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['AlertDialog.Builder']), MockFile('path/Two.java', ['// do not: new AlertDialog.Builder()']), MockFile('path/Three.java', ['/** ChromeAlertDialogBuilder', ' * replaces: new AlertDialog.Builder()']), MockFile('path/PRESUBMIT.py', ['new AlertDialog.Builder()']), MockFile('path/Four.java', ['new AlertDialog.Builder()'], action='D'), ] errors = PRESUBMIT._CheckAlertDialogBuilder( mock_input, MockOutputApi()) self.assertEqual(0, len(errors)) def testFailure_WrongBuilderCheck(self): """Use of AppCompat AlertDialog.Builder is correctly flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['import android.support.v7.app.AlertDialog;', 'new AlertDialog.Builder()']), MockFile('path/Two.java', ['import android.app.AlertDialog;', 'new AlertDialog.Builder(context);']), ] errors = PRESUBMIT._CheckAlertDialogBuilder( mock_input, MockOutputApi()) self.assertEqual(2, len(errors)) self.assertEqual(1, len(errors[1].items)) self.assertIn('One.java', errors[1].items[0]) def testSuccess_WrongBuilderCheck(self): """Use of OS-dependent AlertDialog should not be flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['import android.app.AlertDialog;', 'new AlertDialog.Builder()']), MockFile('path/Two.java', ['import android.app.AlertDialog;', 'new AlertDialog.Builder(context);']), ] errors = PRESUBMIT._CheckAlertDialogBuilder(mock_input, MockOutputApi()) self.assertEqual(1, len(errors)) self.assertEqual(2, len(errors[0].items)) class CheckCompatibleAlertDialogBuilder(unittest.TestCase): """Test the _CheckCompatibleAlertDialogBuilder presubmit check.""" def testFailure(self): """Use of CompatibleAlertDialogBuilder use is correctly flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['import ' 'org.chromium.ui.UiUtils.CompatibleAlertDialogBuilder;', 'new CompatibleAlertDialogBuilder()', 'A new line to make sure there is no duplicate error.']), MockFile('path/Two.java', ['new UiUtils.CompatibleAlertDialogBuilder()']), MockFile('path/Three.java', ['new UiUtils', '.CompatibleAlertDialogBuilder(context)']), MockFile('path/Four.java', ['new UiUtils', ' .CompatibleAlertDialogBuilder()']), ] errors = PRESUBMIT._CheckCompatibleAlertDialogBuilder( mock_input, MockOutputApi()) self.assertEqual(1, len(errors)) self.assertEqual(4, len(errors[0].items)) self.assertIn('One.java', errors[0].items[0]) self.assertIn('Two.java', errors[0].items[1]) self.assertIn('Three.java', errors[0].items[2]) self.assertIn('Four.java', errors[0].items[3]) def testSuccess(self): """Examples of when AlertDialog.Builder should not be flagged.""" mock_input = MockInputApi() mock_input.files = [ MockFile('chrome/android/java/src/org/chromium/chrome/browser/payments/' 'AndroidPaymentApp.java', ['new UiUtils.CompatibleAlertDialogBuilder()']), MockFile('path/One.java', ['UiUtils.CompatibleAlertDialogBuilder']), MockFile('path/Two.java', ['// do not: new UiUtils.CompatibleAlertDialogBuilder']), MockFile('path/Three.java', ['/** ChromeAlertDialogBuilder', ' * replaces: new UiUtils.CompatibleAlertDialogBuilder()']), MockFile('path/PRESUBMIT.py', ['new UiUtils.CompatibleAlertDialogBuilder()']), MockFile('path/Four.java', ['new UiUtils.CompatibleAlertDialogBuilder()'], action='D'), ] errors = PRESUBMIT._CheckCompatibleAlertDialogBuilder( mock_input, MockOutputApi()) self.assertEqual(0, len(errors)) class CheckSplitCompatUtilsIdentifierName(unittest.TestCase): """Test the _CheckSplitCompatUtilsIdentifierName presubmit check.""" def testFailure(self): """ SplitCompatUtils.getIdentifierName() without a String literal is flagged. """ mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', [ 'SplitCompatUtils.getIdentifierName(foo)', 'A new line to make sure there is no duplicate error.']), MockFile('path/Two.java', ['SplitCompatUtils.getIdentifierName( foo)']), MockFile('path/Three.java', ['SplitCompatUtils.getIdentifierName(', ' bar)']), ] errors = PRESUBMIT._CheckSplitCompatUtilsIdentifierName( mock_input, MockOutputApi()) self.assertEqual(1, len(errors)) self.assertEqual(3, len(errors[0].items)) self.assertIn('One.java', errors[0].items[0]) self.assertIn('Two.java', errors[0].items[1]) self.assertIn('Three.java', errors[0].items[2]) def testSuccess(self): """ Examples of when SplitCompatUtils.getIdentifierName() should not be flagged. """ mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', [ 'SplitCompatUtils.getIdentifierName("foo")', 'A new line.']), MockFile('path/Two.java', ['SplitCompatUtils.getIdentifierName( "foo")']), MockFile('path/Three.java', ['SplitCompatUtils.getIdentifierName(', ' "bar")']), MockFile('path/Four.java', [' super(SplitCompatUtils.getIdentifierName(', '"bar"))']), ] errors = PRESUBMIT._CheckSplitCompatUtilsIdentifierName( mock_input, MockOutputApi()) self.assertEqual(0, len(errors)) if __name__ == '__main__': unittest.main()
3,928
2,236
<filename>solution/dynamic_programming_1/9095/main.py # Authored by : osy0056 # Co-authored by : - # Link : http://boj.kr/da3d10e3ebc945349d778cb06444ffb1 import sys def input(): return sys.stdin.readline().rstrip() tc = int(input()) dp = [0] * 15 dp[1] = 1 dp[2] = 2 dp[3] = 4 for i in range(4, 12): dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1] for _ in range(tc): n = int(input()) print(dp[n])
204
14,668
<filename>chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationTriggerScheduler.java // 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. package org.chromium.chrome.browser.notifications; import android.text.format.DateUtils; import androidx.annotation.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; /** * The {@link NotificationTriggerScheduler} singleton is responsible for scheduling notification * triggers to wake Chrome up so that scheduled notifications can be displayed. * Thread model: This class is to be run on the UI thread only. */ public class NotificationTriggerScheduler { /** Clock to use so we can mock time in tests. */ public static interface Clock { public long currentTimeMillis(); } private Clock mClock; // Delay by 9 minutes when we need to reschedule so we're not waking up too often but still // within a reasonable time to show scheduled notifications. Note that if the reschedule was // caused by an upgrade, we'll show all scheduled notifications on the next browser start anyway // so this is just a fallback. 9 minutes were chosen as it's also the minimum time between two // scheduled alarms via AlarmManager. @VisibleForTesting protected static final long RESCHEDULE_DELAY_TIME = DateUtils.MINUTE_IN_MILLIS * 9; private static class LazyHolder { static final NotificationTriggerScheduler INSTANCE = new NotificationTriggerScheduler(System::currentTimeMillis); } private static NotificationTriggerScheduler sInstanceForTests; @VisibleForTesting protected static void setInstanceForTests(NotificationTriggerScheduler instance) { sInstanceForTests = instance; } @CalledByNative public static NotificationTriggerScheduler getInstance() { return sInstanceForTests == null ? LazyHolder.INSTANCE : sInstanceForTests; } @VisibleForTesting protected NotificationTriggerScheduler(Clock clock) { mClock = clock; } /** * Schedules a one-off background task to wake the browser up and call into native code to * display pending notifications. If there is already a trigger scheduled earlier, this is a * nop. Otherwise the existing trigger is overwritten. * @param timestamp The timestamp of the next trigger. */ @CalledByNative @VisibleForTesting protected void schedule(long timestamp) { // Check if there is already a trigger scheduled earlier. Also check for the case where // Android did not execute our task and reschedule. long now = mClock.currentTimeMillis(); long nextTrigger = getNextTrigger(); if (timestamp < nextTrigger) { // New timestamp is earlier than existing one -> schedule new task. setNextTrigger(timestamp); nextTrigger = timestamp; } else if (nextTrigger >= now) { // Existing timestamp is earlier than new one and still in future -> do nothing. return; } // else: Existing timestamp is earlier than new one and overdue -> schedule task again. long delay = Math.max(nextTrigger - now, 0); NotificationTriggerBackgroundTask.schedule(nextTrigger, delay); } /** * Method for rescheduling a background task to wake up Chrome for processing notification * trigger events in the event of an OS upgrade or Google Play Services upgrade. */ public void reschedule() { schedule(mClock.currentTimeMillis() + RESCHEDULE_DELAY_TIME); } /** * Calls into native code to trigger all pending notifications. */ public void triggerNotifications() { NotificationTriggerSchedulerJni.get().triggerNotifications(); } /** * Method to call when Android runs the scheduled task. * @param timestamp The timestamp for which this trigger got scheduled. * @return true if we should continue waking up native code, otherwise this event got handled * already so no need to continue. */ public boolean checkAndResetTrigger(long timestamp) { if (getNextTrigger() != timestamp) return false; removeNextTrigger(); return true; } private long getNextTrigger() { return SharedPreferencesManager.getInstance().readLong( ChromePreferenceKeys.NOTIFICATIONS_NEXT_TRIGGER, Long.MAX_VALUE); } private void removeNextTrigger() { SharedPreferencesManager.getInstance().removeKey( ChromePreferenceKeys.NOTIFICATIONS_NEXT_TRIGGER); } private void setNextTrigger(long timestamp) { SharedPreferencesManager.getInstance().writeLong( ChromePreferenceKeys.NOTIFICATIONS_NEXT_TRIGGER, timestamp); } @NativeMethods interface Natives { void triggerNotifications(); } }
1,665
358
from copy import deepcopy from functools import partial from random import choice, randint, random, sample from typing import Any, Callable, List, TYPE_CHECKING, Union import numpy as np from fedot.core.composer.constraint import constraint_function from fedot.core.log import Log from fedot.core.optimisers.gp_comp.gp_operators import random_graph from fedot.core.optimisers.gp_comp.individual import Individual from fedot.core.optimisers.graph import OptGraph, OptNode from fedot.core.optimisers.opt_history import ParentOperator from fedot.core.pipelines.pipeline import Pipeline from fedot.core.utils import ComparableEnum as Enum, DEFAULT_PARAMS_STUB if TYPE_CHECKING: from fedot.core.optimisers.gp_comp.gp_optimiser import GraphGenerationParams MAX_NUM_OF_ATTEMPTS = 100 MAX_MUT_CYCLES = 5 STATIC_MUTATION_PROBABILITY = 0.7 class MutationTypesEnum(Enum): simple = 'simple' growth = 'growth' local_growth = 'local_growth' reduce = 'reduce' single_add = 'single_add', single_change = 'single_change', single_drop = 'single_drop', single_edge = 'single_edge' none = 'none' class MutationStrengthEnum(Enum): weak = 0.2 mean = 1.0 strong = 5.0 def get_mutation_prob(mut_id, node): """ Function returns mutation probability for certain node in the graph :param mut_id: MutationStrengthEnum mean weak or strong mutation :param node: root node of the graph :return mutation_prob: mutation probability """ default_mutation_prob = 0.7 if mut_id in list(MutationStrengthEnum): mutation_strength = mut_id.value mutation_prob = mutation_strength / (node.distance_to_primary_level + 1) else: mutation_prob = default_mutation_prob return mutation_prob def _will_mutation_be_applied(mutation_prob, mutation_type) -> bool: return not (random() > mutation_prob or mutation_type == MutationTypesEnum.none) def _adapt_and_apply_mutations(new_graph: Any, mutation_prob: float, types: List[Union[MutationTypesEnum, Callable]], num_mut: int, requirements, params: 'GraphGenerationParams', max_depth: int): """ Apply mutation in several iterations with specific adaptation of each graph """ is_static_mutation_type = random() < STATIC_MUTATION_PROBABILITY static_mutation_type = choice(types) mutation_names = [] for _ in range(num_mut): mutation_type = static_mutation_type \ if is_static_mutation_type else choice(types) is_custom_mutation = isinstance(mutation_type, Callable) if is_custom_mutation: new_graph = params.adapter.restore(new_graph) else: if not isinstance(new_graph, OptGraph): new_graph = params.adapter.adapt(new_graph) new_graph = _apply_mutation(new_graph=new_graph, mutation_prob=mutation_prob, mutation_type=mutation_type, is_custom_mutation=is_custom_mutation, requirements=requirements, params=params, max_depth=max_depth) mutation_names.append(str(mutation_type)) if not isinstance(new_graph, OptGraph): new_graph = params.adapter.adapt(new_graph) if is_custom_mutation: # custom mutation occurs once break return new_graph, mutation_names def _apply_mutation(new_graph: Any, mutation_prob: float, mutation_type: Union[MutationTypesEnum, Callable], is_custom_mutation: bool, requirements, params: 'GraphGenerationParams', max_depth: int): """ Apply mutation for adapted graph """ if _will_mutation_be_applied(mutation_prob, mutation_type): if mutation_type in mutation_by_type or is_custom_mutation: if is_custom_mutation: mutation_func = mutation_type else: mutation_func = mutation_by_type[mutation_type] new_graph = mutation_func(new_graph, requirements=requirements, params=params, max_depth=max_depth) elif mutation_type != MutationTypesEnum.none: raise ValueError(f'Required mutation type is not found: {mutation_type}') return new_graph def mutation(types: List[Union[MutationTypesEnum, Callable]], params: 'GraphGenerationParams', ind: Individual, requirements, log: Log, max_depth: int = None, add_to_history=True) -> Any: """ Function apply mutation operator to graph """ max_depth = max_depth if max_depth else requirements.max_depth mutation_prob = requirements.mutation_prob for _ in range(MAX_NUM_OF_ATTEMPTS): new_graph = deepcopy(ind.graph) num_mut = max(int(round(np.random.lognormal(0, sigma=0.5))), 1) new_graph, mutation_names = _adapt_and_apply_mutations(new_graph=new_graph, mutation_prob=mutation_prob, types=types, num_mut=num_mut, requirements=requirements, params=params, max_depth=max_depth) is_correct_graph = constraint_function(new_graph, params) if is_correct_graph: new_individual = Individual(new_graph) if add_to_history: new_individual = Individual(new_graph) new_individual.parent_operators = ind.parent_operators for mutation_name in mutation_names: new_individual.parent_operators.append( ParentOperator(operator_type='mutation', operator_name=str(mutation_name), parent_objects=[params.adapter.restore_as_template(ind.graph)])) return new_individual log.debug('Number of mutation attempts exceeded. ' 'Please check composer requirements for correctness.') return deepcopy(ind) def simple_mutation(graph: Any, requirements, **kwargs) -> Any: """ This type of mutation is passed over all nodes of the tree started from the root node and changes nodes’ operations with probability - 'node mutation probability' which is initialised inside the function """ def replace_node_to_random_recursive(node: Any) -> Any: if node.nodes_from: if random() < node_mutation_probability: secondary_node = OptNode(content={'name': choice(requirements.secondary), 'params': DEFAULT_PARAMS_STUB}, nodes_from=node.nodes_from) graph.update_node(node, secondary_node) for child in node.nodes_from: replace_node_to_random_recursive(child) else: if random() < node_mutation_probability: primary_node = OptNode(content={'name': choice(requirements.primary), 'params': DEFAULT_PARAMS_STUB}) graph.update_node(node, primary_node) node_mutation_probability = get_mutation_prob(mut_id=requirements.mutation_strength, node=graph.root_node) replace_node_to_random_recursive(graph.root_node) return graph def single_edge_mutation(graph: Any, max_depth, *args, **kwargs): old_graph = deepcopy(graph) for _ in range(MAX_NUM_OF_ATTEMPTS): if len(graph.nodes) < 2 or graph.depth > max_depth: return graph source_node, target_node = sample(graph.nodes, 2) nodes_not_cycling = (target_node.descriptive_id not in [n.descriptive_id for n in source_node.ordered_subnodes_hierarchy()]) if nodes_not_cycling and (target_node.nodes_from is None or source_node not in target_node.nodes_from): graph.operator.connect_nodes(source_node, target_node) break if graph.depth > max_depth: return old_graph return graph def _add_intermediate_node(graph: Any, requirements, params, node_to_mutate): # add between node and parent candidates = params.advisor.propose_parent(str(node_to_mutate.content['name']), [str(n.content['name']) for n in node_to_mutate.nodes_from], requirements.secondary) if len(candidates) == 0: return graph new_node = OptNode(content={'name': choice(candidates), 'params': DEFAULT_PARAMS_STUB}) new_node.nodes_from = node_to_mutate.nodes_from node_to_mutate.nodes_from = [new_node] graph.nodes.append(new_node) return graph def _add_separate_parent_node(graph: Any, requirements, params, node_to_mutate): # add as separate parent candidates = params.advisor.propose_parent(str(node_to_mutate.content['name']), None, requirements.primary) if len(candidates) == 0: return graph for iter_num in range(randint(1, 3)): if iter_num == len(candidates): break new_node = OptNode(content={'name': choice(candidates), 'params': DEFAULT_PARAMS_STUB}) if node_to_mutate.nodes_from: node_to_mutate.nodes_from.append(new_node) else: node_to_mutate.nodes_from = [new_node] graph.nodes.append(new_node) return graph def _add_as_child(graph: Any, requirements, params, node_to_mutate): # add as child new_node = OptNode(content={'name': choice(requirements.secondary), 'params': DEFAULT_PARAMS_STUB}) new_node.nodes_from = [node_to_mutate] graph.operator.actualise_old_node_children(node_to_mutate, new_node) graph.nodes.append(new_node) return graph def single_add_mutation(graph: Any, requirements, params, max_depth, *args, **kwargs): """ Add new node between two sequential existing modes """ if graph.depth >= max_depth: # add mutation is not possible return graph node_to_mutate = choice(graph.nodes) single_add_strategies = [_add_as_child, _add_separate_parent_node] if node_to_mutate.nodes_from: single_add_strategies.append(_add_intermediate_node) strategy = choice(single_add_strategies) result = strategy(graph, requirements, params, node_to_mutate) return result def single_change_mutation(graph: Any, requirements, params, *args, **kwargs): """ Add new node between two sequential existing modes """ node = choice(graph.nodes) nodes_from = node.nodes_from candidates = requirements.secondary if node.nodes_from else requirements.primary if params.advisor: candidates = params.advisor.propose_change(current_operation_id=str(node.content['name']), possible_operations=candidates) if len(candidates) == 0: return graph node_new = OptNode(content={'name': choice(candidates), 'params': DEFAULT_PARAMS_STUB}) node_new.nodes_from = nodes_from graph.nodes = [node_new if n == node else n for n in graph.nodes] graph.operator.actualise_old_node_children(node, node_new) return graph def single_drop_mutation(graph: Any, *args, **kwargs): """ Add new node between two sequential existing modes """ node_to_del = choice(graph.nodes) # TODO replace as workaround node_name = node_to_del.content['name'] if (hasattr(node_name, 'operation_type') and 'data_source' in node_name.operation_type): nodes_to_delete = \ [n for n in graph.nodes if node_name.operation_type in n.descriptive_id and n.descriptive_id.count('data_source') == 1] for child_node in nodes_to_delete: graph.delete_node(child_node) graph.delete_node(node_to_del) else: graph.delete_node(node_to_del) if node_to_del.nodes_from: childs = graph.operator.node_children(node_to_del) for child in childs: if child.nodes_from: child.nodes_from.extend(node_to_del.nodes_from) else: child.nodes_from = node_to_del.nodes_from return graph def _tree_growth(graph: Any, requirements, params, max_depth: int, local_growth=True): """ This mutation selects a random node in a tree, generates new subtree, and replaces the selected node's subtree. """ random_layer_in_graph = randint(0, graph.depth - 1) node_from_graph = choice(graph.operator.nodes_from_layer(random_layer_in_graph)) if local_growth: is_primary_node_selected = (not node_from_graph.nodes_from) or ( node_from_graph.nodes_from and node_from_graph != graph.root_node and randint(0, 1)) else: is_primary_node_selected = \ randint(0, 1) and \ not graph.operator.distance_to_root_level(node_from_graph) < max_depth if is_primary_node_selected: new_subtree = OptNode(content={'name': choice(requirements.primary), 'params': DEFAULT_PARAMS_STUB}) else: if local_growth: max_depth = node_from_graph.distance_to_primary_level else: max_depth = max_depth - graph.operator.distance_to_root_level(node_from_graph) new_subtree = random_graph(params=params, requirements=requirements, max_depth=max_depth).root_node graph.update_subtree(node_from_graph, new_subtree) return graph def growth_mutation(graph: Any, requirements, params, max_depth: int, local_growth=True) -> Any: """ This mutation adds new nodes to the graph (just single node between existing nodes or new subtree). :param local_growth: if true then maximal depth of new subtree equals depth of tree located in selected random node, if false then previous depth of selected node doesn't affect to new subtree depth, maximal depth of new subtree just should satisfy depth constraint in parent tree """ if random() > 0.5: # simple growth (one node can be added) return single_add_mutation(graph, requirements, params, max_depth) else: # advanced growth (several nodes can be added) return _tree_growth(graph, requirements, params, max_depth, local_growth) def reduce_mutation(graph: OptGraph, requirements, **kwargs) -> OptGraph: """ Selects a random node in a tree, then removes its subtree. If the current arity of the node's parent is more than the specified minimal arity, then the selected node is also removed. Otherwise, it is replaced by a random primary node. """ if len(graph.nodes) == 1: return graph nodes = [node for node in graph.nodes if node is not graph.root_node] node_to_del = choice(nodes) children = graph.operator.node_children(node_to_del) is_possible_to_delete = all([len(child.nodes_from) - 1 >= requirements.min_arity for child in children]) if is_possible_to_delete: graph.delete_subtree(node_to_del) else: primary_node = OptNode(content={'name': choice(requirements.primary), 'params': DEFAULT_PARAMS_STUB}) graph.update_subtree(node_to_del, primary_node) return graph mutation_by_type = { MutationTypesEnum.simple: simple_mutation, MutationTypesEnum.growth: partial(growth_mutation, local_growth=False), MutationTypesEnum.local_growth: partial(growth_mutation, local_growth=True), MutationTypesEnum.reduce: reduce_mutation, MutationTypesEnum.single_add: single_add_mutation, MutationTypesEnum.single_edge: single_edge_mutation, MutationTypesEnum.single_drop: single_drop_mutation, MutationTypesEnum.single_change: single_change_mutation, }
6,952
389
<filename>ip/Pmods/PmodKYPD_v1_0/drivers/PmodKYPD_v1_0/src/PmodKYPD.c<gh_stars>100-1000 /******************************************************************************/ /* */ /* PmodKYPD.c -- Driver for the Pmod Keypad */ /* */ /******************************************************************************/ /* Author: <NAME> */ /* Copyright 2016, Digilent Inc. */ /******************************************************************************/ /* File Description: */ /* */ /* This library contains basic functions to read the states of the keys of */ /* the Digilent's PmodKYPD */ /* */ /******************************************************************************/ /* Revision History: */ /* */ /* 06/08/2016(MikelS): Created */ /* 08/17/2017(artvvb): Validated for Vivado 2015.4 */ /* 08/30/2017(artvvb): Validated for Vivado 2016.4 */ /* Added Multiple keypress error detection */ /* 01/27/2018(atangzwj): Validated for Vivado 2017.4 */ /* */ /******************************************************************************/ /***************************** Include Files ****************************/ #include "PmodKYPD.h" /*************************** Function Prototypes ************************/ u8 KYPD_lookupShiftPattern(u16 shift); /************************** Function Definitions ************************/ /* -------------------------------------------------------------------- */ /*** void KYPD_begin(PmodKYPD *InstancePtr, u32 GPIO_Address) ** ** Parameters: ** InstancePtr: A PmodKYPD device to start ** GPIO_Address: The Base address of the PmodKYPD GPIO ** ** Return Value: ** none ** ** Description: ** Initialize the PmodKYPD driver device */ void KYPD_begin(PmodKYPD *InstancePtr, u32 GPIO_Address) { InstancePtr->GPIO_addr = GPIO_Address; // Set tri-state register, lower 4 pins are column outputs, upper 4 pins are // row inputs Xil_Out32(InstancePtr->GPIO_addr + 4, 0xF0); InstancePtr->keytable_loaded = FALSE; } /* -------------------------------------------------------------------- */ /*** void KYPD_setCols(PmodKYPD *InstancePtr, u32 cols) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** cols: column bits to set the output pins to ** ** Return Value: ** none ** ** Description: ** Set the column output pins */ void KYPD_setCols(PmodKYPD *InstancePtr, u32 cols) { Xil_Out32(InstancePtr->GPIO_addr, cols & 0xF); } /* -------------------------------------------------------------------- */ /*** u32 KYPD_getRows(PmodKYPD *InstancePtr) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** ** Return Value: ** rows: row bits read from the input pins ** ** Description: ** Read the row input pins */ u32 KYPD_getRows(PmodKYPD *InstancePtr) { return (Xil_In32(InstancePtr->GPIO_addr) >> 4) & 0xF; } /* -------------------------------------------------------------------- */ /*** u16 KYPD_getKeyStates(PmodKYPD *InstancePtr) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** ** Return Value: ** keystate: 16 bits, each represents the status of one key (active high). ** Each set of four keys on a single row are grouped together. ** ** Description: ** Capture the state of each key on the keypad ** ** Errors: ** Multiple key presses may not be detected properly - it can be detected ** that multiple keys are pressed, but not which. */ u16 KYPD_getKeyStates(PmodKYPD *InstancePtr) { u32 rows, cols; u16 keystate; u16 shift[4] = {0, 0, 0, 0}; // Test each column combination, this will help to detect when multiple keys // in the same row are pressed. for (cols = 0; cols < 16; cols++) { KYPD_setCols(InstancePtr, cols); rows = KYPD_getRows(InstancePtr); // Group bits from each individual row shift[0] = (shift[0] << 1) | (rows & 0x1); shift[1] = (shift[1] << 1) | (rows & 0x2) >> 1; shift[2] = (shift[2] << 1) | (rows & 0x4) >> 2; shift[3] = (shift[3] << 1) | (rows & 0x8) >> 3; } // Translate shift patterns for each row into button presses. keystate = 0; keystate |= KYPD_lookupShiftPattern(shift[0]); keystate |= KYPD_lookupShiftPattern(shift[1]) << 4; keystate |= KYPD_lookupShiftPattern(shift[2]) << 8; keystate |= KYPD_lookupShiftPattern(shift[3]) << 12; return keystate; } /* -------------------------------------------------------------------- */ /*** void KYPD_loadKeyTable(PmodKYPD *InstancePtr, char keytable[16]) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** keytable: A 16-character array containing the characters that ** represent each key. ** ** Return Value: ** None ** ** Description: ** Set the keytable array so that KYPD_getKeyPressed will return will ** return the human-readable character that the pressed key represents */ void KYPD_loadKeyTable(PmodKYPD *InstancePtr, u8 keytable[16]) { int i; for (i = 0; i < 16; i++) { // Hard copy string into device struct InstancePtr->keytable[i] = keytable[i]; } InstancePtr->keytable_loaded = TRUE; } /* -------------------------------------------------------------------- */ /*** XStatus KYPD_getKeyPressed(PmodKYPD *InstancePtr, u16 keystate, char *cptr) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** keystate: Status of each key, pressed indicated by a '1' in that ** key's bit position. ** Bit positions correspond with character positions in ** InstancePtr->keytable. ** cptr: Address to return additional information when a single key ** is pressed. ** ** Return Value: ** status: ** XST_SUCCESS when only one key is pressed. ** cptr is loaded with a human-readable character when keytable is ** loaded. ** cptr is loaded with the key index when keytable is not loaded. ** KYPD_MULTI_KEY when multiple keys are pressed. ** KYPD_NO_KEY when no keys are pressed. ** ** Errors: ** KYPD_MULTI_KEY - cannot differentiate which keys are pressed in some ** multi-key cases. ** ** Description: ** Set the keytable array so that KYPD_getKeyPressed will return will ** return the human-readable character that the pressed key represents */ u32 KYPD_getKeyPressed(PmodKYPD *InstancePtr, u16 keystate, u8 *cptr) { u8 i = 0; u8 ci = 0; u32 count = 0; for (i = 0; i < 16; i++) { // If key reading is 0 (pressed) if (0x1 == (keystate & 0x1)) { count++; // Count the number of pressed keys ci = i; } // Increment through keystate bits keystate >>= 1; } if (count > 1) { // Multiple keys pressed, cannot differentiate which return KYPD_MULTI_KEY; } else if (count == 0) { // No key pressed return KYPD_NO_KEY; } else { // One key pressed if (InstancePtr->keytable_loaded == TRUE) *cptr = InstancePtr->keytable[ci]; // Return human-readable key label else *cptr = ci; // Return index of pressed key return KYPD_SINGLE_KEY; } } /* -------------------------------------------------------------------- */ /*** u8 KYPD_lookupShiftPattern(u16 shift) ** ** Parameters: ** InstancePtr: A PmodKYPD device to use ** shift: A 16-bit array containing the read bits of a single row ** received for each column pattern. ** ** Return Value: ** buttons: The button presses detected on this row. ** ** Description: ** Translates reading-pattern detected on a single row into the buttons ** pressed on that row. */ u8 KYPD_lookupShiftPattern(u16 shift) { // Attempt to determine which keys are pressed in this row // These patterns were determined experimentally switch(shift) { case 0xFFFF: return 0x0; case 0x00FF: return 0x1; case 0x0F0F: return 0x2; case 0x0FFF: return 0x3; case 0x3333: return 0x4; case 0x33FF: return 0x5; case 0x3F3F: return 0x6; case 0x033F: return 0x7; case 0x5555: return 0x8; case 0x55FF: return 0x9; case 0x5F5F: return 0xA; case 0x055F: return 0xB; case 0x7777: return 0xC; case 0x1177: return 0xD; case 0x1717: return 0xE; case 0x177F: return 0xF; default: return 0x0; } }
3,953
1,262
<filename>metacat-connector-s3/src/main/java/com/netflix/metacat/connector/s3/dao/DatabaseDao.java /* * Copyright 2016 Netflix, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.metacat.connector.s3.dao; import com.netflix.metacat.common.dto.Pageable; import com.netflix.metacat.common.dto.Sort; import com.netflix.metacat.connector.s3.model.Database; import java.util.List; /** * Database DAO. */ public interface DatabaseDao extends BaseDao<Database> { /** * Get database for the given source and database name. * @param sourceName source name * @param databaseName database name * @return Database */ Database getBySourceDatabaseName(String sourceName, String databaseName); /** * Get list of databases for the given source name and database names. * @param sourceName source name * @param databaseNames list of database names * @return list of databases */ List<Database> getBySourceDatabaseNames(String sourceName, List<String> databaseNames); /** * Get list of databases for the given source name and database name prefix. * @param sourceName source name * @param databaseNamePrefix database name prefix * @param sort sort * @param pageable pageable * @return list of databases */ List<Database> searchBySourceDatabaseName(String sourceName, String databaseNamePrefix, Sort sort, Pageable pageable); }
631
3,269
<gh_stars>1000+ // Time: O(n) // Space: O(1) class Solution { public: int balancedString(string s) { unordered_map<int, int> count; for (const auto& c : s) { ++count[c]; } int result = s.length(); int left = 0; for (int right = 0; right < s.length(); ++right) { --count[s[right]]; while (left < s.length() && all_of(count.cbegin(), count.cend(), [&s](const auto& kvp) { return kvp.second <= s.length() / 4; })) { result = min(result, right - left + 1); ++count[s[left++]]; } } return result; } };
435
1,044
__test__ = False if __name__ == "__main__": import eventlet eventlet.monkey_patch(builtins=True, os=True) with open(__file__, mode="rt", buffering=16): pass print("pass")
82
918
/* * Copyright (c) 2018-2019 <NAME> * * Distributed under the MIT License. See LICENSE.md at * https://github.com/LiquidPlayer/LiquidCore for terms and conditions. */ #ifndef V82JSC_Message_h #define V82JSC_Message_h #include "Value.h" namespace V82JSC { struct Message : Value { v8::Persistent<v8::Script> m_script; static void Constructor(Message *obj) {} static int Destructor(HeapContext& context, Message *obj) { int freed=0; freed += SmartReset<v8::Script>(context, obj->m_script); return freed + Value::Destructor(context, obj); } static Message* New(IsolateImpl* iso, JSValueRef exception, v8::Local<v8::Script> script); void CallHandlers(); }; struct StackTrace : HeapObject { v8::Persistent<v8::Script> m_script; JSObjectRef m_error; JSObjectRef m_stack_frame_array; static void Constructor(StackTrace *obj) {} static int Destructor(HeapContext& context, StackTrace *obj) { if (obj->m_error) JSValueUnprotect(obj->GetNullContext(), obj->m_error); if (obj->m_stack_frame_array) JSValueUnprotect(obj->GetNullContext(), obj->m_stack_frame_array); int freed=0; freed += SmartReset<v8::Script>(context, obj->m_script); return freed; } static v8::Local<v8::StackTrace> New(IsolateImpl* iso, v8::Local<v8::Value> error, v8::Local<v8::Script> script); }; struct StackFrame : HeapObject { v8::Persistent<v8::String> m_function_name; v8::Persistent<v8::String> m_script_name; v8::Persistent<v8::StackTrace> m_stack_trace; int m_line_number; int m_column_number; bool m_is_eval; static void Constructor(StackFrame *obj) {} static int Destructor(HeapContext& context, StackFrame *obj) { int freed=0; freed += SmartReset<v8::String>(context, obj->m_function_name); freed += SmartReset<v8::String>(context, obj->m_script_name); freed += SmartReset<v8::StackTrace>(context, obj->m_stack_trace); return freed; } }; } /* namespace V82JSC */ #endif /* V82JSC_Message_h */
976
1,374
<filename>candy-generator/src/main/java/org/jsweet/util/Tree.java /* * TypeScript definitions to Java translator - http://www.jsweet.org * Copyright (C) 2015 CINCHEO SAS <<EMAIL>> * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jsweet.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import java.util.stream.Collectors; /** * A tree is an element container that can have several child trees. * * @author <NAME> * * @param <E> * the type of the element attached to the tree * @param <ID> * the type of the id attached to the tree */ public class Tree<E, ID> { private E element; private ID id; private Tree<E, ID> parentTree; private List<Tree<E, ID>> childTrees = new ArrayList<Tree<E, ID>>(); /** * A default scanner, to be overriden to perform recursive operations on a * tree. * * @author <NAME> */ public static class Scanner<E, ID> { protected Stack<Tree<E, ID>> stack = new Stack<>(); public final void scan(Tree<E, ID> tree) { if (!enter(tree)) { return; } stack.push(tree); try { for (Tree<E, ID> childTree : tree.getChildTrees()) { scan(childTree); } } finally { stack.pop(); exit(tree); } } protected boolean enter(Tree<E, ID> tree) { return true; } protected void exit(Tree<E, ID> tree) { } } /** * A helper to match a tree or a path on the to-stringed values of its * elements. * * @author <NAME> */ public static class Matcher { protected String[] expressions; /** * Each expression is a matcher for an element in the tested path. * <p> * Not operators are allowed with expressions starting with !. * <p> * A path will match if all the first elements match each expressions of * the matcher. */ public Matcher(String... expressions) { this.expressions = expressions; } /** * Returns true if this matcher matches the given tree (i.e. if one path * starting from that tree matches). */ public boolean matches(Tree<?, ?> tree) { return matches(Arrays.asList(this.expressions), tree); } private static boolean matches(List<String> expressions, Tree<?, ?> tree) { if (expressions.isEmpty()) { return true; } String expr = expressions.get(0); if (expr.startsWith("!")) { expr = expr.substring(1); if (("" + tree.getElement()).equals(expr)) { return false; } } else { if (!("" + tree.getElement()).equals(expr)) { return false; } } if (tree.getChildTrees().isEmpty()) { return true; } for (Tree<?, ?> child : tree.getChildTrees()) { if (matches(expressions.subList(1, expressions.size()), child)) { return true; } } return false; } /** * Returns true if this matcher matches the given path. */ public boolean matches(List<?> path) { return matches(Arrays.asList(this.expressions), path); } private static boolean matches(List<String> expressions, List<?> path) { if (expressions.isEmpty()) { return true; } if (path.isEmpty()) { return false; } String expr = expressions.get(0); if (expr.startsWith("!")) { expr = expr.substring(1); if (("" + path.get(0)).equals(expr)) { return false; } } else { if (!("" + path.get(0)).equals(expr)) { return false; } } return matches(expressions.subList(1, expressions.size()), path.subList(1, path.size())); } } /** * Constructs a tree with a single element (no parent, no children). */ public Tree(E element) { this.element = element; } /** * Gets the id attached to this tree (optional). */ public ID getID() { return id; } /** * Sets the id attached to this tree. */ public void setID(ID id) { this.id = id; } /** * Add some children elements to this tree. * * @param element * the element to add children to (root node if null) * @param childElements * the elements to add to the parent */ public void addChildElements(List<E> childElements) { for (E child : childElements) { Tree<E, ID> childTree = new Tree<E, ID>(child); childTree.parentTree = this; this.childTrees.add(childTree); } } public void clearChildTrees() { this.childTrees.clear(); } public void addChildTrees(List<Tree<E, ID>> childTrees) { for (Tree<E, ID> childTree : childTrees) { childTree.parentTree = this; this.childTrees.add(childTree); } } public void addChildTree(Tree<E, ID> childTree) { childTree.parentTree = this; this.childTrees.add(childTree); } /** * Adds a child to this tree (add the end of the current children). */ public Tree<E, ID> addChildElement(E childElement) { Tree<E, ID> childTree = new Tree<E, ID>(childElement); childTree.parentTree = this; this.childTrees.add(childTree); return childTree; } /** * Gets the parent tree of this tree. */ public Tree<E, ID> getParentTree() { return parentTree; } /** * Gets the parent of this tree. */ public E getParentElement() { return parentTree != null ? parentTree.element : null; } /** * Gets the children of this tree. */ public List<Tree<E, ID>> getChildTrees() { return this.childTrees; } /** * Gets the child trees that match the given element. */ public List<Tree<E, ID>> getChildTrees(E e) { return childTrees.stream().filter(t -> e.equals(t.element)).collect(Collectors.toList()); } /** * Get the elements attached to the child trees. */ public List<E> getChildElements() { return childTrees.stream().map(t -> t.element).collect(Collectors.toList()); } /** * Gets the element contained in this tree. */ public E getElement() { return this.element; } /** * Sets the element contained in this tree; */ public void setElement(E element) { this.element = element; } /** * Adds a path to the current tree. */ final public Tree<E, ID> addPath(List<E> path) { if (path.size() == 0) { return this; } List<E> childElements = getChildElements(); int index = childElements.indexOf(path.get(0)); Tree<E, ID> nextTree; if (index < 0) { nextTree = addChildElement(path.get(0)); } else { nextTree = getChildTrees().get(index); } return nextTree.addPath(path.subList(1, path.size())); } public boolean isLeaf() { return childTrees.isEmpty(); } @Override public String toString() { final StringBuffer output = new StringBuffer(); new Tree.Scanner<E, ID>() { protected boolean enter(Tree<E, ID> tree) { output.append("["); output.append(tree.getElement()); if (tree.getID() != null) { output.append("*"); } return true; } protected void exit(Tree<E, ID> tree) { output.append("]"); } }.scan(this); return output.toString(); } public List<List<Tree<E, ID>>> findElement(final E element) { final List<List<Tree<E, ID>>> result = new ArrayList<>(); final List<Tree<E, ID>> path = new ArrayList<>(); new Tree.Scanner<E, ID>() { protected boolean enter(Tree<E, ID> tree) { if (element.equals(tree.getElement())) { path.clear(); for (Tree<E, ID> t : stack) { path.add(t); } path.add(tree); result.add(new ArrayList<>(path)); } return true; } }.scan(this); return result; } public List<Tree<E, ID>> findFirstElement(final E element) { final List<Tree<E, ID>> path = new ArrayList<>(); new Tree.Scanner<E, ID>() { protected boolean enter(Tree<E, ID> tree) { if (!path.isEmpty()) { return false; } if (element.equals(tree.getElement())) { path.clear(); for (Tree<E, ID> t : stack) { path.add(t); } path.add(tree); return false; } return true; } }.scan(this); return path; } public List<Tree<E, ID>> find(final ID id) { final List<Tree<E, ID>> path = new ArrayList<>(); new Tree.Scanner<E, ID>() { protected boolean enter(Tree<E, ID> tree) { if (!path.isEmpty()) { return false; } if (id.equals(tree.getID())) { for (Tree<E, ID> t : stack) { path.add(t); } path.add(tree); return false; } return true; } }.scan(this); return path; } public static List<String> toStringPath(List<Tree<String, File>> path) { return path.stream().map(t -> t.getElement()).collect(Collectors.toList()); } }
3,522
1,118
<gh_stars>1000+ {"name":{"common":"Botswana","official":"Republic of Botswana","native":{"eng":{"common":"Botswana","official":"Republic of Botswana"},"tsn":{"common":"Botswana","official":"Lefatshe la Botswana"}}},"demonym":"Motswana","capital":"Gaborone","iso_3166_1_alpha2":"BW","iso_3166_1_alpha3":"BWA","iso_3166_1_numeric":"072","currency":{"BWP":{"iso_4217_code":"BWP","iso_4217_numeric":72,"iso_4217_name":"Pula","iso_4217_minor_unit":2}},"tld":[".bw"],"alt_spellings":["BW","Republic of Botswana","Lefatshe la Botswana"],"languages":{"eng":"English","tsn":"Tswana"},"geo":{"continent":{"AF":"Africa"},"postal_code":false,"latitude":"22 00 S","latitude_desc":"-22.186752319335938","longitude":"24 00 E","longitude_desc":"23.81494140625","max_latitude":"-17.833333","max_longitude":"29.016667","min_latitude":"-26.833333","min_longitude":"20","area":582000,"region":"Africa","subregion":"Southern Africa","world_region":"EMEA","region_code":"002","subregion_code":"018","landlocked":true,"borders":["NAM","ZAF","ZMB","ZWE"],"independent":"Yes"},"dialling":{"calling_code":["267"],"national_prefix":null,"national_number_lengths":[7],"national_destination_code_lengths":[2],"international_prefix":"00"},"extra":{"geonameid":933860,"edgar":"B1","itu":"BOT","marc":"bs","wmo":"BC","ds":"BW","fifa":"BOT","fips":"BC","gaul":35,"ioc":"BOT","cowc":"BOT","cown":571,"fao":20,"imf":616,"ar5":"MAF","address_format":null,"eu_member":null,"data_protection":"Other","vat_rates":null,"emoji":"🇧🇼"}}
527
1,838
//---------------------------------------------------------------------// // Wrapper header file that excludes Checked-C-specific declarations // // if the compilation is not for Checked C, or if is for Checked C // // but the implicit inclusion of checked header files is disabled. // ///////////////////////////////////////////////////////////////////////// #if !defined __checkedc || defined NO_IMPLICIT_INCLUDE_CHECKED_HDRS // C implementations may not support the C11 threads package or even the // macro that says C11 threads are not supported. #if defined __has_include_next #if __has_include_next(<threads.h>) #ifdef __checkedc #pragma CHECKED_SCOPE push #pragma CHECKED_SCOPE off #endif #include_next <threads.h> #ifdef __checkedc #pragma CHECKED_SCOPE pop #endif #endif // has threads.h #endif // defined __has_include_next #else // checkedc && implicit include enabled #include <threads_checked.h> #endif
266
578
<reponame>gddhatdisqus/Hive-JSON-Serde-tmp /*======================================================================* * Copyright (c) 2011, OpenX Technologies, Inc. All rights reserved. * * * * Licensed under the New BSD License (the "License"); you may not use * * this file except in compliance with the License. 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. See accompanying LICENSE file. * *======================================================================*/ package org.openx.data.jsonserde.objectinspector.primitive; import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableDoubleObjectInspector; import org.apache.hadoop.hive.serde2.io.DoubleWritable; /** * * @author rcongiu */ public class JavaStringDoubleObjectInspector extends AbstractPrimitiveJavaObjectInspector implements SettableDoubleObjectInspector { public JavaStringDoubleObjectInspector() { super(TypeEntryShim.doubleType); } @Override public Object getPrimitiveWritableObject(Object o) { if(o == null) return null; if(o instanceof String) { return new DoubleWritable(Double.parseDouble((String)o)); } else { return new DoubleWritable((Double) o); } } @Override public double get(Object o) { if(o instanceof String) { return Double.parseDouble((String)o); } else { return (Double) o; } } @Override public Object getPrimitiveJavaObject(Object o) { return get(o); } @Override public Object create(double value) { return value; } @Override public Object set(Object o, double value) { return value; } }
828
1,144
<gh_stars>1000+ package de.metas.material.planning.interceptor; import de.metas.material.planning.IResourceDAO; import de.metas.product.IProductDAO; import de.metas.product.ResourceId; import de.metas.util.Services; import org.adempiere.ad.modelvalidator.annotations.Interceptor; import org.adempiere.ad.modelvalidator.annotations.ModelChange; import org.compiere.model.I_S_Resource; import org.compiere.model.ModelValidator; import org.springframework.stereotype.Component; /* * #%L * metasfresh-material-planning * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Interceptor(I_S_Resource.class) @Component public class S_Resource { /** * Creates a resource product.<br> * Note that it's important to create it <b>after</b> new, because otherwise the given {@code resource}'s {@code Value} mit still be {@code null} (https://github.com/metasfresh/metasfresh/issues/1580) */ @ModelChange(timings = ModelValidator.TYPE_AFTER_NEW) public void createResourceProduct(final I_S_Resource resource) { Services.get(IResourceDAO.class).onResourceChanged(resource); } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE) public void updateResourceProduct(final I_S_Resource resource) { Services.get(IResourceDAO.class).onResourceChanged(resource); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteResourceProduct(final I_S_Resource resource) { final ResourceId resourceId = ResourceId.ofRepoId(resource.getS_Resource_ID()); Services.get(IProductDAO.class).deleteProductByResourceId(resourceId); } }
701
3,850
<reponame>dodgex/androidannotations package org.androidannotations.preference; public class R { public static final class xml { public static final int preferences = 0x7f06000a; } public static final class string { public static final int myKey = <KEY>; } }
85
6,036
/** * Copyright (c) 2016-present, Facebook, 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. */ /* Modifications Copyright (c) Microsoft. */ #include "core/providers/cpu/nn/batch_norm.h" #include "core/providers/cpu/nn/batch_norm_helper.h" namespace onnxruntime { // spec: https://github.com/onnx/onnx/blob/master/docs/Operators.md#BatchNormalization ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 7, 8, float, KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()), BatchNorm<float>); ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 7, 8, double, KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<double>()), BatchNorm<double>); // We alias the running mean to the mean so it stays preserved across multiple batches ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 9, 13, float, KernelDefBuilder().Alias(3, 1).Alias(4, 2).TypeConstraint("T", DataTypeImpl::GetTensorType<float>()), BatchNorm<float>); ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 9, 13, double, KernelDefBuilder().Alias(3, 1).Alias(4, 2).TypeConstraint("T", DataTypeImpl::GetTensorType<double>()), BatchNorm<double>); ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 14, 14, float, KernelDefBuilder() .Alias(3, 1) .Alias(4, 2) // ORT 1.8 was shipped with just the "T" type constraint and // we want to maintain backwards compatibility for // the hash and hence just use "T" for the hash generation .FixedTypeConstraintForHash("T", {DataTypeImpl::GetTensorType<float>()}) .TypeConstraint("T", DataTypeImpl::GetTensorType<float>()) .TypeConstraint("U", DataTypeImpl::GetTensorType<float>()), BatchNorm<float>); ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(BatchNormalization, 14, 14, double, KernelDefBuilder() .Alias(3, 1) .Alias(4, 2) // ORT 1.8 was shipped with just the "T" type constraint and // we want to maintain backwards compatibility for // the hash and hence just use "T" for the hash generation .FixedTypeConstraintForHash("T", {DataTypeImpl::GetTensorType<double>()}) .TypeConstraint("T", DataTypeImpl::GetTensorType<double>()) .TypeConstraint("U", DataTypeImpl::GetTensorType<double>()), BatchNorm<double>); ONNX_CPU_OPERATOR_TYPED_KERNEL(BatchNormalization, 15, float, KernelDefBuilder() .Alias(3, 1) .Alias(4, 2) .TypeConstraint("T", DataTypeImpl::GetTensorType<float>()) .TypeConstraint("T1", DataTypeImpl::GetTensorType<float>()) .TypeConstraint("T2", DataTypeImpl::GetTensorType<float>()), BatchNorm<float>); ONNX_CPU_OPERATOR_TYPED_KERNEL(BatchNormalization, 15, double, KernelDefBuilder() .Alias(3, 1) .Alias(4, 2) .TypeConstraint("T", DataTypeImpl::GetTensorType<double>()) .TypeConstraint("T1", DataTypeImpl::GetTensorType<double>()) .TypeConstraint("T2", DataTypeImpl::GetTensorType<double>()), BatchNorm<double>); } // namespace onnxruntime
2,806
345
<reponame>stefangomez/botbuilder-js<filename>libraries/teams-scenarios/integrationBot/recordings/20191030203555603-reply-integrationBot.json {"scope":"https://smba.trafficmanager.net:443","method":"POST","path":"/amer/v3/conversations","body":{"isGroup":true,"activity":{"type":"message","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","content":{"actions":[{"type":"Action.Submit","title":"Submit","data":{"submitLocation":"messagingExtensionSubmit"}}],"body":[{"text":"Adaptive Card from Task Module","type":"TextBlock","weight":"bolder"},{"text":"","type":"TextBlock","id":"Question"},{"id":"Answer","placeholder":"Answer here...","type":"Input.Text"},{"choices":[{"title":"","value":""},{"title":"","value":""},{"title":"","value":""}],"id":"Choices","isMultiSelect":true,"style":"expanded","type":"Input.ChoiceSet"}],"type":"AdaptiveCard","version":"1.0"}}]},"channelData":{"channel":{"id":"19:<EMAIL>"}}},"status":201,"response":{"id":"19:<EMAIL>;messageid=1572467755453","activityId":"1:1CI01BT6FVaEEoYB6ObZRwpz2kfEw79BhvYdhKqSp_UI"},"rawHeaders":["Content-Length","143","Content-Type","application/json; charset=utf-8","Server","Microsoft-HTTPAPI/2.0","Date","Wed, 30 Oct 2019 20:35:55 GMT","Connection","close"],"reqheaders":{"accept":"application/json, text/plain, */*","authorization":"Bearer <KEY>","cookie":"","content-type":"application/json; charset=utf-8","content-length":729,"host":"smba.trafficmanager.net"}}
436
304
package io.jenkins.plugins.analysis.core.util; import org.jenkinsci.plugins.workflow.actions.WarningAction; import org.jenkinsci.plugins.workflow.graph.FlowNode; import hudson.model.Result; import hudson.model.Run; /** * {@link StageResultHandler} that sets the overall build result of the {@link Run} and annotates the given Pipeline * step with a {@link WarningAction}. */ public class PipelineResultHandler implements StageResultHandler { private final Run<?, ?> run; private final FlowNode flowNode; /** * Creates a new instance of {@link io.jenkins.plugins.analysis.core.util.PipelineResultHandler}. * * @param run * the run to set the result for * @param flowNode * the flow node to add a warning to */ public PipelineResultHandler(final Run<?, ?> run, final FlowNode flowNode) { this.run = run; this.flowNode = flowNode; } @Override public void setResult(final Result result, final String message) { run.setResult(result); WarningAction existing = flowNode.getPersistentAction(WarningAction.class); if (existing == null || existing.getResult().isBetterThan(result)) { flowNode.addOrReplaceAction(new WarningAction(result).withMessage(message)); } } }
462
1,644
<filename>core/src/main/java/google/registry/export/BackupDatastoreAction.java // Copyright 2018 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.export; import static google.registry.export.CheckBackupAction.enqueuePollTask; import static google.registry.request.Action.Method.POST; import com.google.common.flogger.FluentLogger; import google.registry.config.RegistryConfig; import google.registry.export.datastore.DatastoreAdmin; import google.registry.export.datastore.Operation; import google.registry.request.Action; import google.registry.request.HttpException.InternalServerErrorException; import google.registry.request.Response; import google.registry.request.auth.Auth; import javax.inject.Inject; /** * Action to trigger a Datastore backup job that writes a snapshot to Google Cloud Storage. * * <p>This is the first step of a four step workflow for exporting snapshots, with each step calling * the next upon successful completion: * * <ol> * <li>The snapshot is exported to Google Cloud Storage (this action). * <li>The {@link CheckBackupAction} polls until the export is completed. * <li>The {@link UploadDatastoreBackupAction} uploads the data from GCS to BigQuery. * <li>The {@link UpdateSnapshotViewAction} updates the view in latest_datastore_export. * </ol> */ @Action( service = Action.Service.BACKEND, path = BackupDatastoreAction.PATH, method = POST, automaticallyPrintOk = true, auth = Auth.AUTH_INTERNAL_OR_ADMIN) public class BackupDatastoreAction implements Runnable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Queue to use for enqueuing the task that will actually launch the backup. */ static final String QUEUE = "export-snapshot"; // See queue.xml. static final String PATH = "/_dr/task/backupDatastore"; // See web.xml. @Inject DatastoreAdmin datastoreAdmin; @Inject Response response; @Inject BackupDatastoreAction() {} @Override public void run() { try { Operation backup = datastoreAdmin .export( RegistryConfig.getDatastoreBackupsBucket(), AnnotatedEntities.getBackupKinds()) .execute(); String backupName = backup.getName(); // Enqueue a poll task to monitor the backup and load REPORTING-related kinds into bigquery. enqueuePollTask(backupName, AnnotatedEntities.getReportingKinds()); String message = String.format( "Datastore backup started with name: %s\nSaving to %s", backupName, backup.getExportFolderUrl()); logger.atInfo().log(message); response.setPayload(message); } catch (Throwable e) { throw new InternalServerErrorException("Exception occurred while backing up Datastore", e); } } }
1,074
2,049
<gh_stars>1000+ # -*- coding: utf-8 -*- # Copyright 2012 splinter authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import os TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
95
432
<filename>debugger/src/common/generic/cmd_reg_generic.cpp<gh_stars>100-1000 /* * Copyright 2018 <NAME>, <EMAIL> * * 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 "cmd_reg_generic.h" #include "debug/dsumap.h" namespace debugger { CmdRegGeneric::CmdRegGeneric(ITap *tap) : ICommand ("reg", tap) { briefDescr_.make_string("Read/write register value"); detailedDescr_.make_string( "Description:\n" " Read or modify the specific CPU's register.\n" "Usage:\n" " reg name\n" " reg name wrvalue\n" "Example:\n" " reg\n" " reg pc\n" " reg sp 0x10007fc0\n"); } int CmdRegGeneric::isValid(AttributeType *args) { if (!cmdName_.is_equal((*args)[0u].to_string())) { return CMD_INVALID; } if (args->size() == 2 || args->size() == 3) { return CMD_VALID; } return CMD_WRONG_ARGS; } void CmdRegGeneric::exec(AttributeType *args, AttributeType *res) { res->attr_free(); res->make_nil(); uint64_t val; const char *reg_name = (*args)[1].to_string(); uint64_t addr = reg2addr(reg_name); if (addr == REG_ADDR_ERROR) { char tstr[128]; RISCV_sprintf(tstr, sizeof(tstr), "%s not found", reg_name); generateError(res, tstr); return; } if (args->size() == 2) { int err = tap_->read(addr, 8, reinterpret_cast<uint8_t *>(&val)); if (err == TAP_ERROR) { return; } res->make_uint64(val); } else { val = (*args)[2].to_uint64(); tap_->write(addr, 8, reinterpret_cast<uint8_t *>(&val)); } } uint64_t CmdRegGeneric::reg2addr(const char *name) { const ECpuRegMapping *preg = getpMappedReg(); while (preg->name[0]) { if (strcmp(name, preg->name) == 0) { return preg->offset; } preg++; } return REG_ADDR_ERROR; } } // namespace debugger
1,054
984
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.mapper.entity.saving; import com.datastax.oss.driver.api.core.DefaultProtocolVersion; import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.mapper.MapperException; import com.datastax.oss.driver.api.mapper.annotations.Entity; /** Defines how null {@link Entity} properties will be handled during data insertion. */ public enum NullSavingStrategy { /** * Do not insert null properties. * * <p>In other words, the mapper won't call the corresponding setter on the {@link * BoundStatement}. The generated code looks approximately like this: * * <pre> * if (entity.getDescription() != null) { * boundStatement = boundStatement.setString("description", entity.getDescription()); * } * </pre> * * This avoids inserting tombstones for null properties. On the other hand, if the query is an * update and the column previously had another value, it won't be overwritten. * * <p>Note that unset values are only supported with {@link DefaultProtocolVersion#V4 native * protocol v4} (Cassandra 2.2) or above. If you try to use this strategy with a lower Cassandra * version, the mapper will throw a {@link MapperException} when you try to build the * corresponding DAO. * * @see <a href="https://issues.apache.org/jira/browse/CASSANDRA-7304">CASSANDRA-7304</a> */ DO_NOT_SET, /** * Insert null properties as a CQL {@code NULL}. * * <p>In other words, the mapper will always call the corresponding setter on the {@link * BoundStatement}. The generated code looks approximately like this: * * <pre> * // Called even if entity.getDescription() == null * boundStatement = boundStatement.setString("description", entity.getDescription()); * </pre> */ SET_TO_NULL }
735
844
{ "github-username": "mr-siddy", "favourite-emoji": "🙂", "favourite-music": "https://soundcloud.com/cigarettesaftersex/falling-in-love-1", "favourite-color": "#03fcad" }
83
625
<gh_stars>100-1000 package com.jtransc.charset.charsets; import com.jtransc.charset.JTranscCharBuffer; import com.jtransc.charset.JTranscCharset; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; public class JTranscCharsetUTF8 extends JTranscCharset { public JTranscCharsetUTF8() { super(new String[]{"UTF-8", "UTF8"}, 1, 1.2f, 4); } @Override public void encode(char[] in, int offset, int len, ByteArrayOutputStream out) { for (int n = 0; n < len; n++) { int codePoint = in[offset + n]; if ((codePoint & ~0x7F) == 0) { // 1-byte sequence out.write(codePoint); } else { if ((codePoint & ~0x7FF) == 0) { // 2-byte sequence out.write(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & ~0xFFFF) == 0) { // 3-byte sequence out.write(((codePoint >> 12) & 0x0F) | 0xE0); out.write(createByte(codePoint, 6)); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence out.write(((codePoint >> 18) & 0x07) | 0xF0); out.write(createByte(codePoint, 12)); out.write(createByte(codePoint, 6)); } out.write((codePoint & 0x3F) | 0x80); } } } static private int createByte(int codePoint, int shift) { return ((codePoint >> shift) & 0x3F) | 0x80; } @Override public void decode(byte[] in, int offset, int len, JTranscCharBuffer out) { int i = offset; int end = offset + len; while (i < end) { int c = in[i++] & 0xFF; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: { // 0xxxxxxx out.append((char) (c)); break; } case 12: case 13: { // 110x xxxx 10xx xxxx out.append((char) (((c & 0x1F) << 6) | (in[i++] & 0x3F))); break; } case 14: { // 1110 xxxx 10xx xxxx 10xx xxxx out.append((char) (((c & 0x0F) << 12) | ((in[i++] & 0x3F) << 6) | (in[i++] & 0x3F))); break; } } } } @Override public void decode(ByteBuffer in, CharBuffer out) { while (in.hasRemaining() && out.hasRemaining()) { int c = in.get() & 0xFF; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: { // 0xxxxxxx out.append((char) (c)); break; } case 12: case 13: { // 110x xxxx 10xx xxxx if (in.hasRemaining()) { out.append((char) (((c & 0x1F) << 6) | (in.get() & 0x3F))); } break; } case 14: { // 1110 xxxx 10xx xxxx 10xx xxxx if (in.hasRemaining()) { out.append((char) (((c & 0x0F) << 12) | ((in.get() & 0x3F) << 6) | (in.get() & 0x3F))); } break; } } } } }
2,319
2,633
<filename>test/python/ctx_iter_atexit/wsgi.py import atexit class application: def __init__(self, environ, start_response): self.environ = environ self.start = start_response def __iter__(self): atexit.register(self._atexit) content_length = int(self.environ.get('CONTENT_LENGTH', 0)) body = bytes(self.environ['wsgi.input'].read(content_length)) self.start( '200', [ ('Content-Type', self.environ.get('CONTENT_TYPE')), ('Content-Length', str(len(body))), ], ) yield body def _atexit(self): self.start('200', [('Content-Length', '0')])
332
332
<reponame>wwjiang007/spring-xd /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.xd.extension.script; import static org.junit.Assert.*; import java.util.Properties; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author <NAME> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(initializers = {PropertiesInjector.class}) public class ScriptModulePropertiesFactoryBeanTest { @Autowired @Qualifier("props") Properties properties; @Test public void test() { assertEquals("BAZ", properties.getProperty("baz")); assertEquals("CAR", properties.getProperty("car")); } } class PropertiesInjector implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { Properties variables = new Properties(); variables.put("variables", " baz = BAZ, car = CAR"); applicationContext.getEnvironment().getPropertySources() .addLast(new PropertiesPropertySource("variables", variables)); } }
574
8,772
<filename>support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DefaultDelegatedClientIdentityProviderConfigurationProducer.java package org.apereo.cas.web.flow; import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.authentication.principal.WebApplicationService; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.pac4j.client.DelegatedClientAuthenticationRequestCustomizer; import org.apereo.cas.pac4j.client.DelegatedClientIdentityProviderRedirectionStrategy; import org.apereo.cas.util.LoggingUtils; import org.apereo.cas.validation.DelegatedAuthenticationAccessStrategyHelper; import org.apereo.cas.web.DelegatedClientIdentityProviderConfiguration; import org.apereo.cas.web.DelegatedClientIdentityProviderConfigurationFactory; import org.apereo.cas.web.support.WebUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.pac4j.core.client.Client; import org.pac4j.core.client.Clients; import org.pac4j.core.client.IndirectClient; import org.pac4j.core.context.JEEContext; import org.springframework.http.HttpStatus; import org.springframework.webflow.execution.RequestContext; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; /** * This is {@link DefaultDelegatedClientIdentityProviderConfigurationProducer}. * * @author <NAME> * @since 6.2.0 */ @Slf4j @RequiredArgsConstructor public class DefaultDelegatedClientIdentityProviderConfigurationProducer implements DelegatedClientIdentityProviderConfigurationProducer { private final AuthenticationServiceSelectionPlan authenticationRequestServiceSelectionStrategies; private final Clients clients; private final DelegatedAuthenticationAccessStrategyHelper delegatedAuthenticationAccessStrategyHelper; private final CasConfigurationProperties casProperties; private final List<DelegatedClientAuthenticationRequestCustomizer> delegatedClientAuthenticationRequestCustomizers; private final DelegatedClientIdentityProviderRedirectionStrategy delegatedClientIdentityProviderRedirectionStrategy; @Override public Set<DelegatedClientIdentityProviderConfiguration> produce(final RequestContext context) { val currentService = WebUtils.getService(context); val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class); val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context); val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context); val webContext = new JEEContext(request, response); LOGGER.debug("Initialized context with request parameters [{}]", webContext.getRequestParameters()); val allClients = this.clients.findAllClients(); val providers = new LinkedHashSet<DelegatedClientIdentityProviderConfiguration>(allClients.size()); allClients .stream() .filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service, request)) .map(IndirectClient.class::cast) .forEach(client -> { try { val providerResult = produce(context, client); providerResult.ifPresent(provider -> { providers.add(provider); delegatedClientIdentityProviderRedirectionStrategy.getPrimaryDelegatedAuthenticationProvider(context, service, provider) .ifPresent(p -> WebUtils.putDelegatedAuthenticationProviderPrimary(context, p)); }); } catch (final Exception e) { LOGGER.error("Cannot process client [{}]", client); LoggingUtils.error(LOGGER, e); } }); if (!providers.isEmpty()) { val selectionType = casProperties.getAuthn().getPac4j().getCore().getDiscoverySelection().getSelectionType(); switch (selectionType) { case DYNAMIC: WebUtils.putDelegatedAuthenticationProviderConfigurations(context, new HashSet<>()); WebUtils.putDelegatedAuthenticationDynamicProviderSelection(context, Boolean.TRUE); break; case MENU: default: WebUtils.putDelegatedAuthenticationProviderConfigurations(context, providers); WebUtils.putDelegatedAuthenticationDynamicProviderSelection(context, Boolean.FALSE); break; } } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) { LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. " + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers"); } return providers; } @Override public Optional<DelegatedClientIdentityProviderConfiguration> produce(final RequestContext requestContext, final IndirectClient client) { val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext); val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext); val webContext = new JEEContext(request, response); val currentService = WebUtils.getService(requestContext); LOGGER.debug("Initializing client [{}] with request parameters [{}] and service [{}]", client, requestContext.getRequestParameters(), currentService); client.init(); if (delegatedClientAuthenticationRequestCustomizers.isEmpty() || delegatedClientAuthenticationRequestCustomizers.stream().anyMatch(c -> c.isAuthorized(webContext, client, currentService))) { return DelegatedClientIdentityProviderConfigurationFactory.builder() .client(client) .webContext(webContext) .service(currentService) .casProperties(casProperties) .build() .resolve(); } return Optional.empty(); } private boolean isDelegatedClientAuthorizedForService(final Client client, final Service service, final HttpServletRequest request) { return delegatedAuthenticationAccessStrategyHelper.isDelegatedClientAuthorizedForService(client, service, request); } }
2,557
733
// // ZoomTransitioning.h // ZoomTransitioning // // Created by shoji on 7/19/16. // Copyright © 2016 com.shoji. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for ZoomTransitioning. FOUNDATION_EXPORT double ZoomTransitioningVersionNumber; //! Project version string for ZoomTransitioning. FOUNDATION_EXPORT const unsigned char ZoomTransitioningVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ZoomTransitioning/PublicHeader.h>
158
599
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. common utils """ from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class BaseTSModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class BaseModel(models.Model): """Model with 'created' and 'updated' fields.""" creator = models.CharField(_("创建者"), max_length=32) updator = models.CharField(_("修改着"), max_length=32) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) deleted_time = models.DateTimeField(null=True, blank=True) @property def created_display(self): # 转换成本地时间 t = timezone.localtime(self.created) return t.strftime("%Y-%m-%d %H:%M:%S") @property def updated_display(self): # 转换成本地时间 t = timezone.localtime(self.updated) return t.strftime("%Y-%m-%d %H:%M:%S") @property def updated_display_short(self): # 转换成本地时间 t = timezone.localtime(self.updated) return t.strftime("%Y-%m-%d %H:%M") class Meta: abstract = True
770
1,756
package com.libmailcore; /** Operation to fetch the content of a given article. */ public class NNTPFetchArticleOperation extends NNTPOperation { /** Content of the article in RFC 822 format. */ public native byte[] data(); }
66
1,444
<reponame>amc8391/mage<filename>Mage.Sets/src/mage/cards/s/SizzlingBarrage.java package mage.cards.s; import mage.MageObjectReference; import mage.abilities.effects.common.DamageTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.WatcherScope; import mage.filter.FilterPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicate; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import mage.watchers.Watcher; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * @author TheElk801 */ public final class SizzlingBarrage extends CardImpl { private static final FilterPermanent filter = new FilterCreaturePermanent("creature that blocked this turn"); static { filter.add(SizzlingBarragePredicate.instance); } public SizzlingBarrage(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{R}"); // Sizzling Barrage deals 4 damage to target creature that blocked this turn. this.getSpellAbility().addEffect(new DamageTargetEffect(4)); this.getSpellAbility().addTarget(new TargetPermanent(filter)); this.getSpellAbility().addWatcher(new SizzlingBarrageWatcher()); } private SizzlingBarrage(final SizzlingBarrage card) { super(card); } @Override public SizzlingBarrage copy() { return new SizzlingBarrage(this); } } enum SizzlingBarragePredicate implements Predicate<Permanent> { instance; @Override public boolean apply(Permanent input, Game game) { SizzlingBarrageWatcher watcher = game.getState().getWatcher(SizzlingBarrageWatcher.class); return watcher != null && watcher.checkCreature(input, game); } } class SizzlingBarrageWatcher extends Watcher { private final Set<MageObjectReference> blockers = new HashSet<>(); SizzlingBarrageWatcher() { super(WatcherScope.GAME); } @Override public void watch(GameEvent event, Game game) { if (event.getType() != GameEvent.EventType.BLOCKER_DECLARED) { return; } blockers.add(new MageObjectReference(event.getSourceId(), game)); } @Override public void reset() { super.reset(); this.blockers.clear(); } boolean checkCreature(Permanent permanent, Game game) { return blockers.stream().anyMatch(mor -> mor.refersTo(permanent, game)); } }
954