max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,206
import logging import mitmproxy.controller import mitmproxy.proxy import mitmproxy.flow import mitmproxy.dump import mitmproxy.cmdline import mitmproxy.models import mitmproxy.protocol import mitmproxy as mproxy from mitmproxy.script import script from cachebrowser.models import Website from cachebrowser.pipes import SKIP_PIPES logger = logging.getLogger(__name__) class TlsLayer(mproxy.protocol.TlsLayer): @property def sni_for_server_connection(self): if self.server_conn.sni is not None: return self.server_conn.sni return mproxy.protocol.TlsLayer.sni_for_server_connection.fget(self) class ProxyConfig(mitmproxy.proxy.ProxyConfig): def __init__(self, context): mitmproxy.proxy.ProxyConfig.__init__(self, port=context.settings.port) self.context = context self.check_ignore = self._check_ignore def _check_ignore(self, address): """ Have mitmproxy ignore connections for websites which are not enabled. This makes mitmproxy use the original certificate and just pass the data through. However we should still stop the pipes from processing the request (using WebsiteFilterPipe) """ return False # if address is None: # return False # # hostname = address[0] if type(address) == tuple else address.host # website, _ = Website.get_or_create(hostname=hostname) # return not website.enabled class ProxyController(mitmproxy.flow.FlowMaster): def __init__(self, server, ipc, state=None): if state is None: state = mitmproxy.flow.State() mitmproxy.flow.FlowMaster.__init__(self, server, state) self.ipc = ipc def add_pipe(self, pipe): pipe.set_master(self) self.scripts.append(pipe) def handle_serverconnect(self, server_conn): # server_conn.__class__ = ServerConnection mproxy.flow.FlowMaster.handle_serverconnect(self, server_conn) def handle_request(self, f): mproxy.flow.FlowMaster.handle_request(self, f) if f and not (hasattr(f, 'should_reply') and f.should_reply is False): f.reply() return f def handle_response(self, f): mproxy.flow.FlowMaster.handle_response(self, f) if f: f.reply() return f def handle_error(self, f): mproxy.flow.FlowMaster.handle_error(self, f) return f def handle_next_layer(self, top_layer): if top_layer.__class__ == mproxy.protocol.TlsLayer: top_layer.__class__ = TlsLayer mproxy.flow.FlowMaster.handle_next_layer(self, top_layer) def add_event(self, e, level=None, key=None): # mitmproxy gives TLS error: Invalid Hostname because of not using SNI # ignore the message so the log doesn't get cluttered ignore_messages = [ "TLS verification failed for upstream server at depth 0 with error: Invalid Hostname", "Ignoring server verification error, continuing with connection", "clientconnect", "clientdisconnect", ] if any([e.endswith(s) for s in ignore_messages]): return logger.log(getattr(logging, level.upper()), e) # logger.log(logging.DEBUG, e) def run(self): self.run_script_hook('start') super(ProxyController, self).run() def _run_single_script_hook(self, script_obj, name, *args, **kwargs): if script_obj and not self.pause_scripts: try: return script_obj.run(name, *args, **kwargs) except script.ScriptException as e: self.add_event("Script error:\n" + str(e), "error") def run_script_hook(self, name, *args, **kwargs): for script_obj in self.scripts: result = self._run_single_script_hook(script_obj, name, *args, **kwargs) if result == SKIP_PIPES: break class DumpProxyController(mitmproxy.dump.DumpMaster): def __init__(self, server): parser = mitmproxy.cmdline.mitmdump() options = parser.parse_args(None) dump_options = mitmproxy.dump.Options(**mitmproxy.cmdline.get_common_options(options)) mitmproxy.dump.DumpMaster.__init__(self, server, dump_options) def add_pipe(self, pipe): pipe.set_master(self) self.scripts.append(pipe)
1,814
575
<filename>components/content_settings/core/common/features.h<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. #ifndef COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_ #define COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_ #include "base/component_export.h" #include "build/build_config.h" namespace base { struct Feature; } // namespace base namespace content_settings { #if defined(OS_IOS) // Feature to enable a better cookie controls ui. COMPONENT_EXPORT(CONTENT_SETTINGS_FEATURES) extern const base::Feature kImprovedCookieControls; #endif } // namespace content_settings #endif // COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_FEATURES_H_
265
6,717
//****************************************************************************** // // Copyright (c) 2016 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** #pragma once #import <CoreMotion/CoreMotionExport.h> #import <Foundation/NSObject.h> #import <objc/runtime.h> @class NSError; @class NSDate; @class NSOperationQueue; typedef void (^CMStepQueryHandler)(NSInteger numberOfSteps, NSError* error); typedef void (^CMStepUpdateHandler)(NSInteger numberOfSteps, NSDate* timestamp, NSError* error); COREMOTION_EXPORT_CLASS @interface CMStepCounter : NSObject + (BOOL)isStepCountingAvailable STUB_METHOD; - (void)startStepCountingUpdatesToQueue:(NSOperationQueue*)queue updateOn:(NSInteger)stepCounts withHandler:(CMStepUpdateHandler)handler STUB_METHOD; - (void)stopStepCountingUpdates STUB_METHOD; - (void)queryStepCountStartingFrom:(NSDate*)start to:(NSDate*)end toQueue:(NSOperationQueue*)queue withHandler:(CMStepQueryHandler)handler STUB_METHOD; @end
598
1,907
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 <NAME>, Jupiter Jazz Limited // Copyright (c) 2014-2018 <NAME>, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "jobmanager.h" // appleseed.foundation headers. #include "foundation/log/log.h" #include "foundation/utility/foreach.h" #include "foundation/utility/job/jobqueue.h" #include "foundation/utility/job/workerthread.h" // Standard headers. #include <cassert> #include <vector> using namespace boost; namespace foundation { // // JobManager class implementation. // struct JobManager::Impl { typedef std::vector<WorkerThread*> WorkerThreads; Logger& m_logger; JobQueue& m_job_queue; size_t m_thread_count; const int m_flags; WorkerThreads m_worker_threads; // Constructor. Impl( Logger& logger, JobQueue& job_queue, const size_t thread_count, const int flags) : m_logger(logger) , m_job_queue(job_queue) , m_thread_count(thread_count) , m_flags(flags) { } }; JobManager::JobManager( Logger& logger, JobQueue& job_queue, const size_t thread_count, const int flags) : impl(new Impl(logger, job_queue, thread_count, flags)) { } JobManager::~JobManager() { stop(); delete impl; } size_t JobManager::get_thread_count() const { return impl->m_thread_count; } void JobManager::start() { assert(impl->m_worker_threads.empty() || impl->m_worker_threads.size() == impl->m_thread_count); // Create worker threads if they don't already exist. if (impl->m_worker_threads.empty()) { for (size_t i = 0; i < impl->m_thread_count; ++i) { impl->m_worker_threads.push_back( new WorkerThread( i, impl->m_logger, impl->m_job_queue, impl->m_flags)); } } // Start worker threads. for (each<Impl::WorkerThreads> i = impl->m_worker_threads; i; ++i) (*i)->start(); } void JobManager::stop() { // Stop and delete worker threads. for (each<Impl::WorkerThreads> i = impl->m_worker_threads; i; ++i) delete *i; impl->m_worker_threads.clear(); } void JobManager::pause() { for (each<Impl::WorkerThreads> i = impl->m_worker_threads; i; ++i) (*i)->pause(); } void JobManager::resume() { for (each<Impl::WorkerThreads> i = impl->m_worker_threads; i; ++i) (*i)->resume(); } } // namespace foundation
1,517
529
<reponame>inordeng/TASO /* Copyright 2020 Stanford, Tsinghua * * 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 _CPP_EXAMPLES_RESNEXT50_H_ #define _CPP_EXAMPLES_RESNEXT50_H_ TensorHandle resnext_block(Graph* graph, const TensorHandle input, int strideH, int strideW, int outChannels, int groups) { TensorHandle t = input; auto w1 = new_random_weight(graph, { outChannels, t->dim[1], 1, 1 }); t = graph->conv2d(t, w1, 1, 1, PD_MODE_SAME, AC_MODE_RELU); auto w2 = new_random_weight(graph, { outChannels, t->dim[1] / groups, 3, 3 }); t = graph->conv2d(t, w2, strideH, strideW, PD_MODE_SAME, AC_MODE_RELU); auto w3 = new_random_weight(graph, { 2 * outChannels, t->dim[1], 1, 1 }); t = graph->conv2d(t, w3, 1, 1, PD_MODE_SAME); auto inp = input; if (strideH > 1 || inp->dim[1] != 2 * outChannels) { auto w4 = new_random_weight(graph, { 2 * outChannels, inp->dim[1], 1, 1 }); inp = graph->conv2d(inp, w4, strideH, strideW, PD_MODE_SAME, AC_MODE_RELU); } return graph->relu(graph->element(OP_EW_ADD, inp, t)); } Graph* resnext50(float alpha, int budget, bool printSubst = false) { Graph *graph = new Graph(); auto inp = new_input(graph, { 1, 3, 224, 224 }); auto weight = new_random_weight(graph, { 64, 3, 7, 7 }); auto t = graph->conv2d(inp, weight, 2, 2, PD_MODE_SAME, AC_MODE_RELU); t = graph->pool2d_max(t, 3, 3, 2, 2, PD_MODE_SAME); int stride = 1; for (int i = 0; i < 3; i++) { t = resnext_block(graph, t, stride, stride, 128, 32); } stride = 2; for (int i = 0; i < 4; i++) { t = resnext_block(graph, t, stride, stride, 256, 32); stride = 1; } stride = 2; for (int i = 0; i < 6; i++) { t = resnext_block(graph, t, stride, stride, 512, 32); stride = 1; } stride = 2; for (int i = 0; i < 3; i++) { t = resnext_block(graph, t, stride, stride, 1024, 32); stride = 1; } return graph->optimize(alpha, budget, printSubst); } #endif
949
5,349
<reponame>marcio55afr/sktime # -*- coding: utf-8 -*- """Code for creating diagrams."""
37
310
{ "name": "4080", "description": "A double-necked electric guitar.", "url": "https://en.wikipedia.org/wiki/Rickenbacker_4080" }
50
899
# -*- coding: utf-8 -*- """ Empty file to mark package as valid django application. """
30
511
/**************************************************************************** * * Copyright 2021 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ #include <tinyara/config.h> #include <stdio.h> #include <tinyara/seclink.h> #include "sltool.h" #include "sltool_utils.h" #define SLT_OUTPUT_SIZE 16384 // 16KB int sltool_handle_remove_ss(sl_options_s *opt) { printf("[sltool] idx %d %s:%d\n", opt->idx, __FUNCTION__, __LINE__); int fres = 0; int res = 0; sl_ctx hnd; if ((res = sl_init(&hnd)) != SECLINK_OK) { printf("[sltool] error to sl_init %d\n", res); return -1; } if ((res = sl_delete_storage(hnd, opt->idx)) != SECLINK_OK) { printf("[sltool] error delete message reason(%s) %s:%d\n", sl_strerror(res), __FUNCTION__, __LINE__); fres = -1; } if ((res = sl_deinit(hnd)) != SECLINK_OK) { printf("[sltool] error %d %s:%d\n", res, __FUNCTION__, __LINE__); } return fres; } int sltool_handle_write_ss(sl_options_s *opt) { printf("[sltool] idx %d data %02x %ld size %d %s:%d\n", opt->idx, opt->ss_data, sizeof(opt->ss_data), opt->ss_write_size, __FUNCTION__, __LINE__); int fres = 0; int res = 0; sl_ctx hnd; char *data = NULL; hal_data input; if ((res = sl_init(&hnd)) != SECLINK_OK) { printf("[sltool] error to sl_init %d\n", res); return -1; } input.priv = NULL; input.priv_len = 0; input.data_len = opt->ss_write_size; data = (char *)malloc(input.data_len); if (!data) { fres = -1; goto out; } for (int i = 0; i < input.data_len; i++) { data[i] = opt->ss_data; } input.data = data; if ((res = sl_write_storage(hnd, opt->idx, &input)) != SECLINK_OK) { printf("[sltool] error to write data %s %s:%d\n", sl_strerror(res), __FUNCTION__, __LINE__); fres = -1; goto out; } out: if ((res = sl_deinit(hnd)) != SECLINK_OK) { printf("[sltool] error %d %s:%d\n", res, __FUNCTION__, __LINE__); } if (data) { free(data); } return fres; } int sltool_handle_get_ss(sl_options_s *opt) { printf("[sltool] idx %d %s:%d\n", opt->idx, __FUNCTION__, __LINE__); int fres = 0; int res = 0; sl_ctx hnd; char *data = NULL; hal_data output; if ((res = sl_init(&hnd)) != SECLINK_OK) { printf("[sltool] error to sl_init %d\n", res); return -1; } output.priv = NULL; output.priv_len = 0; output.data_len = SLT_OUTPUT_SIZE; data = (char *)malloc(output.data_len); if (!data) { fres = -1; goto out; } output.data = data; /* If output size is less thatn stored size in a secure storage then * it would occur unexpected behavior */ if ((res = sl_read_storage(hnd, opt->idx, &output)) != SECLINK_OK) { printf("[sltool] error to write data %s %s:%d\n", sl_strerror(res), __FUNCTION__, __LINE__); fres = -1; goto out; } sltool_print_buffer(output.data, output.data_len, "Secure Storage Output Data"); out: if ((res = sl_deinit(hnd)) != SECLINK_OK) { printf("[sltool] error %d %s:%d\n", res, __FUNCTION__, __LINE__); } if (data) { free(data); } return fres; }
1,495
5,813
<reponame>RomaKoks/druid /* * 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.druid.query.aggregation.variance; import org.apache.druid.common.config.NullHandling; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.query.Druids; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.query.aggregation.post.FieldAccessPostAggregator; import org.apache.druid.query.aggregation.post.FinalizingFieldAccessPostAggregator; import org.apache.druid.query.timeseries.TimeseriesQuery; import org.apache.druid.query.timeseries.TimeseriesQueryQueryToolChest; import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.column.RowSignature; import org.apache.druid.testing.InitializedNullHandlingTest; import org.junit.Assert; import org.junit.Test; public class VarianceAggregatorFactoryTest extends InitializedNullHandlingTest { @Test public void testResultArraySignature() { final TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("dummy") .intervals("2000/3000") .granularity(Granularities.HOUR) .aggregators( new CountAggregatorFactory("count"), new VarianceAggregatorFactory("variance", "col"), new VarianceFoldingAggregatorFactory("varianceFold", "col", null) ) .postAggregators( new FieldAccessPostAggregator("variance-access", "variance"), new FinalizingFieldAccessPostAggregator("variance-finalize", "variance"), new FieldAccessPostAggregator("varianceFold-access", "varianceFold"), new FinalizingFieldAccessPostAggregator("varianceFold-finalize", "varianceFold") ) .build(); Assert.assertEquals( RowSignature.builder() .addTimeColumn() .add("count", ColumnType.LONG) .add("variance", null) .add("varianceFold", null) .add("variance-access", VarianceAggregatorFactory.TYPE) .add("variance-finalize", ColumnType.DOUBLE) .add("varianceFold-access", VarianceAggregatorFactory.TYPE) .add("varianceFold-finalize", ColumnType.DOUBLE) .build(), new TimeseriesQueryQueryToolChest().resultArraySignature(query) ); } @Test public void testFinalizeComputationWithZeroCountShouldReturnNull() { VarianceAggregatorFactory target = new VarianceAggregatorFactory("test", "test", null, null); VarianceAggregatorCollector v1 = new VarianceAggregatorCollector(); Assert.assertEquals(NullHandling.defaultDoubleValue(), target.finalizeComputation(v1)); } @Test public void testFinalizeComputationWithNullShouldReturnNull() { VarianceAggregatorFactory target = new VarianceAggregatorFactory("test", "test", null, null); Assert.assertEquals(NullHandling.defaultDoubleValue(), target.finalizeComputation(null)); } }
1,482
1,068
/** * Copyright (c) 2012-2015 <NAME> * * This file is part of Handlebars.java. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jknack.handlebars.internal; /** * Utility methods for removing whitespace according to Mustache Spec. * * @author <NAME> * @since 4.1.3 */ public final class MustacheStringUtils { /** * Constructor. */ private MustacheStringUtils() { } /** * Get the index of the start of the second line. * If a non-whitespace character is found first, null is returned. * * @param str The string. * @return The index of the start of the second line. */ public static Integer indexOfSecondLine(final String str) { if (str == null) { return -1; } int end = str.length(); if (end == 0) { return -1; } int i = 0; while (i < end) { char c = str.charAt(i); if ('\r' == c || '\n' == c) { i++; if ('\r' == c && i < end) { char next = str.charAt(i); if ('\n' == next) { i++; } } return i; } if (!Character.isWhitespace(c)) { return null; } i++; } return -1; } /** * Remove the last line if it contains only whitespace. * * @param str The string. * @return The string with it's last line removed. */ public static String removeLastWhitespaceLine(final String str) { if (str == null) { return ""; } int end = str.length(); if (end == 0) { return ""; } while (end != 0) { char c = str.charAt(end - 1); if (!Character.isWhitespace(c)) { return str; } if ('\r' == c || '\n' == c) { return str.substring(0, end); } end--; } return ""; } }
918
2,151
<gh_stars>1000+ // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/loader/request_extra_data.h" #include "content/common/service_worker/service_worker_types.h" #include "services/network/public/cpp/resource_request.h" using blink::WebString; namespace content { RequestExtraData::RequestExtraData() : visibility_state_(blink::mojom::PageVisibilityState::kVisible), render_frame_id_(MSG_ROUTING_NONE), is_main_frame_(false), allow_download_(true), transition_type_(ui::PAGE_TRANSITION_LINK), service_worker_provider_id_(kInvalidServiceWorkerProviderId), originated_from_service_worker_(false), initiated_in_secure_context_(false), is_for_no_state_prefetch_(false), download_to_network_cache_only_(false), block_mixed_plugin_content_(false), navigation_initiated_by_renderer_(false), attach_same_site_cookies_(false) {} RequestExtraData::~RequestExtraData() { } void RequestExtraData::CopyToResourceRequest( network::ResourceRequest* request) const { request->is_prerendering = visibility_state_ == blink::mojom::PageVisibilityState::kPrerender; request->render_frame_id = render_frame_id_; request->is_main_frame = is_main_frame_; request->allow_download = allow_download_; request->transition_type = transition_type_; request->service_worker_provider_id = service_worker_provider_id_; request->originated_from_service_worker = originated_from_service_worker_; request->initiated_in_secure_context = initiated_in_secure_context_; request->attach_same_site_cookies = attach_same_site_cookies_; } } // namespace content
613
605
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 #include <atomic> #include "test_macros.h" template <typename T> constexpr bool test() { [[maybe_unused]] constexpr T a; static_assert(std::is_nothrow_constructible_v<T>); ASSERT_NOEXCEPT(T{}); return true; } struct throwing { throwing() {} }; struct trivial { int a; }; void test() { static_assert(test<std::atomic<bool>>()); static_assert(test<std::atomic<int>>()); static_assert(test<std::atomic<int*>>()); static_assert(test<std::atomic<trivial>>()); static_assert(test<std::atomic_flag>()); static_assert(!std::is_nothrow_constructible_v<std::atomic<throwing>>); ASSERT_NOT_NOEXCEPT(std::atomic<throwing>{}); }
351
777
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/engine_impl/cycle/test_util.h" #include <map> namespace syncer { namespace test_util { void SimulateGetEncryptionKeyFailed( ModelTypeSet requsted_types, sync_pb::GetUpdatesCallerInfo::GetUpdatesSource source, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_get_key_result( SERVER_RESPONSE_VALIDATION_FAILED); cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); } void SimulateConfigureSuccess( ModelTypeSet requsted_types, sync_pb::GetUpdatesCallerInfo::GetUpdatesSource source, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_get_key_result(SYNCER_OK); cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); } void SimulateConfigureFailed( ModelTypeSet requsted_types, sync_pb::GetUpdatesCallerInfo::GetUpdatesSource source, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_get_key_result(SYNCER_OK); cycle->mutable_status_controller()->set_last_download_updates_result( SERVER_RETURN_TRANSIENT_ERROR); } void SimulateConfigureConnectionFailure( ModelTypeSet requsted_types, sync_pb::GetUpdatesCallerInfo::GetUpdatesSource source, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_get_key_result(SYNCER_OK); cycle->mutable_status_controller()->set_last_download_updates_result( NETWORK_CONNECTION_UNAVAILABLE); } void SimulateNormalSuccess(ModelTypeSet requested_types, NudgeTracker* nudge_tracker, SyncCycle* cycle) { cycle->mutable_status_controller()->set_commit_result(SYNCER_OK); cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); } void SimulateDownloadUpdatesFailed(ModelTypeSet requested_types, NudgeTracker* nudge_tracker, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_download_updates_result( SERVER_RETURN_TRANSIENT_ERROR); } void SimulateCommitFailed(ModelTypeSet requested_types, NudgeTracker* nudge_tracker, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_get_key_result(SYNCER_OK); cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); cycle->mutable_status_controller()->set_commit_result( SERVER_RETURN_TRANSIENT_ERROR); } void SimulateConnectionFailure(ModelTypeSet requested_types, NudgeTracker* nudge_tracker, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_download_updates_result( NETWORK_CONNECTION_UNAVAILABLE); } void SimulatePollSuccess(ModelTypeSet requested_types, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); } void SimulatePollFailed(ModelTypeSet requested_types, SyncCycle* cycle) { cycle->mutable_status_controller()->set_last_download_updates_result( SERVER_RETURN_TRANSIENT_ERROR); } void SimulateThrottledImpl(SyncCycle* cycle, const base::TimeDelta& delta) { cycle->mutable_status_controller()->set_last_download_updates_result( SERVER_RETURN_THROTTLED); cycle->delegate()->OnThrottled(delta); } void SimulateTypesThrottledImpl(SyncCycle* cycle, ModelTypeSet types, const base::TimeDelta& delta) { cycle->mutable_status_controller()->set_commit_result(SYNCER_OK); cycle->delegate()->OnTypesThrottled(types, delta); } void SimulatePartialFailureImpl(SyncCycle* cycle, ModelTypeSet types) { cycle->mutable_status_controller()->set_commit_result(SYNCER_OK); cycle->delegate()->OnTypesBackedOff(types); } void SimulatePollIntervalUpdateImpl(ModelTypeSet requested_types, SyncCycle* cycle, const base::TimeDelta& new_poll) { SimulatePollSuccess(requested_types, cycle); cycle->delegate()->OnReceivedLongPollIntervalUpdate(new_poll); } void SimulateSessionsCommitDelayUpdateImpl(ModelTypeSet requested_types, NudgeTracker* nudge_tracker, SyncCycle* cycle, const base::TimeDelta& new_delay) { SimulateNormalSuccess(requested_types, nudge_tracker, cycle); std::map<ModelType, base::TimeDelta> delay_map; delay_map[SESSIONS] = new_delay; cycle->delegate()->OnReceivedCustomNudgeDelays(delay_map); } void SimulateGuRetryDelayCommandImpl(SyncCycle* cycle, base::TimeDelta delay) { cycle->mutable_status_controller()->set_last_download_updates_result( SYNCER_OK); cycle->delegate()->OnReceivedGuRetryDelay(delay); } } // namespace test_util } // namespace syncer
2,126
633
package com.itranswarp; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfiguration { @Value("${spring.application.name:iTranswarp}") public String name; @Value("${spring.profiles.active:native}") public String profiles; }
100
392
<gh_stars>100-1000 /* * Counter. * This class implements a thread-safe counter. */ #include "concurrent/threads/synchronization/counter.hh" namespace concurrent { namespace threads { namespace synchronization { /* * Constructor. * Initialize the counter with value zero. */ counter::counter() : _value(0), _value_mutex() { } /* * Constructor. * Initialize the counter with the specified value. */ counter::counter(unsigned long n) : _value(n), _value_mutex() { } /* * Copy constructor. * Create a new counter with the same value. */ counter::counter(const counter& c) : _value(c.get()), _value_mutex() { } /* * Destructor. */ counter::~counter() { /* do nothing */ } /* * Get the counter value. */ unsigned long counter::get() const { _value_mutex.lock(); unsigned long n = _value; _value_mutex.unlock(); return n; } /* * Set the counter value. */ void counter::set(unsigned long n) { _value_mutex.lock(); _value = n; _value_mutex.unlock(); } /* * Increment the counter and return the new value. */ unsigned long counter::increment(unsigned long inc) { _value_mutex.lock(); _value += inc; unsigned long n = _value; _value_mutex.unlock(); return n; } /* * Decrement the counter and return the new value. * A decrement by more than the counter value sets the counter to zero. */ unsigned long counter::decrement(unsigned long dec) { _value_mutex.lock(); if (_value > dec) _value -= dec; else _value = 0; unsigned long n = _value; _value_mutex.unlock(); return n; } } /* namespace synchronization */ } /* namespace threads */ } /* namespace concurrent */
578
4,126
<gh_stars>1000+ #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Plugin.h" cPlugin::cPlugin(const AString & a_FolderName) : m_Status(cPluginManager::psDisabled), m_Name(a_FolderName), m_Version(0), m_FolderName(a_FolderName) { } cPlugin::~cPlugin() { LOGD("Destroying plugin \"%s\".", m_Name.c_str()); } void cPlugin::Unload(void) { auto pm = cPluginManager::Get(); pm->RemovePluginCommands(this); pm->RemovePluginConsoleCommands(this); pm->RemoveHooks(this); OnDisable(); m_Status = cPluginManager::psUnloaded; m_LoadError.clear(); } AString cPlugin::GetLocalFolder(void) const { return "Plugins" + cFile::GetPathSeparator() + m_FolderName; } void cPlugin::SetLoadError(const AString & a_LoadError) { m_Status = cPluginManager::psError; m_LoadError = a_LoadError; }
334
1,510
<reponame>julien-faye/drill<filename>exec/java-exec/src/test/java/org/apache/drill/exec/physical/resultSet/project/TestTupleProjection.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.drill.exec.physical.resultSet.project; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.apache.drill.categories.RowSetTests; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.common.types.Types; import org.apache.drill.exec.physical.resultSet.project.RequestedTuple.TupleProjectionType; import org.apache.drill.exec.physical.rowSet.RowSetTestUtils; import org.apache.drill.exec.record.metadata.ColumnMetadata; import org.apache.drill.exec.record.metadata.MetadataUtils; import org.apache.drill.test.BaseTest; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test the projection list parser: parses a list of SchemaPath * items into a detailed structure, handling duplicate or overlapping * items. Special cases the select-all (SELECT *) and select none * (SELECT COUNT(*)) cases. * <p> * These tests should verify everything about (runtime) projection * parsing; the only bits not tested here is that which is * inherently specific to some use case. */ @Category(RowSetTests.class) public class TestTupleProjection extends BaseTest { private static final ColumnMetadata NORMAL_COLUMN = MetadataUtils.newScalar("a", Types.required(MinorType.INT)); private static final ColumnMetadata UNPROJECTED_COLUMN = MetadataUtils.newScalar("bar", Types.required(MinorType.INT)); private static final ColumnMetadata SPECIAL_COLUMN = MetadataUtils.newScalar("a", Types.required(MinorType.INT)); private static final ColumnMetadata UNPROJECTED_SPECIAL_COLUMN = MetadataUtils.newScalar("bar", Types.required(MinorType.INT)); static { SPECIAL_COLUMN.setBooleanProperty(ColumnMetadata.EXCLUDE_FROM_WILDCARD, true); UNPROJECTED_SPECIAL_COLUMN.setBooleanProperty(ColumnMetadata.EXCLUDE_FROM_WILDCARD, true); } /** * Null map means everything is projected */ @Test public void testProjectionAll() { RequestedTuple projSet = Projections.parse(null); assertSame(TupleProjectionType.ALL, projSet.type()); assertTrue(projSet.isProjected("foo")); assertTrue(projSet.isProjected(NORMAL_COLUMN)); assertFalse(projSet.isProjected(SPECIAL_COLUMN)); assertTrue(projSet.projections().isEmpty()); assertFalse(projSet.isEmpty()); } /** * SELECT * means everything is projected */ @Test public void testWildcard() { RequestedTuple projSet = Projections.parse(RowSetTestUtils.projectAll()); assertSame(TupleProjectionType.ALL, projSet.type()); assertTrue(projSet.isProjected("foo")); assertNull(projSet.get("foo")); assertTrue(projSet.isProjected(NORMAL_COLUMN)); assertFalse(projSet.isProjected(SPECIAL_COLUMN)); assertEquals(1, projSet.projections().size()); assertFalse(projSet.isEmpty()); } /** * Test an empty projection which occurs in a * SELECT COUNT(*) query. * Empty list means nothing is projected. */ @Test public void testProjectionNone() { RequestedTuple projSet = Projections.parse(new ArrayList<SchemaPath>()); assertSame(TupleProjectionType.NONE, projSet.type()); assertFalse(projSet.isProjected("foo")); assertFalse(projSet.isProjected(NORMAL_COLUMN)); assertFalse(projSet.isProjected(SPECIAL_COLUMN)); assertTrue(projSet.projections().isEmpty()); assertTrue(projSet.isEmpty()); } /** * Simple non-map columns */ @Test public void testProjectionSimple() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a", "b", "c")); assertSame(TupleProjectionType.SOME, projSet.type()); assertTrue(projSet.isProjected("a")); assertTrue(projSet.isProjected("b")); assertTrue(projSet.isProjected("c")); assertFalse(projSet.isProjected("d")); assertTrue(projSet.isProjected(NORMAL_COLUMN)); assertTrue(projSet.isProjected(SPECIAL_COLUMN)); assertFalse(projSet.isProjected(UNPROJECTED_COLUMN)); assertFalse(projSet.isProjected(UNPROJECTED_SPECIAL_COLUMN)); List<RequestedColumn> cols = projSet.projections(); assertEquals(3, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isSimple()); assertFalse(a.isArray()); assertFalse(a.isTuple()); assertFalse(projSet.isEmpty()); } /** * The projection set does not enforce uniqueness. */ @Test public void testSimpleDups() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a", "b", "a")); assertSame(TupleProjectionType.SOME, projSet.type()); assertEquals(2, projSet.projections().size()); assertEquals(2, ((RequestedColumnImpl) projSet.get("a")).refCount()); } /** * Whole-map projection (note, fully projected maps are * identical to projected simple columns at this level of * abstraction.) */ @Test public void testProjectionWholeMap() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("map")); assertSame(TupleProjectionType.SOME, projSet.type()); assertTrue(projSet.isProjected("map")); assertFalse(projSet.isProjected("another")); RequestedTuple mapProj = projSet.mapProjection("map"); assertNotNull(mapProj); assertSame(TupleProjectionType.ALL, mapProj.type()); assertTrue(mapProj.isProjected("foo")); RequestedTuple anotherProj = projSet.mapProjection("another"); assertNotNull(anotherProj); assertSame(TupleProjectionType.NONE, anotherProj.type()); assertFalse(anotherProj.isProjected("anyCol")); } /** * Selected map projection, multiple levels, full projection * at leaf level. */ @Test public void testProjectionMapSubset() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("map.a", "map.b", "map.map2.x")); assertSame(TupleProjectionType.SOME, projSet.type()); // Map itself is projected and has a map qualifier assertTrue(projSet.isProjected("map")); // Map: an explicit map at top level RequestedTuple mapProj = projSet.mapProjection("map"); assertSame(TupleProjectionType.SOME, projSet.type()); assertTrue(mapProj.isProjected("a")); assertTrue(mapProj.isProjected("b")); assertTrue(mapProj.isProjected("map2")); assertFalse(mapProj.isProjected("bogus")); // Map b: an implied nested map assertTrue(mapProj.get("b").isSimple()); RequestedTuple bMapProj = mapProj.mapProjection("b"); assertNotNull(bMapProj); assertSame(TupleProjectionType.ALL, bMapProj.type()); assertTrue(bMapProj.isProjected("foo")); // Map2, an nested map, has an explicit projection RequestedTuple map2Proj = mapProj.mapProjection("map2"); assertNotNull(map2Proj); assertSame(TupleProjectionType.SOME, map2Proj.type()); assertTrue(map2Proj.isProjected("x")); assertFalse(map2Proj.isProjected("bogus")); } /** * Project both a map member and the entire map. */ @Test public void testProjectionMapAndSimple() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("map.a", "map")); RequestedTuple mapProj = projSet.mapProjection("map"); assertSame(TupleProjectionType.ALL, mapProj.type()); assertTrue(mapProj.isProjected("a")); assertTrue(mapProj.isProjected("b")); } /** * Project both an entire map and a map member. */ @Test public void testProjectionSimpleAndMap() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("map", "map.a")); RequestedTuple mapProj = projSet.mapProjection("map"); assertSame(TupleProjectionType.ALL, mapProj.type()); assertTrue(mapProj.isProjected("a")); assertTrue(mapProj.isProjected("b")); } /** * Project both a map member and the entire map. */ @Test public void testProjectionMapAndWildcard() { // Built up by hand because "map.*" is not valid Drill // expression syntax. List<SchemaPath> projCols = new ArrayList<>(); projCols.add(SchemaPath.getCompoundPath("map", "a")); projCols.add(SchemaPath.getCompoundPath("map", SchemaPath.DYNAMIC_STAR)); RequestedTuple projSet = Projections.parse(projCols); RequestedTuple mapProj = projSet.mapProjection("map"); assertSame(TupleProjectionType.ALL, mapProj.type()); assertTrue(mapProj.isProjected("a")); assertTrue(mapProj.isProjected("b")); } /** * Project both an entire map and a map member. */ @Test public void testProjectionWildcardAndMap() { List<SchemaPath> projCols = new ArrayList<>(); projCols.add(SchemaPath.getCompoundPath("map", SchemaPath.DYNAMIC_STAR)); projCols.add(SchemaPath.getCompoundPath("map", "a")); RequestedTuple projSet = Projections.parse(projCols); RequestedTuple mapProj = projSet.mapProjection("map"); assertSame(TupleProjectionType.ALL, mapProj.type()); assertTrue(mapProj.isProjected("a")); assertTrue(mapProj.isProjected("b")); } @Test public void testMapDetails() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a.b.c", "a.c", "d")); List<RequestedColumn> cols = projSet.projections(); assertEquals(2, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertFalse(a.isSimple()); assertFalse(a.isArray()); assertTrue(a.isTuple()); // a{} assertNotNull(a.tuple()); List<RequestedColumn> aMembers = a.tuple().projections(); assertEquals(2, aMembers.size()); // a.b RequestedColumn a_b = aMembers.get(0); assertEquals("b", a_b.name()); assertTrue(a_b.isTuple()); // a.b{} assertNotNull(a_b.tuple()); List<RequestedColumn> a_bMembers = a_b.tuple().projections(); assertEquals(1, a_bMembers.size()); // a.b.c assertEquals("c", a_bMembers.get(0).name()); assertTrue(a_bMembers.get(0).isSimple()); // a.c assertEquals("c", aMembers.get(1).name()); assertTrue(aMembers.get(1).isSimple()); // d assertEquals("d", cols.get(1).name()); assertTrue(cols.get(1).isSimple()); } /** * Duplicate column names are merged for projection. */ @Test public void testMapDups() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a.b", "a.c", "a.b")); RequestedTuple aMap = projSet.mapProjection("a"); assertEquals(2, aMap.projections().size()); assertEquals(2, ((RequestedColumnImpl) aMap.get("b")).refCount()); } @Test public void testArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[1]", "a[3]")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isArray()); assertEquals(1, a.arrayDims()); assertFalse(a.isSimple()); assertFalse(a.isTuple()); assertTrue(a.hasIndexes()); boolean indexes[] = a.indexes(); assertNotNull(indexes); assertEquals(4, indexes.length); assertFalse(indexes[0]); assertTrue(indexes[1]); assertFalse(indexes[2]); assertTrue(indexes[3]); } @Test public void testMultiDimArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[0][1][2]", "a[2][3]")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isArray()); // Dimension count is the maximum seen. assertEquals(3, a.arrayDims()); assertFalse(a.isSimple()); assertFalse(a.isTuple()); boolean[] indexes = a.indexes(); assertNotNull(indexes); assertEquals(3, indexes.length); assertTrue(indexes[0]); assertFalse(indexes[1]); assertTrue(indexes[2]); } /** * Duplicate array entries are allowed to handle the * use case of a[1], a[1].z. Each element is reported once; * the project operator will create copies as needed. */ @Test public void testArrayDupsIgnored() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[1]", "a[3]", "a[1]", "a[3].z")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isArray()); boolean indexes[] = a.indexes(); assertNotNull(indexes); assertEquals(4, indexes.length); assertFalse(indexes[0]); assertTrue(indexes[1]); assertFalse(indexes[2]); assertTrue(indexes[3]); } @Test public void testArrayAndSimple() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[1]", "a")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isArray()); assertNull(a.indexes()); } @Test public void testSimpleAndArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a", "a[1]")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); assertEquals("a", a.name()); assertTrue(a.isArray()); assertFalse(a.hasIndexes()); assertNull(a.indexes()); } @Test // Drill syntax does not support map arrays public void testMapArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[1].x")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); // Column acts like an array assertTrue(a.isArray()); assertTrue(a.hasIndexes()); assertEquals(1, a.arrayDims()); // And the column acts like a map assertTrue(a.isTuple()); RequestedTuple aProj = a.tuple(); assertSame(TupleProjectionType.SOME, aProj.type()); assertTrue(aProj.isProjected("x")); assertFalse(aProj.isProjected("y")); } @Test // Drill syntax does not support map arrays public void testMap2DArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("a[1][2].x")); List<RequestedColumn> cols = projSet.projections(); assertEquals(1, cols.size()); RequestedColumn a = cols.get(0); // Column acts like an array assertTrue(a.isArray()); assertTrue(a.hasIndexes()); // Note that the multiple dimensions are inferred only through // the multiple levels of qualifiers. // And the column acts like a map assertTrue(a.isTuple()); RequestedTuple aProj = a.tuple(); assertSame(TupleProjectionType.SOME, aProj.type()); assertTrue(aProj.isProjected("x")); assertFalse(aProj.isProjected("y")); } /** * Projection does not enforce semantics; it just report what it * sees. This allows cases such as m.a and m[0], which might mean * that m is a map array, m.a wants an array of a-member values, and m[0] * wants the first map in the array. Not clear Drill actually supports * these cases, however. */ @Test public void testArrayAndMap() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("m.a", "m[0]")); RequestedColumn m = projSet.get("m"); assertTrue(m.isArray()); assertEquals(1, m.arrayDims()); assertTrue(m.isTuple()); assertTrue(m.tuple().isProjected("a")); assertFalse(m.tuple().isProjected("b")); } @Test public void testMapAndArray() { RequestedTuple projSet = Projections.parse( RowSetTestUtils.projectList("m[0]", "m.a")); RequestedColumn m = projSet.get("m"); assertTrue(m.isArray()); assertEquals(1, m.arrayDims()); assertTrue(m.isTuple()); assertTrue(m.tuple().isProjected("a")); // m[0] requests the entire tuple assertTrue(m.tuple().isProjected("b")); } }
6,407
310
<reponame>dreeves/usesthis { "name": "PlayStation", "description": "A gaming console.", "url": "https://en.wikipedia.org/wiki/PlayStation_(console)" }
57
726
package org.landy.business.identify.component.enums; /** * 查询结果类型 * @author landyl * @create 2:55 PM 09/10/2018 */ public enum IdentificationResultType { SINGLE, MULTI, NO_MATCH, ; }
100
852
import FWCore.ParameterSet.Config as cms HLTOverallSummary = cms.EDAnalyzer("DQMOfflineHLTEventInfoClient", verbose = cms.untracked.bool(False) ) HLTOverallCertSeq = cms.Sequence(HLTOverallSummary)
92
852
<filename>GeneratorInterface/PyquenInterface/src/PyquenGeneratorFilter.cc #include "GeneratorInterface/PyquenInterface/interface/PyquenHadronizer.h"
48
2,151
/* * Copyright 2010 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.typography.font.sfntly.table.core; import com.google.typography.font.sfntly.Font.MacintoshEncodingId; import com.google.typography.font.sfntly.Font.PlatformId; import com.google.typography.font.sfntly.Font.WindowsEncodingId; import com.google.typography.font.sfntly.data.ReadableFontData; import com.google.typography.font.sfntly.data.WritableFontData; import com.google.typography.font.sfntly.table.Header; import com.google.typography.font.sfntly.table.SubTableContainerTable; import com.google.typography.font.sfntly.table.core.CMap.CMapFormat; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; /** * A CMap table. * * @author <NAME> */ public final class CMapTable extends SubTableContainerTable implements Iterable<CMap> { /** * The .notdef glyph. */ public static final int NOTDEF = 0; /** * Offsets to specific elements in the underlying data. These offsets are relative to the * start of the table or the start of sub-blocks within the table. */ enum Offset { version(0), numTables(2), encodingRecordStart(4), // offsets relative to the encoding record encodingRecordPlatformId(0), encodingRecordEncodingId(2), encodingRecordOffset(4), encodingRecordSize(8), format(0), // Format 0: Byte encoding table format0Format(0), format0Length(2), format0Language(4), format0GlyphIdArray(6), // Format 2: High-byte mapping through table format2Format(0), format2Length(2), format2Language(4), format2SubHeaderKeys(6), format2SubHeaders(518), // offset relative to the subHeader structure format2SubHeader_firstCode(0), format2SubHeader_entryCount(2), format2SubHeader_idDelta(4), format2SubHeader_idRangeOffset(6), format2SubHeader_structLength(8), // Format 4: Segment mapping to delta values format4Format(0), format4Length(2), format4Language(4), format4SegCountX2(6), format4SearchRange(8), format4EntrySelector(10), format4RangeShift(12), format4EndCount(14), format4FixedSize(16), // format 6: Trimmed table mapping format6Format(0), format6Length(2), format6Language(4), format6FirstCode(6), format6EntryCount(8), format6GlyphIdArray(10), // Format 8: mixed 16-bit and 32-bit coverage format8Format(0), format8Length(4), format8Language(8), format8Is32(12), format8nGroups(8204), format8Groups(8208), // ofset relative to the group structure format8Group_startCharCode(0), format8Group_endCharCode(4), format8Group_startGlyphId(8), format8Group_structLength(12), // Format 10: Trimmed array format10Format(0), format10Length(4), format10Language(8), format10StartCharCode(12), format10NumChars(16), format10Glyphs(20), // Format 12: Segmented coverage format12Format(0), format12Length(4), format12Language(8), format12nGroups(12), format12Groups(16), format12Groups_structLength(12), // offsets within the group structure format12_startCharCode(0), format12_endCharCode(4), format12_startGlyphId(8), // Format 13: Last Resort Font format13Format(0), format13Length(4), format13Language(8), format13nGroups(12), format13Groups(16), format13Groups_structLength(12), // offsets within the group structure format13_startCharCode(0), format13_endCharCode(4), format13_glyphId(8), // TODO: finish support for format 14 // Format 14: Unicode Variation Sequences format14Format(0), format14Length(2); final int offset; private Offset(int offset) { this.offset = offset; } } public static final class CMapId implements Comparable<CMapId> { public static final CMapId WINDOWS_BMP = CMapId.getInstance(PlatformId.Windows.value(), WindowsEncodingId.UnicodeUCS2.value()); public static final CMapId WINDOWS_UCS4 = CMapId.getInstance(PlatformId.Windows.value(), WindowsEncodingId.UnicodeUCS4.value()); public static final CMapId MAC_ROMAN = CMapId.getInstance(PlatformId.Macintosh.value(), MacintoshEncodingId.Roman.value()); public static CMapId getInstance(int platformId, int encodingId) { return new CMapId(platformId, encodingId); } private final int platformId; private final int encodingId; private CMapId(int platformId, int encodingId) { this.platformId = platformId; this.encodingId = encodingId; } public int platformId() { return this.platformId; } public int encodingId() { return this.encodingId; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CMapId)) { return false; } CMapId otherKey = (CMapId) obj; if ((otherKey.platformId == this.platformId) && (otherKey.encodingId == this.encodingId)) { return true; } return false; } @Override public int hashCode() { return this.platformId << 8 | this.encodingId; } @Override public int compareTo(CMapId o) { return this.hashCode() - o.hashCode(); } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("pid = "); b.append(this.platformId); b.append(", eid = "); b.append(this.encodingId); return b.toString(); } } /** * Constructor. * * @param header header for the table * @param data data for the table */ private CMapTable(Header header, ReadableFontData data) { super(header, data); } /** * Get the table version. * * @return table version */ public int version() { return this.data.readUShort(Offset.version.offset); } /** * Gets the number of cmaps within the CMap table. * * @return the number of cmaps */ public int numCMaps() { return this.data.readUShort(Offset.numTables.offset); } /** * Returns the index of the cmap with the given CMapId in the table or -1 if a cmap with the * CMapId does not exist in the table. * * @param id the id of the cmap to get the index for; this value cannot be null * @return the index of the cmap in the table or -1 if the cmap with the CMapId does not exist in * the table */ // TODO Modify the iterator to be index-based and used here public int getCmapIndex(CMapId id) { for (int index = 0; index < numCMaps(); index++) { if (id.equals(cmapId(index))) { return index; } } return -1; } /** * Gets the offset in the table data for the encoding record for the cmap with * the given index. The offset is from the beginning of the table. * * @param index the index of the cmap * @return offset in the table data */ private static int offsetForEncodingRecord(int index) { return Offset.encodingRecordStart.offset + index * Offset.encodingRecordSize.offset; } /** * Gets the cmap id for the cmap with the given index. * * @param index the index of the cmap * @return the cmap id */ public CMapId cmapId(int index) { return CMapId.getInstance(platformId(index), encodingId(index)); } /** * Gets the platform id for the cmap with the given index. * * @param index the index of the cmap * @return the platform id */ public int platformId(int index) { return this.data.readUShort( Offset.encodingRecordPlatformId.offset + CMapTable.offsetForEncodingRecord(index)); } /** * Gets the encoding id for the cmap with the given index. * * @param index the index of the cmap * @return the encoding id */ public int encodingId(int index) { return this.data.readUShort( Offset.encodingRecordEncodingId.offset + CMapTable.offsetForEncodingRecord(index)); } /** * Gets the offset in the table data for the cmap table with the given index. * The offset is from the beginning of the table. * * @param index the index of the cmap * @return the offset in the table data */ public int offset(int index) { return this.data.readULongAsInt( Offset.encodingRecordOffset.offset + CMapTable.offsetForEncodingRecord(index)); } /** * Gets an iterator over all of the cmaps within this CMapTable. */ @Override public Iterator<CMap> iterator() { return new CMapIterator(); } /** * Gets an iterator over the cmaps within this CMap table using the provided * filter to select the cmaps returned. * * @param filter the filter * @return iterator over cmaps */ public Iterator<CMap> iterator(CMapFilter filter) { return new CMapIterator(filter); } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); sb.append(" = { "); for (int i = 0; i < this.numCMaps(); i++) { CMap cmap; try { cmap = this.cmap(i); } catch (IOException e) { continue; } sb.append("[0x"); sb.append(Integer.toHexString(this.offset(i))); sb.append(" = "); sb.append(cmap); if (i < this.numCMaps() - 1) { sb.append("], "); } else { sb.append("]"); } } sb.append(" }"); return sb.toString(); } /** * A filter on cmaps. */ public interface CMapFilter { /** * Test on whether the cmap is acceptable or not. * * @param cmapId the id of the cmap * @return true if the cmap is acceptable; false otherwise */ boolean accept(CMapId cmapId); } private class CMapIterator implements Iterator<CMap> { private int tableIndex = 0; private CMapFilter filter; private CMapIterator() { // no filter - iterate over all cmap subtables } private CMapIterator(CMapFilter filter) { this.filter = filter; } @Override public boolean hasNext() { if (this.filter == null) { if (this.tableIndex < numCMaps()) { return true; } return false; } for (; this.tableIndex < numCMaps(); this.tableIndex++) { if (filter.accept(cmapId(this.tableIndex))) { return true; } } return false; } @Override public CMap next() { if (!hasNext()) { throw new NoSuchElementException(); } try { return cmap(this.tableIndex++); } catch (IOException e) { NoSuchElementException newException = new NoSuchElementException("Error during the creation of the CMap."); newException.initCause(e); throw newException; } } @Override public void remove() { throw new UnsupportedOperationException("Cannot remove a CMap table from an existing font."); } } /** * Gets the cmap for the given index. * * @param index the index of the cmap * @return the cmap at the index * @throws IOException */ public CMap cmap(int index) throws IOException { CMap.Builder<? extends CMap> builder = CMapTable.Builder.cmapBuilder(this.readFontData(), index); return builder.build(); } /** * Gets the cmap with the given ids if it exists. * * @param platformId the platform id * @param encodingId the encoding id * @return the cmap if it exists; null otherwise */ public CMap cmap(int platformId, int encodingId) { return cmap(CMapId.getInstance(platformId, encodingId)); } public CMap cmap(final CMapId cmapId) { Iterator<CMap> cmapIter = this.iterator(new CMapFilter() { @Override public boolean accept(CMapId foundCMapId) { if (cmapId.equals(foundCMapId)) { return true; } return false; } }); // can only be one cmap for each set of ids if (cmapIter.hasNext()) { return cmapIter.next(); } return null; } /** * CMap Table Builder. * */ public static class Builder extends SubTableContainerTable.Builder<CMapTable> { private int version = 0; // TODO(stuartg): make a CMapTable constant private Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders; /** * Creates a new builder using the header information and data provided. * * @param header the header information * @param data the data holding the table * @return a new builder */ public static Builder createBuilder(Header header, WritableFontData data) { return new Builder(header, data); } /** * Constructor. * * @param header the table header * @param data the writable data for the table */ protected Builder(Header header, WritableFontData data) { super(header, data); } /** * Constructor. This constructor will try to maintain the data as readable * but if editing operations are attempted then a writable copy will be made * the readable data will be discarded. * * @param header the table header * @param data the readable data for the table */ protected Builder(Header header, ReadableFontData data) { super(header, data); } /** * Static factory method to create a cmap subtable builder. * * @param data the data for the whole cmap table * @param index the index of the cmap subtable within the table * @return the cmap subtable requested if it exists; null otherwise */ protected static CMap.Builder<? extends CMap> cmapBuilder(ReadableFontData data, int index) { if (index < 0 || index > numCMaps(data)) { throw new IndexOutOfBoundsException( "CMap table is outside the bounds of the known tables."); } // read from encoding records int platformId = data.readUShort( Offset.encodingRecordPlatformId.offset + CMapTable.offsetForEncodingRecord(index)); int encodingId = data.readUShort( Offset.encodingRecordEncodingId.offset + CMapTable.offsetForEncodingRecord(index)); int offset = data.readULongAsInt( Offset.encodingRecordOffset.offset + CMapTable.offsetForEncodingRecord(index)); CMapId cmapId = CMapId.getInstance(platformId, encodingId); CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(data, offset, cmapId); return builder; } @Override protected void subDataSet() { this.cmapBuilders = null; super.setModelChanged(false); } private void initialize(ReadableFontData data) { this.cmapBuilders = new /*TreeMap*/ HashMap<CMapId, CMap.Builder<? extends CMap>>(); int numCMaps = numCMaps(data); for (int i = 0; i < numCMaps; i++) { CMap.Builder<? extends CMap> cmapBuilder = cmapBuilder(data, i); cmapBuilders.put(cmapBuilder.cmapId(), cmapBuilder); } } private Map<CMapId, CMap.Builder<? extends CMap>> getCMapBuilders() { if (this.cmapBuilders != null) { return this.cmapBuilders; } this.initialize(this.internalReadData()); this.setModelChanged(); return this.cmapBuilders; } private static int numCMaps(ReadableFontData data) { if (data == null) { return 0; } return data.readUShort(Offset.numTables.offset); } public int numCMaps() { return this.getCMapBuilders().size(); } @Override protected int subDataSizeToSerialize() { if (this.cmapBuilders == null || this.cmapBuilders.size() == 0) { return 0; } boolean variable = false; int size = CMapTable.Offset.encodingRecordStart.offset + this.cmapBuilders.size() * CMapTable.Offset.encodingRecordSize.offset; // calculate size of each table for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) { int cmapSize = b.subDataSizeToSerialize(); size += Math.abs(cmapSize); variable |= cmapSize <= 0; } return variable ? -size : size; } @Override protected boolean subReadyToSerialize() { if (this.cmapBuilders == null) { return false; } // check each table for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) { if (!b.subReadyToSerialize()) { return false; } } return true; } @Override protected int subSerialize(WritableFontData newData) { int size = newData.writeUShort(CMapTable.Offset.version.offset, this.version()); size += newData.writeUShort(CMapTable.Offset.numTables.offset, this.cmapBuilders.size()); int indexOffset = size; size += this.cmapBuilders.size() * CMapTable.Offset.encodingRecordSize.offset; for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) { // header entry indexOffset += newData.writeUShort(indexOffset, b.platformId()); indexOffset += newData.writeUShort(indexOffset, b.encodingId()); indexOffset += newData.writeULong(indexOffset, size); // cmap size += b.subSerialize(newData.slice(size)); } return size; } @Override protected CMapTable subBuildTable(ReadableFontData data) { return new CMapTable(this.header(), data); } // public building API public Iterator<? extends CMap.Builder<? extends CMap>> iterator() { return this.getCMapBuilders().values().iterator(); } public int version() { return this.version; } public void setVersion(int version) { this.version = version; } /** * Gets a new cmap builder for this cmap table. The new cmap builder will be * for the cmap id specified and initialized with the data given. The data * will be copied and the original data will not be modified. * * @param cmapId the id for the new cmap builder * @param data the data to copy for the new cmap builder * @return a new cmap builder initialized with the cmap id and a copy of the * data * @throws IOException */ public CMap.Builder<? extends CMap> newCMapBuilder(CMapId cmapId, ReadableFontData data) throws IOException { WritableFontData wfd = WritableFontData.createWritableFontData(data.size()); data.copyTo(wfd); CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(wfd, 0, cmapId); Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders(); cmapBuilders.put(cmapId, builder); return builder; } public CMap.Builder<? extends CMap> newCMapBuilder(CMapId cmapId, CMapFormat cmapFormat) { CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(cmapFormat, cmapId); Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders(); cmapBuilders.put(cmapId, builder); return builder; } public CMap.Builder<? extends CMap> cmapBuilder(CMapId cmapId) { Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders(); return cmapBuilders.get(cmapId); } } }
7,484
713
<gh_stars>100-1000 package org.infinispan.server.router.integration; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.util.concurrent.CompletionStages.join; import java.lang.invoke.MethodHandles; import java.net.InetAddress; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.ServerConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.Util; import org.infinispan.rest.RestServer; import org.infinispan.server.router.Router; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.rest.RestRouteSource; import org.infinispan.server.router.routes.rest.RestServerRouteDestination; import org.infinispan.server.router.utils.RestTestingUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class RestEndpointRouterTest { private RestServer restServer1; private RestServer restServer2; private Router router; private RestClient restClient; @BeforeClass public static void beforeClass() { TestResourceTracker.testStarted(MethodHandles.lookup().lookupClass().toString()); } @AfterClass public static void afterClass() { TestResourceTracker.testFinished(MethodHandles.lookup().lookupClass().toString()); } @After public void tearDown() { Util.close(restClient); router.stop(); restServer1.getCacheManager().stop(); restServer1.stop(); restServer2.getCacheManager().stop(); restServer2.stop(); } /** * In this scenario we create 2 REST servers, each one with different REST Path: <ul> <li>REST1 - * http://127.0.0.1:8080/rest/rest1</li> <li>REST2 - http://127.0.0.1:8080/rest/rest2</li> </ul> * <p> * The router should match requests based on path and redirect them to proper server. */ @Test public void shouldRouteToProperRestServerBasedOnPath() { //given restServer1 = RestTestingUtil.createDefaultRestServer("rest1", "default"); restServer2 = RestTestingUtil.createDefaultRestServer("rest2", "default"); RestServerRouteDestination rest1Destination = new RestServerRouteDestination("rest1", restServer1); RestRouteSource rest1Source = new RestRouteSource("rest1"); Route<RestRouteSource, RestServerRouteDestination> routeToRest1 = new Route<>(rest1Source, rest1Destination); RestServerRouteDestination rest2Destination = new RestServerRouteDestination("rest2", restServer2); RestRouteSource rest2Source = new RestRouteSource("rest2"); Route<RestRouteSource, RestServerRouteDestination> routeToRest2 = new Route<>(rest2Source, rest2Destination); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .rest() .port(8080) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest1) .add(routeToRest2); router = new Router(routerConfigurationBuilder.build()); router.start(); int port = router.getRouter(EndpointRouter.Protocol.REST).get().getPort(); //when ServerConfigurationBuilder builder = new RestClientConfigurationBuilder().addServer().host("127.0.0.1").port(port); restClient = RestClient.forConfiguration(builder.build()); RestRawClient rawClient = restClient.raw(); String path1 = "/rest/rest1/v2/caches/default/test"; String path2 = "/rest/rest2/v2/caches/default/test"; join(rawClient.putValue(path1, emptyMap(), "rest1", TEXT_PLAIN_TYPE)); join(rawClient.putValue(path2, emptyMap(), "rest2", TEXT_PLAIN_TYPE)); String valueReturnedFromRest1 = join(rawClient.get(path1)).getBody(); String valueReturnedFromRest2 = join(rawClient.get(path2)).getBody(); //then assertThat(valueReturnedFromRest1).isEqualTo("rest1"); assertThat(valueReturnedFromRest2).isEqualTo("rest2"); } }
1,673
3,395
import polars as pl def test_sort_by_bools() -> None: # tests dispatch df = pl.DataFrame( { "foo": [1, 2, 3], "bar": [6.0, 7.0, 8.0], "ham": ["a", "b", "c"], } ) out = df.with_column((pl.col("foo") % 2 == 1).alias("foo_odd")).sort( by=["foo", "foo_odd"] ) assert out.shape == (3, 4)
205
715
<filename>Source/Controls/Lua/As.h /* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCONTROLSLUAAS_H #define ROCKETCONTROLSLUAAS_H /* These are helper functions to fill up the Element.As table with types that are able to be casted */ #include <Rocket/Core/Lua/LuaType.h> #include <Rocket/Core/Lua/lua.hpp> #include <Rocket/Core/Element.h> namespace Rocket { namespace Controls { namespace Lua { //Helper function for the controls, so that the types don't have to define individual functions themselves // to fill the Elements.As table template<typename ToType> int CastFromElementTo(lua_State* L) { Rocket::Core::Element* ele = Rocket::Core::Lua::LuaType<Rocket::Core::Element>::check(L,1); LUACHECKOBJ(ele); Rocket::Core::Lua::LuaType<ToType>::push(L,(ToType*)ele,false); return 1; } //Adds to the Element.As table the name of the type, and the function to use to cast template<typename T> void AddCastFunctionToElementAsTable(lua_State* L) { int top = lua_gettop(L); lua_getglobal(L,"Element"); lua_getfield(L,-1,"As"); if(!lua_isnoneornil(L,-1)) { lua_pushcfunction(L,Rocket::Controls::Lua::CastFromElementTo<T>); lua_setfield(L,-2,Rocket::Core::Lua::GetTClassName<T>()); } lua_settop(L,top); //pop "As" and "Element" } } } } #endif
825
399
<gh_stars>100-1000 /* * StripedLock.java * * Copyright (c) 2013 <NAME> * * This source code is subject to terms and conditions of the Apache License, Version 2.0. * A copy of the license can be found in the License.html file at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. */ package com.strobel.concurrent; import com.strobel.annotations.NotNull; import java.lang.reflect.Array; public abstract class StripedLock<T> { private static final int LOCK_COUNT = 256; @SuppressWarnings("ProtectedField") protected final T[] locks; private int _lockAllocationCounter; @SuppressWarnings({ "unchecked", "OverridableMethodCallDuringObjectConstruction" }) protected StripedLock(final Class<T> lockType) { locks = (T[]) Array.newInstance(lockType, LOCK_COUNT); for (int i = 0; i < locks.length; i++) { locks[i] = createLock(); } } @NotNull public T allocateLock() { return locks[allocateLockIndex()]; } public int allocateLockIndex() { return (_lockAllocationCounter = (_lockAllocationCounter + 1) % LOCK_COUNT); } @NotNull protected abstract T createLock(); public abstract void lock(final int index); public abstract void unlock(final int index); }
549
849
/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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 <sstream> #include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GAuthenticationFailure.h" #include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GCommonDefs.h" namespace magma5g { AuthenticationFailureMsg::AuthenticationFailureMsg(){}; AuthenticationFailureMsg::~AuthenticationFailureMsg(){}; // Decoding Authentication Failure Message and its IEs int AuthenticationFailureMsg::DecodeAuthenticationFailureMsg( AuthenticationFailureMsg* auth_failure, uint8_t* buffer, uint32_t len) { uint32_t decoded = 0; int decoded_result = 0; CHECK_PDU_POINTER_AND_LENGTH_DECODER( buffer, AUTHENTICATION_FAILURE_MINIMUM_LENGTH, len); if ((decoded_result = auth_failure->extended_protocol_discriminator .DecodeExtendedProtocolDiscriminatorMsg( &auth_failure->extended_protocol_discriminator, 0, buffer + decoded, len - decoded)) < 0) return decoded_result; else decoded += decoded_result; if ((decoded_result = auth_failure->spare_half_octet.DecodeSpareHalfOctetMsg( &auth_failure->spare_half_octet, 0, buffer + decoded, len - decoded)) < 0) return decoded_result; else decoded += decoded_result; if ((decoded_result = auth_failure->sec_header_type.DecodeSecurityHeaderTypeMsg( &auth_failure->sec_header_type, 0, buffer + decoded, len - decoded)) < 0) return decoded_result; else decoded += decoded_result; if ((decoded_result = auth_failure->message_type.DecodeMessageTypeMsg( &auth_failure->message_type, 0, buffer + decoded, len - decoded)) < 0) return decoded_result; else decoded += decoded_result; if ((decoded_result = auth_failure->m5gmm_cause.DecodeM5GMMCauseMsg( &auth_failure->m5gmm_cause, 0, buffer + decoded, len - decoded)) < 0) return decoded_result; else decoded += decoded_result; while (decoded < len) { uint8_t ieiDecoded = *(buffer + decoded); switch (ieiDecoded) { case AUTHENTICATION_FAILURE_PARAMETER_IEI_AUTH_CHALLENGE: if ((decoded_result = auth_failure->auth_failure_ie.DecodeM5GAuthenticationFailureIE( &auth_failure->auth_failure_ie, AUTHENTICATION_FAILURE_PARAMETER_IEI_AUTH_CHALLENGE, buffer + decoded, len - decoded)) < 0) return decoded_result; decoded += decoded_result; break; default: return TLV_UNEXPECTED_IEI; } } return decoded; } // Encoding Authentication Failure Message and its IEs int AuthenticationFailureMsg::EncodeAuthenticationFailureMsg( AuthenticationFailureMsg* auth_failure, uint8_t* buffer, uint32_t len) { uint32_t encoded = 0; int encodedresult = 0; CHECK_PDU_POINTER_AND_LENGTH_ENCODER( buffer, AUTHENTICATION_FAILURE_MINIMUM_LENGTH, len); if ((encodedresult = auth_failure->extended_protocol_discriminator .EncodeExtendedProtocolDiscriminatorMsg( &auth_failure->extended_protocol_discriminator, 0, buffer + encoded, len - encoded)) < 0) return encodedresult; else encoded += encodedresult; if ((encodedresult = auth_failure->spare_half_octet.EncodeSpareHalfOctetMsg( &auth_failure->spare_half_octet, 0, buffer + encoded, len - encoded)) < 0) return encodedresult; else encoded += encodedresult; if ((encodedresult = auth_failure->sec_header_type.EncodeSecurityHeaderTypeMsg( &auth_failure->sec_header_type, 0, buffer + encoded, len - encoded)) < 0) return encodedresult; else encoded += encodedresult; if ((encodedresult = auth_failure->message_type.EncodeMessageTypeMsg( &auth_failure->message_type, 0, buffer + encoded, len - encoded)) < 0) return encodedresult; else encoded += encodedresult; if ((encodedresult = auth_failure->m5gmm_cause.EncodeM5GMMCauseMsg( &auth_failure->m5gmm_cause, 0, buffer + encoded, len - encoded)) < 0) return encodedresult; else encoded += encodedresult; return encoded; } } // namespace magma5g
1,964
2,392
<reponame>MelvinG24/dust3d // Copyright (c) 2006-2007 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL: https://github.com/CGAL/cgal/blob/v5.1/Algebraic_foundations/include/CGAL/Fraction_traits.h $ // $Id: Fraction_traits.h 0779373 2020-03-26T13:31:46+01:00 Sébastien Loriot // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : <NAME> <<EMAIL>> // // ============================================================================= // TODO: The comments are all original EXACUS comments and aren't adapted. So // they may be wrong now. /*! \file NiX/Fraction_traits.h \brief Defines class NiX::Fraction_traits. Provides dependent types and function objects for all the functions beyond operators with specializations of the \c Fraction_traits<NT> class for each number type. */ #ifndef CGAL_FRACTION_TRAITS_H #define CGAL_FRACTION_TRAITS_H #include <CGAL/tags.h> namespace CGAL { /*! \ingroup NiX_Fraction_traits_spec * \brief Traits class for accessing numerator and denominator.\n * It is a model of the concept TypeTraits. * * This is the default version of NiX::Fraction_traits. * It typedefs NiX::Fraction_traits::Is_decomposable * as Tag_false and all functors to LiS::Null_type. * * \see module NiX_Fraction_traits * \see module NiX_Cofraction_traits */ template <class Type_ > class Fraction_traits { public: typedef Type_ Type; typedef Tag_false Is_fraction; typedef Null_tag Numerator_type; typedef Null_tag Denominator_type; typedef Null_functor Common_factor; typedef Null_functor Decompose; typedef Null_functor Compose; }; } //namespace CGAL #endif // CGAL_FRACTION_TRAITS_H // EOF
660
3,964
<reponame>siposcsaba89/tensorrtx #ifndef TENSORRTX_PSENET_H #define TENSORRTX_PSENET_H #include <memory> #include <vector> #include <chrono> #include <opencv2/opencv.hpp> #include "utils.h" #include "layers.h" class PSENet { public: PSENet(int max_side_len, int min_side_len, float threshold, int num_kernel, int stride); ~PSENet(); ICudaEngine* createEngine(IBuilder* builder, IBuilderConfig* config); void serializeEngine(); void deserializeEngine(); void init(); void inferenceOnce(IExecutionContext& context, float* input, float* output, int input_h, int input_w); void detect(std::string image_path); float* preProcess(cv::Mat image, int& resize_h, int& resize_w, float& ratio_h, float& ratio_w); std::vector<cv::RotatedRect> postProcess(float* origin_output, int resize_h, int resize_w); private: Logger gLogger; std::shared_ptr<nvinfer1::IRuntime> mRuntime; std::shared_ptr<nvinfer1::ICudaEngine> mCudaEngine; std::shared_ptr<nvinfer1::IExecutionContext> mContext; DataType dt = DataType::kFLOAT; const char* input_name_ = "input"; const char* output_name_ = "output"; int max_side_len_ = 1024; int min_side_len_ = 640; float post_threshold_ = 0.9; int num_kernels_ = 6; int stride_ = 4; }; #endif // TENSORRTX_PSENET_H
526
1,545
/** * * 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.bookkeeper.client.api; import org.apache.bookkeeper.common.annotation.InterfaceAudience.Public; import org.apache.bookkeeper.common.annotation.InterfaceStability.Unstable; /** * Builder-style interface to create new ledgers. * * @since 4.6 * @see BookKeeper#newCreateLedgerOp() */ @Public @Unstable public interface CreateAdvBuilder extends OpBuilder<WriteAdvHandle> { /** * Set a fixed ledgerId for the newly created ledger. If no explicit ledgerId is passed a new ledger id will be * assigned automatically. * * @param ledgerId * * @return the builder itself */ CreateAdvBuilder withLedgerId(long ledgerId); }
418
1,884
package us.sosia.video.stream.agent.ui; import java.awt.Dimension; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class VideoDisplayWindow { protected final DoubleVideoPannel videoPannel; protected final JFrame window; public VideoDisplayWindow(String name,Dimension dimension) { super(); this.window = new JFrame(name); this.videoPannel = new DoubleVideoPannel(); this.videoPannel.setPreferredSize(dimension); this.window.add(videoPannel); this.window.pack(); this.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void setVisible(boolean visible) { this.window.setVisible(visible); } public void updateBigVideo(BufferedImage image) { videoPannel.updateBigImage(image); } public void updateSmallVideo(BufferedImage image) { videoPannel.updateSmallImage(image); } public void close(){ window.dispose(); videoPannel.close(); } }
310
764
{"symbol": "MTB18","address": "0x1BCfD19F541eB62c8CFeBE53fe72bf2aFc35A255","overview":{"en": ""},"email": "<EMAIL>","website": "https://ico.costaflores.com/","state": "NORMAL","links": {"blog": "http://wiki.costaflores.com/#all-updates","twitter": "https://twitter.com/MTBCostaflores","telegram": "https://t.me/openvino","github": "https://github.com/OpenVino/MTB18-token-crowdsale-dapp"}}
157
3,212
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.cassandra; import com.datastax.driver.core.Statement; import org.apache.nifi.serialization.record.RecordSchema; import org.apache.nifi.util.Tuple; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; public class PutCassandraRecordUpdateTest { private PutCassandraRecord testSubject; @Mock private RecordSchema schema; @Before public void setUp() { MockitoAnnotations.initMocks(this); testSubject = new PutCassandraRecord(); } @Test public void testGenerateUpdateWithEmptyKeyList() { Stream.of("", ",", ",,,").forEach(updateKeys -> testGenerateUpdate( "keyspace.table", updateKeys, PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("stringField", "newStringValue") ), new IllegalArgumentException("No Update Keys were specified") )); } @Test public void testGenerateUpdateWithMissingKey() { testGenerateUpdate( "keyspace.table", "keyField,missingKeyField", PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("stringField", "newStringValue") ), new IllegalArgumentException("Update key 'missingKeyField' is not present in the record schema") ); } @Test public void testGenerateUpdateWithInvalidUpdateMethod() { testGenerateUpdate( "keyspace.table", "keyField", "invalidUpdateMethod", Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("longField", 15L) ), new IllegalArgumentException("Update Method 'invalidUpdateMethod' is not valid.") ); } @Test public void testGenerateUpdateIncrementString() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("stringField", "15") ), new IllegalArgumentException("Field 'stringField' is not of type Number") ); } @Test public void testGenerateUpdateSimpleTableName() { testGenerateUpdate( "table", "keyField1", PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField1", 1), new Tuple<>("stringField", "newStringValue") ), "UPDATE table SET stringField='newStringValue' WHERE keyField1=1;" ); } @Test public void testGenerateUpdateKeyspacedTableName() { testGenerateUpdate( "keyspace.table", "keyField1", PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField1", 1), new Tuple<>("stringField", "newStringValue") ), "UPDATE keyspace.table SET stringField='newStringValue' WHERE keyField1=1;" ); } @Test public void testGenerateUpdateMultipleKeys() { testGenerateUpdate( "keyspace.table", "keyField1,keyField2,keyField3", PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField1", 1), new Tuple<>("keyField2", "key2"), new Tuple<>("keyField3", 123L), new Tuple<>("stringField", "newStringValue") ), "UPDATE keyspace.table SET stringField='newStringValue' WHERE keyField1=1 AND keyField2='key2' AND keyField3=123;" ); } @Test public void testGenerateUpdateIncrementLong() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("longField", 15L) ), "UPDATE keyspace.table SET longField=longField+15 WHERE keyField=1;" ); } @Test public void testGenerateUpdateDecrementLong() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.DECR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("longField", 15L) ), "UPDATE keyspace.table SET longField=longField-15 WHERE keyField=1;" ); } @Test public void testGenerateUpdateIncrementInteger() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("integerField", 15) ), "UPDATE keyspace.table SET integerField=integerField+15 WHERE keyField=1;" ); } @Test public void testGenerateUpdateIncrementFloat() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("floatField", 15.05F) ), "UPDATE keyspace.table SET floatField=floatField+15 WHERE keyField=1;" ); } @Test public void testGenerateUpdateIncrementDouble() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("doubleField", 15.05D) ), "UPDATE keyspace.table SET doubleField=doubleField+15 WHERE keyField=1;" ); } @Test public void testGenerateUpdateSetMultipleValues() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.SET_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("stringField", "newStringValue"), new Tuple<>("integerField", 15), new Tuple<>("longField", 67L) ), "UPDATE keyspace.table SET stringField='newStringValue',integerField=15,longField=67 WHERE keyField=1;" ); } @Test public void testGenerateUpdateIncrementMultipleValues() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.INCR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("integerField", 15), new Tuple<>("longField", 67L) ), "UPDATE keyspace.table SET integerField=integerField+15,longField=longField+67 WHERE keyField=1;" ); } @Test public void testGenerateUpdateDecrementMultipleValues() { testGenerateUpdate( "keyspace.table", "keyField", PutCassandraRecord.DECR_TYPE.getValue(), Arrays.asList( new Tuple<>("keyField", 1), new Tuple<>("integerField", 15), new Tuple<>("longField", 67L) ), "UPDATE keyspace.table SET integerField=integerField-15,longField=longField-67 WHERE keyField=1;" ); } private void testGenerateUpdate(String table, String updateKeys, String updateMethod, List<Tuple<String, Object>> records, String expected) { Map<String, Object> recordContentMap = records.stream() .collect(Collectors.toMap(Tuple::getKey, Tuple::getValue)); List<String> fieldNames = records.stream().map(Tuple::getKey).collect(Collectors.toList()); when(schema.getFieldNames()).thenReturn(fieldNames); Statement actual = testSubject.generateUpdate(table, schema, updateKeys, updateMethod, recordContentMap); assertEquals(expected, actual.toString()); } private <E extends Exception> void testGenerateUpdate(String table, String updateKeys, String updateMethod, List<Tuple<String, Object>> records, E expected) { Map<String, Object> recordContentMap = records.stream() .collect(Collectors.toMap(Tuple::getKey, Tuple::getValue)); List<String> fieldNames = records.stream().map(Tuple::getKey).collect(Collectors.toList()); when(schema.getFieldNames()).thenReturn(fieldNames); try { testSubject.generateUpdate("keyspace.table", schema, updateKeys, updateMethod, recordContentMap); fail(); } catch (Exception e) { assertEquals(expected.getClass(), e.getClass()); assertEquals(expected.getMessage(), e.getMessage()); } } }
5,264
317
// // NodeInfo.h // drafter // // Created by <NAME> on 20-10-2005. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #ifndef DRAFTER_NODEINFO_H #define DRAFTER_NODEINFO_H #include "BlueprintSourcemap.h" #include <algorithm> #define NODE_INFO(from, member) from.node->member, from.sourceMap->member #define MAKE_NODE_INFO(from, member) MakeNodeInfo(NODE_INFO(from, member)) namespace drafter { /** * For returned values, * used eg. for Assets. There is duality directly "blueprint value" * vs value generated via JSON Rendering (aka. boutique) * * For boutique is used (<generated JSON>, NullSourceMap) * * There is NodeInfo<> constructor accepting directly NodeInfoByValue<> for simplified conversion */ template <typename T> struct NodeInfoByValue { T first; const snowcrash::SourceMap<T>* second; }; template <typename T> struct NodeInfo { typedef T NodeType; typedef NodeInfo<T> Type; typedef snowcrash::SourceMap<T> SourceMapType; const NodeType* node; const SourceMapType* sourceMap; bool empty; NodeInfo(const NodeType* node, const SourceMapType* sourceMap) : node(node), sourceMap(sourceMap), empty(false) { } explicit NodeInfo(const NodeInfoByValue<T>& node) : node(&node.first), sourceMap(node.second ? node.second : NodeInfo<T>::NullSourceMap()), empty(false) { } NodeInfo() : node(Type::NullNode()), sourceMap(Type::NullSourceMap()), empty(true) {} NodeInfo<T>(const NodeInfo<T>& other) = default; NodeInfo<T>(NodeInfo<T>&& other) = default; NodeInfo<T>& operator=(const NodeInfo<T>& other) = default; NodeInfo<T>& operator=(NodeInfo<T>&& other) = default; static const NodeType* NullNode() { static NodeType nullNode; return &nullNode; } static const SourceMapType* NullSourceMap() { static SourceMapType nullSourceMap; return &nullSourceMap; } bool isNull() const { return empty; } }; template <typename T> NodeInfo<T> MakeNodeInfo(const T& node, const snowcrash::SourceMap<T>& sourceMap) { return NodeInfo<T>(&node, &sourceMap); } template <typename T> NodeInfo<T> MakeNodeInfo(const T* node, const snowcrash::SourceMap<T>* sourceMap) { return NodeInfo<T>(node, sourceMap); } template <typename T> NodeInfo<T> MakeNodeInfoWithoutSourceMap(const T& node) { return NodeInfo<T>(&node, NodeInfo<T>::NullSourceMap()); } template <typename ResultType, typename Collection1, typename Collection2, typename BinOp> ResultType Zip(const Collection1& collection1, const Collection2& collection2, const BinOp& Combinator) { ResultType result; std::transform( collection1.begin(), collection1.end(), collection2.begin(), std::back_inserter(result), Combinator); return result; } template <typename T> struct NodeInfoCollection : public std::vector<NodeInfo<typename T::value_type> > { typedef NodeInfoCollection<T> SelfType; typedef std::vector<NodeInfo<typename T::value_type> > CollectionType; template <typename U> static NodeInfo<U> MakeNodeInfo(const U& node, const snowcrash::SourceMap<U>& sourceMap) { return NodeInfo<U>(&node, &sourceMap); } NodeInfoCollection(const NodeInfo<T>& nodeInfo) { const T& collection = *nodeInfo.node; const snowcrash::SourceMap<T>& sourceMaps = *nodeInfo.sourceMap; if (collection.size() == sourceMaps.collection.size()) { CollectionType nodes = Zip<CollectionType>( collection, sourceMaps.collection, NodeInfoCollection::MakeNodeInfo<typename T::value_type>); std::copy(nodes.begin(), nodes.end(), std::back_inserter(*this)); } else { std::transform(collection.begin(), collection.end(), std::back_inserter(*this), MakeNodeInfoWithoutSourceMap<typename T::value_type>); } } NodeInfoCollection(const T& collection, const snowcrash::SourceMap<T>& sourceMaps) { if (collection.size() == sourceMaps.collection.size()) { CollectionType nodes = Zip<CollectionType>( collection, sourceMaps.collection, NodeInfoCollection::MakeNodeInfo<typename T::value_type>); std::copy(nodes.begin(), nodes.end(), std::back_inserter(*this)); } else { std::transform(collection.begin(), collection.end(), std::back_inserter(*this), MakeNodeInfoWithoutSourceMap<typename T::value_type>); } } }; } #endif // #ifndef DRAFTER_NODEINFO_H
2,191
353
<gh_stars>100-1000 package org.nutz.apidoc.demo.module; import org.nutz.lang.util.NutMap; import org.nutz.mvc.adaptor.JsonAdaptor; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.IocBy; import org.nutz.mvc.annotation.Modules; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.UrlMappingBy; import org.nutz.mvc.ioc.provider.ComboIocProvider; import org.nutz.plugins.apidoc.ApidocUrlMapping; import org.nutz.plugins.apidoc.annotation.Api; import org.nutz.plugins.apidoc.annotation.ApiMatchMode; import org.nutz.plugins.apidoc.annotation.Manual; @Modules @IocBy(type = ComboIocProvider.class, args = { "*anno", "org.nutz.apidoc", "*async" }) @Ok("json") @UrlMappingBy(ApidocUrlMapping.class) @Manual(name="测试",description="scadcew",author="Kerbores",email="<EMAIL>",homePage="http://www.baidu.com",copyRight="️ &copy; 2017 Kerbores All Right XXX") @Api(author="kkk",name="KKK",match=ApiMatchMode.ALL) public class MainModule { @At @Api(name = "index",description="我是描述字段") public NutMap index() { return NutMap.NEW().addv("msg", "Hello Nutz!"); } @At @AdaptBy(type = JsonAdaptor.class) public NutMap name(NutMap data) { return NutMap.NEW().addv("msg", "Hello Nutz!"); } }
531
1,127
import argparse from pathlib import Path from utils import ( create_content, add_content_below, process_notebook_name, verify_notebook_name, split_notebooks_into_sections, ) from consts import ( artifacts_link, binder_template, blacklisted_extensions, notebooks_docs, notebooks_path, no_binder_template, repo_directory, repo_name, repo_owner, rst_template, section_names, ) from notebook import Notebook from section import Section from glob import glob from lxml import html from jinja2 import Template from urllib.request import urlretrieve from requests import get import os class NbTravisDownloader: @staticmethod def download_from_jenkins(path: str = notebooks_path, artifact_link: str = artifacts_link): """Function for downloading files from jenkins artifacts :param path: path where notebooks files will be placed, defaults to notebooks_path :type path: str, optional :param artifact_link: link of notebooks artifacts rst files, defaults to artifacts_link :type artifact_link: str, optional """ def is_directory(path: str) -> bool: """Helper fuction for checking whether path leads to subdirectory :param path: Path to traversed file or directory :type path: str :return: Returns True if path leads to directory, otherwise False :rtype: bool """ return path[-1] == '/' and path != '../' def traverse(path: Path, link: str, blacklisted_extensions: list = blacklisted_extensions): """Traverse recursively to download all directories with their subfolders, within given link. :param path: Path to directory that file will be saved to. :type path: Path :param link: Link to hosted resources :type link: str """ path.mkdir(exist_ok=True) page = get(link, verify=False).content tree = html.fromstring(page) # retrieve all links on page returning their content tree = tree.xpath('//a[@*]/@href') files = map(str, tree) for file in files: if is_directory(file): traverse(path.joinpath(file), link + file) elif len(Path(file).suffix) > 0 and Path(file).suffix not in blacklisted_extensions: urlretrieve(link + file, path.joinpath(file)) traverse(Path(path), artifact_link) class NbProcessor: def __init__(self, nb_path: str = notebooks_path): self.nb_path = nb_path notebooks = [ Notebook( name=process_notebook_name(notebook), path=notebook, ) for notebook in os.listdir(self.nb_path) if verify_notebook_name(notebook) ] notebooks = split_notebooks_into_sections(notebooks) self.rst_data = { "sections": [ Section(name=section_name, notebooks=section_notebooks) for section_name, section_notebooks in zip(section_names, notebooks) ] } self.binder_data = { "owner": repo_owner, "repo": repo_name, "folder": repo_directory, } def fetch_binder_list(self, file_format: str = 'txt') -> list: """Funtion that fetches list of notebooks with binder buttons :param file_format: Format of file containing list of notebooks with button. Defaults to 'txt' :type file_format: str :return: List of notebooks conaining binder buttons :rtype: list """ list_of_buttons = glob(f"{self.nb_path}/*.{file_format}") if list_of_buttons: with open(list_of_buttons[0]) as file: list_of_buttons = file.read().splitlines() return list_of_buttons else: return [] def add_binder(self, buttons_list: list, template_with_binder: str = binder_template, template_without_binder: str = no_binder_template): """Function working as an example how to add binder button to existing rst files :param buttons_list: List of notebooks that work on Binder. :type buttons_list: list :param template_with_binder: Template of button added to rst file if Binder is available. Defaults to binder_template. :type template_with_binder: str :param template_without_binder: Template of button added to rst file if Binder isn't available. Defaults to no_binder_template. :type template_without_binder: str :raises FileNotFoundError: In case of failure of adding content, error will appear """ for notebook in [ nb for nb in os.listdir(self.nb_path) if verify_notebook_name(nb) ]: if '-'.join(notebook.split('-')[:-2]) in buttons_list: button_text = create_content( template_with_binder, self.binder_data, notebook) if not add_content_below(button_text, f"{self.nb_path}/{notebook}"): raise FileNotFoundError("Unable to modify file") else: button_text = create_content( template_without_binder, self.binder_data, notebook) if not add_content_below(button_text, f"{self.nb_path}/{notebook}"): raise FileNotFoundError("Unable to modify file") def render_rst(self, path: str = notebooks_docs, template: str = rst_template): """Rendering rst file for all notebooks :param path: Path to notebook main rst file. Defaults to notebooks_docs. :type path: str :param template: Template for default rst page. Defaults to rst_template. :type template: str """ with open(path, "w+") as nb_file: nb_file.writelines(Template(template).render(self.rst_data)) def main(): parser = argparse.ArgumentParser() parser.add_argument('outdir', type=Path) args = parser.parse_args() outdir = args.outdir outdir.mkdir(parents=True, exist_ok=True) # Step 2. Run default pipeline for downloading NbTravisDownloader.download_from_jenkins(outdir) # Step 3. Run processing on downloaded file nbp = NbProcessor(outdir) buttons_list = nbp.fetch_binder_list('txt') nbp.add_binder(buttons_list) nbp.render_rst(outdir.joinpath(notebooks_docs)) if __name__ == '__main__': main()
2,768
668
<filename>fineract-provider/src/main/java/org/apache/fineract/portfolio/collateralmanagement/api/ClientCollateralManagementApiResource.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.fineract.portfolio.collateralmanagement.api; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; import org.apache.fineract.infrastructure.codes.service.CodeValueReadPlatformService; import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; import org.apache.fineract.portfolio.collateralmanagement.data.ClientCollateralManagementData; import org.apache.fineract.portfolio.collateralmanagement.data.LoanCollateralTemplateData; import org.apache.fineract.portfolio.collateralmanagement.domain.ClientCollateralManagement; import org.apache.fineract.portfolio.collateralmanagement.service.ClientCollateralManagementReadPlatformService; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Path("/clients/{clientId}/collaterals") @Component @Scope("singleton") @Tag(name = "Client Collateral Management", description = "Client Collateral Management is for managing collateral operations") public class ClientCollateralManagementApiResource { private final DefaultToApiJsonSerializer<ClientCollateralManagement> apiJsonSerializerService; private final DefaultToApiJsonSerializer<ClientCollateralManagementData> apiJsonSerializerDataService; private final DefaultToApiJsonSerializer<LoanCollateralTemplateData> apiJsonSerializerForLoanCollateralTemplateService; private final ApiRequestParameterHelper apiRequestParameterHelper; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final PlatformSecurityContext context; private final CodeValueReadPlatformService codeValueReadPlatformService; private final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService; private static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>( Arrays.asList("name", "quantity", "total", "totalCollateral", "clientId", "loanTransactionData")); public ClientCollateralManagementApiResource(final DefaultToApiJsonSerializer<ClientCollateralManagement> apiJsonSerializerService, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context, final CodeValueReadPlatformService codeValueReadPlatformService, final ClientCollateralManagementReadPlatformService clientCollateralManagementReadPlatformService, final DefaultToApiJsonSerializer<ClientCollateralManagementData> apiJsonSerializerDataService, final DefaultToApiJsonSerializer<LoanCollateralTemplateData> apiJsonSerializerForLoanCollateralTemplateService) { this.apiJsonSerializerService = apiJsonSerializerService; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; this.context = context; this.codeValueReadPlatformService = codeValueReadPlatformService; this.clientCollateralManagementReadPlatformService = clientCollateralManagementReadPlatformService; this.apiJsonSerializerDataService = apiJsonSerializerDataService; this.apiJsonSerializerForLoanCollateralTemplateService = apiJsonSerializerForLoanCollateralTemplateService; } @GET @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get Clients Collateral Products", description = "Get Collateral Product of a Client") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.GetClientCollateralManagementsResponse.class)))) }) public String getClientCollateral(@PathParam("clientId") @Parameter(description = "clientId") final Long clientId, @Context final UriInfo uriInfo, @QueryParam("prodId") @Parameter(description = "prodId") final Long prodId) { this.context.authenticatedUser() .validateHasReadPermission(CollateralManagementJsonInputParams.CLIENT_COLLATERAL_PRODUCT_READ_PERMISSION.getValue()); List<ClientCollateralManagementData> collateralProductList = null; collateralProductList = this.clientCollateralManagementReadPlatformService.getClientCollaterals(clientId, prodId); return this.apiJsonSerializerDataService.serialize(collateralProductList); } @GET @Path("{clientCollateralId}") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get Client Collateral Data", description = "Get Client Collateral Data") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.GetClientCollateralManagementsResponse.class))) }) public String getClientCollateralData(@PathParam("clientId") @Parameter(description = "clientId") final Long clientId, @PathParam("clientCollateralId") @Parameter(description = "clientCollateralId") final Long collateralId) { this.context.authenticatedUser() .validateHasReadPermission(CollateralManagementJsonInputParams.CLIENT_COLLATERAL_PRODUCT_READ_PERMISSION.getValue()); ClientCollateralManagementData clientCollateralManagementData = this.clientCollateralManagementReadPlatformService .getClientCollateralManagementData(collateralId); return this.apiJsonSerializerDataService.serialize(clientCollateralManagementData); } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Get Client Collateral Template", description = "Get Client Collateral Template") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.GetLoanCollateralManagementTemplate.class)))) }) public String getClientCollateralTemplate(@Context final UriInfo uriInfo, @PathParam("clientId") @Parameter(description = "clientId") final Long clientId) { List<LoanCollateralTemplateData> loanCollateralTemplateDataList = this.clientCollateralManagementReadPlatformService .getLoanCollateralTemplate(clientId); return this.apiJsonSerializerForLoanCollateralTemplateService.serialize(loanCollateralTemplateDataList); } @POST @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Add New Collateral For a Client", description = "Add New Collateral For a Client") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.PostClientCollateralRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.PostClientCollateralResponse.class))) }) public String addCollateral(@PathParam("clientId") @Parameter(description = "clientId") final Long clientId, @Parameter(hidden = true) String apiJsonRequestBody) { final CommandWrapper commandWrapper = new CommandWrapperBuilder().addClientCollateralProduct(clientId).withJson(apiJsonRequestBody) .build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.apiJsonSerializerService.serialize(commandProcessingResult); } @PUT @Path("{collateralId}") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Update New Collateral of a Client", description = "Update New Collateral of a Client") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.PutClientCollateralRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.PutClientCollateralResponse.class))) }) public String updateCollateral(@PathParam("clientId") @Parameter(description = "clientId") final Long clientId, @PathParam("collateralId") @Parameter(description = "collateralId") final Long collateralId, @Parameter(hidden = true) String apiJsonRequestBody) { final CommandWrapper commandWrapper = new CommandWrapperBuilder().updateClientCollateralProduct(clientId, collateralId) .withJson(apiJsonRequestBody).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.apiJsonSerializerService.serialize(commandProcessingResult); } @DELETE @Path("{collateralId}") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Operation(summary = "Delete Client Collateral", description = "Delete Client Collateral") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ClientCollateralManagementApiResourceSwagger.DeleteClientCollateralResponse.class))) }) public String deleteCollateral(@PathParam("clientId") @Parameter(description = "clientId") final Long clientId, @PathParam("collateralId") @Parameter(description = "collateralId") final Long collateralId) { final CommandWrapper commandWrapper = new CommandWrapperBuilder().deleteClientCollateralProduct(collateralId, clientId).build(); final CommandProcessingResult commandProcessingResult = this.commandsSourceWritePlatformService.logCommandSource(commandWrapper); return this.apiJsonSerializerService.serialize(commandProcessingResult); } }
3,863
406
/*************************************************************************** * include/stxxl/bits/containers/btree/iterator.h * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2006 <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) **************************************************************************/ #ifndef STXXL_CONTAINERS_BTREE_ITERATOR_HEADER #define STXXL_CONTAINERS_BTREE_ITERATOR_HEADER #include <iterator> #include <cassert> #include <stxxl/bits/verbose.h> #include <stxxl/bits/common/types.h> STXXL_BEGIN_NAMESPACE namespace btree { template <class BTreeType> class iterator_map; template <class BTreeType> class btree_iterator; template <class BTreeType> class btree_const_iterator; template <class KeyType, class DataType, class KeyCmp, unsigned LogNElem, class BTreeType> class normal_leaf; template <class BTreeType> class btree_iterator_base { public: typedef BTreeType btree_type; typedef typename btree_type::leaf_bid_type bid_type; typedef typename btree_type::value_type value_type; typedef typename btree_type::reference reference; typedef typename btree_type::const_reference const_reference; typedef std::bidirectional_iterator_tag iterator_category; typedef typename btree_type::difference_type difference_type; typedef typename btree_type::leaf_type leaf_type; friend class iterator_map<btree_type>; template <class KeyType, class DataType, class KeyCmp, unsigned LogNElem, class AnyBTreeType> friend class normal_leaf; template <class AnyBTreeType> friend bool operator == (const btree_iterator<AnyBTreeType>& a, const btree_const_iterator<AnyBTreeType>& b); template <class AnyBTreeType> friend bool operator != (const btree_iterator<AnyBTreeType>& a, const btree_const_iterator<AnyBTreeType>& b); protected: btree_type* btree; bid_type bid; unsigned_type pos; btree_iterator_base() { STXXL_VERBOSE3("btree_iterator_base def construct addr=" << this); make_invalid(); } btree_iterator_base(btree_type* _btree, const bid_type& _bid, unsigned_type _pos) : btree(_btree), bid(_bid), pos(_pos) { STXXL_VERBOSE3("btree_iterator_base parameter construct addr=" << this); btree->m_iterator_map.register_iterator(*this); } void make_invalid() { btree = NULL; pos = 0; } btree_iterator_base(const btree_iterator_base& obj) { STXXL_VERBOSE3("btree_iterator_base constr from" << (&obj) << " to " << this); btree = obj.btree; bid = obj.bid; pos = obj.pos; if (btree) btree->m_iterator_map.register_iterator(*this); } btree_iterator_base& operator = (const btree_iterator_base& obj) { STXXL_VERBOSE3("btree_iterator_base copy from" << (&obj) << " to " << this); if (&obj != this) { if (btree) btree->m_iterator_map.unregister_iterator(*this); btree = obj.btree; bid = obj.bid; pos = obj.pos; if (btree) btree->m_iterator_map.register_iterator(*this); } return *this; } reference non_const_access() { assert(btree); leaf_type* leaf = btree->m_leaf_cache.get_node(bid); assert(leaf); return (reference)((*leaf)[pos]); } const_reference const_access() const { assert(btree); leaf_type const* leaf = btree->m_leaf_cache.get_const_node(bid); assert(leaf); return (reference)((*leaf)[pos]); } bool operator == (const btree_iterator_base& obj) const { return bid == obj.bid && pos == obj.pos && btree == obj.btree; } bool operator != (const btree_iterator_base& obj) const { return bid != obj.bid || pos != obj.pos || btree != obj.btree; } btree_iterator_base & increment() { assert(btree); bid_type cur_bid = bid; const leaf_type* leaf = btree->m_leaf_cache.get_const_node(bid, true); assert(leaf); leaf->increment_iterator(*this); btree->m_leaf_cache.unfix_node(cur_bid); return *this; } btree_iterator_base & decrement() { assert(btree); bid_type cur_bid = bid; const leaf_type* leaf = btree->m_leaf_cache.get_const_node(bid, true); assert(leaf); leaf->decrement_iterator(*this); btree->m_leaf_cache.unfix_node(cur_bid); return *this; } public: virtual ~btree_iterator_base() { STXXL_VERBOSE3("btree_iterator_base deconst " << this); if (btree) btree->m_iterator_map.unregister_iterator(*this); } }; template <class BTreeType> class btree_iterator : public btree_iterator_base<BTreeType> { public: typedef BTreeType btree_type; typedef typename btree_type::leaf_bid_type bid_type; typedef typename btree_type::value_type value_type; typedef typename btree_type::reference reference; typedef typename btree_type::const_reference const_reference; typedef typename btree_type::pointer pointer; typedef btree_iterator_base<btree_type> base_type; template <class KeyType, class DataType, class KeyCmp, unsigned LogNElem, class AnyBTreeType> friend class normal_leaf; using base_type::non_const_access; btree_iterator() : base_type() { } btree_iterator(const btree_iterator& obj) : base_type(obj) { } btree_iterator& operator = (const btree_iterator& obj) { base_type::operator = (obj); return *this; } reference operator * () { return non_const_access(); } pointer operator -> () { return &(non_const_access()); } bool operator == (const btree_iterator& obj) const { return base_type::operator == (obj); } bool operator != (const btree_iterator& obj) const { return base_type::operator != (obj); } btree_iterator& operator ++ () { assert(*this != base_type::btree->end()); base_type::increment(); return *this; } btree_iterator& operator -- () { base_type::decrement(); return *this; } btree_iterator operator ++ (int) { assert(*this != base_type::btree->end()); btree_iterator result(*this); base_type::increment(); return result; } btree_iterator operator -- (int) { btree_iterator result(*this); base_type::decrement(); return result; } private: btree_iterator(btree_type* _btree, const bid_type& _bid, unsigned_type _pos) : base_type(_btree, _bid, _pos) { } }; template <class BTreeType> class btree_const_iterator : public btree_iterator_base<BTreeType> { public: typedef btree_iterator<BTreeType> iterator; typedef BTreeType btree_type; typedef typename btree_type::leaf_bid_type bid_type; typedef typename btree_type::value_type value_type; typedef typename btree_type::const_reference reference; typedef typename btree_type::const_pointer pointer; typedef btree_iterator_base<btree_type> base_type; template <class KeyType, class DataType, class KeyCmp, unsigned LogNElem, class AnyBTreeType> friend class normal_leaf; using base_type::const_access; btree_const_iterator() : base_type() { } btree_const_iterator(const btree_const_iterator& obj) : base_type(obj) { } btree_const_iterator(const iterator& obj) : base_type(obj) { } btree_const_iterator& operator = (const btree_const_iterator& obj) { base_type::operator = (obj); return *this; } reference operator * () { return const_access(); } pointer operator -> () { return &(const_access()); } bool operator == (const iterator& obj) const { return base_type::operator == (obj); } bool operator != (const iterator& obj) const { return base_type::operator != (obj); } bool operator == (const btree_const_iterator& obj) const { return base_type::operator == (obj); } bool operator != (const btree_const_iterator& obj) const { return base_type::operator != (obj); } btree_const_iterator& operator ++ () { assert(*this != base_type::btree->end()); base_type::increment(); return *this; } btree_const_iterator& operator -- () { base_type::decrement(); return *this; } btree_const_iterator operator ++ (int) { assert(*this != base_type::btree->end()); btree_const_iterator result(*this); base_type::increment(); return result; } btree_const_iterator operator -- (int) { btree_const_iterator result(*this); base_type::decrement(); return result; } private: btree_const_iterator(btree_type* _btree, const bid_type& _bid, unsigned_type _pos) : base_type(_btree, _bid, _pos) { } }; template <class BTreeType> inline bool operator == (const btree_iterator<BTreeType>& a, const btree_const_iterator<BTreeType>& b) { return a.btree_iterator_base<BTreeType>::operator == (b); } template <class BTreeType> inline bool operator != (const btree_iterator<BTreeType>& a, const btree_const_iterator<BTreeType>& b) { return a.btree_iterator_base<BTreeType>::operator != (b); } } // namespace btree STXXL_END_NAMESPACE #endif // !STXXL_CONTAINERS_BTREE_ITERATOR_HEADER
4,349
1,058
/* * Copyright (c) 2017-2019 TIBCO Software 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. See accompanying * LICENSE file. */ package io.snappydata.tools; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Properties; import com.gemstone.gemfire.internal.cache.Status; import com.gemstone.gemfire.internal.shared.ClientSharedUtils; import com.gemstone.gemfire.internal.shared.LauncherBase; import com.sun.jna.Platform; class QuickLauncher extends LauncherBase { private static final String DIR_OPT = "-dir="; private static final String CLASSPATH_OPT = "-classpath="; private static final String HEAP_SIZE_OPT = "-heap-size="; private static final String WAIT_FOR_SYNC_OPT = "-sync="; private static final String PASSWORD_OPT = "-password"; private final String launcherClass; private final boolean isLocator; private Path workingDir; public static void main(String[] args) throws Exception { if (args.length < 2) { throw illegalArgument("QuickLauncher: expected at least two args", args); } String nodeType = args[0]; String action = args[1]; QuickLauncher launch; if (nodeType.equalsIgnoreCase("server")) { launch = new QuickLauncher("SnappyData Server", "snappyserver", "io.snappydata.tools.ServerLauncher", false); } else if (nodeType.equalsIgnoreCase("leader")) { launch = new QuickLauncher("SnappyData Leader", "snappyleader", "io.snappydata.tools.LeaderLauncher", false); // always wait till everything is done for leads launch.waitForData = true; } else if (nodeType.equalsIgnoreCase("locator")) { launch = new QuickLauncher("SnappyData Locator", "snappylocator", "io.snappydata.tools.LocatorLauncher", true); } else { throw illegalArgument("QuickLauncher: unknown node type '" + nodeType + "'", args); } if ("start".equalsIgnoreCase(action)) { System.exit(launch.start(args)); } else if ("stop".equalsIgnoreCase(action)) { System.exit(launch.stop(args)); } else if ("status".equalsIgnoreCase(action)) { launch.status(args); } else { throw illegalArgument("QuickLauncher: unsupported action '" + action + "'", args); } } private QuickLauncher(String displayName, String baseName, String launcherClass, boolean locator) { super(displayName, baseName); this.launcherClass = launcherClass; this.isLocator = locator; // don't wait for diskstore sync by default and go into WAITING state this.waitForData = false; } @Override protected Path getWorkingDirPath() { return this.workingDir; } @Override protected long getDefaultHeapSizeMB(boolean hostData) { return this.isLocator ? 1024L : super.getDefaultHeapSizeMB(hostData); } @Override protected long getDefaultSmallHeapSizeMB(boolean hostData) { return this.isLocator ? 512L : super.getDefaultSmallHeapSizeMB(hostData); } private static IllegalArgumentException illegalArgument(String message, String[] args) { return new IllegalArgumentException(message + " (args=" + java.util.Arrays.toString(args) + ')'); } /** * Configures and spawns a VM that hosts a cache server. The standard output * and error are redirected to file prefixed with "start_". */ private int start(final String[] args) throws IOException, InterruptedException { final ArrayList<String> commandLine = new ArrayList<>(16); final HashMap<String, String> env = new HashMap<>(2); final String snappyHome = System.getenv("SNAPPY_HOME"); if (snappyHome == null || snappyHome.isEmpty()) { throw new IllegalArgumentException("SNAPPY_HOME not set"); } // add java path to command-line first commandLine.add(System.getProperty("java.home") + "/bin/java"); commandLine.add("-server"); try { // https://github.com/airlift/jvmkill is added to libgemfirexd.so // adding agentpath helps kill jvm in case of OOM. kill -9 is not // used as it fails in certain cases if (Platform.isLinux()) { if (Platform.is64Bit()) { String agentPath = snappyHome + "/jars/libgemfirexd64.so"; System.load(agentPath); commandLine.add("-agentpath:" + agentPath); } else { String agentPath = snappyHome + "/jars/libgemfirexd.so"; System.load(agentPath); commandLine.add("-agentpath:" + agentPath); } } else if (Platform.isMac()) { if (Platform.is64Bit()) { String agentPath = snappyHome + "/jars/libgemfirexd64.dylib"; System.load(agentPath); commandLine.add("-agentpath:" + agentPath); } else { String agentPath = snappyHome + "/jars/libgemfirexd.dylib"; System.load(agentPath); commandLine.add("-agentpath:" + agentPath); } } } catch (UnsatisfiedLinkError | SecurityException e) { System.out.println("WARNING: agent not loaded due to " + e + ". Service might not be killed on OutOfMemory. Build jvmkill.c on your platform " + "using build.sh script from source on your platform and replace the library " + "in product jars directory to enable the agent."); } // get the startup options and command-line arguments (JVM arguments etc) HashMap<String, Object> options = getStartOptions(args, snappyHome, commandLine, env); // Complain if a cache server is already running in the specified working directory. // See bug 32574. int state = verifyAndClearStatus(); if (state != Status.SHUTDOWN) { // Returning a status of 10 would indicate the startup scripts to know that an // instance was already running and in healthy state. if (state == Status.RUNNING) { return 10; } // else this will indicate that an instance was there but not in running state. // It can be waiting too ( specially for servers -- for lead it can be standby) // but we can ignore making further differentiation here. return 1; } // add the main class and method commandLine.add(this.launcherClass); commandLine.add("server"); // add default log-file option if not present String logFile = (String)options.get(LOG_FILE); if (logFile == null || logFile.isEmpty()) { // check for log4j settings Properties confProps = ClientSharedUtils.getLog4jConfProperties(snappyHome); if (confProps != null) { // read directly avoiding log4j API usage String rootCategory = confProps.getProperty("log4j.rootCategory"); int commaIndex; if (rootCategory != null && (commaIndex = rootCategory.indexOf(',')) != -1) { String categoryName = rootCategory.substring(commaIndex + 1).trim(); // check for file name property logFile = confProps.getProperty("log4j.appender." + categoryName + ".file"); if (logFile == null || logFile.isEmpty()) { // perhaps it is the console appender String appenderType = confProps.getProperty("log4j.appender." + categoryName); if (appenderType != null && appenderType.contains("ConsoleAppender")) { logFile = this.startLogFileName; } } } } } else { logFile = logFile.substring(LOG_FILE.length() + 2); } if (logFile == null || logFile.isEmpty()) { logFile = this.defaultLogFileName; } options.put(LOG_FILE, "-" + LOG_FILE + '=' + logFile); // add the command options for (Object option : options.values()) { commandLine.add((String)option); } // finally launch the main process assert startLogFileName != null; assert pidFileName != null; final Path startLogFile = this.workingDir.resolve(startLogFileName); final Path pidFile = this.workingDir.resolve(pidFileName); Files.deleteIfExists(startLogFile); Files.deleteIfExists(pidFile); // add command-line to ENV2 StringBuilder fullCommandLine = new StringBuilder(1024); fullCommandLine.append(ENV_MARKER).append('['); Iterator<String> cmds = commandLine.iterator(); while (cmds.hasNext()) { String cmd = cmds.next(); if (cmd.equals("-cp")) { // skip classpath which is already output separately cmds.next(); } else { if (cmd.indexOf(' ') != -1) { // quote the argument fullCommandLine.append('"').append(cmd).append('"'); } else { fullCommandLine.append(cmd); } fullCommandLine.append(' '); } } fullCommandLine.setCharAt(fullCommandLine.length() - 1, ']'); env.put(ENV2, fullCommandLine.toString()); ProcessBuilder process = new ProcessBuilder(commandLine); process.environment().putAll(env); process.directory(this.workingDir.toFile()); process.redirectErrorStream(true); process.redirectOutput(startLogFile.toFile()); process.start(); // change to absolute path for printing to screen if (!Paths.get(logFile).isAbsolute()) { logFile = this.workingDir.resolve(logFile).toString(); } return waitForRunning(logFile); } /** * Stops a node (which is running in a different VM) by setting its status to * {@link Status#SHUTDOWN_PENDING}. Waits for the node to actually shut down * and returns the exit status (0 is for success else failure). */ private int stop(final String[] args) throws IOException { setWorkingDir(args); final Path statusFile = getStatusPath(); int exitStatus = 1; // determine the current state of the node readStatus(false, statusFile); Status status = this.status; if (status != null) { // upon reading the status file, request the Cache Server to shutdown // if it has not already... if (status.state != Status.SHUTDOWN) { // copy server PID and not use own PID; see bug #39707 status = Status.create(this.baseName, Status.SHUTDOWN_PENDING, status.pid, statusFile); status.write(); this.status = status; } // poll the Cache Server for a response to our shutdown request // (passes through if the Cache Server has already shutdown) pollCacheServerForShutdown(statusFile); // after polling, determine the status of the Cache Server one last time // and determine how to exit... if (this.status.state == Status.SHUTDOWN) { System.out.println(MessageFormat.format(LAUNCHER_STOPPED, this.baseName, getHostNameAndDir())); Status.delete(statusFile); exitStatus = 0; } else { System.out.println(MessageFormat.format(LAUNCHER_TIMEOUT_WAITING_FOR_SHUTDOWN, this.baseName, this.hostName, this.status)); } } else if (Files.exists(statusFile)) { throw new IllegalStateException(MessageFormat.format( LAUNCHER_NO_AVAILABLE_STATUS, this.statusName)); } else { System.out.println(MessageFormat.format(LAUNCHER_NO_STATUS_FILE, this.workingDir, this.hostName)); } return exitStatus; } /** * Prints the status of the node running in the configured working directory. */ private void status(final String[] args) throws FileNotFoundException { setWorkingDir(args); final Path statusFile = this.workingDir.resolve(this.statusName); readStatus(true, statusFile); if (args.length > 2 && args[2].equalsIgnoreCase("verbose")) { System.out.println(this.status); } else { System.out.println(this.status.shortStatus()); } } private String getHostNameAndDir() { return workingDir != null ? hostName + '(' + workingDir.getFileName() + ')' : this.hostName; } /** * Get the name, value pairs of start options provided on command-line. * Value is the entire argument including the name and starting hyphen. */ private HashMap<String, Object> getStartOptions(String[] args, String snappyHome, ArrayList<String> commandLine, HashMap<String, String> env) throws FileNotFoundException { StringBuilder classPath = new StringBuilder(); // add the conf directory first classPath.append(snappyHome).append("/conf").append(java.io.File.pathSeparator); // then the default product jars directory classPath.append(snappyHome).append("/jars/*"); final int numArgs = args.length; final LinkedHashMap<String, Object> options = new LinkedHashMap<>(numArgs); final ArrayList<String> vmArgs = new ArrayList<>(2); boolean hostData = !this.isLocator; // skip first two arguments for node type and action for (int i = 2; i < numArgs; i++) { String arg = args[i]; // process special arguments separately if (arg.startsWith(DIR_OPT)) { processDirOption(arg.substring(DIR_OPT.length())); } else if (arg.startsWith(CLASSPATH_OPT)) { classPath.append(java.io.File.pathSeparator) .append(arg.substring(CLASSPATH_OPT.length())); } else if (arg.startsWith(HEAP_SIZE_OPT)) { processHeapSize(arg.substring(HEAP_SIZE_OPT.length()), vmArgs); } else if (arg.startsWith("-J")) { processVMArg(arg.substring(2), vmArgs); } else if (arg.startsWith("-D") || arg.startsWith("-XX:")) { processVMArg(arg, vmArgs); } else if (arg.startsWith(PASSWORD_OPT)) { String pwd; if (arg.length() > PASSWORD_OPT.length()) { // next character must be '=' if (arg.charAt(PASSWORD_OPT.length()) != '=') { throw new IllegalArgumentException( "Unexpected option (should be -password or -password=): " + arg); } pwd = arg.substring(PASSWORD_OPT.length() + 1); } else { pwd = LauncherBase.readPassword("Password: "); } if (pwd != null) { // encryption should be done throughout from source and kept // encrypted throughout in the system (SNAP-1657) env.put(ENV1, ENV_MARKER + pwd); } } else if (arg.startsWith(WAIT_FOR_SYNC_OPT)) { processWaitForSync(arg.substring(WAIT_FOR_SYNC_OPT.length())); } else if (arg.length() > 0 && arg.charAt(0) == '-') { // put rest of the arguments as is int eqIndex = arg.indexOf('='); String key = eqIndex != -1 ? arg.substring(1, eqIndex) : arg.substring(1); options.put(key, arg); if (key.equals(HOST_DATA) && eqIndex != -1) { hostData = !"false".equalsIgnoreCase(arg.substring(eqIndex + 1)); } } else { throw new IllegalArgumentException("Unexpected command-line option: " + arg); } } // set the classpath commandLine.add("-cp"); commandLine.add(classPath.toString()); // set default JVM args commandLine.add("-Djava.awt.headless=true"); // configure commons-logging to use Log4J logging commandLine.add("-Dorg.apache.commons.logging.Log=" + "org.apache.commons.logging.impl.Log4JLogger"); setDefaultVMArgs(options, hostData, commandLine); // add the provided JVM args after the defaults if (!vmArgs.isEmpty()) { commandLine.addAll(vmArgs); } return options; } /** * Extracts working directory configuration from command-line arguments * for stop/status/wait/verbose commands. */ private void setWorkingDir(String[] args) throws FileNotFoundException { String workDir = null; // skip first node type argument (locator/server/lead) for (int i = 1; i < args.length; i++) { String arg = args[i]; if (arg.startsWith(DIR_OPT)) { workDir = arg.substring(DIR_OPT.length()); } else if (!arg.equalsIgnoreCase("stop") && !arg.equalsIgnoreCase("status") && !arg.equalsIgnoreCase("wait") && !arg.equalsIgnoreCase("verbose")) { throw new IllegalArgumentException( MessageFormat.format(LAUNCHER_UNKNOWN_ARGUMENT, arg)); } } processDirOption(workDir); } private void processDirOption(String dir) throws FileNotFoundException { if (dir != null) { final Path workingDirectory = Paths.get(dir); if (Files.exists(workingDirectory)) { this.workingDir = workingDirectory.toAbsolutePath(); // see bug 32548 } else { throw new FileNotFoundException( MessageFormat.format(LAUNCHER_WORKING_DIRECTORY_DOES_NOT_EXIST, dir)); } } else { // default to current working directory this.workingDir = Paths.get("."); } } /** * Returns the <code>Status</code> of the node. An empty status is returned * if status file is missing and <code>emptyForMissing</code> argument is true * else null is returned. */ private void readStatus(boolean emptyForMissing, final Path statusFile) { this.status = null; if (Files.exists(statusFile)) { // try some number of times if dsMsg is null for (int i = 1; i <= 3; i++) { this.status = Status.spinRead(baseName, statusFile); if (this.status.dsMsg != null) break; } } if (this.status == null && emptyForMissing) { this.status = Status.create(baseName, Status.SHUTDOWN, 0, statusFile); } } }
6,706
577
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.android.apps.exposurenotification.storage; import static com.google.common.truth.Truth.assertThat; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.apps.exposurenotification.common.time.Clock; import com.google.android.apps.exposurenotification.common.time.RealTimeModule; import com.google.android.apps.exposurenotification.testsupport.ExposureNotificationRules; import com.google.android.apps.exposurenotification.testsupport.FakeClock; import com.google.android.apps.exposurenotification.testsupport.InMemoryDb; import com.google.common.collect.ImmutableList; import dagger.hilt.android.testing.BindValue; import dagger.hilt.android.testing.HiltAndroidTest; import dagger.hilt.android.testing.HiltTestApplication; import dagger.hilt.android.testing.UninstallModules; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import org.threeten.bp.Duration; import org.threeten.bp.Instant; /** * Tests for operations in {@link VerificationCodeRequestRepository} and the underlying DAO. */ @RunWith(AndroidJUnit4.class) @HiltAndroidTest @Config(application = HiltTestApplication.class) @UninstallModules({DbModule.class, RealTimeModule.class}) public class VerificationCodeRequestRepositoryTest { // Number of requests to retrieve created in the last 30 minutes. private static final int THIRTY_MINUTES_NUM_OF_REQUESTS = 1; // Number of requests to retrieve created in the last 30 days. private static final int THIRTY_DAYS_NUM_OF_REQUESTS = 3; // How long verification code and, hence, a request created to get it are valid. private static final Duration VERIFICATION_CODE_DURATION_MIN = Duration.ofMinutes(15); @Rule public ExposureNotificationRules rules = ExposureNotificationRules.forTest(this).build(); @Inject VerificationCodeRequestRepository verificationCodeRequestRepo; @BindValue ExposureNotificationDatabase db = InMemoryDb.create(); @BindValue Clock clock = new FakeClock(); private Instant now, thirtyMinutesThreshold, thirtyDaysThreshold; @Before public void setUp() { rules.hilt().inject(); now = clock.now(); thirtyMinutesThreshold = now.minus(Duration.ofMinutes(30)); thirtyDaysThreshold = now.minus(Duration.ofDays(30)); } @Test public void setExpiresAtTimeForRequest_updatesExpiresAtTime() throws Exception { // GIVEN Instant expiresAtTime = now.plus(Duration.ofMinutes(1)); VerificationCodeRequestEntity request = VerificationCodeRequestEntity.newBuilder() .setRequestTime(now).setExpiresAtTime(null).setNonce("nonce") .build(); long id = verificationCodeRequestRepo.upsertAsync(request).get(); // WHEN verificationCodeRequestRepo.setExpiresAtTimeForRequest(id, expiresAtTime); List<VerificationCodeRequestEntity> storedRequests = verificationCodeRequestRepo.getAll(); // THEN assertThat(storedRequests).hasSize(1); VerificationCodeRequestEntity updatedRequest = storedRequests.get(0); assertThat(updatedRequest.getId()).isEqualTo(request.getId()); assertThat(updatedRequest.getExpiresAtTime()).isEqualTo(expiresAtTime); assertThat(updatedRequest.getRequestTime()).isEqualTo(request.getRequestTime()); assertThat(updatedRequest.getNonce()).isEqualTo(request.getNonce()); } @Test public void deleteObsoleteRequestsIfAny_threshold30days() throws Exception { // GIVEN List<VerificationCodeRequestEntity> requests = getRequestEntities(); List<VerificationCodeRequestEntity> nonObsoleteRequests = requests.subList(2, requests.size()); for (VerificationCodeRequestEntity request : requests) { verificationCodeRequestRepo.upsertAsync(request).get(); } // WHEN verificationCodeRequestRepo.deleteObsoleteRequestsIfAny(thirtyDaysThreshold); // THEN List<VerificationCodeRequestEntity> storedRequests = verificationCodeRequestRepo.getAll(); assertThat(storedRequests).containsExactlyElementsIn(nonObsoleteRequests); } @Test public void resetNonceForExpiredRequestsIfAny_resetsForAllWithExpiresAtTimeEarlierThanNow() throws Exception { // GIVEN List<VerificationCodeRequestEntity> requests = getRequestEntities(); for (VerificationCodeRequestEntity request : requests) { verificationCodeRequestRepo.upsertAsync(request).get(); } // Nonces for expired requests (expiresAtTime earlier than or equal to now). List<String> expiredNonces = requests.subList(0, requests.size() - 2) .stream() .map(VerificationCodeRequestEntity::getNonce) .collect(Collectors.toList()); // Nonces for non-expired requests (expiresAtTime later than now). List<String> nonExpiredNonces = requests.subList(requests.size() - 2, requests.size()) .stream() .map(VerificationCodeRequestEntity::getNonce) .collect(Collectors.toList()); // WHEN verificationCodeRequestRepo.resetNonceForExpiredRequestsIfAny(clock.now()); // THEN List<String> storedNonces = verificationCodeRequestRepo.getAllNonces(); assertThat(storedNonces).containsNoneIn(expiredNonces); assertThat(storedNonces).containsExactlyElementsIn(nonExpiredNonces); } @Test public void getValidNoncesWithMostRecentFirstIfAnyAsync_returnsNoncesForNonExpiredRequests() throws Exception { // GIVEN List<VerificationCodeRequestEntity> requests = getRequestEntities(); for (VerificationCodeRequestEntity request : requests) { verificationCodeRequestRepo.upsertAsync(request).get(); } // Nonces for non-expired requests (expiresAtTime later than now). Sorted with // the-least-soon-to-expire nonce coming first. List<String> sortedNonExpiredNonces = requests.subList(requests.size() - 2, requests.size()) .stream() .sorted((r1, r2) -> r2.getExpiresAtTime().compareTo(r1.getExpiresAtTime())) .map(VerificationCodeRequestEntity::getNonce) .collect(Collectors.toList()); String mostRecentNonce = sortedNonExpiredNonces.get(0); // WHEN List<String> validNonces = verificationCodeRequestRepo .getValidNoncesWithLatestExpiringFirstIfAnyAsync(clock.now()).get(); // THEN assertThat(validNonces).containsExactlyElementsIn(sortedNonExpiredNonces).inOrder(); assertThat(validNonces.get(0)).isEqualTo(mostRecentNonce); } @Test public void getLastXRequestsNotOlderThanThresholdLiveData_threshold30minutes_oneRequest_returnsOneLatestRequest() throws Exception { // GIVEN List<VerificationCodeRequestEntity> requests = getRequestEntities(); VerificationCodeRequestEntity expectedRequest = requests.get(requests.size() - 1); for (VerificationCodeRequestEntity request : requests) { verificationCodeRequestRepo.upsertAsync(request).get(); } // WHEN List<VerificationCodeRequestEntity> retrievedRequests = verificationCodeRequestRepo .getLastXRequestsNotOlderThanThresholdAsync( thirtyMinutesThreshold, THIRTY_MINUTES_NUM_OF_REQUESTS) .get(); // THEN assertThat(retrievedRequests).hasSize(THIRTY_MINUTES_NUM_OF_REQUESTS); assertThat(retrievedRequests.get(0)).isEqualTo(expectedRequest); } @Test public void getLastXRequestsNotOlderThanThresholdLiveData_threshold30Mins_returnsRequestMadeExactly30MinsAgo() throws Exception { // GIVEN VerificationCodeRequestEntity requestMadeExactly30MinsAgo = VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofMinutes(30))) .setExpiresAtTime(now.minus(Duration.ofMinutes(30)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce") .build(); verificationCodeRequestRepo.upsertAsync(requestMadeExactly30MinsAgo).get(); // WHEN List<VerificationCodeRequestEntity> retrievedRequests = verificationCodeRequestRepo .getLastXRequestsNotOlderThanThresholdAsync( thirtyMinutesThreshold, THIRTY_MINUTES_NUM_OF_REQUESTS) .get(); // THEN assertThat(retrievedRequests).hasSize(1); assertThat(retrievedRequests.get(0)).isEqualTo(requestMadeExactly30MinsAgo); } @Test public void getLastXRequestsNotOlderThanThresholdLiveData_threshold30days_threeRequests_returnsThreeLatestRequests() throws Exception { // GIVEN List<VerificationCodeRequestEntity> requests = getRequestEntities(); List<VerificationCodeRequestEntity> expectedRequests = requests .subList(requests.size() - THIRTY_DAYS_NUM_OF_REQUESTS, requests.size()); for (VerificationCodeRequestEntity request : requests) { verificationCodeRequestRepo.upsertAsync(request).get(); } // WHEN List<VerificationCodeRequestEntity> retrievedRequests = verificationCodeRequestRepo .getLastXRequestsNotOlderThanThresholdAsync( thirtyDaysThreshold, THIRTY_DAYS_NUM_OF_REQUESTS) .get(); // THEN assertThat(retrievedRequests).hasSize(THIRTY_DAYS_NUM_OF_REQUESTS); assertThat(retrievedRequests).containsExactlyElementsIn(expectedRequests); } @Test public void getLastXRequestsNotOlderThanThresholdLiveData_threshold30Days_returnsRequestMadeExactly30DaysAgo() throws Exception { // GIVEN VerificationCodeRequestEntity requestMadeExactly30DaysAgo = VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofDays(30))) .setExpiresAtTime(now.minus(Duration.ofDays(30)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce") .build(); verificationCodeRequestRepo.upsertAsync(requestMadeExactly30DaysAgo).get(); // WHEN List<VerificationCodeRequestEntity> retrievedRequests = verificationCodeRequestRepo .getLastXRequestsNotOlderThanThresholdAsync( thirtyDaysThreshold, THIRTY_DAYS_NUM_OF_REQUESTS) .get(); // THEN assertThat(retrievedRequests).hasSize(1); assertThat(retrievedRequests.get(0)).isEqualTo(requestMadeExactly30DaysAgo); } private List<VerificationCodeRequestEntity> getRequestEntities() { return ImmutableList.of( // Requests created in the last 45 days. VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofDays(45))) .setExpiresAtTime(now.minus(Duration.ofDays(45)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-0") .build(), VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofDays(31))) .setExpiresAtTime(now.minus(Duration.ofDays(31)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-1") .build(), VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofDays(16))) .setExpiresAtTime(now.minus(Duration.ofDays(16)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-2") .build(), VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofDays(15))) .setExpiresAtTime(now.minus(Duration.ofDays(15)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-3") .build(), // Requests created in the last 31 minutes. VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofMinutes(31))) .setExpiresAtTime(now.minus(Duration.ofMinutes(31)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-4") .build(), VerificationCodeRequestEntity.newBuilder() .setRequestTime(now.minus(Duration.ofMinutes(1))) .setExpiresAtTime(now.minus(Duration.ofMinutes(1)).plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-5") .build(), VerificationCodeRequestEntity.newBuilder() .setRequestTime(now) .setExpiresAtTime(now.plus(VERIFICATION_CODE_DURATION_MIN)) .setNonce("nonce-6") .build() ); } }
4,609
381
<gh_stars>100-1000 package com.tngtech.jgiven.impl.util; import java.io.InputStream; import java.util.Properties; import com.tngtech.jgiven.exception.JGivenInstallationException; public class Version { public static final String JGIVEN_VERSION_PROPERTIES = "com/tngtech/jgiven/jgiven-version.properties"; public static final Version VERSION = loadVersion(); private final String versionString; private final String commitHash; public Version( String versionString, String commitHash ) { this.versionString = versionString; this.commitHash = commitHash; } @Override public String toString() { return versionString + "-" + commitHash; } private static Version loadVersion() { Properties properties = new Properties(); InputStream resourceAsStream = Version.class.getClassLoader().getResourceAsStream( JGIVEN_VERSION_PROPERTIES ); try { properties.load( resourceAsStream ); return Version.fromProperties( properties ); } catch( Exception e ) { throw new JGivenInstallationException( "Could not load the JGiven version file " + JGIVEN_VERSION_PROPERTIES + ". " + e.getMessage(), e ); } finally { ResourceUtil.close( resourceAsStream ); } } private static Version fromProperties( Properties properties ) { String versionString = properties.getProperty( "jgiven.version", "Unknown Version" ); String commitHash = properties.getProperty( "jgiven.buildNumber", "Unknown Build Number" ); return new Version( versionString, commitHash ); } }
579
355
/* -*- tab-width: 4; -*- */ /* vi: set sw=2 ts=4 expandtab: */ /* * Copyright 2016-2020 <NAME>. * SPDX-License-Identifier: Apache-2.0 */ /** * @file mygl.h * @brief Include appropriate version of gl.h for the shader-based tests. * * This is a separate header to avoid repetition of these conditionals. */ #ifndef MYGL_H #define MYGL_H /* These are enum values in SDL2/SDL_video.h. Need defines for the * following pre-processor conditionals to work. */ #define SDL_GL_CONTEXT_PROFILE_CORE 0x0001 #define SDL_GL_CONTEXT_PROFILE_COMPATIBILITY 0x0002 #define SDL_GL_CONTEXT_PROFILE_ES 0x0004 #if GL_CONTEXT_PROFILE == SDL_GL_CONTEXT_PROFILE_CORE #ifdef _WIN32 #include <windows.h> #undef KTX_USE_GETPROC /* Must use GETPROC on Windows */ #define KTX_USE_GETPROC 1 #else #if !defined(KTX_USE_GETPROC) #define KTX_USE_GETPROC 0 #endif #endif #if KTX_USE_GETPROC #include <GL/glew.h> #else #define GL_GLEXT_PROTOTYPES #include <GL/glcorearb.h> #endif //#define GL_APIENTRY APIENTRY #elif GL_CONTEXT_PROFILE == SDL_GL_CONTEXT_PROFILE_COMPATIBILITY #error This application is not intended to run in compatibility mode. #elif GL_CONTEXT_PROFILE == SDL_GL_CONTEXT_PROFILE_ES #if GL_CONTEXT_MAJOR_VERSION == 1 #error This application cannot run on OpenGL ES 1. #elif GL_CONTEXT_MAJOR_VERSION == 2 #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #elif GL_CONTEXT_MAJOR_VERSION == 3 #define GL_GLEXT_PROTOTYPES #include <GLES3/gl3.h> #include <GLES2/gl2ext.h> #else #error Unexpected GL_CONTEXT_MAJOR_VERSION #endif #endif /* To help find supported transcode targets */ #if !defined(GL_ETC1_RGB8_OES) #define GL_ETC1_RGB8_OES 0x8D64 #endif #if !defined(GL_COMPRESSED_RGB8_ETC2) #define GL_COMPRESSED_RGB8_ETC2 0x9274 #endif #if !defined(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT) #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 #endif /* undef to avoid needing ordering of mygl.h & SDL2/sdl.h inclusion. */ #undef SDL_GL_CONTEXT_PROFILE_CORE #undef SDL_GL_CONTEXT_PROFILE_COMPATIBILITY #undef SDL_GL_CONTEXT_PROFILE_ES #endif /* MYGL_H */
978
808
<filename>lite/kernels/host/topk_v2_compute.cc // Copyright (c) 2021 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/kernels/host/topk_v2_compute.h" #include <utility> #include <vector> namespace paddle { namespace lite { namespace kernels { namespace host { bool comp_func(std::pair<float, int> a, std::pair<float, int> b) { return (a.first > b.first); } void TopkV2Compute::Run() { auto& param = Param<operators::TopkParam>(); const float* x_data = param.X->data<float>(); float* out_val = param.Out->mutable_data<float>(); auto out_ind = param.Indices->mutable_data<int64_t>(); DDim x_dims = param.X->dims(); int axis = param.axis; int dim_size = x_dims.size(); int k = param.K; if (axis < 0) { axis += dim_size; } if (param.k_is_tensor) { k = param.KTensor->data<int>()[0]; } int outer_size = x_dims.count(0, axis); int axis_size = x_dims[axis]; int inner_size = x_dims.count(axis + 1, dim_size); int sum_size = axis_size * inner_size; int out_sum_size = k * inner_size; for (int i = 0; i < outer_size; i++) { for (int tmp_j = 0; tmp_j < inner_size; tmp_j++) { // we need sort outer_size * inner_size times // and every times we need sort `axis_size` float // we should start from here and pick // `axis_size` float strided by inner_size int glb_in_off = i * sum_size + tmp_j; std::vector<std::pair<float, int>> vec; for (int j = 0; j < axis_size; j++) { vec.push_back(std::make_pair(x_data[glb_in_off + j * inner_size], j)); } std::partial_sort(vec.begin(), vec.begin() + k, vec.end(), comp_func); // we should start from here and put // `k` float from here strided by inner_size int glb_out_off = i * out_sum_size + tmp_j; for (int j = 0; j < k; j++) { out_val[glb_out_off + j * inner_size] = vec[j].first; out_ind[glb_out_off + j * inner_size] = vec[j].second; } } } } } // namespace host } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL(top_k_v2, kHost, kFloat, kNCHW, paddle::lite::kernels::host::TopkV2Compute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kHost))}) .BindInput("K", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt32))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kHost))}) .BindOutput("Indices", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64))}) .Finalize();
1,305
479
<gh_stars>100-1000 /* * Different version of the calculator which parses the * first command line argument. E.g. pass your expression as ./calc3 "1+1;" * argv[1] is mapped to a CharInputBuffer and then fed to the lexer */ #include <iostream> #include <antlr/AST.hpp> #include <antlr/CharInputBuffer.hpp> #include "CalcLexer.hpp" #include "CalcParser.hpp" #include "CalcTreeWalker.hpp" int main( int argc, char*argv[] ) { ANTLR_USING_NAMESPACE(std); ANTLR_USING_NAMESPACE(antlr); if( argc != 2 ) { cerr << argv[0] << ": \"<expression>\"" << endl; return 1; } CharInputBuffer input( reinterpret_cast<unsigned char*>(argv[1]), strlen(argv[1]) ); try { CalcLexer lexer(input); lexer.setFilename("<arguments>"); CalcParser parser(lexer); parser.setFilename("<arguments>"); ASTFactory ast_factory; parser.initializeASTFactory(ast_factory); parser.setASTFactory(&ast_factory); // Parse the input expression parser.expr(); RefAST t = parser.getAST(); if( t ) { // Print the resulting tree out in LISP notation cout << t->toStringTree() << endl; CalcTreeWalker walker; // Traverse the tree created by the parser float r = walker.expr(t); cout << "value is " << r << endl; } else cout << "No tree produced" << endl; } catch(ANTLRException& e) { cerr << "Parse exception: " << e.toString() << endl; return -1; } catch(exception& e) { cerr << "exception: " << e.what() << endl; return -1; } return 0; }
610
848
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <sys/param.h> #include <sys/stat.h> #include <errno.h> #include <paths.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include <fcntl.h> #include "log.h" #define KMSG_DEV_NODE "/dev/kmsg" #define KMSG_PREFIX "acrn_dm: " #define KMSG_MAX_LEN (MAX_ONE_LOG_SIZE + 64) #define DEFAULT_KMSG_LEVEL LOG_NOTICE static int kmsg_fd = -1; static uint8_t kmsg_log_level = DEFAULT_KMSG_LEVEL; static bool kmsg_enabled = false; static bool is_kmsg_enabled(void) { return kmsg_enabled; } static uint8_t get_kmsg_log_level(void) { return kmsg_log_level; } static int init_kmsg_logger(bool enable, uint8_t log_level) { kmsg_enabled = enable; kmsg_log_level = log_level; /* usually this init should be called once in DM whole life */ if (kmsg_fd > 0) return kmsg_fd; kmsg_fd = open(KMSG_DEV_NODE, O_RDWR | O_APPEND | O_NONBLOCK); if (kmsg_fd < 0) { kmsg_enabled = false; pr_err(KMSG_PREFIX"open kmsg dev failed"); } return kmsg_fd; } static void deinit_kmsg(void) { if (kmsg_fd > 0) { close(kmsg_fd); kmsg_fd = -1; kmsg_enabled = false; } } static void write_to_kmsg(const char *fmt, va_list args) { char *buf; char kmsg_buf[KMSG_MAX_LEN] = KMSG_PREFIX; int len, write_cnt; if (kmsg_fd < 0) return; len = vasprintf(&buf, fmt, args); if (len < 0) return; strncpy(kmsg_buf + strlen(KMSG_PREFIX), buf, KMSG_MAX_LEN - strlen(KMSG_PREFIX)); kmsg_buf[KMSG_MAX_LEN - 1] = '\0'; free(buf); write_cnt = write(kmsg_fd, kmsg_buf, strnlen(kmsg_buf, KMSG_MAX_LEN)); if (write_cnt < 0) { pr_err(KMSG_PREFIX"write kmsg failed"); close(kmsg_fd); kmsg_fd = -1; } } static struct logger_ops logger_kmsg = { .name = "kmsg", .is_enabled = is_kmsg_enabled, .get_log_level = get_kmsg_log_level, .init = init_kmsg_logger, .deinit = deinit_kmsg, .output = write_to_kmsg, }; DEFINE_LOGGER_DEVICE(logger_kmsg);
955
4,224
<reponame>uavosky/uavosky-px4 /**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). 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 ECL 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. * ****************************************************************************/ /** * @file drag_fusion.cpp * Body frame drag fusion methods used for multi-rotor wind estimation. * equations generated using EKF/python/ekf_derivation/main.py * * @author <NAME> <<EMAIL>> * */ #include "ekf.h" #include <mathlib/mathlib.h> void Ekf::fuseDrag(const dragSample &drag_sample) { SparseVector24f<0,1,2,3,4,5,6,22,23> Hfusion; // Observation Jacobians Vector24f Kfusion; // Kalman gain vector const float R_ACC = fmaxf(_params.drag_noise, 0.5f); // observation noise variance in specific force drag (m/sec**2)**2 const float rho = fmaxf(_air_density, 0.1f); // air density (kg/m**3) // correct rotor momentum drag for increase in required rotor mass flow with altitude // obtained from momentum disc theory const float mcoef_corrrected = _params.mcoef * sqrtf(rho / CONSTANTS_AIR_DENSITY_SEA_LEVEL_15C); // drag model parameters const bool using_bcoef_x = _params.bcoef_x > 1.0f; const bool using_bcoef_y = _params.bcoef_y > 1.0f; const bool using_mcoef = _params.mcoef > 0.001f; if (!using_bcoef_x && !using_bcoef_y && !using_mcoef) { return; } // get latest estimated orientation const float q0 = _state.quat_nominal(0); const float q1 = _state.quat_nominal(1); const float q2 = _state.quat_nominal(2); const float q3 = _state.quat_nominal(3); // get latest velocity in earth frame const float vn = _state.vel(0); const float ve = _state.vel(1); const float vd = _state.vel(2); // get latest wind velocity in earth frame const float vwn = _state.wind_vel(0); const float vwe = _state.wind_vel(1); // predicted specific forces // calculate relative wind velocity in earth frame and rotate into body frame const Vector3f rel_wind_earth(vn - vwn, ve - vwe, vd); const Dcmf earth_to_body = quatToInverseRotMat(_state.quat_nominal); const Vector3f rel_wind_body = earth_to_body * rel_wind_earth; // perform sequential fusion of XY specific forces for (uint8_t axis_index = 0; axis_index < 2; axis_index++) { // measured drag acceleration corrected for sensor bias const float mea_acc = drag_sample.accelXY(axis_index) - _state.delta_vel_bias(axis_index) / _dt_ekf_avg; // predicted drag force sign is opposite to predicted wind relative velocity const float drag_sign = (rel_wind_body(axis_index) >= 0.f) ? -1.f : 1.f; // Drag is modelled as an arbitrary combination of bluff body drag that proportional to // equivalent airspeed squared, and rotor momentum drag that is proportional to true airspeed // parallel to the rotor disc and mass flow through the rotor disc. float pred_acc = 0.0f; // predicted drag acceleration if (axis_index == 0) { float Kacc; // Derivative of specific force wrt airspeed if (using_mcoef && using_bcoef_x) { // Use a combination of bluff body and propeller momentum drag const float bcoef_inv = 1.0f / _params.bcoef_x; // The airspeed used for linearisation is calculated from the measured acceleration by solving the following quadratic // mea_acc = 0.5 * rho * bcoef_inv * airspeed**2 + mcoef_corrrected * airspeed const float airspeed = (_params.bcoef_x / rho) * (- mcoef_corrrected + sqrtf(sq(mcoef_corrrected) + 2.0f * rho * bcoef_inv * fabsf(mea_acc))); Kacc = fmaxf(1e-1f, rho * bcoef_inv * airspeed + mcoef_corrrected); pred_acc = 0.5f * bcoef_inv * rho * sq(rel_wind_body(0)) * drag_sign - rel_wind_body(0) * mcoef_corrrected; } else if (using_mcoef) { // Use propeller momentum drag only Kacc = fmaxf(1e-1f, mcoef_corrrected); pred_acc = - rel_wind_body(0) * mcoef_corrrected; } else if (using_bcoef_x) { // Use bluff body drag only // The airspeed used for linearisation is calculated from the measured acceleration by solving the following quadratic // mea_acc = (0.5 * rho / _params.bcoef_x) * airspeed**2 const float airspeed = sqrtf((2.0f * _params.bcoef_x * fabsf(mea_acc)) / rho); const float bcoef_inv = 1.0f / _params.bcoef_x; Kacc = fmaxf(1e-1f, rho * bcoef_inv * airspeed); pred_acc = 0.5f * bcoef_inv * rho * sq(rel_wind_body(0)) * drag_sign; } else { // skip this axis continue; } // intermediate variables const float HK0 = vn - vwn; const float HK1 = ve - vwe; const float HK2 = HK0*q0 + HK1*q3 - q2*vd; const float HK3 = 2*Kacc; const float HK4 = HK0*q1 + HK1*q2 + q3*vd; const float HK5 = HK0*q2 - HK1*q1 + q0*vd; const float HK6 = -HK0*q3 + HK1*q0 + q1*vd; const float HK7 = ecl::powf(q0, 2) + ecl::powf(q1, 2) - ecl::powf(q2, 2) - ecl::powf(q3, 2); const float HK8 = HK7*Kacc; const float HK9 = q0*q3 + q1*q2; const float HK10 = HK3*HK9; const float HK11 = q0*q2 - q1*q3; const float HK12 = 2*HK9; const float HK13 = 2*HK11; const float HK14 = 2*HK4; const float HK15 = 2*HK2; const float HK16 = 2*HK5; const float HK17 = 2*HK6; const float HK18 = -HK12*P(0,23) + HK12*P(0,5) - HK13*P(0,6) + HK14*P(0,1) + HK15*P(0,0) - HK16*P(0,2) + HK17*P(0,3) - HK7*P(0,22) + HK7*P(0,4); const float HK19 = HK12*P(5,23); const float HK20 = -HK12*P(23,23) - HK13*P(6,23) + HK14*P(1,23) + HK15*P(0,23) - HK16*P(2,23) + HK17*P(3,23) + HK19 - HK7*P(22,23) + HK7*P(4,23); const float HK21 = ecl::powf(Kacc, 2); const float HK22 = HK12*HK21; const float HK23 = HK12*P(5,5) - HK13*P(5,6) + HK14*P(1,5) + HK15*P(0,5) - HK16*P(2,5) + HK17*P(3,5) - HK19 + HK7*P(4,5) - HK7*P(5,22); const float HK24 = HK12*P(5,6) - HK12*P(6,23) - HK13*P(6,6) + HK14*P(1,6) + HK15*P(0,6) - HK16*P(2,6) + HK17*P(3,6) + HK7*P(4,6) - HK7*P(6,22); const float HK25 = HK7*P(4,22); const float HK26 = -HK12*P(4,23) + HK12*P(4,5) - HK13*P(4,6) + HK14*P(1,4) + HK15*P(0,4) - HK16*P(2,4) + HK17*P(3,4) - HK25 + HK7*P(4,4); const float HK27 = HK21*HK7; const float HK28 = -HK12*P(22,23) + HK12*P(5,22) - HK13*P(6,22) + HK14*P(1,22) + HK15*P(0,22) - HK16*P(2,22) + HK17*P(3,22) + HK25 - HK7*P(22,22); const float HK29 = -HK12*P(1,23) + HK12*P(1,5) - HK13*P(1,6) + HK14*P(1,1) + HK15*P(0,1) - HK16*P(1,2) + HK17*P(1,3) - HK7*P(1,22) + HK7*P(1,4); const float HK30 = -HK12*P(2,23) + HK12*P(2,5) - HK13*P(2,6) + HK14*P(1,2) + HK15*P(0,2) - HK16*P(2,2) + HK17*P(2,3) - HK7*P(2,22) + HK7*P(2,4); const float HK31 = -HK12*P(3,23) + HK12*P(3,5) - HK13*P(3,6) + HK14*P(1,3) + HK15*P(0,3) - HK16*P(2,3) + HK17*P(3,3) - HK7*P(3,22) + HK7*P(3,4); //const float HK32 = Kacc/(-HK13*HK21*HK24 + HK14*HK21*HK29 + HK15*HK18*HK21 - HK16*HK21*HK30 + HK17*HK21*HK31 - HK20*HK22 + HK22*HK23 + HK26*HK27 - HK27*HK28 + R_ACC); // calculate innovation variance and exit if badly conditioned _drag_innov_var(0) = (-HK13*HK21*HK24 + HK14*HK21*HK29 + HK15*HK18*HK21 - HK16*HK21*HK30 + HK17*HK21*HK31 - HK20*HK22 + HK22*HK23 + HK26*HK27 - HK27*HK28 + R_ACC); if (_drag_innov_var(0) < R_ACC) { return; } const float HK32 = Kacc / _drag_innov_var(0); // Observation Jacobians Hfusion.at<0>() = -HK2*HK3; Hfusion.at<1>() = -HK3*HK4; Hfusion.at<2>() = HK3*HK5; Hfusion.at<3>() = -HK3*HK6; Hfusion.at<4>() = -HK8; Hfusion.at<5>() = -HK10; Hfusion.at<6>() = HK11*HK3; Hfusion.at<22>() = HK8; Hfusion.at<23>() = HK10; // Kalman gains // Don't allow modification of any states other than wind velocity at this stage of development - we only need a wind estimate. // Kfusion(0) = -HK18*HK32; // Kfusion(1) = -HK29*HK32; // Kfusion(2) = -HK30*HK32; // Kfusion(3) = -HK31*HK32; // Kfusion(4) = -HK26*HK32; // Kfusion(5) = -HK23*HK32; // Kfusion(6) = -HK24*HK32; // Kfusion(7) = -HK32*(HK12*P(5,7) - HK12*P(7,23) - HK13*P(6,7) + HK14*P(1,7) + HK15*P(0,7) - HK16*P(2,7) + HK17*P(3,7) + HK7*P(4,7) - HK7*P(7,22)); // Kfusion(8) = -HK32*(HK12*P(5,8) - HK12*P(8,23) - HK13*P(6,8) + HK14*P(1,8) + HK15*P(0,8) - HK16*P(2,8) + HK17*P(3,8) + HK7*P(4,8) - HK7*P(8,22)); // Kfusion(9) = -HK32*(HK12*P(5,9) - HK12*P(9,23) - HK13*P(6,9) + HK14*P(1,9) + HK15*P(0,9) - HK16*P(2,9) + HK17*P(3,9) + HK7*P(4,9) - HK7*P(9,22)); // Kfusion(10) = -HK32*(-HK12*P(10,23) + HK12*P(5,10) - HK13*P(6,10) + HK14*P(1,10) + HK15*P(0,10) - HK16*P(2,10) + HK17*P(3,10) - HK7*P(10,22) + HK7*P(4,10)); // Kfusion(11) = -HK32*(-HK12*P(11,23) + HK12*P(5,11) - HK13*P(6,11) + HK14*P(1,11) + HK15*P(0,11) - HK16*P(2,11) + HK17*P(3,11) - HK7*P(11,22) + HK7*P(4,11)); // Kfusion(12) = -HK32*(-HK12*P(12,23) + HK12*P(5,12) - HK13*P(6,12) + HK14*P(1,12) + HK15*P(0,12) - HK16*P(2,12) + HK17*P(3,12) - HK7*P(12,22) + HK7*P(4,12)); // Kfusion(13) = -HK32*(-HK12*P(13,23) + HK12*P(5,13) - HK13*P(6,13) + HK14*P(1,13) + HK15*P(0,13) - HK16*P(2,13) + HK17*P(3,13) - HK7*P(13,22) + HK7*P(4,13)); // Kfusion(14) = -HK32*(-HK12*P(14,23) + HK12*P(5,14) - HK13*P(6,14) + HK14*P(1,14) + HK15*P(0,14) - HK16*P(2,14) + HK17*P(3,14) - HK7*P(14,22) + HK7*P(4,14)); // Kfusion(15) = -HK32*(-HK12*P(15,23) + HK12*P(5,15) - HK13*P(6,15) + HK14*P(1,15) + HK15*P(0,15) - HK16*P(2,15) + HK17*P(3,15) - HK7*P(15,22) + HK7*P(4,15)); // Kfusion(16) = -HK32*(-HK12*P(16,23) + HK12*P(5,16) - HK13*P(6,16) + HK14*P(1,16) + HK15*P(0,16) - HK16*P(2,16) + HK17*P(3,16) - HK7*P(16,22) + HK7*P(4,16)); // Kfusion(17) = -HK32*(-HK12*P(17,23) + HK12*P(5,17) - HK13*P(6,17) + HK14*P(1,17) + HK15*P(0,17) - HK16*P(2,17) + HK17*P(3,17) - HK7*P(17,22) + HK7*P(4,17)); // Kfusion(18) = -HK32*(-HK12*P(18,23) + HK12*P(5,18) - HK13*P(6,18) + HK14*P(1,18) + HK15*P(0,18) - HK16*P(2,18) + HK17*P(3,18) - HK7*P(18,22) + HK7*P(4,18)); // Kfusion(19) = -HK32*(-HK12*P(19,23) + HK12*P(5,19) - HK13*P(6,19) + HK14*P(1,19) + HK15*P(0,19) - HK16*P(2,19) + HK17*P(3,19) - HK7*P(19,22) + HK7*P(4,19)); // Kfusion(20) = -HK32*(-HK12*P(20,23) + HK12*P(5,20) - HK13*P(6,20) + HK14*P(1,20) + HK15*P(0,20) - HK16*P(2,20) + HK17*P(3,20) - HK7*P(20,22) + HK7*P(4,20)); // Kfusion(21) = -HK32*(-HK12*P(21,23) + HK12*P(5,21) - HK13*P(6,21) + HK14*P(1,21) + HK15*P(0,21) - HK16*P(2,21) + HK17*P(3,21) - HK7*P(21,22) + HK7*P(4,21)); Kfusion(22) = -HK28*HK32; Kfusion(23) = -HK20*HK32; } else if (axis_index == 1) { float Kacc; // Derivative of specific force wrt airspeed if (using_mcoef && using_bcoef_y) { // Use a combination of bluff body and propeller momentum drag const float bcoef_inv = 1.0f / _params.bcoef_y; // The airspeed used for linearisation is calculated from the measured acceleration by solving the following quadratic // mea_acc = 0.5 * rho * bcoef_inv * airspeed**2 + mcoef_corrrected * airspeed const float airspeed = (_params.bcoef_y / rho) * (- mcoef_corrrected + sqrtf(sq(mcoef_corrrected) + 2.0f * rho * bcoef_inv * fabsf(mea_acc))); Kacc = fmaxf(1e-1f, rho * bcoef_inv * airspeed + mcoef_corrrected); pred_acc = 0.5f * bcoef_inv * rho * sq(rel_wind_body(1)) * drag_sign - rel_wind_body(1) * mcoef_corrrected; } else if (using_mcoef) { // Use propeller momentum drag only Kacc = fmaxf(1e-1f, mcoef_corrrected); pred_acc = - rel_wind_body(1) * mcoef_corrrected; } else if (using_bcoef_y) { // Use bluff body drag only // The airspeed used for linearisation is calculated from the measured acceleration by solving the following quadratic // mea_acc = (0.5 * rho / _params.bcoef_y) * airspeed**2 const float airspeed = sqrtf((2.0f * _params.bcoef_y * fabsf(mea_acc)) / rho); const float bcoef_inv = 1.0f / _params.bcoef_y; Kacc = fmaxf(1e-1f, rho * bcoef_inv * airspeed); pred_acc = 0.5f * bcoef_inv * rho * sq(rel_wind_body(1)) * drag_sign; } else { // nothing more to do return; } // intermediate variables const float HK0 = ve - vwe; const float HK1 = vn - vwn; const float HK2 = HK0*q0 - HK1*q3 + q1*vd; const float HK3 = 2*Kacc; const float HK4 = -HK0*q1 + HK1*q2 + q0*vd; const float HK5 = HK0*q2 + HK1*q1 + q3*vd; const float HK6 = HK0*q3 + HK1*q0 - q2*vd; const float HK7 = q0*q3 - q1*q2; const float HK8 = HK3*HK7; const float HK9 = ecl::powf(q0, 2) - ecl::powf(q1, 2) + ecl::powf(q2, 2) - ecl::powf(q3, 2); const float HK10 = HK9*Kacc; const float HK11 = q0*q1 + q2*q3; const float HK12 = 2*HK11; const float HK13 = 2*HK7; const float HK14 = 2*HK5; const float HK15 = 2*HK2; const float HK16 = 2*HK4; const float HK17 = 2*HK6; const float HK18 = HK12*P(0,6) + HK13*P(0,22) - HK13*P(0,4) + HK14*P(0,2) + HK15*P(0,0) + HK16*P(0,1) - HK17*P(0,3) - HK9*P(0,23) + HK9*P(0,5); const float HK19 = ecl::powf(Kacc, 2); const float HK20 = HK12*P(6,6) - HK13*P(4,6) + HK13*P(6,22) + HK14*P(2,6) + HK15*P(0,6) + HK16*P(1,6) - HK17*P(3,6) + HK9*P(5,6) - HK9*P(6,23); const float HK21 = HK13*P(4,22); const float HK22 = HK12*P(6,22) + HK13*P(22,22) + HK14*P(2,22) + HK15*P(0,22) + HK16*P(1,22) - HK17*P(3,22) - HK21 - HK9*P(22,23) + HK9*P(5,22); const float HK23 = HK13*HK19; const float HK24 = HK12*P(4,6) - HK13*P(4,4) + HK14*P(2,4) + HK15*P(0,4) + HK16*P(1,4) - HK17*P(3,4) + HK21 - HK9*P(4,23) + HK9*P(4,5); const float HK25 = HK9*P(5,23); const float HK26 = HK12*P(5,6) - HK13*P(4,5) + HK13*P(5,22) + HK14*P(2,5) + HK15*P(0,5) + HK16*P(1,5) - HK17*P(3,5) - HK25 + HK9*P(5,5); const float HK27 = HK19*HK9; const float HK28 = HK12*P(6,23) + HK13*P(22,23) - HK13*P(4,23) + HK14*P(2,23) + HK15*P(0,23) + HK16*P(1,23) - HK17*P(3,23) + HK25 - HK9*P(23,23); const float HK29 = HK12*P(2,6) + HK13*P(2,22) - HK13*P(2,4) + HK14*P(2,2) + HK15*P(0,2) + HK16*P(1,2) - HK17*P(2,3) - HK9*P(2,23) + HK9*P(2,5); const float HK30 = HK12*P(1,6) + HK13*P(1,22) - HK13*P(1,4) + HK14*P(1,2) + HK15*P(0,1) + HK16*P(1,1) - HK17*P(1,3) - HK9*P(1,23) + HK9*P(1,5); const float HK31 = HK12*P(3,6) + HK13*P(3,22) - HK13*P(3,4) + HK14*P(2,3) + HK15*P(0,3) + HK16*P(1,3) - HK17*P(3,3) - HK9*P(3,23) + HK9*P(3,5); // const float HK32 = Kacc/(HK12*HK19*HK20 + HK14*HK19*HK29 + HK15*HK18*HK19 + HK16*HK19*HK30 - HK17*HK19*HK31 + HK22*HK23 - HK23*HK24 + HK26*HK27 - HK27*HK28 + R_ACC); _drag_innov_var(1) = (HK12*HK19*HK20 + HK14*HK19*HK29 + HK15*HK18*HK19 + HK16*HK19*HK30 - HK17*HK19*HK31 + HK22*HK23 - HK23*HK24 + HK26*HK27 - HK27*HK28 + R_ACC); if (_drag_innov_var(1) < R_ACC) { // calculation is badly conditioned return; } const float HK32 = Kacc / _drag_innov_var(1); // Observation Jacobians Hfusion.at<0>() = -HK2*HK3; Hfusion.at<1>() = -HK3*HK4; Hfusion.at<2>() = -HK3*HK5; Hfusion.at<3>() = HK3*HK6; Hfusion.at<4>() = HK8; Hfusion.at<5>() = -HK10; Hfusion.at<6>() = -HK11*HK3; Hfusion.at<22>() = -HK8; Hfusion.at<23>() = HK10; // Kalman gains // Don't allow modification of any states other than wind velocity at this stage of development - we only need a wind estimate. // Kfusion(0) = -HK18*HK32; // Kfusion(1) = -HK30*HK32; // Kfusion(2) = -HK29*HK32; // Kfusion(3) = -HK31*HK32; // Kfusion(4) = -HK24*HK32; // Kfusion(5) = -HK26*HK32; // Kfusion(6) = -HK20*HK32; // Kfusion(7) = -HK32*(HK12*P(6,7) - HK13*P(4,7) + HK13*P(7,22) + HK14*P(2,7) + HK15*P(0,7) + HK16*P(1,7) - HK17*P(3,7) + HK9*P(5,7) - HK9*P(7,23)); // Kfusion(8) = -HK32*(HK12*P(6,8) - HK13*P(4,8) + HK13*P(8,22) + HK14*P(2,8) + HK15*P(0,8) + HK16*P(1,8) - HK17*P(3,8) + HK9*P(5,8) - HK9*P(8,23)); // Kfusion(9) = -HK32*(HK12*P(6,9) - HK13*P(4,9) + HK13*P(9,22) + HK14*P(2,9) + HK15*P(0,9) + HK16*P(1,9) - HK17*P(3,9) + HK9*P(5,9) - HK9*P(9,23)); // Kfusion(10) = -HK32*(HK12*P(6,10) + HK13*P(10,22) - HK13*P(4,10) + HK14*P(2,10) + HK15*P(0,10) + HK16*P(1,10) - HK17*P(3,10) - HK9*P(10,23) + HK9*P(5,10)); // Kfusion(11) = -HK32*(HK12*P(6,11) + HK13*P(11,22) - HK13*P(4,11) + HK14*P(2,11) + HK15*P(0,11) + HK16*P(1,11) - HK17*P(3,11) - HK9*P(11,23) + HK9*P(5,11)); // Kfusion(12) = -HK32*(HK12*P(6,12) + HK13*P(12,22) - HK13*P(4,12) + HK14*P(2,12) + HK15*P(0,12) + HK16*P(1,12) - HK17*P(3,12) - HK9*P(12,23) + HK9*P(5,12)); // Kfusion(13) = -HK32*(HK12*P(6,13) + HK13*P(13,22) - HK13*P(4,13) + HK14*P(2,13) + HK15*P(0,13) + HK16*P(1,13) - HK17*P(3,13) - HK9*P(13,23) + HK9*P(5,13)); // Kfusion(14) = -HK32*(HK12*P(6,14) + HK13*P(14,22) - HK13*P(4,14) + HK14*P(2,14) + HK15*P(0,14) + HK16*P(1,14) - HK17*P(3,14) - HK9*P(14,23) + HK9*P(5,14)); // Kfusion(15) = -HK32*(HK12*P(6,15) + HK13*P(15,22) - HK13*P(4,15) + HK14*P(2,15) + HK15*P(0,15) + HK16*P(1,15) - HK17*P(3,15) - HK9*P(15,23) + HK9*P(5,15)); // Kfusion(16) = -HK32*(HK12*P(6,16) + HK13*P(16,22) - HK13*P(4,16) + HK14*P(2,16) + HK15*P(0,16) + HK16*P(1,16) - HK17*P(3,16) - HK9*P(16,23) + HK9*P(5,16)); // Kfusion(17) = -HK32*(HK12*P(6,17) + HK13*P(17,22) - HK13*P(4,17) + HK14*P(2,17) + HK15*P(0,17) + HK16*P(1,17) - HK17*P(3,17) - HK9*P(17,23) + HK9*P(5,17)); // Kfusion(18) = -HK32*(HK12*P(6,18) + HK13*P(18,22) - HK13*P(4,18) + HK14*P(2,18) + HK15*P(0,18) + HK16*P(1,18) - HK17*P(3,18) - HK9*P(18,23) + HK9*P(5,18)); // Kfusion(19) = -HK32*(HK12*P(6,19) + HK13*P(19,22) - HK13*P(4,19) + HK14*P(2,19) + HK15*P(0,19) + HK16*P(1,19) - HK17*P(3,19) - HK9*P(19,23) + HK9*P(5,19)); // Kfusion(20) = -HK32*(HK12*P(6,20) + HK13*P(20,22) - HK13*P(4,20) + HK14*P(2,20) + HK15*P(0,20) + HK16*P(1,20) - HK17*P(3,20) - HK9*P(20,23) + HK9*P(5,20)); // Kfusion(21) = -HK32*(HK12*P(6,21) + HK13*P(21,22) - HK13*P(4,21) + HK14*P(2,21) + HK15*P(0,21) + HK16*P(1,21) - HK17*P(3,21) - HK9*P(21,23) + HK9*P(5,21)); Kfusion(22) = -HK22*HK32; Kfusion(23) = -HK28*HK32; } // Apply an innovation consistency check with a 5 Sigma threshold _drag_innov(axis_index) = pred_acc - mea_acc; _drag_test_ratio(axis_index) = sq(_drag_innov(axis_index)) / (sq(5.0f) * _drag_innov_var(axis_index)); // if the innovation consistency check fails then don't fuse the sample if (_drag_test_ratio(axis_index) <= 1.0f) { measurementUpdate(Kfusion, Hfusion, _drag_innov(axis_index)); } } }
9,965
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Remit", "definitions": [ "The task or area of activity officially assigned to an individual or organization.", "An item referred to someone for consideration." ], "parts-of-speech": "Noun" }
100
14,668
// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_PRESENTATION_MOCK_WEB_PRESENTATION_CLIENT_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_PRESENTATION_MOCK_WEB_PRESENTATION_CLIENT_H_ #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/public/platform/modules/presentation/web_presentation_client.h" namespace blink { class MockWebPresentationClient : public WebPresentationClient { public: MOCK_METHOD1(SetReceiver, void(WebPresentationReceiver*)); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PRESENTATION_MOCK_WEB_PRESENTATION_CLIENT_H_
270
673
<gh_stars>100-1000 """ schematic_worldview """ from __future__ import absolute_import, division, print_function, unicode_literals from PySide import QtGui import logging from mcedit2.rendering.blockmodels import BlockModels from mcedit2.rendering.textureatlas import TextureAtlas from mcedit2.util import minecraftinstall from mcedit2.util.screen import centerWidgetInScreen from mcedit2.util.worldloader import WorldLoader from mcedit2.worldview.camera import CameraWorldView, CameraPanMouseAction, \ CameraStickyPanMouseAction from mcedit2.worldview.viewaction import ViewAction log = logging.getLogger(__name__) minZoom = 0.1 maxZoom = 2.0 class SchematicZoomInAction(ViewAction): labelText = "Zoom Schematic View In" button = ViewAction.WHEEL_UP acceptsMouseWheel = True settingsKey = None def keyPressEvent(self, event): event.view.distance = min(maxZoom, max(minZoom, event.view.distance - 0.05)) class SchematicZoomOutAction(ViewAction): labelText = "Zoom Schematic View Out" button = ViewAction.WHEEL_DOWN acceptsMouseWheel = True settingsKey = None def keyPressEvent(self, event): event.view.distance = min(maxZoom, max(minZoom, event.view.distance + 0.05)) class SchematicWorldView(CameraWorldView): def __init__(self, dimension, textureAtlas): super(SchematicWorldView, self).__init__(dimension, textureAtlas) self.distance = 1.4 self.centerPoint = dimension.bounds.center stickyPanAction = CameraStickyPanMouseAction() self.viewActions = [CameraPanMouseAction(stickyPanAction), stickyPanAction, SchematicZoomInAction(), SchematicZoomOutAction()] _distance = 1.0 @property def distance(self): return self._distance @distance.setter def distance(self, val): self._distance = val self._updateMatrices() self.update() def updateModelviewMatrix(self): cameraPos = self.centerPoint - self.cameraVector * self.dimension.bounds.size.length() * self.distance modelview = QtGui.QMatrix4x4() modelview.lookAt(QtGui.QVector3D(*cameraPos), QtGui.QVector3D(*(cameraPos + self.cameraVector)), QtGui.QVector3D(0, 1, 0)) self.matrixState.modelview = modelview _swv_app = None def displaySchematic(schematic): global _swv_app if QtGui.qApp is None: _swv_app = QtGui.QApplication([]) if hasattr(schematic, 'getDimension'): dim = schematic.getDimension() else: dim = schematic resourceLoader = minecraftinstall.getSelectedResourceLoader() # xxx select using dim.blocktypes blockModels = BlockModels(schematic.blocktypes, resourceLoader) textureAtlas = TextureAtlas(schematic, resourceLoader, blockModels) _swv_view = SchematicWorldView(dim, textureAtlas) loader = WorldLoader(_swv_view.worldScene) loader.timer.timeout.connect(_swv_view.update) loader.startLoader() centerWidgetInScreen(_swv_view, resize=0.75) _swv_view.show() _swv_app.exec_()
1,249
2,151
// // Copyright (c) 2010-2011 Linaro Limited // // All rights reserved. This program and the accompanying materials // are made available under the terms of the MIT License which accompanies // this distribution, and is available at // http://www.opensource.org/licenses/mit-license.php // // Contributors: // <NAME> <<EMAIL>> // <NAME> <<EMAIL>> // #ifndef UTIL_H_ #define UTIL_H_ #include <string> #include <vector> #include <istream> #include <sstream> #include <stdint.h> #ifdef ANDROID #include <android/asset_manager_jni.h> #endif struct Util { /** * How to perform the split() operation */ enum SplitMode { /** Normal split operation */ SplitModeNormal, /** Allow for spaces and multiple consecutive occurences of the delimiter */ SplitModeFuzzy, /** Take into account bash-like quoting and escaping rules */ SplitModeQuoted }; /** * split() - Splits a string into elements using a provided delimiter * * @s: the string to split * @delim: the delimiter to use * @elems: the string vector to populate * @mode: the SplitMode to use * * Using @delim to determine field boundaries, splits @s into separate * string elements. These elements are returned in the string vector * @elems. As long as @s is non-empty, there will be at least one * element in @elems. */ static void split(const std::string& src, char delim, std::vector<std::string>& elems, Util::SplitMode mode); /** * get_timestamp_us() - Returns the current time in microseconds */ static uint64_t get_timestamp_us(); /** * get_resource() - Gets an input filestream for a given file. * * @path: the path to the file * * Returns a pointer to an input stream, which must be deleted when no * longer in use. */ static std::istream *get_resource(const std::string &path); /** * list_files() - Get a list of the files in a given directory. * * @dirName: the directory path to be listed. * @fileVec: the string vector to populate. * * Obtains a list of the files in @dirName, and returns them in the string * vector @fileVec. */ static void list_files(const std::string& dirName, std::vector<std::string>& fileVec); /** * dispose_pointer_vector() - cleans up a vector of pointers * * @vec: vector of pointers to objects or plain-old-data * * Iterates across @vec and deletes the data pointed to by each of the * elements. Clears the vector, resetting it for reuse. */ template <class T> static void dispose_pointer_vector(std::vector<T*> &vec) { for (typename std::vector<T*>::const_iterator iter = vec.begin(); iter != vec.end(); iter++) { delete *iter; } vec.clear(); } /** * toString() - Converts a string to a plain-old-data type. * * @asString: a string representation of plain-old-data. */ template<typename T> static T fromString(const std::string& asString) { std::stringstream ss(asString); T retVal = T(); ss >> retVal; return retVal; } /** * toString() - Converts a plain-old-data type to a string. * * @t: a simple value to be converted to a string */ template<typename T> static std::string toString(const T t) { std::stringstream ss; ss << t; return ss.str(); } /** * appname_from_path() - get the name of an executable from an absolute path * * @path: absolute path of the running application (argv[0]) * * Returns the last portion of @path (everything after the final '/'). */ static std::string appname_from_path(const std::string& path); #ifdef ANDROID static void android_set_asset_manager(AAssetManager *asset_manager); static AAssetManager *android_get_asset_manager(void); private: static AAssetManager *android_asset_manager; #endif }; #endif /* UTIL_H */
1,684
1,562
<reponame>Masud2017/sandboxed-api<filename>oss-internship-2020/libuv/tests/test_error.cc // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <linux/futex.h> #include <uv.h> #include "gtest/gtest.h" #include "sandboxed_api/util/flag.h" #include "sandboxed_api/util/status_matchers.h" #include "uv_sapi.sapi.h" // NOLINT(build/include) namespace { class UVTestErrorSapiSandbox : public uv::UVSandbox { private: std::unique_ptr<sandbox2::Policy> ModifyPolicy( sandbox2::PolicyBuilder*) override { return sandbox2::PolicyBuilder() .AllowDynamicStartup() .AllowExit() .AllowFutexOp(FUTEX_WAKE_PRIVATE) .AllowWrite() .BuildOrDie(); } }; class UVTestError : public ::testing::Test { protected: void SetUp() override { sandbox_ = std::make_unique<UVTestErrorSapiSandbox>(); ASSERT_THAT(sandbox_->Init(), sapi::IsOk()); api_ = std::make_unique<uv::UVApi>(sandbox_.get()); } // Check sapi_uv_strerror on error void UVStrerror(int error) { // Call sapi_uv_strerror absl::StatusOr<void*> error_message_ptr = api_->sapi_uv_strerror(error); ASSERT_THAT(error_message_ptr, sapi::IsOk()); // Get error message from the sandboxee SAPI_ASSERT_OK_AND_ASSIGN( std::string error_message, sandbox_->GetCString(sapi::v::RemotePtr{error_message_ptr.value()})); // Check that it is equal to expected error message ASSERT_EQ(error_message, std::string{uv_strerror(error)}); } // Check sapi_uv_translate_sys_error on error void UVTranslateSysError(int error) { // Call sapi_uv_translate_sys_error and get error code SAPI_ASSERT_OK_AND_ASSIGN(int error_code, api_->sapi_uv_translate_sys_error(error)); // Check that it is equal to expected error code ASSERT_EQ(error_code, uv_translate_sys_error(error)); } std::unique_ptr<UVTestErrorSapiSandbox> sandbox_; std::unique_ptr<uv::UVApi> api_; }; TEST_F(UVTestError, ErrorMessage) { // Test sapi_uv_strerror method UVStrerror(0); UVStrerror(UV_EINVAL); UVStrerror(1337); UVStrerror(-1337); } TEST_F(UVTestError, SystemError) { // Test sapi_uv_translate_sys_error method UVTranslateSysError(EPERM); UVTranslateSysError(EPIPE); UVTranslateSysError(EINVAL); UVTranslateSysError(UV_EINVAL); UVTranslateSysError(UV_ERANGE); UVTranslateSysError(UV_EACCES); UVTranslateSysError(0); } } // namespace
1,138
396
package com.mapbox.samples; import com.mapbox.geojson.Point; import com.mapbox.api.optimization.v1.MapboxOptimization; import com.mapbox.api.optimization.v1.models.OptimizationResponse; import com.mapbox.sample.BuildConfig; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BasicOptimization { public static void main(String[] args) { MapboxOptimization optimization = MapboxOptimization.builder() .accessToken(BuildConfig.MAPBOX_ACCESS_TOKEN) .coordinate(Point.fromLngLat(-122.42, 37.78)) .coordinate(Point.fromLngLat(-122.45, 37.91)) .coordinate(Point.fromLngLat(-122.48, 37.73)) .build(); optimization.enqueueCall(new Callback<OptimizationResponse>() { @Override public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) { System.out.println(response.body().code()); } @Override public void onFailure(Call<OptimizationResponse> call, Throwable throwable) { System.out.println(throwable); } }); } }
433
1,414
/* Copyright (C) 2002 Rice1964 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <cmath> #include "Render.h" #include "Timing.h" void RSP_GBI1_SpNoop(Gfx *gfx) { SP_Timing(RSP_GBI1_SpNoop); if( (gfx+1)->words.cmd == 0x00 && gRSP.ucode >= 17 ) { RSP_RDP_NOIMPL("Double SPNOOP, Skip remain ucodes, PC=%08X, Cmd1=%08X", gDlistStack[gDlistStackPointer].pc, gfx->words.w1); RDP_GFX_PopDL(); //if( gRSP.ucode < 17 ) TriggerDPInterrupt(); } } void RSP_GBI0_Mtx(Gfx *gfx) { SP_Timing(RSP_GBI0_Mtx); uint32 addr = RSPSegmentAddr((gfx->gbi0matrix.addr)); LOG_UCODE(" Command: %s %s %s Length %d Address 0x%08x", gfx->gbi0matrix.projection == 1 ? "Projection" : "ModelView", gfx->gbi0matrix.load == 1 ? "Load" : "Mul", gfx->gbi0matrix.push == 1 ? "Push" : "NoPush", gfx->gbi0matrix.len, addr); if (addr + 64 > g_dwRamSize) { TRACE1("Mtx: Address invalid (0x%08x)", addr); return; } LoadMatrix(addr); if (gfx->gbi0matrix.projection) { //__asm int 3; CRender::g_pRender->SetProjection(matToLoad, gfx->gbi0matrix.push, gfx->gbi0matrix.load); } else { CRender::g_pRender->SetWorldView(matToLoad, gfx->gbi0matrix.push, gfx->gbi0matrix.load); } #ifdef DEBUGGER const char *loadstr = gfx->gbi0matrix.load == 1 ? "Load" : "Mul"; const char *pushstr = gfx->gbi0matrix.push == 1 ? "Push" : "Nopush"; int projlevel = CRender::g_pRender->GetProjectMatrixLevel(); int worldlevel = CRender::g_pRender->GetWorldViewMatrixLevel(); if( pauseAtNext && eventToPause == NEXT_MATRIX_CMD ) { pauseAtNext = false; debuggerPause = true; if (gfx->gbi0matrix.projection) { TRACE3("Pause after %s and %s Matrix: Projection, level=%d\n", loadstr, pushstr, projlevel ); } else { TRACE3("Pause after %s and %s Matrix: WorldView level=%d\n", loadstr, pushstr, worldlevel); } } else { if( pauseAtNext && logMatrix ) { if (gfx->gbi0matrix.projection) { TRACE3("Matrix: %s and %s Projection level=%d\n", loadstr, pushstr, projlevel); } else { TRACE3("Matrix: %s and %s WorldView\n level=%d", loadstr, pushstr, worldlevel); } } } #endif } void RSP_GBI1_Reserved(Gfx *gfx) { SP_Timing(RSP_GBI1_Reserved); RSP_RDP_NOIMPL("RDP: Reserved (0x%08x 0x%08x)", (gfx->words.w0), (gfx->words.w1)); } void RSP_GBI1_MoveMem(Gfx *gfx) { SP_Timing(RSP_GBI1_MoveMem); uint32 type = ((gfx->words.w0)>>16)&0xFF; uint32 dwLength = ((gfx->words.w0))&0xFFFF; uint32 addr = RSPSegmentAddr((gfx->words.w1)); switch (type) { case RSP_GBI1_MV_MEM_VIEWPORT: { LOG_UCODE(" RSP_GBI1_MV_MEM_VIEWPORT. Address: 0x%08x, Length: 0x%04x", addr, dwLength); RSP_MoveMemViewport(addr); } break; case RSP_GBI1_MV_MEM_LOOKATY: LOG_UCODE(" RSP_GBI1_MV_MEM_LOOKATY"); break; case RSP_GBI1_MV_MEM_LOOKATX: LOG_UCODE(" RSP_GBI1_MV_MEM_LOOKATX"); break; case RSP_GBI1_MV_MEM_L0: case RSP_GBI1_MV_MEM_L1: case RSP_GBI1_MV_MEM_L2: case RSP_GBI1_MV_MEM_L3: case RSP_GBI1_MV_MEM_L4: case RSP_GBI1_MV_MEM_L5: case RSP_GBI1_MV_MEM_L6: case RSP_GBI1_MV_MEM_L7: { uint32 dwLight = (type-RSP_GBI1_MV_MEM_L0)/2; LOG_UCODE(" RSP_GBI1_MV_MEM_L%d", dwLight); LOG_UCODE(" Light%d: Length:0x%04x, Address: 0x%08x", dwLight, dwLength, addr); RSP_MoveMemLight(dwLight, addr); } break; case RSP_GBI1_MV_MEM_TXTATT: LOG_UCODE(" RSP_GBI1_MV_MEM_TXTATT"); break; case RSP_GBI1_MV_MEM_MATRIX_1: RSP_GFX_Force_Matrix(addr); break; case RSP_GBI1_MV_MEM_MATRIX_2: break; case RSP_GBI1_MV_MEM_MATRIX_3: break; case RSP_GBI1_MV_MEM_MATRIX_4: break; default: RSP_RDP_NOIMPL("MoveMem: Unknown Move Type, cmd=%08X, %08X", gfx->words.w0, gfx->words.w1); break; } } void RSP_GBI0_Vtx(Gfx *gfx) { SP_Timing(RSP_GBI0_Vtx); int n = gfx->gbi0vtx.n + 1; int v0 = gfx->gbi0vtx.v0; uint32 addr = RSPSegmentAddr((gfx->gbi0vtx.addr)); LOG_UCODE(" Address 0x%08x, v0: %d, Num: %d, Length: 0x%04x", addr, v0, n, gfx->gbi0vtx.len); if ((v0 + n) > 80) { TRACE3("Warning, invalid vertex positions, N=%d, v0=%d, Addr=0x%08X", n, v0, addr); n = 32 - v0; } // Check that address is valid... if ((addr + n*16) > g_dwRamSize) { TRACE1("Vertex Data: Address out of range (0x%08x)", addr); } else { ProcessVertexData(addr, v0, n); status.dwNumVertices += n; DisplayVertexInfo(addr, v0, n); } } void RSP_GBI0_DL(Gfx *gfx) { SP_Timing(RSP_GBI0_DL); uint32 addr = RSPSegmentAddr((gfx->gbi0dlist.addr)) & (g_dwRamSize-1); LOG_UCODE(" Address=0x%08x Push: 0x%02x", addr, gfx->gbi0dlist.param); if( addr > g_dwRamSize ) { RSP_RDP_NOIMPL("Error: DL addr = %08X out of range, PC=%08X", addr, gDlistStack[gDlistStackPointer].pc ); addr &= (g_dwRamSize-1); DebuggerPauseCountN( NEXT_DLIST ); } if( gfx->gbi0dlist.param == RSP_DLIST_PUSH ) gDlistStackPointer++; gDlistStack[gDlistStackPointer].pc = addr; gDlistStack[gDlistStackPointer].countdown = MAX_DL_COUNT; LOG_UCODE("Level=%d", gDlistStackPointer+1); LOG_UCODE("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); } void RSP_GBI1_RDPHalf_Cont(Gfx *gfx) { SP_Timing(RSP_GBI1_RDPHalf_Cont); LOG_UCODE("RDPHalf_Cont: (Ignored)"); } void RSP_GBI1_RDPHalf_2(Gfx *gfx) { SP_Timing(RSP_GBI1_RDPHalf_2); LOG_UCODE("RDPHalf_2: (Ignored)"); } void RSP_GBI1_RDPHalf_1(Gfx *gfx) { SP_Timing(RSP_GBI1_RDPHalf_1); LOG_UCODE("RDPHalf_1: (Ignored)"); } void RSP_GBI1_Line3D(Gfx *gfx) { status.primitiveType = PRIM_LINE3D; uint32 dwPC = gDlistStack[gDlistStackPointer].pc; BOOL bTrisAdded = FALSE; if( gfx->ln3dtri2.v3 == 0 ) { // Flying Dragon uint32 dwV0 = gfx->ln3dtri2.v0/gRSP.vertexMult; uint32 dwV1 = gfx->ln3dtri2.v1/gRSP.vertexMult; uint32 dwWidth = gfx->ln3dtri2.v2; //uint32 dwFlag = gfx->ln3dtri2.v3/gRSP.vertexMult; CRender::g_pRender->SetCombinerAndBlender(); status.dwNumTrisRendered++; CRender::g_pRender->Line3D(dwV0, dwV1, dwWidth); SP_Timing(RSP_GBI1_Line3D); DP_Timing(RSP_GBI1_Line3D); } else { do { uint32 dwV3 = gfx->ln3dtri2.v3/gRSP.vertexMult; uint32 dwV0 = gfx->ln3dtri2.v0/gRSP.vertexMult; uint32 dwV1 = gfx->ln3dtri2.v1/gRSP.vertexMult; uint32 dwV2 = gfx->ln3dtri2.v2/gRSP.vertexMult; LOG_UCODE(" Line3D: V0: %d, V1: %d, V2: %d, V3: %d", dwV0, dwV1, dwV2, dwV3); // Do first tri if (IsTriangleVisible(dwV0, dwV1, dwV2)) { DEBUG_DUMP_VERTEXES("Line3D 1/2", dwV0, dwV1, dwV2); if (!bTrisAdded && CRender::g_pRender->IsTextureEnabled()) { PrepareTextures(); InitVertexTextureConstants(); } if( !bTrisAdded ) { CRender::g_pRender->SetCombinerAndBlender(); } bTrisAdded = true; PrepareTriangle(dwV0, dwV1, dwV2); } // Do second tri if (IsTriangleVisible(dwV2, dwV3, dwV0)) { DEBUG_DUMP_VERTEXES("Line3D 2/2", dwV0, dwV1, dwV2); if (!bTrisAdded && CRender::g_pRender->IsTextureEnabled()) { PrepareTextures(); InitVertexTextureConstants(); } if( !bTrisAdded ) { CRender::g_pRender->SetCombinerAndBlender(); } bTrisAdded = true; PrepareTriangle(dwV2, dwV3, dwV0); } gfx++; dwPC += 8; #ifdef DEBUGGER } while (gfx->words.cmd == (uint8)RSP_LINE3D && !(pauseAtNext && eventToPause==NEXT_FLUSH_TRI)); #else } while (gfx->words.cmd == (uint8)RSP_LINE3D); #endif gDlistStack[gDlistStackPointer].pc = dwPC-8; if (bTrisAdded) { CRender::g_pRender->DrawTriangles(); } } } void RSP_GBI1_ClearGeometryMode(Gfx *gfx) { SP_Timing(RSP_GBI1_ClearGeometryMode); uint32 dwMask = ((gfx->words.w1)); #ifdef DEBUGGER LOG_UCODE(" Mask=0x%08x", dwMask); if (dwMask & G_ZBUFFER) LOG_UCODE(" Disabling ZBuffer"); if (dwMask & G_TEXTURE_ENABLE) LOG_UCODE(" Disabling Texture"); if (dwMask & G_SHADE) LOG_UCODE(" Disabling Shade"); if (dwMask & G_SHADING_SMOOTH) LOG_UCODE(" Disabling Smooth Shading"); if (dwMask & G_CULL_FRONT) LOG_UCODE(" Disabling Front Culling"); if (dwMask & G_CULL_BACK) LOG_UCODE(" Disabling Back Culling"); if (dwMask & G_FOG) LOG_UCODE(" Disabling Fog"); if (dwMask & G_LIGHTING) LOG_UCODE(" Disabling Lighting"); if (dwMask & G_TEXTURE_GEN) LOG_UCODE(" Disabling Texture Gen"); if (dwMask & G_TEXTURE_GEN_LINEAR) LOG_UCODE(" Disabling Texture Gen Linear"); if (dwMask & G_LOD) LOG_UCODE(" Disabling LOD (no impl)"); #endif gRDP.geometryMode &= ~dwMask; RSP_GFX_InitGeometryMode(); } void RSP_GBI1_SetGeometryMode(Gfx *gfx) { SP_Timing(RSP_GBI1_SetGeometryMode); uint32 dwMask = ((gfx->words.w1)); #ifdef DEBUGGER LOG_UCODE(" Mask=0x%08x", dwMask); if (dwMask & G_ZBUFFER) LOG_UCODE(" Enabling ZBuffer"); if (dwMask & G_TEXTURE_ENABLE) LOG_UCODE(" Enabling Texture"); if (dwMask & G_SHADE) LOG_UCODE(" Enabling Shade"); if (dwMask & G_SHADING_SMOOTH) LOG_UCODE(" Enabling Smooth Shading"); if (dwMask & G_CULL_FRONT) LOG_UCODE(" Enabling Front Culling"); if (dwMask & G_CULL_BACK) LOG_UCODE(" Enabling Back Culling"); if (dwMask & G_FOG) LOG_UCODE(" Enabling Fog"); if (dwMask & G_LIGHTING) LOG_UCODE(" Enabling Lighting"); if (dwMask & G_TEXTURE_GEN) LOG_UCODE(" Enabling Texture Gen"); if (dwMask & G_TEXTURE_GEN_LINEAR) LOG_UCODE(" Enabling Texture Gen Linear"); if (dwMask & G_LOD) LOG_UCODE(" Enabling LOD (no impl)"); #endif // DEBUGGER gRDP.geometryMode |= dwMask; RSP_GFX_InitGeometryMode(); } void RSP_GBI1_EndDL(Gfx *gfx) { SP_Timing(RSP_GBI1_EndDL); RDP_GFX_PopDL(); } //static const char * sc_szBlClr[4] = { "In", "Mem", "Bl", "Fog" }; //static const char * sc_szBlA1[4] = { "AIn", "AFog", "AShade", "0" }; //static const char * sc_szBlA2[4] = { "1-A", "AMem", "1", "?" }; void RSP_GBI1_SetOtherModeL(Gfx *gfx) { SP_Timing(RSP_GBI1_SetOtherModeL); uint32 dwShift = ((gfx->words.w0)>>8)&0xFF; uint32 dwLength= ((gfx->words.w0) )&0xFF; uint32 dwData = (gfx->words.w1); uint32 dwMask = ((1<<dwLength)-1)<<dwShift; uint32 modeL = gRDP.otherModeL; modeL = (modeL&(~dwMask)) | dwData; Gfx tempgfx; tempgfx.words.w0 = gRDP.otherModeH; tempgfx.words.w1 = modeL; DLParser_RDPSetOtherMode(&tempgfx); } void RSP_GBI1_SetOtherModeH(Gfx *gfx) { SP_Timing(RSP_GBI1_SetOtherModeH); uint32 dwShift = ((gfx->words.w0)>>8)&0xFF; uint32 dwLength= ((gfx->words.w0) )&0xFF; uint32 dwData = (gfx->words.w1); uint32 dwMask = ((1<<dwLength)-1)<<dwShift; uint32 dwModeH = gRDP.otherModeH; dwModeH = (dwModeH&(~dwMask)) | dwData; Gfx tempgfx; tempgfx.words.w0 = dwModeH; tempgfx.words.w1 = gRDP.otherModeL; DLParser_RDPSetOtherMode(&tempgfx ); } void RSP_GBI1_Texture(Gfx *gfx) { SP_Timing(RSP_GBI1_Texture); float fTextureScaleS = (float)(gfx->texture.scaleS) / (65536.0f * 32.0f); float fTextureScaleT = (float)(gfx->texture.scaleT) / (65536.0f * 32.0f); if( (((gfx->words.w1)>>16)&0xFFFF) == 0xFFFF ) { fTextureScaleS = 1/32.0f; } else if( (((gfx->words.w1)>>16)&0xFFFF) == 0x8000 ) { fTextureScaleS = 1/64.0f; } #ifdef DEBUGGER else if( ((gfx->words.w1>>16)&0xFFFF) != 0 ) { //DebuggerAppendMsg("Warning, texture scale = %08X is not integer", (word1>>16)&0xFFFF); } #endif if( (((gfx->words.w1) )&0xFFFF) == 0xFFFF ) { fTextureScaleT = 1/32.0f; } else if( (((gfx->words.w1) )&0xFFFF) == 0x8000 ) { fTextureScaleT = 1/64.0f; } #ifdef DEBUGGER else if( (gfx->words.w1&0xFFFF) != 0 ) { //DebuggerAppendMsg("Warning, texture scale = %08X is not integer", (word1)&0xFFFF); } #endif if( gRSP.ucode == 6 ) { if( fTextureScaleS == 0 ) fTextureScaleS = 1.0f/32.0f; if( fTextureScaleT == 0 ) fTextureScaleT = 1.0f/32.0f; } CRender::g_pRender->SetTextureEnableAndScale(gfx->texture.tile, gfx->texture.enable_gbi0, fTextureScaleS, fTextureScaleT); // What happens if these are 0? Interpret as 1.0f? LOG_TEXTURE( { DebuggerAppendMsg("SetTexture: Level: %d Tile: %d %s\n", gfx->texture.level, gfx->texture.tile, gfx->texture.enable_gbi0 ? "enabled":"disabled"); DebuggerAppendMsg(" ScaleS: %f, ScaleT: %f\n", fTextureScaleS*32.0f, fTextureScaleT*32.0f); }); DEBUGGER_PAUSE_COUNT_N(NEXT_SET_TEXTURE); LOG_UCODE(" Level: %d Tile: %d %s", gfx->texture.level, gfx->texture.tile, gfx->texture.enable_gbi0 ? "enabled":"disabled"); LOG_UCODE(" ScaleS: %f, ScaleT: %f", fTextureScaleS*32.0f, fTextureScaleT*32.0f); } extern void RSP_RDP_InsertMatrix(uint32 word0, uint32 word1); void RSP_GBI1_MoveWord(Gfx *gfx) { SP_Timing(RSP_GBI1_MoveWord); switch (gfx->gbi0moveword.type) { case RSP_MOVE_WORD_MATRIX: RSP_RDP_InsertMatrix(gfx); break; case RSP_MOVE_WORD_NUMLIGHT: { uint32 dwNumLights = (((gfx->gbi0moveword.value)-0x80000000)/32)-1; LOG_UCODE(" RSP_MOVE_WORD_NUMLIGHT: Val:%d", dwNumLights); gRSP.ambientLightIndex = dwNumLights; SetNumLights(dwNumLights); } break; case RSP_MOVE_WORD_CLIP: { switch (gfx->gbi0moveword.offset) { case RSP_MV_WORD_OFFSET_CLIP_RNX: case RSP_MV_WORD_OFFSET_CLIP_RNY: case RSP_MV_WORD_OFFSET_CLIP_RPX: case RSP_MV_WORD_OFFSET_CLIP_RPY: CRender::g_pRender->SetClipRatio(gfx->gbi0moveword.offset, gfx->gbi0moveword.value); break; default: LOG_UCODE(" RSP_MOVE_WORD_CLIP ? : 0x%08x", gfx->words.w1); break; } } break; case RSP_MOVE_WORD_SEGMENT: { uint32 dwSegment = (gfx->gbi0moveword.offset >> 2) & 0xF; uint32 dwBase = (gfx->gbi0moveword.value)&0x00FFFFFF; LOG_UCODE(" RSP_MOVE_WORD_SEGMENT Seg[%d] = 0x%08x", dwSegment, dwBase); if( dwBase > g_dwRamSize ) { gRSP.segments[dwSegment] = dwBase; #ifdef DEBUGGER if( pauseAtNext ) DebuggerAppendMsg("warning: Segment %d addr is %8X", dwSegment, dwBase); #endif } else { gRSP.segments[dwSegment] = dwBase; } } break; case RSP_MOVE_WORD_FOG: { uint16 wMult = (uint16)(((gfx->gbi0moveword.value) >> 16) & 0xFFFF); uint16 wOff = (uint16)(((gfx->gbi0moveword.value) ) & 0xFFFF); float fMult = (float)(short)wMult; float fOff = (float)(short)wOff; float rng = 128000.0f / fMult; float fMin = 500.0f - (fOff*rng/256.0f); float fMax = rng + fMin; FOG_DUMP(TRACE4("Set Fog: Min=%f, Max=%f, Mul=%f, Off=%f", fMin, fMax, fMult, fOff)); //if( fMult <= 0 || fMin > fMax || fMax < 0 || fMin > 1000 ) if( fMult <= 0 || fMax < 0 ) { // Hack fMin = 996; fMax = 1000; fMult = 0; fOff = 1; } LOG_UCODE(" RSP_MOVE_WORD_FOG/Mul=%d: Off=%d", wMult, wOff); FOG_DUMP(TRACE3("Set Fog: Min=%f, Max=%f, Data=%08X", fMin, fMax, gfx->gbi0moveword.value)); SetFogMinMax(fMin, fMax, fMult, fOff); } break; case RSP_MOVE_WORD_LIGHTCOL: { uint32 dwLight = gfx->gbi0moveword.offset / 0x20; uint32 dwField = (gfx->gbi0moveword.offset & 0x7); LOG_UCODE(" RSP_MOVE_WORD_LIGHTCOL/0x%08x: 0x%08x", gfx->gbi0moveword.offset, gfx->words.w1); switch (dwField) { case 0: if (dwLight == gRSP.ambientLightIndex) { SetAmbientLight( ((gfx->gbi0moveword.value)>>8) ); } else { SetLightCol(dwLight, gfx->gbi0moveword.value); } break; case 4: break; default: TRACE1("RSP_MOVE_WORD_LIGHTCOL with unknown offset 0x%08x", dwField); break; } } break; case RSP_MOVE_WORD_POINTS: { uint32 vtx = gfx->gbi0moveword.offset/40; uint32 where = gfx->gbi0moveword.offset - vtx*40; ModifyVertexInfo(where, vtx, gfx->gbi0moveword.value); } break; case RSP_MOVE_WORD_PERSPNORM: LOG_UCODE(" RSP_MOVE_WORD_PERSPNORM"); //if( word1 != 0x1A ) DebuggerAppendMsg("PerspNorm: 0x%04x", (short)word1); break; default: RSP_RDP_NOIMPL("Unknown MoveWord, %08X, %08X", gfx->words.w0, gfx->words.w1); break; } } void RSP_GBI1_PopMtx(Gfx *gfx) { SP_Timing(RSP_GBI1_PopMtx); LOG_UCODE(" Command: (%s)", gfx->gbi0popmatrix.projection ? "Projection" : "ModelView"); // Do any of the other bits do anything? // So far only Extreme-G seems to Push/Pop projection matrices if (gfx->gbi0popmatrix.projection) { CRender::g_pRender->PopProjection(); } else { CRender::g_pRender->PopWorldView(); } #ifdef DEBUGGER if( pauseAtNext && eventToPause == NEXT_MATRIX_CMD ) { pauseAtNext = false; debuggerPause = true; DebuggerAppendMsg("Pause after Pop Matrix: %s\n", gfx->gbi0popmatrix.projection ? "Proj":"World"); } else { if( pauseAtNext && logMatrix ) { DebuggerAppendMsg("Pause after Pop Matrix: %s\n", gfx->gbi0popmatrix.projection ? "Proj":"World"); } } #endif } void RSP_GBI1_CullDL(Gfx *gfx) { SP_Timing(RSP_GBI1_CullDL); #ifdef DEBUGGER if( !debuggerEnableCullFace ) { return; //Disable Culling } #endif if( g_curRomInfo.bDisableCulling ) { return; //Disable Culling } uint32 dwVFirst = ((gfx->words.w0) & 0xFFF) / gRSP.vertexMult; uint32 dwVLast = (((gfx->words.w1)) & 0xFFF) / gRSP.vertexMult; LOG_UCODE(" Culling using verts %d to %d", dwVFirst, dwVLast); // Mask into range dwVFirst &= 0x1f; dwVLast &= 0x1f; if( dwVLast < dwVFirst ) return; if( !gRSP.bRejectVtx ) return; for (uint32 i = dwVFirst; i <= dwVLast; i++) { if (g_clipFlag[i] == 0) { LOG_UCODE(" Vertex %d is visible, continuing with display list processing", i); return; } } status.dwNumDListsCulled++; LOG_UCODE(" No vertices were visible, culling rest of display list"); RDP_GFX_PopDL(); } void RSP_GBI1_Tri1(Gfx *gfx) { status.primitiveType = PRIM_TRI1; bool bTrisAdded = false; bool bTexturesAreEnabled = CRender::g_pRender->IsTextureEnabled(); // While the next command pair is Tri1, add vertices uint32 dwPC = gDlistStack[gDlistStackPointer].pc; //uint32 * pCmdBase = (uint32 *)(g_pRDRAMu8 + dwPC); do { uint32 dwV0 = gfx->tri1.v0/gRSP.vertexMult; uint32 dwV1 = gfx->tri1.v1/gRSP.vertexMult; uint32 dwV2 = gfx->tri1.v2/gRSP.vertexMult; if (IsTriangleVisible(dwV0, dwV1, dwV2)) { DEBUG_DUMP_VERTEXES("Tri1", dwV0, dwV1, dwV2); LOG_UCODE(" Tri1: 0x%08x 0x%08x %d,%d,%d", gfx->words.w0, gfx->words.w1, dwV0, dwV1, dwV2); if (!bTrisAdded) { if( bTexturesAreEnabled ) { PrepareTextures(); InitVertexTextureConstants(); } CRender::g_pRender->SetCombinerAndBlender(); bTrisAdded = true; } PrepareTriangle(dwV0, dwV1, dwV2); } gfx++; dwPC += 8; #ifdef DEBUGGER } while (!(pauseAtNext && eventToPause==NEXT_TRIANGLE) && gfx->words.cmd == (uint8)RSP_TRI1); #else } while (gfx->words.cmd == (uint8)RSP_TRI1); #endif gDlistStack[gDlistStackPointer].pc = dwPC-8; if (bTrisAdded) { CRender::g_pRender->DrawTriangles(); } DEBUG_TRIANGLE(TRACE0("Pause at GBI0 TRI1")); } void RSP_GBI0_Tri4(Gfx *gfx) { uint32 w0 = gfx->words.w0; uint32 w1 = gfx->words.w1; status.primitiveType = PRIM_TRI2; // While the next command pair is Tri2, add vertices uint32 dwPC = gDlistStack[gDlistStackPointer].pc; BOOL bTrisAdded = FALSE; do { uint32 dwFlag = (w0>>16)&0xFF; LOG_UCODE(" PD Tri4: 0x%08x 0x%08x Flag: 0x%02x", gfx->words.w0, gfx->words.w1, dwFlag); BOOL bVisible; for( int i=0; i<4; i++) { uint32 v0 = (w1>>(4+(i<<3))) & 0xF; uint32 v1 = (w1>>( (i<<3))) & 0xF; uint32 v2 = (w0>>( (i<<2))) & 0xF; bVisible = IsTriangleVisible(v0, v2, v1); LOG_UCODE(" (%d, %d, %d) %s", v0, v1, v2, bVisible ? "": "(clipped)"); if (bVisible) { DEBUG_DUMP_VERTEXES("Tri4_PerfectDark 1/2", v0, v1, v2); if (!bTrisAdded && CRender::g_pRender->IsTextureEnabled()) { PrepareTextures(); InitVertexTextureConstants(); } if( !bTrisAdded ) { CRender::g_pRender->SetCombinerAndBlender(); } bTrisAdded = true; PrepareTriangle(v0, v2, v1); } } w0 = *(uint32 *)(g_pRDRAMu8 + dwPC+0); w1 = *(uint32 *)(g_pRDRAMu8 + dwPC+4); dwPC += 8; #ifdef DEBUGGER } while (!(pauseAtNext && eventToPause==NEXT_TRIANGLE) && (w0>>24) == (uint8)RSP_TRI2); #else } while (((w0)>>24) == (uint8)RSP_TRI2); #endif gDlistStack[gDlistStackPointer].pc = dwPC-8; if (bTrisAdded) { CRender::g_pRender->DrawTriangles(); } DEBUG_TRIANGLE(TRACE0("Pause at GBI0 TRI4")); gRSP.DKRVtxCount=0; } //Nintro64 uses Sprite2d void RSP_RDP_Nothing(Gfx *gfx) { SP_Timing(RSP_RDP_Nothing); #ifdef DEBUGGER if( logWarning ) { TRACE0("Stack Trace"); for( int i=0; i<gDlistStackPointer; i++ ) { DebuggerAppendMsg(" %08X", gDlistStack[i].pc); } uint32 dwPC = gDlistStack[gDlistStackPointer].pc-8; DebuggerAppendMsg("PC=%08X",dwPC); DebuggerAppendMsg("Warning, unknown ucode PC=%08X: 0x%08x 0x%08x\n", dwPC, gfx->words.w0, gfx->words.w1); } DEBUGGER_PAUSE_AND_DUMP_COUNT_N(NEXT_UNKNOWN_OP, {TRACE0("Paused at unknown ucode\n");}) if( debuggerContinueWithUnknown ) { return; } #endif if( options.bEnableHacks ) return; gDlistStackPointer=-1; } void RSP_RDP_InsertMatrix(Gfx *gfx) { float fraction; UpdateCombinedMatrix(); if ((gfx->words.w0) & 0x20) { int x = ((gfx->words.w0) & 0x1F) >> 1; int y = x >> 2; x &= 3; fraction = ((gfx->words.w1)>>16)/65536.0f; gRSPworldProject.m[y][x] = (float)(int)gRSPworldProject.m[y][x]; gRSPworldProject.m[y][x] += fraction; fraction = ((gfx->words.w1)&0xFFFF)/65536.0f; gRSPworldProject.m[y][x+1] = (float)(int)gRSPworldProject.m[y][x+1]; gRSPworldProject.m[y][x+1] += fraction; } else { int x = ((gfx->words.w0) & 0x1F) >> 1; int y = x >> 2; x &= 3; fraction = (float)fabs(gRSPworldProject.m[y][x] - (int)gRSPworldProject.m[y][x]); gRSPworldProject.m[y][x] = (short)((gfx->words.w1)>>16) + fraction; fraction = (float)fabs(gRSPworldProject.m[y][x+1] - (int)gRSPworldProject.m[y][x+1]); gRSPworldProject.m[y][x+1] = (short)((gfx->words.w1)&0xFFFF) + fraction; } gRSP.bMatrixIsUpdated = false; gRSP.bCombinedMatrixIsUpdated = true; #ifdef DEBUGGER if( pauseAtNext && eventToPause == NEXT_MATRIX_CMD ) { pauseAtNext = false; debuggerPause = true; DebuggerAppendMsg("Pause after insert matrix: %08X, %08X", gfx->words.w0, gfx->words.w1); } else { if( pauseAtNext && logMatrix ) { DebuggerAppendMsg("insert matrix: %08X, %08X", gfx->words.w0, gfx->words.w1); } } #endif }
14,650
909
<gh_stars>100-1000 import java.util.List; public class GasUpProblem { /* 18.6 */ public static int findAmpleCity(List<Integer> gallons, List<Integer> distances) { return 0; } }
85
597
"""Home Assistant control object.""" import asyncio from ipaddress import IPv4Address import logging from pathlib import Path import shutil import tarfile from tempfile import TemporaryDirectory from typing import Optional from uuid import UUID from awesomeversion import AwesomeVersion, AwesomeVersionException from securetar import atomic_contents_add, secure_path import voluptuous as vol from voluptuous.humanize import humanize_error from ..const import ( ATTR_ACCESS_TOKEN, ATTR_AUDIO_INPUT, ATTR_AUDIO_OUTPUT, ATTR_BOOT, ATTR_IMAGE, ATTR_PORT, ATTR_REFRESH_TOKEN, ATTR_SSL, ATTR_TYPE, ATTR_UUID, ATTR_VERSION, ATTR_WAIT_BOOT, ATTR_WATCHDOG, FILE_HASSIO_HOMEASSISTANT, BusEvent, ) from ..coresys import CoreSys, CoreSysAttributes from ..exceptions import ( ConfigurationFileError, HomeAssistantBackupError, HomeAssistantError, HomeAssistantWSError, ) from ..hardware.const import PolicyGroup from ..hardware.data import Device from ..jobs.decorator import Job from ..utils import remove_folder from ..utils.common import FileConfiguration from ..utils.json import read_json_file, write_json_file from .api import HomeAssistantAPI from .const import WSType from .core import HomeAssistantCore from .secrets import HomeAssistantSecrets from .validate import SCHEMA_HASS_CONFIG from .websocket import HomeAssistantWebSocket _LOGGER: logging.Logger = logging.getLogger(__name__) HOMEASSISTANT_BACKUP_EXCLUDE = [ "*.db-shm", "*.corrupt.*", "__pycache__/*", "*.log", "*.log.*", "OZW_Log.txt", ] class HomeAssistant(FileConfiguration, CoreSysAttributes): """Home Assistant core object for handle it.""" def __init__(self, coresys: CoreSys): """Initialize Home Assistant object.""" super().__init__(FILE_HASSIO_HOMEASSISTANT, SCHEMA_HASS_CONFIG) self.coresys: CoreSys = coresys self._api: HomeAssistantAPI = HomeAssistantAPI(coresys) self._websocket: HomeAssistantWebSocket = HomeAssistantWebSocket(coresys) self._core: HomeAssistantCore = HomeAssistantCore(coresys) self._secrets: HomeAssistantSecrets = HomeAssistantSecrets(coresys) @property def api(self) -> HomeAssistantAPI: """Return API handler for core.""" return self._api @property def websocket(self) -> HomeAssistantWebSocket: """Return Websocket handler for core.""" return self._websocket @property def core(self) -> HomeAssistantCore: """Return Core handler for docker.""" return self._core @property def secrets(self) -> HomeAssistantSecrets: """Return Secrets Manager for core.""" return self._secrets @property def machine(self) -> str: """Return the system machines.""" return self.core.instance.machine @property def arch(self) -> str: """Return arch of running Home Assistant.""" return self.core.instance.arch @property def error_state(self) -> bool: """Return True if system is in error.""" return self.core.error_state @property def ip_address(self) -> IPv4Address: """Return IP of Home Assistant instance.""" return self.core.instance.ip_address @property def api_port(self) -> int: """Return network port to Home Assistant instance.""" return self._data[ATTR_PORT] @api_port.setter def api_port(self, value: int) -> None: """Set network port for Home Assistant instance.""" self._data[ATTR_PORT] = value @property def api_ssl(self) -> bool: """Return if we need ssl to Home Assistant instance.""" return self._data[ATTR_SSL] @api_ssl.setter def api_ssl(self, value: bool): """Set SSL for Home Assistant instance.""" self._data[ATTR_SSL] = value @property def api_url(self) -> str: """Return API url to Home Assistant.""" return ( f"{'https' if self.api_ssl else 'http'}://{self.ip_address}:{self.api_port}" ) @property def ws_url(self) -> str: """Return API url to Home Assistant.""" return f"{'wss' if self.api_ssl else 'ws'}://{self.ip_address}:{self.api_port}/api/websocket" @property def watchdog(self) -> bool: """Return True if the watchdog should protect Home Assistant.""" return self._data[ATTR_WATCHDOG] @watchdog.setter def watchdog(self, value: bool): """Return True if the watchdog should protect Home Assistant.""" self._data[ATTR_WATCHDOG] = value @property def wait_boot(self) -> int: """Return time to wait for Home Assistant startup.""" return self._data[ATTR_WAIT_BOOT] @wait_boot.setter def wait_boot(self, value: int): """Set time to wait for Home Assistant startup.""" self._data[ATTR_WAIT_BOOT] = value @property def latest_version(self) -> Optional[AwesomeVersion]: """Return last available version of Home Assistant.""" return self.sys_updater.version_homeassistant @property def image(self) -> str: """Return image name of the Home Assistant container.""" if self._data.get(ATTR_IMAGE): return self._data[ATTR_IMAGE] return f"ghcr.io/home-assistant/{self.sys_machine}-homeassistant" @image.setter def image(self, value: Optional[str]) -> None: """Set image name of Home Assistant container.""" self._data[ATTR_IMAGE] = value @property def version(self) -> Optional[AwesomeVersion]: """Return version of local version.""" return self._data.get(ATTR_VERSION) @version.setter def version(self, value: AwesomeVersion) -> None: """Set installed version.""" self._data[ATTR_VERSION] = value @property def boot(self) -> bool: """Return True if Home Assistant boot is enabled.""" return self._data[ATTR_BOOT] @boot.setter def boot(self, value: bool): """Set Home Assistant boot options.""" self._data[ATTR_BOOT] = value @property def uuid(self) -> UUID: """Return a UUID of this Home Assistant instance.""" return self._data[ATTR_UUID] @property def supervisor_token(self) -> Optional[str]: """Return an access token for the Supervisor API.""" return self._data.get(ATTR_ACCESS_TOKEN) @supervisor_token.setter def supervisor_token(self, value: str) -> None: """Set the access token for the Supervisor API.""" self._data[ATTR_ACCESS_TOKEN] = value @property def refresh_token(self) -> Optional[str]: """Return the refresh token to authenticate with Home Assistant.""" return self._data.get(ATTR_REFRESH_TOKEN) @refresh_token.setter def refresh_token(self, value: Optional[str]): """Set Home Assistant refresh_token.""" self._data[ATTR_REFRESH_TOKEN] = value @property def path_pulse(self): """Return path to asound config.""" return Path(self.sys_config.path_tmp, "homeassistant_pulse") @property def path_extern_pulse(self): """Return path to asound config for Docker.""" return Path(self.sys_config.path_extern_tmp, "homeassistant_pulse") @property def audio_output(self) -> Optional[str]: """Return a pulse profile for output or None.""" return self._data[ATTR_AUDIO_OUTPUT] @audio_output.setter def audio_output(self, value: Optional[str]): """Set audio output profile settings.""" self._data[ATTR_AUDIO_OUTPUT] = value @property def audio_input(self) -> Optional[str]: """Return pulse profile for input or None.""" return self._data[ATTR_AUDIO_INPUT] @audio_input.setter def audio_input(self, value: Optional[str]): """Set audio input settings.""" self._data[ATTR_AUDIO_INPUT] = value @property def need_update(self) -> bool: """Return true if a Home Assistant update is available.""" try: return self.version < self.latest_version except (AwesomeVersionException, TypeError): return False async def load(self) -> None: """Prepare Home Assistant object.""" await asyncio.wait([self.secrets.load(), self.core.load()]) # Register for events self.sys_bus.register_event(BusEvent.HARDWARE_NEW_DEVICE, self._hardware_events) def write_pulse(self): """Write asound config to file and return True on success.""" pulse_config = self.sys_plugins.audio.pulse_client( input_profile=self.audio_input, output_profile=self.audio_output ) # Cleanup wrong maps if self.path_pulse.is_dir(): shutil.rmtree(self.path_pulse, ignore_errors=True) # Write pulse config try: self.path_pulse.write_text(pulse_config, encoding="utf-8") except OSError as err: _LOGGER.error("Home Assistant can't write pulse/client.config: %s", err) else: _LOGGER.info("Update pulse/client.config: %s", self.path_pulse) async def _hardware_events(self, device: Device) -> None: """Process hardware requests.""" if ( not self.sys_hardware.policy.is_match_cgroup(PolicyGroup.UART, device) or not self.version or self.version < "2021.9.0" ): return configuration = await self.sys_homeassistant.websocket.async_send_command( {ATTR_TYPE: "get_config"} ) if not configuration or "usb" not in configuration.get("components", []): return self.sys_homeassistant.websocket.send_message({ATTR_TYPE: "usb/scan"}) @Job() async def backup(self, tar_file: tarfile.TarFile) -> None: """Backup Home Assistant Core config/ directory.""" # Let Home Assistant Core know we are about to backup try: await self.websocket.async_send_command({ATTR_TYPE: WSType.BACKUP_START}) except HomeAssistantWSError: _LOGGER.warning( "Preparing backup of Home Assistant Core failed. Check HA Core logs." ) with TemporaryDirectory(dir=self.sys_config.path_tmp) as temp: temp_path = Path(temp) # Store local configs/state try: write_json_file(temp_path.joinpath("homeassistant.json"), self._data) except ConfigurationFileError as err: raise HomeAssistantError( f"Can't save meta for Home Assistant Core: {err!s}", _LOGGER.error ) from err # Backup data config folder def _write_tarfile(): with tar_file as backup: # Backup metadata backup.add(temp, arcname=".") # Backup data atomic_contents_add( backup, self.sys_config.path_homeassistant, excludes=HOMEASSISTANT_BACKUP_EXCLUDE, arcname="data", ) try: _LOGGER.info("Backing up Home Assistant Core config folder") await self.sys_run_in_executor(_write_tarfile) _LOGGER.info("Backup Home Assistant Core config folder done") except (tarfile.TarError, OSError) as err: raise HomeAssistantBackupError( f"Can't backup Home Assistant Core config folder: {str(err)}", _LOGGER.error, ) from err finally: try: await self.sys_homeassistant.websocket.async_send_command( {ATTR_TYPE: WSType.BACKUP_END} ) except HomeAssistantWSError: _LOGGER.warning( "Error during Home Assistant Core backup. Check HA Core logs." ) async def restore(self, tar_file: tarfile.TarFile) -> None: """Restore Home Assistant Core config/ directory.""" with TemporaryDirectory(dir=self.sys_config.path_tmp) as temp: temp_path = Path(temp) temp_data = temp_path.joinpath("data") temp_meta = temp_path.joinpath("homeassistant.json") # extract backup def _extract_tarfile(): """Extract tar backup.""" with tar_file as backup: backup.extractall(path=temp_path, members=secure_path(backup)) try: await self.sys_run_in_executor(_extract_tarfile) except tarfile.TarError as err: raise HomeAssistantError( f"Can't read tarfile {tar_file}: {err}", _LOGGER.error ) from err # Check old backup format v1 if not temp_data.exists(): temp_data = temp_path # Restore data def _restore_data(): """Restore data.""" shutil.copytree( temp_data, self.sys_config.path_homeassistant, symlinks=True ) _LOGGER.info("Restore Home Assistant Core config folder") await remove_folder(self.sys_config.path_homeassistant) try: await self.sys_run_in_executor(_restore_data) except shutil.Error as err: raise HomeAssistantError( f"Can't restore origin data: {err}", _LOGGER.error ) from err _LOGGER.info("Restore Home Assistant Core config folder done") if not temp_meta.exists(): return _LOGGER.info("Restore Home Assistant Core metadata") # Read backup data try: data = read_json_file(temp_meta) except ConfigurationFileError as err: raise HomeAssistantError() from err # Validate try: data = SCHEMA_HASS_CONFIG(data) except vol.Invalid as err: raise HomeAssistantError( f"Can't validate backup data: {humanize_error(data, err)}", _LOGGER.err, ) from err # Restore metadata for attr in ( ATTR_AUDIO_INPUT, ATTR_AUDIO_OUTPUT, ATTR_PORT, ATTR_SSL, ATTR_REFRESH_TOKEN, ATTR_WATCHDOG, ATTR_WAIT_BOOT, ): self._data[attr] = data[attr]
6,514
679
/************************************************************** * * 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 _DBAUI_CHARSETS_HXX_ #define _DBAUI_CHARSETS_HXX_ #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _TOOLS_RC_HXX #include <tools/rc.hxx> #endif #ifndef _DBHELPER_DBCHARSET_HXX_ #include <connectivity/dbcharset.hxx> #endif #ifndef _SVX_TXENCTAB_HXX #include <svx/txenctab.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OCharsetDisplay //========================================================================= typedef ::dbtools::OCharsetMap OCharsetDisplay_Base; class OCharsetDisplay :protected OCharsetDisplay_Base ,protected SvxTextEncodingTable { protected: ::rtl::OUString m_aSystemDisplayName; public: class ExtendedCharsetIterator; friend class OCharsetDisplay::ExtendedCharsetIterator; typedef ExtendedCharsetIterator iterator; typedef ExtendedCharsetIterator const_iterator; OCharsetDisplay(); // various find operations const_iterator findEncoding(const rtl_TextEncoding _eEncoding) const; const_iterator findIanaName(const ::rtl::OUString& _rIanaName) const; const_iterator findDisplayName(const ::rtl::OUString& _rDisplayName) const; /// get access to the first element of the charset collection const_iterator begin() const; /// get access to the (last + 1st) element of the charset collection const_iterator end() const; // size of the map sal_Int32 size() const { return OCharsetDisplay_Base::size(); } protected: virtual sal_Bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const; private: using OCharsetDisplay_Base::find; }; //------------------------------------------------------------------------- //- CharsetDisplayDerefHelper //------------------------------------------------------------------------- typedef ::dbtools::CharsetIteratorDerefHelper CharsetDisplayDerefHelper_Base; class CharsetDisplayDerefHelper : protected CharsetDisplayDerefHelper_Base { friend class OCharsetDisplay::ExtendedCharsetIterator; ::rtl::OUString m_sDisplayName; public: CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource); rtl_TextEncoding getEncoding() const { return CharsetDisplayDerefHelper_Base::getEncoding(); } ::rtl::OUString getIanaName() const { return CharsetDisplayDerefHelper_Base::getIanaName(); } ::rtl::OUString getDisplayName() const { return m_sDisplayName; } protected: CharsetDisplayDerefHelper(const ::dbtools::CharsetIteratorDerefHelper& _rBase, const ::rtl::OUString& _rDisplayName); }; //------------------------------------------------------------------------- //- OCharsetDisplay::ExtendedCharsetIterator //------------------------------------------------------------------------- class OCharsetDisplay::ExtendedCharsetIterator { friend class OCharsetDisplay; friend bool operator==(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs); friend bool operator!=(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs) { return !(lhs == rhs); } typedef ::dbtools::OCharsetMap container; typedef container::CharsetIterator base_iterator; protected: const OCharsetDisplay* m_pContainer; base_iterator m_aPosition; public: ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource); CharsetDisplayDerefHelper operator*() const; /// prefix increment const ExtendedCharsetIterator& operator++(); /// postfix increment const ExtendedCharsetIterator operator++(int) { ExtendedCharsetIterator hold(*this); ++*this; return hold; } /// prefix decrement const ExtendedCharsetIterator& operator--(); /// postfix decrement const ExtendedCharsetIterator operator--(int) { ExtendedCharsetIterator hold(*this); --*this; return hold; } protected: ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition ); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_CHARSETS_HXX_
1,528
357
<gh_stars>100-1000 import numpy as np import json from path import Path from scipy.misc import imread from tqdm import tqdm class test_framework_stillbox(object): def __init__(self, root, test_files, seq_length=3, min_depth=1e-3, max_depth=80, step=1): self.root = root self.min_depth, self.max_depth = min_depth, max_depth self.gt_files, self.img_files, self.displacements = read_scene_data(self.root, test_files, seq_length, step) def __getitem__(self, i): tgt = imread(self.img_files[i][0]).astype(np.float32) depth = np.load(self.gt_files[i]) return {'tgt': tgt, 'ref': [imread(img).astype(np.float32) for img in self.img_files[i][1]], 'path':self.img_files[i][0], 'gt_depth': depth, 'displacements': np.array(self.displacements[i]), 'mask': generate_mask(depth, self.min_depth, self.max_depth) } def __len__(self): return len(self.img_files) def get_displacements(scene, index, ref_indices): speed = np.around(np.linalg.norm(scene['speed']), decimals=3) assert(all(i < scene['length'] and i >= 0 for i in ref_indices)), str(ref_indices) return [speed*scene['time_step']*abs(index - i) for i in ref_indices] def read_scene_data(data_root, test_list, seq_length=3, step=1): data_root = Path(data_root) metadata_files = {} for folder in data_root.dirs(): with open(folder/'metadata.json', 'r') as f: metadata_files[str(folder.name)] = json.load(f) gt_files = [] im_files = [] displacements = [] demi_length = (seq_length - 1) // 2 shift_range = [step*i for i in list(range(-demi_length,0)) + list(range(1, demi_length + 1))] print('getting test metadata ... ') for sample in tqdm(test_list): folder, file = sample.split('/') _, scene_index, index = file[:-4].split('_') # filename is in the form 'RGB_XXXX_XX.jpg' index = int(index) scene = metadata_files[folder]['scenes'][int(scene_index)] tgt_img_path = data_root/sample folder_path = data_root/folder if tgt_img_path.isfile(): capped_indices_range = list(map(lambda x: min(max(0, index + x), scene['length'] - 1), shift_range)) ref_imgs_path = [folder_path/'{}'.format(scene['imgs'][ref_index]) for ref_index in capped_indices_range] gt_files.append(folder_path/'{}'.format(scene['depth'][index])) im_files.append([tgt_img_path,ref_imgs_path]) displacements.append(get_displacements(scene, index, capped_indices_range)) else: print('{} missing'.format(tgt_img_path)) return gt_files, im_files, displacements def generate_mask(gt_depth, min_depth, max_depth): mask = np.logical_and(gt_depth > min_depth, gt_depth < max_depth) # crop gt to exclude border values # if used on gt_size 100x100 produces a crop of [-95, -5, 5, 95] gt_height, gt_width = gt_depth.shape crop = np.array([0.05 * gt_height, 0.95 * gt_height, 0.05 * gt_width, 0.95 * gt_width]).astype(np.int32) crop_mask = np.zeros(mask.shape) crop_mask[crop[0]:crop[1],crop[2]:crop[3]] = 1 mask = np.logical_and(mask, crop_mask) return mask
1,510
23,901
<gh_stars>1000+ # coding=utf-8 # Copyright 2021 The Google Research 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. """Dataset class for a simple datasets.""" # pylint:skip-file import os import tensorflow as tf from smurf import smurf_utils def _deserialize_png(raw_data): image_uint = tf.image.decode_png(raw_data) return tf.image.convert_image_dtype(image_uint, tf.float32) class SimpleDataset(): """Simple dataset that only holds an image triplet.""" def __init__(self): super().__init__() # Context and sequence features encoded in the dataset proto. self._context_features = { 'height': tf.io.FixedLenFeature([], tf.int64), 'width': tf.io.FixedLenFeature([], tf.int64), } self._sequence_features = { 'images': tf.io.FixedLenSequenceFeature([], tf.string) } def parse_train(self, proto, height, width): """Parse features from byte-encoding to the correct type and shape. Args: proto: Encoded data in proto / tf-sequence-example. height: int, desired image height. width: int, desired image width. Returns: A sequence of images as tf.Tensor of shape [2, height, width, 3]. """ _, sequence_parsed = tf.io.parse_single_sequence_example( proto, context_features=self._context_features, sequence_features=self._sequence_features) # Deserialize images to float32 tensors. images = tf.map_fn( _deserialize_png, sequence_parsed['images'], dtype=tf.float32) # Resize images. if height is not None and width is not None: images = smurf_utils.resize(images, height, width, is_flow=False) return {'images': images} def make_dataset(self, path, mode, height=None, width=None): """Make a dataset for training or evaluating SMURF. Args: path: string, in the format of 'some/path/dir1,dir2,dir3' to load all files in some/path/dir1, some/path/dir2, and some/path/dir3. mode: string, one of ['train', 'train-supervised', 'eval'] to switch between loading training data and evaluation data, which return different features. height: int, height for reshaping the images (only if for_eval=False) because reshaping for eval is more complicated and done in the evaluate function through SMURF inference. width: int, width for reshaping the images (only if for_eval=False). Returns: A tf.dataset of image sequences for training and ground truth flow in dictionary format. """ # Split up the possibly comma seperated directories. if ',' in path: l = path.split(',') d = '/'.join(l[0].split('/')[:-1]) l[0] = l[0].split('/')[-1] paths = [os.path.join(d, x) for x in l] else: paths = [path] # Generate list of filenames. # pylint:disable=g-complex-comprehension files = [os.path.join(d, f) for d in paths for f in tf.io.gfile.listdir(d)] num_files = len(files) ds = tf.data.Dataset.from_tensor_slices(files) if mode == 'multiframe': # Create a nested dataset. ds = ds.map(tf.data.TFRecordDataset) # pylint:disable=g-long-lambda ds = ds.interleave( lambda x: x.map( lambda y: self.parse_train(y, height, width), num_parallel_calls=tf.data.experimental.AUTOTUNE), cycle_length=min(10, num_files), num_parallel_calls=tf.data.experimental.AUTOTUNE) # Prefetch a number of batches because reading new ones can take much # longer when they are from new files. ds = ds.prefetch(10) return ds
1,623
518
{ "name": "Microsoft Dynamics", "category": "Task & Project Management", "start_url": "https://home.dynamics.com", "icons": [ { "src": "https://cdn.filestackcontent.com/pVPZzouJSyScky13q5Xa", "platform": "browserx" } ], "theme_color": "#000D93", "scope": "https://home.dynamics.com", "bx_legacy_service_id": "microsoft-dynamics" }
159
669
<gh_stars>100-1000 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # # Copyright 2020 The Microsoft DeepSpeed Team # Copyright (c) 2020, <NAME>. # Some functions in this file are adapted from following sources: # - _check_overflow : https://github.com/microsoft/DeepSpeedExamples/blob/590364d482b592c3a8a44c28141a8139c7918c55/Megatron-LM-v1.1.5-ZeRO3/megatron/fp16/fp16.py#L294 # - clip_master_grads : https://github.com/microsoft/DeepSpeedExamples/blob/590364d482b592c3a8a44c28141a8139c7918c55/Megatron-LM-v1.1.5-ZeRO3/megatron/fp16/fp16.py#L332 # -------------------------------------------------------------------------- import types import warnings from numpy import inf from ._modifier import FP16OptimizerModifier, check_overflow, clip_grad_norm_fp32 class LegacyMegatronLMModifier(FP16OptimizerModifier): def __init__(self, optimizer, **kwargs) -> None: super().__init__(optimizer) self.get_horizontal_model_parallel_rank = kwargs.get("get_horizontal_model_parallel_rank", None) self.get_horizontal_model_parallel_group = kwargs.get("get_horizontal_model_parallel_group", None) def can_be_modified(self): return self.check_requirements( ["_check_overflow", "clip_master_grads"], require_apex=True, require_torch_non_finite_check=True ) def override_function(self): warnings.warn("Megatron-LM fp16_optimizer functions are overrided with faster implementation.", UserWarning) def clip_master_grads(target, max_norm, norm_type=2): """ Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the current fp32 gradients (viewed as a single vector). .. warning:: Returns -1 if the most recently computed fp16 gradients overflowed (that is, if ``self.overflow`` is ``True``). """ if not target.overflow: fp32_params = [] for param_group in target.optimizer.param_groups: for param in param_group["params"]: fp32_params.append(param) #### THIS IS THE ORIGINAL IMPLEMENTATION #### # return self.clip_grad_norm(fp32_params, max_norm, norm_type) #### END OF THE ORIGINAL IMPLEMENTATION #### #### THIS IS THE FASTER IMPLEMENTATION #### return clip_grad_norm_fp32( fp32_params, max_norm, norm_type, get_horizontal_model_parallel_rank=self.get_horizontal_model_parallel_rank, get_horizontal_model_parallel_group=self.get_horizontal_model_parallel_group, ) #### END OF THE FASTER IMPLEMENTATION #### else: return -1 def _check_overflow(target): params = [] for group in target.fp16_groups: for param in group: params.append(param) for group in target.fp32_from_fp32_groups: for param in group: params.append(param) #### THIS IS THE ORIGINAL IMPLEMENTATION #### # self.overflow = self.loss_scaler.has_overflow(params) #### END OF THE ORIGINAL IMPLEMENTATION #### #### THIS IS THE FASTER IMPLEMENTATION #### target.overflow = check_overflow(params) #### END OF THE FASTER IMPLEMENTATION #### return target.overflow self._optimizer._check_overflow = types.MethodType(_check_overflow, self._optimizer) self._optimizer.clip_master_grads = types.MethodType(clip_master_grads, self._optimizer)
1,802
852
<reponame>ckamtsikis/cmssw #include "CondFormats/L1TObjects/interface/L1MuGMTScales.h" #include "FWCore/Utilities/interface/typelookup.h" TYPELOOKUP_DATA_REG(L1MuGMTScales);
78
11,024
<filename>layers/pubsub/pubsub_example.py<gh_stars>1000+ # # pubsub_example.py # # This source file is part of the FoundationDB open source project # # Copyright 2013-2018 Apple Inc. and the FoundationDB project 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. # ################### # PubSub Example # ################### # This example generates a simple topology with specified numbers of feeds and # inboxes. Inboxes are randomly subscribed to feeds. Each feed and inbox is then # run in its own thread. Feeds post a specified number of messages, waiting a # random interval between messages. Each inbox is polled for messages received, # terminating when no messages are received for a wait limit. import random import threading import time import fdb from pubsub import PubSub fdb.api_version(22) db = fdb.open() ps = PubSub(db) ps.clear_all_messages() # Create the specified numbers of feeds and inboxes. Subscribe each inbox to a # randomly selected subset of feeds. def setup_topology(feeds, inboxes): feed_map = {f: ps.create_feed('Alice ' + str(f)) for f in range(feeds)} inbox_map = {} for i in range(inboxes): inbox_map[i] = ps.create_inbox('Bob ' + str(i)) for f in random.sample(xrange(feeds), random.randint(1, feeds)): ps.create_subscription(inbox_map[i], feed_map[f]) return feed_map, inbox_map # Post a fixed number of messages, waiting a random interval under 1 sec # between each message def feed_driver(feed, messages): for i in range(messages): ps.post_message(feed, 'Message {} from {}'.format(i, feed.get_name())) time.sleep(random.random()) def get_and_print_inbox_messages(inbox, limit=10): print "\nMessages to {}:".format(inbox.get_name()) for m in ps.get_inbox_messages(inbox, limit): print " ->", m # Poll the inbox every 0.1 sec, getting and printing messages received, # until no messages have been received for 1.1 sec def inbox_driver(inbox): wait_limit = 1.1 wait_inc = 0.1 waited = 0.0 changed = False latest = None while True: get_and_print_inbox_messages(inbox) changed = (latest != inbox.latest_message) latest = inbox.latest_message if not changed and waited > wait_limit: break waited += wait_inc time.sleep(wait_inc) # Generate and run a thread for each feed and each inbox. def run_threads(feed_map, inbox_map, messages): feed_threads = [threading.Thread(target=feed_driver, args=(feed_map[id], messages)) for id in feed_map] inbox_threads = [threading.Thread(target=inbox_driver, args=(inbox_map[id],)) for id in inbox_map] for f in feed_threads: f.start() for i in inbox_threads: i.start() for f in feed_threads: f.join() for i in inbox_threads: i.join() def sample_pubsub(feeds, inboxes, messages): feed_map, inbox_map = setup_topology(feeds, inboxes) run_threads(feed_map, inbox_map, messages) if __name__ == "__main__": sample_pubsub(3, 3, 3)
1,277
807
{ "ConnectionStrings": { "Default": "Server=(LocalDb)\\MSSQLLocalDB;Database=ElsaDemo;Trusted_Connection=True" }, "IdentityServer": { "Clients": { "ElsaDemo_Web": { "ClientId": "ElsaDemo_Web", "ClientSecret": "<KEY> "RootUrl": "https://localhost:44336" }, "ElsaDemo_App": { "ClientId": "ElsaDemo_App", "ClientSecret": "<KEY> "RootUrl": "http://localhost:4200" }, "ElsaDemo_BlazorServerTiered": { "ClientId": "ElsaDemo_BlazorServerTiered", "ClientSecret": "<KEY> "RootUrl": "https://localhost:44314" }, "ElsaDemo_Swagger": { "ClientId": "ElsaDemo_Swagger", "ClientSecret": "<KEY> "RootUrl": "https://localhost:44371" } } } }
385
451
/* * Copyright 2019 WeBank * * 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.webank.wedatasphere.qualitis.predicate; import com.webank.wedatasphere.qualitis.dao.TaskDataSourceDao; import com.webank.wedatasphere.qualitis.entity.TaskDataSource; import com.webank.wedatasphere.qualitis.project.constant.ProjectUserPermissionEnum; import com.webank.wedatasphere.qualitis.project.dao.ProjectUserDao; import com.webank.wedatasphere.qualitis.project.entity.ProjectUser; import com.webank.wedatasphere.qualitis.query.queryqo.DataSourceQo; import com.webank.wedatasphere.qualitis.rule.dao.RuleDataSourceDao; import com.webank.wedatasphere.qualitis.rule.entity.RuleDataSource; import com.webank.wedatasphere.qualitis.dao.TaskDataSourceDao; import com.webank.wedatasphere.qualitis.entity.TaskDataSource; import com.webank.wedatasphere.qualitis.dao.TaskDataSourceDao; import com.webank.wedatasphere.qualitis.entity.TaskDataSource; import com.webank.wedatasphere.qualitis.project.constant.ProjectUserPermissionEnum; import com.webank.wedatasphere.qualitis.project.dao.ProjectUserDao; import com.webank.wedatasphere.qualitis.project.entity.ProjectUser; import com.webank.wedatasphere.qualitis.query.queryqo.DataSourceQo; import com.webank.wedatasphere.qualitis.rule.dao.RuleDataSourceDao; import com.webank.wedatasphere.qualitis.rule.entity.RuleDataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * 在DaoImpl中使用了Predicate动态查询的做单元测试 * @author v_wblwyan * @date 2018-11-29 */ @RunWith(SpringRunner.class) @SpringBootTest public class PredicateTest { @Autowired ProjectUserDao dao; @Autowired TaskDataSourceDao taskDataSourceDao; @Autowired RuleDataSourceDao ruleDataSourceDao; @Test @Transactional public void test() { String user = "v_wblwyan_test1"; /* * ProjectUserDao测试 */ DataSourceQo param = new DataSourceQo(); param.setUser(user); param.setUserType(new Integer[] { ProjectUserPermissionEnum.CREATOR.getCode()}); List<ProjectUser> projectUsers = dao.findByUsernameAndPermissionsIn(param); assertTrue(projectUsers.isEmpty()); param.setUserType(new Integer[] {ProjectUserPermissionEnum.CREATOR.getCode()}); projectUsers = dao.findByUsernameAndPermissionsIn(param); assertTrue(projectUsers.isEmpty()); param.setUserType(null); projectUsers = dao.findByUsernameAndPermissionsIn(param); assertTrue(projectUsers.isEmpty()); param.setUserType(new Integer[] {}); projectUsers = dao.findByUsernameAndPermissionsIn(param); assertTrue(projectUsers.isEmpty()); /* *TaskDataSourceDao 测试 */ List<TaskDataSource> taskDataSources = taskDataSourceDao.findByUserAndDataSource(user, null, null, null, 0, 5); assertTrue(taskDataSources.isEmpty()); taskDataSources = taskDataSourceDao.findByUserAndDataSource(user, "clusterName_test", null, null, 0, 5); assertTrue(taskDataSources.isEmpty()); taskDataSources = taskDataSourceDao.findByUserAndDataSource(user, "clusterName_test", "databaseName_test", null, 0, 5); assertTrue(taskDataSources.isEmpty()); taskDataSources = taskDataSourceDao.findByUserAndDataSource(user, "clusterName_test", "databaseName_test", "tableName_test", 0, 5); assertTrue(taskDataSources.isEmpty()); long count = taskDataSourceDao.countByUserAndDataSource(user, "clusterName_test", "databaseName_test", null); assertEquals(0, count); /* *RuleDataSourceDao 测试 */ List<RuleDataSource> ruleDataSources = ruleDataSourceDao.findByProjectUser( (long) Integer.MAX_VALUE, null, null, null); assertTrue(ruleDataSources.isEmpty()); ruleDataSources = ruleDataSourceDao.findByProjectUser((long) Integer.MAX_VALUE, "clusterName_test", null, null); assertTrue(ruleDataSources.isEmpty()); ruleDataSources = ruleDataSourceDao.findByProjectUser((long) Integer.MAX_VALUE, "clusterName_test", "databaseName_test", null); assertTrue(ruleDataSources.isEmpty()); ruleDataSources = ruleDataSourceDao.findByProjectUser((long) Integer.MAX_VALUE, "clusterName_test", "databaseName_test", "tableName_test"); assertTrue(ruleDataSources.isEmpty()); } }
2,526
308
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: <NAME>(<EMAIL>) # Object Detection running score. import time import numpy as np class DetRunningScore(object): def __init__(self, configer): self.configer = configer self.gt_list = list() self.pred_list = list() self.num_positive = list() for i in range(self.configer.get('data', 'num_classes')): self.gt_list.append(dict()) self.pred_list.append(list()) self.num_positive.append(1e-9) def _voc_ap(self, rec, prec, use_07_metric=True): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:True). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def _voc_eval(self, iou_threshold=0.5, use_07_metric=False): ap_list = list() rc_list = list() pr_list = list() for i in range(self.configer.get('data', 'num_classes')): class_recs = self.gt_list[i] pred_recs = self.pred_list[i] for key in class_recs.keys(): class_recs[key]['det'] = [False] * class_recs[key]['bbox'].shape[0] image_ids = np.array([pred_rec[0] for pred_rec in pred_recs]) confidence = np.array([pred_rec[1] for pred_rec in pred_recs]) BB = np.array([pred_rec[2] for pred_rec in pred_recs]) # sort by confidence sorted_ind = np.argsort(-confidence) BB = BB[sorted_ind] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: # compute overlaps # intersection ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin, 0.) ih = np.maximum(iymax - iymin, 0.) inters = iw * ih uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) + (BBGT[:, 2] - BBGT[:, 0]) * (BBGT[:, 3] - BBGT[:, 1]) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > iou_threshold: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. # compute precision recall fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(self.num_positive[i]) # avoid divide by zero in case the first detection matches a difficult # ground truth prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec, use_07_metric=use_07_metric) rc_list.append(rec) ap_list.append(ap) pr_list.append(prec) return rc_list, pr_list, ap_list def update(self, batch_pred_bboxes, batch_gt_bboxes, batch_gt_labels): image_name_prefix = str(time.time()) for i in range(len(batch_gt_bboxes)): image_name = '{}_{}'.format(image_name_prefix, i) for cls in range(self.configer.get('data', 'num_classes')): self.gt_list[cls][image_name] = { 'bbox': np.array([batch_gt_bboxes[i][j].cpu().numpy() for j in range(batch_gt_bboxes[i].size(0)) if batch_gt_labels[i][j] == cls]) } self.num_positive[cls] += (self.gt_list[cls][image_name]['bbox']).shape[0] for pred_box in batch_pred_bboxes[i]: self.pred_list[pred_box[4]].append([image_name, pred_box[5], pred_box[:4]]) def get_mAP(self): # compute mAP by APs under different oks thresholds use_07_metric = self.configer.get('val', 'use_07_metric') rc_list, pr_list, ap_list = self._voc_eval(use_07_metric=use_07_metric) if self.num_positive[self.configer.get('data', 'num_classes') - 1] < 1: return sum(ap_list) / (self.configer.get('data', 'num_classes') - 1) else: return sum(ap_list) / self.configer.get('data', 'num_classes') def reset(self): self.gt_list = list() self.pred_list = list() self.num_positive = list() for i in range(self.configer.get('data', 'num_classes')): self.gt_list.append(dict()) self.pred_list.append(list()) self.num_positive.append(1e-9)
3,444
351
package com.talosvfx.talos.runtime.modules; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.talosvfx.talos.runtime.ScopePayload; import com.talosvfx.talos.runtime.values.NumericalValue; public class AttractorModule extends AbstractModule { public static final int INITIAL_ANGLE = 0; public static final int INITIAL_VELOCITY = 1; public static final int ATTRACTOR_POSITION = 2; // maybe change to support multiple attractors later public static final int ALPHA = 3; public static final int ANGLE = 0; public static final int VELOCITY = 1; NumericalValue initialAngle; NumericalValue initialVelocity; NumericalValue attractorPosition; NumericalValue alpha; NumericalValue angle; NumericalValue velocity; Vector2 initialVector = new Vector2(); Vector2 attractionVector = new Vector2(); Vector2 pos = new Vector2(); Vector2 result = new Vector2(); @Override protected void defineSlots() { initialAngle = createInputSlot(INITIAL_ANGLE); initialVelocity = createInputSlot(INITIAL_VELOCITY); attractorPosition = createInputSlot(ATTRACTOR_POSITION); alpha = createInputSlot(ALPHA); angle = createOutputSlot(ANGLE); velocity = createOutputSlot(VELOCITY); initialAngle.setFlavour(NumericalValue.Flavour.ANGLE); } @Override public void processValues() { NumericalValue posNumVal = getScope().get(ScopePayload.PARTICLE_POSITION); pos.set(posNumVal.get(0), posNumVal.get(1)); float alphaVal = getScope().getFloat(ScopePayload.PARTICLE_ALPHA);; if(!alpha.isEmpty()) { alphaVal = alpha.getFloat(); } initialVector.set(initialVelocity.getFloat(), 0); initialVector.rotate(initialAngle.getFloat()); attractionVector.set(attractorPosition.get(0), attractorPosition.get(1)).sub(pos); attractionVector.nor().scl(initialVelocity.getFloat()); Interpolation interpolation = Interpolation.linear; // now let's mix them result.set(interpolation.apply(initialVector.x, attractionVector.x, alphaVal), interpolation.apply(initialVector.y, attractionVector.y, alphaVal)); angle.set(result.angle()); velocity.set(result.len()); } }
887
402
<gh_stars>100-1000 package com.vaadin.flow.mixedtest.ui; import java.io.File; import com.vaadin.flow.testutil.FileTestUtil; import org.junit.Test; public class NpmUsedIT { @Test public void npmIsUsed() { File testPackage = new File("node_modules/lit"); FileTestUtil.waitForFile(testPackage); FileTestUtil.assertDirectory(testPackage, "npm should have been used to install frontend dependencies but node_modules/lit is a symlink and only pnpm uses symlinks"); } }
203
1,056
<filename>enterprise/j2ee.common/src/org/netbeans/modules/j2ee/common/DatasourceHelper.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.j2ee.common; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.netbeans.api.db.explorer.ConnectionManager; import org.netbeans.api.db.explorer.DatabaseConnection; import org.netbeans.modules.j2ee.deployment.common.api.ConfigurationException; import org.netbeans.modules.j2ee.deployment.common.api.Datasource; import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider; /** * An utility class for working with data sources. * * @author <NAME> * * @since 1.7 */ public class DatasourceHelper { private DatasourceHelper() { } /** * Finds the database connections whose database URL and user name equal * the database URL and the user name of the passed data source. * * @param datasource the data source. * * @return the list of database connections; never null. * * @throws NullPointerException if the datasource parameter was null. */ public static List<DatabaseConnection> findDatabaseConnections(Datasource datasource) { if (datasource == null) { throw new NullPointerException("The datasource parameter cannot be null."); // NOI18N } String databaseUrl = datasource.getUrl(); String user = datasource.getUsername(); if (databaseUrl == null || user == null) { return Collections.emptyList(); } List<DatabaseConnection> result = new ArrayList<DatabaseConnection>(); for (DatabaseConnection dbconn : ConnectionManager.getDefault().getConnections()) { if (databaseUrl.equals(dbconn.getDatabaseURL()) && user.equals(dbconn.getUser())) { result.add(dbconn); } } if (result.size() > 0) { return Collections.unmodifiableList(result); } else { return Collections.emptyList(); } } /** * Finds the data source with the given JNDI name in the module and * project data sources of the given provider. * * @param provider the {@link J2eeModuleProvider provider} whose data sources * are to be searched; cannot be null. * @param jndiName the JNDI name to search for; cannot be null. * * @return the found data source or null if no data source was found. * * @throws NullPointerException if either the <code>provider</code> * or the <code>jndiName</code> parameter was null. * * @since 1.11 */ public static Datasource findDatasource(J2eeModuleProvider provider, String jndiName) throws ConfigurationException { if (provider == null) { throw new NullPointerException("The provider parameter cannot be null."); // NOI18N } if (jndiName == null) { throw new NullPointerException("The jndiName parameter cannot be null."); // NOI18N } for (Datasource datasource : provider.getServerDatasources()) { if (jndiName.equals(datasource.getJndiName())) { return datasource; } } for (Datasource datasource : provider.getModuleDatasources()) { if (jndiName.equals(datasource.getJndiName())) { return datasource; } } return null; } }
1,546
14,668
<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/functional/identity.h" #include <vector> #include "testing/gtest/include/gtest/gtest.h" namespace base { TEST(FunctionalTest, Identity) { static constexpr identity id; std::vector<int> v; EXPECT_EQ(&v, &id(v)); constexpr int arr = {0}; static_assert(arr == id(arr), ""); } } // namespace base
174
348
{"nom":"Bretx","circ":"5ème circonscription","dpt":"Haute-Garonne","inscrits":429,"abs":202,"votants":227,"blancs":2,"nuls":2,"exp":223,"res":[{"nuance":"REM","nom":"<NAME>","voix":98},{"nuance":"FN","nom":"<NAME>","voix":43},{"nuance":"UDI","nom":"<NAME>","voix":29},{"nuance":"FI","nom":"Mme <NAME>","voix":21},{"nuance":"SOC","nom":"Mme <NAME>","voix":11},{"nuance":"ECO","nom":"Mme <NAME>","voix":9},{"nuance":"DIV","nom":"M. <NAME>","voix":4},{"nuance":"ECO","nom":"Mme <NAME>","voix":2},{"nuance":"DVG","nom":"M. <NAME>","voix":2},{"nuance":"DIV","nom":"M. <NAME>","voix":2},{"nuance":"COM","nom":"Mme <NAME>","voix":1},{"nuance":"ECO","nom":"Mme <NAME>","voix":1},{"nuance":"ECO","nom":"Mme <NAME>","voix":0},{"nuance":"EXG","nom":"M. <NAME>","voix":0}]}
314
1,350
<reponame>Manny27nyc/azure-sdk-for-java<filename>sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsEventBaseProperties.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.messaging.eventgrid.systemevents; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Schema of common properties of all SMS events. */ @Fluent public class AcsSmsEventBaseProperties { /* * The identity of the SMS message */ @JsonProperty(value = "messageId") private String messageId; /* * The identity of SMS message sender */ @JsonProperty(value = "from") private String from; /* * The identity of SMS message receiver */ @JsonProperty(value = "to") private String to; /** * Get the messageId property: The identity of the SMS message. * * @return the messageId value. */ public String getMessageId() { return this.messageId; } /** * Set the messageId property: The identity of the SMS message. * * @param messageId the messageId value to set. * @return the AcsSmsEventBaseProperties object itself. */ public AcsSmsEventBaseProperties setMessageId(String messageId) { this.messageId = messageId; return this; } /** * Get the from property: The identity of SMS message sender. * * @return the from value. */ public String getFrom() { return this.from; } /** * Set the from property: The identity of SMS message sender. * * @param from the from value to set. * @return the AcsSmsEventBaseProperties object itself. */ public AcsSmsEventBaseProperties setFrom(String from) { this.from = from; return this; } /** * Get the to property: The identity of SMS message receiver. * * @return the to value. */ public String getTo() { return this.to; } /** * Set the to property: The identity of SMS message receiver. * * @param to the to value to set. * @return the AcsSmsEventBaseProperties object itself. */ public AcsSmsEventBaseProperties setTo(String to) { this.to = to; return this; } }
920
655
#pragma once #include <Eigen/Core> #include <df/voxel/movingAverage.h> namespace df { struct ProbabilityVoxel : public MovingAverageVoxel<float,Eigen::Matrix<float, 10, 1, Eigen::DontAlign> > { inline __host__ __device__ static ProbabilityVoxel zero() { ProbabilityVoxel voxel; voxel.weight_ = 0.f; voxel.weightedAverage_ = Eigen::Matrix<float,10,1,Eigen::DontAlign>::Zero(); return voxel; } inline __host__ __device__ Eigen::Matrix<float,10,1,Eigen::DontAlign> probabilityValue() const { return value(); } }; } // namespace df
254
852
<filename>FWCore/TestProcessor/python/TestProcess.py import FWCore.ParameterSet.Config as cms class TestProcess(cms.Process): def __init__(self,name="TEST",*modifiers): super(TestProcess,self).__init__(name,*modifiers) self.__dict__["_TestProcess__moduleToTest"] = None def moduleToTest(self,mod,task=cms.Task()): self.__dict__["_TestProcess__moduleToTest"] = mod if isinstance(mod,cms.EDFilter): self._test_path = cms.Path(mod,task) else: self._test_endpath = cms.EndPath(mod,task) def fillProcessDesc(self, processPSet): if self.__dict__["_TestProcess__moduleToTest"] is None: raise LogicError("moduleToTest was not called") for p in self.paths.iterkeys(): if p != "_test_path": delattr(self,p) for p in self.endpaths.iterkeys(): if p != "_test_endpath": delattr(self,p) if not hasattr(self,"options"): self.options = cms.untracked.PSet() cms.Process.fillProcessDesc(self,processPSet) processPSet.addString(True, "@moduleToTest",self.__dict__["_TestProcess__moduleToTest"].label_())
530
455
<filename>StarEngine/jni/Actions/ScaleAction.h #pragma once #include "TimedAction.h" namespace star { class ScaleAction : public TimedAction { public: ScaleAction( float32 seconds, float32 begin, float32 end, const std::function<void()> & callback = nullptr ); ScaleAction( const tstring & name, float32 seconds, float32 begin, float32 end, const std::function<void()> & callback = nullptr ); virtual ~ScaleAction(void); virtual void Restart(); protected: virtual void Update(const Context& context); float32 m_CurrentSeconds, m_BeginValue, m_EndValue; private: ScaleAction & operator=(const ScaleAction&); ScaleAction & operator=(ScaleAction&&); ScaleAction(const ScaleAction&); ScaleAction(ScaleAction&&); }; }
315
604
#include "pch.h" #include "PinyinSearchPcre.hpp" #include "config.hpp" #include "ipc.hpp" #include "match.hpp" #include "helper.hpp" /* * Region list: * regcomp_p3 * regcomp_p2 * regcomp * pcre_compile2 (not in use) * pcre_fullinfo (not in use) * regexec * pcre_exec (not in use) * free */ #pragma region regcomp_p3 //bool global_regex; void regcomp_p3_common(char* search, char* filter) { if constexpr (debug) DebugOStream() << LR"(regcomp_p3_common(")" << search << LR"(", ")" << filter << LR"("))" << L"\n"; } uint64_t (*regcomp_p3_14_real)(__int64 a1, int a2, int a3, int a4, int a5, int regex, int a7, int a8, char* search, int a10, char* filter, int sort, int a13, int a14, int a15); uint64_t regcomp_p3_14_detour(__int64 a1, int a2, int a3, int a4, int a5, int regex, int a7, int a8, char* search, int a10, char* filter, int sort, int a13, int a14, int a15) { //global_regex = regex; regcomp_p3_common(search, filter); return regcomp_p3_14_real(a1, a2, a3, a4, a5, regex /*1*/, a7, a8, search, a10, filter, sort, a13, a14, a15); } uint64_t (*regcomp_p3_15_real)(void* a1); uint64_t regcomp_p3_15_detour(void* a1) { /* uint32_t* regex = (uint32_t*)a1 + 808; global_regex = *regex; */ // enabling global regex will make the entire search content be treated as // a regular expression (even if there are modifiers and spaces) /* if (!global_regex) *regex = 1; */ regcomp_p3_common(ib::Addr(a1).offset<uint64_t>(406)[0], ib::Addr(a1).offset<uint64_t>(408)[0]); return regcomp_p3_15_real(a1); } #pragma endregion #pragma region regcomp_p2 struct Modifier { using Value = uint32_t; using T = const Value; static T Case = 0x1; // "Match Case" or `case:` static T WholeWord = 0x2; // "Match Whole Word", `wholeword:` or `ww:` static T Path = 0x4; // "Match Path" or `path:` static T Diacritics = 0x8; // "Match Diacritics" or `diacritics:` static T File = 0x10; // `file:` static T Folder = 0x20; // `folder:` static T FastAsciiSearch = 0x40; // `ascii:` (`utf8:` to disable) static T WholeFilename = 0x200; // `wholefilename:` or `wfn:` static T RegEx = 0x800; // "Enable Regex" or `regex:` static T WildcardWholeFilename = 0x1000; // "Match whole filename when using wildcards" static T Alphanumeric = 0x2000; static T WildcardEx = 0x4000; // `wildcards:` }; Modifier::Value modifiers; char termtext_initial; void regcomp_p2_common(Modifier::Value* modifiers_p, char8_t* termtext, size_t* termtext_len) { if constexpr (debug) { std::wstring termtext_u16(*termtext_len, L'\0'); termtext_u16.resize(MultiByteToWideChar(CP_UTF8, 0, (char*)termtext, *termtext_len, termtext_u16.data(), termtext_u16.size())); DebugOStream() << L"regcomp_p2_common(" << std::hex << *modifiers_p << LR"(, ")" << termtext_u16 << LR"("))" << L" on " << GetCurrentThreadId() << L"\n"; // single thread } modifiers = *modifiers_p; std::u8string_view pattern(termtext, *termtext_len); if (pattern.empty()) return; // post-modifiers must be processed first (or it may return with a termtext containing post-modifiers) // NoProcess post-modifier if (pattern.ends_with(u8";np")) { *termtext_len -= 3; return; } // return if term is a regex or term is case sensitive if (modifiers & Modifier::RegEx || modifiers & Modifier::Case) return; // unsupported modifiers if (modifiers & Modifier::WildcardEx || modifiers & Modifier::WholeWord) return; //#TODO: wildcards are not supported if (!(modifiers & Modifier::Alphanumeric) && pattern.find_first_of(u8"*?") != pattern.npos) return; // return if no lower letter if (std::find_if(pattern.begin(), pattern.end(), [](char8_t c) { return u8'a' <= c && c <= u8'z'; }) == pattern.end()) { return; } // could be `CPP;py`, but that's a rare case // return if termtext is an absolute path if (pattern.size() > 1 && pattern[1] == u8':' && 'A' <= ib::toupper(pattern[0]) && ib::toupper(pattern[0]) <= 'Z') return; // "Match path when a search term contains a path separator" if (!(modifiers & Modifier::Path) && std::find(pattern.begin(), pattern.end(), u8'\\') != pattern.end()) { *modifiers_p |= Modifier::Path; } // set regex modifier *modifiers_p |= Modifier::RegEx; // may cause crashes under some versions? // bypass fast regex optimazation termtext_initial = termtext[0]; // .\[^$*{?+|() // $: invalid when termtext is a single char termtext[0] = u8'.'; //#TODO: or nofastregex: (v1.5.0.1291) } #pragma pack(push, 1) struct regcomp_p2_14 { ib::Byte gap0[24]; void* result18; void* result20; Modifier::Value modifiers; uint32_t int2C; char8_t termtext[]; }; #pragma pack(pop) bool (*regcomp_p2_14_real)(void* a1, regcomp_p2_14* a2); bool regcomp_p2_14_detour(void* a1, regcomp_p2_14* a2) { if constexpr (debug) DebugOStream() << L"regcomp_p2_14(" << std::hex << a2 << L"{" << a2->int2C << "})\n"; size_t termtext_len = strlen((char*)a2->termtext); regcomp_p2_common(&a2->modifiers, a2->termtext, &termtext_len); a2->termtext[termtext_len] = u8'\0'; if constexpr (debug) { bool result = regcomp_p2_14_real(a1, a2); DebugOStream() << L"-> {" << a2->result18 << L", " << a2->result20 << L", " << std::hex << a2->modifiers << L"}\n"; return result; } return regcomp_p2_14_real(a1, a2); } bool (*regcomp_p2_15_real)(void** a1); bool regcomp_p2_15_detour(void** a1) { char8_t* termtext = ib::Addr(a1[1]) + 288; size_t* termtext_len = ib::Addr(a1[1]) + 256; assert(termtext[*termtext_len] == u8'\0'); regcomp_p2_common(ib::Addr(a1[1]) + 280, termtext, termtext_len); termtext[*termtext_len] = u8'\0'; return regcomp_p2_15_real(a1); } #pragma endregion #pragma region regcomp #define PCRE_CALL_CONVENTION /* Options, mostly defined by POSIX, but with some extras. */ #define REG_ICASE 0x0001 /* Maps to PCRE_CASELESS */ #define REG_NEWLINE 0x0002 /* Maps to PCRE_MULTILINE */ #define REG_NOTBOL 0x0004 /* Maps to PCRE_NOTBOL */ #define REG_NOTEOL 0x0008 /* Maps to PCRE_NOTEOL */ #define REG_DOTALL 0x0010 /* NOT defined by POSIX; maps to PCRE_DOTALL */ #define REG_NOSUB 0x0020 /* Maps to PCRE_NO_AUTO_CAPTURE */ #define REG_UTF8 0x0040 /* NOT defined by POSIX; maps to PCRE_UTF8 */ #define REG_STARTEND 0x0080 /* BSD feature: pass subject string by so,eo */ #define REG_NOTEMPTY 0x0100 /* NOT defined by POSIX; maps to PCRE_NOTEMPTY */ #define REG_UNGREEDY 0x0200 /* NOT defined by POSIX; maps to PCRE_UNGREEDY */ #define REG_UCP 0x0400 /* NOT defined by POSIX; maps to PCRE_UCP */ /* Error values. Not all these are relevant or used by the wrapper. */ enum { REG_ASSERT = 1, /* internal error ? */ REG_BADBR, /* invalid repeat counts in {} */ REG_BADPAT, /* pattern error */ REG_BADRPT, /* ? * + invalid */ REG_EBRACE, /* unbalanced {} */ REG_EBRACK, /* unbalanced [] */ REG_ECOLLATE, /* collation error - not relevant */ REG_ECTYPE, /* bad class */ REG_EESCAPE, /* bad escape sequence */ REG_EMPTY, /* empty expression */ REG_EPAREN, /* unbalanced () */ REG_ERANGE, /* bad range inside [] */ REG_ESIZE, /* expression too big */ REG_ESPACE, /* failed to get memory */ REG_ESUBREG, /* bad back reference */ REG_INVARG, /* bad argument */ REG_NOMATCH /* match failed */ }; /* The structure representing a compiled regular expression. */ struct regex_t { void* re_pcre; size_t re_nsub; size_t re_erroffset; }; /* The structure in which a captured offset is returned. */ using regoff_t = int; struct regmatch_t { regoff_t rm_so; regoff_t rm_eo; }; /************************************************* * Compile a regular expression * *************************************************/ /* Arguments: preg points to a structure for recording the compiled expression pattern the pattern to compile cflags compilation flags Returns: 0 on success various non-zero codes on failure */ int PCRE_CALL_CONVENTION (*regcomp_real)(regex_t* preg, const char* pattern, int cflags); int PCRE_CALL_CONVENTION regcomp_detour(regex_t* preg, const char* pattern, int cflags) { if constexpr (debug) { size_t length = strlen(pattern); std::wstring pattern_u16(length, L'\0'); pattern_u16.resize(MultiByteToWideChar(CP_UTF8, 0, pattern, length, pattern_u16.data(), pattern_u16.size())); DebugOStream() << LR"(regcomp(")" << pattern_u16 << LR"(", )" << std::hex << cflags << L")\n"; } if (modifiers & Modifier::RegEx) { return regcomp_real(preg, pattern, cflags); } const_cast<char*>(pattern)[0] = termtext_initial; Pattern* compiled_pattern = compile((const char8_t*)pattern, { .match_at_start = bool(modifiers & Modifier::WholeFilename), .match_at_end = bool(modifiers & Modifier::WholeFilename) }, &config.pinyin_search.flags); preg->re_pcre = (void*)((uintptr_t)compiled_pattern | 1); preg->re_nsub = 0; preg->re_erroffset = (size_t)-1; if constexpr (debug) DebugOStream() << L"-> " << preg->re_pcre << L'\n'; return 0; } #pragma endregion #pragma region pcre_compile2 (not in use) using pcre = void; using pcre_extra = void; using PCRE_SPTR = const char*; /************************************************* * Compile a Regular Expression * *************************************************/ /* This function takes a string and returns a pointer to a block of store holding a compiled version of the expression. The original API for this function had no error code return variable; it is retained for backwards compatibility. The new function is given a new name. Arguments: pattern the regular expression options various option bits errorcodeptr pointer to error code variable (pcre_compile2() only) can be NULL if you don't want a code value errorptr pointer to pointer to error text erroroffset ptr offset in pattern where error was detected tables pointer to character tables or NULL Returns: pointer to compiled data block, or NULL on error, with errorptr and erroroffset set */ [[deprecated]] static auto _comment = R"*( pcre* PCRE_CALL_CONVENTION (*pcre_compile2_real)(const char* pattern, int options, int* errorcodeptr, const char** errorptr, int* erroroffset, const unsigned char* tables); [[deprecated]] pcre* PCRE_CALL_CONVENTION pcre_compile2_detour(const char* pattern, int options, int* errorcodeptr, const char** errorptr, int* erroroffset, const unsigned char* tables) { if (!(modifiers & Modifier::RegEx)) { const_cast<char*>(pattern)[0] = termtext_initial; } if constexpr (debug) { size_t pattern_len = strlen(pattern); std::wstring pattern_u16(pattern_len, L'\0'); pattern_u16.resize(MultiByteToWideChar(CP_UTF8, 0, pattern, pattern_len, pattern_u16.data(), pattern_u16.size())); DebugOStream() << LR"(pcre_compile2(")" << pattern_u16 << LR"(", )" << std::hex << options << std::dec << L", " << errorcodeptr << L", " << errorptr << L", " << erroroffset << L", " << tables << std::hex << L") on " << GetCurrentThreadId() << L"\n"; /* pcre_compile2(".", PCRE_UCP | PCRE_UTF8 | PCRE_CASELESS, 0x0020E9D8, 0x0020E9A0, 0x0020E9C0, nullptr) pcre_compile2(".", PCRE_UCP | PCRE_UTF8 | PCRE_CASELESS, 0x0020E9D8, 0x0020E9A0, 0x0020E9C0, nullptr) single thread */ } if (modifiers & Modifier::RegEx) { if constexpr (debug) { pcre* re = pcre_compile2_real(pattern, options, errorcodeptr, errorptr, erroroffset, tables); DebugOStream() << re << L'\n'; return re; } return pcre_compile2_real(pattern, options, errorcodeptr, errorptr, erroroffset, tables); } /* size_t len = strlen(pattern) + 1; // new and malloc will make the process crash under Debug config (although they are also in the process heap) //char* pat = new char[len]; //char* pat = (char*)malloc(len); char* pat = (char*)HeapAlloc(GetProcessHeap(), 0, len); memcpy(pat, pattern, len); if constexpr (debug) DebugOStream() << (void*)pat << L'\n'; return (pcre*)pat; */ return (pcre*)compile((const char8_t*)pattern, 0, &config.pinyin_search.flags); } )*"; #pragma endregion #pragma region pcre_fullinfo (not in use) // pcre_fullinfo (not in use) /************************************************* * Return info about compiled pattern * *************************************************/ /* This is a newer "info" function which has an extensible interface so that additional items can be added compatibly. Arguments: argument_re points to compiled code extra_data points extra data, or NULL what what information is required where where to put the information Returns: 0 if data returned, negative on error */ /* int PCRE_CALL_CONVENTION (*pcre_fullinfo_real)(const pcre* argument_re, const pcre_extra* extra_data, int what, void* where); int PCRE_CALL_CONVENTION pcre_fullinfo_detour(const pcre* argument_re, const pcre_extra* extra_data, int what, void* where) { constexpr int PCRE_INFO_CAPTURECOUNT = 2; if constexpr (debug) DebugOStream() << L"pcre_fullinfo(" << argument_re << L", " << extra_data << L", " << what << L", " << where << L")\n"; if (modifiers & Modifier::RegEx) { int result = pcre_fullinfo_real(argument_re, extra_data, what, where); if constexpr (debug) DebugOStream() << *(int*)where << L'\n'; return result; } if (what == PCRE_INFO_CAPTURECOUNT) { *(int*)where = 0; } return 0; } */ #pragma endregion #pragma region regexec /************************************************* * Match a regular expression * *************************************************/ /* Unfortunately, PCRE requires 3 ints of working space for each captured substring, so we have to get and release working store instead of just using the POSIX structures as was done in earlier releases when PCRE needed only 2 ints. However, if the number of possible capturing brackets is small, use a block of store on the stack, to reduce the use of malloc/free. The threshold is in a macro that can be changed at configure time. If REG_NOSUB was specified at compile time, the PCRE_NO_AUTO_CAPTURE flag will be set. When this is the case, the nmatch and pmatch arguments are ignored, and the only result is yes/no/error. */ int PCRE_CALL_CONVENTION (*regexec_real)(const regex_t* preg, const char* string, size_t nmatch, regmatch_t pmatch[], int eflags); int PCRE_CALL_CONVENTION regexec_detour(const regex_t* preg, const char* string, size_t nmatch, regmatch_t pmatch[], int eflags) { if constexpr (debug) { do { thread_local const regex_t* last_preg = nullptr; thread_local size_t count = 0; if (preg == last_preg) { if (count > 1) break; else ++count; } else { last_preg = preg; count = 1; } //int length = eflags & REG_STARTEND ? pmatch[0].rm_eo : strlen(string); int length, start; if (eflags & REG_STARTEND) { // string is not zero-terminated start = pmatch[0].rm_so; string += start; length = pmatch[0].rm_eo - start; } else { start = 0; length = strlen(string); } std::wstring string_u16(length, L'\0'); string_u16.resize(MultiByteToWideChar(CP_UTF8, 0, string, length, string_u16.data(), string_u16.size())); auto dout = DebugOStream(); dout << LR"(regexec(")" << string_u16 << LR"(", )" << std::hex << eflags << std::dec; if (eflags & REG_STARTEND) dout << L", {" << pmatch[0].rm_so << L"," << pmatch[0].rm_eo << L"}"; dout << L") -> "; int error; int rc; if (modifiers & Modifier::RegEx) { string -= start; error = regexec_real(preg, string, nmatch, pmatch, eflags); rc = 1 + preg->re_nsub; } else { rc = exec((Pattern*)((uintptr_t)preg->re_pcre & ~1), (const char8_t*)string, length, nmatch, (int*)pmatch, { .not_begin_of_line = bool(eflags & REG_NOTBOL) }); if (rc == -1) error = REG_NOMATCH; else error = 0; } dout << rc; if (error == REG_NOMATCH) { dout << L"\n"; return error; } for (int i = 0; i < rc; i++) { dout << L"{" << pmatch[i].rm_so << L"," << pmatch[i].rm_eo << L"}"; } dout << L'\n'; return 0; } while (false); } if (modifiers & Modifier::RegEx) { return regexec_real(preg, string, nmatch, pmatch, eflags); } int length, start; if (eflags & REG_STARTEND) { // string is not zero-terminated start = pmatch[0].rm_so; string += start; length = pmatch[0].rm_eo - start; } else { length = strlen(string); } int rc = exec((Pattern*)((uintptr_t)preg->re_pcre & ~1), (const char8_t*)string, length, nmatch, (int*)pmatch, { .not_begin_of_line = bool(eflags & REG_NOTBOL) }); if (rc == -1) { return REG_NOMATCH; } // Everything removes this characteristic from PCRE regexec /* if (eflags & REG_STARTEND) { for (int i = 0; i < rc; i++) { pmatch[i].rm_so += start; pmatch[i].rm_eo += start; } } */ return 0; } #pragma endregion #pragma region pcre_exec (not in use) /************************************************* * Execute a Regular Expression * *************************************************/ /* This function applies a compiled re to a subject string and picks out portions of the string if it matches. Two elements in the vector are set for each substring: the offsets to the start and end of the substring. Arguments: argument_re points to the compiled expression extra_data points to extra data or is NULL subject points to the subject string length length of subject string (may contain binary zeros) start_offset where to start in the subject string options option bits offsets points to a vector of ints to be filled in with offsets offsetcount the number of elements in the vector Returns: > 0 => success; value is the number of elements filled in = 0 => success, but offsets is not big enough -1 => failed to match < -1 => some kind of unexpected problem */ [[deprecated]] auto _comment1 = R"*( int PCRE_CALL_CONVENTION (*pcre_exec_real)(const pcre* argument_re, const pcre_extra* extra_data, PCRE_SPTR subject, int length, int start_offset, int options, int* offsets, int offsetcount); int PCRE_CALL_CONVENTION pcre_exec_detour(const pcre* argument_re, const pcre_extra* extra_data, PCRE_SPTR subject, int length, int start_offset, int options, int* offsets, int offsetcount) { if constexpr (debug) { do { thread_local const pcre* last_re = nullptr; thread_local size_t count = 0; if (argument_re == last_re) { if (count++ > 10) break; } else { last_re = argument_re; count = 1; } std::wstring subject_u16(length, L'\0'); subject_u16.resize(MultiByteToWideChar(CP_UTF8, 0, subject, length, subject_u16.data(), subject_u16.size())); auto dout = DebugOStream(); dout << L"pcre_exec(" << argument_re /* << L", " << extra_data */ << LR"(, ")" << subject_u16 << LR"(", )" << length << L", " << start_offset << L", " << std::hex << options << std::dec << L", " << offsets << L", " << offsetcount << L")" /* << std::hex << L" on " << GetCurrentThreadId() */; /* pcre_exec(0x03CC42A0, nullptr, "test.txt", 8, 0, 0, 0x0020E910, 30) pcre_exec(0x03CC42A0, nullptr, "test.txt", 8, 0, 0, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "est.txt", 7, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "st.txt", 6, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "t.txt", 5, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, ".txt", 4, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "txt", 3, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "xt", 2, 0, PCRE_NOTBOL, 0x0020EB60, 30) pcre_exec(0x03CC42A0, nullptr, "t", 1, 0, PCRE_NOTBOL, 0x0020EB60, 30) multi threads */ if (modifiers & Modifier::RegEx) { dout << L'\n'; break; } int result = match((Pattern*)argument_re, (const char8_t*)subject, length, offsets, offsetcount); dout << L" -> " << result; if (result > 0) dout << L", " << offsets[0] << L", " << offsets[1]; dout << L'\n'; return result; } while (false); } if (modifiers & Modifier::RegEx) { return pcre_exec_real(argument_re, extra_data, subject, length, start_offset, options, offsets, offsetcount); } return match((Pattern*)argument_re, (const char8_t*)subject, length, offsets, offsetcount); } )*"; #pragma endregion #pragma region free /* bool (*regex_free_real)(void* result); bool regex_free_detour(void* result) { // a2->result18, a2->result20 if constexpr (debug) DebugOStream() << L"regex_free(" << result << L") on " << std::hex << GetCurrentThreadId() << L"\n"; return regex_free_real(result); } */ auto HeapFree_real = HeapFree; _Success_(return != FALSE) BOOL WINAPI HeapFree_detour( _Inout_ HANDLE hHeap, _In_ DWORD dwFlags, __drv_freesMem(Mem) _Frees_ptr_opt_ LPVOID lpMem) { /* if constexpr (debug) DebugOStream() << L"HeapFree(" << lpMem << L")\n"; // multi threads */ if ((uintptr_t)lpMem & 1) { if constexpr (debug) DebugOStream() << L"HeapFree(" << lpMem << L")\n"; delete (Pattern*)((uintptr_t)lpMem & ~1); return true; } return HeapFree_real(hHeap, dwFlags, lpMem); } #pragma endregion PinyinSearchPcre::PinyinSearchPcre() { bool support = true; ib::Addr Everything = ib::ModuleFactory::CurrentProcess().base; if (ipc_version.major == 1 && ipc_version.minor == 4 && ipc_version.revision == 1) { if (ipc_version.build == 1009) { regcomp_p3_14_real = Everything + 0x174C0; regcomp_p2_14_real = Everything + 0x5CB70; regcomp_real = Everything + 0x1A8E80; //pcre_compile2_real = Everything + 0x193340; //pcre_fullinfo_real = Everything + 0x1A7BF0; regexec_real = Everything + 0x1A8F60; //pcre_exec_real = Everything + 0x1A69E0; //regex_free_real = Everything + 0x5D990; } else if (ipc_version.build == 1015) { regcomp_p3_14_real = Everything + 0x175A0; regcomp_p2_14_real = Everything + 0x5CEC0; regcomp_real = Everything + 0x1A8FC0; regexec_real = Everything + 0x1A90A0; } else support = false; if (support) { IbDetourAttach(&regcomp_p3_14_real, regcomp_p3_14_detour); IbDetourAttach(&regcomp_p2_14_real, regcomp_p2_14_detour); } } else if (ipc_version.major == 1 && ipc_version.minor == 5 && ipc_version.revision == 0) { if (ipc_version.build == 1296) { regcomp_p3_15_real = Everything + 0x2D170; regcomp_p2_15_real = Everything + 0xB17A0; regcomp_real = Everything + 0x320800; regexec_real = Everything + 0x3208E0; } else support = false; if (support) { IbDetourAttach(&regcomp_p3_15_real, regcomp_p3_15_detour); IbDetourAttach(&regcomp_p2_15_real, regcomp_p2_15_detour); } } else support = false; if (!support) throw std::runtime_error("Unsupported Everything version"); IbDetourAttach(&regcomp_real, regcomp_detour); //IbDetourAttach(&pcre_compile2_real, pcre_compile2_detour); //IbDetourAttach(&pcre_fullinfo_real, pcre_fullinfo_detour); IbDetourAttach(&regexec_real, regexec_detour); //IbDetourAttach(&pcre_exec_real, pcre_exec_detour); //IbDetourAttach(&regex_free_real, regex_free_detour); IbDetourAttach(&HeapFree_real, HeapFree_detour); } PinyinSearchPcre::~PinyinSearchPcre() { IbDetourDetach(&HeapFree_real, HeapFree_detour); //IbDetourDetach(&regex_free_real, regex_free_detour); //IbDetourDetach(&pcre_exec_real, pcre_exec_detour); IbDetourDetach(&regexec_real, regexec_detour); //IbDetourDetach(&pcre_fullinfo_real, pcre_fullinfo_detour); //IbDetourDetach(&pcre_compile2_real, pcre_compile2_detour); IbDetourDetach(&regcomp_real, regcomp_detour); if (ipc_version.major == 1 && ipc_version.minor == 4) { IbDetourDetach(&regcomp_p2_14_real, regcomp_p2_14_detour); IbDetourDetach(&regcomp_p3_14_real, regcomp_p3_14_detour); } else if (ipc_version.major == 1 && ipc_version.minor == 5) { IbDetourDetach(&regcomp_p2_15_real, regcomp_p2_15_detour); IbDetourDetach(&regcomp_p3_15_real, regcomp_p3_15_detour); } }
11,804
407
<filename>paas/appmanager/tesla-appmanager-definition/src/main/java/com/alibaba/tesla/appmanager/definition/service/DefinitionSchemaService.java package com.alibaba.tesla.appmanager.definition.service; import com.alibaba.tesla.appmanager.common.pagination.Pagination; import com.alibaba.tesla.appmanager.definition.repository.condition.DefinitionSchemaQueryCondition; import com.alibaba.tesla.appmanager.definition.repository.domain.DefinitionSchemaDO; /** * Definition Schema 服务 * * @author <EMAIL> */ public interface DefinitionSchemaService { /** * 根据指定条件查询对应的 definition schema 列表 * * @param condition 条件 * @param operator 操作人 * @return Page of DefinitionSchema */ Pagination<DefinitionSchemaDO> list(DefinitionSchemaQueryCondition condition, String operator); /** * 根据指定条件查询对应的 definition schema (期望只返回一个) * * @param condition 条件 * @param operator 操作人 * @return Page of DefinitionSchema */ DefinitionSchemaDO get(DefinitionSchemaQueryCondition condition, String operator); /** * 向系统中新增或更新一个 Definition Schema * * @param request 记录的值 * @param operator 操作人 */ void apply(DefinitionSchemaDO request, String operator); /** * 删除指定条件的 Definition Schema * * @param condition 条件 * @param operator 操作人 * @return 删除的数量 (0 or 1) */ int delete(DefinitionSchemaQueryCondition condition, String operator); }
632
311
package org.thunlp.tagsuggest.common; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.thunlp.language.chinese.ForwardMaxWordSegment; import org.thunlp.language.chinese.LangUtils; import org.thunlp.language.chinese.WordSegment; public class SimpleExtractor implements FeatureExtractor { WordSegment ws = null; boolean useContent = true; public SimpleExtractor() { try { ws = new ForwardMaxWordSegment(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public SimpleExtractor(Properties config) { this(); if (!config.getProperty("usecontent", "true").equals("true")) { useContent = false; } } @Override public String[] extract(Post p) { String content = p.getTitle(); if (content == null) content = ""; if (useContent) { content += " " + p.getContent(); } content = LangUtils.removePunctuationMarks(content); content = LangUtils.removeLineEnds(content); content = LangUtils.removeExtraSpaces(content); content = content.toLowerCase(); String [] words = ws.segment(content); List<String> filtered = new LinkedList<String>(); for (String word : words) { if (word.length() <= 1) continue; if (org.thunlp.language.english.Stopwords.isStopword(word)) continue; if (org.thunlp.language.chinese.Stopwords.isStopword(word)) continue; filtered.add(word); } return filtered.toArray(new String[filtered.size()]); } }
612
707
<reponame>gcjurgiel/allwpilib<filename>hal/src/main/java/edu/wpi/first/hal/simulation/AddressableLEDDataJNI.java // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package edu.wpi.first.hal.simulation; import edu.wpi.first.hal.JNIWrapper; public class AddressableLEDDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); public static native void cancelInitializedCallback(int index, int uid); public static native boolean getInitialized(int index); public static native void setInitialized(int index, boolean initialized); public static native int registerOutputPortCallback( int index, NotifyCallback callback, boolean initialNotify); public static native void cancelOutputPortCallback(int index, int uid); public static native int getOutputPort(int index); public static native void setOutputPort(int index, int outputPort); public static native int registerLengthCallback( int index, NotifyCallback callback, boolean initialNotify); public static native void cancelLengthCallback(int index, int uid); public static native int getLength(int index); public static native void setLength(int index, int length); public static native int registerRunningCallback( int index, NotifyCallback callback, boolean initialNotify); public static native void cancelRunningCallback(int index, int uid); public static native boolean getRunning(int index); public static native void setRunning(int index, boolean running); public static native int registerDataCallback(int index, ConstBufferCallback callback); public static native void cancelDataCallback(int index, int uid); public static native byte[] getData(int index); public static native void setData(int index, byte[] data); public static native void resetData(int index); public static native int findForChannel(int channel); }
533
3,084
<reponame>ixjf/Windows-driver-samples<filename>wpd/WpdServiceSampleDriver/FakeContactContent.cpp #include "stdafx.h" #include "FakeContactContent.tmh" // Properties supported by a contact const PropertyAttributeInfo g_SupportedContactProperties[] = { // Standard WPD properties. {&WPD_OBJECT_ID, VT_LPWSTR, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, NAME_GenericObj_ObjectID}, {&WPD_OBJECT_PERSISTENT_UNIQUE_ID, VT_LPWSTR, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, NAME_GenericObj_PersistentUID}, {&WPD_OBJECT_PARENT_ID, VT_LPWSTR, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, NAME_GenericObj_ParentID}, {&WPD_OBJECT_NAME, VT_LPWSTR, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, NAME_GenericObj_Name}, {&WPD_OBJECT_FORMAT, VT_CLSID, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, NAME_GenericObj_ObjectFormat}, {&WPD_OBJECT_CONTENT_TYPE, VT_CLSID, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, L"ObjectContentType"}, {&WPD_OBJECT_CAN_DELETE, VT_BOOL, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, L"ObjectCanDelete"}, {&WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID, VT_LPWSTR, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, L"StorageID"}, // Contact Service extension properties {&PKEY_ContactObj_GivenName, VT_LPWSTR, UnspecifiedForm_CanRead_CanWrite_CannotDelete_Fast, NAME_ContactObj_GivenName}, {&PKEY_ContactObj_FamilyName, VT_LPWSTR, UnspecifiedForm_CanRead_CanWrite_CannotDelete_Fast, NAME_ContactObj_FamilyName}, // Custom property used to store the version of this object {&MyContactVersionIdentifier, VT_UI4, UnspecifiedForm_CanRead_CannotWrite_CannotDelete_Fast, L"ContactVersionIdentifier"}, }; HRESULT GetSupportedContactProperties( _In_ IPortableDeviceKeyCollection *pKeys) { HRESULT hr = S_OK; if(pKeys == NULL) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL collection parameter"); return hr; } for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(g_SupportedContactProperties); dwIndex++) { hr = pKeys->Add(*g_SupportedContactProperties[dwIndex].pKey); CHECK_HR(hr, "Failed to add custom contacts property"); } return hr; } HRESULT GetContactPropertyAttributes( _In_ REFPROPERTYKEY Key, _In_ IPortableDeviceValues* pAttributes) { HRESULT hr = S_OK; if(pAttributes == NULL) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL parameter"); return hr; } hr = SetPropertyAttributes(Key, &g_SupportedContactProperties[0], ARRAYSIZE(g_SupportedContactProperties), pAttributes); return hr; } // For this object, the supported properties are the same as the supported // format properties. // This is where customization for supported properties per object can happen HRESULT FakeContactContent::GetSupportedProperties( _In_ IPortableDeviceKeyCollection *pKeys) { return GetSupportedContactProperties(pKeys); } HRESULT FakeContactContent::GetValue( _In_ REFPROPERTYKEY Key, _In_ IPortableDeviceValues* pStore) { HRESULT hr = S_OK; PropVariantWrapper pvValue; if(pStore == NULL) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL parameter"); return hr; } if (IsEqualPropertyKey(Key, WPD_OBJECT_ID)) { // Add WPD_OBJECT_ID pvValue = ObjectID; hr = pStore->SetValue(WPD_OBJECT_ID, &pvValue); CHECK_HR(hr, ("Failed to set WPD_OBJECT_ID")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_PERSISTENT_UNIQUE_ID)) { // Add WPD_OBJECT_PERSISTENT_UNIQUE_ID pvValue = this->PersistentUniqueID; hr = pStore->SetValue(WPD_OBJECT_PERSISTENT_UNIQUE_ID, &pvValue); CHECK_HR(hr, ("Failed to set WPD_OBJECT_PERSISTENT_UNIQUE_ID")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_PARENT_ID)) { // Add WPD_OBJECT_PARENT_ID pvValue = ParentID; hr = pStore->SetValue(WPD_OBJECT_PARENT_ID, &pvValue); CHECK_HR(hr, ("Failed to set WPD_OBJECT_PARENT_ID")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_NAME)) { // Add WPD_OBJECT_NAME pvValue = Name; hr = pStore->SetValue(WPD_OBJECT_NAME, &pvValue); CHECK_HR(hr, ("Failed to set WPD_OBJECT_NAME")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_CONTENT_TYPE)) { // Add WPD_OBJECT_CONTENT_TYPE hr = pStore->SetGuidValue(WPD_OBJECT_CONTENT_TYPE, ContentType); CHECK_HR(hr, ("Failed to set WPD_OBJECT_CONTENT_TYPE")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_FORMAT)) { // Add WPD_OBJECT_FORMAT hr = pStore->SetGuidValue(WPD_OBJECT_FORMAT, Format); CHECK_HR(hr, ("Failed to set WPD_OBJECT_FORMAT")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_CAN_DELETE)) { // Add WPD_OBJECT_CAN_DELETE hr = pStore->SetBoolValue(WPD_OBJECT_CAN_DELETE, CanDelete); CHECK_HR(hr, ("Failed to set WPD_OBJECT_CAN_DELETE")); } else if (IsEqualPropertyKey(Key, WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID)) { // Add WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID hr = pStore->SetStringValue(WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID, ContainerFunctionalObjectID); CHECK_HR(hr, ("Failed to set WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID")); } else if (IsEqualPropertyKey(Key, PKEY_ContactObj_GivenName)) { // Add PKEY_ContactObj_GivenName pvValue = GivenName; hr = pStore->SetValue(PKEY_ContactObj_GivenName, &pvValue); CHECK_HR(hr, ("Failed to set PKEY_ContactObj_GivenName")); } else if (IsEqualPropertyKey(Key, PKEY_ContactObj_FamilyName)) { // Add PKEY_ContactObj_FamilyName pvValue = FamilyName; hr = pStore->SetValue(PKEY_ContactObj_FamilyName, &pvValue); CHECK_HR(hr, ("Failed to set PKEY_ContactObj_FamilyName")); } else if (IsEqualPropertyKey(Key, MyContactVersionIdentifier)) { // Add MyContactVersionIdentifier pvValue = VersionIdentifier; hr = pStore->SetValue(MyContactVersionIdentifier, &pvValue); CHECK_HR(hr, ("Failed to set MyContactVersionIdentifier")); } else { hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); CHECK_HR(hr, "Property {%ws}.%d is not supported", CComBSTR(Key.fmtid), Key.pid); } return hr; } HRESULT FakeContactContent::WriteValue( _In_ REFPROPERTYKEY Key, _In_ REFPROPVARIANT Value) { HRESULT hr = S_OK; PropVariantWrapper pvValue; if(IsEqualPropertyKey(Key, PKEY_ContactObj_FamilyName)) { if(Value.vt == VT_LPWSTR) { FamilyName = Value.pwszVal; } else { hr = E_INVALIDARG; CHECK_HR(hr, "Failed to set PKEY_ContactObj_FamilyName because type was not VT_LPWSTR"); } } else if(IsEqualPropertyKey(Key, PKEY_ContactObj_GivenName)) { if(Value.vt == VT_LPWSTR) { GivenName = Value.pwszVal; } else { hr = E_INVALIDARG; CHECK_HR(hr, "Failed to set PKEY_ContactObj_GivenName because type was not VT_LPWSTR"); } } else { hr = E_ACCESSDENIED; CHECK_HR(hr, "Property %ws.%d on [%ws] does not support set value operation", CComBSTR(Key.fmtid), Key.pid, ObjectID); } return hr; } HRESULT FakeContactContent::GetPropertyAttributes( _In_ REFPROPERTYKEY Key, _In_ IPortableDeviceValues* pAttributes) { HRESULT hr = S_OK; if(pAttributes == NULL) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL attributes parameter"); return hr; } hr = GetContactPropertyAttributes(Key, pAttributes); CHECK_HR(hr, "Failed to add property attributes for %ws.%d", CComBSTR(Key.fmtid), Key.pid); // Some of our properties have extra attributes on top of the ones that are common to all if(IsEqualPropertyKey(Key, WPD_OBJECT_NAME)) { CAtlStringW strDefaultName; strDefaultName.Format(L"%ws%ws", L"Name", ObjectID.GetString()); hr = pAttributes->SetStringValue(WPD_PROPERTY_ATTRIBUTE_DEFAULT_VALUE, strDefaultName.GetString());; CHECK_HR(hr, "Failed to set WPD_PROPERTY_ATTRIBUTE_DEFAULT_VALUE"); } return hr; } HRESULT FakeContactContent::WriteValues( _In_ IPortableDeviceValues* pValues, _In_ IPortableDeviceValues* pResults, _Out_ bool* pbObjectChanged) { HRESULT hr = FakeContent::WriteValues(pValues, pResults, pbObjectChanged); if (SUCCEEDED(hr) && (*pbObjectChanged == true)) { UpdateVersion(); } return hr; } void FakeContactContent::UpdateVersion() { if (VersionIdentifier < ULONG_MAX) { VersionIdentifier++; } else { VersionIdentifier = 0; } }
4,499
354
#include<bits/stdc++.h> using namespace std; int main() { int n,a; float med=0; cout<<"Enter the number of elements in array : "; cin>>n; cout<<"Enter the elements : "; if(n%2==0) { for(int i=0;i<n;i++) { cin>>a; if(i==n/2||i==n/2-1) { med=med+a; } } cout<<"The median is : "<<med/2<<endl; return 0; } for(int i=0;i<n;i++) { cin>>a; if(i==n/2) { cout<<"The median is: "<<a<<endl; return 0; } } }
387
722
<gh_stars>100-1000 // Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include <cstring> #include "uni.h" #include "cpu/x86/int8/tensor_computing_int8.h" template <U32 N> inline EE transformNCHWToNCHWCxNxCx( TensorDesc filterDesc, const INT8 *filterArray, TensorDesc ftmDesc, INT8 *ftmArray, U32 cx) { if (filterArray == NULL || ftmArray == NULL) { CHECK_STATUS(NULL_POINTER); } DataType fdt; DataFormat fdf; U32 fn, fc, fh, fw; CHECK_STATUS(tensor4dGet(filterDesc, &fdt, &fdf, &fn, &fc, &fh, &fw)); U32 fhfw = fh * fw; U32 count = 0; U32 nx = N; if (fn % 32 == 0 && fn % N != 0) { nx = 32; } U32 remain = fn % nx; U32 fcPadding = (fc + 3) / 4 * 4; I32 *offsetC = (I32 *)ftmArray; ftmArray += fn * bytesOf(DT_I32); for (U32 n = 0; n < fn; ++n) { I32 sum = 0; for (U32 i = 0; i < fc * fhfw; ++i) { sum += filterArray[i + n * fc * fhfw]; } offsetC[n] = -128 * sum; } U32 nxArray[4] = {8, 16, 32, 48}; for (; count < fn; count += nx) { nx = UNI_MIN(fn - count, nx); nx = nxArray[nx >> 4]; U32 c = 0; U32 realCx = cx; for (; c < fc / realCx; ++c) { for (U32 hw = 0; hw < fhfw; ++hw) { for (U32 c2 = 0; c2 < realCx; c2 += 4) { for (U32 n = 0; n < nx; ++n) { for (U32 c4 = 0; c4 < 4; ++c4) { U32 iIdx = (n + count) * fc * fhfw + (c4 + c2 + c * realCx) * fhfw + hw; U32 oIdx = count * fc * fhfw + c * realCx * nx * fhfw + hw * nx * realCx + c2 * nx + n * 4 + c4; ftmArray[oIdx] = filterArray[iIdx]; } } } } } c *= realCx; U32 resC = fcPadding - c; while (resC > 0) { U32 icx = fc - c; realCx = (resC == 12) ? 8 : resC; // resC: 4, 8, 12, 16 for (U32 hw = 0; hw < fhfw; ++hw) { for (U32 c2 = 0; c2 < realCx; c2 += 4) { for (U32 n = 0; n < nx; ++n) { for (U32 c4 = 0; c4 < 4; ++c4) { U32 iIdx = (n + count) * fc * fhfw + (c4 + c2 + c) * fhfw + hw; U32 oIdx = count * fc * fhfw + c * nx * fhfw + hw * nx * realCx + c2 * nx + n * 4 + c4; if (c2 + c4 < icx) { ftmArray[oIdx] = filterArray[iIdx]; } else { ftmArray[oIdx] = 0; } } } } } resC -= realCx; c += realCx; } } return SUCCESS; } inline EE convolution_transform_filter_kernel_int8(TensorDesc filterDesc, const INT8 *filterArray, TensorDesc *ftmDesc, INT8 *ftmArray, DataFormat ftmDataFormat, U32 cx) { if (nullptr == filterArray || nullptr == ftmDesc || nullptr == ftmArray) { CHECK_STATUS(NULL_POINTER); } DataType fdt; DataFormat fdf; U32 fn, fc, fh, fw; CHECK_STATUS(tensor4dGet(filterDesc, &fdt, &fdf, &fn, &fc, &fh, &fw)); if (fdf == ftmDataFormat) { *ftmDesc = filterDesc; memcpy(ftmArray, filterArray, fn * fc * fh * fw * bytesOf(fdt)); return SUCCESS; } if (fdf != DF_NCHW) { CHECK_STATUS(NOT_SUPPORTED); } EE ret = SUCCESS; U32 fcPadding = (fc + 3) / 4 * 4; switch (ftmDataFormat) { case DF_NCHWC2NxC4: { *ftmDesc = tensor4df(fdt, ftmDataFormat, fn, fcPadding, fh, fw); transformNCHWToNCHWCxNxCx<48>(filterDesc, filterArray, *ftmDesc, ftmArray, cx); break; } default: ret = NOT_SUPPORTED; break; } return ret; } EE convolution_transform_filter_int8(TensorDesc filterDesc, const INT8 *filter, ConvolutionParamSpec convParamSpec, ConvolutionForwardAlgorithm algorithm, TensorDesc *ftmDesc, INT8 *filterTransformed) { DataFormat ftmDataFormat; DataType fdt; DataFormat fdf; U32 fn, fc, fh, fw; CHECK_STATUS(tensor4dGet(filterDesc, &fdt, &fdf, &fn, &fc, &fh, &fw)); U32 cx = 0; U32 fnBlock = 0; fn = (fn + 7) / 8 * 8 / convParamSpec.group; switch (algorithm) { case CONVOLUTION_ALGORITHM_POINTWISE: case CONVOLUTION_ALGORITHM_DIRECT: { ftmDataFormat = DF_NCHWC2NxC4; fnBlock = 48; cx = 16; break; } default: return NOT_MATCH; } // CHECK_STATUS(InferConvWeightFormat(ftmDataFormat, fnBlock)); U32 channelAxis = filterDesc.nDims - 1; TensorDesc tmpFilterDesc = filterDesc; tmpFilterDesc.dims[channelAxis] /= convParamSpec.group; U32 fnPadding = (tmpFilterDesc.dims[channelAxis] + 7) / 8 * 8; U32 originalTileSize = tensorNumElements(tmpFilterDesc); for (U32 g = 0; g < convParamSpec.group; g++) { CHECK_STATUS(convolution_transform_filter_kernel_int8( tmpFilterDesc, filter, ftmDesc, filterTransformed, ftmDataFormat, cx)); U32 newTileSize = tensorNumElements(*ftmDesc) / tmpFilterDesc.dims[channelAxis] * fnPadding; filter += originalTileSize; filterTransformed += newTileSize; } ftmDesc->dims[channelAxis] = filterDesc.dims[channelAxis]; return SUCCESS; }
3,573
369
// Copyright (c) 2017-2021, Mudita <NAME>.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "Transform.hpp" #include <integer.hpp> #include <type_traits> #include <cassert> #include <cstdint> namespace audio::transcode { /** * @brief Basic interpolation transformation - for every Ratio samples it repeats * Ratio - 1 samples. The transformation is performed using basic integer type * to allow compiler to perform loop optimizations. The transformation is performed * in-place. The transformed signal is not filtered with a low-pass filter. * * @tparam SampleType - type of a single PCM sample, e.g., std::uint16_t for LPCM16 * @tparam Channels - number of channels; 1 for mono, 2 for stereo * @tparam Ratio - order of the interpolator; e.g.: for Ratio = 4 repeats first sample 3 * times for each block of 4 increasing sample rate by the factor of 4. */ template <typename SampleType, unsigned int Channels, unsigned int Ratio> class BasicInterpolator : public Transform { static_assert(Channels == 1 || Channels == 2); static_assert(std::is_integral<SampleType>::value); static_assert(Ratio > 0); /** * @brief Integer type to be used to read and write data from/to a buffer. */ using IntegerType = typename decltype(utils::integer::getIntegerType<sizeof(SampleType) * utils::integer::BitsInByte * Channels>())::type; public: auto transformBlockSize(std::size_t blockSize) const noexcept -> std::size_t override { return blockSize * Ratio; } auto transformBlockSizeInverted(std::size_t blockSize) const noexcept -> std::size_t override { return blockSize / Ratio; } auto transformFormat(const audio::AudioFormat &inputFormat) const noexcept -> audio::AudioFormat override { return audio::AudioFormat{ inputFormat.getSampleRate() * Ratio, inputFormat.getBitWidth(), inputFormat.getChannels()}; } auto validateInputFormat(const audio::AudioFormat &inputFormat) const noexcept -> bool override { return sizeof(SampleType) * utils::integer::BitsInByte == inputFormat.getBitWidth(); } auto transform(const Span &inputSpan, const Span &transformSpace) const -> Span override { auto outputSpan = Span{.data = transformSpace.data, .dataSize = transformBlockSize(inputSpan.dataSize)}; IntegerType *input = reinterpret_cast<IntegerType *>(inputSpan.data); IntegerType *output = reinterpret_cast<IntegerType *>(outputSpan.data); assert(outputSpan.dataSize <= transformSpace.dataSize); for (unsigned i = inputSpan.dataSize / sizeof(IntegerType); i > 0; i--) { for (unsigned j = 1; j <= Ratio; j++) { output[i * Ratio - j] = input[i - 1]; } } return outputSpan; } }; } // namespace audio::transcode
1,265
937
<filename>library/src/com/android/volley/misc/CountingOutputStream.java<gh_stars>100-1000 package com.android.volley.misc; import com.android.volley.Response.ProgressListener; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; public class CountingOutputStream extends DataOutputStream { private final ProgressListener progressListener; private long transferred; private long fileLength; public CountingOutputStream(final OutputStream out, long length, final ProgressListener listener) { super(out); fileLength = length; progressListener = listener; transferred = 0; } public void write(int b) throws IOException { out.write(b); if (progressListener != null) { transferred++; int prog = (int) (transferred * 100 / fileLength); progressListener.onProgress(transferred, prog); } } }
363
450
/******************************************************************** * 2014 - * open source under Apache License Version 2.0 ********************************************************************/ /** * 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 _HDFS_LIBHDFS3_CLIENT_PIPELINEACK_H_ #define _HDFS_LIBHDFS3_CLIENT_PIPELINEACK_H_ #include "datatransfer.pb.h" namespace Hdfs { namespace Internal { class PipelineAck { public: PipelineAck() : invalid(true) { } PipelineAck(const char * buf, int size) : invalid(false) { readFrom(buf, size); } bool isInvalid() { return invalid; } int getNumOfReplies() { return proto.status_size(); } int64_t getSeqno() { return proto.seqno(); } Status getReply(int i) { return proto.status(i); } bool isSuccess() { int size = proto.status_size(); for (int i = 0; i < size; ++i) { if (Status::DT_PROTO_SUCCESS != proto.status(i)) { return false; } } return true; } void readFrom(const char * buf, int size) { invalid = !proto.ParseFromArray(buf, size); } void reset() { proto.Clear(); invalid = true; } private: PipelineAckProto proto; bool invalid; }; } } #endif /* _HDFS_LIBHDFS3_CLIENT_PIPELINEACK_H_ */
785
377
<gh_stars>100-1000 # Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## """ This file contains the elementrary functions to build ResNet models. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import numpy as np from core.config import config as cfg import models.nonlocal_helper as nonlocal_helper logger = logging.getLogger(__name__) def bottleneck_transformation_3d( model, blob_in, dim_in, dim_out, stride, prefix, dim_inner, group=1, use_temp_conv=1, temp_stride=1): """ 3D bottleneck transformation. Note that the temporal convolution happens at the first convolution. """ conv_op = model.Conv3dAffine if cfg.MODEL.USE_AFFINE else model.Conv3dBN # 1x1 layer. blob_out = conv_op( blob_in, prefix + "_branch2a", dim_in, dim_inner, [1 + use_temp_conv * 2, 1, 1], strides=[temp_stride, 1, 1], pads=[use_temp_conv, 0, 0] * 2, inplace_affine=False, ) blob_out = model.Relu_(blob_out) # 3x3 layer. blob_out = conv_op( blob_out, prefix + "_branch2b", dim_inner, dim_inner, [1, 3, 3], strides=[1, stride, stride], pads=[0, cfg.DILATIONS, cfg.DILATIONS] * 2, group=group, inplace_affine=False, dilations=[1, cfg.DILATIONS, cfg.DILATIONS] ) logger.info('%s using dilation %d' % (prefix, cfg.DILATIONS)) blob_out = model.Relu_(blob_out) # 1x1 layer (without relu). blob_out = conv_op( blob_out, prefix + "_branch2c", dim_inner, dim_out, [1, 1, 1], strides=[1, 1, 1], pads=[0, 0, 0] * 2, inplace_affine=False, # must be False bn_init=cfg.MODEL.BN_INIT_GAMMA) # revise BN init of the last block return blob_out def _add_shortcut_3d( model, blob_in, prefix, dim_in, dim_out, stride, temp_stride=1): """Shortcut type B.""" if dim_in == dim_out and temp_stride == 1 and stride == 1: # Identity mapping (do nothing). return blob_in else: # When dimension changes. conv_op = model.Conv3dAffine if cfg.MODEL.USE_AFFINE else model.Conv3dBN return conv_op( blob_in, prefix, dim_in, dim_out, [1, 1, 1], strides=[temp_stride, stride, stride], pads=[0, 0, 0] * 2, group=1, inplace_affine=False,) def _generic_residual_block_3d( model, blob_in, dim_in, dim_out, stride, prefix, dim_inner, group=1, use_temp_conv=0, temp_stride=1, trans_func=None): """Residual block abstraction: x + F(x)""" # Transformation branch (e.g., 1x1-3x3-1x1, or 3x3-3x3), namely, "F(x)". if trans_func is None: trans_func = globals()[cfg.RESNETS.TRANS_FUNC] tr_blob = trans_func( model, blob_in, dim_in, dim_out, stride, prefix, dim_inner, group=group, use_temp_conv=use_temp_conv, temp_stride=temp_stride) # Creat shortcut, namely, "x". sc_blob = _add_shortcut_3d( model, blob_in, prefix + "_branch1", dim_in, dim_out, stride, temp_stride=temp_stride) # Addition, namely, "x + F(x)". sum_blob = model.net.Sum( [tr_blob, sc_blob], # "tr_blob" goes first to enable inplace. tr_blob if cfg.MODEL.ALLOW_INPLACE_SUM else prefix + "_sum") # ReLU after addition. blob_out = model.Relu_(sum_blob) return blob_out def res_stage_nonlocal( model, block_fn, blob_in, dim_in, dim_out, stride, num_blocks, prefix, dim_inner=None, group=None, use_temp_convs=None, temp_strides=None, batch_size=None, nonlocal_name=None, nonlocal_mod=1000, ): """ ResNet stage with optionally non-local blocks. Prefix is something like: res2, res3, etc. """ if use_temp_convs is None: use_temp_convs = np.zeros(num_blocks).astype(int) if temp_strides is None: temp_strides = np.ones(num_blocks).astype(int) if len(use_temp_convs) < num_blocks: for _ in range(num_blocks - len(use_temp_convs)): use_temp_convs.append(0) temp_strides.append(1) for idx in range(num_blocks): block_prefix = "{}_{}".format(prefix, idx) block_stride = 2 if (idx == 0 and stride == 2) else 1 blob_in = _generic_residual_block_3d( model, blob_in, dim_in, dim_out, block_stride, block_prefix, dim_inner, group, use_temp_convs[idx], temp_strides[idx]) dim_in = dim_out if idx % nonlocal_mod == nonlocal_mod - 1: blob_in = nonlocal_helper.add_nonlocal( model, blob_in, dim_in, dim_in, batch_size, nonlocal_name + '_{}'.format(idx), int(dim_in / 2)) return blob_in, dim_in def res_stage_nonlocal_group( model, block_fn, blob_in, dim_in, dim_out, stride, num_blocks, prefix, dim_inner=None, group=None, use_temp_convs=None, temp_strides=None, batch_size=None, pool_stride=None, spatial_dim=None, group_size=None, nonlocal_name=None, nonlocal_mod=1000, ): """ ResNet stage with optionally group-wise non-local blocks. Prefix is something like: res2, res3, etc. """ if use_temp_convs is None: use_temp_convs = np.zeros(num_blocks).astype(int) if temp_strides is None: temp_strides = np.ones(num_blocks).astype(int) if len(use_temp_convs) < num_blocks: for _ in range(num_blocks - len(use_temp_convs)): use_temp_convs.append(0) temp_strides.append(1) for idx in range(num_blocks): block_prefix = "{}_{}".format(prefix, idx) block_stride = 2 if (idx == 0 and stride == 2) else 1 blob_in = _generic_residual_block_3d( model, blob_in, dim_in, dim_out, block_stride, block_prefix, dim_inner, group, use_temp_convs[idx], temp_strides[idx]) dim_in = dim_out if idx % nonlocal_mod == nonlocal_mod - 1: blob_in = nonlocal_helper.add_nonlocal_group( model, blob_in, dim_in, dim_in, batch_size, pool_stride, spatial_dim, spatial_dim, group_size, nonlocal_name + '_{}'.format(idx), int(dim_in / 2)) return blob_in, dim_in
2,982
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.youtubeAnalytics.v2; /** * Service definition for YouTubeAnalytics (v2). * * <p> * Retrieves your YouTube Analytics data. * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/youtube/analytics" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link YouTubeAnalyticsRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class YouTubeAnalytics extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 || (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 && com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)), "You are currently running with version %s of google-api-client. " + "You need at least version 1.31.1 of google-api-client to run version " + "1.32.1 of the YouTube Analytics API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://youtubeanalytics.googleapis.com/"; /** * The default encoded mTLS root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.31 */ public static final String DEFAULT_MTLS_ROOT_URL = "https://youtubeanalytics.mtls.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = ""; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public YouTubeAnalytics(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ YouTubeAnalytics(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the GroupItems collection. * * <p>The typical use is:</p> * <pre> * {@code YouTubeAnalytics youtubeAnalytics = new YouTubeAnalytics(...);} * {@code YouTubeAnalytics.GroupItems.List request = youtubeAnalytics.groupItems().list(parameters ...)} * </pre> * * @return the resource collection */ public GroupItems groupItems() { return new GroupItems(); } /** * The "groupItems" collection of methods. */ public class GroupItems { /** * Removes an item from a group. * * Create a request for the method "groupItems.delete". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @return the request */ public Delete delete() throws java.io.IOException { Delete result = new Delete(); initialize(result); return result; } public class Delete extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.EmptyResponse> { private static final String REST_PATH = "v2/groupItems"; /** * Removes an item from a group. * * Create a request for the method "groupItems.delete". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected Delete() { super(YouTubeAnalytics.this, "DELETE", REST_PATH, null, com.google.api.services.youtubeAnalytics.v2.model.EmptyResponse.class); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * The `id` parameter specifies the YouTube group item ID of the group item that is being * deleted. */ @com.google.api.client.util.Key private java.lang.String id; /** The `id` parameter specifies the YouTube group item ID of the group item that is being deleted. */ public java.lang.String getId() { return id; } /** * The `id` parameter specifies the YouTube group item ID of the group item that is being * deleted. */ public Delete setId(java.lang.String id) { this.id = id; return this; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public Delete setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Creates a group item. * * Create a request for the method "groupItems.insert". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.GroupItem} * @return the request */ public Insert insert(com.google.api.services.youtubeAnalytics.v2.model.GroupItem content) throws java.io.IOException { Insert result = new Insert(content); initialize(result); return result; } public class Insert extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.GroupItem> { private static final String REST_PATH = "v2/groupItems"; /** * Creates a group item. * * Create a request for the method "groupItems.insert". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.GroupItem} * @since 1.13 */ protected Insert(com.google.api.services.youtubeAnalytics.v2.model.GroupItem content) { super(YouTubeAnalytics.this, "POST", REST_PATH, content, com.google.api.services.youtubeAnalytics.v2.model.GroupItem.class); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public Insert setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Returns a collection of group items that match the API request parameters. * * Create a request for the method "groupItems.list". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.ListGroupItemsResponse> { private static final String REST_PATH = "v2/groupItems"; /** * Returns a collection of group items that match the API request parameters. * * Create a request for the method "groupItems.list". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(YouTubeAnalytics.this, "GET", REST_PATH, null, com.google.api.services.youtubeAnalytics.v2.model.ListGroupItemsResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The `groupId` parameter specifies the unique ID of the group for which you want to retrieve * group items. */ @com.google.api.client.util.Key private java.lang.String groupId; /** The `groupId` parameter specifies the unique ID of the group for which you want to retrieve group items. */ public java.lang.String getGroupId() { return groupId; } /** * The `groupId` parameter specifies the unique ID of the group for which you want to retrieve * group items. */ public List setGroupId(java.lang.String groupId) { this.groupId = groupId; return this; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public List setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Groups collection. * * <p>The typical use is:</p> * <pre> * {@code YouTubeAnalytics youtubeAnalytics = new YouTubeAnalytics(...);} * {@code YouTubeAnalytics.Groups.List request = youtubeAnalytics.groups().list(parameters ...)} * </pre> * * @return the resource collection */ public Groups groups() { return new Groups(); } /** * The "groups" collection of methods. */ public class Groups { /** * Deletes a group. * * Create a request for the method "groups.delete". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @return the request */ public Delete delete() throws java.io.IOException { Delete result = new Delete(); initialize(result); return result; } public class Delete extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.EmptyResponse> { private static final String REST_PATH = "v2/groups"; /** * Deletes a group. * * Create a request for the method "groups.delete". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected Delete() { super(YouTubeAnalytics.this, "DELETE", REST_PATH, null, com.google.api.services.youtubeAnalytics.v2.model.EmptyResponse.class); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** The `id` parameter specifies the YouTube group ID of the group that is being deleted. */ @com.google.api.client.util.Key private java.lang.String id; /** The `id` parameter specifies the YouTube group ID of the group that is being deleted. */ public java.lang.String getId() { return id; } /** The `id` parameter specifies the YouTube group ID of the group that is being deleted. */ public Delete setId(java.lang.String id) { this.id = id; return this; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public Delete setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Creates a group. * * Create a request for the method "groups.insert". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.Group} * @return the request */ public Insert insert(com.google.api.services.youtubeAnalytics.v2.model.Group content) throws java.io.IOException { Insert result = new Insert(content); initialize(result); return result; } public class Insert extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.Group> { private static final String REST_PATH = "v2/groups"; /** * Creates a group. * * Create a request for the method "groups.insert". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Insert#execute()} method to invoke the remote operation. * <p> {@link * Insert#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.Group} * @since 1.13 */ protected Insert(com.google.api.services.youtubeAnalytics.v2.model.Group content) { super(YouTubeAnalytics.this, "POST", REST_PATH, content, com.google.api.services.youtubeAnalytics.v2.model.Group.class); } @Override public Insert set$Xgafv(java.lang.String $Xgafv) { return (Insert) super.set$Xgafv($Xgafv); } @Override public Insert setAccessToken(java.lang.String accessToken) { return (Insert) super.setAccessToken(accessToken); } @Override public Insert setAlt(java.lang.String alt) { return (Insert) super.setAlt(alt); } @Override public Insert setCallback(java.lang.String callback) { return (Insert) super.setCallback(callback); } @Override public Insert setFields(java.lang.String fields) { return (Insert) super.setFields(fields); } @Override public Insert setKey(java.lang.String key) { return (Insert) super.setKey(key); } @Override public Insert setOauthToken(java.lang.String oauthToken) { return (Insert) super.setOauthToken(oauthToken); } @Override public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { return (Insert) super.setPrettyPrint(prettyPrint); } @Override public Insert setQuotaUser(java.lang.String quotaUser) { return (Insert) super.setQuotaUser(quotaUser); } @Override public Insert setUploadType(java.lang.String uploadType) { return (Insert) super.setUploadType(uploadType); } @Override public Insert setUploadProtocol(java.lang.String uploadProtocol) { return (Insert) super.setUploadProtocol(uploadProtocol); } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public Insert setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public Insert set(String parameterName, Object value) { return (Insert) super.set(parameterName, value); } } /** * Returns a collection of groups that match the API request parameters. For example, you can * retrieve all groups that the authenticated user owns, or you can retrieve one or more groups by * their unique IDs. * * Create a request for the method "groups.list". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.ListGroupsResponse> { private static final String REST_PATH = "v2/groups"; /** * Returns a collection of groups that match the API request parameters. For example, you can * retrieve all groups that the authenticated user owns, or you can retrieve one or more groups by * their unique IDs. * * Create a request for the method "groups.list". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(YouTubeAnalytics.this, "GET", REST_PATH, null, com.google.api.services.youtubeAnalytics.v2.model.ListGroupsResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The `id` parameter specifies a comma-separated list of the YouTube group ID(s) for the * resource(s) that are being retrieved. Each group must be owned by the authenticated user. * In a `group` resource, the `id` property specifies the group's YouTube group ID. Note that * if you do not specify a value for the `id` parameter, then you must set the `mine` * parameter to `true`. */ @com.google.api.client.util.Key private java.lang.String id; /** The `id` parameter specifies a comma-separated list of the YouTube group ID(s) for the resource(s) that are being retrieved. Each group must be owned by the authenticated user. In a `group` resource, the `id` property specifies the group's YouTube group ID. Note that if you do not specify a value for the `id` parameter, then you must set the `mine` parameter to `true`. */ public java.lang.String getId() { return id; } /** * The `id` parameter specifies a comma-separated list of the YouTube group ID(s) for the * resource(s) that are being retrieved. Each group must be owned by the authenticated user. * In a `group` resource, the `id` property specifies the group's YouTube group ID. Note that * if you do not specify a value for the `id` parameter, then you must set the `mine` * parameter to `true`. */ public List setId(java.lang.String id) { this.id = id; return this; } /** * This parameter can only be used in a properly authorized request. Set this parameter's * value to true to retrieve all groups owned by the authenticated user. */ @com.google.api.client.util.Key private java.lang.Boolean mine; /** This parameter can only be used in a properly authorized request. Set this parameter's value to true to retrieve all groups owned by the authenticated user. */ public java.lang.Boolean getMine() { return mine; } /** * This parameter can only be used in a properly authorized request. Set this parameter's * value to true to retrieve all groups owned by the authenticated user. */ public List setMine(java.lang.Boolean mine) { this.mine = mine; return this; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public List setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } /** * The `pageToken` parameter identifies a specific page in the result set that should be * returned. In an API response, the `nextPageToken` property identifies the next page that * can be retrieved. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The `pageToken` parameter identifies a specific page in the result set that should be returned. In an API response, the `nextPageToken` property identifies the next page that can be retrieved. */ public java.lang.String getPageToken() { return pageToken; } /** * The `pageToken` parameter identifies a specific page in the result set that should be * returned. In an API response, the `nextPageToken` property identifies the next page that * can be retrieved. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Modifies a group. For example, you could change a group's title. * * Create a request for the method "groups.update". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.Group} * @return the request */ public Update update(com.google.api.services.youtubeAnalytics.v2.model.Group content) throws java.io.IOException { Update result = new Update(content); initialize(result); return result; } public class Update extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.Group> { private static final String REST_PATH = "v2/groups"; /** * Modifies a group. For example, you could change a group's title. * * Create a request for the method "groups.update". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.youtubeAnalytics.v2.model.Group} * @since 1.13 */ protected Update(com.google.api.services.youtubeAnalytics.v2.model.Group content) { super(YouTubeAnalytics.this, "PUT", REST_PATH, content, com.google.api.services.youtubeAnalytics.v2.model.Group.class); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ @com.google.api.client.util.Key private java.lang.String onBehalfOfContentOwner; /** This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner. */ public java.lang.String getOnBehalfOfContentOwner() { return onBehalfOfContentOwner; } /** * This parameter can only be used in a properly authorized request. **Note:** This parameter * is intended exclusively for YouTube content partners that own and manage many different * YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's * authorization credentials identify a YouTube user who is acting on behalf of the content * owner specified in the parameter value. It allows content owners to authenticate once and * get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The account that the user authenticates with must * be linked to the specified YouTube content owner. */ public Update setOnBehalfOfContentOwner(java.lang.String onBehalfOfContentOwner) { this.onBehalfOfContentOwner = onBehalfOfContentOwner; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Reports collection. * * <p>The typical use is:</p> * <pre> * {@code YouTubeAnalytics youtubeAnalytics = new YouTubeAnalytics(...);} * {@code YouTubeAnalytics.Reports.List request = youtubeAnalytics.reports().list(parameters ...)} * </pre> * * @return the resource collection */ public Reports reports() { return new Reports(); } /** * The "reports" collection of methods. */ public class Reports { /** * Retrieve your YouTube Analytics reports. * * Create a request for the method "reports.query". * * This request holds the parameters needed by the youtubeAnalytics server. After setting any * optional parameters, call the {@link Query#execute()} method to invoke the remote operation. * * @return the request */ public Query query() throws java.io.IOException { Query result = new Query(); initialize(result); return result; } public class Query extends YouTubeAnalyticsRequest<com.google.api.services.youtubeAnalytics.v2.model.QueryResponse> { private static final String REST_PATH = "v2/reports"; /** * Retrieve your YouTube Analytics reports. * * Create a request for the method "reports.query". * * This request holds the parameters needed by the the youtubeAnalytics server. After setting any * optional parameters, call the {@link Query#execute()} method to invoke the remote operation. * <p> {@link * Query#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected Query() { super(YouTubeAnalytics.this, "GET", REST_PATH, null, com.google.api.services.youtubeAnalytics.v2.model.QueryResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Query set$Xgafv(java.lang.String $Xgafv) { return (Query) super.set$Xgafv($Xgafv); } @Override public Query setAccessToken(java.lang.String accessToken) { return (Query) super.setAccessToken(accessToken); } @Override public Query setAlt(java.lang.String alt) { return (Query) super.setAlt(alt); } @Override public Query setCallback(java.lang.String callback) { return (Query) super.setCallback(callback); } @Override public Query setFields(java.lang.String fields) { return (Query) super.setFields(fields); } @Override public Query setKey(java.lang.String key) { return (Query) super.setKey(key); } @Override public Query setOauthToken(java.lang.String oauthToken) { return (Query) super.setOauthToken(oauthToken); } @Override public Query setPrettyPrint(java.lang.Boolean prettyPrint) { return (Query) super.setPrettyPrint(prettyPrint); } @Override public Query setQuotaUser(java.lang.String quotaUser) { return (Query) super.setQuotaUser(quotaUser); } @Override public Query setUploadType(java.lang.String uploadType) { return (Query) super.setUploadType(uploadType); } @Override public Query setUploadProtocol(java.lang.String uploadProtocol) { return (Query) super.setUploadProtocol(uploadProtocol); } /** * The currency to which financial metrics should be converted. The default is US Dollar * (USD). If the result contains no financial metrics, this flag will be ignored. Responds * with an error if the specified currency is not recognized.", pattern: [A-Z]{3} */ @com.google.api.client.util.Key private java.lang.String currency; /** The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag will be ignored. Responds with an error if the specified currency is not recognized.", pattern: [A-Z]{3} */ public java.lang.String getCurrency() { return currency; } /** * The currency to which financial metrics should be converted. The default is US Dollar * (USD). If the result contains no financial metrics, this flag will be ignored. Responds * with an error if the specified currency is not recognized.", pattern: [A-Z]{3} */ public Query setCurrency(java.lang.String currency) { this.currency = currency; return this; } /** * A comma-separated list of YouTube Analytics dimensions, such as `views` or * `ageGroup,gender`. See the [Available Reports](/youtube/analytics/v2/available_reports) * document for a list of the reports that you can retrieve and the dimensions used for those * reports. Also see the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document for * definitions of those dimensions." pattern: [0-9a-zA-Z,]+ */ @com.google.api.client.util.Key private java.lang.String dimensions; /** A comma-separated list of YouTube Analytics dimensions, such as `views` or `ageGroup,gender`. See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of the reports that you can retrieve and the dimensions used for those reports. Also see the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document for definitions of those dimensions." pattern: [0-9a-zA-Z,]+ */ public java.lang.String getDimensions() { return dimensions; } /** * A comma-separated list of YouTube Analytics dimensions, such as `views` or * `ageGroup,gender`. See the [Available Reports](/youtube/analytics/v2/available_reports) * document for a list of the reports that you can retrieve and the dimensions used for those * reports. Also see the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document for * definitions of those dimensions." pattern: [0-9a-zA-Z,]+ */ public Query setDimensions(java.lang.String dimensions) { this.dimensions = dimensions; return this; } /** * The end date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` * format. required: true, pattern: [0-9]{4}-[0-9]{2}-[0-9]{2} */ @com.google.api.client.util.Key private java.lang.String endDate; /** The end date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` format. required: true, pattern: [0-9]{4}-[0-9]{2}-[0-9]{2} */ public java.lang.String getEndDate() { return endDate; } /** * The end date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` * format. required: true, pattern: [0-9]{4}-[0-9]{2}-[0-9]{2} */ public Query setEndDate(java.lang.String endDate) { this.endDate = endDate; return this; } /** * A list of filters that should be applied when retrieving YouTube Analytics data. The * [Available Reports](/youtube/analytics/v2/available_reports) document identifies the * dimensions that can be used to filter each report, and the * [Dimensions](/youtube/analytics/v2/dimsmets/dims) document defines those dimensions. If a * request uses multiple filters, join them together with a semicolon (`;`), and the returned * result table will satisfy both filters. For example, a filters parameter value of * `video==dMH0bHeiRNg;country==IT` restricts the result set to include data for the given * video in Italy.", */ @com.google.api.client.util.Key private java.lang.String filters; /** A list of filters that should be applied when retrieving YouTube Analytics data. The [Available Reports](/youtube/analytics/v2/available_reports) document identifies the dimensions that can be used to filter each report, and the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document defines those dimensions. If a request uses multiple filters, join them together with a semicolon (`;`), and the returned result table will satisfy both filters. For example, a filters parameter value of `video==dMH0bHeiRNg;country==IT` restricts the result set to include data for the given video in Italy.", */ public java.lang.String getFilters() { return filters; } /** * A list of filters that should be applied when retrieving YouTube Analytics data. The * [Available Reports](/youtube/analytics/v2/available_reports) document identifies the * dimensions that can be used to filter each report, and the * [Dimensions](/youtube/analytics/v2/dimsmets/dims) document defines those dimensions. If a * request uses multiple filters, join them together with a semicolon (`;`), and the returned * result table will satisfy both filters. For example, a filters parameter value of * `video==dMH0bHeiRNg;country==IT` restricts the result set to include data for the given * video in Italy.", */ public Query setFilters(java.lang.String filters) { this.filters = filters; return this; } /** * Identifies the YouTube channel or content owner for which you are retrieving YouTube * Analytics data. - To request data for a YouTube user, set the `ids` parameter value to * `channel==CHANNEL_ID`, where `CHANNEL_ID` specifies the unique YouTube channel ID. - To * request data for a YouTube CMS content owner, set the `ids` parameter value to * `contentOwner==OWNER_NAME`, where `OWNER_NAME` is the CMS name of the content owner. * required: true, pattern: [a-zA-Z]+==[a-zA-Z0-9_+-]+ */ @com.google.api.client.util.Key private java.lang.String ids; /** Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data. - To request data for a YouTube user, set the `ids` parameter value to `channel==CHANNEL_ID`, where `CHANNEL_ID` specifies the unique YouTube channel ID. - To request data for a YouTube CMS content owner, set the `ids` parameter value to `contentOwner==OWNER_NAME`, where `OWNER_NAME` is the CMS name of the content owner. required: true, pattern: [a-zA-Z]+==[a-zA-Z0-9_+-]+ */ public java.lang.String getIds() { return ids; } /** * Identifies the YouTube channel or content owner for which you are retrieving YouTube * Analytics data. - To request data for a YouTube user, set the `ids` parameter value to * `channel==CHANNEL_ID`, where `CHANNEL_ID` specifies the unique YouTube channel ID. - To * request data for a YouTube CMS content owner, set the `ids` parameter value to * `contentOwner==OWNER_NAME`, where `OWNER_NAME` is the CMS name of the content owner. * required: true, pattern: [a-zA-Z]+==[a-zA-Z0-9_+-]+ */ public Query setIds(java.lang.String ids) { this.ids = ids; return this; } /** * If set to true historical data (i.e. channel data from before the linking of the channel to * the content owner) will be retrieved.", */ @com.google.api.client.util.Key private java.lang.Boolean includeHistoricalChannelData; /** If set to true historical data (i.e. channel data from before the linking of the channel to the content owner) will be retrieved.", */ public java.lang.Boolean getIncludeHistoricalChannelData() { return includeHistoricalChannelData; } /** * If set to true historical data (i.e. channel data from before the linking of the channel to * the content owner) will be retrieved.", */ public Query setIncludeHistoricalChannelData(java.lang.Boolean includeHistoricalChannelData) { this.includeHistoricalChannelData = includeHistoricalChannelData; return this; } /** The maximum number of rows to include in the response.", minValue: 1 */ @com.google.api.client.util.Key private java.lang.Integer maxResults; /** The maximum number of rows to include in the response.", minValue: 1 */ public java.lang.Integer getMaxResults() { return maxResults; } /** The maximum number of rows to include in the response.", minValue: 1 */ public Query setMaxResults(java.lang.Integer maxResults) { this.maxResults = maxResults; return this; } /** * A comma-separated list of YouTube Analytics metrics, such as `views` or `likes,dislikes`. * See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of * the reports that you can retrieve and the metrics available in each report, and see the * [Metrics](/youtube/analytics/v2/dimsmets/mets) document for definitions of those metrics. * required: true, pattern: [0-9a-zA-Z,]+ */ @com.google.api.client.util.Key private java.lang.String metrics; /** A comma-separated list of YouTube Analytics metrics, such as `views` or `likes,dislikes`. See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of the reports that you can retrieve and the metrics available in each report, and see the [Metrics](/youtube/analytics/v2/dimsmets/mets) document for definitions of those metrics. required: true, pattern: [0-9a-zA-Z,]+ */ public java.lang.String getMetrics() { return metrics; } /** * A comma-separated list of YouTube Analytics metrics, such as `views` or `likes,dislikes`. * See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of * the reports that you can retrieve and the metrics available in each report, and see the * [Metrics](/youtube/analytics/v2/dimsmets/mets) document for definitions of those metrics. * required: true, pattern: [0-9a-zA-Z,]+ */ public Query setMetrics(java.lang.String metrics) { this.metrics = metrics; return this; } /** * A comma-separated list of dimensions or metrics that determine the sort order for YouTube * Analytics data. By default the sort order is ascending. The '`-`' prefix causes descending * sort order.", pattern: [-0-9a-zA-Z,]+ */ @com.google.api.client.util.Key private java.lang.String sort; /** A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The '`-`' prefix causes descending sort order.", pattern: [-0-9a-zA-Z,]+ */ public java.lang.String getSort() { return sort; } /** * A comma-separated list of dimensions or metrics that determine the sort order for YouTube * Analytics data. By default the sort order is ascending. The '`-`' prefix causes descending * sort order.", pattern: [-0-9a-zA-Z,]+ */ public Query setSort(java.lang.String sort) { this.sort = sort; return this; } /** * The start date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` * format. required: true, pattern: "[0-9]{4}-[0-9]{2}-[0-9]{2} */ @com.google.api.client.util.Key private java.lang.String startDate; /** The start date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` format. required: true, pattern: "[0-9]{4}-[0-9]{2}-[0-9]{2} */ public java.lang.String getStartDate() { return startDate; } /** * The start date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` * format. required: true, pattern: "[0-9]{4}-[0-9]{2}-[0-9]{2} */ public Query setStartDate(java.lang.String startDate) { this.startDate = startDate; return this; } /** * An index of the first entity to retrieve. Use this parameter as a pagination mechanism * along with the max-results parameter (one-based, inclusive).", minValue: 1 */ @com.google.api.client.util.Key private java.lang.Integer startIndex; /** An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive).", minValue: 1 */ public java.lang.Integer getStartIndex() { return startIndex; } /** * An index of the first entity to retrieve. Use this parameter as a pagination mechanism * along with the max-results parameter (one-based, inclusive).", minValue: 1 */ public Query setStartIndex(java.lang.Integer startIndex) { this.startIndex = startIndex; return this; } @Override public Query set(String parameterName, Object value) { return (Query) super.set(parameterName, value); } } } /** * Builder for {@link YouTubeAnalytics}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) { // If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint. // If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS. // Use the regular endpoint for all other cases. String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT"); useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint; if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) { return DEFAULT_MTLS_ROOT_URL; } return DEFAULT_ROOT_URL; } /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, Builder.chooseEndpoint(transport), DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link YouTubeAnalytics}. */ @Override public YouTubeAnalytics build() { return new YouTubeAnalytics(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link YouTubeAnalyticsRequestInitializer}. * * @since 1.12 */ public Builder setYouTubeAnalyticsRequestInitializer( YouTubeAnalyticsRequestInitializer youtubeanalyticsRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(youtubeanalyticsRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
26,116
19,824
{ "main": "dist/keystone-ui-icons-icons-RefreshCwIcon.cjs.js", "module": "dist/keystone-ui-icons-icons-RefreshCwIcon.esm.js" }
59
935
# @Author : bamtercelboo # @Datetime : 2018/07/19 22:35 # @File : model_CNN_MUI.py # @Last Modify Time : 2018/07/19 22:35 # @Contact : <EMAIL>, 163.com} import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import random import torch.nn.init as init from DataUtils.Common import seed_num torch.manual_seed(seed_num) random.seed(seed_num) """ Description: the model is a mulit-channel CNNS model, the model use two external word embedding, and then, one of word embedding built from train/dev/test dataset, and it be used to no-fine-tune,other one built from only train dataset,and be used to fine-tune. my idea,even if the word embedding built from train/dev/test dataset, whether can use fine-tune, in others words, whether can fine-tune with two external word embedding. """ class CNN_MUI(nn.Module): def __init__(self, args): super(CNN_MUI, self).__init__() self.args = args V = args.embed_num V_mui = args.embed_num_mui D = args.embed_dim C = args.class_num Ci = 2 Co = args.kernel_num Ks = args.kernel_sizes if args.max_norm is not None: print("max_norm = {} ".format(args.max_norm)) self.embed_no_static = nn.Embedding(V, D, max_norm=args.max_norm, scale_grad_by_freq=True, padding_idx=args.paddingId) self.embed_static = nn.Embedding(V_mui, D, max_norm=args.max_norm, scale_grad_by_freq=True, padding_idx=args.paddingId_mui) else: print("max_norm = {} ".format(args.max_norm)) self.embed_no_static = nn.Embedding(V, D, scale_grad_by_freq=True, padding_idx=args.paddingId) self.embed_static = nn.Embedding(V_mui, D, scale_grad_by_freq=True, padding_idx=args.paddingId_mui) if args.word_Embedding: self.embed_no_static.weight.data.copy_(args.pretrained_weight) self.embed_static.weight.data.copy_(args.pretrained_weight_static) # whether to fixed the word embedding self.embed_no_static.weight.requires_grad = False if args.wide_conv is True: print("using wide convolution") self.convs1 = [nn.Conv2d(in_channels=Ci, out_channels=Co, kernel_size=(K, D), stride=(1, 1), padding=(K//2, 0), bias=True) for K in Ks] else: print("using narrow convolution") self.convs1 = [nn.Conv2d(in_channels=Ci, out_channels=Co, kernel_size=(K, D), bias=True) for K in Ks] print(self.convs1) if args.init_weight: print("Initing W .......") for conv in self.convs1: init.xavier_normal(conv.weight.data, gain=np.sqrt(args.init_weight_value)) init.uniform(conv.bias, 0, 0) ''' self.conv13 = nn.Conv2d(Ci, Co, (3, D)) self.conv14 = nn.Conv2d(Ci, Co, (4, D)) self.conv15 = nn.Conv2d(Ci, Co, (5, D)) ''' self.dropout = nn.Dropout(args.dropout) # for cnn cuda if self.args.cuda is True: for conv in self.convs1: conv = conv.cuda() in_fea = len(Ks) * Co self.fc1 = nn.Linear(in_features=in_fea, out_features=in_fea // 2, bias=True) self.fc2 = nn.Linear(in_features=in_fea // 2, out_features=C, bias=True) if args.batch_normalizations is True: print("using batch_normalizations in the model......") self.convs1_bn = nn.BatchNorm2d(num_features=Co, momentum=args.bath_norm_momentum, affine=args.batch_norm_affine) self.fc1_bn = nn.BatchNorm1d(num_features=in_fea//2, momentum=args.bath_norm_momentum, affine=args.batch_norm_affine) self.fc2_bn = nn.BatchNorm1d(num_features=C, momentum=args.bath_norm_momentum, affine=args.batch_norm_affine) def conv_and_pool(self, x, conv): x = F.relu(conv(x)).squeeze(3) #(N,Co,W) x = F.max_pool1d(x, x.size(2)).squeeze(2) return x def forward(self, x): x_no_static = self.embed_no_static(x) x_static = self.embed_static(x) x = torch.stack([x_static, x_no_static], 1) x = self.dropout(x) if self.args.batch_normalizations is True: x = [F.relu(self.convs1_bn(conv(x))).squeeze(3) for conv in self.convs1] #[(N,Co,W), ...]*len(Ks) x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] #[(N,Co), ...]*len(Ks) else: x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] #[(N,Co,W), ...]*len(Ks) x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # [(N,Co), ...]*len(Ks) x = torch.cat(x, 1) x = self.dropout(x) # (N,len(Ks)*Co) if self.args.batch_normalizations is True: x = self.fc1(x) logit = self.fc2(F.relu(x)) else: x = self.fc1(x) logit = self.fc2(F.relu(x)) return logit
2,619
1,192
<reponame>clayne/DirectXShaderCompiler /////////////////////////////////////////////////////////////////////////////// // // // PixPassHelpers.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once //#define PIX_DEBUG_DUMP_HELPER #ifdef PIX_DEBUG_DUMP_HELPER #include "dxc/Support/Global.h" #endif namespace PIXPassHelpers { bool IsAllocateRayQueryInstruction(llvm::Value* Val); llvm::CallInst* CreateUAV(hlsl::DxilModule& DM, llvm::IRBuilder<>& Builder, unsigned int registerId, const char *name); llvm::CallInst* CreateHandleForResource(hlsl::DxilModule& DM, llvm::IRBuilder<>& Builder, hlsl::DxilResourceBase * resource, const char* name); llvm::Function* GetEntryFunction(hlsl::DxilModule& DM); std::vector<llvm::BasicBlock*> GetAllBlocks(hlsl::DxilModule& DM); #ifdef PIX_DEBUG_DUMP_HELPER void Log(const char* format, ...); void LogPartialLine(const char* format, ...); void IncreaseLogIndent(); void DecreaseLogIndent(); void DumpFullType(llvm::DIType const* type); #else inline void DumpFullType(llvm::DIType const*) {} inline void Log(const char* , ...) {} inline void LogPartialLine(const char* format, ...) {} inline void IncreaseLogIndent() {} inline void DecreaseLogIndent() {} #endif class ScopedIndenter { public: ScopedIndenter() { IncreaseLogIndent(); } ~ScopedIndenter() { DecreaseLogIndent(); } }; struct ExpandedStruct { llvm::Type *ExpandedPayloadStructType = nullptr; llvm::Type *ExpandedPayloadStructPtrType = nullptr; }; ExpandedStruct ExpandStructType(llvm::LLVMContext& Ctx, llvm::Type* OriginalPayloadStructType); void ReplaceAllUsesOfInstructionWithNewValueAndDeleteInstruction( llvm::Instruction* Instr, llvm::Value* newValue, llvm::Type* newType); }
973
1,816
/********************************************************* * Copyright (C) 2012-2017, 2019-2021 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * @file proto.c * * Client/service protocol */ #ifndef _WIN32 #include <errno.h> #endif #include <stdlib.h> #include <string.h> #include <glib/gstdio.h> #include "VGAuthInt.h" #include "VGAuthProto.h" #include "VGAuthLog.h" #include "VGAuthUtil.h" #include "usercheck.h" /* cranks up parser debugging */ #define VGAUTH_PROTO_TRACE 0 /* * Reply types */ typedef enum { PROTO_REQUEST_UNKNOWN, PROTO_REPLY_ERROR, PROTO_REPLY_SESSION_REQ, PROTO_REPLY_CONN, PROTO_REPLY_ADDALIAS, PROTO_REPLY_REMOVEALIAS, PROTO_REPLY_QUERYALIASES, PROTO_REPLY_QUERYMAPPEDALIASES, PROTO_REPLY_CREATETICKET, PROTO_REPLY_VALIDATETICKET, PROTO_REPLY_REVOKETICKET, PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN, } ProtoReplyType; /* * Possible parse states for replies. */ typedef enum { PARSE_STATE_NONE, PARSE_STATE_SEQ, PARSE_STATE_ERROR, PARSE_STATE_ERROR_CODE, PARSE_STATE_ERROR_MSG, PARSE_STATE_REPLY, PARSE_STATE_VERSION, PARSE_STATE_PIPENAME, PARSE_STATE_PEMCERT, PARSE_STATE_CERTCOMMENT, PARSE_STATE_ALIAS, PARSE_STATE_ALIASINFO, PARSE_STATE_NAMEDSUBJECT, PARSE_STATE_ANYSUBJECT, PARSE_STATE_COMMENT, PARSE_STATE_MAPPEDALIAS, PARSE_STATE_SUBJECTS, PARSE_STATE_TICKET, PARSE_STATE_USERHANDLEINFO, PARSE_STATE_USERHANDLETYPE, PARSE_STATE_USERHANDLESAMLINFO, PARSE_STATE_USERHANDLESAMLSUBJECT, PARSE_STATE_USERNAME, PARSE_STATE_TOKEN, PARSE_STATE_CHALLENGE_EVENT, } ProtoParseState; /* * The reply structure. */ struct ProtoReply { gboolean complete; int sequenceNumber; /* * The client knows what its expecting back, which is * used as a sanity check against what's actually read, * as well as telling us what to allocate for complex replies. */ ProtoReplyType expectedReplyType; /* * If its an error, this will be set instead. */ ProtoReplyType actualReplyType; ProtoParseState parseState; VGAuthError errorCode; union { struct { gchar *errorMsg; } error; struct { int version; gchar *pipeName; } sessionReq; struct { gchar *challengeEvent; } connect; struct { int num; VGAuthUserAlias *uaList; } queryUserAliases; struct { int num; VGAuthMappedAlias *maList; } queryMappedAliases; struct { gchar *ticket; } createTicket; struct { gchar *userName; gchar *token; VGAuthUserHandleType type; gchar *samlSubject; VGAuthAliasInfo aliasInfo; } validateTicket; struct { gchar *userName; char *comment; gchar *token; gchar *samlSubject; VGAuthAliasInfo aliasInfo; } validateSamlBToken; } replyData; #if VGAUTH_PROTO_TRACE gchar *rawData; #endif }; typedef struct ProtoReply ProtoReply; #if VGAUTH_PROTO_TRACE /* ****************************************************************************** * ProtoSubjectToString -- */ /** * * Debugging. Returns the name of a VGAuthSubject. * * @param[in] subj The VGAuthSubject to dump. * ****************************************************************************** */ static const gchar * ProtoSubjectToString(const VGAuthSubject *subj) { if (VGAUTH_SUBJECT_NAMED == subj->type) { return subj->val.name; } else if (VGAUTH_SUBJECT_ANY == subj->type) { return "<ANY>"; } else { return "<UNKNOWN>"; } } /* ****************************************************************************** * Proto_DumpReply -- */ /** * * Debugging. Spews a ProtoReply to stdout. * * @param[in] reply The reply to dump. * ****************************************************************************** */ static void Proto_DumpReply(ProtoReply *reply) { int i; int j; VGAuthUserAlias *ua; VGAuthAliasInfo *ai; printf("raw data: %s\n", reply->rawData ? reply->rawData : "<none>"); printf("complete: %d\n", reply->complete); printf("sequenceNumber: %d\n", reply->sequenceNumber); printf("expectedReplyType: %d\n", reply->expectedReplyType); printf("actualReplyType: %d\n", reply->actualReplyType); printf("error code: "VGAUTHERR_FMT64X"\n", reply->errorCode); switch (reply->actualReplyType) { case PROTO_REPLY_ERROR: printf("error message: '%s'\n", reply->replyData.error.errorMsg ? reply->replyData.error.errorMsg : "<none>"); break; case PROTO_REPLY_SESSION_REQ: printf("version #: %d\n", reply->replyData.sessionReq.version); printf("pipeName: '%s'\n", reply->replyData.sessionReq.pipeName); break; case PROTO_REPLY_CONN: case PROTO_REPLY_ADDALIAS: case PROTO_REPLY_REMOVEALIAS: case PROTO_REPLY_REVOKETICKET: break; case PROTO_REPLY_QUERYALIASES: printf("#%d UserAliases:\n", reply->replyData.queryUserAliases.num); for (i = 0; i < reply->replyData.queryUserAliases.num; i++) { ua = &(reply->replyData.queryUserAliases.uaList[i]); printf("permCert: '%s'\n", ua->pemCert); for (j = 0; j < ua->numInfos; j++) { ai = &(ua->infos[j]); printf("\tsubject: '%s'\n", ProtoSubjectToString(&(ai->subject))); printf("\tcomment: '%s'\n", ai->comment); } } break; case PROTO_REPLY_QUERYMAPPEDALIASES: printf("#%d identities:\n", reply->replyData.queryMappedAliases.num); for (i = 0; i < reply->replyData.queryMappedAliases.num; i++) { printf("pemCert: '%s'\n", reply->replyData.queryMappedAliases.maList[i].pemCert); for (j = 0; j < reply->replyData.queryMappedAliases.maList[i].numSubjects; j++) { printf("subject #%d: '%s'\n", j, ProtoSubjectToString(&reply->replyData.queryMappedAliases.maList[i].subjects[j])); } printf("mapped user: '%s'\n", reply->replyData.queryMappedAliases.maList[i].userName); } break; case PROTO_REPLY_CREATETICKET: printf("ticket '%s'\n", reply->replyData.createTicket.ticket); break; case PROTO_REPLY_VALIDATETICKET: printf("username: '%s'\n", reply->replyData.validateTicket.userName); printf("validate type: %d\n", reply->replyData.validateTicket.type); if (VGAUTH_AUTH_TYPE_SAML == reply->replyData.validateTicket.type) { printf("SAML subject: '%s'\n", reply->replyData.validateTicket.samlSubject); ai = &(reply->replyData.validateTicket.aliasInfo); printf("\tsubject: '%s'\n", ProtoSubjectToString(&(ai->subject))); printf("\tcomment: '%s'\n", ai->comment); } break; case PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN: printf("username: '%s'\n", reply->replyData.validateSamlBToken.userName); printf("SAML subject: '%s'\n", reply->replyData.validateTicket.samlSubject); ai = &(reply->replyData.validateTicket.aliasInfo); printf("\tsubject: '%s'\n", ProtoSubjectToString(&(ai->subject))); printf("\tcomment: '%s'\n", ai->comment); break; default: printf("no reply specific data\n"); break; } } #endif // VGAUTH_PROTO_TRACE /* ****************************************************************************** * Proto_ConcatXMLStrings -- */ /** * * Concatenates 2 XML strings and returns the new string. * g_free()s the two inputs. * Result must be g_free()d. * * @param[in] str1 The first string. * @param[in] str2 The second string. * * @return The new string. * ****************************************************************************** */ static gchar * Proto_ConcatXMLStrings(gchar *str1, gchar *str2) { gchar *newStr; newStr = g_strdup_printf("%s%s", str1, str2); g_free(str1); g_free(str2); return newStr; } /* ****************************************************************************** * ProtoUserHandleTypeString -- */ /** * * Returns the type of a VGAuthUserHandle as a protocol string. * * @param[in] userHandle The VGAuthUSerHandle. * * @return The type as a string. * ****************************************************************************** */ static const gchar * ProtoUserHandleTypeString(const VGAuthUserHandle *userHandle) { switch (userHandle->details.type) { case VGAUTH_AUTH_TYPE_NAMEPASSWORD: return VGAUTH_USERHANDLE_TYPE_NAMEPASSWORD; case VGAUTH_AUTH_TYPE_SSPI: return VGAUTH_USERHANDLE_TYPE_SSPI; break; case VGAUTH_AUTH_TYPE_SAML: return VGAUTH_USERHANDLE_TYPE_SAML; case VGAUTH_AUTH_TYPE_SAML_INFO_ONLY: return VGAUTH_USERHANDLE_TYPE_SAML_INFO_ONLY; case VGAUTH_AUTH_TYPE_UNKNOWN: default: ASSERT(0); Warning("%s: Unsupported handleType %d\n", __FUNCTION__, userHandle->details.type); return "<UNKNOWN>"; } } /* ****************************************************************************** * Proto_StartElement -- */ /** * * Called by the XML parser when it sees the start of a new * element. Used to update the current parser state, and allocate * any space that may be needed for processing that state. * * @param[in] parseContext The XML parse context. * @param[in] elementName The name of the element being started. * @param[in] attributeNames The names of any attributes on the element. * @param[in] attributeValues The values of any attributes on the element. * @param[in] userData The current ProtoReply as callback data. * @param[out] error Any error. * ****************************************************************************** */ static void Proto_StartElement(GMarkupParseContext *parseContext, const gchar *elementName, const gchar **attributeNames, const gchar **attributeValues, gpointer userData, GError **error) { ProtoReply *reply = (ProtoReply *) userData; #if VGAUTH_PROTO_TRACE Debug("%s: elementName '%s', parseState %d, cur reply type %d\n", __FUNCTION__, elementName, reply->parseState, reply->expectedReplyType); #endif switch (reply->parseState) { case PARSE_STATE_NONE: /* * We're in 'idle' mode, expecting a fresh reply. */ if (g_strcmp0(elementName, VGAUTH_REPLY_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_REPLY; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_REPLY: /* * We're in 'reply' mode, expecting some element inside the reply. */ if (g_strcmp0(elementName, VGAUTH_SEQUENCENO_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_SEQ; } else if (g_strcmp0(elementName, VGAUTH_ERRORCODE_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_ERROR_CODE; reply->actualReplyType = PROTO_REPLY_ERROR; } else if (g_strcmp0(elementName, VGAUTH_ERRORMSG_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_ERROR_MSG; reply->actualReplyType = PROTO_REPLY_ERROR; } else if (g_strcmp0(elementName, VGAUTH_VERSION_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_VERSION; if (PROTO_REPLY_SESSION_REQ != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_PIPENAME_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_PIPENAME; if (PROTO_REPLY_SESSION_REQ != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_TOKEN_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_TOKEN; if ((PROTO_REPLY_VALIDATETICKET != reply->expectedReplyType) && (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN != reply->expectedReplyType)) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_USERHANDLEINFO_ELEMENT_NAME) == 0) { if (PROTO_REPLY_VALIDATETICKET != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } else { reply->parseState = PARSE_STATE_USERHANDLEINFO; } } else if (g_strcmp0(elementName, VGAUTH_CHALLENGE_EVENT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_CHALLENGE_EVENT; if ((PROTO_REPLY_CONN != reply->expectedReplyType)) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_USERNAME_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERNAME; if ((PROTO_REPLY_VALIDATETICKET != reply->expectedReplyType) && (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN != reply->expectedReplyType)) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } reply->parseState = PARSE_STATE_USERNAME; } else if (g_strcmp0(elementName, VGAUTH_TICKET_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_TICKET; if (PROTO_REPLY_CREATETICKET != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_COMMENT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_CERTCOMMENT; if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else if (g_strcmp0(elementName, VGAUTH_ALIAS_ELEMENT_NAME) == 0) { VGAuthUserAlias *a; if (PROTO_REPLY_QUERYALIASES != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } else { reply->parseState = PARSE_STATE_ALIAS; a = reply->replyData.queryUserAliases.uaList; reply->replyData.queryUserAliases.num++; a = g_realloc_n(a, reply->replyData.queryUserAliases.num, sizeof(VGAuthUserAlias)); reply->replyData.queryUserAliases.uaList = a; reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1].numInfos = 0; reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1].infos = NULL; } } else if (g_strcmp0(elementName, VGAUTH_MAPPEDALIASES_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_MAPPEDALIAS; reply->replyData.queryMappedAliases.num++; reply->replyData.queryMappedAliases.maList = g_realloc_n(reply->replyData.queryMappedAliases.maList, reply->replyData.queryMappedAliases.num, sizeof(VGAuthMappedAlias)); reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].pemCert = NULL; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].userName = NULL; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].numSubjects = 0; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects = NULL; } else if (g_strcmp0(elementName, VGAUTH_USERHANDLESAMLINFO_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERHANDLESAMLINFO; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_ALIAS: if (g_strcmp0(elementName, VGAUTH_PEMCERT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_PEMCERT; } else if (g_strcmp0(elementName, VGAUTH_ALIASINFO_ELEMENT_NAME) == 0) { VGAuthAliasInfo *info; VGAuthUserAlias *ip = &(reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1]); reply->parseState = PARSE_STATE_ALIASINFO; // grow the AliasInfo array info = ip->infos; ip->numInfos++; info = g_realloc_n(info, ip->numInfos, sizeof(VGAuthAliasInfo)); ip->infos = info; ip->infos[ip->numInfos - 1].subject.type = -1; ip->infos[ip->numInfos - 1].subject.val.name = NULL; ip->infos[ip->numInfos - 1].comment = NULL; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_USERHANDLEINFO: if (PROTO_REPLY_VALIDATETICKET != reply->expectedReplyType) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } if (g_strcmp0(elementName, VGAUTH_USERHANDLETYPE_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERHANDLETYPE; } else if (g_strcmp0(elementName, VGAUTH_USERHANDLESAMLINFO_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERHANDLESAMLINFO; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_USERHANDLESAMLINFO: if (g_strcmp0(elementName, VGAUTH_USERHANDLESAMLSUBJECT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERHANDLESAMLSUBJECT; } else if (g_strcmp0(elementName, VGAUTH_ALIASINFO_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_ALIASINFO; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_ALIASINFO: if (g_strcmp0(elementName, VGAUTH_COMMENT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_COMMENT; } else if (g_strcmp0(elementName, VGAUTH_SUBJECT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_NAMEDSUBJECT; } else if (g_strcmp0(elementName, VGAUTH_ANYSUBJECT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_ANYSUBJECT; /* * Since this is an empty-element tag, the Contents code will * not be called, so do the work here. */ if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { VGAuthAliasInfo *info; VGAuthUserAlias *ip = &(reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1]); info = &(ip->infos[ip->numInfos - 1]); info->subject.type = VGAUTH_SUBJECT_ANY; } else if (PROTO_REPLY_VALIDATETICKET == reply->expectedReplyType) { reply->replyData.validateTicket.aliasInfo.subject.type = VGAUTH_SUBJECT_ANY; } else if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN == reply->expectedReplyType) { reply->replyData.validateSamlBToken.aliasInfo.subject.type = VGAUTH_SUBJECT_ANY; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Got '%s' when expecting a reply of type %d", elementName, reply->expectedReplyType); } } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_MAPPEDALIAS: if (g_strcmp0(elementName, VGAUTH_USERNAME_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_USERNAME; } else if (g_strcmp0(elementName, VGAUTH_PEMCERT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_PEMCERT; } else if (g_strcmp0(elementName, VGAUTH_SUBJECTS_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_SUBJECTS; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); } break; case PARSE_STATE_SUBJECTS: { int n; VGAuthSubject *subjs; VGAuthSubjectType sType = -1; if (g_strcmp0(elementName, VGAUTH_SUBJECT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_NAMEDSUBJECT; sType = VGAUTH_SUBJECT_NAMED; } else if (g_strcmp0(elementName, VGAUTH_ANYSUBJECT_ELEMENT_NAME) == 0) { reply->parseState = PARSE_STATE_ANYSUBJECT; sType = VGAUTH_SUBJECT_ANY; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); break; } // got a new Subject or AnySubject, grow n = ++(reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].numSubjects); subjs = reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects; subjs = g_realloc_n(subjs, n, sizeof(VGAuthSubject)); subjs[n - 1].type = sType; subjs[n - 1].val.name = NULL; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects = subjs; } break; default: g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Unexpected element '%s' in parse state %d", elementName, reply->parseState); break; } } /* ****************************************************************************** * Proto_EndElement -- */ /** * * Called by the XML parser when the end of an element is reached. * Used here to pop the parse state. * * @param[in] parseContext The XML parse context. * @param[in] elementName The name of the element being started. * @param[in] userData The current ProtoReply as callback data. * @param[out] error Any error. * ****************************************************************************** */ static void Proto_EndElement(GMarkupParseContext *parseContext, const gchar *elementName, gpointer userData, GError **error) { ProtoReply *reply = (ProtoReply *) userData; #if VGAUTH_PROTO_TRACE Debug("%s: elementName '%s'\n", __FUNCTION__, elementName); #endif switch (reply->parseState) { case PARSE_STATE_SEQ: case PARSE_STATE_ERROR_CODE: case PARSE_STATE_ERROR_MSG: case PARSE_STATE_VERSION: case PARSE_STATE_PIPENAME: case PARSE_STATE_TICKET: case PARSE_STATE_TOKEN: case PARSE_STATE_CHALLENGE_EVENT: case PARSE_STATE_ALIAS: case PARSE_STATE_MAPPEDALIAS: case PARSE_STATE_USERHANDLEINFO: reply->parseState = PARSE_STATE_REPLY; break; case PARSE_STATE_USERNAME: if (PROTO_REPLY_QUERYMAPPEDALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_MAPPEDALIAS; } else { reply->parseState = PARSE_STATE_REPLY; } break; case PARSE_STATE_ALIASINFO: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_ALIAS; } else if (PROTO_REPLY_VALIDATETICKET == reply->expectedReplyType) { reply->parseState = PARSE_STATE_USERHANDLESAMLINFO; } else if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN == reply->expectedReplyType) { reply->parseState = PARSE_STATE_USERHANDLESAMLINFO; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Bad parse state, popping aliasInfo in reply type %d", reply->expectedReplyType); } break; case PARSE_STATE_SUBJECTS: reply->parseState = PARSE_STATE_MAPPEDALIAS; break; case PARSE_STATE_NAMEDSUBJECT: case PARSE_STATE_ANYSUBJECT: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_ALIASINFO; } else if (PROTO_REPLY_QUERYMAPPEDALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_SUBJECTS; } else if (PROTO_REPLY_VALIDATETICKET == reply->expectedReplyType) { reply->parseState = PARSE_STATE_ALIASINFO; } else if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN == reply->expectedReplyType) { reply->parseState = PARSE_STATE_ALIASINFO; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Bad parse state, popping subject in reply type %d", reply->expectedReplyType); } break; case PARSE_STATE_COMMENT: reply->parseState = PARSE_STATE_ALIASINFO; break; case PARSE_STATE_PEMCERT: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_ALIAS; } else if (PROTO_REPLY_QUERYMAPPEDALIASES == reply->expectedReplyType) { reply->parseState = PARSE_STATE_MAPPEDALIAS; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Bad parse state, popping pemCert in reply type %d", reply->expectedReplyType); } break; case PARSE_STATE_CERTCOMMENT: reply->parseState = PARSE_STATE_REPLY; break; case PARSE_STATE_REPLY: reply->complete = TRUE; reply->parseState = PARSE_STATE_NONE; break; case PARSE_STATE_USERHANDLETYPE: reply->parseState = PARSE_STATE_USERHANDLEINFO; break; case PARSE_STATE_USERHANDLESAMLINFO: if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN == reply->expectedReplyType) { reply->parseState = PARSE_STATE_REPLY; } else { reply->parseState = PARSE_STATE_USERHANDLEINFO; } break; case PARSE_STATE_USERHANDLESAMLSUBJECT: reply->parseState = PARSE_STATE_USERHANDLESAMLINFO; break; default: g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Bad parse state, popping unknown parse state %d", reply->parseState); ASSERT(0); } } /* ****************************************************************************** * Proto_TextContents -- */ /** * * Called by the parser with the contents of an element. * Used to store the values. * * @param[in] parseContext The XML parse context. * @param[in] text The contents of the current element * (not NUL terminated) * @param[in] textSize The length of the text. * @param[in] userData The current ProtoReply as callback data. * @param[out] error Any error. * ****************************************************************************** */ static void Proto_TextContents(GMarkupParseContext *parseContext, const gchar *text, gsize textSize, gpointer userData, GError **error) { ProtoReply *reply = (ProtoReply *) userData; gchar *val; VGAuthUserHandleType t = VGAUTH_AUTH_TYPE_UNKNOWN; #if VGAUTH_PROTO_TRACE Debug("%s: parseState %d, text '%*s'\n", __FUNCTION__, reply->parseState, (int) textSize, text); #endif val = g_strndup(text, textSize); switch (reply->parseState) { case PARSE_STATE_SEQ: reply->sequenceNumber = atoi(val); g_free(val); break; case PARSE_STATE_ERROR_CODE: reply->errorCode = atoi(val); g_free(val); break; case PARSE_STATE_ERROR_MSG: reply->replyData.error.errorMsg = val; break; case PARSE_STATE_VERSION: reply->replyData.sessionReq.version = atoi(val); if (reply->expectedReplyType != PROTO_REPLY_SESSION_REQ) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found version number in reply type %d", reply->expectedReplyType); } g_free(val); break; case PARSE_STATE_PIPENAME: if (reply->expectedReplyType != PROTO_REPLY_SESSION_REQ) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found pipeName in reply type %d", reply->expectedReplyType); g_free(val); } else { reply->replyData.sessionReq.pipeName = val; } break; case PARSE_STATE_TICKET: if (reply->expectedReplyType != PROTO_REPLY_CREATETICKET) { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found ticket in reply type %d", reply->expectedReplyType); g_free(val); } else { reply->replyData.createTicket.ticket = val; } break; case PARSE_STATE_TOKEN: if (reply->expectedReplyType == PROTO_REPLY_VALIDATETICKET) { reply->replyData.validateTicket.token = val; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.token = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found token in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_CHALLENGE_EVENT: if (reply->expectedReplyType == PROTO_REPLY_CONN) { reply->replyData.connect.challengeEvent = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found token in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_USERNAME: if (reply->expectedReplyType == PROTO_REPLY_VALIDATETICKET) { reply->replyData.validateTicket.userName = val; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.userName = val; } else if (reply->expectedReplyType == PROTO_REPLY_QUERYMAPPEDALIASES) { reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].userName = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found username in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_PEMCERT: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1].pemCert = val; } else if (reply->expectedReplyType == PROTO_REPLY_QUERYMAPPEDALIASES) { reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].pemCert = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found pemCert in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_CERTCOMMENT: if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.comment = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found cert comment in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_REPLY: case PARSE_STATE_ALIAS: case PARSE_STATE_ALIASINFO: case PARSE_STATE_SUBJECTS: case PARSE_STATE_MAPPEDALIAS: case PARSE_STATE_USERHANDLEINFO: case PARSE_STATE_USERHANDLESAMLINFO: /* * Should just be whitespace, so drop it */ g_free(val); break; case PARSE_STATE_USERHANDLESAMLSUBJECT: if (PROTO_REPLY_VALIDATETICKET == reply->expectedReplyType) { reply->replyData.validateTicket.samlSubject = val; } else if (PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN == reply->expectedReplyType) { reply->replyData.validateSamlBToken.samlSubject = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found SAMLSubject in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_USERHANDLETYPE: if (PROTO_REPLY_VALIDATETICKET == reply->expectedReplyType) { if (g_strcmp0(val, VGAUTH_USERHANDLE_TYPE_NAMEPASSWORD) == 0) { t = VGAUTH_AUTH_TYPE_NAMEPASSWORD; } else if (g_strcmp0(val, VGAUTH_USERHANDLE_TYPE_SSPI) == 0) { t = VGAUTH_AUTH_TYPE_SSPI; } else if (g_strcmp0(val, VGAUTH_USERHANDLE_TYPE_SAML) == 0) { t = VGAUTH_AUTH_TYPE_SAML; } else if (g_strcmp0(val, VGAUTH_USERHANDLE_TYPE_SAML_INFO_ONLY) == 0) { t = VGAUTH_AUTH_TYPE_SAML_INFO_ONLY; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found unrecognized userHandle type %s", val); } reply->replyData.validateTicket.type = t; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found UserHandleType in reply type %d", reply->expectedReplyType); } g_free(val); break; case PARSE_STATE_NAMEDSUBJECT: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { VGAuthUserAlias *a; a = &(reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1]); a->infos[a->numInfos - 1].subject.val.name = val; a->infos[a->numInfos - 1].subject.type = VGAUTH_SUBJECT_NAMED; } else if (reply->expectedReplyType == PROTO_REPLY_QUERYMAPPEDALIASES) { int idx = reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].numSubjects; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects[idx - 1].val.name = val; reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects[idx - 1].type = VGAUTH_SUBJECT_NAMED; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATETICKET) { reply->replyData.validateTicket.aliasInfo.subject.type = VGAUTH_SUBJECT_NAMED; reply->replyData.validateTicket.aliasInfo.subject.val.name = val; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.aliasInfo.subject.type = VGAUTH_SUBJECT_NAMED; reply->replyData.validateSamlBToken.aliasInfo.subject.val.name = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found NamedSubject in reply type %d", reply->expectedReplyType); g_free(val); } break; case PARSE_STATE_ANYSUBJECT: /* * Won't usually hit this code, since we use an empty-element tag. */ if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { VGAuthUserAlias *a; a = &(reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1]); a->infos[a->numInfos - 1].subject.type = VGAUTH_SUBJECT_ANY; } else if (reply->expectedReplyType == PROTO_REPLY_QUERYMAPPEDALIASES) { reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].subjects[reply->replyData.queryMappedAliases.maList[reply->replyData.queryMappedAliases.num - 1].numSubjects - 1].type = VGAUTH_SUBJECT_ANY; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATETICKET) { reply->replyData.validateTicket.aliasInfo.subject.type = VGAUTH_SUBJECT_ANY; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.aliasInfo.subject.type = VGAUTH_SUBJECT_ANY; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found AnySubject in reply type %d", reply->expectedReplyType); } g_free(val); break; case PARSE_STATE_COMMENT: if (PROTO_REPLY_QUERYALIASES == reply->expectedReplyType) { VGAuthUserAlias *a; a = &(reply->replyData.queryUserAliases.uaList[reply->replyData.queryUserAliases.num - 1]); a->infos[a->numInfos - 1].comment = val; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATETICKET) { reply->replyData.validateTicket.aliasInfo.comment = val; } else if (reply->expectedReplyType == PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN) { reply->replyData.validateSamlBToken.aliasInfo.comment = val; } else { g_set_error(error, G_MARKUP_ERROR_PARSE, VGAUTH_E_INVALID_ARGUMENT, "Found comment in reply type %d", reply->expectedReplyType); g_free(val); } break; default: g_warning("Unexpected value '%s' in unhandled parseState %d in %s\n", val, reply->parseState, __FUNCTION__); g_free(val); ASSERT(0); } } /* * Describes the parser functions. */ static GMarkupParser wireParser = { Proto_StartElement, Proto_EndElement, Proto_TextContents, NULL, NULL, }; /* ****************************************************************************** * Proto_NewReply -- */ /** * * Creates a new ProtoReply * * @param[in] expectedReplyType The type of the new reply. * * @return The new ProtoReply *. * ****************************************************************************** */ ProtoReply * Proto_NewReply(ProtoReplyType expectedReplyType) { ProtoReply *reply = g_malloc0(sizeof(ProtoReply)); reply->parseState = PARSE_STATE_NONE; reply->complete = FALSE; reply->errorCode = VGAUTH_E_OK; reply->expectedReplyType = expectedReplyType; reply->actualReplyType = expectedReplyType; #if VGAUTH_PROTO_TRACE reply->rawData = NULL; #endif return reply; } /* ****************************************************************************** * Proto_FreeReply -- */ /** * * Frees a reply. * * @param[in] reply The reply to free. * ****************************************************************************** */ static void Proto_FreeReply(ProtoReply *reply) { if (NULL == reply) { return; } #if VGAUTH_PROTO_TRACE g_free(reply->rawData); #endif switch (reply->actualReplyType) { case PROTO_REQUEST_UNKNOWN: // partial/empty request -- no-op Debug("%s: Freeing an request of unknown type.\n", __FUNCTION__); break; case PROTO_REPLY_ERROR: g_free(reply->replyData.error.errorMsg); break; case PROTO_REPLY_SESSION_REQ: g_free(reply->replyData.sessionReq.pipeName); break; case PROTO_REPLY_CONN: g_free(reply->replyData.connect.challengeEvent); break; case PROTO_REPLY_ADDALIAS: case PROTO_REPLY_REMOVEALIAS: case PROTO_REPLY_REVOKETICKET: break; case PROTO_REPLY_QUERYMAPPEDALIASES: VGAuth_FreeMappedAliasList(reply->replyData.queryMappedAliases.num, reply->replyData.queryMappedAliases.maList); break; case PROTO_REPLY_QUERYALIASES: VGAuth_FreeUserAliasList(reply->replyData.queryUserAliases.num, reply->replyData.queryUserAliases.uaList); break; case PROTO_REPLY_CREATETICKET: g_free(reply->replyData.createTicket.ticket); break; case PROTO_REPLY_VALIDATETICKET: g_free(reply->replyData.validateTicket.userName); g_free(reply->replyData.validateTicket.token); g_free(reply->replyData.validateTicket.samlSubject); VGAuth_FreeAliasInfoContents(&(reply->replyData.validateTicket.aliasInfo)); break; case PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN: g_free(reply->replyData.validateSamlBToken.comment); g_free(reply->replyData.validateSamlBToken.userName); g_free(reply->replyData.validateSamlBToken.token); g_free(reply->replyData.validateSamlBToken.samlSubject); VGAuth_FreeAliasInfoContents(&(reply->replyData.validateSamlBToken.aliasInfo)); break; } g_free(reply); } /* ****************************************************************************** * Proto_SanityCheckReply -- */ /** * * Verifies a reply is internally consistent and the type is what we expected. * * @param[in] reply The reply to check. * @param[in] expectedSequenceNumber The sequence number that * should be in the reply. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ static VGAuthError Proto_SanityCheckReply(ProtoReply *reply, int expectedSequenceNumber) { #if VGAUTH_PROTO_TRACE ASSERT(strncmp(reply->rawData, VGAUTH_XML_PREAMBLE, strlen(VGAUTH_XML_PREAMBLE)) == 0); #endif if (PROTO_REPLY_ERROR != reply->actualReplyType) { if (reply->actualReplyType != reply->expectedReplyType) { Warning("%s: expected reply type %d doesn't match actual type %d\n", __FUNCTION__, reply->expectedReplyType, reply->actualReplyType); return VGAUTH_E_COMM; } } if (-1 != expectedSequenceNumber) { if (reply->sequenceNumber != expectedSequenceNumber) { Warning("%s: sequence number check failed: wanted %d, got %d\n", __FUNCTION__, expectedSequenceNumber, reply->sequenceNumber); return VGAUTH_E_COMM; } } /* * If it's an error, kick out now. */ if (PROTO_REPLY_ERROR == reply->actualReplyType) { return VGAUTH_E_OK; } return VGAUTH_E_OK; } /* ****************************************************************************** * VGAuth_ReadAndParseResponse -- */ /** * * Reads the next reply off the wire and returns it in wireReply. * * @param[in] ctx The VGAuthContext. * @param[in] expectedReplyType The expected reply type. * @param[out] wireReply The complete reply. The caller * should use Proto_FreeReply on * it when finished. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_ReadAndParseResponse(VGAuthContext *ctx, ProtoReplyType expectedReplyType, ProtoReply **wireReply) { VGAuthError err = VGAUTH_E_OK; GMarkupParseContext *parseContext; gsize len; ProtoReply *reply; gboolean bRet; GError *gErr = NULL; reply = Proto_NewReply(expectedReplyType); parseContext = g_markup_parse_context_new(&wireParser, 0, reply, NULL); /* * May take multiple reads if reply is broken up by the underlying * transport. */ while (!reply->complete) { gchar *rawReply = NULL; err = VGAuth_CommReadData(ctx, &len, &rawReply); if (0 == len) { // EOF -- not expected err = VGAUTH_E_COMM; Warning("%s: EOF on datastream when trying to parse\n", __FUNCTION__); goto quit; } if (VGAUTH_E_OK != err) { goto quit; } #if VGAUTH_PROTO_TRACE if (reply->rawData) { reply->rawData = g_strdup_printf("%s%s", reply->rawData, rawReply); } else { reply->rawData = g_strdup(rawReply); } #endif bRet = g_markup_parse_context_parse(parseContext, rawReply, len, &gErr); g_free(rawReply); if (!bRet) { /* * XXX Could drain the wire here, but since this should * never happen, just treat it as fatal for this socket. */ err = VGAUTH_E_COMM; Warning("%s: g_markup_parse_context_parse() failed: %s\n", __FUNCTION__, gErr->message); g_error_free(gErr); goto quit; } /* * XXX need some way to break out if packet never completed * yet socket left valid. timer? */ } #if VGAUTH_PROTO_TRACE Proto_DumpReply(reply); #endif err = Proto_SanityCheckReply(reply, ctx->comm.sequenceNumber); if (VGAUTH_E_OK != err) { Warning("%s: reply sanity check failed\n", __FUNCTION__); goto quit; } if (PROTO_REPLY_ERROR == reply->actualReplyType) { Debug("%s: service sent back error "VGAUTHERR_FMT64X" (%s)\n", __FUNCTION__, reply->errorCode, reply->replyData.error.errorMsg); err = reply->errorCode; } goto done; quit: Proto_FreeReply(reply); reply = NULL; done: *wireReply = reply; g_markup_parse_context_free(parseContext); return err; } /* ****************************************************************************** * VGAuth_SendSessionRequest -- */ /** * * Sends the sessionRequest message and verifies the returning * reply. The pipeName member of the ctx->comm is filled in. * * @param[in] ctx The VGAuthContext. * @param[in] userName The name of the user. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendSessionRequest(VGAuthContext *ctx, const char *userName, char **pipeName) // OUT { VGAuthError err; gchar *packet; ProtoReply *reply = NULL; packet = g_markup_printf_escaped(VGAUTH_SESSION_REQUEST_FORMAT, ctx->comm.sequenceNumber, userName); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_SESSION_REQ, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } /* version # check */ if (reply->replyData.sessionReq.version != atoi(VGAUTH_PROTOCOL_VERSION)) { Warning("%s: version mismatch client is %d, service %d\n", __FUNCTION__, atoi(VGAUTH_PROTOCOL_VERSION), reply->replyData.sessionReq.version); /* XXX error out, or pretend? */ } *pipeName = g_strdup(reply->replyData.sessionReq.pipeName); ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuthErrorPipeClosed -- */ /** * * Check if the error code contains a system error that * the other end closed the pipe * * @param[in] err A VGAuthError code * * @return TRUE if the error code contains a system error that the other end * closed the pipe. FALSE otherwise. * ****************************************************************************** */ static gboolean VGAuthErrorPipeClosed(VGAuthError err) { #ifdef _WIN32 return VGAUTH_ERROR_EXTRA_ERROR(err) == ERROR_NO_DATA; #else return VGAUTH_ERROR_EXTRA_ERROR(err) == EPIPE; #endif } /* ****************************************************************************** * VGAuth_SendConnectRequest -- */ /** * * Sends the connect message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendConnectRequest(VGAuthContext *ctx) { VGAuthError err = VGAUTH_E_OK; VGAuthError err2; gchar *packet; ProtoReply *reply = NULL; char *pid = NULL; #ifdef _WIN32 unsigned int challengeEventValue; HANDLE hChallengeEvent; DWORD dwPid = GetCurrentProcessId(); pid = Convert_UnsignedInt32ToText(dwPid); #endif /* Value of pid is always NULL on non-Windows platforms */ /* coverity[dead_error_line] */ packet = g_markup_printf_escaped(VGAUTH_CONNECT_REQUEST_FORMAT, ctx->comm.sequenceNumber, pid ? pid : ""); err = VGAuth_CommSendData(ctx, packet); /* * Bail out if failed. * However, continue to read the service response * if the service closed the pipe prematurely. */ if (VGAUTH_FAILED(err) && !VGAuthErrorPipeClosed(err)) { VGAUTH_LOG_WARNING("failed to send packet, %s", packet); goto done; } err2 = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_CONN, &reply); if (VGAUTH_E_OK != err2) { VGAUTH_LOG_WARNING("read & parse reply failed, as user %s", ctx->comm.userName); err = err2; goto done; } #ifdef _WIN32 err = VGAUTH_E_FAIL; CHK_TEXT_TO_UINT32(challengeEventValue, reply->replyData.connect.challengeEvent, goto done); hChallengeEvent = (HANDLE)(size_t)challengeEventValue; if (!SetEvent(hChallengeEvent)) { VGAUTH_LOG_ERR_WIN("SetEvent() failed, pipe = %s", ctx->comm.pipeName); CloseHandle(hChallengeEvent); goto done; } CloseHandle(hChallengeEvent); err = VGAUTH_E_OK; #endif ctx->comm.sequenceNumber++; done: Proto_FreeReply(reply); g_free(packet); g_free(pid); return err; } /* ****************************************************************************** * VGAuth_SendAddAliasRequest -- */ /** * * Sends the AddAlias message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] userName The user of the identity store * being changed. * @param[in] addMappedLink If TRUE, adds an entry to the * mapping file. * @param[in] pemCert The certificate to add. * @param[in] ai The associated AliasInfo. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendAddAliasRequest(VGAuthContext *ctx, const char *userName, gboolean addMappedLink, const char *pemCert, VGAuthAliasInfo *ai) { VGAuthError err = VGAUTH_E_OK; gchar *packet = NULL; ProtoReply *reply = NULL; gchar *aiPacket = NULL; if (!VGAuth_IsConnectedToServiceAsUser(ctx, userName)) { err = VGAuth_ConnectToServiceAsUser(ctx, userName); if (VGAUTH_E_OK != err) { goto quit; } } packet = g_markup_printf_escaped(VGAUTH_ADDALIAS_REQUEST_FORMAT_START, ctx->comm.sequenceNumber, userName, addMappedLink, pemCert); if (VGAUTH_SUBJECT_NAMED == ai->subject.type) { aiPacket = g_markup_printf_escaped(VGAUTH_NAMEDALIASINFO_FORMAT, ai->subject.val.name, ai->comment); } else { aiPacket = g_markup_printf_escaped(VGAUTH_ANYALIASINFO_FORMAT, ai->comment); } packet = Proto_ConcatXMLStrings(packet, aiPacket); packet = Proto_ConcatXMLStrings(packet, g_strdup(VGAUTH_ADDALIAS_REQUEST_FORMAT_END)); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_ADDALIAS, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuth_SendRemoveAliasRequest -- */ /** * * Sends the RemoveAlias message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] userName The user of the identity store being changed. * @param[in] pemCert The certifcate to be removed, in PEM format. * @param[in] subj The subject to be removed (NULL if all). * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendRemoveAliasRequest(VGAuthContext *ctx, const char *userName, const char *pemCert, VGAuthSubject *subj) { VGAuthError err = VGAUTH_E_OK; gchar *packet = NULL; ProtoReply *reply = NULL; gchar *sPacket; /* * Try connecting as user if we can, otherwise try root. * This allows for removing entries from deleted users. */ if (UsercheckUserExists(userName)) { if (!VGAuth_IsConnectedToServiceAsUser(ctx, userName)) { err = VGAuth_ConnectToServiceAsUser(ctx, userName); if (VGAUTH_E_OK != err) { goto quit; } } } else { if (!VGAuth_IsConnectedToServiceAsUser(ctx, SUPERUSER_NAME)) { err = VGAuth_ConnectToServiceAsUser(ctx, SUPERUSER_NAME); if (VGAUTH_E_OK != err) { goto quit; } } } packet = g_markup_printf_escaped(VGAUTH_REMOVEALIAS_REQUEST_FORMAT_START, ctx->comm.sequenceNumber, userName, pemCert); if (subj) { if (VGAUTH_SUBJECT_NAMED == subj->type) { sPacket = g_markup_printf_escaped(VGAUTH_SUBJECT_FORMAT, subj->val.name); } else { sPacket = g_strdup(VGAUTH_ANYSUBJECT_FORMAT); } packet = Proto_ConcatXMLStrings(packet, sPacket); } packet = Proto_ConcatXMLStrings(packet, g_strdup(VGAUTH_REMOVEALIAS_REQUEST_FORMAT_END)); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_REMOVEALIAS, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuth_SendQueryUserAliasesRequest -- */ /** * * Sends the QueryAliases message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] userName The user of the identity store * being queried. * @param[out] num The number of VGAuthUserAlias being returned. * @param[out] uaList The resulting UserAliases. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendQueryUserAliasesRequest(VGAuthContext *ctx, const char *userName, int *num, VGAuthUserAlias **uaList) { VGAuthError err = VGAUTH_E_OK; gchar *packet = NULL; ProtoReply *reply = NULL; *uaList = NULL; *num = 0; /* * Try connecting as user if we can, otherwise try root. * This allows for querying certs for deleted users. */ if (UsercheckUserExists(userName)) { if (!VGAuth_IsConnectedToServiceAsUser(ctx, userName)) { err = VGAuth_ConnectToServiceAsUser(ctx, userName); if (VGAUTH_E_OK != err) { goto quit; } } } else { if (!VGAuth_IsConnectedToServiceAsUser(ctx, SUPERUSER_NAME)) { err = VGAuth_ConnectToServiceAsUser(ctx, SUPERUSER_NAME); if (VGAUTH_E_OK != err) { goto quit; } } } packet = g_markup_printf_escaped(VGAUTH_QUERYALIASES_REQUEST_FORMAT, ctx->comm.sequenceNumber, userName); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_QUERYALIASES, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } // just copy the reply data *num = reply->replyData.queryUserAliases.num; *uaList = reply->replyData.queryUserAliases.uaList; // clear out reply before free reply->replyData.queryUserAliases.num = 0; reply->replyData.queryUserAliases.uaList = NULL; ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuth_SendQueryMappedAliasesRequest -- */ /** * * Sends the QueryMappedAliases message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[out] num The number of identities. * @param[out] maList The VGAuthMappedAliases being returned. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendQueryMappedAliasesRequest(VGAuthContext *ctx, int *num, VGAuthMappedAlias **maList) { VGAuthError err = VGAUTH_E_OK; gchar *packet = NULL; ProtoReply *reply = NULL; *num = 0; *maList = NULL; /* * QueryMappedCerts has no security restrictions, so we don't care * what user is used. */ if (!VGAuth_IsConnectedToServiceAsAnyUser(ctx)) { err = VGAuth_ConnectToServiceAsCurrentUser(ctx); if (VGAUTH_E_OK != err) { goto quit; } } packet = g_markup_printf_escaped(VGAUTH_QUERYMAPPEDALIASES_REQUEST_FORMAT, ctx->comm.sequenceNumber); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_QUERYMAPPEDALIASES, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } // just copy the reply data *num = reply->replyData.queryMappedAliases.num; *maList = reply->replyData.queryMappedAliases.maList; // clear out reply before free reply->replyData.queryMappedAliases.num = 0; reply->replyData.queryMappedAliases.maList = NULL; ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuth_SendCreateTicketRequest -- */ /** * * Sends the CreateTicket message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] userHandle The VGAuthUserHandle. * @param[out] ticket The new ticket. * * @note token is optional on Windows, ignored on other platforms * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendCreateTicketRequest(VGAuthContext *ctx, VGAuthUserHandle *userHandle, char **ticket) { VGAuthError err = VGAUTH_E_OK; gchar *packet = NULL; ProtoReply *reply = NULL; char *tokenInText = NULL; char *sPacket; VGAuthAliasInfo *ai; *ticket = NULL; if (!VGAuth_IsConnectedToServiceAsUser(ctx, userHandle->userName)) { err = VGAuth_ConnectToServiceAsUser(ctx, userHandle->userName); if (VGAUTH_E_OK != err) { goto quit; } } #ifdef _WIN32 ASSERT(Check_Is32bitNumber((size_t)userHandle->token)); tokenInText = Convert_UnsignedInt32ToText((unsigned int)(size_t)userHandle->token); #endif /* Value of tokenInText is always NULL on non-Windows platforms */ /* coverity[dead_error_line] */ packet = g_markup_printf_escaped(VGAUTH_CREATETICKET_REQUEST_FORMAT_START, ctx->comm.sequenceNumber, userHandle->userName, tokenInText ? tokenInText : "", ProtoUserHandleTypeString(userHandle)); if (VGAUTH_AUTH_TYPE_SAML == userHandle->details.type) { sPacket = g_markup_printf_escaped(VGAUTH_USERHANDLESAMLINFO_FORMAT_START, userHandle->details.val.samlData.subject); packet = Proto_ConcatXMLStrings(packet, sPacket); ai = &(userHandle->details.val.samlData.aliasInfo); if (VGAUTH_SUBJECT_NAMED == ai->subject.type) { sPacket = g_markup_printf_escaped(VGAUTH_NAMEDALIASINFO_FORMAT, ai->subject.val.name, ai->comment); } else { sPacket = g_markup_printf_escaped(VGAUTH_ANYALIASINFO_FORMAT, ai->comment); } packet = Proto_ConcatXMLStrings(packet, sPacket); packet = Proto_ConcatXMLStrings(packet, g_strdup(VGAUTH_USERHANDLESAMLINFO_FORMAT_END)); } packet = Proto_ConcatXMLStrings(packet, g_strdup(VGAUTH_CREATETICKET_REQUEST_FORMAT_END)); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_CREATETICKET, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } *ticket = g_strdup(reply->replyData.createTicket.ticket); ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); g_free(tokenInText); return err; } /* ****************************************************************************** * VGAuth_SendValidateTicketRequest -- */ /** * * Sends the ValidateTicket message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] ticket The ticket to validate. * @param[out] userHandle The new VGAuthUserHandle based on * the ticket. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendValidateTicketRequest(VGAuthContext *ctx, const char *ticket, VGAuthUserHandle **userHandle) { VGAuthError err; VGAuthError retCode = VGAUTH_E_FAIL; VGAuthUserHandle *newHandle = NULL; gchar *packet = NULL; ProtoReply *reply = NULL; HANDLE token = NULL; #ifdef _WIN32 unsigned int tokenValue; #endif *userHandle = NULL; /* * Note that only root can validate a ticket. */ if (!VGAuth_IsConnectedToServiceAsUser(ctx, SUPERUSER_NAME)) { err = VGAuth_ConnectToServiceAsUser(ctx, SUPERUSER_NAME); if (VGAUTH_E_OK != err) { retCode = err; goto done; } } packet = g_markup_printf_escaped(VGAUTH_VALIDATETICKET_REQUEST_FORMAT, ctx->comm.sequenceNumber, ticket); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { retCode = err; VGAUTH_LOG_WARNING("%s", "VGAuth_CommSendData() failed"); goto done; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_VALIDATETICKET, &reply); if (VGAUTH_E_OK != err) { retCode = err; VGAUTH_LOG_WARNING("%s", "VGAuth_ReadAndParseResponse() failed"); goto done; } #ifdef _WIN32 CHK_TEXT_TO_UINT32(tokenValue, reply->replyData.validateTicket.token, goto done); token = (HANDLE)(size_t)tokenValue; #endif err = VGAuth_CreateHandleForUsername(ctx, reply->replyData.validateTicket.userName, reply->replyData.validateTicket.type, token, &newHandle); if (err != VGAUTH_E_OK) { #ifdef _WIN32 CloseHandle(token); #endif goto done; } if (VGAUTH_AUTH_TYPE_SAML == reply->replyData.validateTicket.type) { err = VGAuth_SetUserHandleSamlInfo(ctx, newHandle, reply->replyData.validateTicket.samlSubject, &(reply->replyData.validateTicket.aliasInfo)); if (err != VGAUTH_E_OK) { #ifdef _WIN32 CloseHandle(token); #endif goto done; } } *userHandle = newHandle; ctx->comm.sequenceNumber++; retCode = VGAUTH_E_OK; done: Proto_FreeReply(reply); g_free(packet); return retCode; } /* ****************************************************************************** * VGAuth_SendRevokeTicketRequest -- */ /** * * Sends the RevokeTicket message. * * @param[in] ctx The VGAuthContext. * @param[in] ticket The ticket to revoke. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendRevokeTicketRequest(VGAuthContext *ctx, const char *ticket) { VGAuthError err; gchar *packet = NULL; ProtoReply *reply = NULL; /* * Note that only root or the owner can revoke a ticket. * * If we're root, fine. Otherwise, try to connect as current * user, which may also be root. */ if (!VGAuth_IsConnectedToServiceAsUser(ctx, SUPERUSER_NAME)) { err = VGAuth_ConnectToServiceAsCurrentUser(ctx); if (VGAUTH_E_OK != err) { goto done; } } packet = g_markup_printf_escaped(VGAUTH_REVOKETICKET_REQUEST_FORMAT, ctx->comm.sequenceNumber, ticket); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { VGAUTH_LOG_WARNING("%s", "VGAuth_CommSendData() failed"); goto done; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_REVOKETICKET, &reply); if (VGAUTH_E_OK != err) { VGAUTH_LOG_WARNING("%s", "VGAuth_ReadAndParseResponse() failed"); goto done; } ctx->comm.sequenceNumber++; done: Proto_FreeReply(reply); g_free(packet); return err; } /* ****************************************************************************** * VGAuth_SendValidateSamlBearerTokenRequest -- */ /** * * Sends the ValidateSamlToken message and verifies the returning reply. * * @param[in] ctx The VGAuthContext. * @param[in] validateOnly If set, only validation should * occur, not access token creation. * @param[in] samlToken The SAML token. * @param[in] userName The user to authenticate as. * @param[out] userHandle The resulting new userHandle. * * @return VGAUTH_E_OK on success, VGAuthError on failure * ****************************************************************************** */ VGAuthError VGAuth_SendValidateSamlBearerTokenRequest(VGAuthContext *ctx, gboolean validateOnly, const char *samlToken, const char *userName, VGAuthUserHandle **userHandle) { VGAuthError err = VGAUTH_E_OK; VGAuthUserHandle *newHandle = NULL; gchar *packet = NULL; ProtoReply *reply = NULL; HANDLE token = NULL; #ifdef _WIN32 unsigned int tokenValue; #endif VGAuthUserHandleType hType; *userHandle = NULL; /* * ValidateSAMLBearerToken has no security restrictions, so we don't care * what user is used. */ if (!VGAuth_IsConnectedToServiceAsAnyUser(ctx)) { err = VGAuth_ConnectToServiceAsCurrentUser(ctx); if (VGAUTH_E_OK != err) { goto quit; } } packet = g_markup_printf_escaped(VGAUTH_VALIDATESAMLBEARERTOKEN_REQUEST_FORMAT, ctx->comm.sequenceNumber, samlToken, userName ? userName : "", validateOnly ? "1" : "0"); err = VGAuth_CommSendData(ctx, packet); if (VGAUTH_E_OK != err) { Warning("%s: failed to send packet\n", __FUNCTION__); goto quit; } err = VGAuth_ReadAndParseResponse(ctx, PROTO_REPLY_VALIDATE_SAML_BEARER_TOKEN, &reply); if (VGAUTH_E_OK != err) { Warning("%s: read & parse reply failed\n", __FUNCTION__); goto quit; } if (!validateOnly) { hType = VGAUTH_AUTH_TYPE_SAML; #ifdef _WIN32 CHK_TEXT_TO_UINT32(tokenValue, reply->replyData.validateSamlBToken.token, goto quit); token = (HANDLE)(size_t)tokenValue; #endif } else { hType = VGAUTH_AUTH_TYPE_SAML_INFO_ONLY; } err = VGAuth_CreateHandleForUsername(ctx, reply->replyData.validateSamlBToken.userName, hType, token, &newHandle); if (err != VGAUTH_E_OK) { Warning("%s: failed to create userHandle\n", __FUNCTION__); goto quit; } /* * Pull the rest of the userHandle info out of packet and add it * to userHandle */ err = VGAuth_SetUserHandleSamlInfo(ctx, newHandle, reply->replyData.validateSamlBToken.samlSubject, &(reply->replyData.validateSamlBToken.aliasInfo)); if (err != VGAUTH_E_OK) { Warning("%s: failed to set the SAML info on the userHandle\n", __FUNCTION__); goto quit; } *userHandle = newHandle; ctx->comm.sequenceNumber++; quit: Proto_FreeReply(reply); g_free(packet); return err; }
35,150
703
#include <GameEngine/GameEnginePCH.h> #include <Core/Assets/AssetFileHeader.h> #include <GameEngine/Utils/ImageDataResource.h> #include <Texture/Image/Formats/DdsFileFormat.h> #include <Texture/Image/Formats/ImageFileFormat.h> #include <Texture/Image/Formats/StbImageFileFormats.h> #include <Texture/ezTexFormat/ezTexFormat.h> // clang-format off EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezImageDataResource, 1, ezRTTIDefaultAllocator<ezImageDataResource>) EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_RESOURCE_IMPLEMENT_COMMON_CODE(ezImageDataResource); // clang-format on ezImageDataResource::ezImageDataResource() : ezResource(DoUpdate::OnAnyThread, 1) { } ezImageDataResource::~ezImageDataResource() = default; ezResourceLoadDesc ezImageDataResource::UnloadData(Unload WhatToUnload) { m_Descriptor.Clear(); ezResourceLoadDesc res; res.m_uiQualityLevelsDiscardable = 0; res.m_uiQualityLevelsLoadable = 0; res.m_State = ezResourceState::Unloaded; return res; } ezResourceLoadDesc ezImageDataResource::UpdateContent(ezStreamReader* Stream) { EZ_LOG_BLOCK("ezImageDataResource::UpdateContent", GetResourceDescription().GetData()); ezResourceLoadDesc res; res.m_uiQualityLevelsDiscardable = 0; res.m_uiQualityLevelsLoadable = 0; if (Stream == nullptr) { res.m_State = ezResourceState::LoadedResourceMissing; return res; } // skip the absolute file path data that the standard file reader writes into the stream ezStringBuilder sAbsFilePath; (*Stream) >> sAbsFilePath; ezImageDataResourceDescriptor desc; if (sAbsFilePath.HasExtension("ezImageData")) { ezAssetFileHeader AssetHash; if (AssetHash.Read(*Stream).Failed()) { res.m_State = ezResourceState::LoadedResourceMissing; return res; } ezUInt8 uiVersion = 0; ezUInt8 uiDataFormat = 0; *Stream >> uiVersion; *Stream >> uiDataFormat; if (uiVersion != 1 || uiDataFormat != 1) { ezLog::Error("Unsupported ezImageData file format or version"); res.m_State = ezResourceState::LoadedResourceMissing; return res; } ezStbImageFileFormats fmt; if (fmt.ReadImage(*Stream, desc.m_Image, ezLog::GetThreadLocalLogSystem(), "png").Failed()) { res.m_State = ezResourceState::LoadedResourceMissing; return res; } } else { ezStringBuilder ext; ext = sAbsFilePath.GetFileExtension(); if (ezImageFileFormat::GetReaderFormat(ext)->ReadImage(*Stream, desc.m_Image, ezLog::GetThreadLocalLogSystem(), ext).Failed()) { res.m_State = ezResourceState::LoadedResourceMissing; return res; } } CreateResource(std::move(desc)); res.m_State = ezResourceState::Loaded; return res; } void ezImageDataResource::UpdateMemoryUsage(MemoryUsage& out_NewMemoryUsage) { out_NewMemoryUsage.m_uiMemoryCPU = sizeof(ezImageDataResource); out_NewMemoryUsage.m_uiMemoryGPU = 0; if (m_Descriptor) { out_NewMemoryUsage.m_uiMemoryCPU += m_Descriptor->m_Image.GetByteBlobPtr().GetCount(); } } EZ_RESOURCE_IMPLEMENT_CREATEABLE(ezImageDataResource, ezImageDataResourceDescriptor) { m_Descriptor = EZ_DEFAULT_NEW(ezImageDataResourceDescriptor); *m_Descriptor = std::move(descriptor); ezResourceLoadDesc res; res.m_uiQualityLevelsDiscardable = 0; res.m_uiQualityLevelsLoadable = 0; res.m_State = ezResourceState::Loaded; if (m_Descriptor->m_Image.Convert(ezImageFormat::R32G32B32A32_FLOAT).Failed()) { res.m_State = ezResourceState::LoadedResourceMissing; } return res; } // ezResult ezImageDataResourceDescriptor::Serialize(ezStreamWriter& stream) const //{ // EZ_SUCCEED_OR_RETURN(ezImageFileFormat::GetWriterFormat("png")->WriteImage(stream, m_Image, ezLog::GetThreadLocalLogSystem(), "png")); // // return EZ_SUCCESS; //} // // ezResult ezImageDataResourceDescriptor::Deserialize(ezStreamReader& stream) //{ // EZ_SUCCEED_OR_RETURN(ezImageFileFormat::GetReaderFormat("png")->ReadImage(stream, m_Image, ezLog::GetThreadLocalLogSystem(), "png")); // // return EZ_SUCCESS; //}
1,517
1,921
/** * @file * @brief Handling of error conditions that are not program bugs. **/ #include "AppHdr.h" #include "errors.h" #include <cerrno> #include <cstdarg> #include <cstring> #include "stringutil.h" NORETURN void fail(const char *msg, ...) { va_list args; va_start(args, msg); string buf = vmake_stringf(msg, args); va_end(args); // Do we want to call end() right on when there's no one trying catching, // or should we risk exception code mess things up? throw ext_fail_exception(buf); } NORETURN void sysfail(const char *msg, ...) { va_list args; va_start(args, msg); string buf = vmake_stringf(msg, args); va_end(args); buf += ": "; buf += strerror(errno); throw ext_fail_exception(buf); } NORETURN void corrupted(const char *msg, ...) { va_list args; va_start(args, msg); string buf = vmake_stringf(msg, args); va_end(args); throw corrupted_save(buf); } /** * Toss failures from a test into stderr & an error file, if there were any * failures. * * @param fails The failures, if any. * @param name Errors are dumped to "[name].out"; name should be unique. */ void dump_test_fails(string fails, string name) { if (fails.empty()) return; fprintf(stderr, "%s", fails.c_str()); const string outfile = make_stringf("%s.out", name.c_str()); FILE *f = fopen(outfile.c_str(), "w"); if (!f) sysfail("can't write test output"); fprintf(f, "%s", fails.c_str()); fclose(f); fail("%s event errors (dumped to %s)", name.c_str(), outfile.c_str()); }
647
5,169
{ "name": "TGMetaWeblogApi", "version": "0.1.0", "summary": "A simple MetaWeblog Api for OS X and iOS writing in Objective-C", "homepage": "https://github.com/terwer/TGMetaWeblogApi", "license": { "type": "MIT", "file": "LICENSE" }, "authors": "<NAME>", "source": { "git": "https://github.com/terwer/TGMetaWeblogApi.git", "tag": "0.1.0" }, "source_files": "TGMetaWeblogApi", "requires_arc": true, "dependencies": { "AFNetworking": [ "~> 2.5.1" ], "wpxmlrpc": [ "~> 0.7" ] }, "platforms": { "ios": "6.0" }, "frameworks": [ "Foundation", "UIKit", "Security" ] }
314
335
<reponame>Safal08/Hacktoberfest-1<filename>F/Freethinker_noun.json { "word": "Freethinker", "definitions": [ "A person who rejects accepted opinions, especially those concerning religious belief." ], "parts-of-speech": "Noun" }
96
352
// ========================================================================= // Copyright 2019 T-Mobile, US // // 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. // See the readme.txt file for additional language around disclaimer of warranties. // ========================================================================= package com.tmobile.cso.vault.api.config; import java.util.ArrayList; import java.util.List; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.tmobile.cso.vault.api.exception.LogMessage; import com.tmobile.cso.vault.api.utils.JSONUtil; import com.tmobile.cso.vault.api.utils.ThreadLocalContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.StringVendorExtension; import springfox.documentation.service.VendorExtension; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.ApiSelectorBuilder; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 @EnableAutoConfiguration @PropertySource("classpath:swaggernotes.properties") @ComponentScan(basePackages="com.tmobile.cso.vault.api.*") public class SwaggerConfig { @Value("${selfservice.enable:true}") private boolean isSelfServiceEnabled; @Value("${ad.passwordrotation.enable:true}") private boolean isAdPswdRotationEnabled; private static Logger log = LogManager.getLogger(SwaggerConfig.class); @Bean public Docket tvaultapi() { Docket docket = new Docket(DocumentationType.SWAGGER_2); ApiSelectorBuilder apiSelectorBuilder = new ApiSelectorBuilder(docket); apiSelectorBuilder.apis(RequestHandlerSelectors.any()); apiSelectorBuilder.paths(PathSelectors.any()); apiSelectorBuilder.paths(Predicates.not(PathSelectors.regex("/error.*"))); log.debug("Checking enable/disable status for features"); if (!isSelfServiceEnabled) { log.debug("Self Service is disabled"); apiSelectorBuilder.paths(PathSelectors.regex("(?!/v2/ss).+")); } if (!isAdPswdRotationEnabled) { log.debug("AD Password rotation is disabled"); apiSelectorBuilder.paths(PathSelectors.regex("(?!/v2/ad).+")); apiSelectorBuilder.paths(PathSelectors.regex("(?!/v2/serviceaccounts).+")); } return apiSelectorBuilder.build().pathMapping("/").apiInfo(metadata()); } /** * TODO: Values to be corrected later * @return */ private ApiInfo metadata() { List<VendorExtension> vxtensions = new ArrayList<VendorExtension>(); vxtensions.add((new StringVendorExtension("",""))); ApiInfo apiInfo = new ApiInfo( "TVault API - Simplified Secret Management System", "T-Vault is built to simplify the process of secrets management. We wanted to build an intuitive and easy to use tool that application developers can easily adopt without sacrificing their agility while still following best practices for secrets management. It uses a few open source products internally including, at its heart Hashicorp Vault. Hashicorp vault provides the core functionality of safely storing secrets at rest and access control to those secrets. T-Vault builds on that base to provide a higher-level of abstraction called Safe. Safes are logical abstractions, internally using the concept of paths within vault. T-Vault simplifies the access management to secrets by hiding away all the complexities of managing polices.", "2.0", "https://github.com/tmobile/t-vault/blob/dev/CODE_OF_CONDUCT.md", new Contact("","",""), "Apache License Version 2.0", "https://github.com/tmobile/t-vault/blob/dev/LICENSE", vxtensions) ; return apiInfo; } }
1,516
10,608
<gh_stars>1000+ import datasets _CITATION = """\ @software{bact_2019_3457447, author = {Suriyawongkul, Arthit and Chuangsuwanich, Ekapol and Chormai, Pattarawat and Polpanumas, Charin}, title = {PyThaiNLP/wisesight-sentiment: First release}, month = sep, year = 2019, publisher = {Zenodo}, version = {v1.0}, doi = {10.5281/zenodo.3457447}, url = {https://doi.org/10.5281/zenodo.3457447} } """ _LICENSE = "CC0" _DESCRIPTION = """\ `wisesight1000` contains Thai social media texts randomly drawn from the full `wisesight-sentiment`, tokenized by human annotators. Out of the labels `neg` (negative), `neu` (neutral), `pos` (positive), `q` (question), 250 samples each. Some texts are removed because they look like spam.Because these samples are representative of real world content, we believe having these annotaed samples will allow the community to robustly evaluate tokenization algorithms. """ class Wisesight1000Config(datasets.BuilderConfig): def __init__(self, **kwargs): """BuilderConfig Args: **kwargs: keyword arguments forwarded to super. """ super(Wisesight1000Config, self).__init__(**kwargs) class Wisesight1000(datasets.GeneratorBasedBuilder): _DOWNLOAD_URL = "https://raw.githubusercontent.com/PyThaiNLP/wisesight-sentiment/master/word-tokenization/wisesight-1000-samples-tokenised.label" # character type mapping from https://github.com/rkcosmos/deepcut/blob/master/deepcut/utils.py _CHAR_TYPES_DICT = { "กขฃคฆงจชซญฎฏฐฑฒณดตถทธนบปพฟภมยรลวศษสฬอ": "c", "ฅฉผฟฌหฮ": "n", "ะาำิีืึุู": "v", # า ะ ำ ิ ี ึ ื ั ู ุ "เแโใไ": "w", "่้๊๋": "t", # วรรณยุกต์ ่ ้ ๊ ๋ "์ๆฯ.": "s", # ์ ๆ ฯ . "0123456789๑๒๓๔๕๖๗๘๙": "d", '"': "q", "‘": "q", "’": "q", "'": "q", " ": "p", "abcdefghijklmnopqrstuvwxyz": "s_e", "ABCDEFGHIJKLMNOPQRSTUVWXYZ": "b_e", } _CHAR_TYPE_FLATTEN = {} for ks, v in _CHAR_TYPES_DICT.items(): for k in ks: _CHAR_TYPE_FLATTEN[k] = v _CHAR_TYPES = ["b_e", "c", "d", "n", "o", "p", "q", "s", "s_e", "t", "v", "w"] BUILDER_CONFIGS = [ Wisesight1000Config( name="wisesight1000", version=datasets.Version("1.0.0"), description="993 word-annotated social media messages sampled from `wisesight-sentiment`", ), ] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "char": datasets.Sequence(datasets.Value("string")), "char_type": datasets.Sequence(datasets.features.ClassLabel(names=self._CHAR_TYPES)), "is_beginning": datasets.Sequence(datasets.features.ClassLabel(names=["neg", "pos"])), } ), supervised_keys=None, homepage="https://github.com/PyThaiNLP/wisesight-sentiment", citation=_CITATION, license=_LICENSE, ) def _split_generators(self, dl_manager): data_path = dl_manager.download_and_extract(self._DOWNLOAD_URL) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_path}, ), ] def _generate_examples(self, filepath): with open(filepath, encoding="utf-8") as f: for _id, line in enumerate(f): chars = [] char_types = [] is_beginnings = [] # tokens are pipe separated splits = line.split("|") for token in splits: for i in range(len(token)): chars.append(token[i]) char_types.append(self._CHAR_TYPE_FLATTEN.get(token[i], "o")) is_beginning = 1 if i == 0 else 0 is_beginnings.append(is_beginning) yield _id, { "char": chars, "char_type": char_types, "is_beginning": is_beginnings, }
2,336
432
<filename>test/nvmm/demo/toyvirt/toydev.c /* * Copyright (c) 2018-2021 <NAME>, m00nbsd.net * All rights reserved. * * This code is part of the NVMM hypervisor. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* * This file implements two really simple devices. One is an MMIO device, the * other is an IO device. */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "common.h" /* -------------------------------------------------------------------------- */ /* * LAPIC device, MMIO. We only handle the ID. */ static void toydev_lapic(gpaddr_t gpa, bool write, uint8_t *buf, size_t size) { uint32_t *data; #define LAPIC_BASE 0xfee00000 #define LAPIC_ID 0x020 if (write) { printf("[!] Unexpected LAPIC write!\n"); exit(EXIT_FAILURE); } if (size != sizeof(uint32_t)) { printf("[!] Unexpected LAPIC read size %zu!\n", size); exit(EXIT_FAILURE); } if (gpa == LAPIC_BASE + LAPIC_ID) { data = (uint32_t *)&buf[3]; *data = 120; } } /* * Console device, IO. It retrieves a string on port 123, and we display it. */ static int toydev_cons(int port __unused, bool in, uint8_t *buf, size_t size) { static bool new_line = true; size_t i; if (in) { /* This toy device doesn't take in. */ printf("[!] Unexpected IN for the console\n"); exit(EXIT_FAILURE); } for (i = 0; i < size; i++) { if (new_line) { printf("mach>\t"); new_line = false; } printf("%c", (char)buf[i]); new_line = (buf[i] == '\n'); } return 0; } /* -------------------------------------------------------------------------- */ void toydev_mmio(gpaddr_t gpa, bool write, uint8_t *buf, size_t size) { /* * Dispatch MMIO requests to the proper device. */ #define LAPIC_START 0xfee00000 #define LAPIC_END 0xfee01000 if (gpa >= LAPIC_START && gpa + size <= LAPIC_END) { toydev_lapic(gpa, write, buf, size); return; } printf("[!] Unknown MMIO device GPA=%p\n", (void *)gpa); exit(EXIT_FAILURE); } void toydev_io(int port, bool in, uint8_t *buf, size_t size) { /* * Dispatch IO requests to the proper device. */ if (port == 123) { toydev_cons(port, in, buf, size); return; } printf("[!] Unknown IO device PORT=%d\n", port); exit(EXIT_FAILURE); }
1,249
349
import pytest x = 1 @pytest.fixture() def f1(): global x x = 2 yield 15 x = 3 def test_1(): assert x == 1 def test_2(f1): assert x == 2 assert f1 == 15 def test_3(): assert x == 3
106
852
#include "TrackingTools/PatternTools/interface/TrajectoryExtrapolatorToLine.h" #include "TrackingTools/GeomPropagators/interface/AnalyticalPropagator.h" #include "DataFormats/GeometryCommonDetAlgo/interface/DeepCopyPointerByClone.h" #include "DataFormats/GeometrySurface/interface/BoundPlane.h" #include "DataFormats/GeometrySurface/interface/OpenBounds.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" TrajectoryStateOnSurface TrajectoryExtrapolatorToLine::extrapolate(const FreeTrajectoryState& fts, const Line& L, const Propagator& aPropagator) const { DeepCopyPointerByClone<Propagator> p(aPropagator.clone()); p->setPropagationDirection(anyDirection); FreeTrajectoryState fastFts(fts.parameters(), fts.curvilinearError()); GlobalVector T1 = fastFts.momentum().unit(); GlobalPoint T0 = fastFts.position(); double distance = 9999999.9; double old_distance; int n_iter = 0; bool refining = true; LogDebug("TrajectoryExtrapolatorToLine") << "START REFINING"; while (refining) { LogDebug("TrajectoryExtrapolatorToLine") << "Refining cycle..."; // describe orientation of target surface on basis of track parameters n_iter++; Line T(T0, T1); GlobalPoint B = T.closerPointToLine(L); old_distance = distance; //create surface GlobalPoint BB = B + 0.3 * (T0 - B); Surface::PositionType pos(BB); GlobalVector XX(T1.y(), -T1.x(), 0.); GlobalVector YY(T1.cross(XX)); Surface::RotationType rot(XX, YY); ReferenceCountingPointer<Plane> surface = Plane::build(pos, rot); LogDebug("TrajectoryExtrapolatorToLine") << "Current plane position: " << surface->toGlobal(LocalPoint(0., 0., 0.)); LogDebug("TrajectoryExtrapolatorToLine") << "Current plane normal: " << surface->toGlobal(LocalVector(0, 0, 1)); LogDebug("TrajectoryExtrapolatorToLine") << "Current momentum: " << T1; // extrapolate fastFts to target surface TrajectoryStateOnSurface tsos = p->propagate(fastFts, *surface); if (!tsos.isValid()) { LogDebug("TrajectoryExtrapolatorToLine") << "TETL - extrapolation failed"; return tsos; } else { T0 = tsos.globalPosition(); T1 = tsos.globalMomentum().unit(); GlobalVector D = L.distance(T0); distance = D.mag(); if (fabs(old_distance - distance) < 0.000001) { refining = false; } if (old_distance - distance < 0.) { refining = false; LogDebug("TrajectoryExtrapolatorToLine") << "TETL- stop to skip loops"; } } } // // Now propagate with errors and (not for the moment) perform rotation // // Origin of local system: point of closest approach on the line // (w.r.t. to tangent to helix at last iteration) // Line T(T0, T1); GlobalPoint origin(L.closerPointToLine(T)); // // Axes of local system: // x from line to helix at closest approach // z along the helix // y to complete right-handed system // GlobalVector ZZ(T1.unit()); GlobalVector YY(ZZ.cross(T0 - origin).unit()); GlobalVector XX(YY.cross(ZZ)); Surface::RotationType rot(XX, YY, ZZ); ReferenceCountingPointer<Plane> surface = Plane::build(origin, rot); TrajectoryStateOnSurface tsos = p->propagate(fts, *surface); return tsos; }
1,322