max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,338
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <locale> // class time_get<charT, InputIterator> // dateorder date_order() const; #include <locale> #include <cassert> #include "test_macros.h" #include "test_iterators.h" typedef std::time_get<char, cpp17_input_iterator<const char*> > F; class my_facet : public F { public: explicit my_facet(std::size_t refs = 0) : F(refs) {} }; int main(int, char**) { const my_facet f(1); assert(f.date_order() == std::time_base::mdy); return 0; }
288
1,444
<gh_stars>1000+ package mage.cards.i; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.game.Game; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetAnyTarget; import java.util.UUID; /** * @author TheElk801 */ public final class InspiredUltimatum extends CardImpl { public InspiredUltimatum(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{U}{U}{R}{R}{R}{W}{W}"); // Target player gains 5 life. Inspired Ultimatum deals 5 damage to any target. You draw five cards. this.getSpellAbility().addEffect(new InspiredUltimatumEffect()); this.getSpellAbility().addTarget(new TargetPlayer()); this.getSpellAbility().addTarget(new TargetAnyTarget()); } private InspiredUltimatum(final InspiredUltimatum card) { super(card); } @Override public InspiredUltimatum copy() { return new InspiredUltimatum(this); } } class InspiredUltimatumEffect extends OneShotEffect { InspiredUltimatumEffect() { super(Outcome.Benefit); staticText = "Target player gains 5 life, {this} deals 5 damage to any target, then you draw five cards."; } private InspiredUltimatumEffect(final InspiredUltimatumEffect effect) { super(effect); } @Override public InspiredUltimatumEffect copy() { return new InspiredUltimatumEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getTargets().get(0).getFirstTarget()); if (player != null) { player.gainLife(5, game, source); } game.damagePlayerOrPlaneswalker( source.getTargets().get(1).getFirstTarget(), 5, source.getSourceId(), source, game, false, true ); player = game.getPlayer(source.getControllerId()); if (player != null) { player.drawCards(5, source, game); } return true; } }
827
2,971
# Copyright 2020 - 2021 MONAI Consortium # 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. """ Collection of the remote MMAR descriptors See Also: - https://docs.nvidia.com/clara/clara-train-sdk/pt/mmar.html """ import os __all__ = ["MODEL_DESC", "RemoteMMARKeys"] class RemoteMMARKeys: """ Data keys used for loading MMAR. ID must uniquely define an MMAR. """ ID = "id" # unique MMAR NAME = "name" # MMAR name for readability URL = "url" # remote location of the MMAR, see also: `monai.apps.mmars.mmars._get_ngc_url` DOC = "doc" # documentation page of the remote model, see also: `monai.apps.mmars.mmars._get_ngc_doc_url` FILE_TYPE = "file_type" # type of the compressed MMAR HASH_TYPE = "hash_type" # hashing method for the compressed MMAR HASH_VAL = "hash_val" # hashing value for the compressed MMAR MODEL_FILE = "model_file" # within an MMAR folder, the relative path to the model file CONFIG_FILE = "config_file" # within an MMAR folder, the relative path to the config file (for model config) VERSION = "version" # version of the MMAR MODEL_DESC = ( { RemoteMMARKeys.ID: "clara_pt_spleen_ct_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_spleen_ct_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_prostate_mri_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_prostate_mri_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_covid19_ct_lesion_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lesion_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_covid19_3d_ct_classification_1", RemoteMMARKeys.NAME: "clara_pt_covid19_3d_ct_classification", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_covid19_ct_lung_annotation_1", RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lung_annotation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_fed_learning_brain_tumor_mri_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_fed_learning_brain_tumor_mri_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "server", "best_FL_global_model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_pathology_metastasis_detection_1", RemoteMMARKeys.NAME: "clara_pt_pathology_metastasis_detection", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_brain_mri_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_brain_mri_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_brain_mri_segmentation_t1c_1", RemoteMMARKeys.NAME: "clara_pt_brain_mri_segmentation_t1c", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_liver_and_tumor_ct_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_liver_and_tumor_ct_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_pancreas_and_tumor_ct_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_pancreas_and_tumor_ct_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_brain_mri_annotation_t1c_1", RemoteMMARKeys.NAME: "clara_pt_brain_mri_annotation_t1c", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_spleen_ct_annotation_1", RemoteMMARKeys.NAME: "clara_pt_spleen_ct_annotation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_deepgrow_3d_annotation_1", RemoteMMARKeys.NAME: "clara_pt_deepgrow_3d_annotation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_deepgrow_2d_annotation_1", RemoteMMARKeys.NAME: "clara_pt_deepgrow_2d_annotation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, { RemoteMMARKeys.ID: "clara_pt_covid19_ct_lung_segmentation_1", RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lung_segmentation", RemoteMMARKeys.FILE_TYPE: "zip", RemoteMMARKeys.HASH_TYPE: "md5", RemoteMMARKeys.HASH_VAL: None, RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), RemoteMMARKeys.VERSION: 1, }, )
3,881
4,163
"""Denizen labels.""" from proselint.tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms. source: Garner's Modern American Usage source_url: http://bit.ly/1T4alrY """ err = "terms.denizen_labels.garner" msg = "'{}' is the preferred denizen label." preferences = [ ["Afrikaner", ["Afrikaaner"]], ["Afrikaner", ["Afrikander"]], ["Alabamian", ["Alabaman"]], ["Albuquerquean", ["Albuquerquian"]], ["Anchorageite", ["Anchoragite"]], ["Angeleno", ["Los Angelean"]], ["Arizonan", ["Arizonian"]], ["Arkansan", ["Arkansawyer"]], ["Belarusian", ["Belarusan"]], ["Caymanian", ["Cayman Islander"]], ["Coloradan", ["Coloradoan"]], ["Fairbanksan", ["Fairbanksian"]], ["Fort Worthian", ["Fort Worther"]], ["Grenadan", ["Grenadian"]], ["Hong Konger", ["Hong Kongite", "Hong Kongian"]], ["Hoosier", ["Indianan", "Indianian"]], ["Illinoisan", ["Illinoisian"]], ["Iowan", ["Iowegian"]], ["Louisianian", ["Louisianan"]], ["Michigander", ["Michiganite", "Michiganian"]], ["Missourian", ["Missouran"]], ["Monegasque", ["Monacan"]], ["Neapolitan", ["Neopolitan"]], ["New Hampshirite", ["New Hampshireite", "New Hampshireman"]], ["New Jerseyan", ["New Jerseyite"]], ["New Orleanian", ["New Orleansian"]], ["Nutmegger", ["Connecticuter"]], ["Oklahoma Cityan", ["Oklahoma Citian"]], ["Oklahoman", ["Oklahomian"]], ["Seattleite", ["Seattlite"]], ["Surinamese", ["Surinamer"]], ["Tallahasseean", ["Tallahassean"]], ["Tennessean", ["Tennesseean"]], ["Tusconan", ["Tusconian", "Tusconite"]], ["Utahn", ["Utahan"]], ["Saudi", ["Saudi Arabian"]], ] return preferred_forms_check(text, preferences, err, msg) @memoize def check_denizen_labels_norris(text): """Suggest the preferred forms. source: <NAME> source_url: http://nyr.kr/1rGienj """ err = "terms.denizen_labels.norris" msg = "Would you like '{}'?" preferences = [ ["Mancunian", ["Manchesterian"]], ["Mancunians", ["Manchesterians"]], ["Vallisoletano", ["Valladolidian"]], ["Wulfrunian", ["Wolverhamptonian", "Wolverhamptonite"]], ["Novocastrian", ["Newcastleite", "Newcastlite"]], ["Trifluvian", ["Trois-Rivièrester"]], ["Leodenisian", ["Leedsian"]], ["Minneapolitan", ["Minneapolisian"]], ["Hartlepudlian", ["Hartlepoolian"]], ["Liverpudlian", ["Liverpoolian"]], ["Haligonian", ["Halifaxer"]], ["Varsovian", ["Warsawer", "Warsawian"]], ["Providentian", ["Providencian", "Providencer"]], ["Tridentine", ["Trentian", "Trentonian"]], ] return preferred_forms_check(text, preferences, err, msg)
1,667
2,743
# Copyright (c) 2020-2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import cudf import dask_cudf import pandas as pd import numpy as np from cuml.common import has_scipy from cuml.dask.common import utils as dask_utils from cuml.test.utils import unit_param, quality_param, stress_param from sklearn.neighbors import KNeighborsClassifier from cuml.test.utils import array_equal def predict(neigh_ind, _y, n_neighbors): if has_scipy(): import scipy.stats as stats else: raise RuntimeError('Scipy is needed to run predict()') neigh_ind = neigh_ind.astype(np.int64) ypred, count = stats.mode(_y[neigh_ind], axis=1) return ypred.ravel(), count.ravel() * 1.0 / n_neighbors def _prep_training_data(c, X_train, partitions_per_worker, reverse_order=False): workers = c.has_what().keys() if reverse_order: workers = list(workers)[::-1] n_partitions = partitions_per_worker * len(workers) X_cudf = cudf.DataFrame.from_pandas(pd.DataFrame(X_train)) X_train_df = dask_cudf.from_cudf(X_cudf, npartitions=n_partitions) X_train_df, = dask_utils.persist_across_workers(c, [X_train_df], workers=list(workers)) return X_train_df def _scale_rows(client, nrows): workers = list(client.scheduler_info()['workers'].keys()) n_workers = len(workers) return n_workers * nrows @pytest.mark.parametrize("nrows", [unit_param(300), quality_param(1e6), stress_param(5e8)]) @pytest.mark.parametrize("ncols", [10, 30]) @pytest.mark.parametrize("nclusters", [unit_param(5), quality_param(10), stress_param(15)]) @pytest.mark.parametrize("n_neighbors", [unit_param(10), quality_param(4), stress_param(100)]) @pytest.mark.parametrize("n_parts", [unit_param(1), unit_param(5), quality_param(7), stress_param(50)]) @pytest.mark.parametrize("streams_per_handle,reverse_worker_order", [(5, True), (10, False)]) def test_compare_skl(nrows, ncols, nclusters, n_parts, n_neighbors, streams_per_handle, reverse_worker_order, client): from cuml.dask.neighbors import NearestNeighbors as daskNN from sklearn.datasets import make_blobs nrows = _scale_rows(client, nrows) X, y = make_blobs(n_samples=int(nrows), n_features=ncols, centers=nclusters, random_state=0) X = X.astype(np.float32) X_cudf = _prep_training_data(client, X, n_parts, reverse_worker_order) from dask.distributed import wait wait(X_cudf) dist = np.array([len(v) for v in client.has_what().values()]) assert np.all(dist == dist[0]) cumlModel = daskNN(n_neighbors=n_neighbors, streams_per_handle=streams_per_handle) cumlModel.fit(X_cudf) out_d, out_i = cumlModel.kneighbors(X_cudf) local_i = np.array(out_i.compute().to_numpy(), dtype="int64") sklModel = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X, y) skl_y_hat = sklModel.predict(X) y_hat, _ = predict(local_i, y, n_neighbors) sk_d, sk_i = sklModel.kneighbors(X) sk_i = sk_i.astype("int64") assert array_equal(local_i[:, 0], np.arange(nrows)) diff = sk_i-local_i n_diff = len(diff[diff > 0]) perc_diff = n_diff / (nrows * n_neighbors) assert perc_diff <= 3e-3 assert array_equal(y_hat, skl_y_hat) @pytest.mark.parametrize("nrows", [unit_param(1000), stress_param(1e5)]) @pytest.mark.parametrize("ncols", [unit_param(10), stress_param(500)]) @pytest.mark.parametrize("n_parts", [unit_param(10), stress_param(100)]) @pytest.mark.parametrize("batch_size", [unit_param(100), stress_param(1e3)]) def test_batch_size(nrows, ncols, n_parts, batch_size, client): n_neighbors = 10 n_clusters = 5 from cuml.dask.neighbors import NearestNeighbors as daskNN from sklearn.datasets import make_blobs nrows = _scale_rows(client, nrows) X, y = make_blobs(n_samples=int(nrows), n_features=ncols, centers=n_clusters, random_state=0) X = X.astype(np.float32) X_cudf = _prep_training_data(client, X, n_parts) cumlModel = daskNN(n_neighbors=n_neighbors, batch_size=batch_size, streams_per_handle=5) cumlModel.fit(X_cudf) out_d, out_i = cumlModel.kneighbors(X_cudf) local_i = out_i.compute().to_numpy() y_hat, _ = predict(local_i, y, n_neighbors) assert array_equal(y_hat, y) def test_return_distance(client): n_samples = 50 n_feats = 50 k = 5 from cuml.dask.neighbors import NearestNeighbors as daskNN from sklearn.datasets import make_blobs n_samples = _scale_rows(client, n_samples) X, y = make_blobs(n_samples=n_samples, n_features=n_feats, random_state=0) X = X.astype(np.float32) X_cudf = _prep_training_data(client, X, 1) cumlModel = daskNN(streams_per_handle=5) cumlModel.fit(X_cudf) ret = cumlModel.kneighbors(X_cudf, k, return_distance=False) assert not isinstance(ret, tuple) ret = ret.compute() assert ret.shape == (n_samples, k) ret = cumlModel.kneighbors(X_cudf, k, return_distance=True) assert isinstance(ret, tuple) assert len(ret) == 2 def test_default_n_neighbors(client): n_samples = 50 n_feats = 50 k = 15 from cuml.dask.neighbors import NearestNeighbors as daskNN from cuml.neighbors.nearest_neighbors_mg import \ NearestNeighborsMG as cumlNN from sklearn.datasets import make_blobs n_samples = _scale_rows(client, n_samples) X, y = make_blobs(n_samples=n_samples, n_features=n_feats, random_state=0) X = X.astype(np.float32) X_cudf = _prep_training_data(client, X, 1) cumlModel = daskNN(streams_per_handle=5) cumlModel.fit(X_cudf) ret = cumlModel.kneighbors(X_cudf, return_distance=False) assert ret.shape[1] == cumlNN().n_neighbors cumlModel = daskNN(n_neighbors=k) cumlModel.fit(X_cudf) ret = cumlModel.kneighbors(X_cudf, k, return_distance=False) assert ret.shape[1] == k def test_one_query_partition(client): from cuml.dask.neighbors import NearestNeighbors as daskNN from cuml.dask.datasets import make_blobs X_train, _ = make_blobs(n_samples=4000, n_features=16, n_parts=8) X_test, _ = make_blobs(n_samples=200, n_features=16, n_parts=1) cumlModel = daskNN(n_neighbors=4) cumlModel.fit(X_train) cumlModel.kneighbors(X_test)
3,566
790
#!/usr/bin/env python # # Copyright 2007 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. # """Compute statistics on Appstats data and prepare data for UI. Appstats data is processed to compute information necessary for charts. For e.g., for the main page, request counts in different latency bins are computed, and the information is summarized in a manner convenient for the UI. """ try: import json except ImportError: import simplejson as json import math class _ExponentialBinner(object): """Bins data in intervals with exponentially increasing sizes. Helps with preparation of histograms. E.g., histograms that plot number of requests within each latency range. """ def __init__(self, start, exponent): """Initialize parameters for histograms. E.g., start = 10, and exponent = 2 will bin data using intervals [0, 10], [11, 20], [21, 40], and so on. Args: start: upper bound of first interval exponent: ratio of upper bounds of two consecutive intervals. """ self.start = start self.exponent = exponent def Bin(self, data): """Compute counts of data items in various bins. Args: data: sorted list of integer or long data items. Returns: A list, with each element being count of data items in each bin """ bincounts = [] numbins = self._BinIndex(data[-1]) + 1 for bin_index in range(numbins): bincounts.append(0) for item in data: bin_index = self._BinIndex(item) bincounts[bin_index] += 1 return bincounts def Intervals(self, numbins): """Returns the upper bounds of intervals under exponential binning. E.g., if intervals are [0, 10], [11, 20], [21, 40], [41, 80], this function returns the list [10, 20, 40, 80]. Args: numbins: Number of bins. Returns: A list which contains upper bounds of each interval range. """ if numbins < 1: return [] intervals = [self.start] for _ in range(1, numbins): intervals.append(intervals[-1] * self.exponent) return intervals def _BinIndex(self, item): """Get bin to which item belongs. E.g., if intervals are [0, 10], [10, 20], [20, 40], [40, 80], _BinIndex(25) is 2, and _BinIndex(50) is 3. Bin numbers are 0-based. Args: item: data item Returns: bin to which item belongs, assuming 0-based binning. """ if item <= self.start: return 0 else: itembin = math.ceil(math.log(float(item)/self.start, self.exponent)) return int(itembin) def URLFreqRespTime(urlstatsdict): """Computes request counts in different response time ranges for histograms. Args: urlstatsdict: A dictionary. Key is url path. Value is appropriate URLStats object which contains appstats statistics for the path. Returns: resptime_byfreq: A list of 3-tuples, one per URL, sorted in descending order of the number of requests seen by each URL. The elements of each tuple are (i) URL path; (ii) sorted list of response times of all requests corresponding to that URL; and (iii) a list of request counts in each latency bin for that URL. intervals: A list of latency ranges that requests of each URL are binned into. Each latency range is represented by the upper end of the range. E.g., if we are binning requests into latency ranges [0, 10], [11, 20], [21, 40], ... [1601, 3200]. Then, intervals is represented by the list [10, 20, 40,...,3200] """ resptime = [] binner = _ExponentialBinner(10, 2) maxbins = 0 for url, urlstats in urlstatsdict.iteritems(): urlresptime = sorted(urlstats.GetResponseTimeList()) urlbin = binner.Bin(urlresptime) maxbins = max(maxbins, len(urlbin)) resptime.append((url, urlresptime, urlbin)) resptime.sort(key=lambda triple: len(triple[1]), reverse=True) intervals = binner.Intervals(maxbins) return resptime, intervals def _GetPercentile(sortedlist, percent): """Returns a desired percentile value of a sorted list of numbers. E.g., if a list of request latencies is [1, 4, 7, 14, 34, 89, 100, 123, 149, 345], and percent is 0.9, the result is 149. If percent is 0.5 (median), result is 34. Args: sortedlist: A sorted list of integers, longs or floats. percent: A fraction between 0 and 1 that indicates desired percentile value. E.g., 0.9 means 90th percentile is desired. Returns: None if list is empty. Else, the desired percentile value. """ if not sortedlist: return None k = int(math.ceil(len(sortedlist) * percent)) - 1 if k < 0: k = 0 return sortedlist[k] def _GetPercentileList(items, percentilelist): """Given a list, returns a list of desired percentile values. Args: items: A list of integers, longs or floats. percentilelist: A list of fractions, each between 0 and 1 that indicates desired percentile value. E.g., [0.1, 0.9] means 10th and 90th percentiles are desired. Returns: None if list is empty. Else, the list of desired percentile values. """ if not items: return None sortedlist = sorted(items) return [_GetPercentile(sortedlist, p) for p in percentilelist] class RequestSummary(object): """Summarizes request statistics for UI. The class summarizes the timestamps, latencies and total rpc time of all requests of a given URL path. An object of this class will then be passed to the UI for display of the page that drills into specific a URL path. """ def __init__(self): self.timestamps = [] self.totaltimes = [] self.totalrpctimes = [] def Summary(urlstats): """Summarize relevant statistics for requests. Args: urlstats: A list of URLStat objects, which provide statistics for each request of a given URL path. Returns: A RequestSummary object which provides the timestamps, latencies and total rpc times for all requests of a given URL path. Each list is ordered in chronological order. """ summary = RequestSummary() for request in reversed(urlstats.urlrequestlist): summary.timestamps.append(request.timestamp) summary.totaltimes.append(request.totalresponsetime) summary.totalrpctimes.append(request.totalrpctime) return summary class RPCSummary(object): """Summarize RPC statistics for UI. The class summarizes information relevant to each RPC category such as the number of requests, number of calls, time spent in each RPC etc. There is one object per RPC category. Objects of this class will be passed to the UI for display of the page that drills into specific a URL path. """ def __init__(self): self.requests = 0 self.calls = 0 self.times = [] self.indices = [] self.stats = [] self.summary_time = 0 def SortedRPCSummaries(urlstats, summary_percentile): """Summarize RPC statistics of requests for UI. Args: urlstats: A list of URLStat objects, which provide statistics for each request of a given URL path. summary_percentile: Summarize the time spent in an RPC across different requests by this percentile value. RPCs are sorted in the decreasing order of this percentile value. E.g., 0.5 indicates RPC times are summarized and sorted by the median. Returns: A list of tuples. The first element of each tuple is an RPC category label. The second element is an RPCSummary object which summarizes statistics about that RPC category. Summarizing data in this form is convenient for rendering UI on the drill page, particularly for bar charts showing times spent in various RPCs across different requests. The list is sorted in decreasing order of the summary_percentile of time spent in that RPC. This is the order in which RPCs will be rendered in the UI. """ rpcsummary = {} for (index, request) in enumerate(reversed(urlstats.urlrequestlist)): for rpc in request.rpcstatslist: label = rpc.GetLabel() if label not in rpcsummary: rpcsummary[label] = RPCSummary() summary = rpcsummary[label] summary.requests += 1 summary.calls += rpc.numcalls summary.times.append(rpc.time) summary.indices.append(index) successful_reads = len(rpc.keys_read) - len(rpc.keys_failed_get) summary.stats.append((rpc.numcalls, successful_reads, len(rpc.keys_written), len(rpc.keys_failed_get))) for label in rpcsummary: summary = _GetPercentile(sorted(rpcsummary[label].times), summary_percentile) rpcsummary[label].summary_time = summary rpcsummary_sort = sorted(rpcsummary.iteritems(), key=lambda pair: pair[1].summary_time, reverse=True) return rpcsummary_sort def RPCVariation(reqsummary, rpcsummaries): """Generates desired percentiles of times spent in each RPC. Produces results useful for a candlestick chart that shows variation in time spent across different RPCs. Currently, the candlestick chart shows the 10th, 25th, 75th and 90th percentiles of RPC times. Args: reqsummary: A reqsummary object. rpcsummaries: a list of tuples generated by the SortedRPCSummaries function. In each tuple, the first element is an RPC category name and the second element is a dictionary containing information about the RPC category, particularly time spent in that RPC category across URL requests. Returns: A list of lists. Each inner list contains delay percentiles for each RPC. """ rpc_variation = [] markers = [0.1, 0.25, 0.75, 0.9] percentiles = _GetPercentileList(reqsummary.totaltimes, markers) percentiles.insert(0, 'Total') rpc_variation.append(percentiles) percentiles = _GetPercentileList(reqsummary.totalrpctimes, markers) percentiles.insert(0, 'TotalRPCTime') rpc_variation.append(percentiles) for pair in rpcsummaries: percentiles = _GetPercentileList(pair[1].times, markers) percentiles.insert(0, pair[0]) rpc_variation.append(percentiles) return rpc_variation def SplitByKind(freqdict): """Arranges entity/entity group access counts by their kind. Args: freqdict: a dict with keys corresponding to entities or entity groups. Value is a dict with 3 keys, 'read', 'write', 'missed', the values of which correspond to the appropriate counts for that entity. Returns: kinds_bycount: A list of <kind, entitiesOfKind> tuples, one per entity (group) kind sorted in decreasing order of number of entities (entity groups) of each kind. entitiesOfKind is a list of tuples, one per entity (group) of that kind, sorted in decreasing order of the access count of that entity (group). Each tuple consists of the name of the entity (group), along with read, write and miss counts. maxcount: The maximum access count seen by any entity of any kind. """ kinds = {} for kind_fullname, freq in freqdict.items(): (kind, fullname) = kind_fullname.split(',') if not kind in kinds: kinds[kind] = [] kinds[kind].append((fullname, freq['read'], freq['write'], freq['miss'])) for kind in kinds: kinds[kind].sort(key=lambda ent: ent[1] + ent[2], reverse=True) kinds_bycount = sorted(kinds.iteritems(), key=lambda pair: len(pair[1]), reverse=True) maxcount = 0 for kind in kinds: maxcount = max(maxcount, kinds[kind][0][1] + kinds[kind][0][2]) return kinds_bycount, maxcount class Drill(object): """Data structures to be passed to UI for rendering drill page.""" def __init__(self): self.reqsummary = None self.rpcsummaries = [] self.groupcounts = [] self.maxgroupcount = None self.entitycounts = [] self.maxentitycount = None self.rpc_variation = [] def _ToJsonDrill(self): """Encodes data for drill page in JSON for UI. Returns: drill_json: A dictionary representation of the class with attributes encoded into JSON as necessary for the UI. """ drill_json = dict(self.__dict__) drill_json['rpcsummaries'] = [(l, s.requests, s.calls, json.dumps(s, cls=_RPCSummaryEncoder)) for (l, s) in self.rpcsummaries] drill_json['groupcounts'] = [(k, len(v), json.dumps(v)) for (k, v) in self.groupcounts] drill_json['entitycounts'] = [(k, len(v), json.dumps(v)) for (k, v) in self.entitycounts] return drill_json class _RPCSummaryEncoder(json.JSONEncoder): """JSON encoder for class RPCSummary.""" def default(self, obj): """Arranges entity/entity group access counts by their kind. Args: obj: an object whose JSON encoding is desired. Returns: JSON encoding of obj. """ if not isinstance(obj, RPCSummary): return json.JSONEncoder.default(self, obj) return obj.__dict__ def DrillURL(urlstats): """Analyzes URL statistics and generates data for drill page. Master function that calls all necessary functions to compute various data structures needed for rendering the drill page which shows details about a particular URL path. Args: urlstats: An URLStats object which holds appstats information about all requests of an URL path. Returns: drill: An object of class Drill with attributes encoded into JSON as necessary for the UI. """ drill = Drill() drill.reqsummary = Summary(urlstats) drill.rpcsummaries = SortedRPCSummaries(urlstats, 0.9) drill.rpc_variation = RPCVariation(drill.reqsummary, drill.rpcsummaries) groupcounts = urlstats.EntityGroupCount() drill.groupcounts, drill.maxgroupcount = SplitByKind(groupcounts) entitycounts = urlstats.EntityCount() drill.entitycounts, drill.maxentitycount = SplitByKind(entitycounts) drill_json = drill._ToJsonDrill() return drill_json
5,113
435
<filename>warehouse/ingest-core/src/test/java/datawave/ingest/mapreduce/job/metrics/TestEventCountMetricsReceiver.java package datawave.ingest.mapreduce.job.metrics; /** * A metrics receiver for the number of records. */ public class TestEventCountMetricsReceiver<OK,OV> extends BaseMetricsReceiver<OK,OV> { public TestEventCountMetricsReceiver() { super(Metric.EVENT_COUNT); } }
149
4,020
<reponame>CrackerCat/Recaf<gh_stars>1000+ package me.coley.recaf.graph; import me.coley.recaf.util.ClassUtil; import org.objectweb.asm.ClassReader; import java.util.Objects; import java.util.stream.Stream; /** * Graph vertex with a {@link org.objectweb.asm.ClassReader} as the data. * * @param <G> * The type of graph holding the vertex. * * @author Matt */ public abstract class ClassVertex<G extends WorkspaceGraph> extends Vertex<ClassReader> { protected final G graph; private ClassReader clazz; /** * Constructs a class vertex from the containing graph and class reader. * * @param graph * The containing graph. * @param clazz * The vertex data. */ public ClassVertex(G graph, ClassReader clazz) { this.clazz = clazz; this.graph = graph; } /** * @return Name of class stored by the vertex. */ public String getClassName() { return clazz.getClassName(); } @Override public ClassReader getData() { return clazz; } @Override public void setData(ClassReader clazz) { this.clazz = clazz; } @Override public int hashCode() { return getData().getClassName().hashCode(); } @Override public boolean equals(Object other) { if(other == null) throw new IllegalStateException("ClassVertex should not be compared to null"); if(this == other) return true; if(other instanceof ClassVertex) { ClassVertex otherVertex = (ClassVertex) other; return getData().getClassName().equals(otherVertex.getData().getClassName()); } return false; } @Override public String toString() { return getClassName(); } // ============================== UTILITY =================================== // /** * @param names * Stream of names of classes. * * @return Mapped stream where names are replaced with instances. * If a name has no instance mapping, it is discarded. */ protected Stream<ClassReader> getReadersFromNames(Stream<String> names) { return names.map(name -> { // Try loading from workspace ClassReader reader = graph.getWorkspace().getClassReader(name); if(reader != null) return reader; // Try loading from runtime return ClassUtil.fromRuntime(name); }).filter(Objects::nonNull); } }
737
9,717
from colorama import Style from contextlib import contextmanager from typing import Any, Dict, Iterator from queue import Queue, Empty from xml.sax.saxutils import XMLGenerator import codecs import os import sys import time import unicodedata class Logger: def __init__(self) -> None: self.logfile = os.environ.get("LOGFILE", "/dev/null") self.logfile_handle = codecs.open(self.logfile, "wb") self.xml = XMLGenerator(self.logfile_handle, encoding="utf-8") self.queue: "Queue[Dict[str, str]]" = Queue() self.xml.startDocument() self.xml.startElement("logfile", attrs={}) self._print_serial_logs = True @staticmethod def _eprint(*args: object, **kwargs: Any) -> None: print(*args, file=sys.stderr, **kwargs) def close(self) -> None: self.xml.endElement("logfile") self.xml.endDocument() self.logfile_handle.close() def sanitise(self, message: str) -> str: return "".join(ch for ch in message if unicodedata.category(ch)[0] != "C") def maybe_prefix(self, message: str, attributes: Dict[str, str]) -> str: if "machine" in attributes: return "{}: {}".format(attributes["machine"], message) return message def log_line(self, message: str, attributes: Dict[str, str]) -> None: self.xml.startElement("line", attributes) self.xml.characters(message) self.xml.endElement("line") def info(self, *args, **kwargs) -> None: # type: ignore self.log(*args, **kwargs) def warning(self, *args, **kwargs) -> None: # type: ignore self.log(*args, **kwargs) def error(self, *args, **kwargs) -> None: # type: ignore self.log(*args, **kwargs) sys.exit(1) def log(self, message: str, attributes: Dict[str, str] = {}) -> None: self._eprint(self.maybe_prefix(message, attributes)) self.drain_log_queue() self.log_line(message, attributes) def log_serial(self, message: str, machine: str) -> None: self.enqueue({"msg": message, "machine": machine, "type": "serial"}) if self._print_serial_logs: self._eprint( Style.DIM + "{} # {}".format(machine, message) + Style.RESET_ALL ) def enqueue(self, item: Dict[str, str]) -> None: self.queue.put(item) def drain_log_queue(self) -> None: try: while True: item = self.queue.get_nowait() msg = self.sanitise(item["msg"]) del item["msg"] self.log_line(msg, item) except Empty: pass @contextmanager def nested(self, message: str, attributes: Dict[str, str] = {}) -> Iterator[None]: self._eprint(self.maybe_prefix(message, attributes)) self.xml.startElement("nest", attrs={}) self.xml.startElement("head", attributes) self.xml.characters(message) self.xml.endElement("head") tic = time.time() self.drain_log_queue() yield self.drain_log_queue() toc = time.time() self.log("(finished: {}, in {:.2f} seconds)".format(message, toc - tic)) self.xml.endElement("nest") rootlog = Logger()
1,417
852
<filename>CondFormats/DataRecord/src/EcalTPGFineGrainStripEERcd.cc #include "CondFormats/DataRecord/interface/EcalTPGFineGrainStripEERcd.h" #include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h" EVENTSETUP_RECORD_REG(EcalTPGFineGrainStripEERcd);
105
471
<reponame>akashkj/commcare-hq from django.test import SimpleTestCase from smtplib import SMTPSenderRefused from dimagi.utils.django.email import LARGE_FILE_SIZE_ERROR_CODE from unittest.mock import create_autospec, patch, PropertyMock, ANY from corehq.apps.reports import views from corehq.apps.users.models import WebUser from corehq.apps.saved_reports import models from ..models import ReportNotification class TestReportNotification(SimpleTestCase): def test_unauthorized_user_cannot_view_report(self): report = ReportNotification(owner_id='5', domain='test_domain', recipient_emails=[]) bad_user = self._create_user(id='3', is_domain_admin=False) self.assertFalse(report.can_be_viewed_by(bad_user)) def test_owner_can_view_report(self): report = ReportNotification(owner_id='5', domain='test_domain', recipient_emails=[]) owner = self._create_user(id='5') self.assertTrue(report.can_be_viewed_by(owner)) def test_domain_admin_can_view_report(self): report = ReportNotification(owner_id='5', domain='test_domain', recipient_emails=[]) domain_admin = self._create_user(is_domain_admin=True) self.assertTrue(report.can_be_viewed_by(domain_admin)) def test_subscribed_user_can_view_report(self): report = ReportNotification(owner_id='5', domain='test_domain', recipient_emails=['<EMAIL>']) subscribed_user = self._create_user(email='<EMAIL>') self.assertTrue(report.can_be_viewed_by(subscribed_user)) def _create_user(self, id='100', email='not-included', is_domain_admin=False): user_template = WebUser(domain='test_domain', username='test_user') user = create_autospec(user_template, spec_set=True, _id=id) user.is_domain_admin = lambda domain: is_domain_admin user.get_email = lambda: email return user class TestRecipientsByLanguage(SimpleTestCase): def test_existing_user_with_no_language_gets_default_language(self): report = self._create_report_for_emails('<EMAIL>') self._establish_user_languages([{'username': '<EMAIL>', 'language': None}]) recipients_by_language = report.recipients_by_language self.assertEqual(recipients_by_language, {'en': ['<EMAIL>']}) def test_missing_user_gets_default_language(self): report = self._create_report_for_emails('<EMAIL>') self._establish_user_languages([]) recipients_by_language = report.recipients_by_language self.assertEqual(recipients_by_language, {'en': ['<EMAIL>']}) def setUp(self): owner_patcher = patch.object(ReportNotification, 'owner_email', new_callable=PropertyMock) self.mock_owner_email = owner_patcher.start() self.mock_owner_email.return_value = '<EMAIL>' self.addCleanup(owner_patcher.stop) user_doc_patcher = patch.object(models, 'get_user_docs_by_username') self.mock_get_user_docs = user_doc_patcher.start() self.addCleanup(user_doc_patcher.stop) def _create_report_for_emails(self, *emails): return ReportNotification(owner_id='<EMAIL>', domain='test_domain', recipient_emails=list(emails), send_to_owner=False) def _establish_user_languages(self, language_pairs): self.mock_get_user_docs.return_value = language_pairs class TestGetAndSendReport(SimpleTestCase): @patch.object(views, 'get_scheduled_report_response') @patch.object(ReportNotification, 'owner', new_callable=PropertyMock) def test_failing_report_generation_generates_log_message(self, owner_mock, mock_get_scheduled_report_response): owner_mock.return_value = WebUser(username='test user') mock_get_scheduled_report_response.side_effect = Exception('report generation failed!') report = ReportNotification(owner_id='<EMAIL>', domain='test_domain', recipient_emails=['<EMAIL>'], send_to_owner=False) with self.assertLogs('notify', level='ERROR') as cm: report._get_and_send_report('en', ['<EMAIL>']) self.assertIn('Encountered error while generating report', cm.output[0]) class TestSendEmails(SimpleTestCase): def setUp(self): email_mocker = patch.object(models, 'send_HTML_email') self.mock_send_email = email_mocker.start() self.addCleanup(email_mocker.stop) logger_mocker = patch.object(models, 'ScheduledReportLogger') self.report_logger = logger_mocker.start() self.addCleanup(logger_mocker.stop) def test_each_email_is_sent(self): ARG_INDEX = 0 EMAIL_INDEX = 1 report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=[]) emails = {call_args[ARG_INDEX][EMAIL_INDEX] for call_args in self.mock_send_email.call_args_list} self.assertSetEqual(emails, {'<EMAIL>', '<EMAIL>'}) def test_successful_emails_are_logged(self): report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=[]) self.report_logger.log_email_success.assert_any_call(report, '<EMAIL>', ANY) self.report_logger.log_email_success.assert_any_call(report, '<EMAIL>', ANY) @patch.object(ReportNotification, '_export_report') def test_emails_that_are_too_large_are_exported(self, mock_export_report): self.mock_send_email.side_effect = SMTPSenderRefused(code=LARGE_FILE_SIZE_ERROR_CODE, msg='test error', sender='<EMAIL>') report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=[]) mock_export_report.assert_called() self.report_logger.log_email_size_failure.assert_called_with( report, '<EMAIL>', ['<EMAIL>', '<EMAIL>'], ANY) @patch.object(ReportNotification, '_export_report') def test_emails_that_are_too_large_stop_after_first_failure(self, mock_export_report): self.mock_send_email.side_effect = SMTPSenderRefused(code=LARGE_FILE_SIZE_ERROR_CODE, msg='test error', sender='<EMAIL>') report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=[]) self.mock_send_email.assert_called_once() def test_huge_reports_with_attachments_resend_only_attachments(self): # trigger the exception on the first call, success on the second # (a failure needs to occur to trigger the re-send) self.mock_send_email.side_effect = [SMTPSenderRefused(code=LARGE_FILE_SIZE_ERROR_CODE, msg='test error', sender='<EMAIL>'), None] report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=['abba']) self.mock_send_email.assert_called_with('Test Report', ['<EMAIL>', '<EMAIL>'], 'Unable to generate email report. Excel files are attached.', email_from='<EMAIL>', file_attachments=['abba']) def test_failing_emails_are_logged(self): self.mock_send_email.side_effect = Exception('Email failed to send') report = ReportNotification(_id='5', domain='test-domain', uuid='uuid') report._send_emails('Test Report', 'Report Text', ['<EMAIL>', '<EMAIL>'], excel_files=[]) calls = self.report_logger.log_email_failure.call_args_list self.assertEqual(calls[0][0][0], report) self.assertEqual(calls[0][0][1], '<EMAIL>') self.assertEqual(str(calls[0][0][3]), 'Email failed to send') self.assertEqual(calls[1][0][0], report) self.assertEqual(calls[1][0][1], '<EMAIL>') self.assertEqual(str(calls[1][0][3]), 'Email failed to send')
3,321
1,073
// RUN: clang-format -output-replacements-xml -sort-includes %s \ // RUN: | FileCheck -strict-whitespace %s // CHECK: <?xml // CHECK-NEXT: {{<replacements.*incomplete_format='false'}} // CHECK-NEXT: {{<replacement.*#include &lt;a>&#10;#include &lt;b><}} // CHECK-NEXT: {{<replacement.*>&#10;<}} // CHECK-NEXT: {{<replacement.*> <}} #include <b> #include <a> int a;int*b;
159
648
{"resourceType":"DataElement","id":"HealthcareService.telecom","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/HealthcareService.telecom","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"HealthcareService.telecom","path":"HealthcareService.telecom","short":"Contacts related to the healthcare service","definition":"List of contacts related to this specific healthcare service.","comment":"If this is empty, then refer to the location's contacts.","min":0,"max":"*","type":[{"code":"ContactPoint"}],"mapping":[{"identity":"rim","map":".telecom"}]}]}
166
5,169
{ "name": "SSReaderView", "version": "0.0.1", "summary": "A reader view for novel", "platforms": { "ios": "9.0" }, "swift_versions": "5.0", "homepage": "https://github.com/namesubai/SSReaderView.git", "authors": { "subai": "<EMAIL>" }, "source": { "git": "https://github.com/namesubai/SSReaderView.git", "tag": "0.0.1" }, "license": "MIT", "source_files": "Sources/SSReaderView/*.{swift}", "requires_arc": true, "swift_version": "5.0" }
214
713
package org.infinispan.server.core.security.external; import static org.infinispan.server.core.security.SubjectSaslServer.SUBJECT; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicBoolean; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.x500.X500Principal; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import org.infinispan.commons.util.Util; final class ExternalSaslServer implements SaslServer { private final AtomicBoolean complete = new AtomicBoolean(); private String authorizationID; private final X500Principal peerPrincipal; private final CallbackHandler callbackHandler; ExternalSaslServer(final CallbackHandler callbackHandler, final X500Principal peerPrincipal) { this.callbackHandler = callbackHandler; this.peerPrincipal = peerPrincipal; } public String getMechanismName() { return "EXTERNAL"; } public byte[] evaluateResponse(final byte[] response) throws SaslException { if (complete.getAndSet(true)) { throw new SaslException("Received response after complete"); } String userName = new String(response, StandardCharsets.UTF_8); if (userName.length() == 0) { userName = peerPrincipal.getName(); } final AuthorizeCallback authorizeCallback = new AuthorizeCallback(peerPrincipal.getName(), userName); handleCallback(callbackHandler, authorizeCallback); if (authorizeCallback.isAuthorized()) { authorizationID = authorizeCallback.getAuthorizedID(); } else { throw new SaslException("EXTERNAL: " + peerPrincipal.getName() + " is not authorized to act as " + userName); } return Util.EMPTY_BYTE_ARRAY; } private static void handleCallback(CallbackHandler handler, Callback callback) throws SaslException { try { handler.handle(new Callback[]{ callback, }); } catch (SaslException e) { throw e; } catch (IOException e) { throw new SaslException("Failed to authenticate due to callback exception", e); } catch (UnsupportedCallbackException e) { throw new SaslException("Failed to authenticate due to unsupported callback", e); } } public boolean isComplete() { return complete.get(); } public String getAuthorizationID() { return authorizationID; } public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException { throw new IllegalStateException(); } public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException { throw new IllegalStateException(); } public Object getNegotiatedProperty(final String propName) { if (SUBJECT.equals(propName)) { if (isComplete()) { Subject subject = new Subject(); subject.getPrincipals().add(peerPrincipal); return subject; } else { throw new IllegalStateException("Authentication is not complete"); } } else { return null; } } public void dispose() throws SaslException { } }
1,204
352
/* * Visitor.cpp * * This file is part of the XShaderCompiler project (Copyright (c) 2014-2018 by <NAME>) * See "LICENSE.txt" for license information. */ #include "Visitor.h" #include "AST.h" #include "ReportIdents.h" namespace Xsc { #define IMPLEMENT_VISIT_PROC(AST_NAME) \ void Visitor::Visit##AST_NAME(AST_NAME* ast, void* args) IMPLEMENT_VISIT_PROC(Program) { Visit(ast->globalStmnts); } IMPLEMENT_VISIT_PROC(CodeBlock) { Visit(ast->stmnts); } IMPLEMENT_VISIT_PROC(Attribute) { Visit(ast->arguments); } IMPLEMENT_VISIT_PROC(SwitchCase) { Visit(ast->expr); Visit(ast->stmnts); } IMPLEMENT_VISIT_PROC(SamplerValue) { Visit(ast->value); } IMPLEMENT_VISIT_PROC(Register) { // do nothing } IMPLEMENT_VISIT_PROC(PackOffset) { // do nothing } IMPLEMENT_VISIT_PROC(ArrayDimension) { Visit(ast->expr); } IMPLEMENT_VISIT_PROC(TypeSpecifier) { Visit(ast->structDecl); } /* --- Declarations --- */ IMPLEMENT_VISIT_PROC(VarDecl) { Visit(ast->namespaceExpr); Visit(ast->arrayDims); Visit(ast->slotRegisters); Visit(ast->packOffset); Visit(ast->annotations); Visit(ast->initializer); } IMPLEMENT_VISIT_PROC(BufferDecl) { Visit(ast->arrayDims); Visit(ast->slotRegisters); Visit(ast->annotations); } IMPLEMENT_VISIT_PROC(SamplerDecl) { Visit(ast->arrayDims); Visit(ast->slotRegisters); Visit(ast->samplerValues); } IMPLEMENT_VISIT_PROC(StructDecl) { Visit(ast->localStmnts); } IMPLEMENT_VISIT_PROC(AliasDecl) { // do nothing } IMPLEMENT_VISIT_PROC(FunctionDecl) { Visit(ast->returnType); Visit(ast->parameters); Visit(ast->annotations); Visit(ast->codeBlock); } IMPLEMENT_VISIT_PROC(UniformBufferDecl) { Visit(ast->slotRegisters); Visit(ast->localStmnts); } /* --- Declaration statements --- */ IMPLEMENT_VISIT_PROC(BufferDeclStmnt) { Visit(ast->attribs); Visit(ast->bufferDecls); } IMPLEMENT_VISIT_PROC(SamplerDeclStmnt) { Visit(ast->attribs); Visit(ast->samplerDecls); } IMPLEMENT_VISIT_PROC(VarDeclStmnt) { Visit(ast->attribs); Visit(ast->typeSpecifier); Visit(ast->varDecls); } IMPLEMENT_VISIT_PROC(AliasDeclStmnt) { Visit(ast->attribs); Visit(ast->structDecl); Visit(ast->aliasDecls); } IMPLEMENT_VISIT_PROC(BasicDeclStmnt) { Visit(ast->attribs); Visit(ast->declObject); } /* --- Statements --- */ IMPLEMENT_VISIT_PROC(NullStmnt) { Visit(ast->attribs); } IMPLEMENT_VISIT_PROC(CodeBlockStmnt) { Visit(ast->attribs); Visit(ast->codeBlock); } IMPLEMENT_VISIT_PROC(ForLoopStmnt) { Visit(ast->attribs); Visit(ast->initStmnt); Visit(ast->condition); Visit(ast->iteration); Visit(ast->bodyStmnt); } IMPLEMENT_VISIT_PROC(WhileLoopStmnt) { Visit(ast->attribs); Visit(ast->condition); Visit(ast->bodyStmnt); } IMPLEMENT_VISIT_PROC(DoWhileLoopStmnt) { Visit(ast->attribs); Visit(ast->bodyStmnt); Visit(ast->condition); } IMPLEMENT_VISIT_PROC(IfStmnt) { Visit(ast->attribs); Visit(ast->condition); Visit(ast->bodyStmnt); Visit(ast->elseStmnt); } IMPLEMENT_VISIT_PROC(ElseStmnt) { Visit(ast->attribs); Visit(ast->bodyStmnt); } IMPLEMENT_VISIT_PROC(SwitchStmnt) { Visit(ast->attribs); Visit(ast->selector); Visit(ast->cases); } IMPLEMENT_VISIT_PROC(ExprStmnt) { Visit(ast->attribs); Visit(ast->expr); } IMPLEMENT_VISIT_PROC(ReturnStmnt) { Visit(ast->attribs); Visit(ast->expr); } IMPLEMENT_VISIT_PROC(CtrlTransferStmnt) { Visit(ast->attribs); } IMPLEMENT_VISIT_PROC(LayoutStmnt) { Visit(ast->attribs); } /* --- Expressions --- */ IMPLEMENT_VISIT_PROC(NullExpr) { // do nothing } IMPLEMENT_VISIT_PROC(SequenceExpr) { Visit(ast->exprs); } IMPLEMENT_VISIT_PROC(LiteralExpr) { // do nothing } IMPLEMENT_VISIT_PROC(TypeSpecifierExpr) { Visit(ast->typeSpecifier); } IMPLEMENT_VISIT_PROC(TernaryExpr) { Visit(ast->condExpr); Visit(ast->thenExpr); Visit(ast->elseExpr); } IMPLEMENT_VISIT_PROC(BinaryExpr) { Visit(ast->lhsExpr); Visit(ast->rhsExpr); } IMPLEMENT_VISIT_PROC(UnaryExpr) { Visit(ast->expr); } IMPLEMENT_VISIT_PROC(PostUnaryExpr) { Visit(ast->expr); } IMPLEMENT_VISIT_PROC(CallExpr) { Visit(ast->prefixExpr); Visit(ast->arguments); } IMPLEMENT_VISIT_PROC(BracketExpr) { Visit(ast->expr); } IMPLEMENT_VISIT_PROC(AssignExpr) { Visit(ast->lvalueExpr); Visit(ast->rvalueExpr); } IMPLEMENT_VISIT_PROC(ObjectExpr) { Visit(ast->prefixExpr); } IMPLEMENT_VISIT_PROC(ArrayExpr) { Visit(ast->prefixExpr); Visit(ast->arrayIndices); } IMPLEMENT_VISIT_PROC(CastExpr) { Visit(ast->typeSpecifier); Visit(ast->expr); } IMPLEMENT_VISIT_PROC(InitializerExpr) { Visit(ast->exprs); } #undef IMPLEMENT_VISIT_PROC } // /namespace Xsc // ================================================================================
2,249
384
/* * 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.apache.tez.serviceplugins.api; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.tez.common.ServicePluginLifecycle; /** * Plugin to allow custom container launchers to be written to launch containers on different types * of executors. */ @InterfaceAudience.Public @InterfaceStability.Unstable public abstract class ContainerLauncher implements ServicePluginLifecycle { private final ContainerLauncherContext containerLauncherContext; public ContainerLauncher(ContainerLauncherContext containerLauncherContext) { this.containerLauncherContext = containerLauncherContext; } /** * An entry point for initialization. * Order of service setup. Constructor, initialize(), start() - when starting a service. * * @throws Exception */ @Override public void initialize() throws Exception { } /** * An entry point for starting the service. * Order of service setup. Constructor, initialize(), start() - when starting a service. * * @throws Exception */ @Override public void start() throws Exception { } /** * Stop the service. This could be invoked at any point, when the service is no longer required - * including in case of errors. * * @throws Exception */ @Override public void shutdown() throws Exception { } /** * Get the {@link ContainerLauncherContext} associated with this instance of the container * launcher, which is used to communicate with the rest of the system * * @return an instance of {@link ContainerLauncherContext} */ public final ContainerLauncherContext getContext() { return this.containerLauncherContext; } /** * Get the {@link ContainerLauncherContext} associated with this instance of the container * launcher, which is used to communicate with the rest of the system * * @param launchRequest the actual launch request * @throws ServicePluginException when the service runs into a fatal error which it cannot handle. * This will cause the app to shutdown. */ public abstract void launchContainer(ContainerLaunchRequest launchRequest) throws ServicePluginException; /** * A request to stop a specific container * * @param stopRequest the actual stop request * @throws ServicePluginException when the service runs into a fatal error which it cannot handle. * This will cause the app to shutdown. */ public abstract void stopContainer(ContainerStopRequest stopRequest) throws ServicePluginException; }
888
466
from rdkit import Chem import numpy as np class Attribute: def __init__(self, attr_type, name, one_hot=True, values=None): if attr_type not in ['node', 'edge']: raise ValueError('Invalid value for attribute type: must be "node" ' 'or "edge"') self.attr_type = attr_type self.name = name if values is not None: self.n_values = len(values) self.attr_values = values self.one_hot = one_hot if self.one_hot: self.one_hot_dict = {} for i in range(self.n_values): tmp = np.zeros(self.n_values) tmp[i] = 1 self.one_hot_dict[self.attr_values[i]] = tmp class Node: def __init__(self, idx, rdmol, get_atom_attributes, has_3D=False): rdatom = rdmol.GetAtoms()[idx] self.node_idx = idx self.atom_type = rdatom.GetAtomicNum() self.attributes_dict = get_atom_attributes(rdatom) if has_3D: pos = rdmol.GetConformer().GetAtomPosition(idx) self.pos_x = pos.x self.pos_y = pos.y self.pos_z = pos.z class Edge: def __init__(self, rdbond, get_bond_attributes=None): self.begin_atom_idx = rdbond.GetBeginAtomIdx() self.end_atom_idx = rdbond.GetEndAtomIdx() if get_bond_attributes is not None: self.attributes_dict = get_bond_attributes(rdbond) class Graph: """Describes an undirected graph class""" def __init__(self, mol, max_size, get_atom_attributes, get_bond_attributes=None, kekulize=True, addHs=False, has_3D=False, from_rdmol=False): self.kekulize = kekulize self.addHs = addHs self.has_3D = has_3D if from_rdmol: self.smiles = Chem.MolToSmiles(mol) else: self.smiles = mol if from_rdmol: rdmol = mol else: rdmol = Chem.MolFromSmiles(mol) if self.addHs: rdmol = Chem.AddHs(rdmol) if kekulize: Chem.Kekulize(rdmol) self.num_nodes = rdmol.GetNumAtoms() self.num_edges = rdmol.GetNumBonds() self.nodes = [] if has_3D: self.xyz = np.zeros((max_size, 3)) num_atoms = rdmol.GetNumAtoms() for k in range(num_atoms): cur_node = Node(k, rdmol, get_atom_attributes, has_3D) self.nodes.append(cur_node) if has_3D: self.xyz[k, 0] = cur_node.pos_x self.xyz[k, 1] = cur_node.pos_y self.xyz[k, 2] = cur_node.pos_z adj_matrix = np.eye(self.num_nodes) self.edges = [] for _, bond in enumerate(rdmol.GetBonds()): cur_edge = Edge(bond, get_bond_attributes) self.edges.append(cur_edge) adj_matrix[cur_edge.begin_atom_idx, cur_edge.end_atom_idx] = 1.0 adj_matrix[cur_edge.end_atom_idx, cur_edge.begin_atom_idx] = 1.0 self.adj_matrix = np.zeros((max_size, max_size)) self.adj_matrix[:self.num_nodes, :self.num_nodes] = adj_matrix if get_bond_attributes is not None and len(self.edges) > 0: tmp = self.edges[0] self.n_attr = len(tmp.attributes_dict.keys()) def get_node_attr_adj_matrix(self, attr): node_attr_adj_matrix = np.zeros((self.num_nodes, self.num_nodes, attr.n_values)) attr_one_hot = [] node_idx = [] for node in self.nodes: tmp = attr.one_hot_dict[node.attributes_dict[attr.name]] attr_one_hot.append(tmp) node_attr_adj_matrix[node.node_idx, node.node_idx] = tmp node_idx.append(node.node_idx) for edge in self.edges: begin = edge.begin_atom_idx end = edge.end_atom_idx begin_one_hot = attr_one_hot[node_idx.index(begin)] end_one_hot = attr_one_hot[node_idx.index(end)] node_attr_adj_matrix[begin, end, :] = (begin_one_hot + end_one_hot) / 2 return node_attr_adj_matrix def get_edge_attr_adj_matrix(self, all_atr_dict, max_size): fl = True for edge in self.edges: begin = edge.begin_atom_idx end = edge.end_atom_idx cur_features = [] for attr_name in edge.attributes_dict.keys(): cur_attr = all_atr_dict[attr_name] if cur_attr.one_hot: cur_features += list(cur_attr.one_hot_dict[edge.attributes_dict[cur_attr.name]]) else: cur_features += [edge.attributes_dict[cur_attr.name]] cur_features = np.array(cur_features) attr_len = len(cur_features) if fl: edge_attr_adj_matrix = np.zeros((max_size, max_size, attr_len)) fl = False edge_attr_adj_matrix[begin, end, :] = cur_features edge_attr_adj_matrix[end, begin, :] = cur_features return edge_attr_adj_matrix def get_node_feature_matrix(self, all_atr_dict, max_size): features = [] for node in self.nodes: cur_features = [] for attr_name in node.attributes_dict.keys(): cur_attr = all_atr_dict[attr_name] try: if cur_attr.one_hot: cur_features += list(cur_attr.one_hot_dict[node.attributes_dict[cur_attr.name]]) else: cur_features += [node.attributes_dict[cur_attr.name]] except: raise ValueError("Attribute name " + cur_attr.name + " encountered an invalid value: " + str(node.attributes_dict[cur_attr.name]) + " for molecule " + self.smiles) features.append(cur_features) features = np.array(features) padded_features = np.zeros((max_size, features.shape[1])) padded_features[:features.shape[0], :features.shape[1]] = features return padded_features def xyz_to_zmat(self): raise NotImplementedError() def zmat_to_xyz(self): raise NotImplementedError()
3,287
376
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Universal Asynchronous Receiver/Transmitter namespace Uart0TasksStartrx{ ///<Start UART receiver using Addr = Register::Address<0x40002000,0xffffffff,0x00000000,unsigned>; } namespace Uart0TasksStoprx{ ///<Stop UART receiver using Addr = Register::Address<0x40002004,0xffffffff,0x00000000,unsigned>; } namespace Uart0TasksStarttx{ ///<Start UART transmitter using Addr = Register::Address<0x40002008,0xffffffff,0x00000000,unsigned>; } namespace Uart0TasksStoptx{ ///<Stop UART transmitter using Addr = Register::Address<0x4000200c,0xffffffff,0x00000000,unsigned>; } namespace Uart0TasksSuspend{ ///<Suspend UART using Addr = Register::Address<0x4000201c,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsCts{ ///<CTS is activated (set low). Clear To Send. using Addr = Register::Address<0x40002100,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsNcts{ ///<CTS is deactivated (set high). Not Clear To Send. using Addr = Register::Address<0x40002104,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsRxdrdy{ ///<Data received in RXD using Addr = Register::Address<0x40002108,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsTxdrdy{ ///<Data sent from TXD using Addr = Register::Address<0x4000211c,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsError{ ///<Error detected using Addr = Register::Address<0x40002124,0xffffffff,0x00000000,unsigned>; } namespace Uart0EventsRxto{ ///<Receiver timeout using Addr = Register::Address<0x40002144,0xffffffff,0x00000000,unsigned>; } namespace Uart0Shorts{ ///<Shortcut register using Addr = Register::Address<0x40002200,0xffffffe7,0x00000000,unsigned>; ///Shortcut between EVENTS_CTS event and TASKS_STARTRX task enum class CtsstartrxVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,CtsstartrxVal> ctsStartrx{}; namespace CtsstartrxValC{ constexpr Register::FieldValue<decltype(ctsStartrx)::Type,CtsstartrxVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(ctsStartrx)::Type,CtsstartrxVal::enabled> enabled{}; } ///Shortcut between EVENTS_NCTS event and TASKS_STOPRX task enum class NctsstoprxVal { disabled=0x00000000, ///<Disable shortcut enabled=0x00000001, ///<Enable shortcut }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,NctsstoprxVal> nctsStoprx{}; namespace NctsstoprxValC{ constexpr Register::FieldValue<decltype(nctsStoprx)::Type,NctsstoprxVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(nctsStoprx)::Type,NctsstoprxVal::enabled> enabled{}; } } namespace Uart0Intenset{ ///<Enable interrupt using Addr = Register::Address<0x40002304,0xfffdfd78,0x00000000,unsigned>; ///Write '1' to Enable interrupt on EVENTS_CTS event enum class CtsVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,CtsVal> cts{}; namespace CtsValC{ constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_NCTS event enum class NctsVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NctsVal> ncts{}; namespace NctsValC{ constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_RXDRDY event enum class RxdrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,RxdrdyVal> rxdrdy{}; namespace RxdrdyValC{ constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_TXDRDY event enum class TxdrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TxdrdyVal> txdrdy{}; namespace TxdrdyValC{ constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_ERROR event enum class ErrorVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,ErrorVal> error{}; namespace ErrorValC{ constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::set> set{}; } ///Write '1' to Enable interrupt on EVENTS_RXTO event enum class RxtoVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled set=0x00000001, ///<Enable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,RxtoVal> rxto{}; namespace RxtoValC{ constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::set> set{}; } } namespace Uart0Intenclr{ ///<Disable interrupt using Addr = Register::Address<0x40002308,0xfffdfd78,0x00000000,unsigned>; ///Write '1' to Clear interrupt on EVENTS_CTS event enum class CtsVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,CtsVal> cts{}; namespace CtsValC{ constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(cts)::Type,CtsVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_NCTS event enum class NctsVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NctsVal> ncts{}; namespace NctsValC{ constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(ncts)::Type,NctsVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_RXDRDY event enum class RxdrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,RxdrdyVal> rxdrdy{}; namespace RxdrdyValC{ constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(rxdrdy)::Type,RxdrdyVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_TXDRDY event enum class TxdrdyVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TxdrdyVal> txdrdy{}; namespace TxdrdyValC{ constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(txdrdy)::Type,TxdrdyVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_ERROR event enum class ErrorVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,ErrorVal> error{}; namespace ErrorValC{ constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(error)::Type,ErrorVal::clear> clear{}; } ///Write '1' to Clear interrupt on EVENTS_RXTO event enum class RxtoVal { disabled=0x00000000, ///<Read: Disabled enabled=0x00000001, ///<Read: Enabled clear=0x00000001, ///<Disable }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,RxtoVal> rxto{}; namespace RxtoValC{ constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(rxto)::Type,RxtoVal::clear> clear{}; } } namespace Uart0Errorsrc{ ///<Error source using Addr = Register::Address<0x40002480,0xfffffff0,0x00000000,unsigned>; ///Overrun error enum class OverrunVal { notpresent=0x00000000, ///<Read: error not present present=0x00000001, ///<Read: error present }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,OverrunVal> overrun{}; namespace OverrunValC{ constexpr Register::FieldValue<decltype(overrun)::Type,OverrunVal::notpresent> notpresent{}; constexpr Register::FieldValue<decltype(overrun)::Type,OverrunVal::present> present{}; } ///Parity error enum class ParityVal { notpresent=0x00000000, ///<Read: error not present present=0x00000001, ///<Read: error present }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,ParityVal> parity{}; namespace ParityValC{ constexpr Register::FieldValue<decltype(parity)::Type,ParityVal::notpresent> notpresent{}; constexpr Register::FieldValue<decltype(parity)::Type,ParityVal::present> present{}; } ///Framing error occurred enum class FramingVal { notpresent=0x00000000, ///<Read: error not present present=0x00000001, ///<Read: error present }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,FramingVal> framing{}; namespace FramingValC{ constexpr Register::FieldValue<decltype(framing)::Type,FramingVal::notpresent> notpresent{}; constexpr Register::FieldValue<decltype(framing)::Type,FramingVal::present> present{}; } ///Break condition enum class Break_Val { notpresent=0x00000000, ///<Read: error not present present=0x00000001, ///<Read: error present }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,Break_Val> break_{}; namespace Break_ValC{ constexpr Register::FieldValue<decltype(break_)::Type,Break_Val::notpresent> notpresent{}; constexpr Register::FieldValue<decltype(break_)::Type,Break_Val::present> present{}; } } namespace Uart0Enable{ ///<Enable UART using Addr = Register::Address<0x40002500,0xfffffff0,0x00000000,unsigned>; ///Enable or disable UART constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> enable{}; } namespace Uart0Pselrts{ ///<Pin select for RTS using Addr = Register::Address<0x40002508,0x00000000,0x00000000,unsigned>; ///Pin number configuration for UART RTS signal constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pselrts{}; } namespace Uart0Pseltxd{ ///<Pin select for TXD using Addr = Register::Address<0x4000250c,0x00000000,0x00000000,unsigned>; ///Pin number configuration for UART TXD signal constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pseltxd{}; } namespace Uart0Pselcts{ ///<Pin select for CTS using Addr = Register::Address<0x40002510,0x00000000,0x00000000,unsigned>; ///Pin number configuration for UART CTS signal constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pselcts{}; } namespace Uart0Pselrxd{ ///<Pin select for RXD using Addr = Register::Address<0x40002514,0x00000000,0x00000000,unsigned>; ///Pin number configuration for UART RXD signal constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pselrxd{}; } namespace Uart0Rxd{ ///<RXD register using Addr = Register::Address<0x40002518,0xffffff00,0x00000000,unsigned>; ///RX data received in previous transfers, double buffered constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rxd{}; } namespace Uart0Txd{ ///<TXD register using Addr = Register::Address<0x4000251c,0xffffff00,0x00000000,unsigned>; ///TX data to be transferred constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> txd{}; } namespace Uart0Baudrate{ ///<Baud rate using Addr = Register::Address<0x40002524,0x00000000,0x00000000,unsigned>; ///Baud-rate enum class BaudrateVal { baud1200=0x0004f000, ///<1200 baud (actual rate: 1205) baud2400=0x0009d000, ///<2400 baud (actual rate: 2396) baud4800=0x0013b000, ///<4800 baud (actual rate: 4808) baud9600=0x00275000, ///<9600 baud (actual rate: 9598) baud14400=0x003b0000, ///<14400 baud (actual rate: 14414) baud19200=0x004ea000, ///<19200 baud (actual rate: 19208) baud28800=0x0075f000, ///<28800 baud (actual rate: 28829) baud38400=0x009d5000, ///<38400 baud (actual rate: 38462) baud57600=0x00ebf000, ///<57600 baud (actual rate: 57762) baud76800=0x013a9000, ///<76800 baud (actual rate: 76923) baud115200=0x01d7e000, ///<115200 baud (actual rate: 115942) baud230400=0x03afb000, ///<230400 baud (actual rate: 231884) baud250000=0x04000000, ///<250000 baud baud460800=0x075f7000, ///<460800 baud (actual rate: 470588) baud921600=0x0ebed000, ///<921600 baud (actual rate: 941176) baud1m=0x10000000, ///<1Mega baud }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,BaudrateVal> baudrate{}; namespace BaudrateValC{ constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud1200> baud1200{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud2400> baud2400{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud4800> baud4800{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud9600> baud9600{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud14400> baud14400{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud19200> baud19200{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud28800> baud28800{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud38400> baud38400{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud57600> baud57600{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud76800> baud76800{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud115200> baud115200{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud230400> baud230400{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud250000> baud250000{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud460800> baud460800{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud921600> baud921600{}; constexpr Register::FieldValue<decltype(baudrate)::Type,BaudrateVal::baud1m> baud1m{}; } } namespace Uart0Config{ ///<Configuration of parity and hardware flow control using Addr = Register::Address<0x4000256c,0xfffffff0,0x00000000,unsigned>; ///Hardware flow control enum class HwfcVal { disabled=0x00000000, ///<Disabled enabled=0x00000001, ///<Enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,HwfcVal> hwfc{}; namespace HwfcValC{ constexpr Register::FieldValue<decltype(hwfc)::Type,HwfcVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(hwfc)::Type,HwfcVal::enabled> enabled{}; } ///Parity constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,1),Register::ReadWriteAccess,unsigned> parity{}; } }
8,876
506
<gh_stars>100-1000 package com.ewolff.microservice.order.kafka; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.kafka.config.KafkaListenerEndpointRegistry; import org.springframework.kafka.listener.MessageListenerContainer; import org.springframework.kafka.test.utils.ContainerTestUtils; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.testcontainers.containers.KafkaContainer; import com.ewolff.microservice.order.OrderApp; import com.ewolff.microservice.order.OrderTestDataGenerator; import com.ewolff.microservice.order.logic.OrderService; @RunWith(SpringRunner.class) @SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.NONE) @ActiveProfiles("test") @ContextConfiguration(initializers = { OrderKafkaTest.Initializer.class }) public class OrderKafkaTest { public static Logger logger = LoggerFactory.getLogger(OrderKafkaTest.class); @ClassRule public static KafkaContainer kafkaContainer = new KafkaContainer(); @Autowired private KafkaListenerBean kafkaListenerBean; @Autowired private OrderService orderService; @Autowired private OrderTestDataGenerator orderTestDataGenerator; @Autowired private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry; static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of("spring.kafka.bootstrap-servers=" + kafkaContainer.getBootstrapServers()) .applyTo(configurableApplicationContext.getEnvironment()); } } @Test public void orderCreatedSendsKafkaMassage() throws Exception { assertThat(kafkaContainer.isRunning(), is(true)); for (int i = 0; i < 3; i++) { try { for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry .getListenerContainers()) { ContainerTestUtils.waitForAssignment(messageListenerContainer, 1); } } catch (IllegalStateException ex) { logger.warn("Waited unsuccessfully for Kafka assignments"); } } int receivedBefore = kafkaListenerBean.getReceived(); orderService.order(orderTestDataGenerator.createOrder()); int i = 0; while (kafkaListenerBean.getReceived() == receivedBefore && i < 10) { Thread.sleep(1000); i++; } assertThat(kafkaListenerBean.getReceived(), is(greaterThan(receivedBefore))); } }
985
1,251
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_TAGGEDTEXT_H_ #define _FA_TAGGEDTEXT_H_ #include "FAConfig.h" #include "FATaggedTextA.h" #include "FAArray_cont_t.h" namespace BlingFire { class FAAllocatorA; /// /// Tagged text container. /// class FATaggedText : public FATaggedTextA { public: FATaggedText (FAAllocatorA * pAlloc); virtual ~FATaggedText (); public: const int GetWordCount () const; const int GetWord (const int Num, const int ** pWord) const; const int GetTag (const int Num) const; const int GetOffset (const int Num) const; public: void AddWord ( const int * pWord, const int Length, const int Tag ); void AddWord ( const int * pWord, const int Length, const int Tag, const int Offset ); void Clear (); public: void SetTags (const int * pTags, const int Count); private: FAArray_cont_t < int > m_chars; FAArray_cont_t < int > m_num2sl; FAArray_cont_t < int > m_num2tag; FAArray_cont_t < int > m_num2offset; }; } #endif
568
578
<filename>src/test/java/net/rubyeye/xmemcached/test/unittest/KestrelClientIT.java package net.rubyeye.xmemcached.test.unittest; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CyclicBarrier; import junit.framework.Assert; import junit.framework.TestCase; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.MemcachedClientBuilder; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.KestrelCommandFactory; import net.rubyeye.xmemcached.utils.AddrUtil; import com.google.code.yanf4j.util.ResourcesUtils; public class KestrelClientIT extends TestCase { static class UserDefinedClass implements Serializable { private String name; public UserDefinedClass(String name) { super(); this.name = name; } } Properties properties; private MemcachedClient memcachedClient; @Override public void setUp() throws Exception { this.properties = ResourcesUtils.getResourceAsProperties("test.properties"); MemcachedClientBuilder builder = newBuilder(); builder.setConnectionPoolSize(5); // builder.getConfiguration().setSessionIdleTimeout(5); this.memcachedClient = builder.build(); this.memcachedClient.flushAll(); } private MemcachedClientBuilder newBuilder() { MemcachedClientBuilder builder = new XMemcachedClientBuilder( AddrUtil.getAddresses(this.properties.getProperty("test.kestrel.servers"))); // Use kestrel command factory builder.setCommandFactory(new KestrelCommandFactory()); return builder; } public void testPrimitiveAsString() throws Exception { this.memcachedClient.setPrimitiveAsString(true); // store integer for (int i = 0; i < 1000; i++) { this.memcachedClient.set("queue1", 0, i); } // but get string for (int i = 0; i < 1000; i++) { Assert.assertEquals(String.valueOf(i), this.memcachedClient.get("queue1")); } this.memcachedClient.setPrimitiveAsString(false); // store integer for (int i = 0; i < 1000; i++) { this.memcachedClient.set("queue1", 0, i); } // still get integer for (int i = 0; i < 1000; i++) { Assert.assertEquals(i, this.memcachedClient.get("queue1")); } } @Override public void tearDown() throws IOException { this.memcachedClient.shutdown(); } public void testNormalSetAndGet() throws Exception { Assert.assertNull(this.memcachedClient.get("queue1")); Assert.assertTrue(this.memcachedClient.set("queue1", 0, "hello world")); Assert.assertEquals("hello world", this.memcachedClient.get("queue1")); Assert.assertNull(this.memcachedClient.get("queue1")); } public void testNormalSetAndGetMore() throws Exception { Assert.assertNull(this.memcachedClient.get("queue1")); for (int i = 0; i < 10; i++) { Assert.assertTrue(this.memcachedClient.set("queue1", 0, i)); } for (int i = 0; i < 10; i++) { Assert.assertEquals(i, this.memcachedClient.get("queue1")); } Assert.assertNull(this.memcachedClient.get("queue1")); } public void testSetAndGetObject() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("a", "a"); map.put("b", "b"); map.put("c", "c"); Assert.assertTrue(this.memcachedClient.set("queue1", 0, map)); Map<String, String> mapFromMQ = (Map<String, String>) this.memcachedClient.get("queue1"); Assert.assertEquals(3, mapFromMQ.size()); Assert.assertEquals("a", mapFromMQ.get("a")); Assert.assertEquals("b", mapFromMQ.get("b")); Assert.assertEquals("c", mapFromMQ.get("c")); Assert.assertNull(this.memcachedClient.get("queue1")); List<UserDefinedClass> userDefinedClassList = new ArrayList<UserDefinedClass>(); userDefinedClassList.add(new UserDefinedClass("a")); userDefinedClassList.add(new UserDefinedClass("b")); userDefinedClassList.add(new UserDefinedClass("c")); Assert.assertTrue(this.memcachedClient.set("queue1", 0, userDefinedClassList)); List<UserDefinedClass> userDefinedClassListFromMQ = (List<UserDefinedClass>) this.memcachedClient.get("queue1"); Assert.assertEquals(3, userDefinedClassListFromMQ.size()); } public void testBlockingFetch() throws Exception { this.memcachedClient.setOpTimeout(60000); long start = System.currentTimeMillis(); // blocking read 1 second Assert.assertNull(this.memcachedClient.get("queue1/t=1000")); Assert.assertEquals(1000, System.currentTimeMillis() - start, 100); Assert.assertTrue(this.memcachedClient.set("queue1", 0, "hello world")); Assert.assertEquals("hello world", this.memcachedClient.get("queue1/t=1000")); } public void testPeek() throws Exception { Assert.assertNull(this.memcachedClient.get("queue1/peek")); this.memcachedClient.set("queue1", 0, 1); Assert.assertEquals(1, this.memcachedClient.get("queue1/peek")); this.memcachedClient.set("queue1", 0, 10); Assert.assertEquals(1, this.memcachedClient.get("queue1/peek")); this.memcachedClient.set("queue1", 0, 11); Assert.assertEquals(1, this.memcachedClient.get("queue1/peek")); Assert.assertEquals(1, this.memcachedClient.get("queue1")); Assert.assertEquals(10, this.memcachedClient.get("queue1/peek")); Assert.assertEquals(10, this.memcachedClient.get("queue1")); Assert.assertEquals(11, this.memcachedClient.get("queue1/peek")); Assert.assertEquals(11, this.memcachedClient.get("queue1")); Assert.assertNull(this.memcachedClient.get("queue1/peek")); } public void testDelete() throws Exception { Assert.assertNull(this.memcachedClient.get("queue1")); for (int i = 0; i < 10; i++) { Assert.assertTrue(this.memcachedClient.set("queue1", 0, i)); } this.memcachedClient.delete("queue1"); for (int i = 0; i < 10; i++) { Assert.assertNull(this.memcachedClient.get("queue1")); } } public void testReliableFetch() throws Exception { Assert.assertTrue(this.memcachedClient.set("queue1", 0, "hello world")); Assert.assertEquals("hello world", this.memcachedClient.get("queue1/open")); // close connection this.memcachedClient.shutdown(); // still can fetch it MemcachedClient newClient = newBuilder().build(); newClient.setOptimizeGet(false); // begin transaction Assert.assertEquals("hello world", newClient.get("queue1/open")); // confirm Assert.assertNull(newClient.get("queue1/close")); Assert.assertNull(newClient.get("queue1")); // test abort,for kestrel 1.2 Assert.assertTrue(newClient.set("queue1", 0, "hello world")); Assert.assertEquals("hello world", newClient.get("queue1/open")); // abort Assert.assertNull(newClient.get("queue1/abort")); // still alive Assert.assertEquals("hello world", newClient.get("queue1/open")); // confirm Assert.assertNull(newClient.get("queue1/close")); // null Assert.assertNull(newClient.get("queue1")); newClient.shutdown(); } public void testPerformance() throws Exception { long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { this.memcachedClient.set("queue1", 0, "hello"); } System.out.println("push 10000 message:" + (System.currentTimeMillis() - start) + "ms"); start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { this.memcachedClient.get("queue1"); } System.out.println("fetch 10000 message:" + (System.currentTimeMillis() - start) + "ms"); } class AccessThread extends Thread { private CyclicBarrier cyclicBarrier; public AccessThread(CyclicBarrier cyclicBarrier) { super(); this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { this.cyclicBarrier.await(); for (int i = 0; i < 10000; i++) { KestrelClientIT.this.memcachedClient.set("queue1", 0, "hello"); } for (int i = 0; i < 10000; i++) { KestrelClientIT.this.memcachedClient.get("queue1"); } this.cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } } } public void ignoreTestConcurrentAccess() throws Exception { int threadCount = 100; CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount + 1); for (int i = 0; i < threadCount; i++) { new AccessThread(cyclicBarrier).start(); } cyclicBarrier.await(); cyclicBarrier.await(); } public void testHearBeat() throws Exception { Thread.sleep(30 * 1000); this.memcachedClient.set("queue1", 0, "hello"); assertEquals("hello", this.memcachedClient.get("queue1")); } }
3,339
441
<reponame>fanwenkai/Smooth-Line-View<filename>levinunnink-Smooth-Line-View/spline/CGPointArithmetic.h /* * CGPointArithmetic.h * Curve * * A set of tools for doing CGPoint calculations. For efficiency, these are preprocessor macros * instead of C functions. * * Created by <NAME> on 10-01-26. * Copyright 2010 <NAME>. All rights reserved. * */ #import <math.h> #define CGPointDifference(p1,p2) (CGPointMake(((p1.x) - (p2.x)), ((p1.y) - (p2.y)))) #define CGPointMagnitude(p) sqrt(p.x*p.x + p.y*p.y) #define CGPointSlope(p) (p.y / p.x) #define CGPointScale(p, d) CGPointMake(p.x * d, p.y * d) #define CGPointAdd(p1, p2) CGPointMake(p1.x + p2.x, p1.y + p2.y) #define CGPointMidpoint(p1, p2) CGPointMake((p1.x + p2.x)/2., (p1.y + p2.y)/2.)
344
663
/* * Copyright 2016-2017 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 com.github.blindpirate.gogradle.core; import com.github.blindpirate.gogradle.GolangPluginSetting; import com.github.blindpirate.gogradle.crossplatform.Arch; import com.github.blindpirate.gogradle.crossplatform.GoBinaryManager; import com.github.blindpirate.gogradle.crossplatform.Os; import com.github.blindpirate.gogradle.util.Assert; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @Singleton public class DefaultBuildConstraintManager implements BuildConstraintManager { private static final Pattern GO_VERSION_REGEX = Pattern.compile("(\\d+)\\.(\\d+).*"); private final GoBinaryManager goBinaryManager; private final GolangPluginSetting setting; private Set<String> allConstraints; @Inject public DefaultBuildConstraintManager(GoBinaryManager goBinaryManager, GolangPluginSetting setting) { this.goBinaryManager = goBinaryManager; this.setting = setting; } // https://golang.org/pkg/go/build/#hdr-Build_Constraints // We need it because we may need to analyze source code for dependencies @Override public void prepareConstraints() { Set<String> tmpAllConstraints = new HashSet<>(); tmpAllConstraints.add(Os.getHostOs().toString()); tmpAllConstraints.add(Arch.getHostArch().toString()); // gccgo/gc/cgo not supported yet tmpAllConstraints.addAll(allGoVersionConstraints()); tmpAllConstraints.addAll(setting.getBuildTags()); allConstraints = Collections.unmodifiableSet(tmpAllConstraints); } private Set<String> allGoVersionConstraints() { Set<String> ret = new HashSet<>(); String goVersion = goBinaryManager.getGoVersion(); Matcher m = GO_VERSION_REGEX.matcher(goVersion); Assert.isTrue(m.find(), "Unrecognized version:" + goVersion); int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); Assert.isTrue(major == 1, "Only go1 is supported!"); for (int i = 1; i <= minor; ++i) { ret.add("go1." + i); } return ret; } @Override public Set<String> getAllConstraints() { return allConstraints; } }
1,101
2,360
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Lcov(MakefilePackage): """LCOV is a graphical front-end for GCC's coverage testing tool gcov. It collects gcov data for multiple source files and creates HTML pages containing the source code annotated with coverage information. It also adds overview pages for easy navigation within the file structure. LCOV supports statement, function and branch coverage measurement.""" homepage = "http://ltp.sourceforge.net/coverage/lcov.php" url = "https://github.com/linux-test-project/lcov/releases/download/v1.14/lcov-1.14.tar.gz" version('1.15', sha256='c1cda2fa33bec9aa2c2c73c87226cfe97de0831887176b45ee523c5e30f8053a') version('1.14', sha256='14995699187440e0ae4da57fe3a64adc0a3c5cf14feab971f8db38fb7d8f071a') def install(self, spec, prefix): make("DESTDIR=", "PREFIX=%s" % prefix, "install")
388
344
<reponame>gaoxiaoyang/webrtc<filename>modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator.cc<gh_stars>100-1000 /* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator.h" #include <stddef.h> #include <algorithm> #include <memory> #include <utility> #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" namespace webrtc { AcknowledgedBitrateEstimator::AcknowledgedBitrateEstimator( const WebRtcKeyValueConfig* key_value_config) : AcknowledgedBitrateEstimator( key_value_config, std::make_unique<BitrateEstimator>(key_value_config)) {} AcknowledgedBitrateEstimator::~AcknowledgedBitrateEstimator() {} AcknowledgedBitrateEstimator::AcknowledgedBitrateEstimator( const WebRtcKeyValueConfig* key_value_config, std::unique_ptr<BitrateEstimator> bitrate_estimator) : in_alr_(false), bitrate_estimator_(std::move(bitrate_estimator)) {} void AcknowledgedBitrateEstimator::IncomingPacketFeedbackVector( const std::vector<PacketResult>& packet_feedback_vector) { RTC_DCHECK(std::is_sorted(packet_feedback_vector.begin(), packet_feedback_vector.end(), PacketResult::ReceiveTimeOrder())); for (const auto& packet : packet_feedback_vector) { if (alr_ended_time_ && packet.sent_packet.send_time > *alr_ended_time_) { bitrate_estimator_->ExpectFastRateChange(); alr_ended_time_.reset(); } DataSize acknowledged_estimate = packet.sent_packet.size; acknowledged_estimate += packet.sent_packet.prior_unacked_data; bitrate_estimator_->Update(packet.receive_time, acknowledged_estimate, in_alr_); } } absl::optional<DataRate> AcknowledgedBitrateEstimator::bitrate() const { return bitrate_estimator_->bitrate(); } absl::optional<DataRate> AcknowledgedBitrateEstimator::PeekRate() const { return bitrate_estimator_->PeekRate(); } void AcknowledgedBitrateEstimator::SetAlrEndedTime(Timestamp alr_ended_time) { alr_ended_time_.emplace(alr_ended_time); } void AcknowledgedBitrateEstimator::SetAlr(bool in_alr) { in_alr_ = in_alr; } } // namespace webrtc
994
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.keyvault.cryptography; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128Cbc; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192Cbc; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192CbcHmacSha384; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256Cbc; import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256CbcHmacSha512; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw128; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw192; import com.microsoft.azure.keyvault.cryptography.algorithms.AesKw256; import com.microsoft.azure.keyvault.cryptography.algorithms.Es256k; import com.microsoft.azure.keyvault.cryptography.algorithms.Es256; import com.microsoft.azure.keyvault.cryptography.algorithms.Es384; import com.microsoft.azure.keyvault.cryptography.algorithms.Es512; import com.microsoft.azure.keyvault.cryptography.algorithms.Rs256; import com.microsoft.azure.keyvault.cryptography.algorithms.Rsa15; import com.microsoft.azure.keyvault.cryptography.algorithms.RsaOaep; public class AlgorithmResolver { public static final AlgorithmResolver Default = new AlgorithmResolver(); static { Default.put(Aes128CbcHmacSha256.ALGORITHM_NAME, new Aes128CbcHmacSha256()); Default.put(Aes192CbcHmacSha384.ALGORITHM_NAME, new Aes192CbcHmacSha384()); Default.put(Aes256CbcHmacSha512.ALGORITHM_NAME, new Aes256CbcHmacSha512()); Default.put(Aes128Cbc.ALGORITHM_NAME, new Aes128Cbc()); Default.put(Aes192Cbc.ALGORITHM_NAME, new Aes192Cbc()); Default.put(Aes256Cbc.ALGORITHM_NAME, new Aes256Cbc()); Default.put(AesKw128.ALGORITHM_NAME, new AesKw128()); Default.put(AesKw192.ALGORITHM_NAME, new AesKw192()); Default.put(AesKw256.ALGORITHM_NAME, new AesKw256()); Default.put(Rsa15.ALGORITHM_NAME, new Rsa15()); Default.put(RsaOaep.ALGORITHM_NAME, new RsaOaep()); Default.put(Rs256.ALGORITHM_NAME, new Rs256()); // Default.put(RsNull.ALGORITHM_NAME, new RsNull()); Default.put(Es256k.ALGORITHM_NAME, new Es256k()); Default.put(Es256.ALGORITHM_NAME, new Es256()); Default.put(Es384.ALGORITHM_NAME, new Es384()); Default.put(Es512.ALGORITHM_NAME, new Es512()); } private final ConcurrentMap<String, Algorithm> algorithms = new ConcurrentHashMap<String, Algorithm>(); /** * Returns the implementation for an algorithm name. * * @param algorithmName The algorithm name. * @return The implementation for the algorithm or null. */ public Algorithm get(String algorithmName) { return algorithms.get(algorithmName); } /** * Add/Update a named algorithm implementation. * * @param algorithmName The algorithm name. * @param provider The implementation of the algorithm. */ public void put(String algorithmName, Algorithm provider) { algorithms.put(algorithmName, provider); } /** * Remove a named algorithm implementation. * * @param algorithmName The algorithm name */ public void remove(String algorithmName) { algorithms.remove(algorithmName); } }
1,379
348
{"nom":"Bazoches-sur-Vesles","circ":"5ème circonscription","dpt":"Aisne","inscrits":341,"abs":192,"votants":149,"blancs":0,"nuls":1,"exp":148,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":54},{"nuance":"FN","nom":"<NAME>","voix":31},{"nuance":"FI","nom":"M. <NAME>","voix":23},{"nuance":"DVD","nom":"M. <NAME>","voix":16},{"nuance":"UDI","nom":"M. <NAME>","voix":15},{"nuance":"ECO","nom":"M. <NAME>","voix":5},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"DLF","nom":"Mme <NAME>","voix":2},{"nuance":"DIV","nom":"Mme <NAME>","voix":0},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
246
777
<gh_stars>100-1000 // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_RESULTS_VIEW_H_ #define IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_RESULTS_VIEW_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/contextual_search/contextual_search_controller.h" #import "ios/chrome/browser/ui/contextual_search/contextual_search_panel_protocols.h" #import "url/gurl.h" @class Tab; @protocol ContextualSearchTabPromoter<NSObject> // Expand the search results displayed in the tab retrieved by |tabRetriever| to // a new tab, dismissing the panel. If |headerPressed| is YES, then this is // happening because of a tap on the header view. Otherwise, this is because of // navigation inside the search view. - (void)promoteTabHeaderPressed:(BOOL)headerPressed; @end @protocol ContextualSearchPreloadChecker<NSObject> // YES if it's OK to preload search results. - (BOOL)canPreloadSearchResults; @end @interface ContextualSearchResultsView : UIView<ContextualSearchPanelMotionObserver, ContextualSearchPanelScrollSynchronizer, ContextualSearchTabProvider> @property(nonatomic, assign) BOOL active; // The tab that is credited with opening the search results tab. @property(nonatomic, assign) Tab* opener; // Object that can handle promoting the search results. @property(nonatomic, assign) id<ContextualSearchTabPromoter> promoter; // Object that can determine if search results can be preloaded. @property(nonatomic, assign) id<ContextualSearchPreloadChecker> preloadChecker; // YES if the search results have loaded and this view was visible. @property(nonatomic, readonly) BOOL contentVisible; // Creates an new (internal) Tab object loading |url|; if |preloadEnabled| is // YES, then this tab will start loading as soon as possible, otherwise it will // start loading as soon as this view becomes visible. - (void)createTabForSearch:(GURL)url preloadEnabled:(BOOL)preloadEnabled; // Scroll the search results tab content so the top of the loaded page is // visible. - (void)scrollToTopAnimated:(BOOL)animated; // Record metrics for the loaded search results having finished, marking them // as 'chained' or not according to |chained|. - (void)recordFinishedSearchChained:(BOOL)chained; @end #endif // IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_RESULTS_VIEW_H_
773
327
<reponame>ClickHouse/cpp-driver /* Copyright (c) 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. */ #include "cluster.hpp" #include "constants.hpp" #include "dc_aware_policy.hpp" #include "external.hpp" #include "logger.hpp" #include "resolver.hpp" #include "round_robin_policy.hpp" #include "speculative_execution.hpp" #include "utils.hpp" using namespace datastax; using namespace datastax::internal::core; namespace datastax { namespace internal { namespace core { /** * A task for initiating the cluster close process. */ class ClusterRunClose : public Task { public: ClusterRunClose(const Cluster::Ptr& cluster) : cluster_(cluster) {} void run(EventLoop* event_loop) { cluster_->internal_close(); } private: Cluster::Ptr cluster_; }; /** * A task for marking a node as UP. */ class ClusterNotifyUp : public Task { public: ClusterNotifyUp(const Cluster::Ptr& cluster, const Address& address) : cluster_(cluster) , address_(address) {} void run(EventLoop* event_loop) { cluster_->internal_notify_host_up(address_); } private: Cluster::Ptr cluster_; Address address_; }; /** * A task for marking a node as DOWN. */ class ClusterNotifyDown : public Task { public: ClusterNotifyDown(const Cluster::Ptr& cluster, const Address& address) : cluster_(cluster) , address_(address) {} void run(EventLoop* event_loop) { cluster_->internal_notify_host_down(address_); } private: Cluster::Ptr cluster_; Address address_; }; class ClusterStartEvents : public Task { public: ClusterStartEvents(const Cluster::Ptr& cluster) : cluster_(cluster) {} void run(EventLoop* event_loop) { cluster_->internal_start_events(); } private: Cluster::Ptr cluster_; }; class ClusterStartClientMonitor : public Task { public: ClusterStartClientMonitor(const Cluster::Ptr& cluster, const String& client_id, const String& session_id, const Config& config) : cluster_(cluster) , client_id_(client_id) , session_id_(session_id) , config_(config) {} void run(EventLoop* event_loop) { cluster_->internal_start_monitor_reporting(client_id_, session_id_, config_); } private: Cluster::Ptr cluster_; String client_id_; String session_id_; Config config_; }; /** * A no operation cluster listener. This is used when a listener is not set. */ class NopClusterListener : public ClusterListener { public: virtual void on_connect(Cluster* cluster) {} virtual void on_host_up(const Host::Ptr& host) {} virtual void on_host_down(const Host::Ptr& host) {} virtual void on_host_added(const Host::Ptr& host) {} virtual void on_host_removed(const Host::Ptr& host) {} virtual void on_token_map_updated(const TokenMap::Ptr& token_map) {} virtual void on_close(Cluster* cluster) {} }; }}} // namespace datastax::internal::core void ClusterEvent::process_event(const ClusterEvent& event, ClusterListener* listener) { switch (event.type) { case HOST_UP: listener->on_host_up(event.host); break; case HOST_DOWN: listener->on_host_down(event.host); break; case HOST_ADD: listener->on_host_added(event.host); break; case HOST_REMOVE: listener->on_host_removed(event.host); break; case HOST_MAYBE_UP: listener->on_host_maybe_up(event.host); break; case HOST_READY: listener->on_host_ready(event.host); break; case TOKEN_MAP_UPDATE: listener->on_token_map_updated(event.token_map); break; } } void ClusterEvent::process_events(const ClusterEvent::Vec& events, ClusterListener* listener) { for (ClusterEvent::Vec::const_iterator it = events.begin(), end = events.end(); it != end; ++it) { process_event(*it, listener); } } static NopClusterListener nop_cluster_listener__; LockedHostMap::LockedHostMap(const HostMap& hosts) : hosts_(hosts) { uv_mutex_init(&mutex_); } LockedHostMap::~LockedHostMap() { uv_mutex_destroy(&mutex_); } LockedHostMap::const_iterator LockedHostMap::find(const Address& address) const { HostMap::const_iterator it = hosts_.find(address); if (it == hosts_.end()) { // If this is from an event (not SNI) and we're using SNI addresses then fallback to using the // "rpc_address" to compare. for (HostMap::const_iterator i = hosts_.begin(), end = hosts_.end(); i != end; ++i) { if (i->second->rpc_address() == address) { return i; } } } return it; } Host::Ptr LockedHostMap::get(const Address& address) const { ScopedMutex l(&mutex_); const_iterator it = find(address); if (it == end()) return Host::Ptr(); return it->second; } void LockedHostMap::erase(const Address& address) { ScopedMutex l(&mutex_); hosts_.erase(address); } Host::Ptr& LockedHostMap::operator[](const Address& address) { ScopedMutex l(&mutex_); return hosts_[address]; } LockedHostMap& LockedHostMap::operator=(const HostMap& hosts) { ScopedMutex l(&mutex_); hosts_ = hosts; return *this; } ClusterSettings::ClusterSettings() : load_balancing_policy(new RoundRobinPolicy()) , port(CASS_DEFAULT_PORT) , reconnection_policy(new ExponentialReconnectionPolicy()) , prepare_on_up_or_add_host(CASS_DEFAULT_PREPARE_ON_UP_OR_ADD_HOST) , max_prepares_per_flush(CASS_DEFAULT_MAX_PREPARES_PER_FLUSH) , disable_events_on_startup(false) , cluster_metadata_resolver_factory(new DefaultClusterMetadataResolverFactory()) { load_balancing_policies.push_back(load_balancing_policy); } ClusterSettings::ClusterSettings(const Config& config) : control_connection_settings(config) , load_balancing_policy(config.load_balancing_policy()) , load_balancing_policies(config.load_balancing_policies()) , port(config.port()) , reconnection_policy(config.reconnection_policy()) , prepare_on_up_or_add_host(config.prepare_on_up_or_add_host()) , max_prepares_per_flush(CASS_DEFAULT_MAX_PREPARES_PER_FLUSH) , disable_events_on_startup(false) , cluster_metadata_resolver_factory(config.cluster_metadata_resolver_factory()) {} Cluster::Cluster(const ControlConnection::Ptr& connection, ClusterListener* listener, EventLoop* event_loop, const Host::Ptr& connected_host, const HostMap& hosts, const ControlConnectionSchema& schema, const LoadBalancingPolicy::Ptr& load_balancing_policy, const LoadBalancingPolicy::Vec& load_balancing_policies, const String& local_dc, const StringMultimap& supported_options, const ClusterSettings& settings) : connection_(connection) , listener_(listener ? listener : &nop_cluster_listener__) , event_loop_(event_loop) , load_balancing_policy_(load_balancing_policy) , load_balancing_policies_(load_balancing_policies) , settings_(settings) , is_closing_(false) , connected_host_(connected_host) , hosts_(hosts) , local_dc_(local_dc) , supported_options_(supported_options) , is_recording_events_(settings.disable_events_on_startup) { inc_ref(); connection_->set_listener(this); query_plan_.reset(load_balancing_policy_->new_query_plan("", NULL, NULL)); update_schema(schema); update_token_map(hosts, connected_host_->partitioner(), schema); listener_->on_reconnect(this); } void Cluster::close() { event_loop_->add(new ClusterRunClose(Ptr(this))); } void Cluster::notify_host_up(const Address& address) { event_loop_->add(new ClusterNotifyUp(Ptr(this), address)); } void Cluster::notify_host_down(const Address& address) { event_loop_->add(new ClusterNotifyDown(Ptr(this), address)); } void Cluster::start_events() { event_loop_->add(new ClusterStartEvents(Ptr(this))); } void Cluster::start_monitor_reporting(const String& client_id, const String& session_id, const Config& config) { event_loop_->add(new ClusterStartClientMonitor(Ptr(this), client_id, session_id, config)); } Metadata::SchemaSnapshot Cluster::schema_snapshot() { return metadata_.schema_snapshot(); } Host::Ptr Cluster::find_host(const Address& address) const { return hosts_.get(address); } PreparedMetadata::Entry::Ptr Cluster::prepared(const String& id) const { return prepared_metadata_.get(id); } void Cluster::prepared(const String& id, const PreparedMetadata::Entry::Ptr& entry) { prepared_metadata_.set(id, entry); } HostMap Cluster::available_hosts() const { HostMap available; for (HostMap::const_iterator it = hosts_.begin(), end = hosts_.end(); it != end; ++it) { if (!is_host_ignored(it->second)) { available[it->first] = it->second; } } return available; } void Cluster::set_listener(ClusterListener* listener) { listener_ = listener ? listener : &nop_cluster_listener__; } void Cluster::update_hosts(const HostMap& hosts) { // Update the hosts and properly notify the listener HostMap existing(hosts_); for (HostMap::const_iterator it = hosts.begin(), end = hosts.end(); it != end; ++it) { HostMap::iterator find_it = existing.find(it->first); if (find_it != existing.end()) { existing.erase(find_it); // Already exists mark as visited } else { notify_host_add(it->second); // A new host has been added } } // Any hosts that existed before, but aren't in the new hosts // need to be marked as removed. for (HostMap::const_iterator it = existing.begin(), end = existing.end(); it != end; ++it) { notify_host_remove(it->first); } } void Cluster::update_schema(const ControlConnectionSchema& schema) { metadata_.clear_and_update_back(connection_->server_version()); if (schema.keyspaces) { metadata_.update_keyspaces(schema.keyspaces.get(), false); } if (schema.tables) { metadata_.update_tables(schema.tables.get()); } if (schema.views) { metadata_.update_views(schema.views.get()); } if (schema.columns) { metadata_.update_columns(schema.columns.get()); } if (schema.indexes) { metadata_.update_indexes(schema.indexes.get()); } if (schema.user_types) { metadata_.update_user_types(schema.user_types.get()); } if (schema.functions) { metadata_.update_functions(schema.functions.get()); } if (schema.aggregates) { metadata_.update_aggregates(schema.aggregates.get()); } if (schema.virtual_keyspaces) { metadata_.update_keyspaces(schema.virtual_keyspaces.get(), true); } if (schema.virtual_tables) { metadata_.update_tables(schema.virtual_tables.get()); } if (schema.virtual_columns) { metadata_.update_columns(schema.virtual_columns.get()); } metadata_.swap_to_back_and_update_front(); } void Cluster::update_token_map(const HostMap& hosts, const String& partitioner, const ControlConnectionSchema& schema) { if (settings_.control_connection_settings.use_token_aware_routing && schema.keyspaces) { // Create a new token map and populate it token_map_ = TokenMap::from_partitioner(partitioner); if (!token_map_) { return; // Partition is not supported } token_map_->add_keyspaces(connection_->server_version(), schema.keyspaces.get()); for (HostMap::const_iterator it = hosts.begin(), end = hosts.end(); it != end; ++it) { token_map_->add_host(it->second); } token_map_->build(); } } // All hosts from the cluster are included in the host map and in the load // balancing policies (LBP) so that LBPs return the correct host distance (esp. // important for DC-aware). This method prevents connection pools from being // created to ignored hosts. bool Cluster::is_host_ignored(const Host::Ptr& host) const { return core::is_host_ignored(load_balancing_policies_, host); } void Cluster::schedule_reconnect() { if (!reconnection_schedule_) { reconnection_schedule_.reset(settings_.reconnection_policy->new_reconnection_schedule()); } uint64_t delay_ms = reconnection_schedule_->next_delay_ms(); if (delay_ms > 0) { timer_.start(connection_->loop(), delay_ms, bind_callback(&Cluster::on_schedule_reconnect, this)); } else { handle_schedule_reconnect(); } } void Cluster::on_schedule_reconnect(Timer* timer) { handle_schedule_reconnect(); } void Cluster::handle_schedule_reconnect() { const Host::Ptr& host = query_plan_->compute_next(); if (host) { reconnector_.reset(new ControlConnector(host, connection_->protocol_version(), bind_callback(&Cluster::on_reconnect, this))); reconnector_->with_settings(settings_.control_connection_settings) ->connect(connection_->loop()); } else { // No more hosts, refresh the query plan and schedule a re-connection LOG_TRACE("Control connection query plan has no more hosts. " "Reset query plan and schedule reconnect"); query_plan_.reset(load_balancing_policy_->new_query_plan("", NULL, NULL)); schedule_reconnect(); } } void Cluster::on_reconnect(ControlConnector* connector) { reconnector_.reset(); if (is_closing_) { handle_close(); return; } if (connector->is_ok()) { connection_ = connector->release_connection(); connection_->set_listener(this); // Incrementally update the hosts (notifying the listener) update_hosts(connector->hosts()); // Get the newly connected host connected_host_ = hosts_[connection_->address()]; assert(connected_host_ && "Connected host not found in hosts map"); update_schema(connector->schema()); update_token_map(connector->hosts(), connected_host_->partitioner(), connector->schema()); // Notify the listener that we've built a new token map if (token_map_) { notify_or_record(ClusterEvent(token_map_)); } LOG_INFO("Control connection connected to %s", connected_host_->address_string().c_str()); listener_->on_reconnect(this); reconnection_schedule_.reset(); } else if (!connector->is_canceled()) { LOG_ERROR( "Unable to reestablish a control connection to host %s because of the following error: %s", connector->address().to_string().c_str(), connector->error_message().c_str()); schedule_reconnect(); } } void Cluster::internal_close() { is_closing_ = true; bool was_timer_running = timer_.is_running(); timer_.stop(); monitor_reporting_timer_.stop(); if (was_timer_running) { handle_close(); } else if (reconnector_) { reconnector_->cancel(); } else if (connection_) { connection_->close(); } } void Cluster::handle_close() { for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->close_handles(); } connection_.reset(); listener_->on_close(this); dec_ref(); } void Cluster::internal_notify_host_up(const Address& address) { LockedHostMap::const_iterator it = hosts_.find(address); if (it == hosts_.end()) { LOG_WARN("Attempting to mark host %s that we don't have as UP", address.to_string().c_str()); return; } Host::Ptr host(it->second); if (load_balancing_policy_->is_host_up(address)) { // Already marked up so don't repeat duplicate notifications. if (!is_host_ignored(host)) { notify_or_record(ClusterEvent(ClusterEvent::HOST_READY, host)); } return; } for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->on_host_up(host); } if (is_host_ignored(host)) { return; // Ignore host } if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_up, Cluster::Ptr(this)))) { notify_host_up_after_prepare(host); } } void Cluster::notify_host_up_after_prepare(const Host::Ptr& host) { notify_or_record(ClusterEvent(ClusterEvent::HOST_READY, host)); notify_or_record(ClusterEvent(ClusterEvent::HOST_UP, host)); } void Cluster::internal_notify_host_down(const Address& address) { LockedHostMap::const_iterator it = hosts_.find(address); if (it == hosts_.end()) { // Using DEBUG level here because this can happen normally as the result of // a remove event. LOG_DEBUG("Attempting to mark host %s that we don't have as DOWN", address.to_string().c_str()); return; } Host::Ptr host(it->second); if (!load_balancing_policy_->is_host_up(address)) { // Already marked down so don't repeat duplicate notifications. return; } for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->on_host_down(address); } notify_or_record(ClusterEvent(ClusterEvent::HOST_DOWN, host)); } void Cluster::internal_start_events() { // Ignore if closing or already processed events if (!is_closing_ && is_recording_events_) { is_recording_events_ = false; ClusterEvent::process_events(recorded_events_, listener_); recorded_events_.clear(); } } void Cluster::internal_start_monitor_reporting(const String& client_id, const String& session_id, const Config& config) { monitor_reporting_.reset(create_monitor_reporting(client_id, session_id, config)); if (!is_closing_ && monitor_reporting_->interval_ms(connection_->dse_server_version()) > 0) { monitor_reporting_->send_startup_message(connection_->connection(), config, available_hosts(), load_balancing_policies_); monitor_reporting_timer_.start( event_loop_->loop(), monitor_reporting_->interval_ms(connection_->dse_server_version()), bind_callback(&Cluster::on_monitor_reporting, this)); } } void Cluster::on_monitor_reporting(Timer* timer) { if (!is_closing_) { monitor_reporting_->send_status_message(connection_->connection(), available_hosts()); monitor_reporting_timer_.start( event_loop_->loop(), monitor_reporting_->interval_ms(connection_->dse_server_version()), bind_callback(&Cluster::on_monitor_reporting, this)); } } void Cluster::notify_host_add(const Host::Ptr& host) { LockedHostMap::const_iterator host_it = hosts_.find(host->address()); if (host_it != hosts_.end()) { LOG_WARN("Attempting to add host %s that we already have", host->address_string().c_str()); // If an entry already exists then notify that the node has been removed // then re-add it. for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->on_host_removed(host_it->second); } notify_or_record(ClusterEvent(ClusterEvent::HOST_REMOVE, host)); } hosts_[host->address()] = host; for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->on_host_added(host); } if (is_host_ignored(host)) { return; // Ignore host } if (!prepare_host(host, bind_callback(&Cluster::on_prepare_host_add, Cluster::Ptr(this)))) { notify_host_add_after_prepare(host); } } void Cluster::notify_host_add_after_prepare(const Host::Ptr& host) { if (token_map_) { token_map_ = token_map_->copy(); token_map_->update_host_and_build(host); notify_or_record(ClusterEvent(token_map_)); } notify_or_record(ClusterEvent(ClusterEvent::HOST_ADD, host)); } void Cluster::notify_host_remove(const Address& address) { LockedHostMap::const_iterator it = hosts_.find(address); if (it == hosts_.end()) { LOG_WARN("Attempting removing host %s that we don't have", address.to_string().c_str()); return; } Host::Ptr host(it->second); if (token_map_) { token_map_ = token_map_->copy(); token_map_->remove_host_and_build(host); notify_or_record(ClusterEvent(token_map_)); } // If not marked down yet then explicitly trigger the event. if (load_balancing_policy_->is_host_up(address)) { notify_or_record(ClusterEvent(ClusterEvent::HOST_DOWN, host)); } hosts_.erase(it->first); for (LoadBalancingPolicy::Vec::const_iterator it = load_balancing_policies_.begin(), end = load_balancing_policies_.end(); it != end; ++it) { (*it)->on_host_removed(host); } notify_or_record(ClusterEvent(ClusterEvent::HOST_REMOVE, host)); } void Cluster::notify_or_record(const ClusterEvent& event) { if (is_recording_events_) { recorded_events_.push_back(event); } else { ClusterEvent::process_event(event, listener_); } } bool Cluster::prepare_host(const Host::Ptr& host, const PrepareHostHandler::Callback& callback) { if (connection_ && settings_.prepare_on_up_or_add_host) { PrepareHostHandler::Ptr prepare_host_handler( new PrepareHostHandler(host, prepared_metadata_.copy(), callback, connection_->protocol_version(), settings_.max_prepares_per_flush)); prepare_host_handler->prepare(connection_->loop(), settings_.control_connection_settings.connection_settings); return true; } return false; } void Cluster::on_prepare_host_add(const PrepareHostHandler* handler) { notify_host_add_after_prepare(handler->host()); } void Cluster::on_prepare_host_up(const PrepareHostHandler* handler) { notify_host_up_after_prepare(handler->host()); } void Cluster::on_update_schema(SchemaType type, const ResultResponse::Ptr& result, const String& keyspace_name, const String& target_name) { switch (type) { case KEYSPACE: // Virtual keyspaces are not updated (always false) metadata_.update_keyspaces(result.get(), false); if (token_map_) { token_map_ = token_map_->copy(); token_map_->update_keyspaces_and_build(connection_->server_version(), result.get()); notify_or_record(ClusterEvent(token_map_)); } break; case TABLE: metadata_.update_tables(result.get()); break; case VIEW: metadata_.update_views(result.get()); break; case COLUMN: metadata_.update_columns(result.get()); break; case INDEX: metadata_.update_indexes(result.get()); break; case USER_TYPE: metadata_.update_user_types(result.get()); break; case FUNCTION: metadata_.update_functions(result.get()); break; case AGGREGATE: metadata_.update_aggregates(result.get()); break; } } void Cluster::on_drop_schema(SchemaType type, const String& keyspace_name, const String& target_name) { switch (type) { case KEYSPACE: metadata_.drop_keyspace(keyspace_name); if (token_map_) { token_map_ = token_map_->copy(); token_map_->drop_keyspace(keyspace_name); notify_or_record(ClusterEvent(token_map_)); } break; case TABLE: metadata_.drop_table_or_view(keyspace_name, target_name); break; case VIEW: metadata_.drop_table_or_view(keyspace_name, target_name); break; case USER_TYPE: metadata_.drop_user_type(keyspace_name, target_name); break; case FUNCTION: metadata_.drop_function(keyspace_name, target_name); break; case AGGREGATE: metadata_.drop_aggregate(keyspace_name, target_name); break; default: break; } } void Cluster::on_up(const Address& address) { LockedHostMap::const_iterator it = hosts_.find(address); if (it == hosts_.end()) { LOG_WARN("Received UP event for an unknown host %s", address.to_string().c_str()); return; } notify_or_record(ClusterEvent(ClusterEvent::HOST_MAYBE_UP, it->second)); } void Cluster::on_down(const Address& address) { // Ignore down events from the control connection. Use the method // `notify_host_down()` to trigger the DOWN status. } void Cluster::on_add(const Host::Ptr& host) { notify_host_add(host); } void Cluster::on_remove(const Address& address) { notify_host_remove(address); } void Cluster::on_close(ControlConnection* connection) { if (!is_closing_) { LOG_WARN("Lost control connection to host %s", connection_->address_string().c_str()); schedule_reconnect(); } else { handle_close(); } }
9,343
5,169
{ "name": "Shanyan", "version": "0.0.1", "summary": "A short description of Shanyan.", "description": "Shanyan SDK.", "homepage": "http://colorv.cn/Shanyan", "license": "MIT", "authors": { "jichengcolorv": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "<EMAIL>:cvios/vendor_shanyan.git", "tag": "0.0.1" }, "vendored_frameworks": "TYRZSDK.framework", "resources": "uni_account_login_sdk_res.bundle" }
208
746
// 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. #include "scheduling/admissiond-env.h" #include "common/daemon-env.h" #include "rpc/rpc-mgr.h" #include "runtime/mem-tracker.h" #include "scheduling/admission-control-service.h" #include "scheduling/admission-controller.h" #include "scheduling/cluster-membership-mgr.h" #include "scheduling/scheduler.h" #include "service/impala-http-handler.h" #include "util/default-path-handlers.h" #include "util/mem-info.h" #include "util/memory-metrics.h" #include "util/metrics.h" #include "util/uid-util.h" #include "common/names.h" DEFINE_int32( admission_service_port, 29500, "The port where the admission control service runs"); DECLARE_string(state_store_host); DECLARE_int32(state_store_port); DECLARE_int32(state_store_subscriber_port); DECLARE_string(hostname); namespace impala { AdmissiondEnv* AdmissiondEnv::admissiond_env_ = nullptr; AdmissiondEnv::AdmissiondEnv() : pool_mem_trackers_(new PoolMemTrackerRegistry), request_pool_service_(new RequestPoolService(DaemonEnv::GetInstance()->metrics())), rpc_mgr_(new RpcMgr(IsInternalTlsConfigured())), rpc_metrics_(DaemonEnv::GetInstance()->metrics()->GetOrCreateChildGroup("rpc")) { MetricGroup* metrics = DaemonEnv::GetInstance()->metrics(); TNetworkAddress admission_service_addr = MakeNetworkAddress(FLAGS_hostname, FLAGS_admission_service_port); TNetworkAddress subscriber_address = MakeNetworkAddress(FLAGS_hostname, FLAGS_state_store_subscriber_port); TNetworkAddress statestore_address = MakeNetworkAddress(FLAGS_state_store_host, FLAGS_state_store_port); statestore_subscriber_.reset(new StatestoreSubscriber( Substitute("admissiond@$0", TNetworkAddressToString(admission_service_addr)), subscriber_address, statestore_address, metrics)); scheduler_.reset(new Scheduler(metrics, request_pool_service())); cluster_membership_mgr_.reset(new ClusterMembershipMgr( PrintId(DaemonEnv::GetInstance()->backend_id()), subscriber(), metrics)); admission_controller_.reset(new AdmissionController(cluster_membership_mgr(), subscriber(), request_pool_service(), metrics, scheduler(), pool_mem_trackers(), admission_service_addr)); http_handler_.reset(ImpalaHttpHandler::CreateAdmissiondHandler( admission_controller_.get(), cluster_membership_mgr_.get())); admissiond_env_ = this; } AdmissiondEnv::~AdmissiondEnv() { if (rpc_mgr_ != nullptr) rpc_mgr_->Shutdown(); } Status AdmissiondEnv::Init() { int64_t bytes_limit; RETURN_IF_ERROR(ChooseProcessMemLimit(&bytes_limit)); mem_tracker_.reset( new MemTracker(AggregateMemoryMetrics::TOTAL_USED, bytes_limit, "Process")); mem_tracker_->RegisterMetrics( DaemonEnv::GetInstance()->metrics(), "mem-tracker.process"); http_handler_->RegisterHandlers(DaemonEnv::GetInstance()->webserver()); string ip_address; RETURN_IF_ERROR(HostnameToIpAddr(FLAGS_hostname, &ip_address)); TNetworkAddress ip_addr_port; ip_addr_port.__set_hostname(ip_address); ip_addr_port.__set_port(FLAGS_admission_service_port); RETURN_IF_ERROR(rpc_mgr_->Init(ip_addr_port)); admission_control_svc_.reset( new AdmissionControlService(DaemonEnv::GetInstance()->metrics())); RETURN_IF_ERROR(admission_control_svc_->Init()); RETURN_IF_ERROR(cluster_membership_mgr_->Init()); cluster_membership_mgr_->RegisterUpdateCallbackFn( [&](ClusterMembershipMgr::SnapshotPtr snapshot) { std::unordered_set<BackendIdPB> current_backends; for (const auto& it : snapshot->current_backends) { current_backends.insert(it.second.backend_id()); } admission_control_svc_->CancelQueriesOnFailedCoordinators(current_backends); }); RETURN_IF_ERROR(admission_controller_->Init()); return Status::OK(); } Status AdmissiondEnv::StartServices() { LOG(INFO) << "Starting statestore subscriber service"; // Must happen after all topic registrations / callbacks are done if (statestore_subscriber_.get() != nullptr) { Status status = statestore_subscriber_->Start(); if (!status.ok()) { status.AddDetail("Statestore subscriber did not start up."); return status; } } LOG(INFO) << "Starting KRPC service."; RETURN_IF_ERROR(rpc_mgr_->StartServices()); return Status::OK(); } } // namespace impala
1,755
4,036
<gh_stars>1000+ // Generated automatically from com.google.common.collect.RegularImmutableSortedSet for testing purposes package com.google.common.collect; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.UnmodifiableIterator; import java.util.Collection; import java.util.Comparator; import java.util.Spliterator; import java.util.function.Consumer; class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> { protected RegularImmutableSortedSet() {} Comparator<Object> unsafeComparator(){ return null; } ImmutableList<E> createAsList(){ return null; } ImmutableSortedSet<E> createDescendingSet(){ return null; } ImmutableSortedSet<E> headSetImpl(E p0, boolean p1){ return null; } ImmutableSortedSet<E> subSetImpl(E p0, boolean p1, E p2, boolean p3){ return null; } ImmutableSortedSet<E> tailSetImpl(E p0, boolean p1){ return null; } Object[] internalArray(){ return null; } RegularImmutableSortedSet(ImmutableList<E> p0, Comparator<? super E> p1){} RegularImmutableSortedSet<E> getSubSet(int p0, int p1){ return null; } boolean isPartialView(){ return false; } int copyIntoArray(Object[] p0, int p1){ return 0; } int headIndex(E p0, boolean p1){ return 0; } int indexOf(Object p0){ return 0; } int internalArrayEnd(){ return 0; } int internalArrayStart(){ return 0; } int tailIndex(E p0, boolean p1){ return 0; } public E ceiling(E p0){ return null; } public E first(){ return null; } public E floor(E p0){ return null; } public E higher(E p0){ return null; } public E last(){ return null; } public E lower(E p0){ return null; } public Spliterator<E> spliterator(){ return null; } public UnmodifiableIterator<E> descendingIterator(){ return null; } public UnmodifiableIterator<E> iterator(){ return null; } public boolean contains(Object p0){ return false; } public boolean containsAll(Collection<? extends Object> p0){ return false; } public boolean equals(Object p0){ return false; } public int size(){ return 0; } public void forEach(Consumer<? super E> p0){} static RegularImmutableSortedSet<Comparable> NATURAL_EMPTY_SET = null; }
752
1,467
/* * Copyright 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://aws.amazon.com/apache2.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. * * Original source licensed under the Apache License 2.0 by playframework. */ package software.amazon.awssdk.http.nio.netty.internal.nrs.util; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import java.util.concurrent.Executor; /** * A batched producer. * * Responds to read requests with batches of elements according to batch size. When eofOn is reached, it closes the * channel. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ public class BatchedProducer extends ChannelOutboundHandlerAdapter { protected final long eofOn; protected final int batchSize; private final Executor executor; protected long sequence; public BatchedProducer(long eofOn, int batchSize, long sequence, Executor executor) { this.eofOn = eofOn; this.batchSize = batchSize; this.sequence = sequence; this.executor = executor; } private boolean cancelled = false; @Override public void read(final ChannelHandlerContext ctx) throws Exception { if (cancelled) { throw new IllegalStateException("Received demand after being cancelled"); } executor.execute(() -> { for (int i = 0; i < batchSize && sequence != eofOn; i++) { ctx.fireChannelRead(sequence++); } if (eofOn == sequence) { ctx.fireChannelInactive(); } else { ctx.fireChannelReadComplete(); } }); } @Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { if (cancelled) { throw new IllegalStateException("Cancelled twice"); } cancelled = true; } }
940
20,453
<reponame>iam-abbas/numpy<filename>numpy/core/src/common/simd/avx512/maskop.h #ifndef NPY_SIMD #error "Not a standalone header, use simd/simd.h instead" #endif #ifndef _NPY_SIMD_AVX512_MASKOP_H #define _NPY_SIMD_AVX512_MASKOP_H /** * Implements conditional addition and subtraction. * e.g. npyv_ifadd_f32(m, a, b, c) -> m ? a + b : c * e.g. npyv_ifsub_f32(m, a, b, c) -> m ? a - b : c */ #define NPYV_IMPL_AVX512_EMULATE_MASK_ADDSUB(SFX, BSFX) \ NPY_FINLINE npyv_##SFX npyv_ifadd_##SFX \ (npyv_##BSFX m, npyv_##SFX a, npyv_##SFX b, npyv_##SFX c) \ { \ npyv_##SFX add = npyv_add_##SFX(a, b); \ return npyv_select_##SFX(m, add, c); \ } \ NPY_FINLINE npyv_##SFX npyv_ifsub_##SFX \ (npyv_##BSFX m, npyv_##SFX a, npyv_##SFX b, npyv_##SFX c) \ { \ npyv_##SFX sub = npyv_sub_##SFX(a, b); \ return npyv_select_##SFX(m, sub, c); \ } #define NPYV_IMPL_AVX512_MASK_ADDSUB(SFX, BSFX, ZSFX) \ NPY_FINLINE npyv_##SFX npyv_ifadd_##SFX \ (npyv_##BSFX m, npyv_##SFX a, npyv_##SFX b, npyv_##SFX c) \ { return _mm512_mask_add_##ZSFX(c, m, a, b); } \ NPY_FINLINE npyv_##SFX npyv_ifsub_##SFX \ (npyv_##BSFX m, npyv_##SFX a, npyv_##SFX b, npyv_##SFX c) \ { return _mm512_mask_sub_##ZSFX(c, m, a, b); } #ifdef NPY_HAVE_AVX512BW NPYV_IMPL_AVX512_MASK_ADDSUB(u8, b8, epi8) NPYV_IMPL_AVX512_MASK_ADDSUB(s8, b8, epi8) NPYV_IMPL_AVX512_MASK_ADDSUB(u16, b16, epi16) NPYV_IMPL_AVX512_MASK_ADDSUB(s16, b16, epi16) #else NPYV_IMPL_AVX512_EMULATE_MASK_ADDSUB(u8, b8) NPYV_IMPL_AVX512_EMULATE_MASK_ADDSUB(s8, b8) NPYV_IMPL_AVX512_EMULATE_MASK_ADDSUB(u16, b16) NPYV_IMPL_AVX512_EMULATE_MASK_ADDSUB(s16, b16) #endif NPYV_IMPL_AVX512_MASK_ADDSUB(u32, b32, epi32) NPYV_IMPL_AVX512_MASK_ADDSUB(s32, b32, epi32) NPYV_IMPL_AVX512_MASK_ADDSUB(u64, b64, epi64) NPYV_IMPL_AVX512_MASK_ADDSUB(s64, b64, epi64) NPYV_IMPL_AVX512_MASK_ADDSUB(f32, b32, ps) NPYV_IMPL_AVX512_MASK_ADDSUB(f64, b64, pd) #endif // _NPY_SIMD_AVX512_MASKOP_H
1,540
7,892
<filename>src/toolbars/MeterToolBar.h /********************************************************************** Audacity: A Digital Audio Editor MeterToolbar.h <NAME> <NAME> ToolBar to hold the VU Meter **********************************************************************/ #ifndef __AUDACITY_METER_TOOLBAR__ #define __AUDACITY_METER_TOOLBAR__ #include "ToolBar.h" class wxDC; class wxGridBagSizer; class wxSizeEvent; class wxWindow; class AudacityProject; class MeterPanel; // Constants used as bit pattern const int kWithRecordMeter = 1; const int kWithPlayMeter = 2; class MeterToolBar final : public ToolBar { public: MeterToolBar(AudacityProject &project, int type); virtual ~MeterToolBar(); void Create(wxWindow *parent) override; void Populate() override; void ReCreateButtons() override; void Repaint(wxDC * WXUNUSED(dc)) override {}; void EnableDisableButtons() override {}; void UpdatePrefs() override; void OnSize(wxSizeEvent & event); bool Expose(bool show) override; int GetInitialWidth() override {return (mWhichMeters == (kWithRecordMeter + kWithPlayMeter)) ? 338 : 460;} // Separate bars used to be smaller. int GetMinToolbarWidth() override { return 150; } wxSize GetDockedSize() override { return GetSmartDockedSize(); }; virtual void SetDocked(ToolDock *dock, bool pushed)override; private: void RegenerateTooltips() override; int mWhichMeters; wxGridBagSizer *mSizer; MeterPanel *mPlayMeter; MeterPanel *mRecordMeter; public: DECLARE_CLASS(MeterToolBar) DECLARE_EVENT_TABLE() }; #endif
539
460
<filename>trunk/win/Source/BT_TexHelperManager.cpp // Copyright 2012 Google 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. #include "BT_Common.h" #include "BT_TexHelperManager.h" #include "TexHelperResponse.h" struct Pipe { HANDLE out_w; //write handle to std out for child process HANDLE out_r; //read handle to std out for child process HANDLE in_w; //write handle to std in for child process HANDLE in_r; //read handle to std in for child process }; TexHelperManager::~TexHelperManager() { SAFE_DELETE_ARRAY(_pipes); SAFE_DELETE_ARRAY(_pipeBusy); if (_processInfos) { for (unsigned int i = 0; i < _processCount; i++) TerminateProcess(_processInfos[i].hProcess, 1); } SAFE_DELETE_ARRAY(_processInfos); SAFE_DELETE_ARRAY(_startupInfos); } TexHelperManager::TexHelperManager(QString processPath, unsigned int processCount) { _processPath = processPath; _processCount = processCount; //SYSTEM_INFO sysInfo; //GetNativeSystemInfo(&sysInfo); //const unsigned int MINIMUM_PROCESS_COUNT = 2; //_processCount = sysInfo.dwNumberOfProcessors - 1 < MINIMUM_PROCESS_COUNT ? MINIMUM_PROCESS_COUNT : sysInfo.dwNumberOfProcessors - 1; _processInfos = new PROCESS_INFORMATION [_processCount]; _startupInfos = new STARTUPINFO [_processCount]; _pipes = new Pipe [_processCount]; _pipeBusy = new bool [_processCount]; for (unsigned int i = 0; i < _processCount; i++) { _pipeBusy[i] = false; SECURITY_ATTRIBUTES sa = {0}; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = true; sa.lpSecurityDescriptor = NULL; if (!CreatePipe(&_pipes[i].out_r, &_pipes[i].out_w, &sa, 0x40000)) // Create a pipe for the child process's STDOUT. puts("Failed StdoutRd CreatePipe \n"); if (!SetHandleInformation(_pipes[i].out_r, HANDLE_FLAG_INHERIT, 0)) // Ensure the read handle to the pipe for STDOUT is not inherited. puts("Failed Stdout SetHandleInformation \n"); if (!CreatePipe(&_pipes[i].in_r, &_pipes[i].in_w, &sa, 1024)) // Create a pipe for the child process's STDIN. puts("Stdin CreatePipe \n"); if (!SetHandleInformation(_pipes[i].in_w, HANDLE_FLAG_INHERIT, 0)) // Ensure the write handle to the pipe for STDIN is not inherited. puts("Stdin SetHandleInformation \n"); restartPipe(i); } } // Returns true if response is read and valid, false if no response available and not valid bool readResponse(HANDLE inHandle, TexHelperResponse & response) { unsigned long read = 0, available = 0, left = 0; PeekNamedPipe(inHandle, NULL, 0, NULL, &available, &left); if (sizeof(response) <= available) { read = 0; bool result = ReadFile(inHandle, &response, sizeof(response), &read, NULL); result &= sizeof(response) == read; _ASSERT(result); _ASSERT(response.calculateCheckSum() == response.CheckSum); if (!result) puts("TexHelperManager readResponse failed"); if (response.calculateCheckSum() != response.CheckSum) puts("TexHelperManager readResponse checksum failed"); return result; } else return false; } bool clearPipe(HANDLE inHandle) { unsigned long read = 0, available = 0, left = 0; PeekNamedPipe(inHandle, NULL, 0, NULL, &available, &left); if (0 < available) { unsigned char * buffer = new unsigned char [available]; ReadFile(inHandle, buffer, available, &read, NULL); delete [] buffer; return true; } else return false; } bool TexHelperManager::isPipeBusy(unsigned int texhelperId) const { _ASSERT(texhelperId < _processCount); return _pipeBusy[texhelperId]; } void TexHelperManager::freePipe(unsigned int texhelperId) { QMutexLocker mutexLocker(&_mutex); _ASSERT(texhelperId < _processCount); _ASSERT(_pipeBusy[texhelperId]); _pipeBusy[texhelperId] = false; } unsigned int TexHelperManager::getPipe() { QMutexLocker mutexLocker(&_mutex); for (unsigned int i = 0; i< _processCount; i++) { if (!_pipeBusy[i]) { _pipeBusy[i] = true; return i; } } VASSERT(0, QString_NT("TexHelperManager::getPipe no available pipe, assigning new process id 0xFFFFFFFF (ignore)")); return 0xFFFFFFFF; } void TexHelperManager::restartPipe(unsigned int texhelperId) { _ASSERT(texhelperId < _processCount); if (_processInfos[texhelperId].hProcess) TerminateProcess(_processInfos[texhelperId].hProcess, 1); clearPipe(_pipes[texhelperId].out_r); SECURITY_ATTRIBUTES sa = {0}; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = true; sa.lpSecurityDescriptor = NULL; ZeroMemory(&_processInfos[texhelperId], sizeof(*_processInfos)); ZeroMemory(&_startupInfos[texhelperId], sizeof(*_startupInfos)); _startupInfos[texhelperId].cb = sizeof(STARTUPINFO); _startupInfos[texhelperId].hStdError = NULL; _startupInfos[texhelperId].hStdOutput = _pipes[texhelperId].out_w; _startupInfos[texhelperId].hStdInput = _pipes[texhelperId].in_r; _startupInfos[texhelperId].dwFlags |= STARTF_USESTDHANDLES; bool success = CreateProcess((wchar_t *)_processPath.utf16(), NULL, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited CREATE_NO_WINDOW | DETACHED_PROCESS, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &_startupInfos[texhelperId], // STARTUPINFO pointer &_processInfos[texhelperId]); // receives PROCESS_INFORMATION _ASSERT(success); } int TexHelperManager::texHelperOperation(QString command, unsigned int texhelperId, unsigned long long lifeTime, TexHelperResponse * outResponse, void ** outData) { LARGE_INTEGER frequency, anchorTime, currentTime, maximumTime; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&anchorTime); maximumTime.QuadPart = anchorTime.QuadPart + lifeTime * frequency.QuadPart / 1000; _ASSERT(maximumTime.QuadPart > anchorTime.QuadPart); _ASSERT(texhelperId < _processCount); _ASSERT(_pipeBusy[texhelperId]); unsigned long readyRead = 0; TexHelperResponse readyResponse; ReadFile(_pipes[texhelperId].out_r, &readyResponse, sizeof(readyResponse), &readyRead, NULL); // Wait for ready _ASSERT(sizeof(readyResponse) == readyRead); _ASSERT(readyResponse.Ready && !readyResponse.Restart && !readyResponse.Finish); _ASSERT(readyResponse.calculateCheckSum() == readyResponse.CheckSum); if (readyResponse.calculateCheckSum() != readyResponse.CheckSum) { puts("TexHelperManager::texHelperOperation ready response checksum fail"); restartPipe(texhelperId); readyRead = 0; readyResponse = TexHelperResponse(); ReadFile(_pipes[texhelperId].out_r, &readyResponse, sizeof(readyResponse), &readyRead, NULL); // Wait for ready _ASSERT(sizeof(readyResponse) == readyRead); _ASSERT(readyResponse.calculateCheckSum() == readyResponse.CheckSum); } unsigned long written = 0; WriteFile(_pipes[texhelperId].in_w, command.utf16(), command.size() * 2 + 2, &written, NULL); _ASSERT(command.size() * 2 + 2 == written); do { TexHelperResponse response; if (!readResponse(_pipes[texhelperId].out_r, response)) { Sleep(10); QueryPerformanceCounter(&currentTime); continue; } _ASSERT(response.calculateCheckSum() == response.CheckSum); if (response.calculateCheckSum() != response.CheckSum) { puts("TexHelperManager::texHelperOperation finish response checksum fail"); break; // Failed, restart pipe outside of loop. } if (outResponse) *outResponse = response; if (response.ImageData) { _ASSERT(response.Finish && !response.Fail); _ASSERT(outResponse); _ASSERT(outData); unsigned int imageDataSize = response.ImageWidth * response.ImageHeight * response.ImageBytePerPixel; unsigned char * imageDataBuffer = new unsigned char [imageDataSize]; unsigned long read = 0; bool result = ReadFile(_pipes[texhelperId].out_r, imageDataBuffer, imageDataSize, &read, NULL); HRESULT lastError = GetLastError(); _ASSERT(imageDataSize == read); if (outData && outResponse) { SAFE_DELETE_ARRAY(*outData); *outData = imageDataBuffer; } else { SAFE_DELETE_ARRAY(imageDataBuffer); _ASSERTE(!"TexHelperManager received unexpected pixel data"); } } if (response.Restart) { restartPipe(texhelperId); response.Fail = true; wprintf(L"TexHelperManager pipe %u restarted %s \n", texhelperId, command.utf16()); } return response.Fail; } while (currentTime.QuadPart <= maximumTime.QuadPart); restartPipe(texhelperId); wprintf(L"TexHelperManager pipe %u op time-out(%I64u)ms; restart pipe; %s \n", texhelperId, (currentTime.QuadPart - anchorTime.QuadPart) * 1000 / frequency.QuadPart, command.utf16()); if (outResponse) *outResponse = TexHelperResponse(false, true, true); return 1; }
3,652
831
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.common.analytics; import static com.android.SdkConstants.ANDROID_URI; import static com.android.SdkConstants.CONSTRAINT_LAYOUT_LIB_ARTIFACT_ID; import static com.android.SdkConstants.FLEXBOX_LAYOUT_LIB_ARTIFACT_ID; import static com.android.SdkConstants.TOOLS_NS_NAME_PREFIX; import static com.android.SdkConstants.TOOLS_URI; import com.android.ide.common.rendering.api.ResourceNamespace; import com.android.ide.common.rendering.api.ResourceReference; import com.google.common.annotations.VisibleForTesting; import com.google.wireless.android.sdk.stats.AndroidAttribute; import com.google.wireless.android.sdk.stats.AndroidView; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.android.dom.attrs.AttributeDefinition; import org.jetbrains.android.dom.attrs.AttributeDefinitions; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.resourceManagers.ModuleResourceManagers; import org.jetbrains.android.resourceManagers.ResourceManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class UsageTrackerUtil { // Identifies a custom tag name or attribute name i.e. a placeholder for a name we do NOT want to log. @VisibleForTesting public static final String CUSTOM_NAME = "CUSTOM"; // Prevent instantiation private UsageTrackerUtil() { } @NotNull public static AndroidAttribute convertAttribute(@NotNull String attributeName, @NotNull AndroidFacet facet) { AndroidAttribute.AttributeNamespace namespace = null; if (attributeName.startsWith(TOOLS_NS_NAME_PREFIX)) { namespace = AndroidAttribute.AttributeNamespace.TOOLS; attributeName = StringUtil.trimStart(attributeName, TOOLS_NS_NAME_PREFIX); } NamespaceAndLibraryNamePair lookup = lookupAttributeResource(facet, attributeName); if (namespace == null) { namespace = lookup.getNamespace(); } return AndroidAttribute.newBuilder() .setAttributeName(convertAttributeName(attributeName, lookup.getNamespace(), lookup.getLibraryName(), facet)) .setAttributeNamespace(namespace) .build(); } @NotNull public static AndroidAttribute.AttributeNamespace convertNamespace(@Nullable String namespace) { if (StringUtil.isEmpty(namespace)) { return AndroidAttribute.AttributeNamespace.ANDROID; } switch (namespace) { case TOOLS_URI: return AndroidAttribute.AttributeNamespace.TOOLS; case ANDROID_URI: return AndroidAttribute.AttributeNamespace.ANDROID; default: return AndroidAttribute.AttributeNamespace.APPLICATION; } } @NotNull public static String convertAttributeName(@NotNull String attributeName, @NotNull AndroidAttribute.AttributeNamespace namespace, @Nullable String libraryName, @NotNull AndroidFacet facet) { switch (namespace) { case ANDROID: return attributeName; case APPLICATION: return libraryName != null && acceptedGoogleLibraryNamespace(libraryName) ? attributeName : CUSTOM_NAME; case TOOLS: NamespaceAndLibraryNamePair lookup = lookupAttributeResource(facet, attributeName); assert lookup.getNamespace() != AndroidAttribute.AttributeNamespace.TOOLS; return convertAttributeName(attributeName, lookup.getNamespace(), lookup.getLibraryName(), facet); default: return CUSTOM_NAME; } } @NotNull public static AndroidView convertTagName(@NotNull String tagName) { tagName = acceptedGoogleTagNamespace(tagName) ? StringUtil.getShortName(tagName, '.') : CUSTOM_NAME; return AndroidView.newBuilder() .setTagName(tagName) .build(); } @VisibleForTesting static boolean acceptedGoogleLibraryNamespace(@NotNull String libraryName) { return libraryName.startsWith("com.android.") || libraryName.startsWith("com.google.") || // The following lines are temporary. // Remove these when we consistently get the full library names. // Currently the library names loaded by Intellij does NOT contain the package / group name. libraryName.startsWith(CONSTRAINT_LAYOUT_LIB_ARTIFACT_ID) || libraryName.startsWith(FLEXBOX_LAYOUT_LIB_ARTIFACT_ID) || libraryName.startsWith("design-") || libraryName.startsWith("appcompat-v7-") || libraryName.startsWith("cardview-v7-") || libraryName.startsWith("gridlayout-v7") || libraryName.startsWith("recyclerview-v7") || libraryName.startsWith("coordinatorlayout-v7") || libraryName.startsWith("play-services-maps-") || libraryName.startsWith("play-services-ads-") || libraryName.startsWith("leanback-v17-"); } @VisibleForTesting static boolean acceptedGoogleTagNamespace(@NotNull String fullyQualifiedTagName) { return fullyQualifiedTagName.indexOf('.') < 0 || fullyQualifiedTagName.startsWith("com.android.") || fullyQualifiedTagName.startsWith("com.google.") || fullyQualifiedTagName.startsWith("android.support.") || fullyQualifiedTagName.startsWith("android.databinding."); } @NotNull @VisibleForTesting static NamespaceAndLibraryNamePair lookupAttributeResource(@NotNull AndroidFacet facet, @NotNull String attributeName) { ModuleResourceManagers resourceManagers = ModuleResourceManagers.getInstance(facet); ResourceManager frameworkResourceManager = resourceManagers.getFrameworkResourceManager(); if (frameworkResourceManager == null) { return new NamespaceAndLibraryNamePair(AndroidAttribute.AttributeNamespace.APPLICATION); } ResourceManager localResourceManager = resourceManagers.getLocalResourceManager(); AttributeDefinitions localAttributeDefinitions = localResourceManager.getAttributeDefinitions(); AttributeDefinitions systemAttributeDefinitions = frameworkResourceManager.getAttributeDefinitions(); if (systemAttributeDefinitions != null && systemAttributeDefinitions.getAttrs().contains(ResourceReference.attr(ResourceNamespace.ANDROID, attributeName))) { return new NamespaceAndLibraryNamePair(AndroidAttribute.AttributeNamespace.ANDROID); } if (localAttributeDefinitions == null) { return new NamespaceAndLibraryNamePair(AndroidAttribute.AttributeNamespace.APPLICATION); } AttributeDefinition definition = localAttributeDefinitions.getAttrDefinition(ResourceReference.attr(ResourceNamespace.TODO(), attributeName)); if (definition == null) { return new NamespaceAndLibraryNamePair(AndroidAttribute.AttributeNamespace.APPLICATION); } return new NamespaceAndLibraryNamePair(AndroidAttribute.AttributeNamespace.APPLICATION, definition.getLibraryName()); } @VisibleForTesting static class NamespaceAndLibraryNamePair { private final AndroidAttribute.AttributeNamespace myNamespace; private final String myLibraryName; @VisibleForTesting NamespaceAndLibraryNamePair(@NotNull AndroidAttribute.AttributeNamespace namespace) { this(namespace, null); } @VisibleForTesting NamespaceAndLibraryNamePair(@NotNull AndroidAttribute.AttributeNamespace namespace, @Nullable String libraryName) { myNamespace = namespace; myLibraryName = libraryName; } @NotNull public AndroidAttribute.AttributeNamespace getNamespace() { return myNamespace; } @Nullable public String getLibraryName() { return myLibraryName; } } }
2,773
335
/* * Copyright 2019-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.bdd.issue; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import org.vividus.bdd.context.IBddVariableContext; import org.vividus.softassert.issue.IKnownIssueDataProvider; import org.vividus.softassert.issue.KnownIssueDataProvider; public class DelegatingKnownIssueDataProvider implements KnownIssueDataProvider { @Inject private IBddVariableContext bddVariableContext; private Map<String, IKnownIssueDataProvider> knownIssueDataProviders; @Override public Optional<String> getData(String key) { return Optional.ofNullable(knownIssueDataProviders.get(key)) .map(IKnownIssueDataProvider::getData) .orElseGet(() -> Optional.ofNullable(bddVariableContext.getVariable(key))); } public void setKnownIssueDataProviders(Map<String, IKnownIssueDataProvider> knownIssueDataProviders) { this.knownIssueDataProviders = knownIssueDataProviders; } }
505
605
//===-- Statistics.h --------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLDB_TARGET_STATISTICS_H #define LLDB_TARGET_STATISTICS_H #include <chrono> #include <string> #include <vector> #include "lldb/Utility/Stream.h" #include "lldb/lldb-forward.h" #include "llvm/Support/JSON.h" namespace lldb_private { using StatsClock = std::chrono::high_resolution_clock; using StatsDuration = std::chrono::duration<double>; using StatsTimepoint = std::chrono::time_point<StatsClock>; /// A class that measures elapsed time in an exception safe way. /// /// This is a RAII class is designed to help gather timing statistics within /// LLDB where objects have optional Duration variables that get updated with /// elapsed times. This helps LLDB measure statistics for many things that are /// then reported in LLDB commands. /// /// Objects that need to measure elapsed times should have a variable of type /// "StatsDuration m_time_xxx;" which can then be used in the constructor of /// this class inside a scope that wants to measure something: /// /// ElapsedTime elapsed(m_time_xxx); /// // Do some work /// /// This class will increment the m_time_xxx variable with the elapsed time /// when the object goes out of scope. The "m_time_xxx" variable will be /// incremented when the class goes out of scope. This allows a variable to /// measure something that might happen in stages at different times, like /// resolving a breakpoint each time a new shared library is loaded. class ElapsedTime { public: /// Set to the start time when the object is created. StatsTimepoint m_start_time; /// Elapsed time in seconds to increment when this object goes out of scope. StatsDuration &m_elapsed_time; public: ElapsedTime(StatsDuration &opt_time) : m_elapsed_time(opt_time) { m_start_time = StatsClock::now(); } ~ElapsedTime() { StatsDuration elapsed = StatsClock::now() - m_start_time; m_elapsed_time += elapsed; } }; /// A class to count success/fail statistics. struct StatsSuccessFail { StatsSuccessFail(llvm::StringRef n) : name(n.str()) {} void NotifySuccess() { ++successes; } void NotifyFailure() { ++failures; } llvm::json::Value ToJSON() const; std::string name; uint32_t successes = 0; uint32_t failures = 0; }; /// A class that represents statistics for a since lldb_private::Module. struct ModuleStats { llvm::json::Value ToJSON() const; intptr_t identifier; std::string path; std::string uuid; std::string triple; double symtab_parse_time = 0.0; double symtab_index_time = 0.0; double debug_parse_time = 0.0; double debug_index_time = 0.0; uint64_t debug_info_size = 0; bool symtab_loaded_from_cache = false; bool symtab_saved_to_cache = false; bool debug_info_index_loaded_from_cache = false; bool debug_info_index_saved_to_cache = false; }; /// A class that represents statistics for a since lldb_private::Target. class TargetStats { public: llvm::json::Value ToJSON(Target &target); void SetLaunchOrAttachTime(); void SetFirstPrivateStopTime(); void SetFirstPublicStopTime(); StatsDuration &GetCreateTime() { return m_create_time; } StatsSuccessFail &GetExpressionStats() { return m_expr_eval; } StatsSuccessFail &GetFrameVariableStats() { return m_frame_var; } protected: StatsDuration m_create_time{0.0}; llvm::Optional<StatsTimepoint> m_launch_or_attach_time; llvm::Optional<StatsTimepoint> m_first_private_stop_time; llvm::Optional<StatsTimepoint> m_first_public_stop_time; StatsSuccessFail m_expr_eval{"expressionEvaluation"}; StatsSuccessFail m_frame_var{"frameVariable"}; std::vector<intptr_t> m_module_identifiers; void CollectStats(Target &target); }; class DebuggerStats { public: static void SetCollectingStats(bool enable) { g_collecting_stats = enable; } static bool GetCollectingStats() { return g_collecting_stats; } /// Get metrics associated with one or all targets in a debugger in JSON /// format. /// /// \param debugger /// The debugger to get the target list from if \a target is NULL. /// /// \param target /// The single target to emit statistics for if non NULL, otherwise dump /// statistics only for the specified target. /// /// \return /// Returns a JSON value that contains all target metrics. static llvm::json::Value ReportStatistics(Debugger &debugger, Target *target); protected: // Collecting stats can be set to true to collect stats that are expensive // to collect. By default all stats that are cheap to collect are enabled. // This settings is here to maintain compatibility with "statistics enable" // and "statistics disable". static bool g_collecting_stats; }; } // namespace lldb_private #endif // LLDB_TARGET_STATISTICS_H
1,502
1,682
/* Copyright (c) 2019 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.linkedin.restli.server.annotations; import com.linkedin.restli.server.errors.ServiceError; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Defines the set of acceptable service errors for some resource class. * * @author <NAME> * @author <NAME> * @author <NAME> */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ServiceErrorDef { /** * The enum implementing {@link ServiceError} which describes the set of acceptable service errors. * Service error codes are mapped to these service errors using the {@link ServiceError#code()} method. */ Class<? extends Enum<? extends ServiceError>> value(); }
386
651
package com.squareup.subzero.server; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; public class ServerExceptionMapper implements ExceptionMapper<Throwable> { public Response toResponse(Throwable exception) { return Response.status(400) .entity(exception.getMessage()) .type(MediaType.TEXT_PLAIN) .build(); } }
150
316
#include "json_element.hpp" #include "json_array.hpp" #include "json_object.hpp" #include "json_primitive.hpp" namespace mbgl { namespace android { namespace gson { jni::Local<jni::Object<JsonElement>> JsonElement::New(jni::JNIEnv& env, const mbgl::Value& value) { static auto& primitive = jni::Class<JsonPrimitive>::Singleton(env); static auto stringConstructor = primitive.GetConstructor<jni::String>(env); static auto numberConstructor = primitive.GetConstructor<jni::Number>(env); static auto booleanConstructor = primitive.GetConstructor<jni::Boolean>(env); return value.match( [&] (const mbgl::NullValue&) { return jni::Local<jni::Object<JsonElement>>(); }, [&] (const std::string& value) { return primitive.New(env, stringConstructor, jni::Make<jni::String>(env, value)); }, [&] (const double value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, [&] (const int64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, [&] (const uint64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, int64_t(value))); // TODO: should use BigInteger }, [&] (const bool value) { return primitive.New(env, booleanConstructor, jni::Box(env, value ? jni::jni_true : jni::jni_false)); }, [&] (const std::vector<mbgl::Value>& values) { return JsonArray::New(env, values); }, [&] (const mbgl::PropertyMap& values) { return JsonObject::New(env, values); } ); } mbgl::Value JsonElement::convert(jni::JNIEnv &env, const jni::Object<JsonElement>& jsonElement) { if (!jsonElement) { return mbgl::NullValue(); } static auto& elementClass = jni::Class<JsonElement>::Singleton(env); static auto isJsonObject = elementClass.GetMethod<jni::jboolean ()>(env, "isJsonObject"); static auto isJsonArray = elementClass.GetMethod<jni::jboolean ()>(env, "isJsonArray"); static auto isJsonPrimitive = elementClass.GetMethod<jni::jboolean ()>(env, "isJsonPrimitive"); static auto& primitiveClass = jni::Class<JsonPrimitive>::Singleton(env); static auto isBoolean = primitiveClass.GetMethod<jni::jboolean ()>(env, "isBoolean"); static auto isString = primitiveClass.GetMethod<jni::jboolean ()>(env, "isString"); static auto isNumber = primitiveClass.GetMethod<jni::jboolean ()>(env, "isNumber"); static auto getAsBoolean = primitiveClass.GetMethod<jni::jboolean ()>(env, "getAsBoolean"); static auto getAsString = primitiveClass.GetMethod<jni::String ()>(env, "getAsString"); static auto getAsDouble = primitiveClass.GetMethod<jni::jdouble ()>(env, "getAsDouble"); if (jsonElement.Call(env, isJsonPrimitive)) { auto primitive = jni::Cast(env, primitiveClass, jsonElement); if (primitive.Call(env, isBoolean)) { return bool(primitive.Call(env, getAsBoolean)); } else if (primitive.Call(env, isNumber)) { return primitive.Call(env, getAsDouble); } else if (primitive.Call(env, isString)) { return jni::Make<std::string>(env, primitive.Call(env, getAsString)); } else { return mbgl::NullValue(); } } else if (jsonElement.Call(env, isJsonObject)) { return JsonObject::convert(env, jni::Cast(env, jni::Class<JsonObject>::Singleton(env), jsonElement)); } else if (jsonElement.Call(env, isJsonArray)) { return JsonArray::convert(env, jni::Cast(env, jni::Class<JsonArray>::Singleton(env), jsonElement)); } else { return mbgl::NullValue(); } } void JsonElement::registerNative(jni::JNIEnv &env) { jni::Class<JsonElement>::Singleton(env); } } // namespace gson } // namespace android } // namespace mbgl
1,571
442
<reponame>nicchagil/spring-framework<gh_stars>100-1000 /** * Server-side support for the Jetty 9+ WebSocket API. */ package org.springframework.web.socket.server.jetty;
58
1,493
/******************************************************************************* * Copyright 2017 Bstek * * 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.bstek.urule.model.table; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.bstek.urule.model.rule.Library; /** * @author Jacky.gao * @since 2015年5月5日 */ public class ScriptDecisionTable { private List<Row> rows; private List<Column> columns; private Map<String,ScriptCell> cellMap; private List<Library> libraries; public List<Row> getRows() { return rows; } public void addLibrary(Library library){ if(libraries==null){ libraries=new ArrayList<Library>(); } libraries.add(library); } public void addRow(Row row){ if(rows==null){ rows=new ArrayList<Row>(); } rows.add(row); } public void addColumn(Column col){ if(columns==null){ columns=new ArrayList<Column>(); } columns.add(col); } public void addCell(ScriptCell cell){ if(cellMap==null){ cellMap=new HashMap<String,ScriptCell>(); } cellMap.put(buildCellKey(cell.getRow(),cell.getCol()), cell); } public void setRows(List<Row> rows) { this.rows = rows; } public List<Column> getColumns() { return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } public Map<String, ScriptCell> getCellMap() { return cellMap; } public List<Library> getLibraries() { return libraries; } public void setLibraries(List<Library> libraries) { this.libraries = libraries; } public String buildCellKey(int row,int col){ return row+","+col; } }
727
3,212
<reponame>YolandaMDavis/nifi /* * 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.nifi.integration.auth; import org.apache.nifi.authorization.AccessPolicy; import org.apache.nifi.authorization.AccessPolicyProvider; import org.apache.nifi.authorization.AccessPolicyProviderInitializationContext; import org.apache.nifi.authorization.AuthorizerConfigurationContext; import org.apache.nifi.authorization.RequestAction; import org.apache.nifi.authorization.exception.AuthorizationAccessException; import org.apache.nifi.authorization.exception.AuthorizerCreationException; import org.apache.nifi.authorization.exception.AuthorizerDestructionException; import java.util.HashSet; import java.util.Objects; import java.util.Set; public class VolatileAccessPolicyProvider implements AccessPolicyProvider { private final VolatileUserGroupProvider userGroupProvider = new VolatileUserGroupProvider(); private Set<AccessPolicy> accessPolicies = new HashSet<>(); public synchronized void grantAccess(final String user, final String resourceIdentifier, final RequestAction action) { final AccessPolicy existingPolicy = getAccessPolicy(resourceIdentifier, action); final AccessPolicy policy; if (existingPolicy == null) { policy = new AccessPolicy.Builder() .addUser(user) .action(action) .identifierGenerateRandom() .resource(resourceIdentifier) .build(); } else { policy = new AccessPolicy.Builder() .addUsers(existingPolicy.getUsers()) .addUser(user) .action(action) .identifier(existingPolicy.getIdentifier()) .resource(resourceIdentifier) .build(); } accessPolicies.remove(existingPolicy); accessPolicies.add(policy); } public synchronized void revokeAccess(final String user, final String resourceIdentifier, final RequestAction action) { final AccessPolicy existingPolicy = getAccessPolicy(resourceIdentifier, action); if (existingPolicy == null) { return; } final AccessPolicy policy= new AccessPolicy.Builder() .addUsers(existingPolicy.getUsers()) .removeUser(user) .action(action) .identifier(existingPolicy.getIdentifier()) .resource(resourceIdentifier) .build(); accessPolicies.remove(existingPolicy); accessPolicies.add(policy); } @Override public synchronized Set<AccessPolicy> getAccessPolicies() throws AuthorizationAccessException { return new HashSet<>(accessPolicies); } @Override public synchronized AccessPolicy getAccessPolicy(final String identifier) throws AuthorizationAccessException { return accessPolicies.stream() .filter(policy -> policy.getIdentifier().equals(identifier)) .findAny() .orElse(null); } @Override public synchronized AccessPolicy getAccessPolicy(final String resourceIdentifier, final RequestAction action) throws AuthorizationAccessException { return accessPolicies.stream() .filter(policy -> Objects.equals(policy.getResource(), resourceIdentifier)) .filter(policy -> Objects.equals(policy.getAction(), action)) .findAny() .orElse(null); } @Override public synchronized VolatileUserGroupProvider getUserGroupProvider() { return userGroupProvider; } @Override public void initialize(final AccessPolicyProviderInitializationContext initializationContext) throws AuthorizerCreationException { } @Override public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException { } @Override public void preDestruction() throws AuthorizerDestructionException { } }
1,615
6,457
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #pragma once #include <map> #include <utility> #include "device_hub.h" #include "sync.h" #include "profile.h" #include "config.h" #include "resolver.h" #include "aggregator.h" namespace librealsense { namespace pipeline { class pipeline : public std::enable_shared_from_this<pipeline> { public: //Top level API explicit pipeline(std::shared_ptr<librealsense::context> ctx); virtual ~pipeline(); std::shared_ptr<profile> start(std::shared_ptr<config> conf, frame_callback_ptr callback = nullptr); void stop(); std::shared_ptr<profile> get_active_profile() const; frame_holder wait_for_frames(unsigned int timeout_ms); bool poll_for_frames(frame_holder* frame); bool try_wait_for_frames(frame_holder* frame, unsigned int timeout_ms); //Non top level API std::shared_ptr<device_interface> wait_for_device(const std::chrono::milliseconds& timeout = std::chrono::hours::max(), const std::string& serial = ""); std::shared_ptr<librealsense::context> get_context() const; protected: frame_callback_ptr get_callback(std::vector<int> unique_ids); std::vector<int> on_start(std::shared_ptr<profile> profile); void unsafe_start(std::shared_ptr<config> conf); void unsafe_stop(); mutable std::mutex _mtx; std::shared_ptr<profile> _active_profile; device_hub _hub; std::shared_ptr<config> _prev_conf; private: std::shared_ptr<profile> unsafe_get_active_profile() const; std::shared_ptr<librealsense::context> _ctx; int _playback_stopped_token = -1; dispatcher _dispatcher; std::unique_ptr<syncer_process_unit> _syncer; std::unique_ptr<aggregator> _aggregator; frame_callback_ptr _streams_callback; std::vector<rs2_stream> _synced_streams; }; } }
970
1,025
//================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file gdTextureImageProxy.cpp /// //================================================================================== //------------------------------ gdTextureImageProxy.cpp ------------------------------ // Qt #include <AMDTApplicationComponents/Include/acQtIncludes.h> // Infra: #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTBaseTools/Include/gtString.h> #include <AMDTOSWrappers/Include/osDebuggingFunctions.h> #include <AMDTOSWrappers/Include/osFile.h> #include <AMDTOSWrappers/Include/osOSDefinitions.h> #include <AMDTOSWrappers/Include/osStopWatch.h> #include <AMDTAPIClasses/Include/apGLTexture.h> #include <AMDTAPIClasses/Include/apCLImage.h> #include <AMDTAPIClasses/Include/apGLPixelInternalFormatParameter.h> #include <AMDTApiFunctions/Include/gaGRApiFunctions.h> #include <AMDTApplicationComponents/Include/acRawFileHandler.h> #include <AMDTApplicationComponents/Include/acFunctions.h> // AMDTApplicationFramework: #include <AMDTApplicationFramework/Include/afAppStringConstants.h> #include <AMDTApplicationFramework/src/afUtils.h> // Local: #include <AMDTGpuDebuggingComponents/Include/gdAidFunctions.h> #include <AMDTGpuDebuggingComponents/Include/gdGDebuggerGlobalVariablesManager.h> #include <AMDTGpuDebuggingComponents/Include/gdStringConstants.h> #include <AMDTGpuDebuggingComponents/Include/gdHTMLProperties.h> #include <AMDTGpuDebuggingComponents/Include/views/gdTextureImageProxy.h> // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::gdTextureImageProxy // Description: Constructor // Arguments: gdDebugApplicationTreeData* pTextureTreeItemData // isInGLBeginEndBlock - are we in a begin - end block // imageW - the image width // imageH - the image height // Author: <NAME> // Date: 10/4/2011 // --------------------------------------------------------------------------- gdTextureImageProxy::gdTextureImageProxy(afApplicationTreeItemData* pTextureTreeItemData, bool isInGLBeginEndBlock, int imageW, int imageH, bool releaseItemDataMemory) : _pTextureTreeItemData(pTextureTreeItemData), _releaseItemDataMemory(releaseItemDataMemory), _isInGLBeginEndBlock(isInGLBeginEndBlock), _imageW(imageW), _imageH(imageH), _optimizedMiplevel(-1), _calculatedLoadedImageSize(-1) { } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::~gdTextureImageProxy // Description: Destructor // Author: <NAME> // Date: 10/4/2011 // --------------------------------------------------------------------------- gdTextureImageProxy::~gdTextureImageProxy() { if (_releaseItemDataMemory) { if (_pTextureTreeItemData != NULL) { delete _pTextureTreeItemData; _pTextureTreeItemData = NULL; } } } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::loadImage // Description: Generates a texture image preview // Return Val: bool - Success / failure. // Author: <NAME> // Date: 24/7/2012 // --------------------------------------------------------------------------- bool gdTextureImageProxy::loadImage() { bool retVal = false; // First, clear the loaded image if such an image exists releaseLoadedImage(); // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Generate a texture preview only if we not in a glBegin - glEnd block if (!_isInGLBeginEndBlock) { // Try to generate the texture image bool rc1 = generateTextureImage(); if (!rc1) { // We failed to generate the texture image. Now we got two options: // 1. If texture type is unknown, we notify the user texture type is unknown. // 2. There was a problem writing / reading / converting the texture. Show texture not available message // This flag indicates if texture type is unknown bool isTextureTypeUnknown = false; // Get the selected texture details: bool rc2 = gaGetTextureObjectThumbnailData(pGDData->_contextId._contextId, pGDData->_textureMiplevelID._textureName, _textureThumbnailDetails); if (rc2) { // Get texture type apTextureType textureType = _textureThumbnailDetails.textureType(); // Is this an unknown texture? isTextureTypeUnknown = (textureType == AP_UNKNOWN_TEXTURE_TYPE); } // Get the context type: bool isOpenGLContext = (pGDData->_contextId.isOpenGLContext()); GT_ASSERT(pGDData->_contextId.isValid() && (!pGDData->_contextId.isDefault())); // Check if the texture format is supported for OpenGL ES projects: bool isSupportedFormat = true; #if (AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT) if (apDoesProjectTypeSupportOpenGLES(gdGDebuggerGlobalVariablesManager::instance().CodeXLProjectType())) { // Get the buffer format: oaTexelDataFormat dataFormat = _textureThumbnailDetails.texelDataFormat(); // Check if the buffer format is supported for OpenGLES (RGB | RGBA): if ((dataFormat != OA_TEXEL_FORMAT_RGB) && (dataFormat != OA_TEXEL_FORMAT_RGBA)) { isSupportedFormat = false; } } #endif if (isTextureTypeUnknown || !isSupportedFormat) { // If this is an unknown texture, generate an unknown texture message: m_pLoadedQImage = createMessageImage(isOpenGLContext ? GD_STR_ImageProxyTextureTypeUnknown : GD_STR_ImageProxyImageTypeUnknown); } else { // Generate an "Texture data is not available at this time." message: gtString msg; if (isOpenGLContext) { msg.appendFormattedString(GD_STR_ImageProxyObjectNAMessage, GD_STR_ImageProxyTexture); } else { msg.appendFormattedString(GD_STR_ImageProxyObjectNAMessage, GD_STR_ImageProxyImage); } m_pLoadedQImage = createMessageImage(msg); } } } } else { // We are in a glBegin - glEnd block. generate the appropriate message: gtString msg; msg.appendFormattedString(GD_STR_ImageProxyGLBeginEndMessage, GD_STR_ImageProxyTexture); m_pLoadedQImage = createMessageImage(msg); } } // Return true if we got a valid image retVal = (m_pLoadedQImage != NULL); return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::calculateOptimizedMiplevel // Description: Calculate the optimized texture mip level for the requested // image size // Arguments: int& optimizedMipLevel // Return Val: bool - Success / failure. // Author: <NAME> // Date: 21/1/2009 // --------------------------------------------------------------------------- bool gdTextureImageProxy::calculateOptimizedMiplevel() { bool retVal = false; _optimizedMiplevel = 0; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) // TO_DO iPhone: Uri, 14/6/09 - we currently can't get mipmap levels beyond 0 in the iPhone // spy, so we just use level 0 here: if (apDoesProjectTypeSupportOpenGLES(gdGDebuggerGlobalVariablesManager::instance().CodeXLProjectType())) { retVal = true; } else #endif { // Get the texture mip level data: bool rc = gaGetTextureObjectThumbnailData(pGDData->_contextId._contextId, pGDData->_textureMiplevelID._textureName, _textureThumbnailDetails); GT_IF_WITH_ASSERT(rc) { retVal = true; // Check if the texture has mip levels: if (_textureThumbnailDetails.maxLevel() > _textureThumbnailDetails.minLevel()) { // Browse the levels, from the smallest sized to the biggest, and search for the best: for (int i = _textureThumbnailDetails.maxLevel(); i >= _textureThumbnailDetails.minLevel(); i--) { // Get the level size division: int levelExp = (int)pow(2.0f, (float)i); GLsizei textureW = 0, textureH = 0, textureD = 0, borderSize = 0; _textureThumbnailDetails.getDimensions(textureW, textureH, textureD, borderSize); int miplevelW = textureW / levelExp; int miplevelH = textureH / levelExp; // Check if this mip level's size is enough: if ((miplevelH >= _imageH) && (miplevelW >= _imageH)) { _optimizedMiplevel = i; retVal = true; break; } } } } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::generateTextureImage // Description: Generates a texture image according to the texture // Return Val: bool - Success / failure. // Author: <NAME> // Date: 2/12/2009 // --------------------------------------------------------------------------- bool gdTextureImageProxy::generateTextureImage() { bool retVal = false; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { if (pGDData->_contextId.isOpenCLContext()) { // Generate an OpenCL texture image: retVal = generateCachedCLImageImage(); } else if (pGDData->_contextId.isOpenGLContext()) { // Generate an OpenGL texture image: retVal = generateCachedGLTextureImage(); } else // pGDData->_contextId.isDefault() { // Texture image generation should not be called for NULL context: GT_ASSERT_EX(false, L"should not get here"); } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::generateCachedGLTextureImage // Description: Generates a cached thumbnail image. // 1. If the texture has mip levels, optimize using the mip levels // mechanism. // 2. After the thumbnail is produced, save it to the disk. // 3. If the image is not dirty, load the cached copy of the thumbnail. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 28/7/2010 // --------------------------------------------------------------------------- bool gdTextureImageProxy::generateCachedGLTextureImage() { bool retVal = false; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { bool isInteropObject = (_pTextureTreeItemData->m_itemType == AF_TREE_ITEM_CL_IMAGE) && (pGDData->_objectOpenGLName > 0); isInteropObject = ((_pTextureTreeItemData->m_itemType == AF_TREE_ITEM_GL_TEXTURE) && (pGDData->_objectOpenCLName > 0)) || isInteropObject; if (!isInteropObject) { // Check if the image is dirty: // Find out the smallest mip level needed to fit the requested size (if the image has mip levels): bool rcOptimizeMipLevel = calculateOptimizedMiplevel(); GT_ASSERT(rcOptimizeMipLevel); // Get texture main raw data file path: osFilePath textureRawDataFile; apGLTextureMipLevelID mipLevelId = pGDData->_textureMiplevelID; mipLevelId._textureMipLevel = _optimizedMiplevel; bool rcGetFilePath = gaGetTextureMiplevelDataFilePath(pGDData->_contextId._contextId, mipLevelId, 0, textureRawDataFile); // YuriR: if file path is invalid set Mip Level to 0 and try again if (!textureRawDataFile.exists()) { retVal = updateTextureRawData(); rcGetFilePath = gaGetTextureMiplevelDataFilePath(pGDData->_contextId._contextId, mipLevelId, 0, textureRawDataFile); } else { retVal = true; } if ((_optimizedMiplevel != 0) && ((!retVal) || (!textureRawDataFile.exists()))) { _optimizedMiplevel = 0; mipLevelId._textureMipLevel = _optimizedMiplevel; retVal = updateTextureRawData(); rcGetFilePath = gaGetTextureMiplevelDataFilePath(pGDData->_contextId._contextId, mipLevelId, 0, textureRawDataFile); } GT_IF_WITH_ASSERT(rcGetFilePath && retVal && textureRawDataFile.exists()) { // Localize the path as needed: gaRemoteToLocalFile(textureRawDataFile, false); // Try to load the cached file: retVal = loadCachedThumbnailFile(textureRawDataFile); // If the textures raw data is updated: if (!retVal) { // Load the original file: retVal = loadRawDataFile(textureRawDataFile); } } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::generateCachedCLImageImage // Description: Generates an OpenCL texture image // Return Val: bool - Success / failure. // Author: <NAME> // Date: 2/12/2009 // --------------------------------------------------------------------------- bool gdTextureImageProxy::generateCachedCLImageImage() { bool retVal = false; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // TO_DO: implement dirty mechanism for OpenCL textures bool dirtyImageExists = true; // bool rcDirtyCheck = gaIsOpenCLTextureImageDirty(pGDData->_contextId, (int)_textureMiplevelID._textureName, dirtyImageExists, dirtyRawDataExists); // GT_ASSERT(rcDirtyCheck); // Update texture data if necessary: gtVector <int> textures; textures.push_back(pGDData->_objectOpenCLIndex); bool isTextureDataUpdated = gaUpdateOpenCLImageRawData(pGDData->_contextId._contextId, textures); GT_IF_WITH_ASSERT(isTextureDataUpdated) { // Get texture main raw data file path osFilePath textureRawDataFile; apCLImage textureDetails; bool rcGetTexture = gaGetOpenCLImageObjectDetails(pGDData->_contextId._contextId, pGDData->_objectOpenCLIndex, textureDetails); GT_IF_WITH_ASSERT(rcGetTexture) { // Get the texture file path: textureDetails.imageFilePath(textureRawDataFile); // Localize the path as needed: gaRemoteToLocalFile(textureRawDataFile, false); // Try to load the cached file: if (!dirtyImageExists) { retVal = loadCachedThumbnailFile(textureRawDataFile); } // If the textures raw data is updated: if (!retVal) { // Load the original file: retVal = loadRawDataFile(textureRawDataFile); } } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::updateTextureRawData // Description: Update the texture raw data (either with the optimized mip // level or with 0 level // Return Val: bool - Success / failure. // Author: <NAME> // Date: 28/7/2010 // --------------------------------------------------------------------------- bool gdTextureImageProxy::updateTextureRawData() { bool retVal = false; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Update and extract the texture raw data to disk: gtVector<apGLTextureMipLevelID> texturesVector; apGLTextureMipLevelID mipLevelId = pGDData->_textureMiplevelID; mipLevelId._textureMipLevel = _optimizedMiplevel; texturesVector.push_back(pGDData->_textureMiplevelID); // Check if the requested mip level contain dirty data: bool dirtyImageExists = true, dirtyRawDataExists = true; bool rcDirtyCheck = gaIsTextureImageDirty(pGDData->_contextId._contextId, mipLevelId, dirtyImageExists, dirtyRawDataExists); GT_ASSERT(rcDirtyCheck); if (dirtyImageExists || dirtyRawDataExists) { retVal = gaUpdateTextureRawData(pGDData->_contextId._contextId, texturesVector); } else { retVal = true; } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::loadRawDataFile // Description: Loads a texture thumbnail file. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 28/7/2010 // --------------------------------------------------------------------------- bool gdTextureImageProxy::loadRawDataFile(const osFilePath& textureFilePath) { bool retVal = false; // Load the texture raw data: acRawFileHandler rawFileHandler; // Get the texture file page: bool rc5 = rawFileHandler.loadFromFile(textureFilePath); if (rc5) { // If raw data was loaded successfully: if (rawFileHandler.isOk()) { if (_textureThumbnailDetails.textureType() == AP_BUFFER_TEXTURE) { // Set the raw file handler data format: bool rc3 = rawFileHandler.setDataFormatAndAdaptSize(_textureThumbnailDetails.bufferInternalFormat()); GT_ASSERT(rc3); } // Set middle page to be active page rawFileHandler.setMiddlePageAsActivePage(); // Convert the raw data to QImage object: m_pLoadedQImage = rawFileHandler.convertToQImage(); // Return true if we got a valid image retVal = (m_pLoadedQImage != NULL); } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::loadCachedThumbnailFile // Description: Loads a texture thumbnail file from cache, if it exists. // Arguments: const osFilePath& textureRawDataFile - the texture raw data file path // Return Val: bool - Success / failure. // Author: <NAME> // Date: 28/7/2010 // --------------------------------------------------------------------------- bool gdTextureImageProxy::loadCachedThumbnailFile(const osFilePath& textureRawDataFilePath) { bool retVal = false; // Create temporary file path: osFilePath cachedFilePath = textureRawDataFilePath; // Get the original file name: gtString origFileName; cachedFilePath.getFileName(origFileName); // The thumbnail file is saved in the same folder, with the same name, // with postfix _thumb: origFileName += GD_STR_TexturesAndBuffersLoggingThumbPostfix; cachedFilePath.setFileName(origFileName); cachedFilePath.setFileExtension(acQStringToGTString(GD_STR_TexturesAndBuffersLoggingFormatBmp)); if (cachedFilePath.exists()) { // Get the file path as string: gtString localFilePathStr = cachedFilePath.asString(); // Convert the raw data to QImage object: m_pLoadedQImage = new QImage(acGTStringToQString(localFilePathStr)); retVal = true; } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::cacheThumbnail // Description: If the thumbnail is big, save the image to the disk, in order // to optimize the textures load next time. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 29/7/2010 // --------------------------------------------------------------------------- bool gdTextureImageProxy::cacheThumbnail() { bool retVal = false; // Sanity Check: GT_IF_WITH_ASSERT((m_pLoadedQImage != NULL) && (_pTextureTreeItemData != NULL)) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Save a thumbnail only for non text messages: if (!m_isTextMessage) { bool rcGetFilePath = false; osFilePath textureRawDataFile; if (pGDData->_contextId.isOpenGLContext()) { // Get the texture raw data file path: rcGetFilePath = gaGetTextureMiplevelDataFilePath(pGDData->_contextId._contextId, pGDData->_textureMiplevelID, 0, textureRawDataFile); } else { // Get texture main raw data file path apCLImage textureDetails; rcGetFilePath = gaGetOpenCLImageObjectDetails(pGDData->_contextId._contextId, pGDData->_objectOpenCLIndex, textureDetails); if (rcGetFilePath) { // Get the texture file path: textureDetails.imageFilePath(textureRawDataFile); } } if (rcGetFilePath) { // Localize the path as needed: gaRemoteToLocalFile(textureRawDataFile, false); // Get the original file name: gtString origFileName; textureRawDataFile.getFileName(origFileName); origFileName += GD_STR_TexturesAndBuffersLoggingThumbPostfix; textureRawDataFile.setFileName(origFileName); textureRawDataFile.setFileExtension(acQStringToGTString(GD_STR_TexturesAndBuffersLoggingFormatBmp)); // Get the file path as string: gtString filePathStr = textureRawDataFile.asString(); // Save the bitmap: retVal = m_pLoadedQImage->save(acGTStringToQString(filePathStr)); } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::calculateLoadedImageSize // Description: Calculate the loaded image size, if not calculated yet // Return Val: int // Author: <NAME> // Date: 1/8/2010 // --------------------------------------------------------------------------- int gdTextureImageProxy::calculateLoadedImageSize() { // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { if (_calculatedLoadedImageSize < 0) { // Default: _calculatedLoadedImageSize = _imageW * _imageH * 4; if (pGDData->_contextId.isOpenCLContext()) { // Calculate the OpenCL texture: _calculatedLoadedImageSize = calculateOpenCLLoadedImageSize(); } else if (pGDData->_contextId.isOpenGLContext()) { // Calculate the OpenGL texture: _calculatedLoadedImageSize = calculateOpenGLLoadedImageSize(); } } } } return _calculatedLoadedImageSize; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::calculateOpenGLLoadedImageSize // Description: Get the loaded item size // Return Val: bool - Success / failure. // Author: <NAME> // Date: 1/8/2010 // --------------------------------------------------------------------------- int gdTextureImageProxy::calculateOpenGLLoadedImageSize() { int retVal = 0; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Get the selected texture details: bool rc = gaGetTextureObjectThumbnailData(pGDData->_contextId._contextId, pGDData->_textureMiplevelID._textureName, _textureThumbnailDetails); GT_IF_WITH_ASSERT(rc) { // Get the texture texel type: oaTexelDataFormat dataFormat = _textureThumbnailDetails.texelDataFormat(); oaDataType dataType = _textureThumbnailDetails.dataType(); // Get the texture pixel size: int pixelSize = oaCalculatePixelUnitByteSize(dataFormat, dataType); GT_IF_WITH_ASSERT(pixelSize > 0) { // Get the texture size: GLsizei textureW, textureH, textureD, textureBorderSize; _textureThumbnailDetails.getDimensions(textureW, textureH, textureD, textureBorderSize); retVal = textureW * textureH * pixelSize; if (m_isTextMessage) { retVal = _imageH * _imageW * 4; } else { // Check if the requested mip level contain dirty data: bool dirtyImageExists = true, dirtyRawDataExists = true; bool rcDirtyCheck = gaIsTextureImageDirty(pGDData->_contextId._contextId, pGDData->_textureMiplevelID, dirtyImageExists, dirtyRawDataExists); GT_ASSERT(rcDirtyCheck); // Get the texture size: if (dirtyRawDataExists) { // Get the texture mip level data: rc = gaGetTextureObjectThumbnailData(pGDData->_contextId._contextId, pGDData->_textureMiplevelID._textureName, _textureThumbnailDetails); GT_IF_WITH_ASSERT(rc) { // Check if the texture has mip levels: if (_textureThumbnailDetails.maxLevel() > _textureThumbnailDetails.minLevel()) { // Browse the levels, from the smallest sized to the biggest, and search for the best: for (int i = _textureThumbnailDetails.maxLevel(); i >= _textureThumbnailDetails.minLevel(); i--) { // Get the level size division: int levelExp = (int)pow(2.0f, (float)i); GLsizei texW = 0, texH = 0, textureDepth = 0, borderSize = 0; _textureThumbnailDetails.getDimensions(texW, texH, textureDepth, borderSize); int miplevelW = texW / levelExp; int miplevelH = texH / levelExp; // Check if this mip level's size is enough: if ((miplevelH >= _imageH) && (miplevelW >= _imageH)) { _optimizedMiplevel = i; retVal = miplevelW * miplevelH * pixelSize; break; } } } } } else { // Get texture main raw data file path: osFilePath textureRawDataFile; bool rcGetFilePath = gaGetTextureMiplevelDataFilePath(pGDData->_contextId._contextId, pGDData->_textureMiplevelID, 0, textureRawDataFile); GT_IF_WITH_ASSERT(rcGetFilePath) { // Localize the path as needed: gaRemoteToLocalFile(textureRawDataFile, false); // Get the original file name: gtString origFileName; textureRawDataFile.getFileName(origFileName); origFileName += GD_STR_TexturesAndBuffersLoggingThumbPostfix; textureRawDataFile.setFileName(origFileName); textureRawDataFile.setFileExtension(acQStringToGTString(GD_STR_TexturesAndBuffersLoggingFormatBmp)); // Check if the file exists: if (textureRawDataFile.exists()) { retVal = _imageH * _imageW * pixelSize; } } } } } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::calculateOpenCLLoadedImageSize // Description: Get the loaded item size // Return Val: bool - Success / failure. // Author: <NAME> // Date: 1/8/2010 // --------------------------------------------------------------------------- int gdTextureImageProxy::calculateOpenCLLoadedImageSize() { int retVal = 0; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Get texture main raw data file path osFilePath textureRawDataFile; apCLImage textureDetails; bool rcGetTexture = gaGetOpenCLImageObjectDetails(pGDData->_contextId._contextId, pGDData->_objectOpenCLIndex, textureDetails); GT_IF_WITH_ASSERT(rcGetTexture) { if (m_isTextMessage) { retVal = _imageH * _imageW * 4; } else { // Get the texture texel type: cl_uint clDataFormat = textureDetails.dataFormat(); cl_uint clDataType = textureDetails.dataType(); // Translates cl image format to its equivalent oaTexelDataFormat: oaTexelDataFormat dataFormat; bool rc1 = oaCLImageFormatToTexelFormat(clDataFormat, dataFormat); GT_ASSERT(rc1); oaDataType dataType; bool rc2 = oaCLImageDataTypeToOSDataType(clDataType, dataType); GT_ASSERT(rc2); // Get the texture pixel size: int pixelSize = oaCalculatePixelUnitByteSize(dataFormat, dataType); // Get the texture size: size_t textureW, textureH, textureD; textureDetails.getDimensions(textureW, textureH, textureD); retVal = textureW * textureH * pixelSize; // Get the texture file path: osFilePath texRawDataFile; textureDetails.imageFilePath(textureRawDataFile); // Localize the path as needed: gaRemoteToLocalFile(texRawDataFile, false); // Get the original file name: gtString origFileName; texRawDataFile.getFileName(origFileName); origFileName += GD_STR_TexturesAndBuffersLoggingThumbPostfix; texRawDataFile.setFileName(origFileName); texRawDataFile.setFileExtension(acQStringToGTString(GD_STR_TexturesAndBuffersLoggingFormatBmp)); // Check if the file exists: if (textureRawDataFile.exists()) { retVal = _imageH * _imageW * pixelSize; } } } } } return retVal; } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::tooltipText // Description: Builds the texture tooltip text // Return Val: void // Author: <NAME> // Date: 23/8/2010 // --------------------------------------------------------------------------- void gdTextureImageProxy::buildTooltipText() { // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { // Build the texture tooltip: m_tooltipText.makeEmpty(); // Build the texture name (ignore CL interoperability): gdHTMLProperties htmlBuilder; htmlBuilder.getGLTextureName(pGDData->_textureMiplevelID, -1, -1, m_tooltipText, false); // Get the texture min / max levels: int minLevel = _textureThumbnailDetails.minLevel(); int maxLevel = _textureThumbnailDetails.maxLevel(); bool resetValues = false; #if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)) gdGDebuggerGlobalVariablesManager& globalVarsManager = gdGDebuggerGlobalVariablesManager::instance(); apProjectType CodeXLProjectType = globalVarsManager.CodeXLProjectType(); // The iPhone OpenGL ES implementation doesn't give us texture level information, so we suffice in the // auto generated value (min = 0 max = log2(width)). resetValues = resetValues && (!apDoesProjectTypeSupportOpenGLES(CodeXLProjectType)); #endif if (resetValues) { minLevel = 0; maxLevel = 1000; } // Calculate the amount if texture levels: int amountOfTextureLevels = maxLevel - minLevel + 1; if (amountOfTextureLevels > 1) { m_tooltipText.appendFormattedString(GD_STR_ObjectTooltipMiplevels, amountOfTextureLevels); } else { m_tooltipText.appendFormattedString(GD_STR_ObjectTooltipMiplevel, amountOfTextureLevels); } m_tooltipText.append(AF_STR_NewLine); // Build the requested internal pixel format string: gtString strTextureRequestedInternalFormat; GLenum textureRequestedInternalFormat = _textureThumbnailDetails.requestedInternalPixelFormat(); apGLPixelInternalFormatParameter internalRequestedPixelFormat; internalRequestedPixelFormat.setValueFromInt(textureRequestedInternalFormat); internalRequestedPixelFormat.valueAsString(strTextureRequestedInternalFormat); // Add the pixel format: m_tooltipText.appendFormattedString(GD_STR_ObjectTooltipRequestedInternalFormat, strTextureRequestedInternalFormat.asCharArray()); m_tooltipText.append(AF_STR_NewLine); // Add the texel data format to the tooltip: if (_textureThumbnailDetails.texelDataFormat() != OA_TEXEL_FORMAT_UNKNOWN) { gtString texelFormatStr; oaGetTexelDataFormatName(_textureThumbnailDetails.texelDataFormat(), texelFormatStr); m_tooltipText.appendFormattedString(GD_STR_ObjectTooltipTexelFormat, texelFormatStr.asCharArray()); m_tooltipText.append(AF_STR_NewLine); } // Add the pixel data type to the tooltip: if (_textureThumbnailDetails.dataType() != OA_UNKNOWN_DATA_TYPE) { gtString dataTypeStr; GLenum glDataType = oaDataTypeToGLEnum(_textureThumbnailDetails.dataType()); apGLenumParameter dataTypeParam(glDataType); dataTypeParam.valueAsString(dataTypeStr); m_tooltipText.appendFormattedString(GD_STR_ObjectTooltipDataType, dataTypeStr.asCharArray()); } } } } // --------------------------------------------------------------------------- // Name: gdTextureImageProxy::getDebugString // Description: Used for debugging // Return Val: gtString // Author: <NAME> // Date: 10/4/2011 // --------------------------------------------------------------------------- gtString gdTextureImageProxy::getDebugString() { gtString dbg; // Sanity check: GT_IF_WITH_ASSERT(_pTextureTreeItemData != NULL) { gdDebugApplicationTreeData* pGDData = qobject_cast<gdDebugApplicationTreeData*>(_pTextureTreeItemData->extendedItemData()); GT_IF_WITH_ASSERT(pGDData != NULL) { dbg.appendFormattedString(L" %d ", pGDData->_textureMiplevelID._textureName); } } return dbg; }
18,523
2,446
/* Copyright (C) 2017 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The app's view controller which presents viewable content. */ #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @class TiledPDFScrollView; @interface DataViewController: UIViewController @property (strong) IBOutlet TiledPDFScrollView *scrollView; @property CGPDFDocumentRef pdf; @property CGPDFPageRef page; @property int pageNumber; @property CGFloat myScale; - (void)dealloc; - (void)viewDidLoad; - (void)viewDidLayoutSubviews; - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator; - (void)restoreScale; @end
244
1,030
<filename>built-in-policies/policyDefinitions/Key Vault/Certificates_Issuers_SupportedCAs.json { "properties": { "displayName": "Certificates should be issued by the specified integrated certificate authority", "policyType": "BuiltIn", "mode": "Microsoft.KeyVault.Data", "description": "Manage your organizational compliance requirements by specifying the Azure integrated certificate authorities that can issue certificates in your key vault such as Digicert or GlobalSign.", "metadata": { "version": "2.0.1", "category": "Key Vault" }, "parameters": { "allowedCAs": { "type": "Array", "metadata": { "displayName": "Allowed Azure Key Vault Supported CAs", "description": "The list of allowed certificate authorities supported by Azure Key Vault." }, "allowedValues": [ "DigiCert", "GlobalSign" ], "defaultValue": [ "DigiCert", "GlobalSign" ] }, "effect": { "type": "string", "defaultValue": "audit", "allowedValues": [ "audit", "deny", "disabled" ], "metadata": { "displayName": "Effect", "description": "'Audit' allows a non-compliant resource to be created, but flags it as non-compliant. 'Deny' blocks the resource creation. 'Disable' turns off the policy." } } }, "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.KeyVault.Data/vaults/certificates" }, { "field": "Microsoft.KeyVault.Data/vaults/certificates/issuer.name", "notIn": "[parameters('allowedCAs')]" } ] }, "then": { "effect": "[parameters('effect')]" } } }, "id": "/providers/Microsoft.Authorization/policyDefinitions/8e826246-c976-48f6-b03e-619bb92b3d82", "name": "8e826246-c976-48f6-b03e-619bb92b3d82" }
916
546
// See https://aka.ms/vscode-remote/devcontainer.json for format details. { "name": "HA unifiprotect", "dockerFile": "Dockerfile", "context": "..", "appPort": [ "9123:9123" ], "runArgs": [ "-v", "${env:HOME}${env:USERPROFILE}/.ssh:/tmp/.ssh" // This is added so you can push from inside the container ], "extensions": [ "ms-python.python", "github.vscode-pull-request-github", "ryanluker.vscode-coverage-gutters", "ms-python.vscode-pylance", "bungcip.better-toml", ], "mounts": [ "type=volume,target=/config,src=vsc-dev-unifiprotect-ha-config,volume-driver=local" ], "settings": { "files.eol": "\n", "editor.tabSize": 4, "terminal.integrated.defaultProfile.linux": "bash", "python.pythonPath": "/usr/local/python/bin/python", "python.analysis.autoSearchPaths": false, "python.formatting.blackArgs": [ "--line-length", "88" ], "python.formatting.provider": "black", "python.linting.banditEnabled": false, "python.linting.enabled": true, "python.linting.flake8Enabled": false, "python.linting.mypyEnabled": false, "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--rcfile=${workspaceFolder}/pyproject.toml" ], "python.linting.pylamaEnabled": false, "python.sortImports.args": [ "--settings-path=${workspaceFolder}/pyproject.toml" ], "editor.formatOnPaste": false, "editor.formatOnSave": true, "editor.formatOnType": true, "files.trimTrailingWhitespace": true, "yaml.customTags": [ "!secret scalar" ] } }
646
4,013
from checkov.common.models.enums import CheckCategories from checkov.common.models.consts import ANY_VALUE from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck class AKSNetworkPolicy(BaseResourceValueCheck): def __init__(self): name = "Ensure AKS cluster has Network Policy configured" id = "CKV_AZURE_7" supported_resources = ['azurerm_kubernetes_cluster'] categories = [CheckCategories.KUBERNETES] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def get_inspected_key(self): return 'network_profile/[0]/network_policy' def get_expected_value(self): return ANY_VALUE check = AKSNetworkPolicy()
271
1,204
<reponame>DiegoEliasCosta/gs-collections<gh_stars>1000+ /* * Copyright 2015 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.multimap.list; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.list.mutable.FastList; /** * Test of {@link SynchronizedPutFastListMultimap}. */ public class SynchronizedPutFastListMultimapTest extends AbstractMutableListMultimapTestCase { @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimap() { return SynchronizedPutFastListMultimap.newMultimap(); } @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimapWithKeyValue(K key, V value) { SynchronizedPutFastListMultimap<K, V> mutableMultimap = this.newMultimap(); mutableMultimap.put(key, value); return mutableMultimap; } @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimapWithKeysValues(K key1, V value1, K key2, V value2) { SynchronizedPutFastListMultimap<K, V> mutableMultimap = this.newMultimap(); mutableMultimap.put(key1, value1); mutableMultimap.put(key2, value2); return mutableMultimap; } @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimapWithKeysValues( K key1, V value1, K key2, V value2, K key3, V value3) { SynchronizedPutFastListMultimap<K, V> mutableMultimap = this.newMultimap(); mutableMultimap.put(key1, value1); mutableMultimap.put(key2, value2); mutableMultimap.put(key3, value3); return mutableMultimap; } @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimapWithKeysValues( K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4) { SynchronizedPutFastListMultimap<K, V> mutableMultimap = this.newMultimap(); mutableMultimap.put(key1, value1); mutableMultimap.put(key2, value2); mutableMultimap.put(key3, value3); mutableMultimap.put(key4, value4); return mutableMultimap; } @SafeVarargs @Override public final <K, V> SynchronizedPutFastListMultimap<K, V> newMultimap(Pair<K, V>... pairs) { return SynchronizedPutFastListMultimap.newMultimap(pairs); } @Override public <K, V> SynchronizedPutFastListMultimap<K, V> newMultimapFromPairs(Iterable<Pair<K, V>> inputIterable) { return SynchronizedPutFastListMultimap.newMultimap(inputIterable); } @SafeVarargs @Override protected final <V> FastList<V> createCollection(V... args) { return FastList.newListWith(args); } }
1,366
2,151
<gh_stars>1000+ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.toolbar; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.R; import org.chromium.chrome.browser.omnibox.LocationBarLayout; import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.security_state.ConnectionSecurityLevel; /** * Unit tests for {@link LocationBarLayout} class. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public final class ToolbarSecurityIconTest { private static final boolean IS_SMALL_DEVICE = true; private static final boolean IS_OFFLINE_PAGE = true; private static final int[] SECURITY_LEVELS = new int[] {ConnectionSecurityLevel.NONE, ConnectionSecurityLevel.HTTP_SHOW_WARNING, ConnectionSecurityLevel.DANGEROUS, ConnectionSecurityLevel.SECURE, ConnectionSecurityLevel.EV_SECURE}; @Mock private Tab mTab; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testGetSecurityLevel() { assertEquals(ConnectionSecurityLevel.NONE, ToolbarModel.getSecurityLevel(null, !IS_OFFLINE_PAGE, null)); assertEquals(ConnectionSecurityLevel.NONE, ToolbarModel.getSecurityLevel(null, IS_OFFLINE_PAGE, null)); assertEquals(ConnectionSecurityLevel.NONE, ToolbarModel.getSecurityLevel(mTab, IS_OFFLINE_PAGE, null)); for (int securityLevel : SECURITY_LEVELS) { when(mTab.getSecurityLevel()).thenReturn(securityLevel); assertEquals("Wrong security level returned for " + securityLevel, securityLevel, ToolbarModel.getSecurityLevel(mTab, !IS_OFFLINE_PAGE, null)); } when(mTab.getSecurityLevel()).thenReturn(ConnectionSecurityLevel.SECURE); assertEquals("Wrong security level returned for HTTPS publisher URL", ConnectionSecurityLevel.SECURE, ToolbarModel.getSecurityLevel(mTab, !IS_OFFLINE_PAGE, "https://example.com")); assertEquals("Wrong security level returned for HTTP publisher URL", ConnectionSecurityLevel.HTTP_SHOW_WARNING, ToolbarModel.getSecurityLevel(mTab, !IS_OFFLINE_PAGE, "http://example.com")); when(mTab.getSecurityLevel()).thenReturn(ConnectionSecurityLevel.DANGEROUS); assertEquals("Wrong security level returned for publisher URL on insecure page", ConnectionSecurityLevel.DANGEROUS, ToolbarModel.getSecurityLevel(mTab, !IS_OFFLINE_PAGE, null)); } @Test public void testGetSecurityIconResource() { for (int securityLevel : SECURITY_LEVELS) { assertEquals("Wrong phone resource for security level " + securityLevel, R.drawable.offline_pin_round, ToolbarModel.getSecurityIconResource( securityLevel, IS_SMALL_DEVICE, IS_OFFLINE_PAGE)); assertEquals("Wrong tablet resource for security level " + securityLevel, R.drawable.offline_pin_round, ToolbarModel.getSecurityIconResource( securityLevel, !IS_SMALL_DEVICE, IS_OFFLINE_PAGE)); } assertEquals(0, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.NONE, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_info, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.NONE, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_info, ToolbarModel.getSecurityIconResource(ConnectionSecurityLevel.HTTP_SHOW_WARNING, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_info, ToolbarModel.getSecurityIconResource(ConnectionSecurityLevel.HTTP_SHOW_WARNING, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_invalid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.DANGEROUS, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_invalid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.DANGEROUS, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.SECURE_WITH_POLICY_INSTALLED_CERT, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.SECURE_WITH_POLICY_INSTALLED_CERT, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.SECURE, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.SECURE, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.EV_SECURE, IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); assertEquals(R.drawable.omnibox_https_valid, ToolbarModel.getSecurityIconResource( ConnectionSecurityLevel.EV_SECURE, !IS_SMALL_DEVICE, !IS_OFFLINE_PAGE)); } }
2,756
464
package dev.fiki.forgehax.main.services; import dev.fiki.forgehax.api.event.SubscribeListener; import dev.fiki.forgehax.api.events.game.PreGameTickEvent; import dev.fiki.forgehax.api.extension.LocalPlayerEx; import dev.fiki.forgehax.api.mod.ServiceMod; import dev.fiki.forgehax.api.modloader.RegisterMod; import lombok.experimental.ExtensionMethod; import lombok.val; import static dev.fiki.forgehax.main.Common.getLocalPlayer; import static dev.fiki.forgehax.main.Common.isInWorld; @RegisterMod @ExtensionMethod({LocalPlayerEx.class}) public class HotbarSelectionService extends ServiceMod { @SubscribeListener public void onClientTick(PreGameTickEvent event) { val data = LocalPlayerEx.getSelectedItemData(); if (isInWorld()) { if (data.getOriginalIndex() != -1 && data.testReset()) { data.resetSelected(getLocalPlayer().getInventory()); } data.tick(); } else { data.reset(); } } }
346
2,766
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2021, <NAME>, <EMAIL> # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('image49.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet1 = workbook.add_worksheet() worksheet2 = workbook.add_worksheet() worksheet3 = workbook.add_worksheet() worksheet1.insert_image('A1', self.image_dir + 'blue.png') worksheet1.insert_image('B3', self.image_dir + 'red.jpg') worksheet1.insert_image('D5', self.image_dir + 'yellow.jpg') worksheet1.insert_image('F9', self.image_dir + 'grey.png') worksheet2.insert_image('A1', self.image_dir + 'blue.png') worksheet2.insert_image('B3', self.image_dir + 'red.jpg') worksheet2.insert_image('D5', self.image_dir + 'yellow.jpg') worksheet2.insert_image('F9', self.image_dir + 'grey.png') worksheet3.insert_image('A1', self.image_dir + 'blue.png') worksheet3.insert_image('B3', self.image_dir + 'red.jpg') worksheet3.insert_image('D5', self.image_dir + 'yellow.jpg') worksheet3.insert_image('F9', self.image_dir + 'grey.png') workbook.close() self.assertExcelEqual()
648
323
<reponame>MartinBalin/graalvm-demos /* * Copyright (c) 2021, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.espresso.jshell; import java.util.Objects; import java.util.function.Supplier; /** * Represents a lazily computed value. Ensures that a single thread runs the computation. */ public final class Lazy<T> implements Supplier<T> { private volatile T ref; private final Supplier<T> supplier; private Lazy(Supplier<T> supplier) { this.supplier = supplier; } /** * If the supplier returns <code>null</code>, {@link NullPointerException} is thrown. Exceptions * thrown by the supplier will be propagated. If the supplier returns a non-null object, it will * be cached and the computation is considered finished. The supplier is guaranteed to run on a * single thread. A successful computation ({@link Supplier#get()} returns a non-null object) is * guaranteed to be executed only once. * * @return the computed object, guaranteed to be non-null */ @Override public T get() { T localRef = ref; if (localRef == null) { synchronized (this) { localRef = ref; if (localRef == null) { localRef = Objects.requireNonNull(supplier.get()); ref = localRef; } } } return localRef; } /** * (Not so) Lazy value that does not run a computation. */ public static <T> Lazy<T> value(T nonNullValue) { Lazy<T> result = new Lazy<T>(null); result.ref = Objects.requireNonNull(nonNullValue); return result; } /** * @param supplier if the supplier returns null, {@link #get()} will throw * {@link NullPointerException} */ public static <V> Lazy<V> of(Supplier<V> supplier) { return new Lazy<>(Objects.requireNonNull(supplier)); } }
1,033
8,273
// Copyright 2010-2021 Google LLC // 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. // The header defines an interface for functions taking and returning an int64_t // and supporting range queries over their domain and codomain. #ifndef OR_TOOLS_UTIL_RANGE_QUERY_FUNCTION_H_ #define OR_TOOLS_UTIL_RANGE_QUERY_FUNCTION_H_ #include <functional> #include <memory> #include "ortools/base/integral_types.h" namespace operations_research { // RangeIntToIntFunction is an interface to int64_t->int64_t functions // supporting fast answer to range queries about their domain/codomain. class RangeIntToIntFunction { public: virtual ~RangeIntToIntFunction() = default; // Suppose f is the abstract underlying function. // Returns f(argument). // TODO(user): Rename to Run virtual int64_t Query(int64_t argument) const = 0; // Returns min_x f(x), where x is in [from, to). virtual int64_t RangeMin(int64_t from, int64_t to) const = 0; // Returns max_x f(x), where x is in [from, to). virtual int64_t RangeMax(int64_t from, int64_t to) const = 0; // Returns the first x from [range_begin, range_end) for which f(x) is in // [interval_begin, interval_end), or range_end if there is no such x. virtual int64_t RangeFirstInsideInterval(int64_t range_begin, int64_t range_end, int64_t interval_begin, int64_t interval_end) const = 0; // Returns the last x from [range_begin, range_end) for which f(x) is in // [interval_begin, interval_end), or range_begin-1 if there is no such x. virtual int64_t RangeLastInsideInterval(int64_t range_begin, int64_t range_end, int64_t interval_begin, int64_t interval_end) const = 0; }; // RangeMinMaxIndexFunction is different from RangeIntToIntFunction in two ways: // // 1. It does not support codomain or value queries. // // 2. For domain queries it returns an argument where the minimum/maximum is // attained, rather than the minimum/maximum value. class RangeMinMaxIndexFunction { public: virtual ~RangeMinMaxIndexFunction() = default; // Suppose f is the abstract underlying function. // Returns an x from [from, to), such that f(x) => f(y) for every y from // [from, to). virtual int64_t RangeMaxArgument(int64_t from, int64_t to) const = 0; // Returns an x from [from, to), such that f(x) <= f(y) for every y from // [from, to). virtual int64_t RangeMinArgument(int64_t from, int64_t to) const = 0; }; // A copy of f is going to be stored in the returned object, so its closure // should remain intact as long as the returned object is being used. RangeIntToIntFunction* MakeBareIntToIntFunction( std::function<int64_t(int64_t)> f); // It is assumed that f is defined over the interval [domain_start, domain_end). // The function scans f once and it is safe to destroy f and its closure after // MakeCachedIntToIntFunction returns. RangeIntToIntFunction* MakeCachedIntToIntFunction( const std::function<int64_t(int64_t)>& f, int64_t domain_start, int64_t domain_end); // It is safe to destroy the first argument and its closure after // MakeCachedRangeMinMaxIndexFunction returns. RangeMinMaxIndexFunction* MakeCachedRangeMinMaxIndexFunction( const std::function<int64_t(int64_t)>& f, int64_t domain_start, int64_t domain_end); } // namespace operations_research #endif // OR_TOOLS_UTIL_RANGE_QUERY_FUNCTION_H_
1,467
465
<reponame>no5ix/realtime-server<gh_stars>100-1000 #include <realtime_srv/RealtimeServer.h> // #ifdef IS_LINUX #include "Character.h" #include "ExampleRedisCli.h" #include "CharacterLuaBind.h" #include "ExampleInputState.h" #include "Robot.h" using namespace realtime_srv; class ExampleSrvForUe4DemoPlus : noncopyable { public: ExampleSrvForUe4DemoPlus() { // for spawning your own controlled GameObject. server_.GetNetworkManager()->SetNewPlayerCallback( std::bind(&ExampleSrvForUe4DemoPlus::OnNewPlayer, this, _1)); // test -> ExampleInputState // for using your own InputState class. server_.GetNetworkManager()->SetCustomInputStateCallback(std::bind( &ExampleSrvForUe4DemoPlus::MyInputState, this)); // init hiredis db_.Init(server_.GetNetworkManager()->GetEventLoop()); } InputState* MyInputState() { return new ExampleInputState; } void Run() { AddRobot(); server_.Run(); } void AddRobot() { server_.GetWorld()->RegistGameObj(GameObjPtr(new Robot)); } // for spawning your own controlled GameObject to the World, // just return a GameObj* , // realtime_srv will sync it to all the other clients. // of course u can do anything else for return nullptr or // u can regist ur GameObj to the World by urself. GameObj* OnNewPlayer(ClientProxyPtr& newClientProxy) { // test -> hiredis db_.SaveNewPlayer(newClientProxy->GetNetId(), "realtime_srv_test_player"); // test -> lua CharacterLuaBind clb; Character* newCharacter = clb.DoFile(); newCharacter->SetPlayerId(newClientProxy->GetNetId()); // after 3 sec, your character die. server_.GetNetworkManager()->GetEventLoop()->runAfter(3.0, [=]() { newCharacter->SetPendingToDie(); }); // after 6 sec, create a new character to play. server_.GetNetworkManager()->GetEventLoop()->runAfter(5.0, [=]() { CharacterPtr anotherCharacter(new Character); // one NetId, One Client. anotherCharacter->SetPlayerId(newClientProxy->GetNetId()); // let the client controll the new character. anotherCharacter->SetMaster(newClientProxy); // regist this character ( derived from GameObj class ) to World. server_.GetWorld()->RegistGameObj(GameObjPtr(anotherCharacter)); }); return newCharacter; } private: RealtimeServer server_; ExampleRedisCli db_; }; int main(int argc, const char** argv) { ExampleSrvForUe4DemoPlus exmaple_server; exmaple_server.Run(); } // #endif // IS_LINUX
855
1,442
<gh_stars>1000+ #include "battery_timer.h" #include "apps_container.h" BatteryTimer::BatteryTimer() : Timer(1) { } bool BatteryTimer::fire() { AppsContainer * container = AppsContainer::sharedAppsContainer(); bool needRedrawing = container->updateBatteryState(); if (Ion::Battery::level() == Ion::Battery::Charge::EMPTY && !Ion::USB::isPlugged()) { container->shutdownDueToLowBattery(); } return needRedrawing; }
144
995
/* * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/portability/OpenSSL.h> #include <openssl/evp.h> #include <stdexcept> namespace fizz { struct AESOCB128 { static const EVP_CIPHER* Cipher() { #if FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_OCB) return EVP_aes_128_ocb(); #else throw std::runtime_error( "aes-ocb support requires OpenSSL 1.1.0 with ocb enabled"); #endif } static const size_t kKeyLength{16}; static const size_t kIVLength{12}; static const size_t kTagLength{16}; static const bool kOperatesInBlocks{true}; static const bool kRequiresPresetTagLen{true}; }; } // namespace fizz
298
407
<filename>core/src/main/java/com/alibaba/smart/framework/engine/xml/parser/ParseContext.java package com.alibaba.smart.framework.engine.xml.parser; import lombok.Data; /** * Created by ettear on 16-4-12. */ @Data public class ParseContext { private ParseContext parent; private Object currentElement; public ParseContext evolve(Object currentElement){ ParseContext parseContext=new ParseContext(); parseContext.setParent(this); parseContext.setCurrentElement(currentElement); return parseContext; } }
192
317
<reponame>realcredit1/drafter<filename>test/refract/dsd/test-Ref.cc // // test/refract/dsd/test-Ref.cc // test-librefract // // Created by <NAME> on 27/08/2017 // Copyright (c) 2017 Apiary Inc. All rights reserved. // #include <catch2/catch.hpp> #include "refract/dsd/Ref.h" using namespace refract; using namespace dsd; TEST_CASE("`Ref`'s default element name is `ref`", "[Element][Ref]") { REQUIRE(std::string(Ref::name) == "ref"); } SCENARIO("`Ref` is default constructed and both copy- and move constructed from", "[ElementData][Ref]") { GIVEN("A default initialized Ref") { Ref ref; THEN("its symbol is an empty string") { REQUIRE(ref.symbol() == ""); } THEN("it equals an empty string") { REQUIRE(ref == ""); } WHEN("from it another Ref is copy constructed") { Ref ref2(ref); THEN("the latter Ref's symbol is also an empty string") { REQUIRE(ref2.symbol() == ""); } THEN("the latter Ref also equals empty string") { REQUIRE(ref2 == ""); } } WHEN("from it another Ref is move constructed") { Ref ref2(std::move(ref)); THEN("the latter Ref's symbol is also an empty string") { REQUIRE(ref2.symbol() == ""); } THEN("the latter Ref also equals empty string") { REQUIRE(ref2 == ""); } } } } SCENARIO("Ref is constructed from values, both copy- and move constructed from and all its copies are destroyed", "[ElementData][Ref]") { GIVEN("A std::string B = `foobar32dsfjklsgh\\000fdfjks`") { const std::string B = "foobar32dsfjklsgh\000fdfjks"; WHEN("a Ref is constructed using it") { { Ref ref(B); THEN("its symbol is B") { REQUIRE(ref.symbol() == B); } THEN("it is equal to B") { REQUIRE(ref == B); } } } } GIVEN("A Ref with value B = \"foobar32dsfjklsgh\\000fdfjks\"") { const std::string B = "foobar32dsfjklsgh\000fdfjks"; Ref ref(B); WHEN("another Ref is copy constructed from it") { Ref ref2(ref); THEN("its symbol is B") { REQUIRE(ref2.symbol() == B); } THEN("it is equal to B") { REQUIRE(ref2 == B); } } WHEN("another Ref is move constructed from it") { Ref ref2(std::move(ref)); THEN("its symbol is B") { REQUIRE(ref2.symbol() == B); } THEN("it is equal to B") { REQUIRE(ref2 == B); } } } } SCENARIO("ref DSDs are tested for equality and inequality", "[Element][Ref][equality]") { GIVEN("An ref DSD with \"foobar\" value") { Ref data("foobar"); GIVEN("An ref element constructed equivalently") { Ref data2("foobar"); THEN("they test positive for equality") { REQUIRE(data == data2); } THEN("they test negative for inequality") { REQUIRE(!(data != data2)); } } GIVEN("An ref element with different value") { Ref data2("foobarz"); THEN("they test negative for equality") { REQUIRE(!(data == data2)); } THEN("they test positive for inequality") { REQUIRE(data != data2); } } GIVEN("An empty ref element") { Ref data2; THEN("they test negative for equality") { REQUIRE(!(data == data2)); } THEN("they test positive for inequality") { REQUIRE(data != data2); } } } }
2,288
382
<filename>clouddriver-yandex/src/main/java/com/netflix/spinnaker/clouddriver/yandex/provider/view/YandexInstanceProvider.java /* * Copyright 2020 YANDEX LLC * * 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.spinnaker.clouddriver.yandex.provider.view; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.spinnaker.cats.cache.Cache; import com.netflix.spinnaker.clouddriver.model.InstanceProvider; import com.netflix.spinnaker.clouddriver.security.AccountCredentials; import com.netflix.spinnaker.clouddriver.security.AccountCredentialsProvider; import com.netflix.spinnaker.clouddriver.yandex.YandexCloudProvider; import com.netflix.spinnaker.clouddriver.yandex.model.YandexCloudInstance; import com.netflix.spinnaker.clouddriver.yandex.provider.Keys; import com.netflix.spinnaker.clouddriver.yandex.security.YandexCloudCredentials; import com.netflix.spinnaker.clouddriver.yandex.service.YandexCloudFacade; import java.util.Optional; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class YandexInstanceProvider implements InstanceProvider<YandexCloudInstance, String> { private AccountCredentialsProvider accountCredentialsProvider; private YandexCloudFacade yandexCloudFacade; private final CacheClient<YandexCloudInstance> cacheClient; @Autowired public YandexInstanceProvider( Cache cacheView, AccountCredentialsProvider accountCredentialsProvider, YandexCloudFacade yandexCloudFacade, ObjectMapper objectMapper) { this.yandexCloudFacade = yandexCloudFacade; this.accountCredentialsProvider = accountCredentialsProvider; this.cacheClient = new CacheClient<>( cacheView, objectMapper, Keys.Namespace.INSTANCES, YandexCloudInstance.class); } @Override public String getCloudProvider() { return YandexCloudProvider.ID; } @Override public YandexCloudInstance getInstance(String account, String region, String name) { return getAccountCredentials(account) .map(credentials -> Keys.getInstanceKey(account, "*", credentials.getFolder(), name)) .flatMap(cacheClient::findOne) .orElse(null); } @Override public String getConsoleOutput(String account, String region, String id) { YandexCloudCredentials credentials = getAccountCredentials(account) .orElseThrow(() -> new IllegalArgumentException("Invalid credentials: " + account)); return Optional.ofNullable(getInstance(account, region, id)) .map(instance -> yandexCloudFacade.getSerialPortOutput(credentials, instance.getId())) .orElse(null); } @NotNull private Optional<YandexCloudCredentials> getAccountCredentials(String account) { AccountCredentials<?> accountCredentials = accountCredentialsProvider.getCredentials(account); if (!(accountCredentials instanceof YandexCloudCredentials)) { return Optional.empty(); } return Optional.of((YandexCloudCredentials) accountCredentials); } }
1,170
4,054
<gh_stars>1000+ { "docs": [ { "location": "/", "text": "Read the Docs MkDocs Test Project\n\n\nThis is a test of \nMkDocs\n as it appears on \nRead the Docs\n.", "title": "Read the Docs MkDocs Test Project" }, { "location": "/#read-the-docs-mkdocs-test-project", "text": "Read the Docs MkDocs Test Project\n\n\nThis is a test of \nMkDocs\n as it appears on \nRead the Docs\n.", "title": "Read the Docs MkDocs Test Project" }, { "location": "/versions/", "text": "Versions & Themes\n\n\nThere are a number of versions and themes for mkdocs.", "title": "Versions & Themes" }, { "location": "/versions/#versions-themes", "text": "Versions & Themes\n\n\nThere are a number of versions and themes for mkdocs.", "title": "Versions &amp; Themes" } ] }
364
416
<filename>runtime/classpath/src/main/java/org/springframework/roo/classpath/details/annotations/AbstractAnnotationAttributeValue.java package org.springframework.roo.classpath.details.annotations; import org.apache.commons.lang3.Validate; import org.springframework.roo.model.JavaSymbolName; /** * Abstract base class for annotation attribute values. * * @author <NAME> * @since 1.0 */ public abstract class AbstractAnnotationAttributeValue<T extends Object> implements AnnotationAttributeValue<T> { private final JavaSymbolName name; /** * Constructor * * @param name the attribute name (required) */ protected AbstractAnnotationAttributeValue(final JavaSymbolName name) { Validate.notNull(name, "Annotation attribute name required"); this.name = name; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof AbstractAnnotationAttributeValue<?>)) { return false; } final AbstractAnnotationAttributeValue<?> other = (AbstractAnnotationAttributeValue<?>) obj; if (getValue() == null) { if (other.getValue() != null) { return false; } } else if (!getValue().equals(other.getValue())) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } public JavaSymbolName getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (getValue() == null ? 0 : getValue().hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } }
637
422
<filename>python/setup.py<gh_stars>100-1000 # ---------------------------------------------------------------------- # Copyright (c) 2016, The Regents of the University of California 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 The Regents of the University of California # 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 REGENTS OF THE # UNIVERSITY OF CALIFORNIA 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. # ---------------------------------------------------------------------- # Filename: setup.py # Version: 2.0 # Description: Python setup script for RIFFA. # Author: <NAME> # History: @mattj: Initial release. Version 2.0. from distutils.core import setup setup(name='riffa', version='2.0', description='RIFFA 2.0 Python Library', author='<NAME>', author_email='<EMAIL>', url='http://cseweb.ucsd.edu/~mdjacobs', platforms='Linux,Windows', license='Other/Proprietary License', py_modules=['riffa'], long_description=''' Copyright (c) 2016, The Regents of the University of California 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 The Regents of the University of California 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 REGENTS OF THE UNIVERSITY OF CALIFORNIA 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.''' )
1,178
494
package app.hanks.com.conquer.util; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.view.View; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import app.hanks.com.conquer.R; import app.hanks.com.conquer.config.Constants; /** * 给一个布局用来播放音频 * * @author zyh */ public class AudioUtils { private static MediaPlayer player;// 播放器 private static Timer timer_play;// 定时器 private static MyBroadcastReceiver receiver; private static AudioUtils audioUtils; private static String lastPath; private static int lastView; private AudioUtils() { } public static AudioUtils getInstance() { if (audioUtils == null) { audioUtils = new AudioUtils(); if (timer_play == null) timer_play = new Timer(); } return audioUtils; } /** * 播放或继续 * * @param context * @param view * @param recorderPath */ public void play(final Context context, View view, String recorderPath) { if (lastPath != null) L.d("lastPath=" + lastPath); L.d("lastView=" + lastView); L.d("recorderPath=" + recorderPath + ",view=" + view.hashCode()); // 注册退出广播 if (receiver == null) { L.d("注册音乐停止广播"); IntentFilter filter = new IntentFilter(); filter.addAction(Constants.ACTION_DESTORY_PLAYER); receiver = new MyBroadcastReceiver(); context.registerReceiver(receiver, filter); } // 换了个音频,重新开始 if (recorderPath == null || !recorderPath.equals(lastPath) || view.hashCode() != lastView) { lastPath = recorderPath; lastView = view.hashCode(); // 停止上一个控件状态 if (pb != null) pb.setProgress(0); if (ib_play != null) { ib_play.setTag("play"); ib_play.setImageResource(R.drawable.play_audio); } // 获取当前的控件 ib_play = (ImageButton) view.findViewById(R.id.ib_play); pb = (ProgressBar) view.findViewById(R.id.pb); tv_duration = (TextView) view.findViewById(R.id.tv_duration); loading = (ProgressBar) view.findViewById(R.id.loading); } L.d("播放按钮tag" + ib_play.getTag()); // 判断播放按钮状态 if (ib_play.getTag().equals("play")) { // 播放操作 ib_play.setTag("pause"); ib_play.setImageResource(R.drawable.pause_audio); if (player != null) player.release(); player = new MediaPlayer(); player.reset(); try { player.setDataSource(recorderPath); } catch (Exception e) { e.printStackTrace(); } player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepareAsync(); loading.setVisibility(0); player.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { pb.setMax(player.getDuration()); loading.setVisibility(View.GONE); player.start(); playingAnim(context); } }); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { ib_play.setTag("play"); ib_play.setImageResource(R.drawable.play_audio); pb.setProgress(0); if (timer_play != null) { timer_play.cancel(); timer_play = null; } } }); } else if (ib_play.getTag().equals("pause")) {// 暂停操作 ib_play.setTag("resume"); ib_play.setImageResource(R.drawable.play_audio); player.pause(); if (timer_play != null) { timer_play.cancel(); timer_play = null; } stopAnim(); } else { ib_play.setTag("pause"); ib_play.setImageResource(R.drawable.pause_audio); player.start(); playingAnim(context); } // try { // if (player == null) player = new MediaPlayer(); // player.setDataSource(recorderPath); // player.setAudioStreamType(AudioManager.STREAM_MUSIC); // player.prepareAsync(); // loading.setVisibility(0); // player.setOnPreparedListener(new OnPreparedListener() { // @Override // public void onPrepared(MediaPlayer mp) { // pb.setMax(player.getDuration()); // if (isFirst) { // isFirst = false; // pb.setProgress(0); // curPosition = 0; // loading.setVisibility(View.GONE); // } // palying(context); // } // }); // player.setOnCompletionListener(new OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // ib_play.setTag("play"); // ib_play.setImageResource(R.drawable.play_audio); // pb.setProgress(0); // curPosition = 0; // stopAnim(); // releasePlayer(); // } // }); // } catch (Exception e) { // e.printStackTrace(); // } } /** * 释放播放器 */ private void releasePlayer() { if (pb != null) pb.setProgress(0); if (ib_play != null) { ib_play.setTag("play"); ib_play.setImageResource(R.drawable.play_audio); } if (player != null) { player.release(); player = null; } } /** * 停止进度,秒动画 */ private void stopAnim() { if (timer_play != null) { timer_play.cancel(); timer_play = null; } } /** * 播放时进度,秒的动画 */ private void playingAnim(final Context context) { if (timer_play == null) timer_play = new Timer(); timer_play.schedule(new TimerTask() { @Override public void run() { ((Activity) context).runOnUiThread(new Runnable() { public void run() { if (player != null) { tv_duration.setText((player.getCurrentPosition() / 1000) + "秒"); pb.setProgress(player.getCurrentPosition()); } } }); } }, new Date(), 1000); } // // private void palying(final Context context) { // try { // player.start(); // // 秒++ // // } catch (IllegalStateException e) { // e.printStackTrace(); // } // } // // public void pause() { // try { // if (player != null && player.isPlaying()) { // curPosition = player.getCurrentPosition(); // player.pause(); // } // if (timer_play != null) { // timer_play.cancel(); // timer_play = null; // } // } catch (IllegalStateException e) { // e.printStackTrace(); // } // } private ProgressBar pb; private TextView tv_duration; private ProgressBar loading; private ImageButton ib_play; /** * Acivitiy 进行Finish的接受者 * * @author wmf */ public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent != null && Constants.ACTION_DESTORY_PLAYER.equals(intent.getAction())) { stopAnim(); releasePlayer(); L.d("停止音乐"); context.unregisterReceiver(this); receiver = null; } } } }
4,289
436
/** * The MIT License * Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS) * Copyright (c) 2018 Estonian Information System Authority (RIA), * Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK) * Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * 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 ee.ria.xroad.monitor; import ee.ria.xroad.common.TestCertUtil; import ee.ria.xroad.common.conf.serverconf.ServerConf; import ee.ria.xroad.common.util.CryptoUtils; import ee.ria.xroad.monitor.CertificateInfoSensor.CertificateInfoCollector; import ee.ria.xroad.monitor.CertificateInfoSensor.TokenExtractor; import ee.ria.xroad.monitor.common.SystemMetricNames; import ee.ria.xroad.signer.protocol.dto.CertRequestInfo; import ee.ria.xroad.signer.protocol.dto.CertificateInfo; import ee.ria.xroad.signer.protocol.dto.KeyInfo; import ee.ria.xroad.signer.protocol.dto.TokenInfo; import ee.ria.xroad.signer.protocol.dto.TokenStatusInfo; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.typesafe.config.ConfigFactory; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import scala.concurrent.Await; import scala.concurrent.duration.Duration; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static ee.ria.xroad.monitor.CertificateInfoSensor.CERT_HEX_DELIMITER; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * CertificateInfoSensorTest */ @Slf4j public class CertificateInfoSensorTest { private static ActorSystem actorSystem; private MetricRegistry metrics; private TokenInfo caTokenInfo; private TokenInfo tspTokenInfo; private static String caCertId; private static String tspCertId; private static final String CA_NOT_BEFORE = "2014-09-29T09:41:37Z"; private static final String CA_NOT_AFTER = "2024-09-26T09:41:37Z"; private static final String TSP_NOT_BEFORE = "2012-11-29T11:53:06Z"; private static final String TSP_NOT_AFTER = "2014-11-29T11:53:06Z"; /** * Before test handler */ @Before public void init() throws Exception { actorSystem = ActorSystem.create("AkkaRemoteServer", ConfigFactory.load()); metrics = new MetricRegistry(); MetricRegistryHolder.getInstance().setMetrics(metrics); // test uses real certificates from common-test module X509Certificate caCert = TestCertUtil.getCaCert(); X509Certificate tspCert = TestCertUtil.getTspCert(); CertificateInfo caInfo = createTestCertificateInfo(caCert); caCertId = caInfo.getId(); CertificateInfo tspInfo = createTestCertificateInfo(tspCert); tspCertId = tspInfo.getId(); KeyInfo caKeyInfo = createTestKeyInfo(caInfo); KeyInfo tspKeyInfo = createTestKeyInfo(tspInfo); caTokenInfo = createTestTokenInfo(caKeyInfo); tspTokenInfo = createTestTokenInfo(tspKeyInfo); ServerConf.reload(new EmptyServerConf()); } /** * Shut down actor system and wait for clean up, so that other tests are not disturbed */ @After public void tearDown() throws Exception { Await.result(actorSystem.terminate(), Duration.Inf()); } private TokenInfo createTestTokenInfo(KeyInfo... keyInfoParams) { List<KeyInfo> keyInfos = new ArrayList<>(); for (KeyInfo info: keyInfoParams) { keyInfos.add(info); } Map<String, String> tokenInfos = new HashMap<>(); return new TokenInfo("type", "friendlyName", "id", false, false, false, "serialNumber", "label", -1, TokenStatusInfo.OK, Collections.unmodifiableList(keyInfos), Collections.unmodifiableMap(tokenInfos)); } private KeyInfo createTestKeyInfo(CertificateInfo caInfo) { KeyInfo keyInfo = new KeyInfo(true, null, "friendlyName", "id", "label", "publickey", new ArrayList<CertificateInfo>(), new ArrayList<CertRequestInfo>(), "mechanismName"); keyInfo.getCerts().add(caInfo); return keyInfo; } private CertificateInfo createTestCertificateInfo(X509Certificate cert) throws Exception { CertificateInfo cInfo = new CertificateInfo( null, false, false, "status", CryptoUtils.calculateDelimitedCertHexHash(cert, CERT_HEX_DELIMITER), cert.getEncoded(), null); return cInfo; } @Test public void testSystemMetricsRequest() throws Exception { log.info("testing"); final Props props = Props.create(CertificateInfoSensor.class); final TestActorRef<CertificateInfoSensor> ref = TestActorRef.create(actorSystem, props, "testActorRef"); CertificateInfoSensor sensor = ref.underlyingActor(); CertificateInfoCollector collector = new CertificateInfoCollector() .addExtractor(new TokenExtractor(() -> Arrays.asList(caTokenInfo, tspTokenInfo))); sensor.setCertificateInfoCollector(collector); sensor.onReceive(new CertificateInfoSensor.CertificateInfoMeasure()); Map<String, Metric> result = metrics.getMetrics(); assertEquals(2, result.entrySet().size()); // certs & jmx certs SimpleSensor<JmxStringifiedData<CertificateMonitoringInfo>> certificates = (SimpleSensor<JmxStringifiedData<CertificateMonitoringInfo>>) result.get(SystemMetricNames.CERTIFICATES); SimpleSensor<ArrayList<String>> certificatesAsText = (SimpleSensor<ArrayList<String>>) result.get(SystemMetricNames.CERTIFICATES_STRINGS); assertNotNull(certificates); assertNotNull(certificatesAsText); assertEquals(2, certificates.getValue().getDtoData().size()); assertEquals(3, certificatesAsText.getValue().size()); // header line + 2 certs CertificateMonitoringInfo caInfo = getCertificateInfo(certificates.getValue().getDtoData(), caCertId); assertEquals(CA_NOT_AFTER, caInfo.getNotAfter()); assertEquals(CA_NOT_BEFORE, caInfo.getNotBefore()); CertificateMonitoringInfo tspInfo = getCertificateInfo(certificates.getValue().getDtoData(), tspCertId); assertEquals(TSP_NOT_AFTER, tspInfo.getNotAfter()); assertEquals(TSP_NOT_BEFORE, tspInfo.getNotBefore()); log.info("testing done"); } @Test public void testFailingCertExtractionSystemMetricsRequest() throws Exception { final Props props = Props.create(CertificateInfoSensor.class); final TestActorRef<CertificateInfoSensor> ref = TestActorRef.create(actorSystem, props, "testActorRef"); X509Certificate mockCert = mock(X509Certificate.class, Mockito.RETURNS_DEEP_STUBS); when(mockCert.getEncoded()).thenThrow(new IllegalStateException("some random exception")); when(mockCert.getIssuerDN().getName()).thenReturn("DN"); CertificateInfoSensor sensor = ref.underlyingActor(); CertificateInfoCollector collector = new CertificateInfoCollector() .addExtractor(new CertificateInfoSensor.CertificateInfoExtractor() { @Override Stream<CertificateMonitoringInfo> getCertificates() { return convertToMonitoringInfo( mockCert, CertificateMonitoringInfo.CertificateType.AUTH_OR_SIGN, true); } }); sensor.setCertificateInfoCollector(collector); sensor.onReceive(new CertificateInfoSensor.CertificateInfoMeasure()); Map<String, Metric> result = metrics.getMetrics(); assertEquals(2, result.entrySet().size()); // certs & jmx certs SimpleSensor<JmxStringifiedData<CertificateMonitoringInfo>> certificates = (SimpleSensor<JmxStringifiedData<CertificateMonitoringInfo>>) result.get(SystemMetricNames.CERTIFICATES); SimpleSensor<ArrayList<String>> certificatesAsText = (SimpleSensor<ArrayList<String>>) result.get(SystemMetricNames.CERTIFICATES_STRINGS); assertNotNull(certificates); assertNotNull(certificatesAsText); assertEquals(0, certificates.getValue().getDtoData().size()); assertEquals(1, certificatesAsText.getValue().size()); // header line + 0 certs } private CertificateMonitoringInfo getCertificateInfo(ArrayList<CertificateMonitoringInfo> dtoData, String certId) { return dtoData.stream() .filter(c -> certId.equals(c.getSha1hash())) .findAny() .get(); } }
4,079
2,628
<filename>pony/orm/tests/test_get_pk.py import unittest from datetime import date from pony.orm import * from pony.orm.tests import setup_database, teardown_database day = date.today() db = Database() class A(db.Entity): b = Required("B") c = Required("C") PrimaryKey(b, c) class B(db.Entity): id = PrimaryKey(date) a_set = Set(A) class C(db.Entity): x = Required("X") y = Required("Y") a_set = Set(A) PrimaryKey(x, y) class X(db.Entity): id = PrimaryKey(int) c_set = Set(C) class Y(db.Entity): id = PrimaryKey(int) c_set = Set(C) class Test(unittest.TestCase): def setUp(self): setup_database(db) with db_session: x1 = X(id=123) y1 = Y(id=456) b1 = B(id=day) c1 = C(x=x1, y=y1) A(b=b1, c=c1) def tearDown(self): teardown_database(db) @db_session def test_1(self): a1 = A.select().first() a2 = A[a1.get_pk()] self.assertEqual(a1, a2) @db_session def test2(self): a = A.select().first() b = B.select().first() c = C.select().first() pk = (b.get_pk(), c._get_raw_pkval_()) self.assertTrue(a is A[pk]) @db_session def test3(self): a = A.select().first() c = C.select().first() pk = (day, c.get_pk()) self.assertTrue(a is A[pk])
731
441
<reponame>vinhig/rbfx // // Copyright (c) 2008-2020 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../IO/File.h" #include "../IO/Log.h" #include "../IO/PackageFile.h" #include "../IO/FileSystem.h" namespace Urho3D { PackageFile::PackageFile(Context* context) : Object(context), totalSize_(0), totalDataSize_(0), checksum_(0), compressed_(false) { } PackageFile::PackageFile(Context* context, const ea::string& fileName, unsigned startOffset) : Object(context), totalSize_(0), totalDataSize_(0), checksum_(0), compressed_(false) { Open(fileName, startOffset); } PackageFile::~PackageFile() = default; bool PackageFile::Open(const ea::string& fileName, unsigned startOffset) { SharedPtr<File> file(new File(context_, fileName)); if (!file->IsOpen()) return false; // Check ID, then read the directory file->Seek(startOffset); ea::string id = file->ReadFileID(); if (id != "UPAK" && id != "ULZ4" && id != "RPAK" && id != "RLZ4") { // If start offset has not been explicitly specified, also try to read package size from the end of file // to know how much we must rewind to find the package start if (!startOffset) { unsigned fileSize = file->GetSize(); file->Seek((unsigned)(fileSize - sizeof(unsigned))); unsigned newStartOffset = fileSize - file->ReadUInt(); if (newStartOffset < fileSize) { startOffset = newStartOffset; file->Seek(startOffset); id = file->ReadFileID(); } } if (id != "UPAK" && id != "ULZ4" && id != "RPAK" && id != "RLZ4") { URHO3D_LOGERROR(fileName + " is not a valid package file"); return false; } } fileName_ = fileName; nameHash_ = fileName_; totalSize_ = file->GetSize(); compressed_ = id == "ULZ4" || id == "RLZ4"; unsigned numFiles = file->ReadUInt(); checksum_ = file->ReadUInt(); if (id == "RPAK" || id == "RLZ4") { // New PAK file format includes two extra PAK header fields: // * Version. At this time this field is unused and is always 0. It will be used in the future if PAK format needs to be extended. // * File list offset. New format writes file list in the end of the file. This allows PAK creation without knowing entire file list // beforehand. unsigned version = file->ReadUInt(); // Reserved for future use. assert(version == 0); int64_t fileListOffset = file->ReadInt64(); // New format has file list at the end of the file. file->Seek(fileListOffset); // TODO: Serializer/Deserializer do not support files bigger than 4 GB } for (unsigned i = 0; i < numFiles; ++i) { ea::string entryName = file->ReadString(); PackageEntry newEntry{}; newEntry.offset_ = file->ReadUInt() + startOffset; totalDataSize_ += (newEntry.size_ = file->ReadUInt()); newEntry.checksum_ = file->ReadUInt(); if (!compressed_ && newEntry.offset_ + newEntry.size_ > totalSize_) { URHO3D_LOGERROR("File entry " + entryName + " outside package file"); return false; } else entries_[entryName] = newEntry; } return true; } bool PackageFile::Exists(const ea::string& fileName) const { bool found = entries_.find(fileName) != entries_.end(); #ifdef _WIN32 // On Windows perform a fallback case-insensitive search if (!found) { for (auto i = entries_.begin(); i != entries_.end(); ++i) { if (!i->first.comparei(fileName)) { found = true; break; } } } #endif return found; } const PackageEntry* PackageFile::GetEntry(const ea::string& fileName) const { auto i = entries_.find(fileName); if (i != entries_.end()) return &i->second; #ifdef _WIN32 // On Windows perform a fallback case-insensitive search else { for (auto j = entries_.begin(); j != entries_.end(); ++j) { if (!j->first.comparei(fileName)) return &j->second; } } #endif return nullptr; } void PackageFile::Scan(ea::vector<ea::string>& result, const ea::string& pathName, const ea::string& filter, bool recursive) const { result.clear(); ea::string sanitizedPath = GetSanitizedPath(pathName); ea::string filterExtension; unsigned dotPos = filter.find_last_of('.'); if (dotPos != ea::string::npos) filterExtension = filter.substr(dotPos); if (filterExtension.contains('*')) filterExtension.clear(); bool caseSensitive = true; #ifdef _WIN32 // On Windows ignore case in string comparisons caseSensitive = false; #endif const StringVector& entryNames = GetEntryNames(); for (auto i = entryNames.begin(); i != entryNames.end(); ++i) { ea::string entryName = GetSanitizedPath(*i); if ((filterExtension.empty() || entryName.ends_with(filterExtension, caseSensitive)) && entryName.starts_with(sanitizedPath, caseSensitive)) { ea::string fileName = entryName.substr(sanitizedPath.length()); if (fileName.starts_with("\\") || fileName.starts_with("/")) fileName = fileName.substr(1, fileName.length() - 1); if (!recursive && (fileName.contains("\\") || fileName.contains("/"))) continue; result.push_back(fileName); } } } }
2,712
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Caubios-Loos","dpt":"Pyrénées-Atlantiques","inscrits":414,"abs":60,"votants":354,"blancs":32,"nuls":9,"exp":313,"res":[{"panneau":"1","voix":246},{"panneau":"2","voix":67}]}
96
5,788
/* * 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.shardingsphere.driver.jdbc.base; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.dbcp2.BasicDataSource; import javax.sql.DataSource; /** * Data source builder. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class DataSourceBuilder { /** * Build data source. * * @param dataSourceName data source name * @return data source */ public static DataSource build(final String dataSourceName) { BasicDataSource result = new BasicDataSource(); result.setDriverClassName("org.h2.Driver"); result.setUrl(String.format("jdbc:h2:mem:%s;DATABASE_TO_UPPER=false;MODE=MySQL", dataSourceName)); result.setUsername("sa"); result.setPassword(""); result.setMaxTotal(50); return result; } }
521
764
{"symbol": "APY","address": "0x95a4492F028aa1fd432Ea71146b433E7B4446611","overview":{"en": ""},"email": "","website": "https://apy.finance/","state": "NORMAL","links": {"blog": "https://medium.com/apy-finance","twitter": "https://twitter.com/apyfinance","telegram": "","github": ""}}
105
945
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 <iostream> #include "itkVariableLengthVector.h" #include "itkMath.h" #define ASSERT(cond, text) \ CLANG_PRAGMA_PUSH \ CLANG_SUPPRESS_Wfloat_equal if (!(cond)) CLANG_PRAGMA_POP \ { \ std::cerr << __FILE__ << ":" << __LINE__ << ":" \ << "Assertion failed: " << #cond << ": " << text << std::endl; \ result = EXIT_FAILURE; \ } \ ITK_MACROEND_NOOP_STATEMENT int itkVariableLengthVectorTest(int, char *[]) { using FloatVariableLengthVectorType = itk::VariableLengthVector<float>; using DoubleVariableLengthVectorType = itk::VariableLengthVector<double>; int result = EXIT_SUCCESS; FloatVariableLengthVectorType f(3); f[0] = 1.0; f[1] = 2.0; f[2] = 3.0; DoubleVariableLengthVectorType g(3); g[0] = 4.0; g[1] = 5.0; g[2] = 6.0; FloatVariableLengthVectorType h; h = g + f; g = h++; h -= 1.1; h *= 2.0; h /= 2.0; h += g; h -= g; h = g - h; h = -h; std::cout << h << std::endl; // should be [-1.1 -1.1 -1.1] h = (FloatVariableLengthVectorType)g; if (h != static_cast<FloatVariableLengthVectorType>(g)) { std::cerr << "Casts: [FAILED]" << std::endl; } { auto * d = new double[3]; d[0] = 0.1; d[1] = 0.2; d[2] = 0.3; { DoubleVariableLengthVectorType x(d, 3, false); } { DoubleVariableLengthVectorType x(d, 3, false); if ((itk::Math::NotExactlyEquals(d[0], 0.1)) || (itk::Math::NotExactlyEquals(x[0], 0.1))) { std::cerr << "Memory management(1): [FAILED]" << std::endl; } std::cout << x << std::endl; x.SetSize(5, false); x[3] = 3.0; x[4] = 4.0; std::cout << d[0] << "->" << x << std::endl; if (itk::Math::NotExactlyEquals(d[0], 0.1) || itk::Math::NotExactlyEquals(x[0], 0.1)) // increase length but preserve existing data { std::cerr << "Memory management(2): [FAILED]" << std::endl; } x.SetSize(2, false); // reduce length but preserve existing data std::cout << x << std::endl; if ((x.GetSize() != 2) || (itk::Math::NotExactlyEquals(d[0], 0.1)) || (itk::Math::NotExactlyEquals(x[0], 0.1))) { std::cerr << "Memory management(3): [FAILED]" << std::endl; } x.SetSize(5, true); // increase size, destroy data. x.SetSize(7, true); // increase size, destroy data. x.SetSize(6, true); // decrease size, destroy data. } // Tests for SetSize(size, allocation policy, values keeping policy) { DoubleVariableLengthVectorType ref(d, 3, false); ASSERT(ref.IsAProxy(), "Unexpected Reference VLV value"); ASSERT((ref[0] == 0.1) && (d[0] == 0.1), "Unexpected Reference VLV value"); DoubleVariableLengthVectorType x(d, 3, false); ASSERT(x.IsAProxy(), "Unexpected VLV value"); ASSERT((x[0] == 0.1) && (x[0] == 0.1), "Unexpected VLV value"); // ===[ Keep old values // ---[ Shrink To Fit x.SetSize(5, DoubleVariableLengthVectorType::ShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing a proxy, it shall not be a proxy anymore"); ASSERT(ref[0] == x[0] && ref[1] == x[1] && ref[2] == x[2], "Old Values shall have been kept"); x[3] = 3.0; x[4] = 4.0; double * start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::ShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(x == ref, "Values haven't been preserved"); ASSERT(&x[0] != start, "ShrinkToFit shall induce a resizing"); start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::ShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(&x[0] == start, "ShrinkToFit on the same size shall not induce a reallocation"); // ---[ Don't Shrink To Fit x.SetSize(5, DoubleVariableLengthVectorType::DontShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref[0] == x[0] && ref[1] == x[1] && ref[2] == x[2], "Old Values shall have been kept"); ASSERT(&x[0] != start, "DontShrinkToFit shall induce a resizing when the size grows"); x[3] = 3.0; x[4] = 4.0; start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::DontShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref == x, "Old Values shall have been kept"); ASSERT(&x[0] == start, "DontShrinkToFit shall not induce a resizing when the size diminishes"); start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::DontShrinkToFit(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref == x, "Old Values shall have been kept"); ASSERT(&x[0] == start, "DontShrinkToFit shall not induce a resizing when the size stays the same"); // ---[ Always Reallocate x.SetSize(5, DoubleVariableLengthVectorType::AlwaysReallocate(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref[0] == x[0] && ref[1] == x[1] && ref[2] == x[2], "Old Values shall have been kept"); ASSERT(&x[0] != start, "AlwaysReallocate shall induce a reallocation when resizing"); start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::AlwaysReallocate(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref[0] == x[0] && ref[1] == x[1] && ref[2] == x[2], "Old Values shall have been kept"); ASSERT(&x[0] != start, "AlwaysReallocate shall induce a reallocation when resizing"); start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::AlwaysReallocate(), DoubleVariableLengthVectorType::KeepOldValues()); ASSERT(!x.IsAProxy(), "After resizing, it shall never be a proxy"); ASSERT(ref[0] == x[0] && ref[1] == x[1] && ref[2] == x[2], "Old Values shall have been kept"); ASSERT(&x[0] != start, "AlwaysReallocate shall induce a reallocation when resizing, even with the same size"); start = &x[0]; // ===[ Don't keep old values // ---[ ShrinkToFit x.SetSize(5, DoubleVariableLengthVectorType::ShrinkToFit(), DoubleVariableLengthVectorType::DumpOldValues()); ASSERT(&x[0] != start, "ShrintToFit(bigger) => reallocate"); // ASSERT(x[0] is uninitialized); x[0] = ref[0]; start = &x[0]; x.SetSize(3, DoubleVariableLengthVectorType::ShrinkToFit(), DoubleVariableLengthVectorType::DumpOldValues()); ASSERT(&x[0] != start, "ShrintToFit(smaller) => reallocate"); // ASSERT(x[0] is uninitialized); x[0] = ref[0]; start = &x[0]; x.SetSize(5, DoubleVariableLengthVectorType::DontShrinkToFit(), DoubleVariableLengthVectorType::DumpOldValues()); ASSERT(&x[0] != start, "DontShrintToFit(bigger) => reallocate"); // ASSERT(x[0] is uninitialized); x[0] = ref[0]; start = &x[0]; } // Test on assignments { // We won't be able to test that old values are dumped. // Only when reallocations will be avoided. DoubleVariableLengthVectorType ref1(3); ref1[0] = 0.1; ref1[1] = 0.2; ref1[2] = 0.3; DoubleVariableLengthVectorType ref2(3); ref2[0] = 1.1; ref2[1] = 1.2; ref2[2] = 1.3; DoubleVariableLengthVectorType ref4(4); ref4[0] = 1.1; ref4[1] = 1.2; ref4[2] = 1.3; ref4[3] = 1.4; DoubleVariableLengthVectorType x; ASSERT(x != ref1, "New VLV shall be empty"); x = ref1; ASSERT(x == ref1, "Ref1 is expected to be copied into x"); double * start = &x[0]; x = ref2; ASSERT(x == ref2, "Ref2 is expected to be copied into x"); ASSERT(start == &x[0], "Assignment doesn't imply reallocation when the new size is identical to the current one"); x = ref4; ASSERT(x == ref4, "Ref4 is expected to be copied into x"); ASSERT(start != &x[0], "Assignment implies reallocation when the current size is insufficient to hold the new value"); start = &x[0]; x = ref1; ASSERT(x == ref1, "Ref1 is expected to be copied into x"); ASSERT(start == &x[0], "Assignment doesn't imply reallocation when the current size is enough"); // NB: From here, x=ref4; will induce a reallocation even if enough memory has already // been allocated. } // Test Swap { DoubleVariableLengthVectorType ref1(3); ref1[0] = 0.1; ref1[1] = 0.2; ref1[2] = 0.3; DoubleVariableLengthVectorType ref2(3); ref2[0] = 1.1; ref2[1] = 1.2; ref2[2] = 1.3; ref1.Swap(ref2); ASSERT(ref1[0] == 1.1, "Swap shall ... swap VLVs"); ASSERT(ref1[1] == 1.2, "Swap shall ... swap VLVs"); ASSERT(ref1[2] == 1.3, "Swap shall ... swap VLVs"); ASSERT(ref2[0] == 0.1, "Swap shall ... swap VLVs"); ASSERT(ref2[1] == 0.2, "Swap shall ... swap VLVs"); ASSERT(ref2[2] == 0.3, "Swap shall ... swap VLVs"); } // Test FastAssign { DoubleVariableLengthVectorType ref1(3); ref1[0] = 0.1; ref1[1] = 0.2; ref1[2] = 0.3; DoubleVariableLengthVectorType ref2(3); ref2[0] = 1.1; ref2[1] = 1.2; ref2[2] = 1.3; DoubleVariableLengthVectorType ref4(4); ref4[0] = 1.1; ref4[1] = 1.2; ref4[2] = 1.3; ref4[3] = 1.4; DoubleVariableLengthVectorType x(3); // FastAssign pre conditions assert(x.GetSize() == ref1.GetSize()); assert(!x.IsAProxy()); double * start = &x[0]; x.FastAssign(ref1); ASSERT(start == &x[0], "FastAssign shall never reallocate"); ASSERT(x == ref1, "FastAssign shall ... assign VLVs"); assert(x.GetSize() == ref2.GetSize()); x.FastAssign(ref2); ASSERT(start == &x[0], "FastAssign shall never reallocate"); ASSERT(x == ref2, "FastAssign shall ... assign VLVs"); // As ref4.GetSize() is different from x.GetSize(), // x.FastAssign(ref4); // is an invalid instruction: Indeed FastAssign preconditions are not met. } delete[] d; } { // Testing arithmetic operations (and rvalue references) { FloatVariableLengthVectorType v = f + f + f; ASSERT(v[0] == 3.0 && v[1] == 6.0 && v[2] == 9.0, "Chained additions failed"); } { // rvref + lv FloatVariableLengthVectorType v = (f + f) + f; ASSERT(v[0] == 3.0 && v[1] == 6.0 && v[2] == 9.0, "Chained additions failed"); } { // lv + rvref FloatVariableLengthVectorType v = f + (f + f); ASSERT(v[0] == 3.0 && v[1] == 6.0 && v[2] == 9.0, "Chained additions failed"); } { // 2xlv+lv ; rvref + rvref FloatVariableLengthVectorType v = (f + f) + (f + f); ASSERT(v[0] == 4.0 && v[1] == 8.0 && v[2] == 12.0, "Chained additions failed"); } { FloatVariableLengthVectorType v = f - f - f; ASSERT(v[0] == -1.0 && v[1] == -2.0 && v[2] == -3.0, "Chained subtractions failed"); } { // rvref - lv FloatVariableLengthVectorType v = (f - f) - f; ASSERT(v[0] == -1.0 && v[1] == -2.0 && v[2] == -3.0, "Chained subtractions failed"); } { // lv - rvref FloatVariableLengthVectorType v = f - (f - f); ASSERT(v[0] == 1.0 && v[1] == 2.0 && v[2] == 3.0, "Chained subtractions failed"); } { // 2xlv-lv ; rvref - rvref FloatVariableLengthVectorType v = (f - f) - (f - f); ASSERT(v[0] == 0.0 && v[1] == 0.0 && v[2] == 0.0, "Chained subtractions failed"); } { // c + lv FloatVariableLengthVectorType v = 2.f + f; ASSERT(v[0] == 3.0 && v[1] == 4.0 && v[2] == 5.0, "Addition with scalar failed"); } { // lv + c FloatVariableLengthVectorType v = f + 2.f; ASSERT(v[0] == 3.0 && v[1] == 4.0 && v[2] == 5.0, "Addition with scalar failed"); } { // rvref + c FloatVariableLengthVectorType v = (f + f) + 2.f; ASSERT(v[0] == 4.0 && v[1] == 6.0 && v[2] == 8.0, "Addition with scalar failed"); } { // c + rvref FloatVariableLengthVectorType v = 2.f + (f + f); ASSERT(v[0] == 4.0 && v[1] == 6.0 && v[2] == 8.0, "Addition with scalar failed"); } { // c - lv FloatVariableLengthVectorType v = 2.f - f; ASSERT(v[0] == 1.0 && v[1] == 0.0 && v[2] == -1.0, "Subtraction with scalar failed"); } { // lv - c FloatVariableLengthVectorType v = f - 2.f; ASSERT(v[0] == -1.0 && v[1] == 0.0 && v[2] == 1.0, "Subtraction with scalar failed"); } { // rvref - c FloatVariableLengthVectorType v = (f + f) - 2.f; ASSERT(v[0] == 0.0 && v[1] == 2.0 && v[2] == 4.0, "Subtraction with scalar failed"); } { // c - rvref FloatVariableLengthVectorType v = 2.f - (f + f); ASSERT(v[0] == 0.0 && v[1] == -2.0 && v[2] == -4.0, "Subtraction with scalar failed"); } { // c * lv FloatVariableLengthVectorType v = 2 * f; ASSERT(v[0] == 2.0 && v[1] == 4.0 && v[2] == 6.0, "Multiplication with scalar failed"); } { // lv * c FloatVariableLengthVectorType v = f * 2; ASSERT(v[0] == 2.0 && v[1] == 4.0 && v[2] == 6.0, "Multiplication with scalar failed"); } { // rvref * c FloatVariableLengthVectorType v = (f + f) * 2; ASSERT(v[0] == 4.0 && v[1] == 8.0 && v[2] == 12.0, "Multiplication with scalar failed"); } { // c * rvref FloatVariableLengthVectorType v = 2 * (f + f); ASSERT(v[0] == 4.0 && v[1] == 8.0 && v[2] == 12.0, "Multiplication with scalar failed"); } { // lv / c FloatVariableLengthVectorType v = f / 2; ASSERT(v[0] == 0.5 && v[1] == 1.0 && v[2] == 1.5, "Division with scalar failed"); } { // rvref / c FloatVariableLengthVectorType v = (f + f) / 2; ASSERT(v[0] == 1.0 && v[1] == 2.0 && v[2] == 3.0, "Division with scalar failed"); } } { // Testing arithmetic operations and on the fly conversions. { // f[0]=1.0; f[1] = 2.0; f[2] = 3.0; // g[0]=4.0; g[1] = 5.0; g[2] = 6.0; // g += f+1 FloatVariableLengthVectorType v = f + 2 * g; ASSERT(v[0] == 13.0 && v[1] == 18.0 && v[2] == 23.0, "On-the-fly conversion failed; v=" << v); } { DoubleVariableLengthVectorType v = f + 2 * g; ASSERT(v[0] == 13.0 && v[1] == 18.0 && v[2] == 23.0, "On-the-fly conversion failed; v=" << v); } } { // Testing empty vectors FloatVariableLengthVectorType v1; v1.Fill(0); FloatVariableLengthVectorType v2 = v1; v1 = v2; FloatVariableLengthVectorType v3, v4; v1 = 2 * v2 + (v3 - v4) / 6; v1.SetSize(0, FloatVariableLengthVectorType::DontShrinkToFit(), FloatVariableLengthVectorType::KeepOldValues()); v1.SetSize(1, FloatVariableLengthVectorType::DontShrinkToFit(), FloatVariableLengthVectorType::KeepOldValues()); } std::cout << (result == EXIT_SUCCESS ? "[PASSED]" : "[FAILED]") << std::endl; return result; }
6,885
4,640
# 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. import pytest pytest.importorskip("ethosu.vela") import tvm from tvm.relay.backend.contrib.ethosu.tir.scheduler import OperatorCompute import tvm.relay.backend.contrib.ethosu.codegen as codegen import tensorflow as tf from . import infra @pytest.mark.parametrize( "axis, ifm_shape, pool_shape", [ (1, (1, 12, 1, 2), (3, 1)), (1, (1, 12, 12, 2), (3, 3)), (2, (1, 1, 12, 2), (1, 3)), (2, (1, 12, 12, 2), (3, 3)), ], ) def test_rolling_buffer_2_layers(axis, ifm_shape, pool_shape): accel_type = "ethos-u55-256" strides = (1, 1) @tf.function def tf_model(x): padding = "VALID" pool_0 = tf.nn.max_pool(x, pool_shape, strides, padding) pool_1 = tf.nn.max_pool(pool_0, pool_shape, strides, padding) return pool_1 def _cascader(cached_func, const_dict, sch): pool_b_out = cached_func.outputs[0] pool_b_compute = OperatorCompute.from_output(pool_b_out) pool_a_out = pool_b_compute.read.op.input_tensors[0] pool_a_compute = OperatorCompute.from_output(pool_a_out) outer = pool_b_compute.split(sch, axis=axis, val=4) pool_a_compute.compute_at(sch, stage=sch[pool_b_out], axis=outer) pool_a_compute.rolling_buffer(sch) codegen.SCHEDULER = lambda: _cascader infra.compare_tvm_with_tflite(tf_model, [ifm_shape], accel_type) @pytest.mark.parametrize( "axis, ifm_shape, pool_shape", [ (1, (1, 12, 1, 2), (3, 1)), (1, (1, 12, 1, 17), (3, 1)), (1, (1, 12, 12, 2), (3, 3)), (1, (1, 12, 12, 17), (3, 3)), (2, (1, 1, 12, 2), (1, 3)), (2, (1, 1, 12, 17), (1, 3)), (2, (1, 12, 12, 2), (3, 3)), (2, (1, 12, 12, 17), (3, 3)), ], ) def test_rolling_buffer_3_layers(axis, ifm_shape, pool_shape): accel_type = "ethos-u55-256" strides = (1, 1) @tf.function def tf_model(x): padding = "VALID" pool_0 = tf.nn.max_pool(x, pool_shape, strides, padding) pool_1 = tf.nn.max_pool(pool_0, pool_shape, strides, padding) pool_2 = tf.nn.max_pool(pool_1, pool_shape, strides, padding) return pool_2 def _cascader(cached_func, const_dict, sch): pool_b_out = cached_func.outputs[0] pool_b_compute = OperatorCompute.from_output(pool_b_out) pool_a_out = pool_b_compute.read.op.input_tensors[0] pool_a_compute = OperatorCompute.from_output(pool_a_out) outer = pool_b_compute.split(sch, axis=axis, val=4) pool_a_compute.compute_at(sch, stage=sch[pool_b_out], axis=outer) pool_a_compute.rolling_buffer(sch) codegen.SCHEDULER = lambda: _cascader infra.compare_tvm_with_tflite(tf_model, [ifm_shape], accel_type) if __name__ == "__main__": pytest.main([__file__])
1,588
476
/* * acl.c - Manage the ACL (Access Control List) * * Copyright (C) 2013 - 2015, <NAME> <<EMAIL>> * * This file is part of the shadowsocks-libev. * * shadowsocks-libev 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. * * shadowsocks-libev 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 shadowsocks-libev; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. */ #include <ipset/ipset.h> #include "utils.h" static struct ip_set acl_ipv4_set; static struct ip_set acl_ipv6_set; static void parse_addr_cidr(const char *str, char *host, int *cidr) { int ret = -1, n = 0; char *pch; pch = strchr(str, '/'); while (pch != NULL) { n++; ret = pch - str; pch = strchr(pch + 1, '/'); } if (ret == -1) { strcpy(host, str); *cidr = -1; } else { memcpy(host, str, ret); host[ret] = '\0'; *cidr = atoi(str + ret + 1); } } int init_acl(const char *path) { // initialize ipset ipset_init_library(); ipset_init(&acl_ipv4_set); ipset_init(&acl_ipv6_set); FILE *f = fopen(path, "r"); if (f == NULL) { LOGE("Invalid acl path."); return -1; } char line[256]; while (!feof(f)) { if (fgets(line, 256, f)) { // Trim the newline int len = strlen(line); if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } char host[256]; int cidr; parse_addr_cidr(line, host, &cidr); struct cork_ip addr; int err = cork_ip_init(&addr, host); if (!err) { if (addr.version == 4) { if (cidr >= 0) { ipset_ipv4_add_network(&acl_ipv4_set, &(addr.ip.v4), cidr); } else { ipset_ipv4_add(&acl_ipv4_set, &(addr.ip.v4)); } } else if (addr.version == 6) { if (cidr >= 0) { ipset_ipv6_add_network(&acl_ipv6_set, &(addr.ip.v6), cidr); } else { ipset_ipv6_add(&acl_ipv6_set, &(addr.ip.v6)); } } } } } fclose(f); return 0; } void free_acl(void) { ipset_done(&acl_ipv4_set); ipset_done(&acl_ipv6_set); } int acl_contains_ip(const char * host) { struct cork_ip addr; int err = cork_ip_init(&addr, host); if (err) { return 0; } if (addr.version == 4) { return ipset_contains_ipv4(&acl_ipv4_set, &(addr.ip.v4)); } else if (addr.version == 6) { return ipset_contains_ipv6(&acl_ipv6_set, &(addr.ip.v6)); } return 0; }
1,651
1,766
<reponame>aalonsog/licode #include <algorithm> #include "rtp/RtcpNackGenerator.h" #include "rtp/RtpUtils.h" namespace erizo { DEFINE_LOGGER(RtcpNackGenerator, "rtp.RtcpNackGenerator"); static const int kMaxRetransmits = 2; static const int kMaxNacks = 150; static const int kMinNackDelayMs = 20; static const int kNackCommonHeaderLengthRtcp = kNackCommonHeaderLengthBytes/4 - 1; RtcpNackGenerator::RtcpNackGenerator(uint32_t ssrc, std::shared_ptr<Clock> the_clock) : initialized_{false}, highest_seq_num_{0}, ssrc_{ssrc}, clock_{the_clock} {} bool RtcpNackGenerator::handleRtpPacket(std::shared_ptr<DataPacket> packet) { if (packet->type != VIDEO_PACKET) { return false; } RtpHeader *head = reinterpret_cast<RtpHeader*>(packet->data); uint16_t seq_num = head->getSeqNumber(); if (head->getSSRC() != ssrc_) { ELOG_DEBUG("message: handleRtpPacket Unknown SSRC, ssrc: %u", head->getSSRC()); return false; } if (!initialized_) { highest_seq_num_ = seq_num; initialized_ = true; return false; } if (seq_num == highest_seq_num_) { return false; } // TODO(pedro) Consider clearing the nack list if this is a keyframe if (RtpUtils::sequenceNumberLessThan(seq_num, highest_seq_num_)) { ELOG_DEBUG("message: packet out of order, ssrc: %u, seq_num: %u, highest_seq_num: %u", seq_num, highest_seq_num_, ssrc_); // Look for it in nack list, remove it if its there auto nack_info = std::find_if(nack_info_list_.begin(), nack_info_list_.end(), [seq_num](NackInfo& current_nack) { return (current_nack.seq_num == seq_num); }); if (nack_info != nack_info_list_.end()) { ELOG_DEBUG("message: Recovered Packet %u", seq_num); nack_info_list_.erase(nack_info); } return false; } bool available_nacks = addNacks(seq_num); highest_seq_num_ = seq_num; return available_nacks; } bool RtcpNackGenerator::addNacks(uint16_t seq_num) { for (uint16_t current_seq_num = highest_seq_num_ + 1; current_seq_num != seq_num; current_seq_num++) { ELOG_DEBUG("message: Inserting a new Nack in list, ssrc: %u, seq_num: %u", ssrc_, current_seq_num); nack_info_list_.push_back(NackInfo{current_seq_num}); } while (nack_info_list_.size() > kMaxNacks) { nack_info_list_.erase(nack_info_list_.end() - 1); } return !nack_info_list_.empty(); } bool RtcpNackGenerator::addNackPacketToRr(std::shared_ptr<DataPacket> rr_packet) { // Goes through the list adds blocks of 16 in compound packets (adds more PID/BLP blocks) max is 10 blocks // Only does it if it's time (> 100 ms since last NACK) std::vector <NackBlock> nack_vector; ELOG_DEBUG("message: Adding nacks to RR, nack_info_list_.size(): %lu", nack_info_list_.size()); uint64_t now_ms = ClockUtils::timePointToMs(clock_->now()); for (uint16_t index = 0; index < nack_info_list_.size(); index++) { NackInfo& base_nack_info = nack_info_list_[index]; if (!isTimeToRetransmit(base_nack_info, now_ms)) { ELOG_DEBUG("It's not time to retransmit %lu, now %lu, diff %lu", base_nack_info.sent_time, now_ms, now_ms - base_nack_info.sent_time); continue; } if (base_nack_info.retransmits >= kMaxRetransmits) { ELOG_DEBUG("message: Removing Nack in list too many retransmits, ssrc: %u, seq_num: %u", ssrc_, base_nack_info.seq_num); nack_info_list_.erase(nack_info_list_.begin() + index); index--; // Items are moved in the list so the next element has the current index continue; } ELOG_DEBUG("message: PID, seq_num %u", base_nack_info.seq_num); uint16_t pid = base_nack_info.seq_num; uint16_t blp = 0; base_nack_info.sent_time = now_ms; base_nack_info.retransmits++; while (index + 1u < nack_info_list_.size()) { NackInfo& blp_nack_info = nack_info_list_[index + 1]; uint16_t distance = blp_nack_info.seq_num - pid -1; if (distance <= 15) { if (!isTimeToRetransmit(blp_nack_info, now_ms)) { index++; continue; } if (blp_nack_info.retransmits >= kMaxRetransmits) { ELOG_DEBUG("message: Removing Nack in list too many retransmits, ssrc: %u, seq_num: %u", ssrc_, blp_nack_info.seq_num); nack_info_list_.erase(nack_info_list_.begin() + index + 1); continue; } ELOG_DEBUG("message: Adding Nack to BLP, seq_num: %u", blp_nack_info.seq_num); blp |= (1 << distance); blp_nack_info.sent_time = now_ms; blp_nack_info.retransmits++; index++; } else { break; } } NackBlock block; block.setNackPid(pid); block.setNackBlp(blp); nack_vector.push_back(block); } if (nack_vector.size() == 0) { return false; } char* buffer = rr_packet->data; buffer += rr_packet->length; RtcpHeader nack_packet; nack_packet.setPacketType(RTCP_RTP_Feedback_PT); nack_packet.setBlockCount(1); nack_packet.setSSRC(ssrc_); nack_packet.setSourceSSRC(ssrc_); nack_packet.setLength(kNackCommonHeaderLengthRtcp + nack_vector.size()); memcpy(buffer, reinterpret_cast<char *>(&nack_packet), kNackCommonHeaderLengthBytes); buffer += kNackCommonHeaderLengthBytes; memcpy(buffer, &nack_vector[0], nack_vector.size()*4); int nack_length = (nack_packet.getLength()+1)*4; rr_packet->length += nack_length; return true; } bool RtcpNackGenerator::isTimeToRetransmit(const NackInfo& nack_info, uint64_t current_time_ms) { return (nack_info.sent_time == 0 || (current_time_ms - nack_info.sent_time) > kMinNackDelayMs); } } // namespace erizo
2,424
488
#include "main.h" extern "C" { EXPORT btPointCollector* btPointCollector_new(); EXPORT btScalar btPointCollector_getDistance(btPointCollector* obj); EXPORT bool btPointCollector_getHasResult(btPointCollector* obj); EXPORT void btPointCollector_getNormalOnBInWorld(btPointCollector* obj, btScalar* value); EXPORT void btPointCollector_getPointInWorld(btPointCollector* obj, btScalar* value); EXPORT void btPointCollector_setDistance(btPointCollector* obj, btScalar value); EXPORT void btPointCollector_setHasResult(btPointCollector* obj, bool value); EXPORT void btPointCollector_setNormalOnBInWorld(btPointCollector* obj, const btScalar* value); EXPORT void btPointCollector_setPointInWorld(btPointCollector* obj, const btScalar* value); }
267
515
<reponame>paulo-e/caelum-stella<filename>stella-gateway-formas-pagamento/src/main/java/br/com/caelum/stella/gateway/redecard/RedecardSolicitacaoAutorizacaoPagamento.java package br.com.caelum.stella.gateway.redecard; import br.com.caelum.stella.gateway.core.IntegrationHandler; /** * Classe responsável por criar o objeto, cujo os atributos devem ser enviados * via formulario para o master. * * @author <NAME> * */ public class RedecardSolicitacaoAutorizacaoPagamento implements IntegrationHandler<RedecardDadosAutorizacaoPagamento> { private RedecardCheckout checkout; private String ipComprador; private RedecardDadosConfiguracao dadosConfiguracao; public RedecardSolicitacaoAutorizacaoPagamento(RedecardCheckout checkout, String ipComprador, RedecardDadosConfiguracao dadosConfiguracao) { super(); this.checkout = checkout; this.ipComprador = ipComprador; this.dadosConfiguracao = dadosConfiguracao; } public RedecardSolicitacaoAutorizacaoPagamento(RedecardCheckout checkout, String ipComprador) { this(checkout, ipComprador, new RedecardDadosConfiguracao()); } /** * Retorna um objeto contendo tudo que precisa ser enviado para o ambiente * da redecard. O post para a url tem que ser feito direto via browser. * * @return */ public RedecardDadosAutorizacaoPagamento handle() { // TODO Auto-generated method stub return new RedecardDadosAutorizacaoPagamento(checkout, new RedecardDadosFiliacao(dadosConfiguracao.getNumeroFiliacaoFornecedor(), dadosConfiguracao.getNumeroFiliacaoDistribuidor()), CodVer .calculaCodigoVerificacao(String.valueOf(dadosConfiguracao.getNumeroFiliacaoFornecedor()), checkout .getTotalComDuasCasasDecimais().toString(), ipComprador),dadosConfiguracao.getUrlRetornoTransacao(), null, null); } }
765
356
<gh_stars>100-1000 /* Stock Span Problem ======================================= You are given the price of a stock for N consecutive days and are required to find the span of stock's price on ith day. The span of a stock's price on a given day i, is the maximum consecutive days before the (i+1)th day, for which the stock's price is less than equal to that on the ith day. The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days. The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. ======================================== */ #include<iostream> #include<stack> using namespace std; int main() { // n : Total number of days int n; cin >> n; int price[n]; int span[n]; // Input price for n days for (int i = 0; i < n; i++) { cin >> price[i]; } // Stack for keeping track of span of largest element till now stack<pair<int, int>> s; // Push first element in the stack s.push({1, price[0]}); // Span for first day will always be 1 span[0] = 1; // Looping through rest of the days for (int i = 1; i < n; i++) { // Initally the curr span of a day will be 1, i.e, itself int currSpan = 1; int currPrice = price[i]; // Taking the topmost element in the stack // p : Temporary Variable used to store topmost element of Stack 's'. auto p = s.top(); int topSpan = p.first; int topPrice = p.second; // While we have elements in the stack and currPrice is greater than equal to topPrice // keeping popping out elements and update the currSpan while (s.size() && topPrice <= currPrice) { // Update currSpan currSpan += topSpan; // Pop out the topmost element as its price was less than currPrice s.pop(); // Update top element after popping if (s.size()) { p = s.top(); topSpan = p.first; topPrice = p.second; } else { // Stack is empty break; } } // Finally update ans span[i] = currSpan; // Push curr element into the stack s.push({currSpan, currPrice}); } // Print ans for (int i = 0; i < n; i++) { cout << span[i] << " "; } } /* ------------------------ Sample Input : 5 30 35 40 38 35 Sample Output : 1 2 3 1 1 ------------------------ Sample Input: 7 100 80 60 70 60 75 85 Smaple Output: 1 1 1 2 1 4 6 Explanation: Traversing the given input span for 100 will be 1, 80 is smaller than 100 so the span is 1, 60 is smaller than 80 so the span is 1, 70 is greater than 60 so the span is 2 and so on. Hence the output will be 1 1 1 2 1 4 6. ------------------------ Time Complexity: O(n) Space Complexity: O(n) */
1,203
2,308
/** * Copyright 2016 vip.com. * <p> * 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. * </p> **/ package com.vip.saturn.job.console; import java.io.IOException; import java.io.UnsupportedEncodingException; import com.alibaba.fastjson.JSONObject; import com.vip.saturn.job.console.springboot.SaturnConsoleApp; import org.junit.AfterClass; import org.junit.BeforeClass; import org.springframework.test.web.servlet.MvcResult; public abstract class AbstractSaturnConsoleTest { @BeforeClass public static void beforeClass() throws Exception { System.setProperty("db.profiles.active", "h2"); System.setProperty("authentication.enabled", "false"); SaturnConsoleApp.startEmbeddedDb(); } @AfterClass public static void afterClass() throws IOException, InterruptedException { SaturnConsoleApp.stopEmbeddedDb(); } protected String fetchErrorMessage(MvcResult result) throws UnsupportedEncodingException { return JSONObject.parseObject(result.getResponse().getContentAsString()).getString("message"); } }
432
3,227
// Copyright (c) 2020 GeometryFactory SARL (France). // 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_TANGENT_WEIGHTS_H #define CGAL_TANGENT_WEIGHTS_H // Internal includes. #include <CGAL/Weights/internal/utils.h> namespace CGAL { namespace Weights { /// \cond SKIP_IN_MANUAL namespace tangent_ns { template<typename FT> FT half_angle_tangent(const FT r, const FT d, const FT A, const FT D) { FT t = FT(0); const FT P = r * d + D; CGAL_precondition(P != FT(0)); if (P != FT(0)) { const FT inv = FT(2) / P; t = A * inv; } return t; } template<typename FT> FT half_weight(const FT t, const FT r) { FT w = FT(0); CGAL_precondition(r != FT(0)); if (r != FT(0)) { const FT inv = FT(2) / r; w = t * inv; } return w; } template<typename FT> FT weight(const FT t1, const FT t2, const FT r) { FT w = FT(0); CGAL_precondition(r != FT(0)); if (r != FT(0)) { const FT inv = FT(2) / r; w = (t1 + t2) * inv; } return w; } template<typename FT> FT weight( const FT d1, const FT r, const FT d2, const FT A1, const FT A2, const FT D1, const FT D2) { const FT P1 = d1 * r + D1; const FT P2 = d2 * r + D2; FT w = FT(0); CGAL_precondition(P1 != FT(0) && P2 != FT(0)); if (P1 != FT(0) && P2 != FT(0)) { const FT inv1 = FT(2) / P1; const FT inv2 = FT(2) / P2; const FT t1 = A1 * inv1; const FT t2 = A2 * inv2; w = weight(t1, t2, r); } return w; } // This is positive case only. // This version is based on the positive area. // This version is more precise for all positive cases. template<typename GeomTraits> typename GeomTraits::FT tangent_weight_v1( const typename GeomTraits::Point_3& t, const typename GeomTraits::Point_3& r, const typename GeomTraits::Point_3& p, const typename GeomTraits::Point_3& q, const GeomTraits& traits) { using FT = typename GeomTraits::FT; const auto dot_product_3 = traits.compute_scalar_product_3_object(); const auto construct_vector_3 = traits.construct_vector_3_object(); const auto v1 = construct_vector_3(q, t); const auto v2 = construct_vector_3(q, r); const auto v3 = construct_vector_3(q, p); const FT l1 = internal::length_3(traits, v1); const FT l2 = internal::length_3(traits, v2); const FT l3 = internal::length_3(traits, v3); const FT A1 = internal::positive_area_3(traits, r, q, t); const FT A2 = internal::positive_area_3(traits, p, q, r); const FT D1 = dot_product_3(v1, v2); const FT D2 = dot_product_3(v2, v3); return weight(l1, l2, l3, A1, A2, D1, D2); } // This version handles both positive and negative cases. // However, it is less precise. template<typename GeomTraits> typename GeomTraits::FT tangent_weight_v2( const typename GeomTraits::Point_3& t, const typename GeomTraits::Point_3& r, const typename GeomTraits::Point_3& p, const typename GeomTraits::Point_3& q, const GeomTraits& traits) { using FT = typename GeomTraits::FT; const auto construct_vector_3 = traits.construct_vector_3_object(); auto v1 = construct_vector_3(q, t); auto v2 = construct_vector_3(q, r); auto v3 = construct_vector_3(q, p); const FT l2 = internal::length_3(traits, v2); internal::normalize_3(traits, v1); internal::normalize_3(traits, v2); internal::normalize_3(traits, v3); const double ha_rad_1 = internal::angle_3(traits, v1, v2) / 2.0; const double ha_rad_2 = internal::angle_3(traits, v2, v3) / 2.0; const FT t1 = static_cast<FT>(std::tan(ha_rad_1)); const FT t2 = static_cast<FT>(std::tan(ha_rad_2)); return weight(t1, t2, l2); } } /// \endcond /*! \ingroup PkgWeightsRefTangentWeights \brief computes the tangent of the half angle. This function computes the tangent of the half angle using the precomputed distance, area, and dot product values. The returned value is \f$\frac{2\textbf{A}}{\textbf{d}\textbf{l} + \textbf{D}}\f$. \tparam FT a model of `FieldNumberType` \param d the distance value \param l the distance value \param A the area value \param D the dot product value \pre (d * l + D) != 0 \sa `half_tangent_weight()` */ template<typename FT> FT tangent_half_angle(const FT d, const FT l, const FT A, const FT D) { return tangent_ns::half_angle_tangent(d, l, A, D); } /*! \ingroup PkgWeightsRefTangentWeights \brief computes the half value of the tangent weight. This function constructs the half of the tangent weight using the precomputed half angle tangent and distance values. The returned value is \f$\frac{2\textbf{tan05}}{\textbf{d}}\f$. \tparam FT a model of `FieldNumberType` \param tan05 the half angle tangent value \param d the distance value \pre d != 0 \sa `tangent_half_angle()` \sa `tangent_weight()` */ template<typename FT> FT half_tangent_weight(const FT tan05, const FT d) { return tangent_ns::half_weight(tan05, d); } /*! \ingroup PkgWeightsRefTangentWeights \brief computes the half value of the tangent weight. This function constructs the half of the tangent weight using the precomputed distance, area, and dot product values. The returned value is \f$\frac{2\textbf{t}}{\textbf{d}}\f$ where \f$\textbf{t} = \frac{2\textbf{A}}{\textbf{d}\textbf{l} + \textbf{D}}\f$. \tparam FT a model of `FieldNumberType` \param d the distance value \param l the distance value \param A the area value \param D the dot product value \pre (d * l + D) != 0 && d != 0 \sa `tangent_weight()` */ template<typename FT> FT half_tangent_weight(const FT d, const FT l, const FT A, const FT D) { const FT tan05 = tangent_half_angle(d, l, A, D); return half_tangent_weight(tan05, d); } #if defined(DOXYGEN_RUNNING) /*! \ingroup PkgWeightsRefTangentWeights \brief computes the tangent weight in 2D at `q` using the points `p0`, `p1`, and `p2`, given a traits class `traits` with geometric objects, predicates, and constructions. */ template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const typename GeomTraits::Point_2& p0, const typename GeomTraits::Point_2& p1, const typename GeomTraits::Point_2& p2, const typename GeomTraits::Point_2& q, const GeomTraits& traits) { } /*! \ingroup PkgWeightsRefTangentWeights \brief computes the tangent weight in 3D at `q` using the points `p0`, `p1`, and `p2`, given a traits class `traits` with geometric objects, predicates, and constructions. */ template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const typename GeomTraits::Point_3& p0, const typename GeomTraits::Point_3& p1, const typename GeomTraits::Point_3& p2, const typename GeomTraits::Point_3& q, const GeomTraits& traits) { } /*! \ingroup PkgWeightsRefTangentWeights \brief computes the tangent weight in 2D at `q` using the points `p0`, `p1`, and `p2` which are parameterized by a `Kernel` K. */ template<typename K> typename K::FT tangent_weight( const CGAL::Point_2<K>& p0, const CGAL::Point_2<K>& p1, const CGAL::Point_2<K>& p2, const CGAL::Point_2<K>& q) { } /*! \ingroup PkgWeightsRefTangentWeights \brief computes the tangent weight in 3D at `q` using the points `p0`, `p1`, and `p2` which are parameterized by a `Kernel` K. */ template<typename K> typename K::FT tangent_weight( const CGAL::Point_3<K>& p0, const CGAL::Point_3<K>& p1, const CGAL::Point_3<K>& p2, const CGAL::Point_3<K>& q) { } #endif // DOXYGEN_RUNNING /// \cond SKIP_IN_MANUAL template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const typename GeomTraits::Point_2& t, const typename GeomTraits::Point_2& r, const typename GeomTraits::Point_2& p, const typename GeomTraits::Point_2& q, const GeomTraits& traits) { using FT = typename GeomTraits::FT; const auto dot_product_2 = traits.compute_scalar_product_2_object(); const auto construct_vector_2 = traits.construct_vector_2_object(); const auto v1 = construct_vector_2(q, t); const auto v2 = construct_vector_2(q, r); const auto v3 = construct_vector_2(q, p); const FT l1 = internal::length_2(traits, v1); const FT l2 = internal::length_2(traits, v2); const FT l3 = internal::length_2(traits, v3); const FT A1 = internal::area_2(traits, r, q, t); const FT A2 = internal::area_2(traits, p, q, r); const FT D1 = dot_product_2(v1, v2); const FT D2 = dot_product_2(v2, v3); return tangent_ns::weight( l1, l2, l3, A1, A2, D1, D2); } template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const CGAL::Point_2<GeomTraits>& t, const CGAL::Point_2<GeomTraits>& r, const CGAL::Point_2<GeomTraits>& p, const CGAL::Point_2<GeomTraits>& q) { const GeomTraits traits; return tangent_weight(t, r, p, q, traits); } template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const typename GeomTraits::Point_3& t, const typename GeomTraits::Point_3& r, const typename GeomTraits::Point_3& p, const typename GeomTraits::Point_3& q, const GeomTraits& traits) { // return tangent_ns::tangent_weight_v1(t, r, p, q, traits); return tangent_ns::tangent_weight_v2(t, r, p, q, traits); } template<typename GeomTraits> typename GeomTraits::FT tangent_weight( const CGAL::Point_3<GeomTraits>& t, const CGAL::Point_3<GeomTraits>& r, const CGAL::Point_3<GeomTraits>& p, const CGAL::Point_3<GeomTraits>& q) { const GeomTraits traits; return tangent_weight(t, r, p, q, traits); } // Undocumented tangent weight class. // Its constructor takes a polygon mesh and a vertex to point map // and its operator() is defined based on the halfedge_descriptor only. // This version is currently used in: // Surface_mesh_parameterizer -> Iterative_authalic_parameterizer_3.h template< typename PolygonMesh, typename VertexPointMap = typename boost::property_map<PolygonMesh, CGAL::vertex_point_t>::type> class Edge_tangent_weight { using GeomTraits = typename CGAL::Kernel_traits< typename boost::property_traits<VertexPointMap>::value_type>::type; using FT = typename GeomTraits::FT; const PolygonMesh& m_pmesh; const VertexPointMap m_pmap; const GeomTraits m_traits; public: using vertex_descriptor = typename boost::graph_traits<PolygonMesh>::vertex_descriptor; using halfedge_descriptor = typename boost::graph_traits<PolygonMesh>::halfedge_descriptor; Edge_tangent_weight(const PolygonMesh& pmesh, const VertexPointMap pmap) : m_pmesh(pmesh), m_pmap(pmap), m_traits() { } FT operator()(const halfedge_descriptor he) const { FT weight = FT(0); if (is_border_edge(he, m_pmesh)) { const auto h1 = next(he, m_pmesh); const auto v0 = target(he, m_pmesh); const auto v1 = source(he, m_pmesh); const auto v2 = target(h1, m_pmesh); const auto& p0 = get(m_pmap, v0); const auto& p1 = get(m_pmap, v1); const auto& p2 = get(m_pmap, v2); weight = internal::tangent_3(m_traits, p0, p2, p1); } else { const auto h1 = next(he, m_pmesh); const auto h2 = prev(opposite(he, m_pmesh), m_pmesh); const auto v0 = target(he, m_pmesh); const auto v1 = source(he, m_pmesh); const auto v2 = target(h1, m_pmesh); const auto v3 = source(h2, m_pmesh); const auto& p0 = get(m_pmap, v0); const auto& p1 = get(m_pmap, v1); const auto& p2 = get(m_pmap, v2); const auto& p3 = get(m_pmap, v3); weight = tangent_weight(p2, p1, p3, p0) / FT(2); } return weight; } }; // Undocumented tangent weight class. // Its constructor takes three points either in 2D or 3D. // This version is currently used in: // Surface_mesh_parameterizer -> MVC_post_processor_3.h // Surface_mesh_parameterizer -> Orbifold_Tutte_parameterizer_3.h template<typename FT> class Tangent_weight { FT m_d_r, m_d_p, m_w_base; public: template<typename GeomTraits> Tangent_weight( const CGAL::Point_2<GeomTraits>& p, const CGAL::Point_2<GeomTraits>& q, const CGAL::Point_2<GeomTraits>& r) { const GeomTraits traits; const auto scalar_product_2 = traits.compute_scalar_product_2_object(); const auto construct_vector_2 = traits.construct_vector_2_object(); m_d_r = internal::distance_2(traits, q, r); CGAL_assertion(m_d_r != FT(0)); // two points are identical! m_d_p = internal::distance_2(traits, q, p); CGAL_assertion(m_d_p != FT(0)); // two points are identical! const auto v1 = construct_vector_2(q, r); const auto v2 = construct_vector_2(q, p); const auto A = internal::area_2(traits, p, q, r); CGAL_assertion(A != FT(0)); // three points are identical! const auto S = scalar_product_2(v1, v2); m_w_base = -tangent_half_angle(m_d_r, m_d_p, A, S); } template<typename GeomTraits> Tangent_weight( const CGAL::Point_3<GeomTraits>& p, const CGAL::Point_3<GeomTraits>& q, const CGAL::Point_3<GeomTraits>& r) { const GeomTraits traits; const auto scalar_product_3 = traits.compute_scalar_product_3_object(); const auto construct_vector_3 = traits.construct_vector_3_object(); m_d_r = internal::distance_3(traits, q, r); CGAL_assertion(m_d_r != FT(0)); // two points are identical! m_d_p = internal::distance_3(traits, q, p); CGAL_assertion(m_d_p != FT(0)); // two points are identical! const auto v1 = construct_vector_3(q, r); const auto v2 = construct_vector_3(q, p); const auto A = internal::positive_area_3(traits, p, q, r); CGAL_assertion(A != FT(0)); // three points are identical! const auto S = scalar_product_3(v1, v2); m_w_base = -tangent_half_angle(m_d_r, m_d_p, A, S); } FT get_w_r() const { return half_tangent_weight(m_w_base, m_d_r) / FT(2); } FT get_w_p() const { return half_tangent_weight(m_w_base, m_d_p) / FT(2); } }; /// \endcond } // namespace Weights } // namespace CGAL #endif // CGAL_TANGENT_WEIGHTS_H
6,537
317
<filename>library/src/main/java/com/seatgeek/placesautocomplete/model/DateTimePair.java package com.seatgeek.placesautocomplete.model; public final class DateTimePair { /** * "a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday" */ public final String day; /** * may contain a time of day in 24-hour hhmm format. Values are in the range 0000–2359. The time will be reported in the place’s time zone. */ public final String time; public DateTimePair(final String day, final String time) { this.day = day; this.time = time; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DateTimePair)) return false; DateTimePair that = (DateTimePair) o; if (day != null ? !day.equals(that.day) : that.day != null) return false; if (time != null ? !time.equals(that.time) : that.time != null) return false; return true; } @Override public int hashCode() { int result = day != null ? day.hashCode() : 0; result = 31 * result + (time != null ? time.hashCode() : 0); return result; } }
473
1,738
<filename>dev/Code/Sandbox/Plugins/MaglevControlPanel/DetailWidget/FocusButtonWidget.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "FocusButtonWidget.h" #include <DetailWidget/FocusButtonWidget.moc> FocusButtonWidget::FocusButtonWidget() : QPushButton{} , m_numFocusGains{0} {} FocusButtonWidget::FocusButtonWidget(const QString& title) : QPushButton{title} , m_numFocusGains{0} {} void FocusButtonWidget::enterEvent(QEvent* event) { HandleGainFocus(); QPushButton::enterEvent(event); } void FocusButtonWidget::leaveEvent(QEvent* event) { HandleLoseFocus(); QPushButton::leaveEvent(event); } void FocusButtonWidget::focusInEvent(QFocusEvent* event) { HandleGainFocus(); QPushButton::focusInEvent(event); } void FocusButtonWidget::focusOutEvent(QFocusEvent* event) { HandleLoseFocus(); QPushButton::focusOutEvent(event); } void FocusButtonWidget::HandleGainFocus() { ++m_numFocusGains; if (m_numFocusGains == 1) // First focus { FocusGained(); } } void FocusButtonWidget::HandleLoseFocus() { --m_numFocusGains; if (m_numFocusGains == 0) // No sources of focus (e.g., mouse, keyboard) remain { FocusLost(); } }
586
977
<gh_stars>100-1000 #pragma once #include "Models/Model.hpp" namespace acid { /** * @brief Resource that represents a cube model. */ class ACID_EXPORT CubeModel : public Model::Registrar<CubeModel> { inline static const bool Registered = Register("cube"); public: /** * Creates a new cube model, or finds one with the same values. * @param node The node to decode values from. * @return The cube model with the requested values. */ static std::shared_ptr<CubeModel> Create(const Node &node); /** * Creates a new cube model, or finds one with the same values. * @param extents The size (width, height, depth) to load from. * @return The cube model with the requested values. */ static std::shared_ptr<CubeModel> Create(const Vector3f &extents = Vector3f(1.0f)); /** * Creates a new cube model. * @param extents The size (width, height, depth) to load from. * @param load If this resource will be loaded immediately, otherwise {@link ModelCube#Load} can be called later. */ explicit CubeModel(const Vector3f &extents = Vector3f(1.0f), bool load = true); friend const Node &operator>>(const Node &node, CubeModel &model); friend Node &operator<<(Node &node, const CubeModel &model); private: void Load(); Vector3f extents; }; }
396
314
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "CDStructures.h" #import <DVTKit/DVTTextAnnotation.h> @class NSImage, NSString; @interface DVTMessageBubbleAnnotation : DVTTextAnnotation { NSString *_messageBubbleText; NSImage *_messageBubbleIcon; BOOL _miniaturized; BOOL _wantsPreferredSizeAndPosition; BOOL _wantsFlatStyle; unsigned long long _messageBubbleTextAlignment; NSString *_messageBubbleToolTipText; } @property BOOL wantsFlatStyle; // @synthesize wantsFlatStyle=_wantsFlatStyle; @property BOOL wantsPreferredSizeAndPosition; // @synthesize wantsPreferredSizeAndPosition=_wantsPreferredSizeAndPosition; @property(copy, nonatomic) NSString *messageBubbleToolTipText; // @synthesize messageBubbleToolTipText=_messageBubbleToolTipText; @property(retain, nonatomic) NSImage *messageBubbleIcon; // @synthesize messageBubbleIcon=_messageBubbleIcon; @property unsigned long long messageBubbleTextAlignment; // @synthesize messageBubbleTextAlignment=_messageBubbleTextAlignment; @property(copy, nonatomic) NSString *messageBubbleText; // @synthesize messageBubbleText=_messageBubbleText; @property(nonatomic, getter=isMiniaturized) BOOL miniaturized; // @synthesize miniaturized=_miniaturized; - (id)annotationDisplayDescription; @property(retain) id delegate; - (void)fontAndColorThemeChanged:(id)arg1; - (void)invalidateDisplayAndLayoutIfNeeded:(BOOL)arg1; - (void)setNeedsInvalidate; - (id)currentStateInTextView:(id)arg1; - (BOOL)drawsHighlightedRanges; - (void)drawLineHighlightInRect:(struct CGRect)arg1 textView:(id)arg2; - (BOOL)drawsLineHighlight; - (struct CGRect)sidebarMarkerRectForFirstLineRect:(struct CGRect)arg1; - (double)preferredWidthForAvailableWidth:(double)arg1; - (void)setVisible:(BOOL)arg1; - (BOOL)wantsMergeAnnotations; @property int messageBubbleStackPolicy; - (id)init; @end
697
2,542
<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace HttpGateway { class RequestMessageContext::SendResponseAsyncOperation : public Common::AsyncOperation { DENY_COPY(SendResponseAsyncOperation); public: SendResponseAsyncOperation( Common::ErrorCode operationStatus, Common::ByteBufferUPtr bodyUPtr, RequestMessageContext const & messageContext, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) : Common::AsyncOperation(callback, parent) , bodyUPtr_(std::move(bodyUPtr)) , operationStatus_(operationStatus) , messageContext_(messageContext) , statusCode_(0) { } SendResponseAsyncOperation( USHORT statusCode, std::wstring const& statusDescription, Common::ByteBufferUPtr bodyUPtr, RequestMessageContext const & messageContext, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) : Common::AsyncOperation(callback, parent) , bodyUPtr_(std::move(bodyUPtr)) , statusCode_(statusCode) , statusDescription_(statusDescription) , messageContext_(messageContext) { } static Common::ErrorCode End(__in Common::AsyncOperationSPtr const & asyncOperation); protected: void OnStart(Common::AsyncOperationSPtr const& thisSPtr); void OnCancel(); private: RequestMessageContext const & messageContext_; Common::AsyncOperationSPtr thisSPtr_; Common::ByteBufferUPtr bodyUPtr_; Common::ErrorCode operationStatus_; USHORT statusCode_; std::wstring statusDescription_; }; }
818
3,428
{"id":"00247","group":"easy-ham-2","checksum":{"type":"MD5","value":"50ea609a623c12f75df32997a35b45cb"},"text":"From <EMAIL> Tue Aug 6 11:52:20 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 5FC7B441E2\n\tfor <jm@localhost>; Tue, 6 Aug 2002 06:48:17 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 06 Aug 2002 11:48:17 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [172.16.58.35]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g73EHtv15816 for\n <<EMAIL>>; Sat, 3 Aug 2002 15:17:55 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id PAA00866; Sat, 3 Aug 2002 15:16:05 +0100\nReceived: from claymore.diva.ie (diva.ie [195.218.115.17] (may be forged))\n by lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id PAA00813 for\n <<EMAIL>>; Sat, 3 Aug 2002 15:15:58 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host diva.ie [195.218.115.17]\n (may be forged) claimed to be claymore.diva.ie\nReceived: from cunniffe.net (ts08-118.dublin.indigo.ie [194.125.205.245])\n by claymore.diva.ie (8.9.3/8.9.3) with ESMTP id PAA05178 for\n <<EMAIL>>; Sat, 3 Aug 2002 15:15:55 +0100\nMessage-Id: <<EMAIL>>\nDate: Sat, 03 Aug 2002 15:15:24 +0100\nFrom: <NAME> <<EMAIL>>\nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.0.0)\n Gecko/20020530\nX-Accept-Language: en-us, en\nMIME-Version: 1.0\nTo: ilug <<EMAIL>>\nSubject: Re: [ILUG] Network problems\nReferences: <1028383169.22<EMAIL>>\nContent-Type: text/plain; charset=ISO-8859-15; format=flowed\nContent-Transfer-Encoding: 7bit\nSender: ilug-admin<EMAIL>\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.<EMAIL>.ie>\nX-Beenthere: <EMAIL>\n\n<NAME> wrote:\n> Hi guys,\n\n<schnip>\n\n> there is an option in there for something called hisax, but whatever\n> that is, the machine doesn't have one.\n\nHisax is one of the ISDN modules : doesn't apply at all in this\ncase and won't affect your system.\n\nCan't really help with the rest, soz.\n\nRegards,\n\nVin\n\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"}
1,047
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Séailles","circ":"2ème circonscription","dpt":"Gers","inscrits":42,"abs":13,"votants":29,"blancs":4,"nuls":4,"exp":21,"res":[{"nuance":"SOC","nom":"<NAME>","voix":14},{"nuance":"REM","nom":"<NAME>","voix":7}]}
109
665
# Trinket IO demo - analog output import board from analogio import AnalogOut aout = AnalogOut(board.D1) while True: # Count up from 0 to 65535, with 64 increment # which ends up corresponding to the DAC's 10-bit range for i in range(0, 65535, 64): aout.value = i
102
4,036
int printf(const char *format, ...); void test1() { long l; void *ptr; printf("%ld\n", l); // GOOD printf("%d\n", l); // BAD printf("%p\n", ptr); // GOOD printf("%d\n", ptr); // BAD printf("%u\n", ptr); // BAD printf("%x\n", ptr); // BAD }
111
343
<filename>spring-cloud-alibaba-seata/seata-provider/seata-provider-order-api/src/main/java/com/funtl/spring/cloud/alibaba/seata/service/api/TbOrderService.java<gh_stars>100-1000 package com.funtl.spring.cloud.alibaba.seata.service.api; import com.funtl.spring.cloud.alibaba.seata.domain.TbOrder; public interface TbOrderService { void insert(TbOrder order); }
141
1,543
<gh_stars>1000+ package com.vladmihalcea.hibernate.type.basic.internal; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; import java.time.Instant; import java.time.LocalDate; import java.time.MonthDay; import java.time.ZoneId; import java.util.Date; import java.util.Objects; /** * @author <NAME> (<EMAIL>) */ public class MonthDayTypeDescriptor extends AbstractTypeDescriptor<MonthDay> { public static final MonthDayTypeDescriptor INSTANCE = new MonthDayTypeDescriptor(); protected MonthDayTypeDescriptor() { super(MonthDay.class); } @Override public MonthDay fromString(String s) { return MonthDay.parse(s); } @SuppressWarnings({"unchecked"}) @Override public <X> X unwrap(MonthDay monthDay, Class<X> type, WrapperOptions wrapperOptions) { if (monthDay == null) { return null; } if (String.class.isAssignableFrom(type)) { return (X) toString(monthDay); } if (Number.class.isAssignableFrom(type)) { Integer numericValue = (monthDay.getMonthValue() * 100) + monthDay.getDayOfMonth(); return (X) (numericValue); } if (Date.class.isAssignableFrom(type)) { int currentYear = LocalDate.now().getYear(); return (X) java.sql.Date.valueOf(monthDay.atYear(currentYear)); } throw unknownUnwrap(type); } @Override public <X> MonthDay wrap(X value, WrapperOptions wrapperOptions) { if (value == null) { return null; } if (value instanceof String) { return fromString((String) value); } if (value instanceof Number) { int numericValue = ((Number) (value)).intValue(); int month = numericValue / 100; int dayOfMonth = numericValue % 100; return MonthDay.of(month, dayOfMonth); } if (value instanceof Date) { Date date = (Date) value; return MonthDay.from(Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate()); } throw unknownWrap(value.getClass()); } @Override public boolean areEqual(MonthDay one, MonthDay another) { return Objects.equals(one, another); } @Override public String toString(MonthDay value) { return value.toString(); } }
1,070
2,542
<reponame>gridgentoo/ServiceFabricAzure<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Transport; using namespace Common; using namespace std; size_t MessageHeaders::compactThreshold_ = 1024; size_t MessageHeaders::outgoingChunkSize_ = MessageHeaders::defaultOutgoingChunkSize_; MessageHeaders::MessageHeaders() : sharedHeaders_(EmptyByteBique.begin(), EmptyByteBique.end(), false), nonSharedHeaders_(outgoingChunkSize_), appendStream_(nonSharedHeaders_) { } MessageHeaders::MessageHeaders(ByteBiqueRange && shared, StopwatchTime recvTime) : sharedHeaders_(std::move(shared)) , nonSharedHeaders_(outgoingChunkSize_) , appendStream_(nonSharedHeaders_) , recvTime_(recvTime) { CheckSize(); UpdateCommonHeaders(); } uint MessageHeaders::SerializedSize() { // size overflow checking is done at other places, no need to repeat here return (uint)(sharedHeaders_.End - sharedHeaders_.Begin + nonSharedHeaders_.size()); } void MessageHeaders::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { // todo, remove this const_cast MessageHeaders* thisPtr = const_cast<MessageHeaders*>(this); w.Write("Headers["); for(auto iter = thisPtr->Begin(); this->IsValid && iter != thisPtr->End(); ++ iter) { MessageHeaderTrace::Trace(w, *iter); } w.Write(" ~ {0} deleted bytes ~]", deletedHeaderByteCount_); } wstring MessageHeaders::ToString() const { wstring result; StringWriter(result).Write(*this); return result; } NTSTATUS MessageHeaders::CheckSizeLimitBeforeAdd(size_t toAdd) { auto beforeSize = SerializedSize(); auto afterSize = beforeSize + toAdd; if (afterSize <= MessageHeaders::SizeLimitStatic()) return STATUS_SUCCESS; Compact(); #if DBG textTrace.WriteNoise("MessageHeaders", "CheckSizeLimitBeforeAdd: serializedSize = {0}, toAdd = {1}, serializedSizeAfterCompact = {2}", beforeSize, toAdd, SerializedSize()); #endif beforeSize = SerializedSize(); afterSize = beforeSize + toAdd; if (afterSize <= MessageHeaders::SizeLimitStatic()) return STATUS_SUCCESS; RaiseSizeLimitForTracingUnsafe(); trace.MessageHeaderAddFailure(TraceThis, beforeSize, afterSize, ToString()); Fault(STATUS_BUFFER_OVERFLOW); Common::Assert::TestAssert("Exceeding header size limit"); return STATUS_BUFFER_OVERFLOW; } void MessageHeaders::CheckSize() { if (SerializedSize() > SizeLimitStatic()) { Fault(STATUS_BUFFER_OVERFLOW); } } _Use_decl_annotations_ void MessageHeaders::MakeSharedBuffers( Serialization::IFabricSerializableStream& serializedHeaders, ByteBique& sharedBuffers) { BiqueWriteStream bws(sharedBuffers); auto status = Add(bws, serializedHeaders); Invariant(NT_SUCCESS(status)); } NTSTATUS MessageHeaders::Add(KBuffer const& buffer, bool addingCommonHeaders) { auto status = CheckSizeLimitBeforeAdd(buffer.QuerySize()); if (!NT_SUCCESS(status)) return status; appendStream_.SeekToEnd(); appendStream_.WriteBytes(buffer.GetBuffer(), buffer.QuerySize()); if (addingCommonHeaders) { status = UpdateCommonHeaders(); } return status; } NTSTATUS MessageHeaders::Add(Serialization::IFabricSerializableStream const& serializedHeaders, bool addingCommonHeaders) { auto status = CheckSizeLimitBeforeAdd(serializedHeaders.Size()); if (!NT_SUCCESS(status)) return status; status = Add(appendStream_, serializedHeaders); if (!NT_SUCCESS(status)) return status; if (addingCommonHeaders) { status = UpdateCommonHeaders(); } return status; } _Use_decl_annotations_ NTSTATUS MessageHeaders::Add( BiqueWriteStream& bws, Serialization::IFabricSerializableStream const& serializedHeaders) { Serialization::FabricIOBuffer bufferListOnStack[16]; Serialization::FabricIOBuffer* bufferList = bufferListOnStack; size_t count = sizeof(bufferListOnStack) / sizeof(Serialization::FabricIOBuffer); auto status = serializedHeaders.GetAllBuffers(bufferList, count); if (!NT_SUCCESS(status)) { Invariant(status == K_STATUS_BUFFER_TOO_SMALL); auto bufferListInHeap = std::make_unique<Serialization::FabricIOBuffer[]>(count); bufferList = bufferListInHeap.get(); status = serializedHeaders.GetAllBuffers(bufferList, count); if (!NT_SUCCESS(status)) { return status; } } bws.SeekToEnd(); for (uint i = 0; i < count; ++i) { bws.WriteBytes(bufferList[i].buffer, bufferList[i].length); } return status; } NTSTATUS MessageHeaders::Serialize(Serialization::IFabricSerializableStream& stream, Serialization::IFabricSerializable const & header, MessageHeaderId::Enum id) { // WriteRawBytes to avoid compression and meta data stream.SeekToEnd(); stream.WriteRawBytes(sizeof(id), &id); auto headerSizeCursor = stream.Position(); MessageHeaderSize headerSize = 0; stream.WriteRawBytes(sizeof(headerSize), &headerSize); size_t beforeSize = stream.Size(); Serialization::IFabricSerializable * serializable = const_cast<Serialization::IFabricSerializable*>(&header); NTSTATUS status = stream.WriteSerializable(serializable); if (NT_ERROR(status)) return status; headerSize = (MessageHeaderSize)(stream.Size() - beforeSize); // Write actual header size stream.Seek(headerSizeCursor); stream.WriteRawBytes(sizeof(headerSize), &headerSize); stream.SeekToEnd(); return status; } NTSTATUS MessageHeaders::Add( Serialization::IFabricSerializableStream & stream, Serialization::IFabricSerializable const & header, MessageHeaderId::Enum id) { if (!this->IsValid) { return this->Status; } auto status = Serialize(stream, header, id); ASSERT_IF(NT_ERROR(status), "Serialize failed: {0}", status); return Add(stream, false); } bool MessageHeaders::HeaderReference::TryDeserializeInternal(Serialization::IFabricSerializable* header) { if (!this->IsValid) { Common::Assert::TestAssert(); return false; } KMemChannel::UPtr memoryStream = KMemChannel::UPtr( _new (WF_SERIALIZATION_TAG, Common::GetSFDefaultKtlSystem().NonPagedAllocator()) KMemChannel(Common::GetSFDefaultKtlSystem().NonPagedAllocator())); if (!memoryStream) { Fault(STATUS_INSUFFICIENT_RESOURCES); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } NTSTATUS status = memoryStream->Status(); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } // Tell the stream not to delete what it is looking at memoryStream->DetachOnDestruct(); status = memoryStream->StartCapture(); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } ULONG bytesLeft = static_cast<ULONG>(this->serializedHeaderObjectSize_); while (bytesLeft > 0) { Common::const_buffer buffer; this->bufferStream_->GetCurrentSegment(buffer); KMemRef memoryReference(buffer.len, buffer.buf); memoryReference._Param = std::min(buffer.len, bytesLeft); status = memoryStream->Capture(memoryReference); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } this->bufferStream_->SeekForward(buffer.len); bytesLeft -= std::min(buffer.len, bytesLeft); } status = memoryStream->EndCapture(); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } KArray<Serialization::FabricIOBuffer> receivingExtensionBuffers(Common::GetSFDefaultKtlSystem().NonPagedAllocator()); status = receivingExtensionBuffers.Status(); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } Serialization::IFabricStream * receiveByteStream; status = Serialization::FabricStream::Create(&receiveByteStream, Ktl::Move(memoryStream), Ktl::Move(receivingExtensionBuffers)); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } Serialization::IFabricStreamUPtr receiveByteStreamUPtr(receiveByteStream); if (receiveByteStream == nullptr) { Fault(STATUS_INSUFFICIENT_RESOURCES); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } Serialization::IFabricSerializableStream * readStream; status = Serialization::FabricSerializableStream::Create(&readStream, Ktl::Move(receiveByteStreamUPtr)); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } Serialization::IFabricSerializableStreamUPtr readStreamUPtr(readStream); if (readStream == nullptr) { Fault(STATUS_INSUFFICIENT_RESOURCES); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } KAssert(serializedHeaderObjectSize_ == readStreamUPtr->Size()); status = readStreamUPtr->ReadSerializable(header); if (NT_ERROR(status)) { Fault(status); trace.MessageHeaderDeserializationFailure(TraceThis, this->Status); Common::Assert::TestAssert(); return false; } return true; } MessageHeaders::HeaderIterator::HeaderIterator(const BiqueRangeStream& first, const BiqueRangeStream& second, MessageHeaders & parent) : parent_(parent), first_(first), second_(second), currentStream_(&first_), headerReference_(this, &first_), currentDeletedBytesCount_(0) { if ((first_.Size() > parent_.SizeLimit()) || (second_.Size() > parent_.SizeLimit()) || ((first_.Size() + second_.Size()) > parent_.SizeLimit())) { this->Fault(STATUS_INVALID_PARAMETER); ErrorOccurred(); return; } if (first_.Eos()) { currentStream_ = &second_; headerReference_ = HeaderReference(this, &second_); } if (ErrorOccurred()) { return; } currentDeletedBytesCount_ += headerReference_.DeletedBytesBetweenThisAndPredecessor(); } MessageHeaders::HeaderIterator::HeaderIterator(HeaderIterator const & source) : TransportObject(source), first_(source.first_), second_(source.second_), currentStream_(&first_), headerReference_(source.headerReference_), currentDeletedBytesCount_(source.currentDeletedBytesCount_), parent_(source.parent_) { if (ErrorOccurred()) { return; } if (!source.InFirstStream()) { currentStream_ = &second_; } } void MessageHeaders::HeaderReference::OnFault(NTSTATUS status) { bufferStream_->Fault(status); if (headerIterator_) { headerIterator_->Fault(status); } } MessageHeaders::HeaderIterator MessageHeaders::HeaderIterator::Begin( BiqueRangeStream& first, BiqueRangeStream& second, MessageHeaders & parent) { first.SeekToBegin(); second.SeekToBegin(); return HeaderIterator(first, second, parent); } MessageHeaders::HeaderIterator MessageHeaders::HeaderIterator::End( BiqueRangeStream& first, BiqueRangeStream& second, MessageHeaders & parent) { first.SeekToEnd(); second.SeekToEnd(); return HeaderIterator(first, second, parent); } bool MessageHeaders::HeaderIterator::ErrorOccurred() { if (!this->IsValid) { currentStream_ = &second_; currentStream_->SeekToEnd(); return true; } if (!currentStream_->IsValid) { Fault(currentStream_->Status); currentStream_ = &second_; currentStream_->SeekToEnd(); return true; } return false; } MessageHeaders::HeaderIterator & MessageHeaders::HeaderIterator::operator ++ () { if (ErrorOccurred()) { return *this; } // move to next header currentStream_->SeekToBookmark(); currentStream_->SeekForward(headerReference_.ByteTotalInStream()); if (ErrorOccurred()) { return *this; } if (InFirstStream() && first_.Eos()) { // We are at the end of the first stream, so we need to switch to the second stream currentStream_ = &second_; } headerReference_ = HeaderReference(this, currentStream_); if (ErrorOccurred()) { return *this; } // We might have skipped some removed headers, so again we need to check if we need to switch to the second stream if (InFirstStream() && first_.Eos()) { currentStream_ = &second_; headerReference_ = HeaderReference(this, currentStream_, headerReference_.DeletedBytesBetweenThisAndPredecessor()); if (ErrorOccurred()) { return *this; } currentDeletedBytesCount_ += headerReference_.DeletedBytesBetweenThisAndPredecessor(); } else { currentDeletedBytesCount_ += headerReference_.DeletedBytesBetweenThisAndPredecessor(); } return *this; } bool MessageHeaders::HeaderIterator::operator == (HeaderIterator const & rhs) const { return (InFirstStream() == rhs.InFirstStream()) && currentStream_->HasBookmarkEqualTo(*(rhs.currentStream_)); } MessageHeaders::HeaderIterator & MessageHeaders::HeaderIterator::Remove() { if (ErrorOccurred()) { return *this; } currentStream_->SeekToBookmark(); if (!currentStream_->Eos()) { *currentStream_ << MessageHeaderId::INVALID_SYSTEM_HEADER_ID; if (ErrorOccurred()) { return *this; } } ++ (*this); return *this; } void MessageHeaders::HeaderIterator::OnFault(NTSTATUS status) { headerReference_.Fault(status); parent_.Fault(status); } MessageHeaders::HeaderReference::HeaderReference(HeaderIterator* headerIterator, BiqueRangeStream* biqueStream, size_t skippedBytes) : headerIterator_(headerIterator), bufferStream_(biqueStream), start_(biqueStream->GetBookmark()), deletedBytesBetweenThisAndPredecessor_(skippedBytes) { while (!bufferStream_->Eos()) { bufferStream_->SetBookmark(); start_ = bufferStream_->GetBookmark(); *bufferStream_ >> id_; if(!bufferStream_->IsValid) break; MessageHeaderSize messageHeaderSize; *bufferStream_ >> messageHeaderSize; if(!bufferStream_->IsValid) break; if (messageHeaderSize == 0) { this->Fault(STATUS_INVALID_PARAMETER); return; } byteTotalInStream_ = sizeof(MessageHeaderId::Enum) + sizeof(MessageHeaderSize) + messageHeaderSize; if (byteTotalInStream_ > headerIterator_->Parent().SizeLimit()) { this->Fault(STATUS_INVALID_PARAMETER); return; } serializedHeaderObjectSize_ = messageHeaderSize; if(id_ == MessageHeaderId::INVALID_SYSTEM_HEADER_ID) // Need to skip removed headers { this->deletedBytesBetweenThisAndPredecessor_ += this->byteTotalInStream_; bufferStream_->SeekForward(messageHeaderSize); if(!bufferStream_->IsValid) break; continue; } return; } serializedHeaderObjectSize_ = 0; byteTotalInStream_ = 0; bufferStream_->SetBookmark(); } void MessageHeaders::HeaderReference::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { w.Write( "address = {0}, InFirstStream = {1}, headerSize = {2}, headerId = {3}, data =", TextTracePtr(&(*start_)), headerIterator_->InFirstStream(), serializedHeaderObjectSize_, id_); ByteBiqueIterator iter = start_; for (ULONG i = 0; i < byteTotalInStream_; ++ i, ++ iter) { byte byteValue = *iter; w.Write(" {0:x}", byteValue); } w.WriteLine(); } void MessageHeaders::CheckPoint() { nonSharedHeaders_.insert(nonSharedHeaders_.begin(), sharedHeaders_.Begin, sharedHeaders_.End); sharedHeaders_ = std::move(ByteBiqueRange(std::move(nonSharedHeaders_))); checkpointDone_ = true; // todo, consider clearing message properties here, so that later clone operation don't have to copy them } void MessageHeaders::CompactIfNeeded() { if (DeletedHeaderByteCount > compactThreshold_) { Compact(); } } size_t MessageHeaders::SetCompactThreshold(size_t threshold) { compactThreshold_ = threshold; return compactThreshold_; } void MessageHeaders::Compact() { //okay to compact "cloned" messages, as sharedHeaders_ is completed replaced, instead of updating in place if (deletedHeaderByteCount_ == 0) { return; } ByteBique compacted(outgoingChunkSize_); // TODO this is somewhat redundant with CheckPoint, and could be skipped if enumerating header chunks did not include // deleted headers. // iterating headers skips deleted headers for (auto iter = Begin(); iter != End(); ++iter) { compacted.append(iter->Start(), iter->ByteTotalInStream()); } if (!this->IsValid) return; sharedHeaders_ = std::move(ByteBiqueRange(std::move(compacted))); nonSharedHeaders_.truncate_before(nonSharedHeaders_.end()); // all headers marked as deleted have been purged this->deletedHeaderByteCount_ = 0; } void MessageHeaders::AppendFrom(MessageHeaders & other) { // Checkpoint other headers other.CheckPoint(); other.deletedHeaderByteCount_ = 0; // all headers in "other" will be moved to "this" // Steal all shared headers from other into nonSharedHeaders_ ByteBiqueRange localBiqueRange(std::move(other.sharedHeaders_)); nonSharedHeaders_.insert(nonSharedHeaders_.begin(), localBiqueRange.Begin, localBiqueRange.End); CheckSize(); // Update all common other.ResetCommonHeaders(); UpdateCommonHeaders(); } void MessageHeaders::SetShared(ByteBique & buffers, bool setCommonHeaders) { sharedHeaders_ = ByteBiqueRange(buffers.begin(), buffers.end(), true); CheckSize(); if (setCommonHeaders) { ResetCommonHeaders(); UpdateCommonHeaders(); } } void MessageHeaders::Replace(ByteBiqueRange && otherRange) { ReplaceUnsafe(std::move(otherRange)); ResetCommonHeaders(); UpdateCommonHeaders(); } void MessageHeaders::ReplaceUnsafe(ByteBiqueRange && headers) { sharedHeaders_ = std::move(ByteBiqueRange(std::move(headers))); nonSharedHeaders_.truncate_before(nonSharedHeaders_.end()); CheckSize(); } MessageHeaders::HeaderIterator& MessageHeaders::Remove(HeaderIterator& iter) { ASSERT_IF(&iter.Parent() != this, "Only allow iterators from this"); ASSERT_IF(checkpointDone_ && iter.InFirstStream(), "after CheckPoint, shared header {0} cannot be removed from {1}", *iter, *this); // todo, leikong, it may be unsafe to remove from sharedHeaders_ if a message is cloned but no checkpoint, e.g. // removing a shared header from a clone for retry will also remove the header from the clone for the original // send, which may be still on-going due to slow connection setup. Possible solutions: // 1. copy all remaining headers when removing a shared header. Performance may suffer, e.g. federation // routing, multicasting and broadcasting, where headers may be removed after cloning // 2. record the removed locations into a list local to each message object, and skip these removed headers // when doing chunk iteration // todo: the following needs to updated when common header shortcut properties become real header instances switch (iter->Id()) { case MessageHeaderId::Action: action_.clear(); break; case MessageHeaderId::Actor: actor_ = Actor::Enum::Empty; break; case MessageHeaderId::MessageId: messageId_ = Transport::MessageId(Common::Guid::Empty(), 0); break; case MessageHeaderId::RelatesTo: relatesTo_ = Transport::MessageId(Common::Guid::Empty(), 0); break; case MessageHeaderId::Retry: retryCount_ = 0; break; case MessageHeaderId::ExpectsReply: expectsReply_ = false; break; case MessageHeaderId::Idempotent: idempotent_ = false; break; case MessageHeaderId::HighPriority: highPriority_ = false; break; case MessageHeaderId::Fault: faultErrorCodeValue_ = Common::ErrorCodeValue::Success; hasFaultBody_ = false; break; case MessageHeaderId::UncorrelatedReply: isUncorrelatedReply_ = false; break; } this->deletedHeaderByteCount_ += iter->ByteTotalInStream(); return iter.Remove(); } void MessageHeaders::RemoveAll() { sharedHeaders_ = ByteBiqueRange(EmptyByteBique.begin(), EmptyByteBique.end(), false); nonSharedHeaders_.truncate_before(nonSharedHeaders_.end()); deletedHeaderByteCount_ = 0; ResetCommonHeaders(); } void MessageHeaders::ResetCommonHeaders() { action_.clear(); actor_ = Actor::Enum::Empty; messageId_ = Transport::MessageId(Common::Guid::Empty(), 0); relatesTo_ = Transport::MessageId(Common::Guid::Empty(), 0); retryCount_ = 0; expectsReply_ = false; idempotent_ = false; highPriority_ = false; faultErrorCodeValue_ = Common::ErrorCodeValue::Success; hasFaultBody_ = false; isUncorrelatedReply_ = false; } NTSTATUS MessageHeaders::UpdateCommonHeaders() { // Search for common headers // todo, consider moving this to HeaderReference.Deserialize<T> specilization. // we only need to do this when the requested common header is not already cached HeaderIterator iter = Begin(); for ( ; this->IsValid && iter != End(); ++ iter) { switch (iter->Id()) { case MessageHeaderId::Action: { ActionHeader header = iter->Deserialize<ActionHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } action_ = header.Action; break; } case MessageHeaderId::Actor: { ActorHeader header = iter->Deserialize<ActorHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } actor_ = header.Actor; break; } case MessageHeaderId::MessageId: { MessageIdHeader header = iter->Deserialize<MessageIdHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } messageId_ = header.MessageId; UpdateTraceId(); break; } case MessageHeaderId::RelatesTo: { RelatesToHeader header = iter->Deserialize<RelatesToHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } relatesTo_ = header.MessageId; UpdateTraceId(); break; } case MessageHeaderId::Retry: { RetryHeader header = iter->Deserialize<RetryHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } retryCount_ = header.RetryCount; break; } case MessageHeaderId::ExpectsReply: { ExpectsReplyHeader header = iter->Deserialize<ExpectsReplyHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } expectsReply_ = header.ExpectsReply; break; } case MessageHeaderId::Idempotent: { IdempotentHeader header = iter->Deserialize<IdempotentHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } idempotent_ = header.Idempotent; break; } case MessageHeaderId::HighPriority: { HighPriorityHeader header = iter->Deserialize<HighPriorityHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } highPriority_ = header.HighPriority; break; } case MessageHeaderId::Fault: { FaultHeader header = iter->Deserialize<FaultHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } faultErrorCodeValue_ = header.ErrorCodeValue; hasFaultBody_ = header.HasFaultBody; break; } case MessageHeaderId::UncorrelatedReply: { UncorrelatedReplyHeader header = iter->Deserialize<UncorrelatedReplyHeader>(); if (!iter->IsValid) { KAssert(!this->IsValid); return this->Status; } isUncorrelatedReply_ = header.IsUncorrelatedReply; break; } } } if (!this->IsValid) return this->Status; this->deletedHeaderByteCount_ = iter.CurrentDeletedBytesCount(); return this->Status; } void MessageHeaders::Test_SetOutgoingChunkSize(size_t value) { outgoingChunkSize_ = value; } void MessageHeaders::Test_SetOutgoingChunkSizeToDefault() { outgoingChunkSize_ = defaultOutgoingChunkSize_; } MessageId const & MessageHeaders::TraceId() const { return traceId_; } void MessageHeaders::SetTraceId(Transport::MessageId const & value) { traceId_ = value; } bool MessageHeaders::IsReply() const { return isReply_; } void MessageHeaders::CopyFrom(const MessageHeaders & other) { recvTime_ = other.recvTime_; // todo, leikong, the assumption is there is no shared header, may need to clear first nonSharedHeaders_.append(other.nonSharedHeaders_.begin(), other.nonSharedHeaders_.size()); nonSharedHeaders_.append(other.sharedHeaders_.Begin, other.sharedHeaders_.End - other.sharedHeaders_.Begin); UpdateCommonHeaders(); } void MessageHeaders::CopyNonSharedHeadersFrom(const MessageHeaders & other) { CODING_ERROR_ASSERT(nonSharedHeaders_.empty()); nonSharedHeaders_.append(other.nonSharedHeaders_.begin(), other.nonSharedHeaders_.size()); UpdateCommonHeaders(); } bool MessageHeaders::Contains(MessageHeaderId::Enum headerId) { for (auto headerIter = Begin(); this->IsValid && (headerIter != End()); ++headerIter) { if (headerIter->Id() == headerId) { return true; } } return false; } NTSTATUS MessageHeaders::FinalizeIdempotentHeader() { if (idempotent_) { IdempotentHeader header; return Add(*Common::FabricSerializer::CreateSerializableStream(), header, header.Id); } return STATUS_SUCCESS; }
11,496
4,184
<gh_stars>1000+ /** * Copyright (c) 2007-2012, <NAME> * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. */ #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include "logfile.hh" #include "grep_proc.hh" #include "line_buffer.hh" class my_source : public grep_proc_source { public: logfile *ms_lf; my_source(logfile *lf) : ms_lf(lf) { }; size_t grep_lines(void) { return this->ms_lf->size(); }; void grep_value_for_line(int line, std::string &value_out, int pass) { value_out = this->ms_lf->read_line(this->ms_lf->begin() + line); }; }; class my_sink : public grep_proc_sink { public: void grep_match(grep_line_t line, int start, int end) { printf("%d - %d:%d\n", (int)line, start, end); }; }; int main(int argc, char *argv[]) { int retval = EXIT_SUCCESS; auto_fd fd; fd = open("/tmp/gp.err", O_WRONLY|O_CREAT|O_APPEND, 0666); dup2(fd, STDERR_FILENO); fprintf(stderr, "startup\n"); if (argc < 2) { fprintf(stderr, "error: no file given\n"); } else { logfile lf(argv[1]); lf.rebuild_index(); my_source ms(&lf); my_sink msink; grep_proc gp("pnp", ms); gp.start(); gp.set_sink(&msink); fd_set read_fds; int maxfd = gp.update_fd_set(read_fds); while (1) { fd_set rfds = read_fds; select(maxfd + 1, &rfds, NULL, NULL, NULL); gp.check_fd_set(rfds); if (!FD_ISSET(maxfd, &read_fds)) break; } } return retval; }
1,123
358
<gh_stars>100-1000 """ cx_Freeze command line tool (enable python -m cx_Freeze syntax) """ import cx_Freeze.cli if __name__ == "__main__": cx_Freeze.cli.main()
67
6,465
<reponame>mszabo-wikia/dropwizard<gh_stars>1000+ package io.dropwizard.testing.junit5; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtensionContext; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; // Utility interface for tests in this file. @FunctionalInterface interface Invokable { void invoke(); } // Utility class for tests in this file. // Allows us to count whether before() and after() are being correctly called by DropwizardExtensionsSupport. class CountingExtension implements DropwizardExtension { private int beforeInvocations; private int afterInvocations; @Override public void before() throws Throwable { beforeInvocations++; } @Override public void after() throws Throwable { afterInvocations++; } public int getBeforeInvocations() { return beforeInvocations; } public int getAfterInvocations() { return afterInvocations; } } // Utility interface for tests in this file. // Tests that need to assert things after invocation of DropwizardExtensionsSupport.afterEach() can implement this. // CallbackVerifyingExtension will then call this interface's method to then invoke any additional assertions. interface DelayedAssertionsTest { List<Invokable> getDelayedAssertions(); } // Utility class for tests in this file. // Allows us to perform assertions *after* DropwizardExtensionsSupport.afterEach() is invoked. class CallbackVerifyingExtension implements AfterEachCallback { @Override public void afterEach(ExtensionContext context) throws Exception { DelayedAssertionsTest testInstance = (DelayedAssertionsTest) context.getTestInstance() .orElseThrow(() -> new AssertionError("Null context.testInstance")); testInstance.getDelayedAssertions().forEach(Invokable::invoke); } } // ----------------------- // The rest of the classes in this file set up various different test class hierarchies. // (Ensure DropwizardExtensionsSupport's reflection logic works regardless of how one's tests are structured.) // Related issue: #4205 // ----------------------- abstract class ParentClass_ChildHasExtension implements DelayedAssertionsTest { protected abstract CountingExtension getExtension(); @Test public void parentClassTestMethod() { // when, then getDelayedAssertions().add(() -> { assertThat(getExtension().getBeforeInvocations()).isEqualTo(1); assertThat(getExtension().getAfterInvocations()).isEqualTo(1); }); } @Test public void overriddenTestMethod() { // when, then getDelayedAssertions().add(() -> { assertThat(getExtension().getBeforeInvocations()).isEqualTo(1); assertThat(getExtension().getAfterInvocations()).isEqualTo(1); }); } @Nested public class NestedClass_OnlyInParent implements DelayedAssertionsTest { @Override public List<Invokable> getDelayedAssertions() { return ParentClass_ChildHasExtension.this.getDelayedAssertions(); } // This specific test failed due to issue: #4205 @Test public void onlyInParent() { // when, then getDelayedAssertions().add(() -> { assertThat(getExtension().getBeforeInvocations()).isEqualTo(1); assertThat(getExtension().getAfterInvocations()).isEqualTo(1); }); } } } @ExtendWith(CallbackVerifyingExtension.class) @ExtendWith(DropwizardExtensionsSupport.class) abstract class ParentClass_ParentHasExtension implements DelayedAssertionsTest { protected final CountingExtension extension = new CountingExtension(); protected final List<Invokable> delayedAssertions = new ArrayList<>(); @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void parentClassTestMethod() { // when, then getDelayedAssertions().add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Test public void overriddenTestMethod() { // when, then getDelayedAssertions().add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Nested public class NestedClass_OnlyInParent implements DelayedAssertionsTest { @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void onlyInParent() { // when, then getDelayedAssertions().add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } } } @ExtendWith(CallbackVerifyingExtension.class) @ExtendWith(DropwizardExtensionsSupport.class) class DropwizardExtensionsSupport_ChildHasExtension_NestedUseTest implements DelayedAssertionsTest { private final CountingExtension extension = new CountingExtension(); private final List<Invokable> delayedAssertions = new ArrayList<>(); @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void regularTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Nested public class NestedClass_Standalone implements DelayedAssertionsTest { @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void nestedClassMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } } @Nested public class NestedClass_Inheriting extends ParentClass_ChildHasExtension { @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Override protected CountingExtension getExtension() { return extension; } @Test public void childClassTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Test @Override public void parentClassTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } } } @ExtendWith(CallbackVerifyingExtension.class) @ExtendWith(DropwizardExtensionsSupport.class) class DropwizardExtensionsSupport_ChildHasExtension_OuterUseTest extends ParentClass_ChildHasExtension { private final CountingExtension extension = new CountingExtension(); private final List<Invokable> delayedAssertions = new ArrayList<>(); @Override protected CountingExtension getExtension() { return extension; } @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void regularTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Nested public class NestedClass_Standalone implements DelayedAssertionsTest { @Override public List<Invokable> getDelayedAssertions() { return delayedAssertions; } @Test public void nestedClassMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } } } class DropwizardExtensionsSupport_ParentHasExtensionTest { @Nested public class NestedClass_Inheriting extends ParentClass_ParentHasExtension { @Test public void childClassTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } @Test @Override public void parentClassTestMethod() { // when, then delayedAssertions.add(() -> { assertThat(extension.getBeforeInvocations()).isEqualTo(1); assertThat(extension.getAfterInvocations()).isEqualTo(1); }); } } }
3,868
852
#include "RecoParticleFlow/PFProducer/interface/BlockElementLinkerBase.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockElementCluster.h" #include "RecoParticleFlow/PFClusterTools/interface/LinkByRecHit.h" class ECALAndECALLinker : public BlockElementLinkerBase { public: ECALAndECALLinker(const edm::ParameterSet& conf) : BlockElementLinkerBase(conf), useKDTree_(conf.getParameter<bool>("useKDTree")), debug_(conf.getUntrackedParameter<bool>("debug", false)) {} bool linkPrefilter(const reco::PFBlockElement*, const reco::PFBlockElement*) const override; double testLink(const reco::PFBlockElement*, const reco::PFBlockElement*) const override; private: bool useKDTree_, debug_; }; DEFINE_EDM_PLUGIN(BlockElementLinkerFactory, ECALAndECALLinker, "ECALAndECALLinker"); bool ECALAndECALLinker::linkPrefilter(const reco::PFBlockElement* elem1, const reco::PFBlockElement* elem2) const { const reco::PFBlockElementCluster* ecal1 = static_cast<const reco::PFBlockElementCluster*>(elem1); const reco::PFBlockElementCluster* ecal2 = static_cast<const reco::PFBlockElementCluster*>(elem2); return (ecal1->superClusterRef().isNonnull() && ecal2->superClusterRef().isNonnull()); } double ECALAndECALLinker::testLink(const reco::PFBlockElement* elem1, const reco::PFBlockElement* elem2) const { double dist = -1.0; const reco::PFBlockElementCluster* ecal1 = static_cast<const reco::PFBlockElementCluster*>(elem1); const reco::PFBlockElementCluster* ecal2 = static_cast<const reco::PFBlockElementCluster*>(elem2); const reco::SuperClusterRef& sc1 = ecal1->superClusterRef(); const reco::SuperClusterRef& sc2 = ecal2->superClusterRef(); const reco::PFClusterRef& clus1 = ecal1->clusterRef(); const reco::PFClusterRef& clus2 = ecal2->clusterRef(); if (sc1.isNonnull() && sc2.isNonnull() && sc1 == sc2) { dist = LinkByRecHit::computeDist( clus1->positionREP().Eta(), clus1->positionREP().Phi(), clus2->positionREP().Eta(), clus2->positionREP().Phi()); } return dist; }
759
862
/* * (c) Copyright 2020 Palantir Technologies 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.palantir.atlasdb.timelock.adjudicate; import static org.assertj.core.api.Assertions.assertThat; import com.palantir.logsafe.exceptions.SafeIllegalStateException; import java.util.Arrays; import org.junit.Test; public class HealthStateTest { @Test public void worstStatusOfAllOptions() { assertThat(getWorst(HealthStatus.HEALTHY, HealthStatus.UNKNOWN)).isEqualTo(HealthStatus.UNKNOWN); assertThat(getWorst(HealthStatus.HEALTHY, HealthStatus.UNHEALTHY)).isEqualTo(HealthStatus.UNHEALTHY); assertThat(getWorst(HealthStatus.HEALTHY, HealthStatus.HEALTHY)).isEqualTo(HealthStatus.HEALTHY); assertThat(getWorst(HealthStatus.UNKNOWN, HealthStatus.UNHEALTHY)).isEqualTo(HealthStatus.UNHEALTHY); assertThat(getWorst(HealthStatus.UNKNOWN, HealthStatus.UNHEALTHY, HealthStatus.HEALTHY)) .isEqualTo(HealthStatus.UNHEALTHY); } private HealthStatus getWorst(HealthStatus... healthStatuses) { return Arrays.stream(healthStatuses) .max(HealthStatus.getHealthStatusComparator()) .orElseThrow(() -> new SafeIllegalStateException("Attempted to get the worst of zero health statuses")); } }
621