diff --git a/pool/shard009/C++/0109950_toolboxcontroller.cpp b/pool/shard009/C++/0109950_toolboxcontroller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e0df36147464790fd645fc5c7021c8377d60d7b --- /dev/null +++ b/pool/shard009/C++/0109950_toolboxcontroller.cpp @@ -0,0 +1,102 @@ +/* + * niepce - darkroom/toolboxcontroller.cpp + * + * Copyright (C) 2008-2014 Hubert Figuiere + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include +#include +#include + +#include "toolboxcontroller.hpp" +#include "fwk/base/debug.hpp" +#include "fwk/toolkit/widgets/editablehscale.hpp" +#include "dritemwidget.hpp" + +#ifndef DATADIR +#error DATADIR is not defined +#endif + +namespace dr { + +ToolboxController::ToolboxController() + : Dockable("tools", _("Develop"), "apply") // FIXME there is no equivalent it seems. +{ + +} + +Gtk::Widget * +ToolboxController::buildWidget() +{ + if(m_widget) { + return m_widget; + } + DrItemWidget *item = nullptr; + fwk::EditableHScale *s = nullptr; + + Gtk::Box *toolbox = Dockable::build_vbox(); + m_widget = toolbox; + DBG_ASSERT(toolbox, "vbox not found."); + + item = manage(new DrItemWidget(_("Crop"))); + toolbox->pack_start(*item, Gtk::PACK_SHRINK); + s = Gtk::manage(new fwk::EditableHScale("/org/gnome/Niepce/pixmaps/niepce-transform-rotate.png", + -45.0, 45.0, 0.5)); + item->add_widget(_("Tilt"), *s); + + item = manage(new DrItemWidget(_("White balance"))); + toolbox->pack_start(*item, Gtk::PACK_SHRINK); + s = Gtk::manage(new fwk::EditableHScale(0.0, 100.0, 1.0)); + item->add_widget(_("Color temperature"), *s); + + item = manage(new DrItemWidget(_("Tone and colour"))); + toolbox->pack_start(*item, Gtk::PACK_SHRINK); + s = Gtk::manage(new fwk::EditableHScale(-5.0, 5.0, 0.1)); +// s->signal_value_changed().connect(); + item->add_widget(_("Exposure"), *s); + s = Gtk::manage(new fwk::EditableHScale(0, 100, 1)); + item->add_widget(_("Recovery"), *s); + s = Gtk::manage(new fwk::EditableHScale(0, 100, 1)); + item->add_widget(_("Fill Light"), *s); + s = Gtk::manage(new fwk::EditableHScale(0, 100, 1)); + item->add_widget(_("Blacks"), *s); + s = Gtk::manage(new fwk::EditableHScale(-100, 100, 1)); + item->add_widget(_("Brightness"), *s); + s = Gtk::manage(new fwk::EditableHScale(-100, 100, 1)); + item->add_widget(_("Contrast"), *s); + s = Gtk::manage(new fwk::EditableHScale(-100, 100, 1)); + item->add_widget(_("Saturation"), *s); + s = Gtk::manage(new fwk::EditableHScale(-100, 100, 1)); + item->add_widget(_("Vibrance"), *s); + + return m_widget; +} + + +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)) + indent-tabs-mode:nil + fill-column:80 + End: +*/ diff --git a/pool/shard009/C++/0109952_analyzer_tester.cc b/pool/shard009/C++/0109952_analyzer_tester.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b5be7f3ee33c73a9704bafa9f1b736c8a3cd9ea --- /dev/null +++ b/pool/shard009/C++/0109952_analyzer_tester.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2018 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 "paddle/fluid/inference/analysis/analyzer.h" + +#include +#include +#include "paddle/fluid/inference/analysis/ut_helper.h" +#include "paddle/fluid/inference/api/paddle_inference_api.h" +#include "paddle/fluid/inference/api/paddle_inference_pass.h" + +namespace paddle { +namespace inference { +namespace analysis { + +using namespace framework; // NOLINT + +TEST(Analyzer, analysis_without_tensorrt) { + FLAGS_IA_enable_tensorrt_subgraph_engine = false; + Argument argument; + argument.fluid_model_dir.reset(new std::string(FLAGS_inference_model_dir)); + Analyzer analyser; + analyser.Run(&argument); +} + +TEST(Analyzer, analysis_with_tensorrt) { + FLAGS_IA_enable_tensorrt_subgraph_engine = true; + Argument argument; + argument.fluid_model_dir.reset(new std::string(FLAGS_inference_model_dir)); + Analyzer analyser; + analyser.Run(&argument); +} + +void TestWord2vecPrediction(const std::string &model_path) { + NativeConfig config; + config.model_dir = model_path; + config.use_gpu = false; + config.device = 0; + auto predictor = + ::paddle::CreatePaddlePredictor( + config); + + // One single batch + + int64_t data[4] = {1, 2, 3, 4}; + PaddleTensor tensor; + tensor.shape = std::vector({4, 1}); + tensor.data = PaddleBuf(data, sizeof(data)); + tensor.dtype = PaddleDType::INT64; + + // For simplicity, we set all the slots with the same data. + std::vector slots(4, tensor); + std::vector outputs; + CHECK(predictor->Run(slots, &outputs)); + + PADDLE_ENFORCE(outputs.size(), 1UL); + // Check the output buffer size and result of each tid. + PADDLE_ENFORCE(outputs.front().data.length(), 33168UL); + float result[5] = {0.00129761, 0.00151112, 0.000423564, 0.00108815, + 0.000932706}; + const size_t num_elements = outputs.front().data.length() / sizeof(float); + // The outputs' buffers are in CPU memory. + for (size_t i = 0; i < std::min(5UL, num_elements); i++) { + LOG(INFO) << "data: " + << static_cast(outputs.front().data.data())[i]; + PADDLE_ENFORCE(static_cast(outputs.front().data.data())[i], + result[i]); + } +} + +TEST(Analyzer, word2vec_without_analysis) { + TestWord2vecPrediction(FLAGS_inference_model_dir); +} + +} // namespace analysis +} // namespace inference +} // namespace paddle diff --git a/pool/shard009/C++/0109956_Rectangle.cpp b/pool/shard009/C++/0109956_Rectangle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9dcc4b43134820851a2dc829e7d09edc0ed4ec26 --- /dev/null +++ b/pool/shard009/C++/0109956_Rectangle.cpp @@ -0,0 +1,64 @@ +#include + +#include +#include +#include +#include + +#include "Rectangle.h" + +// Rectangle (heigth, witdth) +ph::Rectangle::Rectangle(const int height, const int width) { + this->height = height; + this->width = width; + this->rectangle = new Geometry; + this->addDrawable(rectangle); + + compute(); +} + +// creating vertices/ normals / indices; simple rectangle build from two triangles +void ph::Rectangle::compute() { + ref_ptr vertices = new Vec3Array(); + ref_ptr normals = new Vec3Array(); + ref_ptr indices = new DrawElementsUInt(GL_TRIANGLE_STRIP); + + vertices->push_back(Vec3((-1/2.0)*height, 0.0, (-1/2.0)*width)); + vertices->push_back(Vec3((1/2.0)*height, 0.0, (-1/2.0)*width)); + vertices->push_back(Vec3((-1/2.0)*height, 0.0, (1/2.0)*width)); + vertices->push_back(Vec3((1/2.0)*height, 0.0, (1/2.0)*width)); + + indices->push_back(0); indices->push_back(1); indices->push_back(2); + indices->push_back(1); indices->push_back(2); indices->push_back(3); + + this->rectangle->setVertexArray(vertices.get()); + this->rectangle->addPrimitiveSet(indices.get()); +} + +// creating texture coordinates +void ph::Rectangle::setTextureCoordinates(int textureNumber) { + ref_ptr texcoords = new Vec2Array; + + texcoords->push_back(Vec2(0.0,0.0)); + texcoords->push_back(Vec2(1.0,0.0)); + texcoords->push_back(Vec2(0.0,1.0)); + texcoords->push_back(Vec2(1.0,1.0)); + + this->rectangle->setTexCoordArray(textureNumber, texcoords.get()); +} + +// setting texture on rectangle +void ph::Rectangle::setTexture(const int textureNumber, const string filename) { + this->setTextureCoordinates(textureNumber); + + ref_ptr texture = new Texture2D; + ref_ptr image = osgDB::readImageFile(filename); + texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE); + texture->setImage(image.get()); + this->getOrCreateStateSet()->setTextureAttributeAndModes(textureNumber, texture.get()); + + // enabling culling for rectangles / skybox + ref_ptr cull = new CullFace; + cull->setMode(CullFace::BACK); + this->getOrCreateStateSet()->setAttributeAndModes(cull.get()); +} diff --git a/pool/shard009/C++/0109958_FreeLink.cc b/pool/shard009/C++/0109958_FreeLink.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa6389aacb5080e49c65ebc44044dc8db975887b --- /dev/null +++ b/pool/shard009/C++/0109958_FreeLink.cc @@ -0,0 +1,103 @@ +/* + * opencog/atoms/core/FreeLink.cc + * + * Copyright (C) 2015 Linas Vepstas + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License v3 as + * published by the Free Software Foundation and including the exceptions + * at http://opencog.org/wiki/Licenses + * + * 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 Affero General Public License + * along with this program; if not, write to: + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include "FreeLink.h" +#include "ScopeLink.h" +#include "VariableList.h" + +using namespace opencog; + +FreeLink::FreeLink(const HandleSeq& oset, + TruthValuePtr tv, + AttentionValuePtr av) + : Link(FREE_LINK, oset, tv, av) +{ + init(); +} + +FreeLink::FreeLink(const Handle& a, + TruthValuePtr tv, + AttentionValuePtr av) + : Link(FREE_LINK, a, tv, av) +{ + init(); +} + +FreeLink::FreeLink(Type t, const HandleSeq& oset, + TruthValuePtr tv, + AttentionValuePtr av) + : Link(t, oset, tv, av) +{ + if (not classserver().isA(t, FREE_LINK)) + throw InvalidParamException(TRACE_INFO, "Expecting a FreeLink"); + + // Derived classes have thier own init routines. + if (FREE_LINK != t) return; + init(); +} + +FreeLink::FreeLink(Type t, const Handle& a, + TruthValuePtr tv, + AttentionValuePtr av) + : Link(t, a, tv, av) +{ + if (not classserver().isA(t, FREE_LINK)) + throw InvalidParamException(TRACE_INFO, "Expecting a FreeLink"); + + // Derived classes have thier own init routines. + if (FREE_LINK != t) return; + init(); +} + +FreeLink::FreeLink(Type t, const Handle& a, const Handle& b, + TruthValuePtr tv, + AttentionValuePtr av) + : Link(t, a, b, tv, av) +{ + if (not classserver().isA(t, FREE_LINK)) + throw InvalidParamException(TRACE_INFO, "Expecting a FreeLink"); + + // Derived classes have thier own init routines. + if (FREE_LINK != t) return; + init(); +} + +FreeLink::FreeLink(Link& l) + : Link(l) +{ + Type tscope = l.getType(); + if (not classserver().isA(tscope, FREE_LINK)) + throw InvalidParamException(TRACE_INFO, "Expecting a FreeLink"); + + // Derived classes have thier own init routines. + if (FREE_LINK != tscope) return; + init(); +} + +/* ================================================================= */ + +void FreeLink::init(void) +{ + _vars.find_variables(_outgoing); +} diff --git a/pool/shard009/C++/0109959_cryptauth_device_id_provider_impl.cc b/pool/shard009/C++/0109959_cryptauth_device_id_provider_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..0dd5e6747aa65ab9d69144dd532db9acf3e43beb --- /dev/null +++ b/pool/shard009/C++/0109959_cryptauth_device_id_provider_impl.cc @@ -0,0 +1,44 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/cryptauth/cryptauth_device_id_provider_impl.h" + +#include "base/guid.h" +#include "base/no_destructor.h" +#include "chrome/browser/browser_process.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" + +namespace ash { + +// static +void CryptAuthDeviceIdProviderImpl::RegisterLocalPrefs( + PrefRegistrySimple* registry) { + registry->RegisterStringPref(prefs::kCryptAuthDeviceId, std::string()); +} + +// static +const CryptAuthDeviceIdProviderImpl* +CryptAuthDeviceIdProviderImpl::GetInstance() { + static const base::NoDestructor provider; + return provider.get(); +} + +std::string CryptAuthDeviceIdProviderImpl::GetDeviceId() const { + PrefService* local_state = g_browser_process->local_state(); + DCHECK(local_state); + + std::string device_id = local_state->GetString(prefs::kCryptAuthDeviceId); + if (device_id.empty()) { + device_id = base::GenerateGUID(); + local_state->SetString(prefs::kCryptAuthDeviceId, device_id); + } + + return device_id; +} + +CryptAuthDeviceIdProviderImpl::CryptAuthDeviceIdProviderImpl() = default; + +} // namespace ash diff --git a/pool/shard009/C++/0109960_slot1comp_mc.cpp b/pool/shard009/C++/0109960_slot1comp_mc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1540712d20ada0bbb1c6e291fce50c7b6c5fb479 --- /dev/null +++ b/pool/shard009/C++/0109960_slot1comp_mc.cpp @@ -0,0 +1,43 @@ +/* + Copyright (C) 2013-2017 DeSmuME team + + This file 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 file 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 the this software. If not, see . +*/ + +//this file contains the components used for emulating standard gamecard "MC" devices (eeprom, fram, flash) +//this is largely done by accessing the BackupDevice resources in the core emulator + +#include "slot1comp_mc.h" + +#include "../MMU.h" +#include "../NDSSystem.h" + +Slot1Comp_MC g_Slot1Comp_MC; + +u8 Slot1Comp_MC::auxspi_transaction(int PROCNUM, u8 value) +{ + return MMU_new.backupDevice.data_command(value, PROCNUM); +} + +void Slot1Comp_MC::auxspi_reset(int PROCNUM) +{ + MMU_new.backupDevice.reset_command(); +} + +void Slot1Comp_MC::connect() +{ + //gamehack: not really a game hack + if(gameInfo.IsCode("AXBJ")) + MMU_new.backupDevice.uninitializedValue = 0x00; // Daigassou! Band Brothers DX (JP) +} \ No newline at end of file diff --git a/pool/shard009/C++/0109965_page_launcher_api.cc b/pool/shard009/C++/0109965_page_launcher_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..c52a012adc96e479a7ac47adaae275ff69c6d218 --- /dev/null +++ b/pool/shard009/C++/0109965_page_launcher_api.cc @@ -0,0 +1,39 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/page_launcher/page_launcher_api.h" + +#include "base/lazy_instance.h" +#include "base/memory/linked_ptr.h" +#include "chrome/browser/extensions/event_router.h" +#include "chrome/browser/extensions/extension_system.h" +#include "chrome/common/extensions/api/page_launcher.h" +#include "googleurl/src/gurl.h" + +namespace extensions { + +// static +void PageLauncherAPI::DispatchOnClickedEvent( + Profile* profile, + const std::string& extension_id, + const GURL& url, + const std::string& mimetype, + const std::string* page_title, + const std::string* selected_text) { + api::page_launcher::PageData data; + data.url = url.spec(); + data.mimetype = mimetype; + if (page_title) + data.title.reset(new std::string(*page_title)); + if (selected_text) + data.selection_text.reset(new std::string(*selected_text)); + + scoped_ptr event( + new Event("pageLauncher.onClicked", + api::page_launcher::OnClicked::Create(data))); + EventRouter* event_router = ExtensionSystem::Get(profile)->event_router(); + event_router->DispatchEventToExtension(extension_id, event.Pass()); +} + +} // namespace extensions diff --git a/pool/shard009/C++/0109967_3955491.cpp b/pool/shard009/C++/0109967_3955491.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e71c5cc2a2c036359d8bdbd80a4a873ddf197ead --- /dev/null +++ b/pool/shard009/C++/0109967_3955491.cpp @@ -0,0 +1,80 @@ +//Language: GNU C++ + + + // #includes {{{ + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + using namespace std; + // }}} + // #defines {{{ + #define FOR(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++) + #define SZ(x) ((int)(x).size()) + #define ALL(x) (x).begin(),(x).end() + #define REP(i,n) for(int i=0;i<(n);i++) + #define REP1(i,a,b) for(int i=(a);i<=(b);i++) + #define PER(i,n) for(int i=(n)-1;i>=0;i--) + #define PER1(i,a,b) for(int i=(a);i>=(b);i--) + #define RI(x) scanf("%d",&x) + #define DRI(x) int x;RI(x) + #define RII(x,y) scanf("%d%d",&x,&y) + #define DRII(x,y) int x,y;RII(x,y) + #define RIII(x,y,z) scanf("%d%d%d",&x,&y,&z) + #define DRIII(x,y,z) int x,y,z;RIII(x,y,z) + #define RS(x) scanf("%s",x) + #define PI(x) printf("%d\n",x) + #define PIS(x) printf("%d ",x) + #define CASET int ___T,cas=1;scanf("%d",&___T);while(___T--) + #define CASEN0(n) int cas=1;while(scanf("%d",&n)!=EOF&&n) + #define CASEN(n) int cas=1;while(scanf("%d",&n)!=EOF) + #define MP make_pair + #define PB push_back + #define MS0(x) memset(x,0,sizeof(x)) + #define MS1(x) memset(x,-1,sizeof(x)) + + #define F first + #define S second + typedef pair PII; + typedef long long LL; + typedef unsigned long long ULL; + // }}} +int a[102][2],n; +int s[102]; +bool dfs(int x,int y){ + if (x==y) return true; + s[x]=1; + REP1(i,1,n){ + if (!s[i] && ((a[i][0]a[x][0])||(a[i][0]a[x][1]))) + if (dfs(i,y)) return true; + } + return false; + +} +main(){ + DRI(t); + n=0; + REP(i,t){ + DRIII(o,x,y); + if (o==1){ + a[++n][0]=x; + a[n][1]=y; + }else{ + MS0(s); + if (dfs(x,y)) puts("YES");else puts("NO"); + } + } +} diff --git a/pool/shard009/C++/0109969_GxsChannelUserNotify.cpp b/pool/shard009/C++/0109969_GxsChannelUserNotify.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c20b54b08cec0af1fb65bb9931f337b5056ed69a --- /dev/null +++ b/pool/shard009/C++/0109969_GxsChannelUserNotify.cpp @@ -0,0 +1,51 @@ +/**************************************************************** + * RetroShare is distributed under the following license: + * + * Copyright (C) 2014 RetroShare Team + * + * 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., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + ****************************************************************/ + +#include "GxsChannelUserNotify.h" +#include "gui/MainWindow.h" + +GxsChannelUserNotify::GxsChannelUserNotify(RsGxsIfaceHelper *ifaceImpl, QObject *parent) : + GxsUserNotify(ifaceImpl, parent) +{ +} + +bool GxsChannelUserNotify::hasSetting(QString *name, QString *group) +{ + if (name) *name = tr("Channel Post"); + if (group) *group = "Channel"; + + return true; +} + +QIcon GxsChannelUserNotify::getIcon() +{ + return QIcon(":/icons/png/channels.png"); +} + +QIcon GxsChannelUserNotify::getMainIcon(bool hasNew) +{ + return hasNew ? QIcon(":/icons/png/channels-notify.png") : QIcon(":/icons/png/channels.png"); +} + +void GxsChannelUserNotify::iconClicked() +{ + MainWindow::showWindow(MainWindow::Channels); +} diff --git a/pool/shard009/C++/0109970_SVGAngleInterpolationType.cpp b/pool/shard009/C++/0109970_SVGAngleInterpolationType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a5fefcb5582f5b2e82e00a5dd44366e4a02b50e --- /dev/null +++ b/pool/shard009/C++/0109970_SVGAngleInterpolationType.cpp @@ -0,0 +1,34 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "config.h" +#include "core/animation/SVGAngleInterpolationType.h" + +#include "core/animation/InterpolationEnvironment.h" +#include "core/animation/StringKeyframe.h" +#include "core/svg/SVGAngle.h" + +namespace blink { + +PassOwnPtr SVGAngleInterpolationType::maybeConvertNeutral() const +{ + return InterpolationValue::create(*this, InterpolableNumber::create(0)); +} + +PassOwnPtr SVGAngleInterpolationType::maybeConvertSVGValue(const SVGPropertyBase& svgValue) const +{ + if (toSVGAngle(svgValue).orientType()->enumValue() != SVGMarkerOrientAngle) + return nullptr; + return InterpolationValue::create(*this, InterpolableNumber::create(toSVGAngle(svgValue).value())); +} + +PassRefPtrWillBeRawPtr SVGAngleInterpolationType::appliedSVGValue(const InterpolableValue& interpolableValue, const NonInterpolableValue*) const +{ + double doubleValue = toInterpolableNumber(interpolableValue).value(); + RefPtrWillBeRawPtr result = SVGAngle::create(); + result->newValueSpecifiedUnits(SVGAngle::SVG_ANGLETYPE_DEG, doubleValue); + return result.release(); +} + +} // namespace blink diff --git a/pool/shard009/C++/0109972_group_cipher_delegate.cpp b/pool/shard009/C++/0109972_group_cipher_delegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da6ea77bb8de1fc9c8195718cc695f10edfd87ce --- /dev/null +++ b/pool/shard009/C++/0109972_group_cipher_delegate.cpp @@ -0,0 +1,118 @@ +// +// The MIT License(MIT) +// +// Copyright(c) 2014 Demonsaw LLC +// +// 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 +#include +#include +#include +#include +#include + +#include "component/group/group_security_component.h" +#include "delegate/group/group_cipher_delegate.h" +#include "entity/entity.h" +#include "security/cipher/aes.h" +#include "security/cipher/mars.h" +#include "security/cipher/rc6.h" +#include "security/cipher/serpent.h" +#include "security/cipher/twofish.h" + +Q_DECLARE_METATYPE(eja::entity::ptr); + +namespace eja +{ + // Utility + QWidget* group_cipher_delegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const + { + QComboBox* widget = new QComboBox(parent); + widget->addItem(cipher_name::aes); + widget->addItem(cipher_name::mars); + widget->addItem(cipher_name::rc6); + widget->addItem(cipher_name::serpent); + widget->addItem(cipher_name::twofish); + + return widget; + } + + void group_cipher_delegate::setEditorData(QWidget* editor, const QModelIndex& index) const + { + if (QComboBox* widget = qobject_cast(editor)) + { + const auto data = index.data(Qt::EditRole).toString(); + widget->setCurrentText(data); + } + else + { + QStyledItemDelegate::setEditorData(editor, index); + } + } + + void group_cipher_delegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const + { + if (QComboBox* widget = qobject_cast(editor)) + model->setData(index, widget->currentText(), Qt::EditRole); + else + QStyledItemDelegate::setModelData(editor, model, index); + } + + QSize group_cipher_delegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const + { + // Data + auto variant = index.data(Qt::EditRole); + QString str = variant.toString(); + + // Size + QFontMetrics metrics(option.font); + QRect rect = metrics.boundingRect(str); + rect.setWidth(rect.width() + offset::padding); + + return rect.size(); + } + + void group_cipher_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const + { + QStyledItemDelegate::paint(painter, option, index); + + if (option.state & QStyle::State_Enabled) + { + // Entity + const auto variant = index.data(Qt::DisplayRole); + const auto entity = variant.value(); + if (!entity) + return; + + // Security + const auto security = entity->get(); + const auto name = security->get_cipher(); + + painter->save(); + painter->setRenderHint(QPainter::Antialiasing, true); + + // Name + QRect rect = QRect(option.rect.left(), option.rect.top(), option.rect.width(), option.rect.height()); + painter->drawText(rect, Qt::TextSingleLine | Qt::AlignVCenter, name.c_str()); + + painter->restore(); + } + } +} diff --git a/pool/shard009/C++/0109973_class1.cpp b/pool/shard009/C++/0109973_class1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d01c94b446849b29a3d49576cebabd0c7bdf47d --- /dev/null +++ b/pool/shard009/C++/0109973_class1.cpp @@ -0,0 +1,30 @@ +#include +#include "class.h" + +using namespace std; + +CA::CA() { + a = 0; + cout << "Construction: " << a << endl; +} + +CA::~CA() { + cout << "Destruct: " << a << endl; +} + +void CA::setA(int x) { + a = x; +} + +void CA::print() { + cout << "print: " << a << endl; +} + +int main() +{ + CA ca; + ca.setA(10); + ca.print(); + + return 0; +} diff --git a/pool/shard009/C++/0109975_CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84a.cpp b/pool/shard009/C++/0109975_CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80b4883f15bf0b1c25dde4cd95b9ff1339987c5c --- /dev/null +++ b/pool/shard009/C++/0109975_CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84a.cpp @@ -0,0 +1,95 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84a.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml +Template File: sources-sinks-84a.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: realloc Allocate data using realloc() + * GoodSource: Allocate data using new + * Sinks: + * GoodSink: Deallocate data using free() + * BadSink : Deallocate data using delete + * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use + * + * */ + +#include "std_testcase.h" +#include "CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84 +{ + +#ifndef OMITBAD + +void bad() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_bad * badObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_bad(data); + delete badObject; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_goodG2B * goodG2BObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_goodG2B(data); + delete goodG2BObject; +} + +/* goodG2B uses the BadSource with the GoodSink */ +static void goodB2G() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_goodB2G * goodB2GObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84_goodB2G(data); + delete goodB2GObject; +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_realloc_84; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard009/C++/0109977_rounding.cpp b/pool/shard009/C++/0109977_rounding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ca84af8d51165cd0a7799b6f4bfb0861f9a9cf8 --- /dev/null +++ b/pool/shard009/C++/0109977_rounding.cpp @@ -0,0 +1,95 @@ +/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ +/* + * Main authors: + * Vincent Barichard + * + * Contributing authors: + * Christian Schulte + * + * Copyright: + * Christian Schulte, 2012 + * Vincent Barichard, 2012 + * + * Last modified: + * $Date$ by $Author$ + * $Revision$ + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.org + * + * 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 + +#ifdef GECODE_HAS_MPFR + +#include +#include + +namespace Gecode { namespace Float { + + /// Type signatur of mpfr function + typedef int mpfr_func(mpfr_t, const __mpfr_struct*, mp_rnd_t); + + /// Routine to call mpfr function with proper rounding + forceinline double + invoke_mpfr(FloatNum x, mpfr_func f, mp_rnd_t r) { + mpfr_t xx; + mpfr_init_set_d(xx, x, GMP_RNDN); + f(xx, xx, r); + FloatNum res = mpfr_get_d(xx, r); + mpfr_clear(xx); + return res; + } + + /// Define mpfr functions with proper rounding +#define GECODE_GENR_FUNC(name) \ + FloatNum Rounding::name##_down(FloatNum x) { \ + return invoke_mpfr(x, mpfr_##name, GMP_RNDD); \ + } \ + FloatNum Rounding::name##_up(FloatNum x) { \ + return invoke_mpfr(x, mpfr_##name, GMP_RNDU); \ + } + GECODE_GENR_FUNC(exp) + GECODE_GENR_FUNC(log) + GECODE_GENR_FUNC(sin) + GECODE_GENR_FUNC(cos) + GECODE_GENR_FUNC(tan) + GECODE_GENR_FUNC(asin) + GECODE_GENR_FUNC(acos) + GECODE_GENR_FUNC(atan) + GECODE_GENR_FUNC(sinh) + GECODE_GENR_FUNC(cosh) + GECODE_GENR_FUNC(tanh) + GECODE_GENR_FUNC(asinh) + GECODE_GENR_FUNC(acosh) + GECODE_GENR_FUNC(atanh) + +#undef GECODE_GENR_FUNC + +}} + +#endif + +// STATISTICS: float-var + diff --git a/pool/shard009/C++/0109982_pointer_partial_void.cc b/pool/shard009/C++/0109982_pointer_partial_void.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a4377fb6e47f8bcdcbed87bee4a9bc72aa775a0 --- /dev/null +++ b/pool/shard009/C++/0109982_pointer_partial_void.cc @@ -0,0 +1,69 @@ +// { dg-require-atomic-builtins "" } +// { dg-options "-std=gnu++0x" } + +// Copyright (C) 2012-2013 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library 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 library; see the file COPYING3. If not see +// . + +#include +#include //std::abs +#include + +// pointer arithimetic vs. atomic. +// atomic vs. explicitly specialized w/o operators, like atomic_bool? +int main(void) +{ + using namespace std; + + typedef int value_type; + const size_t n = 2; + value_type value = 42; + value_type* p = &value; + void* vp = p; + ptrdiff_t __attribute__((unused)) dist(0); + + atomic a(vp); + + // operator++ + void* vp2(a); + a++; + void* vp3(a); + dist = reinterpret_cast(vp2) - reinterpret_cast(vp3); + VERIFY ( std::abs(dist) == 1 ); + + // operator-- + void* vp4(a); + a--; + void* vp5(a); + dist = reinterpret_cast(vp4) - reinterpret_cast(vp5); + VERIFY ( std::abs(dist) == 1 ); + + // operator+= + void* vp6(a); + a+=n; + void* vp7(a); + dist = reinterpret_cast(vp6) - reinterpret_cast(vp7); + VERIFY ( std::abs(dist) == n ); + + // operator-= + void* vp8(a); + a-=n; + void* vp9(a); + dist = reinterpret_cast(vp8) - reinterpret_cast(vp9); + VERIFY ( std::abs(dist) == n ); + + return 0; +} diff --git a/pool/shard009/C++/0109985_sample_attach.cc b/pool/shard009/C++/0109985_sample_attach.cc new file mode 100644 index 0000000000000000000000000000000000000000..114990c6b59588f8aa66ff10498aa3574df791e1 --- /dev/null +++ b/pool/shard009/C++/0109985_sample_attach.cc @@ -0,0 +1,243 @@ +//----------------------------------------------------------------------------// +// // +// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation // +// and distributed under the MIT License (MIT). // +// // +// Copyright (c) 2015 Guillaume Blanc // +// // +// 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 "ozz/animation/runtime/skeleton.h" +#include "ozz/animation/runtime/animation.h" +#include "ozz/animation/runtime/sampling_job.h" +#include "ozz/animation/runtime/local_to_model_job.h" + +#include "ozz/base/log.h" + +#include "ozz/base/memory/allocator.h" + +#include "ozz/base/maths/vec_float.h" +#include "ozz/base/maths/simd_math.h" +#include "ozz/base/maths/box.h" +#include "ozz/base/maths/soa_transform.h" + +#include "ozz/options/options.h" + +#include "framework/application.h" +#include "framework/renderer.h" +#include "framework/imgui.h" +#include "framework/utils.h" + +// Skeleton archive can be specified as an option. +OZZ_OPTIONS_DECLARE_STRING( + skeleton, + "Path to the skeleton (ozz archive format).", + "media/alain_skeleton.ozz", + false) + +// Animation archive can be specified as an option. +OZZ_OPTIONS_DECLARE_STRING( + animation, + "Path to the animation (ozz archive format).", + "media/alain_walk.ozz", + false) + +class AttachSampleApplication : public ozz::sample::Application { + public: + AttachSampleApplication() + : cache_(NULL), + attachment_(0), + offset_(-.02f, .03f, .05f) { + } + + protected: + // Updates current animation time. + virtual bool OnUpdate(float _dt) { + // Updates current animation time. + controller_.Update(animation_, _dt); + + // Samples optimized animation at t = animation_time_. + ozz::animation::SamplingJob sampling_job; + sampling_job.animation = &animation_; + sampling_job.cache = cache_; + sampling_job.time = controller_.time(); + sampling_job.output = locals_; + if (!sampling_job.Run()) { + return false; + } + + // Converts from local space to model space matrices. + ozz::animation::LocalToModelJob ltm_job; + ltm_job.skeleton = &skeleton_; + ltm_job.input = locals_; + ltm_job.output = models_; + if (!ltm_job.Run()) { + return false; + } + + return true; + } + + // Samples animation, transforms to model space and renders. + virtual bool OnDisplay(ozz::sample::Renderer* _renderer) { + if (!_renderer->DrawPosture(skeleton_, + models_, + ozz::math::Float4x4::identity())) { + return false; + } + + // Prepares attached object transformation. + // Gets model space transformation of the joint. + const ozz::math::Float4x4& joint = models_[attachment_]; + + // Builds offset transformation matrix. + const ozz::math::SimdFloat4 translation = + ozz::math::simd_float4::Load3PtrU(&offset_.x); + + // Concatenates joint and offset transformations. + const ozz::math::Float4x4 transform = + joint * ozz::math::Float4x4::Translation(translation); + + // Prepare rendering. + const float thickness = .01f; + const float length = .5f; + const ozz::math::Box box(ozz::math::Float3(-thickness, -thickness, -length), + ozz::math::Float3(thickness, thickness, 0.f)); + const ozz::sample::Renderer::Color colors[2] = { + {0xff, 0, 0, 0xff}, {0, 0xff, 0, 0xff}}; + + return _renderer->DrawBoxIm(box, transform, colors); + } + + virtual bool OnInitialize() { + ozz::memory::Allocator* allocator = ozz::memory::default_allocator(); + + // Reading skeleton. + if (!ozz::sample::LoadSkeleton(OPTIONS_skeleton, &skeleton_)) { + return false; + } + + // Reading animation. + if (!ozz::sample::LoadAnimation(OPTIONS_animation, &animation_)) { + return false; + } + + // Allocates runtime buffers. + const int num_joints = skeleton_.num_joints(); + const int num_soa_joints = skeleton_.num_soa_joints(); + locals_ = allocator->AllocateRange(num_soa_joints); + models_ = allocator->AllocateRange(num_joints); + + // Allocates a cache that matches animation requirements. + cache_ = allocator->New(num_joints); + + // Finds the joint where the object should be attached. + for (int i = 0; i < num_joints; i++) { + if (std::strstr(skeleton_.joint_names()[i], "LeftHandMiddle")) { + attachment_ = i; + break; + } + } + + return true; + } + + virtual void OnDestroy() { + ozz::memory::Allocator* allocator = ozz::memory::default_allocator(); + allocator->Deallocate(locals_); + allocator->Deallocate(models_); + allocator->Delete(cache_); + } + + virtual bool OnGui(ozz::sample::ImGui* _im_gui) { + // Exposes animation runtime playback controls. + { + static bool open = true; + ozz::sample::ImGui::OpenClose oc(_im_gui, "Animation control", &open); + if (open) { + controller_.OnGui(animation_, _im_gui); + } + } + + // Exposes selection of the attachment joint. + { + static bool open = true; + ozz::sample::ImGui::OpenClose oc(_im_gui, "Attachment joint", &open); + if (open && skeleton_.num_joints() != 0) { + _im_gui->DoLabel("Select joint:"); + char label[64]; + std::sprintf(label, "%s (%d)", + skeleton_.joint_names()[attachment_], + attachment_); + _im_gui->DoSlider(label, + 0, skeleton_.num_joints() - 1, + &attachment_); + + _im_gui->DoLabel("Attachment offset:"); + sprintf(label, "x: %02f", offset_.x); + _im_gui->DoSlider(label, -1.f, 1.f, &offset_.x); + sprintf(label, "y: %02f", offset_.y); + _im_gui->DoSlider(label, -1.f, 1.f, &offset_.y); + sprintf(label, "z: %02f", offset_.z); + _im_gui->DoSlider(label, -1.f, 1.f, &offset_.z); + } + } + + return true; + } + + virtual void GetSceneBounds(ozz::math::Box* _bound) const { + ozz::sample::ComputePostureBounds(models_, _bound); + } + + private: + + // Playback animation controller. This is a utility class that helps with + // controlling animation playback time. + ozz::sample::PlaybackController controller_; + + // Runtime skeleton. + ozz::animation::Skeleton skeleton_; + + // Runtime animation. + ozz::animation::Animation animation_; + + // Sampling cache. + ozz::animation::SamplingCache* cache_; + + // Buffer of local transforms as sampled from animation_. + ozz::Range locals_; + + // Buffer of model space matrices. + ozz::Range models_; + + // Joint where the object is attached. + int attachment_; + + // Offset, translation of the attached object from the joint. + ozz::math::Float3 offset_; +}; + +int main(int _argc, const char** _argv) { + const char* title = + "Ozz-animation sample: Attachment to animated skeleton joints"; + return AttachSampleApplication().Run(_argc, _argv, "1.0", title); +} diff --git a/pool/shard009/C++/0109986_QXmppInvokable.cpp b/pool/shard009/C++/0109986_QXmppInvokable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e407aa4f3ff41826c06dd3f6e54d030ad91e84e8 --- /dev/null +++ b/pool/shard009/C++/0109986_QXmppInvokable.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2008-2021 The QXmpp developers + * + * Authors: + * Ian Reinhart Geiser + * + * Source: + * https://github.com/qxmpp-project/qxmpp + * + * This file is a part of QXmpp library. + * + * This library 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; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + */ + +#include "QXmppInvokable.h" + +#include +#include +#include +#include + +/// Constructs a QXmppInvokable with the specified \a parent. +/// +/// \param parent + +QXmppInvokable::QXmppInvokable(QObject *parent) + : QObject(parent) +{ +} + +/// Destroys a QXmppInvokable. + +QXmppInvokable::~QXmppInvokable() +{ +} + +QVariant QXmppInvokable::dispatch(const QByteArray &method, const QList &args) +{ + buildMethodHash(); + + if (!m_methodHash.contains(method)) + return QVariant(); + + int idx = m_methodHash[method]; + if (paramTypes(args) != metaObject()->method(idx).parameterTypes()) + return QVariant(); + + const char *typeName = metaObject()->method(idx).typeName(); + int resultType = QMetaType::type(typeName); + + void *result = QMetaType::create(resultType, nullptr); + + QGenericReturnArgument ret(typeName, result); + QList genericArgs; + QList::ConstIterator iter = args.begin(); + while (iter != args.end()) { + const void *data = iter->data(); + const char *name = iter->typeName(); + genericArgs << QGenericArgument(name, data); + ++iter; + } + + if (QMetaObject::invokeMethod(this, method.constData(), ret, + genericArgs.value(0, QGenericArgument()), + genericArgs.value(1, QGenericArgument()), + genericArgs.value(2, QGenericArgument()), + genericArgs.value(3, QGenericArgument()), + genericArgs.value(4, QGenericArgument()), + genericArgs.value(5, QGenericArgument()), + genericArgs.value(6, QGenericArgument()), + genericArgs.value(7, QGenericArgument()), + genericArgs.value(8, QGenericArgument()), + genericArgs.value(9, QGenericArgument()))) { +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + QVariant returnValue(QMetaType(resultType), result); +#else + QVariant returnValue(resultType, result); +#endif + QMetaType::destroy(resultType, result); + return returnValue; + } else { + qDebug("No such method '%s'", method.constData()); + return QVariant(); + } +} + +QList QXmppInvokable::paramTypes(const QList ¶ms) +{ + QList types; + for (const auto &variant : std::as_const(params)) + types << variant.typeName(); + return types; +} + +void QXmppInvokable::buildMethodHash() +{ + QWriteLocker locker(&m_lock); + if (m_methodHash.size() > 0) + return; + + int methodCount = metaObject()->methodCount(); + for (int idx = 0; idx < methodCount; ++idx) { + QByteArray signature = metaObject()->method(idx).methodSignature(); + m_methodHash[signature.left(signature.indexOf('('))] = idx; + // qDebug() << metaObject()->method(idx).parameterTypes(); + } +} + +QStringList QXmppInvokable::interfaces() const +{ + QStringList results; + int methodCount = metaObject()->methodCount(); + for (int idx = 0; idx < methodCount; ++idx) { + if (metaObject()->method(idx).methodType() == QMetaMethod::Slot) { + QByteArray signature = metaObject()->method(idx).methodSignature(); + results << signature.left(signature.indexOf('(')); + } + } + return results; +} diff --git a/pool/shard009/C++/0109988_ckeyboardeventstranslator.cpp b/pool/shard009/C++/0109988_ckeyboardeventstranslator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97ab98449d8a3cc5656d6ac2dedf4f4bd3fad1a1 --- /dev/null +++ b/pool/shard009/C++/0109988_ckeyboardeventstranslator.cpp @@ -0,0 +1,189 @@ +/************************************************************************** +* Copyright (C) 2008 by Paf * +* * +* 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 +#include + +#include "../include/ckeyboardeventstranslator.h" +#include "../include/ctranslationevents.h" +#include "../../dynamicobject/include/dynamicobjectmanager.h" +#include "../../dynamicobject/include/float.h" +#include "../../core/include/cmessagemodule.h" +#include "../../log/include/clogmodule.h" +#include "../include/cinputmouseevents.h" +#include +#include "../../time/include/ctimemodule.h" + +#include "../../config.h" + +using namespace boost; +using namespace Gnoll::Core; +using namespace Gnoll::DynamicObject; +using namespace Gnoll::Time; + + +namespace Gnoll +{ + namespace Input + { + + CKeyboardEventsTranslator::CKeyboardEventsTranslator(): keyUp("KEYBOARD_KEYUP"), keyDown("KEYBOARD_KEYDOWN"), m_lastTimeTriggerCalled(0) + { + + DynamicObjectManager *pom = DynamicObjectManager::getInstancePtr(); + + + /** + * Loading translation map : Keycode -> Action + */ + this->keyboardEventTranslationMap = pom->load("keyboardEventTranslationMap"); + + + /** + * Keyboard config + */ + this->keyboardConfig = pom->load("keyboardConfig"); + + } + + + CKeyboardEventsTranslator::~CKeyboardEventsTranslator() + { + } + + + void CKeyboardEventsTranslator::handle ( shared_ptr message ) + { + /** + * Get the key code + */ + OIS::KeyCode keyCode = message->getData(); + + + /** + * Get the value and convert it to a string + */ + string keyCodeValue = lexical_cast (keyCode); + + + Gnoll::Log::CLogModule::getInstancePtr()->logMessage( "Looking for KeyCode [" + keyCodeValue + "]"); + + /** + * If an action is associated to this key code, an action message is sent + */ + if ( keyboardEventTranslationMap->hasAttribute(keyCodeValue) ) + { + CTimeModule* timeModule = CTimeModule::getInstancePtr(); + + Messages::MessageType messageType = message->getType(); + + if (messageType == keyDown) + { + m_keyPressed[keyCodeValue] = timeModule->getMsecs(); + + if (m_durationKeyPressed.find(keyCodeValue) == m_durationKeyPressed.end()) + { + m_durationKeyPressed[keyCodeValue] = 0; + } + } + else + { + m_durationKeyPressed[keyCodeValue] += timeModule->getMsecs() - m_keyPressed[keyCodeValue]; + m_keyPressed[keyCodeValue] = 0; + } + + } + + } + + + void CKeyboardEventsTranslator::trigger ( shared_ptr _msg ) + { + + Messages::MessageType actionEventType(ACTION_EVENT_TYPE); + CTimeModule* timeModule = CTimeModule::getInstancePtr(); + + shared_ptr defaultKeyboardSensibility = shared_ptr (new Float(1.0f)); + shared_ptr< Gnoll::DynamicObject::Float > keyboardSensibility = keyboardConfig->getAttributeOrDefault("sensibility", defaultKeyboardSensibility); + + unsigned long int now = timeModule->getMsecs(); + unsigned long int period = now - m_lastTimeTriggerCalled; + + + for( map::iterator it = m_durationKeyPressed.begin(); it != m_durationKeyPressed.end(); it++) + { + unsigned long int timePressed = it->second; + + if (m_keyPressed[it->first] != 0) + { + timePressed += now - m_keyPressed[it->first]; + + m_keyPressed[it->first] = now; + } + + + if (timePressed > 0) + { + + float intensity = (float) timePressed / (float) period * (*keyboardSensibility); + + shared_ptr actionList = keyboardEventTranslationMap->getAttribute( it->first ); + typedef list< shared_ptr >::iterator ListIterator; + + /** + * Send all action messages in the list + */ + for (ListIterator itAttrs = actionList->begin(); itAttrs != actionList->end(); itAttrs++) + { + if (shared_ptr actionName = dynamic_pointer_cast(*itAttrs)) + { + ActionEvent actionEvent(*actionName, intensity); + + shared_ptr data (new boost::any(actionEvent) ) ; + shared_ptr actionMessage (new CMessage( actionEventType, data )); + + std::ostringstream tmpString; + + try + { + CMessageModule::getInstancePtr()->getMessageManager()->queueMessage(actionMessage); + tmpString << "Message ajoute ["<< *actionName << "]" << endl; + } + catch(...) + { + tmpString << "Message NON ajoute ["<< *actionName << "]" << " of intensity "; + tmpString << intensity << " => " << timePressed << " / " << period << endl; + } + + Gnoll::Log::CLogModule::getInstancePtr()->logMessage( tmpString.str() ); + + it->second = 0; + } + } + } + } + + m_lastTimeTriggerCalled = now; + } + }; +}; + + + diff --git a/pool/shard009/C++/0109996_CCTiledLayerTestCommon.cpp b/pool/shard009/C++/0109996_CCTiledLayerTestCommon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec2105327900e8395c150853c730745ff92803a6 --- /dev/null +++ b/pool/shard009/C++/0109996_CCTiledLayerTestCommon.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "CCTiledLayerTestCommon.h" + +using namespace WebCore; + +namespace WebKitTests { + +FakeLayerTextureUpdater::Texture::Texture(FakeLayerTextureUpdater* layer, PassOwnPtr texture) + : LayerTextureUpdater::Texture(texture) + , m_layer(layer) +{ +} + +FakeLayerTextureUpdater::Texture::~Texture() +{ +} + +void FakeLayerTextureUpdater::Texture::updateRect(CCResourceProvider* resourceProvider, const IntRect&, const IntRect&) +{ + texture()->acquireBackingTexture(resourceProvider); + m_layer->updateRect(); +} + +void FakeLayerTextureUpdater::Texture::prepareRect(const IntRect&, WebCore::CCRenderingStats&) +{ + m_layer->prepareRect(); +} + +FakeLayerTextureUpdater::FakeLayerTextureUpdater() + : m_prepareCount(0) + , m_updateCount(0) + , m_prepareRectCount(0) +{ +} + +FakeLayerTextureUpdater::~FakeLayerTextureUpdater() +{ +} + +void FakeLayerTextureUpdater::prepareToUpdate(const IntRect& contentRect, const IntSize&, float, float, IntRect& resultingOpaqueRect, CCRenderingStats&) +{ + m_prepareCount++; + m_lastUpdateRect = contentRect; + if (!m_rectToInvalidate.isEmpty()) { + m_layer->invalidateContentRect(m_rectToInvalidate); + m_rectToInvalidate = IntRect(); + m_layer = 0; + } + resultingOpaqueRect = m_opaquePaintRect; +} + +void FakeLayerTextureUpdater::setRectToInvalidate(const IntRect& rect, FakeTiledLayerChromium* layer) +{ + m_rectToInvalidate = rect; + m_layer = layer; +} + +PassOwnPtr FakeLayerTextureUpdater::createTexture(CCPrioritizedTextureManager* manager) +{ + return adoptPtr(new Texture(this, CCPrioritizedTexture::create(manager))); +} + +FakeCCTiledLayerImpl::FakeCCTiledLayerImpl(int id) + : CCTiledLayerImpl(id) +{ +} + +FakeCCTiledLayerImpl::~FakeCCTiledLayerImpl() +{ +} + +FakeTiledLayerChromium::FakeTiledLayerChromium(CCPrioritizedTextureManager* textureManager) + : TiledLayerChromium() + , m_fakeTextureUpdater(adoptRef(new FakeLayerTextureUpdater)) + , m_textureManager(textureManager) +{ + setTileSize(tileSize()); + setTextureFormat(GraphicsContext3D::RGBA); + setBorderTexelOption(CCLayerTilingData::NoBorderTexels); + setIsDrawable(true); // So that we don't get false positives if any of these tests expect to return false from drawsContent() for other reasons. +} + +FakeTiledLayerChromium::~FakeTiledLayerChromium() +{ +} + +void FakeTiledLayerChromium::setNeedsDisplayRect(const FloatRect& rect) +{ + m_lastNeedsDisplayRect = rect; + TiledLayerChromium::setNeedsDisplayRect(rect); +} + +void FakeTiledLayerChromium::update(CCTextureUpdater& updater, const CCOcclusionTracker* occlusion, CCRenderingStats& stats) +{ + updateContentRect(updater, visibleContentRect(), occlusion, stats); +} + +void FakeTiledLayerChromium::setTexturePriorities(const CCPriorityCalculator& calculator) +{ + // Ensure there is always a target render surface available. If none has been + // set (the layer is an orphan for the test), then just set a surface on itself. + bool missingTargetRenderSurface = !renderTarget(); + + if (missingTargetRenderSurface) + createRenderSurface(); + + TiledLayerChromium::setTexturePriorities(calculator); + + if (missingTargetRenderSurface) { + clearRenderSurface(); + setRenderTarget(0); + } +} + +FakeTiledLayerWithScaledBounds::FakeTiledLayerWithScaledBounds(CCPrioritizedTextureManager* textureManager) + : FakeTiledLayerChromium(textureManager) +{ +} + +} // namespace diff --git a/pool/shard009/C++/0110000_Blob.cpp b/pool/shard009/C++/0110000_Blob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a9f922731a6273b06ab333ea406e7ea73c8c222 --- /dev/null +++ b/pool/shard009/C++/0110000_Blob.cpp @@ -0,0 +1,208 @@ +/* +Copyright (c) 2012-2015, Coherent Labs AD +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Coherent UI 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 HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "precompiled.h" + +#include + +namespace Coherent +{ +namespace Blob +{ + const Value* GetNextValue(const Value* value) + { + return reinterpret_cast(reinterpret_cast(value) + value->GetSize()); + } + + template + T& Value::As() + { + return *reinterpret_cast(m_Storage); + } + + template Null& Value::As(); + template Boolean& Value::As(); + template Integer& Value::As(); + template UInteger& Value::As(); + template Number& Value::As(); + template String& Value::As(); + template Array& Value::As(); + template Object& Value::As(); + template Integer64& Value::As(); + template WString& Value::As(); + template Byte& Value::As(); + template UByte& Value::As(); + + template + const T& Value::As() const + { + return *reinterpret_cast(m_Storage); + } + + template const Null& Value::As() const; + template const Boolean& Value::As() const; + template const Integer& Value::As() const; + template const UInteger& Value::As() const; + template const Number& Value::As() const; + template const String& Value::As() const; + template const Array& Value::As() const; + template const Object& Value::As() const; + template const Integer64& Value::As() const; + template const WString& Value::As() const; + template const Byte& Value::As() const; + template const UByte& Value::As() const; + + struct SizeGetter + { + typedef size_t ResultType; + + template + ResultType Invoke(T& value) const + { + return value.GetSizeInBytes(); + } + }; + + size_t Value::GetSize() const + { + return sizeof(AlignedType) + Invoke(SizeGetter()); + } + + Array::ConstIterator::ConstIterator(const Value* value) : m_Value(value) + { + + } + + Array::ConstIterator::~ConstIterator() + { + + } + + const Value& Array::ConstIterator::operator*() const + { + return *m_Value; + } + + const Value* Array::ConstIterator::operator->() const + { + return m_Value; + } + + Array::ConstIterator& Array::ConstIterator::operator++() + { + m_Value = GetNextValue(m_Value); + return *this; + } + + bool Array::ConstIterator::operator==(const ConstIterator& rhs) const + { + return m_Value == rhs.m_Value; + } + + bool Array::ConstIterator::operator!=(const ConstIterator& rhs) const + { + return m_Value != rhs.m_Value; + } + + Array::ConstIterator Array::Begin() const + { + return ConstIterator(reinterpret_cast(m_Storage)); + } + + Array::ConstIterator Array::End() const + { + return ConstIterator(reinterpret_cast(m_Storage + m_Size - 2 * sizeof(AlignedType))); + } + + const Value* Object::EndOfStorage() const + { + return reinterpret_cast(m_Storage + m_Size - 2 * sizeof(AlignedType)); + } + + Object::ConstIterator Object::Begin() const + { + return ConstIterator(reinterpret_cast(m_Storage), EndOfStorage()); + } + + Object::ConstIterator Object::End() const + { + const Value* end = EndOfStorage(); + return ConstIterator(end, end); + } + + + Object::ConstIterator::ConstIterator(const Value* begin, const Value* end) + : m_Value(begin, nullptr) + , m_End(end) + { + if (m_Value.first != m_End) + { + m_Value.second = GetNextValue(m_Value.first); + } + } + + Object::ConstIterator::~ConstIterator() + { + } + + + Object::ConstIterator& Object::ConstIterator::operator++() + { + m_Value.first = GetNextValue(m_Value.second); + if (m_Value.first != m_End) + { + m_Value.second = GetNextValue(m_Value.first); + } + return *this; + } + + const Object::ConstIterator::value_type& Object::ConstIterator::operator*() const + { + return m_Value; + } + + const Object::ConstIterator::value_type* Object::ConstIterator::operator->() const + { + return &m_Value; + } + + bool Object::ConstIterator::operator==(const Object::ConstIterator& rhs) const + { + return m_Value.first == rhs.m_Value.first && m_End == rhs.m_End; + } + + bool Object::ConstIterator::operator!=(const Object::ConstIterator& rhs) const + { + return m_Value.first != rhs.m_Value.first || m_End != rhs.m_End; + } + + + +} +} diff --git a/pool/shard009/C++/0110004_cv_api.cc b/pool/shard009/C++/0110004_cv_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..b0915fd405794d168862294550fb00a28fd60a20 --- /dev/null +++ b/pool/shard009/C++/0110004_cv_api.cc @@ -0,0 +1,172 @@ +/* + * 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. + */ + +/*! + * Copyright (c) 2016 by Contributors + * \file cv_api.h + * \brief C API for opencv + * \author Junyuan Xie + */ +#include +#include +#include +#include +#include "cv_api.h" +#include "../../src/c_api/c_api_common.h" + + +using namespace mxnet; +// http://www.64lines.com/jpeg-width-height +// Gets the JPEG size from the array of data passed to the function, file reference: http://www.obrador.com/essentialjpeg/headerinfo.htm +bool get_jpeg_size(const unsigned char* data, mx_uint data_size, mx_uint *width, mx_uint *height) { + // Check for valid JPEG image + mx_uint i = 0; // Keeps track of the position within the file + if (data[i] == 0xFF && data[i+1] == 0xD8 && data[i+2] == 0xFF && data[i+3] == 0xE0) { + i += 4; + // Check for valid JPEG header (null terminated JFIF) + if (data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' + && data[i+5] == 'F' && data[i+6] == 0x00) { + // Retrieve the block length of the first block since + // the first block will not contain the size of file + uint16_t block_length = data[i] * 256 + data[i+1]; + while (i < data_size) { + i+=block_length; // Increase the file index to get to the next block + if (i >= data_size) return false; // Check to protect against segmentation faults + if (data[i] != 0xFF) return false; // Check that we are truly at the start of another block + if (data[i+1] == 0xC0) { + // 0xFFC0 is the "Start of frame" marker which contains the file size + // The structure of the 0xFFC0 block is quite simple + // [0xFFC0][ushort length][uchar precision][ushort x][ushort y] + *height = data[i+5]*256 + data[i+6]; + *width = data[i+7]*256 + data[i+8]; + return true; + } else { + i+=2; // Skip the block marker + block_length = data[i] * 256 + data[i+1]; // Go to the next block + } + } + return false; // If this point is reached then no size was found + } else { + return false; // Not a valid JFIF string + } + } else { + return false; // Not a valid SOI header + } +} + +bool get_png_size(const unsigned char* data, mx_uint data_size, mx_uint *width, mx_uint *height) { + if (data[0] == 0x89 && data[1] == 0x50 && data[2] ==0x4E && data[3] == 0x47) { + unsigned char const* p = data + 16; + *width = ((p[0]*256 + p[1])*256 + p[2])*256 + p[3]; + p += 4; + *height = ((p[0]*256 + p[1])*256 + p[2])*256 + p[3]; + return true; + } else { + return false; + } +} + +MXNET_DLL int MXCVImdecode(const unsigned char *img, const mx_uint len, + const int flag, NDArrayHandle *out) { + API_BEGIN(); + mx_uint dims[3]; + CHECK_GE(flag, 0) << "flag must be 0 (grayscale) or 1 (colored)."; + dims[2] = flag == 0 ? 1 : 3; + if (get_jpeg_size(img, len, dims+1, dims)) { + } else if (get_png_size(img, len, dims+1, dims)) { + } else { + LOG(FATAL) << "Only supports png and jpg."; + } + NDArray ndout(mxnet::TShape(dims, dims+3), Context::CPU(), true, mshadow::kUint8); + unsigned char *img_cpy = new unsigned char[len]; + memcpy(img_cpy, img, sizeof(unsigned char)*len); + Engine::Get()->PushSync([=](RunContext ctx){ + ndout.CheckAndAlloc(); + cv::Mat buf(1, len, CV_8U, img_cpy); + cv::Mat dst(dims[0], dims[1], flag == 0 ? CV_8U : CV_8UC3, ndout.data().dptr_); +#if (CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION >= 3)) + cv::imdecode(buf, flag | cv::IMREAD_IGNORE_ORIENTATION, &dst); +#else + cv::imdecode(buf, flag, &dst); +#endif + CHECK(!dst.empty()); + delete[] img_cpy; + }, ndout.ctx(), {}, {ndout.var()}); + NDArray *tmp = new NDArray(); + *tmp = ndout; + *out = tmp; + API_END(); +} + + +MXNET_DLL int MXCVResize(NDArrayHandle src, const mx_uint w, const mx_uint h, + const int interpolation, NDArrayHandle *out) { + API_BEGIN(); + NDArray ndsrc = *static_cast(src); + CHECK_EQ(ndsrc.shape().ndim(), 3); + CHECK_EQ(ndsrc.ctx(), Context::CPU()); + CHECK_EQ(ndsrc.dtype(), mshadow::kUint8); + + mx_uint dims[3] = {h, w, ndsrc.shape()[2]}; + NDArray ndout(mxnet::TShape(dims, dims+3), Context::CPU(), true, mshadow::kUint8); + + Engine::Get()->PushSync([=](RunContext ctx){ + ndout.CheckAndAlloc(); + cv::Mat buf(ndsrc.shape()[0], ndsrc.shape()[1], + dims[2] == 3 ? CV_8UC3 : CV_8U, ndsrc.data().dptr_); + cv::Mat dst(h, w, dims[2] == 3 ? CV_8UC3 : CV_8U, ndout.data().dptr_); + cv::resize(buf, dst, cv::Size(w, h), 0, 0, interpolation); + CHECK(!dst.empty()); + }, ndout.ctx(), {ndsrc.var()}, {ndout.var()}); + NDArray *tmp = new NDArray(); + *tmp = ndout; + *out = tmp; + API_END(); +} + +MXNET_DLL int MXCVcopyMakeBorder(NDArrayHandle src, + const int top, + const int bot, + const int left, + const int right, + const int type, + const double value, + NDArrayHandle *out) { + API_BEGIN(); + NDArray ndsrc = *static_cast(src); + CHECK_EQ(ndsrc.shape().ndim(), 3); + CHECK_EQ(ndsrc.ctx(), Context::CPU()); + CHECK_EQ(ndsrc.dtype(), mshadow::kUint8); + + int h = ndsrc.shape()[0], w = ndsrc.shape()[1], c = ndsrc.shape()[2]; + mx_uint dims[3] = {top+h+bot, left+w+right, c}; + NDArray ndout(mxnet::TShape(dims, dims+3), Context::CPU(), true, mshadow::kUint8); + + Engine::Get()->PushSync([=](RunContext ctx){ + ndout.CheckAndAlloc(); + cv::Mat buf(h, w, c == 3 ? CV_8UC3 : CV_8U, ndsrc.data().dptr_); + cv::Mat dst(top+h+bot, left+w+right, c == 3 ? CV_8UC3 : CV_8U, ndout.data().dptr_); + cv::copyMakeBorder(buf, dst, top, bot, left, right, type, cv::Scalar(value)); + CHECK(!dst.empty()); + }, ndout.ctx(), {ndsrc.var()}, {ndout.var()}); + NDArray *tmp = new NDArray(); + *tmp = ndout; + *out = tmp; + API_END(); +} diff --git a/pool/shard009/C++/0110005_gesture_point.cc b/pool/shard009/C++/0110005_gesture_point.cc new file mode 100644 index 0000000000000000000000000000000000000000..31d9e918e2c41c9ac688ce040240e4d57cec05f7 --- /dev/null +++ b/pool/shard009/C++/0110005_gesture_point.cc @@ -0,0 +1,199 @@ +// 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 "ui/base/gestures/gesture_point.h" + +#include + +#include "base/basictypes.h" +#include "ui/base/events/event.h" +#include "ui/base/events/event_constants.h" +#include "ui/base/gestures/gesture_configuration.h" +#include "ui/base/gestures/gesture_types.h" +#include "ui/base/gestures/gesture_util.h" + +namespace ui { + +GesturePoint::GesturePoint() + : first_touch_time_(0.0), + last_touch_time_(0.0), + last_tap_time_(0.0), + velocity_calculator_( + GestureConfiguration::points_buffered_for_velocity()), + point_id_(-1), + touch_id_(-1) { +} + +GesturePoint::~GesturePoint() {} + +void GesturePoint::Reset() { + first_touch_time_ = last_touch_time_ = 0.0; + velocity_calculator_.ClearHistory(); + point_id_ = -1; + clear_enclosing_rectangle(); +} + +void GesturePoint::ResetVelocity() { + velocity_calculator_.ClearHistory(); +} + +void GesturePoint::UpdateValues(const TouchEvent& event) { + const int64 event_timestamp_microseconds = + event.time_stamp().InMicroseconds(); + if (event.type() == ui::ET_TOUCH_MOVED) { + velocity_calculator_.PointSeen(event.location().x(), + event.location().y(), + event_timestamp_microseconds); + } + + last_touch_time_ = event.time_stamp().InSecondsF(); + last_touch_position_ = event.location(); + + if (event.type() == ui::ET_TOUCH_PRESSED) { + first_touch_time_ = last_touch_time_; + first_touch_position_ = event.location(); + velocity_calculator_.ClearHistory(); + velocity_calculator_.PointSeen(event.location().x(), + event.location().y(), + event_timestamp_microseconds); + clear_enclosing_rectangle(); + } + + UpdateEnclosingRectangle(event); +} + +void GesturePoint::UpdateForTap() { + // Update the tap-position and time, and reset every other state. + last_tap_time_ = last_touch_time_; + last_tap_position_ = last_touch_position_; +} + +void GesturePoint::UpdateForScroll() { + // Update the first-touch position and time so that the scroll-delta and + // scroll-velocity can be computed correctly for the next scroll gesture + // event. + first_touch_position_ = last_touch_position_; + first_touch_time_ = last_touch_time_; +} + +bool GesturePoint::IsInClickWindow(const TouchEvent& event) const { + return IsInClickTimeWindow() && IsInsideManhattanSquare(event); +} + +bool GesturePoint::IsInDoubleClickWindow(const TouchEvent& event) const { + return IsInSecondClickTimeWindow() && + IsSecondClickInsideManhattanSquare(event); +} + +bool GesturePoint::IsInScrollWindow(const TouchEvent& event) const { + return event.type() == ui::ET_TOUCH_MOVED && + !IsInsideManhattanSquare(event); +} + +bool GesturePoint::IsInFlickWindow(const TouchEvent& event) { + return IsOverMinFlickSpeed() && + event.type() != ui::ET_TOUCH_CANCELLED; +} + +bool GesturePoint::DidScroll(const TouchEvent& event, int dist) const { + return abs(last_touch_position_.x() - first_touch_position_.x()) > dist || + abs(last_touch_position_.y() - first_touch_position_.y()) > dist; +} + +bool GesturePoint::HasEnoughDataToEstablishRail() const { + int dx = x_delta(); + int dy = y_delta(); + + int delta_squared = dx * dx + dy * dy; + return delta_squared > GestureConfiguration::min_scroll_delta_squared(); +} + +bool GesturePoint::IsInHorizontalRailWindow() const { + int dx = x_delta(); + int dy = y_delta(); + return abs(dx) > GestureConfiguration::rail_start_proportion() * abs(dy); +} + +bool GesturePoint::IsInVerticalRailWindow() const { + int dx = x_delta(); + int dy = y_delta(); + return abs(dy) > GestureConfiguration::rail_start_proportion() * abs(dx); +} + +bool GesturePoint::BreaksHorizontalRail() { + float vx = XVelocity(); + float vy = YVelocity(); + return fabs(vy) > GestureConfiguration::rail_break_proportion() * fabs(vx) + + GestureConfiguration::min_rail_break_velocity(); +} + +bool GesturePoint::BreaksVerticalRail() { + float vx = XVelocity(); + float vy = YVelocity(); + return fabs(vx) > GestureConfiguration::rail_break_proportion() * fabs(vy) + + GestureConfiguration::min_rail_break_velocity(); +} + +bool GesturePoint::IsInClickTimeWindow() const { + double duration = last_touch_time_ - first_touch_time_; + return duration >= + GestureConfiguration::min_touch_down_duration_in_seconds_for_click() && + duration < + GestureConfiguration::max_touch_down_duration_in_seconds_for_click(); +} + +bool GesturePoint::IsInSecondClickTimeWindow() const { + double duration = last_touch_time_ - last_tap_time_; + return duration < GestureConfiguration::max_seconds_between_double_click(); +} + +bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const { + return ui::gestures::IsInsideManhattanSquare(event.location(), + first_touch_position_); +} + +bool GesturePoint::IsSecondClickInsideManhattanSquare( + const TouchEvent& event) const { + int manhattan_distance = abs(event.location().x() - last_tap_position_.x()) + + abs(event.location().y() - last_tap_position_.y()); + return manhattan_distance < + GestureConfiguration::max_distance_between_taps_for_double_tap(); +} + +bool GesturePoint::IsOverMinFlickSpeed() { + return velocity_calculator_.VelocitySquared() > + GestureConfiguration::min_flick_speed_squared(); +} + +void GesturePoint::UpdateEnclosingRectangle(const TouchEvent& event) { + int radius; + + // Ignore this TouchEvent if it has a radius larger than the maximum + // allowed radius size. + if (event.radius_x() > GestureConfiguration::max_radius() || + event.radius_y() > GestureConfiguration::max_radius()) + return; + + // If the device provides at least one of the radius values, take the larger + // of the two and use this as both the x radius and the y radius of the + // touch region. Otherwise use the default radius value. + // TODO(tdanderson): Implement a more specific check for the exact + // information provided by the device (0-2 radii values, force, angle) and + // use this to compute a more representative rectangular touch region. + if (event.radius_x() || event.radius_y()) + radius = std::max(event.radius_x(), event.radius_y()); + else + radius = GestureConfiguration::default_radius(); + + gfx::Rect rect(event.location().x() - radius, + event.location().y() - radius, + radius * 2, + radius * 2); + if (IsInClickWindow(event)) + enclosing_rect_.Union(rect); + else + enclosing_rect_ = rect; +} + +} // namespace ui diff --git a/pool/shard009/C++/0110006_searchMatrix.cc b/pool/shard009/C++/0110006_searchMatrix.cc new file mode 100644 index 0000000000000000000000000000000000000000..066581574e5206157ed7b7811067a03fb35ba556 --- /dev/null +++ b/pool/shard009/C++/0110006_searchMatrix.cc @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + if (matrix.size() == 0 || matrix[0].size() == 0) + return false; + int i = 0, j = matrix.size(), mid; + while (i < j) { + mid = (i+j)/2; + if (matrix[mid][0] > target) + j = mid; + else if (matrix[mid].back() < target) + i = mid+1; + else + return std::binary_search (matrix[mid].begin(), matrix[mid].end(), target); + } + return false; + } +}; + +/* + * input: vector> int ## true|false + */ + +template +istream& operator >> (istream& in, vector& vi) { + T val; + vi.clear(); + while (!in.eof() && isspace(in.peek())) in.get(); + if (in.eof()) return in; + in.get(); + + while (true) { + while (isspace(in.peek())) in.get(); + if (in.peek() == '}') { + in.get(); + return in; + } + else if (in.peek() == ',') in.get(); + in >> val; + vi.push_back(val); + } + + return in; +} + +template +ostream& operator << (ostream& out, vector& vi) { + out << "{"; + if (vi.size() != 0) + out << vi[0]; + for (int i = 1; i < vi.size(); i++) + out << ", " << vi[i]; + out << "}"; + return out; +} + + +int main() { + bool err = false; + string buf; + vector> matrix; + int target; + bool res, expected; + cout.setf(std::ios_base::boolalpha); + + while (true) { + cin >> matrix; + if (cin.eof()) break; + cin >> target >> buf >> buf; + if (buf == "true") + expected = true; + else + expected = false; + res = Solution().searchMatrix(matrix, target); + if (res != expected) { + err = true; + cout << "input: " << matrix << " " << target << endl + << "result: " << res << endl + << "expected: " << expected << endl << endl; + } + } + + if (!err) + cout << "All tests passed!\n"; + + return 0; +} diff --git a/pool/shard009/C++/0110014_basic_string.cpp b/pool/shard009/C++/0110014_basic_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25ec20b502d1d29b01b15fdfca401564f0f68dcc --- /dev/null +++ b/pool/shard009/C++/0110014_basic_string.cpp @@ -0,0 +1,127 @@ +/* + Copyright (c) 2014, Randolph Voorhies, Shane Grant + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of cereal 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 RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "common.hpp" +#include + +template +void test_string_basic() +{ + std::random_device rd; + std::mt19937 gen(rd()); + + for(size_t i=0; i<100; ++i) + { + std::basic_string o_string = random_basic_string(gen); + std::basic_string o_string2 = ""; + + std::ostringstream os; + { + OArchive oar(os); + oar(o_string); + oar(o_string2); + } + + std::basic_string i_string; + std::basic_string i_string2; + + std::istringstream is(os.str()); + { + IArchive iar(is); + + iar(i_string); + iar(i_string2); + } + + BOOST_CHECK_EQUAL(i_string, o_string); + BOOST_CHECK_EQUAL(i_string2, o_string2); + } +} + +template +void test_string_all() +{ + std::random_device rd; + std::mt19937 gen(rd()); + + for(size_t i=0; i<100; ++i) + { + std::basic_string o_string = random_basic_string(gen); + std::basic_string o_wstring = random_basic_string(gen); + std::basic_string o_u16string = random_basic_string(gen); + std::basic_string o_u32string = random_basic_string(gen); + + std::ostringstream os; + { + OArchive oar(os); + oar(o_string); + oar(o_wstring); + oar(o_u16string); + oar(o_u32string); + } + + std::basic_string i_string; + std::basic_string i_wstring; + std::basic_string i_u16string; + std::basic_string i_u32string; + + std::istringstream is(os.str()); + { + IArchive iar(is); + + iar(i_string); + iar(i_wstring); + iar(i_u16string); + iar(i_u32string); + } + + BOOST_CHECK_EQUAL(i_string, o_string); + BOOST_CHECK_EQUAL_COLLECTIONS(i_wstring.begin(), i_wstring.end(), o_wstring.begin(), o_wstring.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(i_u16string.begin(), i_u16string.end(), o_u16string.begin(), o_u16string.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(i_u32string.begin(), i_u32string.end(), o_u32string.begin(), o_u32string.end()); + } +} + +BOOST_AUTO_TEST_CASE( binary_string ) +{ + test_string_all(); +} + +BOOST_AUTO_TEST_CASE( portable_binary_string ) +{ + test_string_all(); +} + +BOOST_AUTO_TEST_CASE( xml_string_basic ) +{ + test_string_basic(); +} + +BOOST_AUTO_TEST_CASE( json_string_basic ) +{ + test_string_basic(); +} + diff --git a/pool/shard009/C++/0110021_BinaryTreePreorderTraversal.cc b/pool/shard009/C++/0110021_BinaryTreePreorderTraversal.cc new file mode 100644 index 0000000000000000000000000000000000000000..af2749ed64af430b2ae01c8ca68f63bd47067a7d --- /dev/null +++ b/pool/shard009/C++/0110021_BinaryTreePreorderTraversal.cc @@ -0,0 +1,31 @@ +// https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ +namespace BinaryTreePreorderTraversal { + class Solution { + public: + vector preorderTraversal(TreeNode *root) { + vector v; + if (root == NULL) { + return v; + } + + stack s; + s.push(root); + while (!s.empty()) { + TreeNode * cur = s.top(); + v.push_back(cur->val); + s.pop(); + if (cur->right) { + s.push(cur->right); + } + + if (cur->left) { + s.push(cur->left); + } + + } + + return v; + + } + }; +} diff --git a/pool/shard009/C++/0110022_BoostUtilities.cpp b/pool/shard009/C++/0110022_BoostUtilities.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c2cf901da23f1b789b77418cfeeacd8620e17ba --- /dev/null +++ b/pool/shard009/C++/0110022_BoostUtilities.cpp @@ -0,0 +1,170 @@ +#include "BoostUtilities.hpp" +#include "BoostConstants.hpp" + +#include "stdlib.h" + +namespace BoostUtilities +{ + QueueSender::QueueSender(const char* queueName) + { + pQueue = new interop_message_queue(boost::interprocess::open_only, queueName); + } + + SharedMemReader::SharedMemReader(const char* name) + { + // The intermediate variables in this function are necessary for some reason. + std::string sharedMemName = BoostConstants::buildSharedMemName(name); + const char* sharedMemChar = sharedMemName.c_str(); + pSharedMem = new boost::interprocess::shared_memory_object(boost::interprocess::open_only, sharedMemChar, boost::interprocess::read_only); + + std::string mutexName = BoostConstants::buildMutexName(name); + const char* mutexChar = mutexName.c_str(); + pMutex = new boost::interprocess::named_sharable_mutex(boost::interprocess::open_only, mutexChar); + } + + ByteBuffer SharedMemReader::fetchData() + { + // The lock will be released when this object goes out of scope + boost::interprocess::sharable_lock myLock(*pMutex); + hasLock = true; + + boost::interprocess::offset_t size; + pSharedMem->get_size(size); + + if (size == 0) + { + // Bail out early because mapped_region will freak out if size is zero. + ByteBuffer empty; + empty.ptr = new char[1]; // Arbitrary valid pointer to an array. We'll be calling delete[] on this later. + empty.size = 0; + return empty; + } + + boost::interprocess::mapped_region region(*pSharedMem, boost::interprocess::read_only); + unsigned char *buffer = new unsigned char[region.get_size()]; + memcpy(buffer, region.get_address(), region.get_size()); + + ByteBuffer buf; + buf.ptr = buffer; + buf.size = region.get_size(); + + hasLock = false; + + return buf; + } + + void SharedMemReader::unlockMutex() + { + if (hasLock) + { + pMutex->unlock_sharable(); + hasLock = false; + } + } + + SharedMemWriter::SharedMemWriter(const char* name, int size) + { + // The intermediate variables in this function are necessary for some reason. + + pMemName = name; + + std::string sharedMemName = BoostConstants::buildSharedMemName(name); + const char* sharedMemChar = sharedMemName.c_str(); + boost::interprocess::shared_memory_object::remove(sharedMemChar); + pSharedMem = new boost::interprocess::shared_memory_object(boost::interprocess::create_only, sharedMemChar, boost::interprocess::read_write); + pSharedMem->truncate(size); + + std::string mutexName = BoostConstants::buildMutexName(name); + const char* mutexChar = mutexName.c_str(); + boost::interprocess::named_sharable_mutex::remove(mutexChar); + pMutex = new boost::interprocess::named_sharable_mutex(boost::interprocess::create_only, mutexChar); + } + + SharedMemWriter::~SharedMemWriter() + { + std::string mutexName = BoostConstants::buildMutexName(pMemName); + const char* mutexChar = mutexName.c_str(); + boost::interprocess::named_sharable_mutex::remove(mutexChar); + boost::interprocess::shared_memory_object::remove(pSharedMem->get_name()); + } + + void SharedMemWriter::writeData(void* address, int size) + { + // The lock will be released when this object goes out of scope, i.e. when this function exits. + boost::interprocess::scoped_lock myLock(*pMutex); + + if (size > 0) + { + boost::interprocess::mapped_region region(*pSharedMem, boost::interprocess::read_write); + std::memcpy(region.get_address(), address, size); + } + } + + RLBotCoreStatus QueueSender::sendMessage(void* message, int messageSize) + { + if (messageSize > pQueue->get_max_msg_size()) + { + return RLBotCoreStatus::MessageLargerThanMax; + } + + bool sent = pQueue->try_send(message, messageSize, 0); + + if (!sent) + { + return RLBotCoreStatus::BufferOverfilled; + } + return RLBotCoreStatus::Success; + } + + SharedByteReader::SharedByteReader(const char* name) + { + // The intermediate variables in this function are necessary for some reason. + std::string sharedMemName = BoostConstants::buildSharedMemName(name); + const char* sharedMemChar = sharedMemName.c_str(); + pSharedMem = new boost::interprocess::shared_memory_object(boost::interprocess::open_only, sharedMemChar, boost::interprocess::read_only); + } + + // This is expected to be very fast and cheap to call because it does not take a lock + // and just reads a single byte from shared memory. Suitable for being called at + // high frequency from multiple processes. + char SharedByteReader::fetchByte() + { + boost::interprocess::offset_t size; + pSharedMem->get_size(size); + + if (size == 0) + { + // Bail out early because mapped_region will freak out if size is zero. + return 0; + } + + boost::interprocess::mapped_region region(*pSharedMem, boost::interprocess::read_only); + return *(char*)(region.get_address()); + } + + SharedByteWriter::SharedByteWriter(const char* name) + { + // The intermediate variables in this function are necessary for some reason. + + pMemName = name; + + std::string sharedMemName = BoostConstants::buildSharedMemName(name); + const char* sharedMemChar = sharedMemName.c_str(); + boost::interprocess::shared_memory_object::remove(sharedMemChar); + pSharedMem = new boost::interprocess::shared_memory_object(boost::interprocess::create_only, sharedMemChar, boost::interprocess::read_write); + pSharedMem->truncate(1); + } + + SharedByteWriter::~SharedByteWriter() + { + boost::interprocess::shared_memory_object::remove(pSharedMem->get_name()); + } + + void SharedByteWriter::writeByte(char data) + { + char dataArr[] = { data }; + boost::interprocess::mapped_region region(*pSharedMem, boost::interprocess::read_write); + std::memcpy(region.get_address(), dataArr, 1); + } + +} diff --git a/pool/shard009/C++/0110026_h264_poc.cc b/pool/shard009/C++/0110026_h264_poc.cc new file mode 100644 index 0000000000000000000000000000000000000000..2934f25d3b79e8595717b95b807234fd0750f5f8 --- /dev/null +++ b/pool/shard009/C++/0110026_h264_poc.cc @@ -0,0 +1,231 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include + +#include "base/logging.h" +#include "base/macros.h" +#include "media/filters/h264_parser.h" +#include "media/video/h264_poc.h" + +namespace media { + +H264POC::H264POC() { + Reset(); +} + +H264POC::~H264POC() { +} + +void H264POC::Reset() { + // It shouldn't be necessary to reset these values, but doing so will improve + // reproducibility for buggy streams. + ref_pic_order_cnt_msb_ = 0; + ref_pic_order_cnt_lsb_ = 0; + prev_frame_num_ = 0; + prev_frame_num_offset_ = 0; +} + +// Check if a slice includes memory management control operation 5, which +// results in some |pic_order_cnt| state being cleared. +static bool HasMMCO5(const media::H264SliceHeader& slice_hdr) { + // Require that the frame actually has memory management control operations. + if (slice_hdr.nal_ref_idc == 0 || + slice_hdr.idr_pic_flag || + !slice_hdr.adaptive_ref_pic_marking_mode_flag) { + return false; + } + + for (size_t i = 0; i < arraysize(slice_hdr.ref_pic_marking); i++) { + int32_t op = slice_hdr.ref_pic_marking[i].memory_mgmnt_control_operation; + if (op == 5) + return true; + + // Stop at the end of the list. + if (op == 0) + return false; + } + + // Should not get here, the list is always zero terminated. + return false; +} + +bool H264POC::ComputePicOrderCnt( + const H264SPS* sps, + const H264SliceHeader& slice_hdr, + int32_t *pic_order_cnt) { + if (slice_hdr.field_pic_flag) { + DLOG(ERROR) << "Interlaced frames are not supported"; + return false; + } + + bool mmco5 = HasMMCO5(slice_hdr); + int32_t max_frame_num = 1 << (sps->log2_max_frame_num_minus4 + 4); + int32_t max_pic_order_cnt_lsb = + 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + + // Check for invalid (including duplicate) |frame_num| values. All cases are + // treated as gaps, which is to say that nothing is done. (Gaps don't affect + // POC computation.) + if (!slice_hdr.idr_pic_flag && + slice_hdr.frame_num != (prev_frame_num_ + 1) % max_frame_num) { + if (!sps->gaps_in_frame_num_value_allowed_flag) + DLOG(WARNING) << "Invalid gap in frame_num"; + } + + // Based on T-REC-H.264 8.2.1, "Decoding process for picture order + // count", available from http://www.itu.int/rec/T-REC-H.264. + // + // Reorganized slightly from spec pseudocode to handle MMCO5 when storing + // state instead of when loading it. + switch (sps->pic_order_cnt_type) { + case 0: { + int32_t prev_pic_order_cnt_msb = ref_pic_order_cnt_msb_; + int32_t prev_pic_order_cnt_lsb = ref_pic_order_cnt_lsb_; + + // For an IDR picture, clear the state. + if (slice_hdr.idr_pic_flag) { + prev_pic_order_cnt_msb = 0; + prev_pic_order_cnt_lsb = 0; + } + + // 8-3. Derive |pic_order_cnt_msb|, accounting for wrapping which is + // detected when |pic_order_cnt_lsb| increases or decreases by at + // least half of its maximum. + int32_t pic_order_cnt_msb; + if ((slice_hdr.pic_order_cnt_lsb < prev_pic_order_cnt_lsb) && + (prev_pic_order_cnt_lsb - slice_hdr.pic_order_cnt_lsb >= + max_pic_order_cnt_lsb / 2)) { + pic_order_cnt_msb = prev_pic_order_cnt_msb + max_pic_order_cnt_lsb; + } else if ((slice_hdr.pic_order_cnt_lsb > prev_pic_order_cnt_lsb) && + (slice_hdr.pic_order_cnt_lsb - prev_pic_order_cnt_lsb > + max_pic_order_cnt_lsb / 2)) { + pic_order_cnt_msb = prev_pic_order_cnt_msb - max_pic_order_cnt_lsb; + } else { + pic_order_cnt_msb = prev_pic_order_cnt_msb; + } + + // 8-4, 8-5. Derive |top_field_order_count| and |bottom_field_order_cnt| + // (assuming no interlacing). + int32_t top_foc = pic_order_cnt_msb + slice_hdr.pic_order_cnt_lsb; + int32_t bottom_foc = top_foc + slice_hdr.delta_pic_order_cnt_bottom; + *pic_order_cnt = std::min(top_foc, bottom_foc); + + // Store state. + prev_frame_num_ = slice_hdr.frame_num; + if (slice_hdr.nal_ref_idc != 0) { + if (mmco5) { + ref_pic_order_cnt_msb_ = 0; + ref_pic_order_cnt_lsb_ = top_foc; + } else { + ref_pic_order_cnt_msb_ = pic_order_cnt_msb; + ref_pic_order_cnt_lsb_ = slice_hdr.pic_order_cnt_lsb; + } + } + + break; + } + + case 1: { + // 8-6. Derive |frame_num_offset|. + int32_t frame_num_offset; + if (slice_hdr.idr_pic_flag) + frame_num_offset = 0; + else if (prev_frame_num_ > slice_hdr.frame_num) + frame_num_offset = prev_frame_num_offset_ + max_frame_num; + else + frame_num_offset = prev_frame_num_offset_; + + // 8-7. Derive |abs_frame_num|. + int32_t abs_frame_num; + if (sps->num_ref_frames_in_pic_order_cnt_cycle != 0) + abs_frame_num = frame_num_offset + slice_hdr.frame_num; + else + abs_frame_num = 0; + + if (slice_hdr.nal_ref_idc == 0 && abs_frame_num > 0) + abs_frame_num--; + + // 8-9. Derive |expected_pic_order_cnt| (the |pic_order_cnt| indicated + // by the cycle described in the SPS). + int32_t expected_pic_order_cnt = 0; + if (abs_frame_num > 0) { + // 8-8. Derive pic_order_cnt_cycle_cnt and + // frame_num_in_pic_order_cnt_cycle. + // Moved inside 8-9 to avoid division when this check is not done. + if (sps->num_ref_frames_in_pic_order_cnt_cycle == 0) { + DLOG(ERROR) << "Invalid num_ref_frames_in_pic_order_cnt_cycle"; + return false; + } + + // H264Parser checks that num_ref_frames_in_pic_order_cnt_cycle < 255. + int32_t pic_order_cnt_cycle_cnt = + (abs_frame_num - 1) / sps->num_ref_frames_in_pic_order_cnt_cycle; + int32_t frame_num_in_pic_order_cnt_cycle = + (abs_frame_num - 1) % sps->num_ref_frames_in_pic_order_cnt_cycle; + + // 8-9 continued. + expected_pic_order_cnt = pic_order_cnt_cycle_cnt * + sps->expected_delta_per_pic_order_cnt_cycle; + for (int32_t i = 0; i <= frame_num_in_pic_order_cnt_cycle; i++) + expected_pic_order_cnt += sps->offset_for_ref_frame[i]; + } + if (slice_hdr.nal_ref_idc == 0) + expected_pic_order_cnt += sps->offset_for_non_ref_pic; + + // 8-10. Derive |top_field_order_cnt| and |bottom_field_order_cnt| + // (assuming no interlacing). + int32_t top_foc = expected_pic_order_cnt + slice_hdr.delta_pic_order_cnt0; + int32_t bottom_foc = top_foc + sps->offset_for_top_to_bottom_field + + slice_hdr.delta_pic_order_cnt1; + *pic_order_cnt = std::min(top_foc, bottom_foc); + + // Store state. + prev_frame_num_ = slice_hdr.frame_num; + prev_frame_num_offset_ = frame_num_offset; + if (mmco5) + prev_frame_num_offset_ = 0; + + break; + } + + case 2: { + // 8-11. Derive |frame_num_offset|. + int32_t frame_num_offset; + if (slice_hdr.idr_pic_flag) + frame_num_offset = 0; + else if (prev_frame_num_ > slice_hdr.frame_num) + frame_num_offset = prev_frame_num_offset_ + max_frame_num; + else + frame_num_offset = prev_frame_num_offset_; + + // 8-12, 8-13. Derive |temp_pic_order_count| (it's always the + // |pic_order_cnt|, regardless of interlacing). + if (slice_hdr.idr_pic_flag) + *pic_order_cnt = 0; + else if (slice_hdr.nal_ref_idc == 0) + *pic_order_cnt = 2 * (frame_num_offset + slice_hdr.frame_num) - 1; + else + *pic_order_cnt = 2 * (frame_num_offset + slice_hdr.frame_num); + + // Store state. + prev_frame_num_ = slice_hdr.frame_num; + prev_frame_num_offset_ = frame_num_offset; + if (mmco5) + prev_frame_num_offset_ = 0; + + break; + } + + default: + DLOG(ERROR) << "Invalid pic_order_cnt_type: " << sps->pic_order_cnt_type; + return false; + } + + return true; +} + +} // namespace media diff --git a/pool/shard009/C++/0110028_brake.cpp b/pool/shard009/C++/0110028_brake.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22fa8665984117f9dd8a531afb8cfa00a505b1eb --- /dev/null +++ b/pool/shard009/C++/0110028_brake.cpp @@ -0,0 +1,27 @@ +#include "commands/brake.hpp" +#include "base/commands_baseclean.hpp" +#include +#include +#include + +namespace retrobotics { +namespace isobot { +namespace commands { +Brake::Brake() + : BaseClean{"Brake"} { + Requires(drive_); +} + +auto Brake::Execute() -> void { + std::pair accel_xy{oi_->accelerometer_->GetX(), oi_->accelerometer_->GetY()}; + std::pair accel_rt{std::hypot(accel_xy.first, accel_xy.second), std::atan2( + accel_xy.second, accel_xy.first) - oi_->accelerometer_angle_}; + std::pair wheels{-std::cos(accel_rt.second) + * (std::signbit(std::sin(accel_rt.first)) ? 1 : -1) * std::min(accel_rt.first, 1.), std::cos( + accel_rt.second) * (std::signbit(std::sin(accel_rt.first)) ? 1 : -1) + * std::min(accel_rt.first, 1.)}; + drive_->set(wheels); +} +} +} +} diff --git a/pool/shard009/C++/0110036_protocol-parameter.cpp b/pool/shard009/C++/0110036_protocol-parameter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0960d14ba0a5d4e59137aa4eede044eb26d18b9 --- /dev/null +++ b/pool/shard009/C++/0110036_protocol-parameter.cpp @@ -0,0 +1,230 @@ +/** + * This file is part of TelepathyQt + * + * @copyright Copyright (C) 2010 Collabora Ltd. + * @copyright Copyright (C) 2010 Nokia Corporation + * @license LGPL 2.1 + * + * This library 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; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "TelepathyQt/debug-internal.h" + +#include + +namespace Tp +{ + +struct TP_QT_NO_EXPORT ProtocolParameter::Private : public QSharedData +{ + Private(const ParamSpec &sp) + : spec(sp), + type(variantTypeFromDBusSignature(spec.signature)) + { + init(); + } + + Private(const QString &name, const QString &dbusSignature, + ConnMgrParamFlags flags, const QVariant &defaultValue) + : type(variantTypeFromDBusSignature(dbusSignature)) + { + spec.name = name; + spec.flags = flags; + spec.signature = dbusSignature; + spec.defaultValue = QDBusVariant(defaultValue); + init(); + } + + void init() + { + if (spec.flags & ConnMgrParamFlagHasDefault) { + if (spec.defaultValue.variant() == QVariant::Invalid) { + // flags contains HasDefault but no default value is passed, + // lets warn and build a default value from signature + warning() << "Building ProtocolParameter with flags containing ConnMgrParamFlagHasDefault" + " and no default value, generating a dummy one from signature"; + spec.defaultValue = QDBusVariant( + parseValueWithDBusSignature(QString(), spec.signature)); + } + } else { + if (spec.defaultValue.variant() != QVariant::Invalid) { + // flags does not contain HasDefault but a default value is passed, + // lets add HasDefault to flags + debug() << "Building ProtocolParameter with flags not containing ConnMgrParamFlagHasDefault" + " and a default value, updating flags to contain ConnMgrParamFlagHasDefault"; + spec.flags |= ConnMgrParamFlagHasDefault; + } + } + } + + ParamSpec spec; + QVariant::Type type; +}; + +/** + * \class ProtocolParameter + * \ingroup clientcm + * \headerfile TelepathyQt/protocol-parameter.h + * + * \brief The ProtocolParameter class represents a Telepathy protocol parameter. + */ + + +ProtocolParameter::ProtocolParameter() +{ +} + +ProtocolParameter::ProtocolParameter(const ParamSpec &spec) + : mPriv(new Private(spec)) +{ +} + +ProtocolParameter::ProtocolParameter(const QString &name, + const QDBusSignature &dbusSignature, + ConnMgrParamFlags flags, + QVariant defaultValue) + : mPriv(new Private(name, dbusSignature.signature(), flags, defaultValue)) +{ +} + +ProtocolParameter::ProtocolParameter(const QString &name, + const QString &dbusSignature, + ConnMgrParamFlags flags, + QVariant defaultValue) + : mPriv(new Private(name, dbusSignature, flags, defaultValue)) +{ +} + +ProtocolParameter::ProtocolParameter(const ProtocolParameter &other) + : mPriv(other.mPriv) +{ +} + +ProtocolParameter::~ProtocolParameter() +{ +} + +ProtocolParameter &ProtocolParameter::operator=(const ProtocolParameter &other) +{ + this->mPriv = other.mPriv; + return *this; +} + +bool ProtocolParameter::operator==(const ProtocolParameter &other) const +{ + if (!isValid() || !other.isValid()) { + if (!isValid() && !other.isValid()) { + return true; + } + return false; + } + + return (mPriv->spec.name == other.name()); +} + +bool ProtocolParameter::operator==(const QString &name) const +{ + if (!isValid()) { + return false; + } + + return (mPriv->spec.name == name); +} + +bool ProtocolParameter::operator<(const Tp::ProtocolParameter& other) const +{ + return mPriv->spec.name < other.name(); +} + +QString ProtocolParameter::name() const +{ + if (!isValid()) { + return QString(); + } + + return mPriv->spec.name; +} + +QDBusSignature ProtocolParameter::dbusSignature() const +{ + if (!isValid()) { + return QDBusSignature(); + } + + return QDBusSignature(mPriv->spec.signature); +} + +QVariant::Type ProtocolParameter::type() const +{ + if (!isValid()) { + return QVariant::Invalid; + } + + return mPriv->type; +} + +QVariant ProtocolParameter::defaultValue() const +{ + if (!isValid()) { + return QVariant(); + } + + return mPriv->spec.defaultValue.variant(); +} + +bool ProtocolParameter::isRequired() const +{ + if (!isValid()) { + return false; + } + + return mPriv->spec.flags & ConnMgrParamFlagRequired; +} + +bool ProtocolParameter::isSecret() const +{ + if (!isValid()) { + return false; + } + + return mPriv->spec.flags & ConnMgrParamFlagSecret; +} + +bool ProtocolParameter::isRequiredForRegistration() const +{ + if (!isValid()) { + return false; + } + + return mPriv->spec.flags & ConnMgrParamFlagRegister; +} + +ParamSpec ProtocolParameter::bareParameter() const +{ + if (!isValid()) { + return ParamSpec(); + } + + return mPriv->spec; +} + +uint qHash(const ProtocolParameter& parameter) +{ + return qHash(parameter.name()); +} + +} // Tp diff --git a/pool/shard009/C++/0110038_AttributeList.cpp b/pool/shard009/C++/0110038_AttributeList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55e9601bf5e5877b0e2ecc0b54ba09be1035d659 --- /dev/null +++ b/pool/shard009/C++/0110038_AttributeList.cpp @@ -0,0 +1,229 @@ +//===--- AttributeList.cpp --------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the AttributeList class implementation +// +//===----------------------------------------------------------------------===// + +#include "clang/Sema/AttributeList.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclTemplate.h" +#include "clang/AST/Expr.h" +#include "clang/Basic/IdentifierTable.h" +#include "clang/Basic/TargetInfo.h" +#include "clang/Sema/SemaInternal.h" +#include "llvm/ADT/SmallString.h" +using namespace clang; + +IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc, + IdentifierInfo *Ident) { + IdentifierLoc *Result = new (Ctx) IdentifierLoc; + Result->Loc = Loc; + Result->Ident = Ident; + return Result; +} + +size_t AttributeList::allocated_size() const { + if (IsAvailability) return AttributeFactory::AvailabilityAllocSize; + else if (IsTypeTagForDatatype) + return AttributeFactory::TypeTagForDatatypeAllocSize; + else if (IsProperty) + return AttributeFactory::PropertyAllocSize; + return (sizeof(AttributeList) + NumArgs * sizeof(ArgsUnion)); +} + +AttributeFactory::AttributeFactory() { + // Go ahead and configure all the inline capacity. This is just a memset. + FreeLists.resize(InlineFreeListsCapacity); +} +AttributeFactory::~AttributeFactory() {} + +static size_t getFreeListIndexForSize(size_t size) { + assert(size >= sizeof(AttributeList)); + assert((size % sizeof(void*)) == 0); + return ((size - sizeof(AttributeList)) / sizeof(void*)); +} + +void *AttributeFactory::allocate(size_t size) { + // Check for a previously reclaimed attribute. + size_t index = getFreeListIndexForSize(size); + if (index < FreeLists.size()) { + if (AttributeList *attr = FreeLists[index]) { + FreeLists[index] = attr->NextInPool; + return attr; + } + } + + // Otherwise, allocate something new. + return Alloc.Allocate(size, alignof(AttributeFactory)); +} + +void AttributeFactory::reclaimPool(AttributeList *cur) { + assert(cur && "reclaiming empty pool!"); + do { + // Read this here, because we're going to overwrite NextInPool + // when we toss 'cur' into the appropriate queue. + AttributeList *next = cur->NextInPool; + + size_t size = cur->allocated_size(); + size_t freeListIndex = getFreeListIndexForSize(size); + + // Expand FreeLists to the appropriate size, if required. + if (freeListIndex >= FreeLists.size()) + FreeLists.resize(freeListIndex+1); + + // Add 'cur' to the appropriate free-list. + cur->NextInPool = FreeLists[freeListIndex]; + FreeLists[freeListIndex] = cur; + + cur = next; + } while (cur); +} + +void AttributePool::takePool(AttributeList *pool) { + assert(pool); + + // Fast path: this pool is empty. + if (!Head) { + Head = pool; + return; + } + + // Reverse the pool onto the current head. This optimizes for the + // pattern of pulling a lot of pools into a single pool. + do { + AttributeList *next = pool->NextInPool; + pool->NextInPool = Head; + Head = pool; + pool = next; + } while (pool); +} + +#include "clang/Sema/AttrParsedAttrKinds.inc" + +static StringRef normalizeAttrName(StringRef AttrName, StringRef ScopeName, + AttributeList::Syntax SyntaxUsed) { + // Normalize the attribute name, __foo__ becomes foo. This is only allowable + // for GNU attributes. + bool IsGNU = SyntaxUsed == AttributeList::AS_GNU || + (SyntaxUsed == AttributeList::AS_CXX11 && ScopeName == "gnu"); + if (IsGNU && AttrName.size() >= 4 && AttrName.startswith("__") && + AttrName.endswith("__")) + AttrName = AttrName.slice(2, AttrName.size() - 2); + + return AttrName; +} + +AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name, + const IdentifierInfo *ScopeName, + Syntax SyntaxUsed) { + StringRef AttrName = Name->getName(); + + SmallString<64> FullName; + if (ScopeName) + FullName += ScopeName->getName(); + + AttrName = normalizeAttrName(AttrName, FullName, SyntaxUsed); + + // Ensure that in the case of C++11 attributes, we look for '::foo' if it is + // unscoped. + if (ScopeName || SyntaxUsed == AS_CXX11) + FullName += "::"; + FullName += AttrName; + + return ::getAttrKind(FullName, SyntaxUsed); +} + +unsigned AttributeList::getAttributeSpellingListIndex() const { + // Both variables will be used in tablegen generated + // attribute spell list index matching code. + StringRef Scope = ScopeName ? ScopeName->getName() : ""; + StringRef Name = normalizeAttrName(AttrName->getName(), Scope, + (AttributeList::Syntax)SyntaxUsed); + +#include "clang/Sema/AttrSpellingListIndex.inc" + +} + +struct ParsedAttrInfo { + unsigned NumArgs : 4; + unsigned OptArgs : 4; + unsigned HasCustomParsing : 1; + unsigned IsTargetSpecific : 1; + unsigned IsType : 1; + unsigned IsStmt : 1; + unsigned IsKnownToGCC : 1; + + bool (*DiagAppertainsToDecl)(Sema &S, const AttributeList &Attr, + const Decl *); + bool (*DiagLangOpts)(Sema &S, const AttributeList &Attr); + bool (*ExistsInTarget)(const TargetInfo &Target); + unsigned (*SpellingIndexToSemanticSpelling)(const AttributeList &Attr); +}; + +namespace { + #include "clang/Sema/AttrParsedAttrImpl.inc" +} + +static const ParsedAttrInfo &getInfo(const AttributeList &A) { + return AttrInfoMap[A.getKind()]; +} + +unsigned AttributeList::getMinArgs() const { + return getInfo(*this).NumArgs; +} + +unsigned AttributeList::getMaxArgs() const { + return getMinArgs() + getInfo(*this).OptArgs; +} + +bool AttributeList::hasCustomParsing() const { + return getInfo(*this).HasCustomParsing; +} + +bool AttributeList::diagnoseAppertainsTo(Sema &S, const Decl *D) const { + return getInfo(*this).DiagAppertainsToDecl(S, *this, D); +} + +bool AttributeList::diagnoseLangOpts(Sema &S) const { + return getInfo(*this).DiagLangOpts(S, *this); +} + +bool AttributeList::isTargetSpecificAttr() const { + return getInfo(*this).IsTargetSpecific; +} + +bool AttributeList::isTypeAttr() const { + return getInfo(*this).IsType; +} + +bool AttributeList::isStmtAttr() const { + return getInfo(*this).IsStmt; +} + +bool AttributeList::existsInTarget(const TargetInfo &Target) const { + return getInfo(*this).ExistsInTarget(Target); +} + +bool AttributeList::isKnownToGCC() const { + return getInfo(*this).IsKnownToGCC; +} + +unsigned AttributeList::getSemanticSpelling() const { + return getInfo(*this).SpellingIndexToSemanticSpelling(*this); +} + +bool AttributeList::hasVariadicArg() const { + // If the attribute has the maximum number of optional arguments, we will + // claim that as being variadic. If we someday get an attribute that + // legitimately bumps up against that maximum, we can use another bit to track + // whether it's truly variadic or not. + return getInfo(*this).OptArgs == 15; +} diff --git a/pool/shard009/C++/0110046_rmsprop_op.cc b/pool/shard009/C++/0110046_rmsprop_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e7960c237fdec4d61ab8cf2663558b7b596d087 --- /dev/null +++ b/pool/shard009/C++/0110046_rmsprop_op.cc @@ -0,0 +1,175 @@ +/* Copyright (c) 2016 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 "paddle/fluid/operators/optimizers/rmsprop_op.h" + +namespace paddle { +namespace operators { + +class RmspropOp : public framework::OperatorWithKernel { + public: + using framework::OperatorWithKernel::OperatorWithKernel; + + void InferShape(framework::InferShapeContext *ctx) const override { + PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true, + platform::errors::NotFound( + "Input(Param) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ( + ctx->HasInput("MeanSquare"), true, + platform::errors::NotFound( + "Input(MeanSquare) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ( + ctx->HasInput("LearningRate"), true, + platform::errors::NotFound( + "Input(LearningRate) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true, + platform::errors::NotFound( + "Input(Grad) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ(ctx->HasInput("Moment"), true, + platform::errors::NotFound( + "Input(Moment) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Param").front(), + framework::proto::VarType::LOD_TENSOR, + platform::errors::InvalidArgument( + "The input var's type in RmspropOp should be " + "LoDTensor, but the received is %s", + ctx->GetInputsVarType("Param").front())); + + PADDLE_ENFORCE_EQ( + ctx->HasOutput("ParamOut"), true, + platform::errors::NotFound( + "Output(param_out) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ( + ctx->HasOutput("MomentOut"), true, + platform::errors::NotFound( + "Output(MomentOut) of RmspropOp should not be null.")); + PADDLE_ENFORCE_EQ( + ctx->HasOutput("MeanSquareOut"), true, + platform::errors::NotFound( + "Output(MeanSquareOut) of RmspropOp should not be null.")); + if (ctx->Attrs().Get("centered")) { + PADDLE_ENFORCE_EQ( + ctx->HasOutput("MeanGradOut"), true, + platform::errors::NotFound( + "Output(MeanGradOut) of RmspropOp should not be null.")); + } + + auto param_dim = ctx->GetInputDim("Param"); + PADDLE_ENFORCE_EQ( + param_dim, ctx->GetInputDim("Grad"), + platform::errors::InvalidArgument( + "Param and grad input of RmspropOp should have the same dimension. " + "But received Param's dim [%s] and Grad's dim [%s].", + param_dim, ctx->GetInputDim("Grad"))); + PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("Moment"), + platform::errors::InvalidArgument( + "Param and Momentum input of RmspropOp " + "should have the same dimension. But received " + "Param's dim [%s] and Moment [%s]", + param_dim, ctx->GetInputDim("Moment"))); + PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("MeanSquare"), + platform::errors::InvalidArgument( + "Param and Momentum input of RmspropOp " + "should have the same dimension. But received " + "Param's dim [%s] and MeanSquare [%s]", + param_dim, ctx->GetInputDim("MeanSquare"))); + + auto lr_dim = ctx->GetInputDim("LearningRate"); + PADDLE_ENFORCE_EQ(framework::product(lr_dim), 1, + platform::errors::InvalidArgument( + "Learning Rate of RmspropOp should be a scalar. But " + "received LearningRate's dim [%s]", + framework::product(lr_dim))); + + ctx->SetOutputDim("ParamOut", param_dim); + ctx->SetOutputDim("MomentOut", param_dim); + ctx->SetOutputDim("MeanSquareOut", param_dim); + if (ctx->Attrs().Get("centered")) { + ctx->SetOutputDim("MeanGradOut", param_dim); + } + } +}; + +class RmspropOpMaker : public framework::OpProtoAndCheckerMaker { + public: + void Make() override { + AddInput("Param", + "(Tensor, default Tensor) " + "Input parameter value that has to be updated."); + AddInput("MeanSquare", + "(Tensor, default Tensor)" + " The mean square value that gets updated."); + AddInput("MeanGrad", + "(Tensor, default Tensor)" + " The moving average of gradient") + .AsDispensable(); + AddInput("LearningRate", + "(Tensor, default Tensor) " + "The learning rate should be a tensor of size 1."); + AddInput("Grad", + "(Tensor, default Tensor) " + "Input gradient of the parameter."); + AddInput("Moment", + "(Tensor, default Tensor) The moment that gets updated."); + + AddOutput("ParamOut", "(Tensor) Output updated parameter value."); + AddOutput("MomentOut", "(Tensor) Output updated moment."); + AddOutput("MeanSquareOut", "(Tensor) Output Mean squared updated value."); + AddOutput("MeanGradOut", + "(Tensor) Output moving average of gradient updated value."); + + AddAttr("epsilon", + "(float, default 1e-10) Constant " + "for numerical stability.") + .SetDefault(1.0e-10f); + AddAttr("decay", + "(float, default 0.9) " + "Discounting factor for coming gradient.") + .SetDefault(0.9f); + AddAttr("momentum", "(float, default 0.0) Constant value.") + .SetDefault(0.0f); + AddAttr("centered", "(bool, default false) use centered rmsprop.") + .SetDefault(false); + AddComment(R"DOC( +Rmsprop Optimizer. + +$$ +MeanSquareOut = decay * MeanSquare + (1 - decay) * Grad * Grad \\ +MomentOut = momentum * Moment + + \frac{LearningRate * Grad}{\sqrt{MeanSquareOut + epsilon}} \\ +ParamOut = Param - MomentOut +$$ + +if centered is true: + +mean_grad = decay * mean_square{t-1} + (1-decay) * gradient +mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 +mom = momentum * mom{t-1} + learning_rate * g_t / + sqrt(mean_square - mean_grad**2 + epsilon) +param -= mom + +The original slides that proposed Rmsprop: Slide 29 of +http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) + +)DOC"); + } +}; +} // namespace operators +} // namespace paddle + +namespace ops = paddle::operators; +REGISTER_OP_WITHOUT_GRADIENT(rmsprop, ops::RmspropOp, ops::RmspropOpMaker); +REGISTER_OP_CPU_KERNEL( + rmsprop, ops::RmspropOpKernel, + ops::RmspropOpKernel); diff --git a/pool/shard009/C++/0110047_ClawHumanView.cpp b/pool/shard009/C++/0110047_ClawHumanView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed8a1694add5ded391d8ef5a90cbdeee898eaac4 --- /dev/null +++ b/pool/shard009/C++/0110047_ClawHumanView.cpp @@ -0,0 +1,133 @@ +#include "ClawHumanView.h" +#include "ClawGameLogic.h" +#include "ActorController.h" +#include "Engine/UserInterface/GameHUD.h" +#include "Engine/Resource/Loaders/XmlLoader.h" + +//--------------------------------------------------------------------------------------------------------------------- +// ClawHumanView +//--------------------------------------------------------------------------------------------------------------------- + +ClawHumanView::ClawHumanView(SDL_Renderer* renderer) + : HumanView(renderer) +{ + RegisterAllDelegates(); + + m_pCamera->SetSize((uint32)g_pApp->GetWindowSize().x, (uint32)g_pApp->GetWindowSize().y); + + Point startingPos = Point(400, 4500); + m_pCamera->VSetPosition(startingPos); + + m_pFreeCameraController.reset(new MovementController(m_pCamera)); + + m_pKeyboardHandler = m_pFreeCameraController; + m_pPointerHandler = m_pFreeCameraController; + m_pTouchHandler = m_pFreeCameraController; + g_pApp->RegisterTouchRecognizers(*m_pFreeCameraController); +} + +ClawHumanView::~ClawHumanView() +{ + RemoveAllDelegates(); +} + +bool ClawHumanView::VOnEvent(SDL_Event& event) +{ + if (HumanView::VOnEvent(event)) + { + return true; + } + + // Handle game specific events + return false; +} + +void ClawHumanView::VOnUpdate(uint32 msDiff) +{ + // Update engine, then game specific stuff + HumanView::VOnUpdate(msDiff); + + // Actor controller has higher priority + if (m_pActorController) + { + m_pActorController->OnUpdate(msDiff); + } + else if (m_pFreeCameraController) + { + m_pFreeCameraController->OnUpdate(msDiff); + } +} + +void ClawHumanView::VOnAttach(uint32 gameViewId, uint32 actorId) +{ + HumanView::VOnAttach(gameViewId, actorId); +} + +void ClawHumanView::VSetControlledActor(uint32 actorId) +{ + m_pControlledActor = static_pointer_cast(m_pScene->FindActor(actorId)); + + if (!m_pControlledActor) + { + LOG_ERROR("Trying to assign control to invalid actor. Id: " + ToStr(actorId)); + return; + } + + HumanView::VSetControlledActor(actorId); + + /*m_pFreeCameraController.reset(new MovementController(m_pCamera)); + m_pKeyboardHandler = m_pFreeCameraController; + m_pPointerHandler = m_pFreeCameraController;*/ + + m_pActorController.reset(new ActorController(m_pControlledActor)); + m_pKeyboardHandler = m_pActorController; + m_pPointerHandler = m_pActorController; + m_pTouchHandler = m_pActorController; + g_pApp->RegisterTouchRecognizers(*m_pActorController); + + m_pCamera->SetTarget(m_pControlledActor); +} + +bool ClawHumanView::VLoadGameDelegate(TiXmlElement* pLevelXmlElem, LevelData* pLevelData) +{ + if (!HumanView::VLoadGameDelegate(pLevelXmlElem, pLevelData)) + { + return false; + } + + if (!m_pHUD->Initialize(g_pApp->GetRenderer(), m_pCamera)) + { + LOG_ERROR("Failed to create in-game HUD"); + return false; + } + + TiXmlElement* pXmlIngameMenuRoot = XmlResourceLoader::LoadAndReturnRootXmlElement("INGAME_MENU.XML"); + assert(pXmlIngameMenuRoot != NULL); + + m_pIngameMenu.reset(new ScreenElementMenu(g_pApp->GetRenderer())); + if (!m_pIngameMenu->Initialize(pXmlIngameMenuRoot)) + { + LOG_ERROR("Failed to create in-game Menu"); + return false; + } + + m_ScreenElements.push_back(m_pHUD); + m_ScreenElements.push_back(m_pIngameMenu); + m_pIngameMenu->VSetVisible(false); + + return true; +} + +//===================================================================================================================== +// ClawHumanView: Private implementations +//===================================================================================================================== + +void ClawHumanView::RegisterAllDelegates() +{ + +} + +void ClawHumanView::RemoveAllDelegates() +{ + +} \ No newline at end of file diff --git a/pool/shard009/C++/0110051_propitem.cpp b/pool/shard009/C++/0110051_propitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5684cba59889e188defd57560bef12c68a21d79 --- /dev/null +++ b/pool/shard009/C++/0110051_propitem.cpp @@ -0,0 +1,64 @@ + +#include "propitem.h" + +PropItem::PropItem(const QString &name, const QVariant &value, PropItem *parent) +{ + itemName = name; + itemValue = value; + parentItem = parent; +} + +PropItem::~PropItem() +{ + qDeleteAll(childItems); +} + +bool PropItem::setData(int column, const QVariant &value) +{ + // We can only edit the right hand column + if (column != 1) return false; + itemValue = value; + return true; +} + +void PropItem::appendChild(PropItem *child) +{ + childItems.append(child); +} + +PropItem *PropItem::child(int row) +{ + return childItems.value(row); +} + +int PropItem::childCount() const +{ + return childItems.count(); +} + +int PropItem::row() const +{ + if (parentItem) + return parentItem->childItems.indexOf(const_cast(this)); + return 0; +} + +int PropItem::columnCount() const +{ + return 2; +} + +PropItem *PropItem::parent() +{ + return parentItem; +} + +QString PropItem::name() const +{ + return itemName; +} + +QVariant PropItem::value() +{ + return itemValue; +} diff --git a/pool/shard009/C++/0110052_test_memory_pool.cpp b/pool/shard009/C++/0110052_test_memory_pool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d210f6c74629b5e511229d0d068ef97fede9ad2 --- /dev/null +++ b/pool/shard009/C++/0110052_test_memory_pool.cpp @@ -0,0 +1,178 @@ +/***************************************************************************** + * Licensed to Qualys, Inc. (QUALYS) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * QUALYS 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. + ****************************************************************************/ + +/** + * @file + * @brief IronBee++ Internals --- Memory Pool Tests + * + * @author Christopher Alfeld + **/ + +#include +#include +#include + +#include "gtest/gtest.h" + +#include + +using namespace std; + +class TestMemoryPool : public ::testing::Test, public IronBee::TestFixture +{ +}; + +class test_callback +{ +public: + test_callback(bool& called_flag) : + m_called_flag(called_flag) + { + // nop + } + + void operator()() + { + m_called_flag = true; + } + +private: + bool& m_called_flag; +}; + +TEST_F(TestMemoryPool, create) +{ + IronBee::MemoryPool m; + + m = IronBee::MemoryPool::create(); + EXPECT_EQ(string("MemoryPool"), m.name()); + m.destroy(); + + EXPECT_NO_THROW(m = IronBee::MemoryPool::create("Hello World")); + EXPECT_EQ(string("Hello World"), m.name()); + + IronBee::MemoryPool m2; + EXPECT_NO_THROW(m2 = IronBee::MemoryPool::create("WorldChild", m)); + EXPECT_EQ(string("WorldChild"), m2.name()); + m2.destroy(); + + EXPECT_NO_THROW(m2 = m.create_subpool()); + EXPECT_EQ(string("SubPool"), m2.name()); + m2.destroy(); + + EXPECT_NO_THROW(m2 = m.create_subpool("WorldChild2")); + EXPECT_EQ(string("WorldChild2"), m2.name()); + m2.destroy(); + m.destroy(); +} + +TEST_F(TestMemoryPool, basic) +{ + IronBee::MemoryPool m = IronBee::MemoryPool::create(); + char* p; + + p = reinterpret_cast(m.alloc(20)); + EXPECT_TRUE(p); + + int* ip = m.allocate(2); + EXPECT_TRUE(ip); + + // With no introspection, testing is limited. + EXPECT_NO_THROW(m.clear()); + EXPECT_NO_THROW(m.destroy()); +} + +TEST_F(TestMemoryPool, callbacks) +{ + bool called_flag = false; + + IronBee::MemoryPool m = IronBee::MemoryPool::create(); + m.register_cleanup(test_callback(called_flag)); + + ASSERT_FALSE(called_flag); + m.clear(); + EXPECT_TRUE(called_flag); + m.destroy(); + EXPECT_TRUE(called_flag); +} + +TEST_F(TestMemoryPool, boolness) +{ + IronBee::MemoryPool singular; + + EXPECT_FALSE(singular); + + ib_mpool_t* ib_memory_pool = reinterpret_cast(1); + IronBee::MemoryPool nonsingular(ib_memory_pool); + + EXPECT_TRUE(nonsingular); +} + +TEST_F(TestMemoryPool, expose_c) +{ + ib_mpool_t* ib_memory_pool = reinterpret_cast(1); + IronBee::MemoryPool m(ib_memory_pool); + + ASSERT_TRUE(m); + EXPECT_EQ(ib_memory_pool, m.ib()); + + const IronBee::MemoryPool& cm = m; + ASSERT_TRUE(cm); + EXPECT_EQ(ib_memory_pool, cm.ib()); +} + +TEST_F(TestMemoryPool, scoped) +{ + bool called_flag = false; + { + IronBee::ScopedMemoryPool scoped; + + IronBee::MemoryPool m = scoped; + EXPECT_TRUE(m); + EXPECT_EQ(string("ScopedMemoryPool"), m.name()); + + m.register_cleanup(test_callback(called_flag)); + } + EXPECT_TRUE(called_flag); + + called_flag = false; + { + IronBee::ScopedMemoryPool scoped("Hello World"); + + IronBee::MemoryPool m = scoped; + EXPECT_TRUE(m); + EXPECT_EQ(string("Hello World"), m.name()); + + m.register_cleanup(test_callback(called_flag)); + } + EXPECT_TRUE(called_flag); +} + +TEST_F(TestMemoryPool, Const) +{ + IronBee::MemoryPool m = IronBee::MemoryPool::create(); + IronBee::ConstMemoryPool cm = m; + + EXPECT_EQ(cm, m); + + IronBee::MemoryPool m2 = IronBee::MemoryPool::remove_const(cm); + + EXPECT_EQ(cm, m2); + EXPECT_EQ(m, m2); + + m.destroy(); +} diff --git a/pool/shard009/C++/0110054_moveable2.cc b/pool/shard009/C++/0110054_moveable2.cc new file mode 100644 index 0000000000000000000000000000000000000000..418e5807963f1745eeafee43713c3de8dac825eb --- /dev/null +++ b/pool/shard009/C++/0110054_moveable2.cc @@ -0,0 +1,102 @@ +// { dg-options "-std=gnu++11" } + +// Copyright (C) 2009-2015 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library 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 library; see the file COPYING3. If not see +// . + +// 25.3.4 [lib.alg.merge] + +#include +#include +#include +#include + +using __gnu_test::test_container; +using __gnu_test::bidirectional_iterator_wrapper; +using __gnu_test::rvalstruct; + +typedef test_container container; + +bool +are_ordered(const rvalstruct& lhs, const rvalstruct& rhs) +{ return lhs < rhs; } + +void +test01() +{ + bool test __attribute__((unused)) = true; + + int array1[]={0,2,4,1,3,5}; + rvalstruct rv_array1[6]; + std::copy(array1, array1 + 6, rv_array1); + container con1(rv_array1, rv_array1 + 6); + std::inplace_merge(con1.begin(), con1.it(3), con1.end(), are_ordered); + VERIFY( rv_array1[0] == 0 && rv_array1[1] == 1 && rv_array1[2] == 2 + && rv_array1[3] == 3 && rv_array1[4] == 4 && rv_array1[5] == 5 ); + + int array2[]={0,2,4,5,1,3}; + rvalstruct rv_array2[6]; + std::copy(array2, array2 + 6, rv_array2); + container con2(rv_array2, rv_array2 + 6); + std::inplace_merge(con2.begin(), con2.it(4), con2.end(), are_ordered); + VERIFY( rv_array2[0] == 0 && rv_array2[1] == 1 && rv_array2[2] == 2 + && rv_array2[3] == 3 && rv_array2[4] == 4 && rv_array2[5] == 5 ); + + int array3[]={1,1,1,2,2,2}; + rvalstruct rv_array3[6]; + std::copy(array3, array3 + 6, rv_array3); + container con3(rv_array3, rv_array3 + 6); + std::inplace_merge(con3.begin(), con3.it(3), con3.end(), are_ordered); + VERIFY( rv_array3[0] == 1 && rv_array3[1] == 1 && rv_array3[2] == 1 + && rv_array3[3] == 2 && rv_array3[4] == 2 && rv_array3[5] == 2 ); + + int array4[]={1,1,1,1,2,2}; + rvalstruct rv_array4[6]; + std::copy(array4, array4 + 6, rv_array4); + container con4(rv_array4, rv_array4 + 6); + std::inplace_merge(con4.begin(), con4.it(4), con4.end(), are_ordered); + VERIFY( rv_array4[0] == 1 && rv_array4[1] == 1 && rv_array4[2] == 1 + && rv_array4[3] == 1 && rv_array4[4] == 2 && rv_array4[5] == 2 ); + + int array5[]={3,3,3,3}; + rvalstruct rv_array5[4]; + std::copy(array5, array5 + 4, rv_array5); + container con5(rv_array5, rv_array5 + 4); + std::inplace_merge(con5.begin(), con5.it(2), con5.end(), are_ordered); + VERIFY( rv_array5[0] == 3 && rv_array5[1] == 3 && rv_array5[2] == 3 + && rv_array5[3] == 3 ); + + int array6[]={3,3,3}; + rvalstruct rv_array6[3]; + std::copy(array6, array6 + 3, rv_array6); + container con6(rv_array6, rv_array6 + 3); + std::inplace_merge(con6.begin(), con6.it(0), con6.end(), are_ordered); + VERIFY( rv_array6[0] == 3 && rv_array6[1] == 3 && rv_array6[2] == 3 ); + + int array7[]={3,3}; + rvalstruct rv_array7[2]; + std::copy(array7, array7 + 2, rv_array7); + container con7(rv_array7, rv_array7 + 2); + std::inplace_merge(con7.begin(), con7.it(2), con7.end(), are_ordered); + VERIFY( rv_array7[0] == 3 && rv_array7[1] == 3 ); +} + +int +main() +{ + test01(); + return 0; +} diff --git a/pool/shard009/C++/0110056_lambdaCaptureReference.cpp b/pool/shard009/C++/0110056_lambdaCaptureReference.cpp new file mode 100644 index 0000000000000000000000000000000000000000..585ca776a03967f4fcba10278be6f86c89948925 --- /dev/null +++ b/pool/shard009/C++/0110056_lambdaCaptureReference.cpp @@ -0,0 +1,28 @@ +// lambdaCaptureReference.cpp + +#include +#include + +std::function makeLambda(int a){ + int local = 2 * a; + auto lam = [&local](int b){ return local + b; }; // 1 + std::cout << "lam(5): "<< lam(5) << std::endl; // 2 + return lam; +} + +int main(){ + + std::cout << std::endl; + + int local = 10; + + auto addLocal = [&local](int b){ return local + b; }; // 3 + + auto add10 = makeLambda(5); + + std::cout << "addLocal(5): " << addLocal(5) << std::endl; // 4 + std::cout << "add10(5): " << add10(5) << std::endl; // 5 + + std::cout << std::endl; + +} diff --git a/pool/shard009/C++/0110060_drvkillu.cpp b/pool/shard009/C++/0110060_drvkillu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a257b573d3a1b5329304d38dfe417b3c3b7073 --- /dev/null +++ b/pool/shard009/C++/0110060_drvkillu.cpp @@ -0,0 +1,214 @@ +/* + drvkillu.cpp : This file is part of pstoedit + Implementation of Kontour output driver. + + Copyright (C) 1993 - 2009 Wolfgang Glunz, wglunz35_AT_pstoedit.net + Copyright (C) 1998,1999 Kai-Uwe Sattler, kus_AT_iti.cs.uni-magdeburg.de + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. + +*/ +#include "drvkillu.h" +#include I_fstream +#include I_stdio +#include I_stdlib +#include + + + +drvKontour::derivedConstructor(drvKontour):constructBase +{ +// driver specific initializations +// and writing of header to output file + +// +// +// + + + outf << "\n" + << "\n"; + + outf << "\n" << + "\n" + << "\n"; +} + +drvKontour::~drvKontour() +{ + // driver specific deallocations + // and writing of trailer to output file + outf << "\n"; + options=0; +} + +void drvKontour::print_coords() +{ + for (unsigned int n = 0; n < numberOfElementsInPath(); n++) { + const basedrawingelement & elem = pathElement(n); + switch (elem.getType()) { + case moveto:{ + const Point & p = elem.getPoint(0); + outf << "\n"; + } + break; + case lineto:{ + const Point & p = elem.getPoint(0); + outf << "\n"; + } + break; + case closepath: + break; + case curveto:{ + for (unsigned int cp = 0; cp < 3; cp++) { + const Point & p = elem.getPoint(cp); + outf << "\n"; + } + } + break; + default: + errf << "\t\tFatal: unexpected case in drvKontour " << endl; + abort(); + break; + } + } +} + + +void drvKontour::open_page() +{ +} + +void drvKontour::close_page() +{ +} + +void drvKontour::show_text(const TextInfo & textinfo) +{ + static const float toRad = 3.14159265359f / 180.0f; + const double angle = (360.0 - textinfo.currentFontAngle) * toRad; + const double cosa = cos(angle); + const double sina = sin(angle); + outf << "\n"; + outf << "\n"; + + const char *c = textinfo.thetext.value(); + while (*c != '\0') { + if (*c == '<') + outf << "<"; + else if (*c == '&') + outf << "&"; + else if (*c == '>') + outf << ">"; + else + outf << *c; + c++; + } + outf << "\n"; +} + +void drvKontour::show_path() +{ + if (isPolygon()) + outf << "\n"; + print_coords(); + if (isPolygon()) + outf << "\n"; + else + outf << "\n"; +} + +void drvKontour::show_rectangle(const float llx, const float lly, + const float urx, const float ury) +{ + outf << "" << endl; +} + +int drvKontour::cvtColor(float c) +{ + return int ((c * 255.0) + 0.5); +} + +static DriverDescriptionT < drvKontour > D_Kontour("kil", ".kil format for Kontour", "","kil", false, // backend supports subpathes + // if subpathes are supported, the backend must deal with + // sequences of the following form + // moveto (start of subpath) + // lineto (a line segment) + // lineto + // moveto (start of a new subpath) + // lineto (a line segment) + // lineto + // + // If this argument is set to false each subpath is drawn + // individually which might not necessarily represent + // the original drawing. + false, // backend supports curves + false, // backend supports elements which are filled and have edges + true, // backend supports text + DriverDescription::noimage, // no support for PNG file images + DriverDescription::normalopen, false, // if format supports multiple pages in one file + false + /*clipping */ + ); diff --git a/pool/shard009/C++/0110061_test_api_observer_registry.cc b/pool/shard009/C++/0110061_test_api_observer_registry.cc new file mode 100644 index 0000000000000000000000000000000000000000..fdb6209089573128f6eb759f2ad26c5cb8919723 --- /dev/null +++ b/pool/shard009/C++/0110061_test_api_observer_registry.cc @@ -0,0 +1,60 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/api/test/test_api_observer_registry.h" + +#include + +#include "base/check.h" +#include "base/no_destructor.h" + +namespace extensions { + +TestApiObserverRegistry::TestApiObserverRegistry() = default; +TestApiObserverRegistry::~TestApiObserverRegistry() = default; + +// static +TestApiObserverRegistry* TestApiObserverRegistry::GetInstance() { + static base::NoDestructor registry; + return registry.get(); +} + +void TestApiObserverRegistry::NotifyTestPassed( + content::BrowserContext* browser_context) { + for (auto& observer : observers_) { + observer.OnTestPassed(browser_context); + } +} + +void TestApiObserverRegistry::NotifyTestFailed( + content::BrowserContext* browser_context, + const std::string& message) { + for (auto& observer : observers_) { + observer.OnTestFailed(browser_context, message); + } +} + +bool TestApiObserverRegistry::NotifyTestMessage( + TestSendMessageFunction* function, + const std::string& message) { + bool any_listener_will_respond = false; + for (auto& observer : observers_) { + bool listener_will_respond = observer.OnTestMessage(function, message); + DCHECK(!any_listener_will_respond || !listener_will_respond) + << "Only one listener may reply."; + any_listener_will_respond = + any_listener_will_respond || listener_will_respond; + } + return any_listener_will_respond; +} + +void TestApiObserverRegistry::AddObserver(TestApiObserver* observer) { + observers_.AddObserver(observer); +} + +void TestApiObserverRegistry::RemoveObserver(TestApiObserver* observer) { + observers_.RemoveObserver(observer); +} + +} // namespace extensions diff --git a/pool/shard009/C++/0110064_main.cpp b/pool/shard009/C++/0110064_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68b218f51809f341863ceee8ef7b20d2956a2763 --- /dev/null +++ b/pool/shard009/C++/0110064_main.cpp @@ -0,0 +1,51 @@ +#include "main.h" +#include "AppDelegate.h" +#include "cocos2d.h" + +#include +#include +#include + +using namespace cocos2d; + +int APIENTRY _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) +{ + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + + // set current working directory to executable's path + { + // get to path to the exe + TCHAR exePath[MAX_PATH]; + GetModuleFileName(NULL, exePath, MAX_PATH); + + // terminate the string at the end of the path + TCHAR* trailingSlash = wcsrchr(exePath, '\\'); + if(trailingSlash) + *trailingSlash = NULL; + + // switch to the directory of the exe + SetCurrentDirectory(exePath); + } + + bool fullscreen = false; + #ifdef NDEBUG + fullscreen = false; + #endif + + // create the application instance + AppDelegate app; + + // set the view + GLView* view = nullptr; + if (fullscreen) + view = GLViewImpl::createWithFullScreen("TwoScene"); + else + view = GLViewImpl::createWithRect("TwoScene", Rect(0, 0, 1024, 768)); + Director::getInstance()->setOpenGLView(view); + + return Application::getInstance()->run(); +} diff --git a/pool/shard009/C++/0110065_SampleRooFitMgr.cc b/pool/shard009/C++/0110065_SampleRooFitMgr.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfc5218a805bd9201c895936064e34a2e576994f --- /dev/null +++ b/pool/shard009/C++/0110065_SampleRooFitMgr.cc @@ -0,0 +1,109 @@ +/******************************************************************************* +* +* Filename : SampleRooFitMgr.cc +* Description : implementation of roofit manager class +* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] +* +*******************************************************************************/ +#include "TstarAnalysis/Common/interface/InitSample.hpp" +#include "TstarAnalysis/LimitCalc/interface/SampleRooFitMgr.hpp" +#include + +#include "RooDataSet.h" + +using namespace std; +using namespace mgr; + +/******************************************************************************* +* Static member function +*******************************************************************************/ +RooRealVar& +SampleRooFitMgr::x(){ return *StaticVar( "x" ); } + +/******************************************************************************/ + +RooRealVar& +SampleRooFitMgr::w(){ return *StaticVar( "w" ); } + +/******************************************************************************/ + +double +SampleRooFitMgr::MinMass(){ return x().getMin(); } + +/******************************************************************************/ + +double +SampleRooFitMgr::MaxMass(){ return x().getMax(); } + +/******************************************************************************/ + +void +SampleRooFitMgr::InitStaticVars( const double min, const double max ) +{ + StaticNewVar( "x", "m_{t+jet}", "GeV/c^{2}", min, max ); + StaticNewVar( "w", "event_weight", "", -1000, 1000 ); +} + +/******************************************************************************* +* Constructor and destructor +*******************************************************************************/ +SampleRooFitMgr::SampleRooFitMgr( const string& name, const ConfigReader& cfg ) : + Named( name ), + SampleGroup( name, cfg ), + RooFitMgr( name ) +{ + definesets(); + + for( auto& sample : SampleList() ){ + // Caching sample wide variable (weight sums.. etc), see Common/src/InitSample.cc + InitSampleFromEDM( sample ); + + // Fitting the defined dataset, see LimitCalc/src/SampleRooFitMgr_FillSet.cc + fillsets( sample ); + } +} + +/******************************************************************************/ + +SampleRooFitMgr::~SampleRooFitMgr() +{ + // for( const auto& name : VarNameList() ){ + // RooRealVar* var = Var( name ); + // printf( "%-50s %8.4lf %8.4f %8.4f\n", var->GetName(), var->getVal(), var->getErrorHi(), var->getErrorLo() ); + // fflush( stdout ); + // } + + // for( const auto& name : FuncNameList() ){ + // RooAbsReal* func = Func( name ); + // printf( "%50s %8.1lf\n", func->GetName(), func->getVal() ); + // fflush( stdout ); + // } +} + + +/******************************************************************************* +* RooAbsData argument options +*******************************************************************************/ +RooAbsData* +SampleRooFitMgr::NewDataSet( const std::string& name ) +{ + if( DataSet( name ) ){ + return DataSet( name ); + } else { + RooDataSet* set = new RooDataSet(// Using unbinned RooDataSet object + name.c_str(), "", + RooArgSet( x(), w() ), + RooFit::WeightVar( w() ) + ); + AddDataSet( set ); + return set; + } +} + +/******************************************************************************/ + +RooAbsData* +SampleRooFitMgr::DataSet( const std::string& name ) +{ + return RooFitMgr::DataSet( name ); +} diff --git a/pool/shard009/C++/0110078_guide_algorithm_lowpass.cpp b/pool/shard009/C++/0110078_guide_algorithm_lowpass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d217c8a7825d854d03e2849f3f7dbbd305368c7 --- /dev/null +++ b/pool/shard009/C++/0110078_guide_algorithm_lowpass.cpp @@ -0,0 +1,294 @@ +/* +* guide_algorithm_lowpass.cpp +* PHD Guiding +* +* Created by Bret McKee +* Copyright (c) 2012 Bret McKee +* All rights reserved. +* +* Based upon work by Craig Stark. +* Copyright (c) 2006-2010 Craig Stark. +* All rights reserved. +* +* This source code is distributed under the following "BSD" license +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, +* this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* Neither the name of Bret McKee, Dad Dog Development, +* Craig Stark, Stark Labs 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 HOLDER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* +*/ + +#include "phd.h" + +static const double DefaultMinMove = 0.2; +static const double DefaultSlopeWeight = 5.0; + +GuideAlgorithmLowpass::GuideAlgorithmLowpass(Mount *pMount, GuideAxis axis) + : GuideAlgorithm(pMount, axis) +{ + double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); + SetMinMove(minMove); + + double slopeWeight = pConfig->Profile.GetDouble(GetConfigPath() + "/SlopeWeight", DefaultSlopeWeight); + SetSlopeWeight(slopeWeight); + + reset(); +} + +GuideAlgorithmLowpass::~GuideAlgorithmLowpass(void) +{ +} + +GUIDE_ALGORITHM GuideAlgorithmLowpass::Algorithm(void) +{ + return GUIDE_ALGORITHM_LOWPASS; +} + +void GuideAlgorithmLowpass::reset(void) +{ + m_history.Empty(); + + while (m_history.GetCount() < HISTORY_SIZE) + { + m_history.Add(0.0); + } +} + +double GuideAlgorithmLowpass::result(double input) +{ + m_history.Add(input); + + ArrayOfDbl sortedHistory(m_history); + sortedHistory.Sort(dbl_sort_func); + + m_history.RemoveAt(0); + unsigned int numpts = m_history.GetCount(); + + double median = sortedHistory[sortedHistory.GetCount()/2]; + double slope = CalcSlope(m_history); + double dReturn = median + m_slopeWeight*slope; + + if (fabs(dReturn) > fabs(input)) + { + Debug.Write(wxString::Format("GuideAlgorithmLowpass::Result() input %.2f is < calculated value %.2f, using input\n", input, dReturn)); + dReturn = input; + } + + //TODO: Undertand this. I think this is wrong, since it divides the orignial input + // by 11 if it was less than the computed value. And since the computed + // value is median + slope, I'm not sure that it should be divided by 11 + // either. But the goal of this exercise is to be bug for bug compatible + // with PHD 1.x + + if (fabs(input) < m_minMove) + { + dReturn = 0.0; + } + else + { + // Look for a direction reversal - possibly due to backlash comp + if (numpts > 2 && (m_history[numpts - 2] * m_history[numpts - 1] < 0)) + m_pMount->FlagBacklashOverShoot(fabs(input) - m_minMove, m_guideAxis); + } + + Debug.Write(wxString::Format("GuideAlgorithmLowpass::Result() returns %.2f from input %.2f\n", dReturn, input)); + + return dReturn; +} + +double GuideAlgorithmLowpass::GetMinMove(void) +{ + return m_minMove; +} + +bool GuideAlgorithmLowpass::SetMinMove(double minMove) +{ + bool bError = false; + + try + { + if (minMove < 0) + { + throw ERROR_INFO("invalid minMove"); + } + + m_minMove = minMove; + + } + catch (wxString Msg) + { + POSSIBLY_UNUSED(Msg); + bError = true; + m_minMove = DefaultMinMove; + } + + pConfig->Profile.SetDouble(GetConfigPath() + "/minMove", m_minMove); + + return bError; +} + +double GuideAlgorithmLowpass::GetSlopeWeight(void) +{ + return m_slopeWeight; +} + +bool GuideAlgorithmLowpass::SetSlopeWeight(double slopeWeight) +{ + bool bError = false; + + try + { + if (slopeWeight < 0.0) + { + throw ERROR_INFO("invalid slopeWeight"); + } + + m_slopeWeight = slopeWeight; + } + catch (wxString Msg) + { + POSSIBLY_UNUSED(Msg); + bError = true; + m_slopeWeight = DefaultSlopeWeight; + } + + pConfig->Profile.SetDouble(GetConfigPath() + "/SlopeWeight", m_slopeWeight); + + return bError; +} + +wxString GuideAlgorithmLowpass::GetSettingsSummary() +{ + // return a loggable summary of current mount settings + return wxString::Format("Slope weight = %.3f, Minimum move = %.3f\n", + GetSlopeWeight(), + GetMinMove() + ); +} + +ConfigDialogPane *GuideAlgorithmLowpass::GetConfigDialogPane(wxWindow *pParent) +{ + return new GuideAlgorithmLowpassConfigDialogPane(pParent, this); +} + +GuideAlgorithmLowpass:: + GuideAlgorithmLowpassConfigDialogPane:: + GuideAlgorithmLowpassConfigDialogPane(wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm) + : ConfigDialogPane(_("Lowpass Guide Algorithm"), pParent) +{ + int width; + + m_pGuideAlgorithm = pGuideAlgorithm; + + width = StringWidth(_T("000.00")); + m_pSlopeWeight = new wxSpinCtrlDouble(pParent, wxID_ANY,_T("foo2"), wxPoint(-1,-1), + wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5,_T("SlopeWeight")); + m_pSlopeWeight->SetDigits(2); + + DoAdd(_("Slope Weight"), m_pSlopeWeight, + _("Weighting of slope parameter in lowpass auto-dec")); + + width = StringWidth(_T("000.00")); + m_pMinMove = new wxSpinCtrlDouble(pParent, wxID_ANY,_T("foo2"), wxPoint(-1,-1), + wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05,_T("MinMove")); + m_pMinMove->SetDigits(2); + + DoAdd(_("Minimum Move (pixels)"), m_pMinMove, + _("How many (fractional) pixels must the star move to trigger a guide pulse? Default = 0.15")); + +} + +GuideAlgorithmLowpass:: + GuideAlgorithmLowpassConfigDialogPane:: + ~GuideAlgorithmLowpassConfigDialogPane(void) +{ +} + +void GuideAlgorithmLowpass:: + GuideAlgorithmLowpassConfigDialogPane:: + LoadValues(void) +{ + m_pSlopeWeight->SetValue(m_pGuideAlgorithm->GetSlopeWeight()); + m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); +} + +void GuideAlgorithmLowpass:: + GuideAlgorithmLowpassConfigDialogPane:: + UnloadValues(void) +{ + m_pGuideAlgorithm->SetSlopeWeight(m_pSlopeWeight->GetValue()); + m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); +} + +GraphControlPane *GuideAlgorithmLowpass::GetGraphControlPane(wxWindow *pParent, const wxString& label) +{ + return new GuideAlgorithmLowpassGraphControlPane(pParent, this, label); +} + +GuideAlgorithmLowpass:: + GuideAlgorithmLowpassGraphControlPane:: + GuideAlgorithmLowpassGraphControlPane(wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm, const wxString& label) + : GraphControlPane(pParent, label) +{ + int width; + + m_pGuideAlgorithm = pGuideAlgorithm; + + width = StringWidth(_T("000.00")); + m_pSlopeWeight = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5,_T("SlopeWeight")); + m_pSlopeWeight->SetDigits(2); + m_pSlopeWeight->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnSlopeWeightSpinCtrlDouble, this); + DoAdd(m_pSlopeWeight, _("Sl W")); + + width = StringWidth(_T("000.00")); + m_pMinMove = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width+30, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05,_T("MinMove")); + m_pMinMove->SetDigits(2); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnMinMoveSpinCtrlDouble, this); + DoAdd(m_pMinMove, _("MnMo")); + + m_pSlopeWeight->SetValue(m_pGuideAlgorithm->GetSlopeWeight()); + m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); +} + +GuideAlgorithmLowpass:: + GuideAlgorithmLowpassGraphControlPane:: + ~GuideAlgorithmLowpassGraphControlPane(void) +{ +} + +void GuideAlgorithmLowpass:: + GuideAlgorithmLowpassGraphControlPane:: + OnSlopeWeightSpinCtrlDouble(wxSpinDoubleEvent& evt) +{ + m_pGuideAlgorithm->SetSlopeWeight(m_pSlopeWeight->GetValue()); + GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass slope weight", m_pSlopeWeight->GetValue()); +} + +void GuideAlgorithmLowpass:: + GuideAlgorithmLowpassGraphControlPane:: + OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) +{ + m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); + GuideLog.SetGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass minimum move", m_pMinMove->GetValue()); +} diff --git a/pool/shard009/C++/0110079_MetadataParser.cpp b/pool/shard009/C++/0110079_MetadataParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b91f15863f085557bd01a8486ee05b592f1c8d33 --- /dev/null +++ b/pool/shard009/C++/0110079_MetadataParser.cpp @@ -0,0 +1,36 @@ +#if defined(ENABLE_METADATAPARSER) + +#include "MetadataParser.h" +#include "Trace.h" +#include + +unsigned int MetadataParser::num = 0; +MetadataParser::registry_t MetadataParser::registry; + +MetadataParser::MetadataParser(const string _parsekey) : parsekey(_parsekey) +{ + Pair ret; + + ret = registry.insert(make_pair(parsekey, this)); + + if (!ret.second) { + HAGGLE_ERR("Parser with given name '%s' already registered", parsekey.c_str()); + return; + } + + HAGGLE_DBG("Registered metadata parser with key \'%s\'\n", parsekey.c_str()); +} + +MetadataParser::~MetadataParser() +{ + HAGGLE_DBG("Unregistered metadata parser with key \'%s\'\n", parsekey.c_str()); + registry.erase(parsekey); +} + +MetadataParser *MetadataParser::getParser(string& key) +{ + registry_t::iterator it = registry.find(key); + return (it == registry.end() ? NULL : (*it).second); +} + +#endif /* ENABLE_METADATAPARSER */ diff --git a/pool/shard009/C++/0110086_TestThriftCpp.cpp b/pool/shard009/C++/0110086_TestThriftCpp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc291d6574376da96341ed3afc45280bdaf8d09e --- /dev/null +++ b/pool/shard009/C++/0110086_TestThriftCpp.cpp @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "../gen-cpp/ThriftNeptuneService.h" + +using namespace std; +using namespace apache::thrift; +using namespace apache::thrift::protocol; +using namespace apache::thrift::transport; + +using namespace neptune; +using namespace boost; + +int main(int argc, char** argv) { + if(argc < 3) { + printf("Usage: TestThriftCpp \n"); + printf(" TestThriftCpp localhost 7002\n"); + return 0; + } + shared_ptr socket(new TSocket(argv[1], atoi(argv[2]))); + shared_ptr transport(new TBufferedTransport(socket)); + shared_ptr protocol(new TBinaryProtocol(transport)); + ThriftNeptuneServiceClient client(protocol); + + try { + transport->open(); + + ThriftTableSchema schema; + client.descTable(schema, "META"); + printf("Test OK\n"); + printf("TableName: %s\n", schema.tableName.c_str()); + transport->close(); + } catch (TException &tx) { + printf("ERROR: %s\n", tx.what()); + } +} \ No newline at end of file diff --git a/pool/shard009/C++/0110087_PrefixLevelStorageMetrics.cpp b/pool/shard009/C++/0110087_PrefixLevelStorageMetrics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa40ae7070e80960ba6be5aa533423b2e54e2b6d --- /dev/null +++ b/pool/shard009/C++/0110087_PrefixLevelStorageMetrics.cpp @@ -0,0 +1,82 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +#include + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace S3Control +{ +namespace Model +{ + +PrefixLevelStorageMetrics::PrefixLevelStorageMetrics() : + m_isEnabled(false), + m_isEnabledHasBeenSet(false), + m_selectionCriteriaHasBeenSet(false) +{ +} + +PrefixLevelStorageMetrics::PrefixLevelStorageMetrics(const XmlNode& xmlNode) : + m_isEnabled(false), + m_isEnabledHasBeenSet(false), + m_selectionCriteriaHasBeenSet(false) +{ + *this = xmlNode; +} + +PrefixLevelStorageMetrics& PrefixLevelStorageMetrics::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode isEnabledNode = resultNode.FirstChild("IsEnabled"); + if(!isEnabledNode.IsNull()) + { + m_isEnabled = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(isEnabledNode.GetText()).c_str()).c_str()); + m_isEnabledHasBeenSet = true; + } + XmlNode selectionCriteriaNode = resultNode.FirstChild("SelectionCriteria"); + if(!selectionCriteriaNode.IsNull()) + { + m_selectionCriteria = selectionCriteriaNode; + m_selectionCriteriaHasBeenSet = true; + } + } + + return *this; +} + +void PrefixLevelStorageMetrics::AddToNode(XmlNode& parentNode) const +{ + Aws::StringStream ss; + if(m_isEnabledHasBeenSet) + { + XmlNode isEnabledNode = parentNode.CreateChildElement("IsEnabled"); + ss << std::boolalpha << m_isEnabled; + isEnabledNode.SetText(ss.str()); + ss.str(""); + } + + if(m_selectionCriteriaHasBeenSet) + { + XmlNode selectionCriteriaNode = parentNode.CreateChildElement("SelectionCriteria"); + m_selectionCriteria.AddToNode(selectionCriteriaNode); + } + +} + +} // namespace Model +} // namespace S3Control +} // namespace Aws diff --git a/pool/shard009/C++/0110088_array.cpp b/pool/shard009/C++/0110088_array.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56703e3de6a06f6acbb540acf1778b7af97a0c38 --- /dev/null +++ b/pool/shard009/C++/0110088_array.cpp @@ -0,0 +1,78 @@ +#include "array.h" + +#include +#include +#include +#include +#include + +using std::valarray; +using std::cerr; +using std::endl; +using std::slice_array; +using std::slice; +using std::ostream; + +Array::Array(int n, int len) : dims(n), mem(len) { + for (int i=0; i < (int)mem.size(); i++) + mem[i] = 0; +} + +int prod(std::valarray x) { + int res = 1; + for (int i=0; i < (int)x.size(); i++) { + res *= x[i]; + } + return res; +} + +double& Array::pos(Nop nop, ...) { + va_list ap; + va_start(ap, nop); + int dimprod = 1; + int cell = 0; + for (int i = 0; i < (int)dims.size(); i++) { + int x = va_arg(ap, int); + cell += dimprod*x; + dimprod *= dims[i]; + } + va_end(ap); + return mem[cell]; +} + +void Array::set_dims(Nop nop, ...) { + va_list ap; + va_start(ap, nop); + for (int i = 0; i < (int)dims.size(); i++) { + int d = va_arg(ap, int); + dims[i] = d; + } + va_end(ap); + return; +} + +double& Array::posi(int i) { + return mem[i]; +} + +/* A print stream operator for Array objects */ +ostream& operator<<(ostream &s, const Array &a) { + int p = prod(a.dims); + std::ios_base::fmtflags old = s.flags(); + s.setf(std::ios_base::fixed); + s.precision(9); + s << "dims has product p=" << p << endl << " "; + for (int i=0; i <(int)a.mem.size(); i++) { + s << a.mem[i] << " "; + if ((i+1) % 6 == 0) + s << endl << " "; + } + s.flags(old); + return s; +} + + +/* END */ + + + diff --git a/pool/shard009/C++/0110089_HarvbotStepper.cpp b/pool/shard009/C++/0110089_HarvbotStepper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78aff673400a5ecf7900a290e9af1a7713f2393c --- /dev/null +++ b/pool/shard009/C++/0110089_HarvbotStepper.cpp @@ -0,0 +1,214 @@ +#include +#include "HarvbotStepper.h" + +void HarvbotStepper::moveTo(long absolute) +{ + if (_targetPos != absolute) + { + _direction = (absolute > _targetPos) ? DIRECTION_CW : DIRECTION_CCW; + + unsigned int time = 0; + do + { + time = micros(); + } while (time < _lastStepTime + _pulsePeriod); + digitalWrite(_dirPin, _direction ? HIGH : LOW); + + _targetPos = absolute; + } +} + +void HarvbotStepper::move(long relative) +{ + moveTo(_currentPos + relative); +} + +bool HarvbotStepper::runSpeed() +{ + if (distanceToGo() != 0) + { + unsigned int time = micros(); + if (time < _lastStepTime + _pulsePeriod) + { + return true; + } + + _lastStepTime = time; + + if (_direction == DIRECTION_CW) + { + // Clockwise + _currentPos += 1; + } + else + { + // Anticlockwise + _currentPos -= 1; + } + + step(_currentPos); + return true; + } + else + { + return false; + } +} + +long HarvbotStepper::distanceToGo() +{ + return _targetPos - _currentPos; +} + +long HarvbotStepper::targetPosition() +{ + return _targetPos; +} + +long HarvbotStepper::currentPosition() +{ + return _currentPos; +} + +void HarvbotStepper::setCurrentPosition(long position) +{ + _targetPos = _currentPos = position; +} + +bool HarvbotStepper::run() +{ + if (runSpeed()) + return distanceToGo() != 0; +} + +HarvbotStepper::HarvbotStepper(uint8_t stepPin, uint8_t dirPin, bool enable) +{ + _stepPin = stepPin; + _dirPin = dirPin; + _currentPos = 0; + _targetPos = 0; + setEngineFrequency(1000); + _enablePin = 0xff; + _lastStepTime = 0; + + // NEW + _direction = DIRECTION_CCW; + + if (enable) + enableOutputs(); +} + +void HarvbotStepper::setEngineFrequency(unsigned int frequency) +{ + _engineFrequency = frequency; + _pulsePeriod = 1000000 / frequency; +} + +unsigned int HarvbotStepper::engineFrequency() +{ + return _engineFrequency; +} + +void HarvbotStepper::setPulsePeriod(unsigned int waitInterval) +{ + if (_engineFrequency < 1000000 / _engineFrequency) + { + _pulsePeriod = 1000000 / _engineFrequency; + } + else + { + _pulsePeriod = waitInterval; + } +} + +unsigned int HarvbotStepper::pulsePeriod() +{ + return _pulsePeriod; +} + +bool HarvbotStepper::direction() +{ + return _direction; +} + +// Subclasses can override +void HarvbotStepper::step(long step) +{ + digitalWrite(_stepPin, HIGH); // Set direction first else get rogue pulses + delayMicroseconds(1); + digitalWrite(_stepPin, LOW); // step LOW +} + +// Prevents power consumption on the outputs +void HarvbotStepper::disableOutputs() +{ + digitalWrite(_dirPin, LOW); + digitalWrite(_stepPin, LOW); + if (_enablePin != 0xff) + digitalWrite(_enablePin, LOW ^ _enableInverted); +} + +void HarvbotStepper::enableOutputs() +{ + pinMode(_dirPin, OUTPUT); + pinMode(_stepPin, OUTPUT); + + if (_enablePin != 0xff) + { + pinMode(_enablePin, OUTPUT); + digitalWrite(_enablePin, HIGH ^ _enableInverted); + } +} + +void HarvbotStepper::setEnablePin(uint8_t enablePin) +{ + _enablePin = enablePin; + + // This happens after construction, so init pin now. + if (_enablePin != 0xff) + { + pinMode(_enablePin, OUTPUT); + digitalWrite(_enablePin, HIGH ^ _enableInverted); + } +} + +// Blocks until the target position is reached and stopped +void HarvbotStepper::runToPosition() +{ + while (run()) + ; +} + +bool HarvbotStepper::runSpeedToPosition() +{ + if (_targetPos == _currentPos) + return false; + if (_targetPos >_currentPos) + _direction = DIRECTION_CW; + else + _direction = DIRECTION_CCW; + return runSpeed(); +} + +// Blocks until the new target position is reached +void HarvbotStepper::runToNewPosition(long position) +{ + moveTo(position); + runToPosition(); +} + +void HarvbotStepper::stop() +{ + digitalWrite(_dirPin, LOW); + digitalWrite(_stepPin, LOW); +} + +uint8_t HarvbotStepper::stepPin() +{ + return _stepPin; +} + +uint8_t HarvbotStepper::directionPin() +{ + return _dirPin; +} \ No newline at end of file diff --git a/pool/shard009/C++/0110095_if_tests.cpp b/pool/shard009/C++/0110095_if_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfbc9d5f46821e8a12595b28d929c3db441a7630 --- /dev/null +++ b/pool/shard009/C++/0110095_if_tests.cpp @@ -0,0 +1,250 @@ +/*============================================================================= + Copyright (c) 2004 Stefan Slapeta + Copyright (c) 2002-2003 Martin Wille + http://spirit.sourceforge.net/ + + Use, modification and distribution is subject to the Boost Software + License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at + http://www.boost.org/LICENSE_1_0.txt) +=============================================================================*/ +// vi:ts=4:sw=4:et +// Tests for BOOST_SPIRIT_CLASSIC_NS::if_p +// [28-Dec-2002] +//////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include +#include +#include "impl/string_length.hpp" + +namespace local +{ + template + struct var_wrapper + : public ::boost::reference_wrapper + { + typedef ::boost::reference_wrapper parent; + + explicit inline var_wrapper(T& t) : parent(t) {} + + inline T& operator()() const { return parent::get(); } + }; + + template + inline var_wrapper + var(T& t) + { + return var_wrapper(t); + } +} + +typedef ::BOOST_SPIRIT_CLASSIC_NS::rule<> rule_t; +typedef ::BOOST_SPIRIT_CLASSIC_NS::rule::type > + no_actions_rule_t; + +unsigned int test_count = 0; +unsigned int error_count = 0; + +unsigned int number_result; +static const unsigned int kError = 999; +static const bool good = true; +static const bool bad = false; + +rule_t hex_prefix; +no_actions_rule_t oct_prefix; +rule_t hex_rule, oct_rule, dec_rule; + +rule_t auto_number_rule; +rule_t hex_or_dec_number_rule; + +void +test_number(char const *s, unsigned int wanted, rule_t const &r) +{ + using namespace std; + + ++test_count; + + number_result = wanted-1; + ::BOOST_SPIRIT_CLASSIC_NS::parse_info<> m = ::BOOST_SPIRIT_CLASSIC_NS::parse(s, s + test_impl::string_length(s), r); + + bool result = wanted == kError?(m.full?bad:good): (number_result==wanted); + + if (m.full && (m.length != test_impl::string_length(s))) + result = bad; + + + if (result==good) + cout << "PASSED"; + else + { + ++error_count; + cout << "FAILED"; + } + + cout << ": \"" << s << "\" ==> "; + if (number_result==wanted-1) + cout << ""; + else + cout << number_result; + + cout << "\n"; +} + +void +test_enclosed_fail() +{ + using namespace std; + + using ::BOOST_SPIRIT_CLASSIC_NS::if_p; + using ::BOOST_SPIRIT_CLASSIC_NS::str_p; + using ::BOOST_SPIRIT_CLASSIC_NS::nothing_p; + + cout << "\nfail enclosed parser:\n"; + + const char *p = "abc"; + + ::BOOST_SPIRIT_CLASSIC_NS::strlit success_p = str_p(p); + ::BOOST_SPIRIT_CLASSIC_NS::strlit fail_p = str_p("xxx"); + + ::BOOST_SPIRIT_CLASSIC_NS::rule<> r = if_p(success_p)[nothing_p]; + + ::BOOST_SPIRIT_CLASSIC_NS::parse_info<> m = ::BOOST_SPIRIT_CLASSIC_NS::parse(p, r); + + if (m.full) { + cout << "FAILED: if --> match" << endl; + ++error_count; + } else { + cout << "PASSED: if --> no_match" << endl; + } + + r = if_p(fail_p)[success_p].else_p[nothing_p]; + + m = ::BOOST_SPIRIT_CLASSIC_NS::parse(p, r); + + if (m.full) { + cout << "FAILED: else --> match" << endl; + ++error_count; + } else { + cout << "PASSED: else --> no_match" << endl; + } +} + +int +main() +{ + using namespace std; + using ::BOOST_SPIRIT_CLASSIC_NS::if_p; + using ::BOOST_SPIRIT_CLASSIC_NS::uint_p; + using ::BOOST_SPIRIT_CLASSIC_NS::oct_p; + using ::BOOST_SPIRIT_CLASSIC_NS::hex_p; + using ::BOOST_SPIRIT_CLASSIC_NS::str_p; + using ::BOOST_SPIRIT_CLASSIC_NS::ch_p; + using ::BOOST_SPIRIT_CLASSIC_NS::assign_a; + + cout << "/////////////////////////////////////////////////////////\n"; + cout << "\n"; + cout << " if_p test\n"; + cout << "\n"; + cout << "/////////////////////////////////////////////////////////\n"; + cout << "\n"; + + bool as_hex; + +#if qDebug + BOOST_SPIRIT_DEBUG_RULE(hex_prefix); + BOOST_SPIRIT_DEBUG_RULE(hex_rule); + BOOST_SPIRIT_DEBUG_RULE(oct_prefix); + BOOST_SPIRIT_DEBUG_RULE(oct_rule); + BOOST_SPIRIT_DEBUG_RULE(dec_rule); + BOOST_SPIRIT_DEBUG_RULE(auto_number_rule); + BOOST_SPIRIT_DEBUG_RULE(hex_or_dec_number_rule); +#endif + + hex_prefix = str_p("0x"); + oct_prefix = ch_p('0'); + + hex_rule = hex_p[assign_a(number_result)]; + oct_rule = oct_p[assign_a(number_result)]; + dec_rule = uint_p[assign_a(number_result)]; + + auto_number_rule = + if_p(hex_prefix) + [hex_rule] + .else_p + [ + if_p(::BOOST_SPIRIT_CLASSIC_NS::eps_p(oct_prefix)) + [oct_rule] + .else_p + [dec_rule] + ]; + + hex_or_dec_number_rule = + if_p(local::var(as_hex))[hex_prefix>>hex_rule].else_p[dec_rule]; + + cout << "auto:\n"; + test_number("", kError, auto_number_rule); + test_number("0", 0, auto_number_rule); + test_number("1", 1, auto_number_rule); + test_number("00", 0, auto_number_rule); + test_number("0x", kError, auto_number_rule); + test_number("0x0", 0, auto_number_rule); + test_number("0755", 493, auto_number_rule); + test_number("0x100", 256, auto_number_rule); + + cout << "\ndecimal:\n"; + as_hex = false; + test_number("", kError, hex_or_dec_number_rule); + test_number("100", 100, hex_or_dec_number_rule); + test_number("0x100", kError, hex_or_dec_number_rule); + test_number("0xff", kError, hex_or_dec_number_rule); + + cout << "\nhexadecimal:\n"; + as_hex = true; + test_number("", kError, hex_or_dec_number_rule); + test_number("0x100", 256, hex_or_dec_number_rule); + test_number("0xff", 255, hex_or_dec_number_rule); + + ////////////////////////////////// + // tests for if_p without else-parser + cout << "\nno-else:\n"; + rule_t r = if_p(::BOOST_SPIRIT_CLASSIC_NS::eps_p('0'))[oct_rule]; + + test_number("0", 0, r); + + ++test_count; + ::BOOST_SPIRIT_CLASSIC_NS::parse_info<> m = ::BOOST_SPIRIT_CLASSIC_NS::parse("", r); + if (!m.hit || !m.full || m.length!=0) + { + std::cout << "FAILED: \"\" ==> \n"; + ++error_count; + } + else + std::cout << "PASSED: \"\" ==> \n"; + + ++test_count; + m = ::BOOST_SPIRIT_CLASSIC_NS::parse("junk", r); + if (!m.hit || m.full || m.length!=0) + { + std::cout << "FAILED: \"junk\" ==> \n"; + ++error_count; + } + else + std::cout << "PASSED: \"junk\" ==> \n"; + + test_enclosed_fail(); + + + ////////////////////////////////// + // report results + std::cout << "\n "; + if (error_count==0) + cout << "All " << test_count << " if_p-tests passed.\n" + << "Test concluded successfully\n"; + else + cout << error_count << " of " << test_count << " if_p-tests failed\n" + << "Test failed\n"; + + return error_count!=0; +} diff --git a/pool/shard009/C++/0110098_hotkeys.cpp b/pool/shard009/C++/0110098_hotkeys.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbaa4a8dc8d06429fb961fed6e29110887519fd7 --- /dev/null +++ b/pool/shard009/C++/0110098_hotkeys.cpp @@ -0,0 +1,111 @@ +#include +#include +#include "hotkeys.hxx" +#include + +struct Hotkey +{ + Hotkey() : shortcut(NULL), context(Qt::WindowShortcut) {} + + QKeySequence keyseq; + QShortcut* shortcut; + Qt::ShortcutContext context; +}; + +typedef std::map HotkeyMap; +typedef std::map HotkeyGroupMap; + +HotkeyGroupMap hotkey_groups; + +void SaveHotkeys(QSettings& settings) +{ + settings.beginGroup("Shortcuts"); + + for (auto group : hotkey_groups) + { + settings.beginGroup(group.first); + for (auto hotkey : group.second) + { + settings.beginGroup(hotkey.first); + settings.setValue(QString("KeySeq"), hotkey.second.keyseq.toString()); + settings.setValue(QString("Context"), hotkey.second.context); + settings.endGroup(); + } + settings.endGroup(); + } + settings.endGroup(); +} + +void LoadHotkeys(QSettings& settings) +{ + settings.beginGroup("Shortcuts"); + + // Make sure NOT to use a reference here because it would become invalid once we call beginGroup() + QStringList groups = settings.childGroups(); + for (auto group : groups) + { + settings.beginGroup(group); + + QStringList hotkeys = settings.childGroups(); + for (auto hotkey : hotkeys) + { + settings.beginGroup(hotkey); + + // RegisterHotkey assigns default keybindings, so use old values as default parameters + Hotkey& hk = hotkey_groups[group][hotkey]; + hk.keyseq = QKeySequence::fromString(settings.value("KeySeq", hk.keyseq.toString()).toString()); + hk.context = (Qt::ShortcutContext)settings.value("Context", hk.context).toInt(); + if (hk.shortcut) + hk.shortcut->setKey(hk.keyseq); + + settings.endGroup(); + } + + settings.endGroup(); + } + + settings.endGroup(); +} + +void RegisterHotkey(const QString& group, const QString& action, const QKeySequence& default_keyseq, Qt::ShortcutContext default_context) +{ + if (hotkey_groups[group].find(action) == hotkey_groups[group].end()) + { + hotkey_groups[group][action].keyseq = default_keyseq; + hotkey_groups[group][action].context = default_context; + } +} + +QShortcut* GetHotkey(const QString& group, const QString& action, QWidget* widget) +{ + Hotkey& hk = hotkey_groups[group][action]; + + if (!hk.shortcut) + hk.shortcut = new QShortcut(hk.keyseq, widget, NULL, NULL, hk.context); + + return hk.shortcut; +} + + +GHotkeysDialog::GHotkeysDialog(QWidget* parent): QDialog(parent) +{ + ui.setupUi(this); + + for (auto group : hotkey_groups) + { + QTreeWidgetItem* toplevel_item = new QTreeWidgetItem(QStringList(group.first)); + for (auto hotkey : group.second) + { + QStringList columns; + columns << hotkey.first << hotkey.second.keyseq.toString(); + QTreeWidgetItem* item = new QTreeWidgetItem(columns); + toplevel_item->addChild(item); + } + ui.treeWidget->addTopLevelItem(toplevel_item); + } + // TODO: Make context configurable as well (hiding the column for now) + ui.treeWidget->setColumnCount(2); + + ui.treeWidget->resizeColumnToContents(0); + ui.treeWidget->resizeColumnToContents(1); +} diff --git a/pool/shard009/C++/0110100_vfsStream.cpp b/pool/shard009/C++/0110100_vfsStream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5972cb39e5453874369da842f1bf62605fc5e199 --- /dev/null +++ b/pool/shard009/C++/0110100_vfsStream.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" +#include "vfsStream.h" + +vfsStream::vfsStream() +{ +} + +vfsStream::~vfsStream() +{ + Close(); +} + +void vfsStream::Reset() +{ + m_pos = 0; +} + +bool vfsStream::Close() +{ + Reset(); + + return true; +} + +u64 vfsStream::GetSize() +{ + u64 last_pos = Tell(); + Seek(0, vfsSeekEnd); + u64 size = Tell(); + Seek(last_pos, vfsSeekSet); + + return size; +} + +u64 vfsStream::Write(const void* src, u64 size) +{ + m_pos += size; + + return size; +} + +u64 vfsStream::Read(void* dst, u64 size) +{ + m_pos += size; + + return size; +} + +u64 vfsStream::Seek(s64 offset, vfsSeekMode mode) +{ + switch(mode) + { + case vfsSeekSet: m_pos = offset; break; + case vfsSeekCur: m_pos += offset; break; + case vfsSeekEnd: m_pos = GetSize() + offset; break; + } + + return m_pos; +} + +u64 vfsStream::Tell() const +{ + return m_pos; +} + +bool vfsStream::Eof() +{ + return Tell() >= GetSize(); +} + +bool vfsStream::IsOpened() const +{ + return true; +} \ No newline at end of file diff --git a/pool/shard009/C++/0110101_cell_contains.cpp b/pool/shard009/C++/0110101_cell_contains.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e176797b0dc3bd15cbb41a02fb1578486b6c415f --- /dev/null +++ b/pool/shard009/C++/0110101_cell_contains.cpp @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2015-2018 Skymind, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available 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. + * + * SPDX-License-Identifier: Apache-2.0 + ******************************************************************************/ + +// +// @author George A. Shulinok +#if NOT_EXCLUDED(OP_cell_contains) + +#include +#include + +namespace sd { + namespace ops { + + CUSTOM_OP_IMPL(cell_contains, 3, 1, false, 0, 1) { + auto corner = INPUT_VARIABLE(0); + auto width = INPUT_VARIABLE(1); + auto point = INPUT_VARIABLE(2); + + auto output = OUTPUT_VARIABLE(0); + auto dimension = INT_ARG(0); + output->assign(helpers::cell_contains(corner, width, point, dimension)); + return Status::OK(); + } + + DECLARE_TYPES(cell_contains) { + getOpDescriptor() + ->setAllowedInputTypes(sd::DataType::ANY) + ->setAllowedOutputTypes(sd::DataType::BOOL) + ->setSameMode(false); + } + + DECLARE_SHAPE_FN(cell_contains) { + return SHAPELIST(CONSTANT(ShapeBuilders::createScalarShapeInfo(sd::DataType::BOOL, block.workspace()))); + } + } +} + +#endif \ No newline at end of file diff --git a/pool/shard009/C++/0110102_audioeditor.cpp b/pool/shard009/C++/0110102_audioeditor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8d8a5f00c7e23f86479f05d09c66244781fe382 --- /dev/null +++ b/pool/shard009/C++/0110102_audioeditor.cpp @@ -0,0 +1,160 @@ +/* + * audioeditor.cpp + * + * Copyright (C) 2004-2005 Christophe Thommeret + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "audioeditor.h" + +AudioEditor::AudioEditor( ChannelDesc *chan, QWidget *parent ) : AudioEditorUI( parent ) +{ + QString s, t; + int i; + + channel = chan; + pidList->clear(); + + for ( i=0; inapid; i++ ) insertItem( i ); + + if ( channel->napid==channel->maxapid ) newBtn->setEnabled( false ); + + connect( pidList, SIGNAL(highlighted(int)), this, SLOT(showProp(int)) ); + connect( upBtn, SIGNAL(clicked()), this, SLOT(itemUp()) ); + connect( downBtn, SIGNAL(clicked()), this, SLOT(itemDown()) ); + connect( delBtn, SIGNAL(clicked()), this, SLOT(itemDelete()) ); + connect( updateBtn, SIGNAL(clicked()), this, SLOT(itemUpdate()) ); + connect( newBtn, SIGNAL(clicked()), this, SLOT(itemNew()) ); +} + +void AudioEditor::insertItem( int index, bool updt ) +{ + QString s, t; + + s = t.setNum( channel->apid[index].pid ); + if ( !channel->apid[index].lang.isEmpty() ) s = s+"("+channel->apid[index].lang+")"; + if ( channel->apid[index].ac3 ) s = s+"(ac3)"; + if ( updt ) pidList->changeItem( s, index ); + else pidList->insertItem( s, index ); +} + +void AudioEditor::showProp( int index ) +{ + if ( index<0 ) { + pidSpin->setValue( 0 ); + langLe->setText( "" ); + ac3Cb->setChecked( false ); + } + else { + pidSpin->setValue( channel->apid[index].pid ); + langLe->setText( channel->apid[index].lang ); + ac3Cb->setChecked( channel->apid[index].ac3 ); + } +} + +void AudioEditor::itemUp() +{ + AudioPid a; + + int n = pidList->currentItem(); + + if ( n<1 ) return; + + a = channel->apid[n-1]; + channel->apid[n-1] = channel->apid[n]; + channel->apid[n] = a; + + insertItem( n, true ); + insertItem( n-1, true ); +} + +void AudioEditor::itemDown() +{ + AudioPid a; + + int n = pidList->currentItem(); + + if ( (n<0) || (n>(channel->napid-2)) ) return; + + a = channel->apid[n+1]; + channel->apid[n+1] = channel->apid[n]; + channel->apid[n] = a; + + insertItem( n, true ); + insertItem( n+1, true ); +} + +void AudioEditor::itemDelete() +{ + int n = pidList->currentItem(); + + if ( channel->napid==0 || (n<0) ) return; //for sure + + for ( int i=n; inapid-1; i++ ) channel->apid[i] = channel->apid[i+1]; + channel->napid--; + pidList->removeItem( n ); + + newBtn->setEnabled( true ); +} + +void AudioEditor::itemUpdate() +{ + int n = pidList->currentItem(); + + if ( n<0 ) return; + + channel->apid[n].pid = pidSpin->value(); + channel->apid[n].lang = langLe->text().stripWhiteSpace(); + if ( ac3Cb->isChecked() ) channel->apid[n].ac3 = 1; + else channel->apid[n].ac3 = 0; + + insertItem( n, true ); +} + +void AudioEditor::itemNew() +{ + if ( channel->napid==channel->maxapid ) { //for sure + newBtn->setEnabled( false ); + return; + } + + if ( !pidSpin->value() ) { + KMessageBox::sorry( this, i18n("Pid must be non zero!") ); + return; + } + channel->napid++; + channel->apid[channel->napid-1].pid = pidSpin->value(); + channel->apid[channel->napid-1].lang = langLe->text().stripWhiteSpace(); + if ( ac3Cb->isChecked() ) channel->apid[channel->napid-1].ac3 = 1; + else channel->apid[channel->napid-1].ac3 = 0; + insertItem( channel->napid-1 ); + if ( channel->napid==channel->maxapid ) newBtn->setEnabled( false ); +} + +AudioEditor::~AudioEditor() +{ +} + +#include "audioeditor.moc" diff --git a/pool/shard009/C++/0110104_dxvalidate_gtable.cc b/pool/shard009/C++/0110104_dxvalidate_gtable.cc new file mode 100644 index 0000000000000000000000000000000000000000..565ca94dd21dff6d1962cea1ff975e59eb34f49b --- /dev/null +++ b/pool/shard009/C++/0110104_dxvalidate_gtable.cc @@ -0,0 +1,147 @@ +// Copyright (C) 2013-2015 DNAnexus, Inc. +// +// This file is part of dx-toolkit (DNAnexus platform client libraries). +// +// 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 "dxvalidate_gtable.h" +#include "dxcpp/dxcpp.h" + +using namespace dx; + +bool GTableValidator::processColumns() { + columns->Init(); + columns->Add(desc["columns"]); + queryColumns = columns->getQueryColumns(); + + string cols = columns->getColumnList(0); + if (cols.size() > 0) { + msg->setData(cols, 0); + return msg->setError("COLUMNS_MISSING", true); + } + + cols = columns->getColumnList(1); + if (cols.size() > 0) { + msg->setData(cols, 0); + msg->addWarning("COLUMNS_MISSING", true); + } + + cols = columns->getColumnList(2); + if (cols.size() > 0) { + msg->setData(cols, 0); + return msg->setError("COLUMNS_INVALID_TYPES", true); + } + + cols = columns->getColumnList(4); + if (cols.size() > 0) { + msg->setData(cols, 0); + return msg->setError("COLUMNS_FORBIDDEN", true); + } + + cols = columns->getColumnList(3); + if (cols.size() > 0) { + msg->setData(cols, 0); + msg->addWarning("COLUMNS_NOT_RECOGNIZED", true); + } + + return true; +} + +bool GTableValidator::validateColumns() { + columns = new ColumnsHandler(); + bool ret_val = processColumns(); + delete columns; + return ret_val; +} + +bool GTableValidator::fetchHead(const string &source_id) { + table.setIDs(source_id); + try { + desc = table.describe(); + details = table.getDetails(); + } catch (DXAPIError &e) { + if (e.resp_code == 404) { + msg->setError("OBJECT_INVALID"); + } else { + msg->setDXError(e.msg, "GTABLE_FETCH_FAIL"); + } + return false; + } + + if (desc["class"].get() != "gtable") return msg->setError("CLASS_NOT_GTABLE"); + if (desc["state"].get() != "closed") return msg->setError("GTABLE_NOT_CLOSED"); + if (details.type() != JSON_OBJECT) return msg->setError("DETAILS_NOT_HASH"); + + types.Add(desc["types"]); + numRows = int64_t(desc["length"]); + + return true; +} + +bool GTableValidator::validateData() { + cerr << "Total rows " << numRows << endl; + + setRowValidator(); + if (! rowV->isReady()) { + delete rowV; + return false; + } + + table.startLinearQuery(queryColumns); + int64_t offset = 0; + int count = 0; + + JSON data; + try { + while (table.getNextChunk(data)) { + for (int i = 0; i < data.size(); i++) { + msg->setRowIndex(offset + i); + if (! rowV->validateRow(data[i])) { + delete rowV; + return false; + } + } + + offset += data.size(); + count ++; + if ( (count % 10) == 0) cerr << offset << "\n"; + } + + rowV->finalValidate(); + table.stopLinearQuery(); + } catch(DXError &e) { + delete rowV; + return msg->setDXError(e.msg, "GTABLE_FETCH_FAIL"); + } + + delete rowV; + return true; +} + +void GTableValidator::Validate(const string &source_id) { + if (! fetchHead(source_id)) return; + if (! validateTypes()) return; + if (! validateDetails()) return; + if (! validateColumns()) return; + + validateData(); +} + +JSON GTableValidator::Validate(const string &source_id, ValidateInfo *m) { + msg = m; + msg->setString("sourceId", source_id); + + Validate(source_id); + + return msg->getInfo(); +} diff --git a/pool/shard009/C++/0110107_tcp_client_cfstream.cc b/pool/shard009/C++/0110107_tcp_client_cfstream.cc new file mode 100644 index 0000000000000000000000000000000000000000..7d3f5d633939115a498de99dd391cefca7d58d6b --- /dev/null +++ b/pool/shard009/C++/0110107_tcp_client_cfstream.cc @@ -0,0 +1,197 @@ + +/* + * + * Copyright 2018 gRPC 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. + * + */ + +#include + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM_CLIENT + +#include +#include +#include + +#include +#include +#include + +#include "src/core/lib/address_utils/sockaddr_utils.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/gprpp/host_port.h" +#include "src/core/lib/iomgr/cfstream_handle.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/endpoint_cfstream.h" +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/error_cfstream.h" +#include "src/core/lib/iomgr/tcp_client.h" +#include "src/core/lib/iomgr/timer.h" + +extern grpc_core::TraceFlag grpc_tcp_trace; + +struct CFStreamConnect { + gpr_mu mu; + gpr_refcount refcount; + + CFReadStreamRef read_stream; + CFWriteStreamRef write_stream; + CFStreamHandle* stream_handle; + + grpc_timer alarm; + grpc_closure on_alarm; + grpc_closure on_open; + + bool read_stream_open; + bool write_stream_open; + bool failed; + + grpc_closure* closure; + grpc_endpoint** endpoint; + int refs; + std::string addr_name; +}; + +static void CFStreamConnectCleanup(CFStreamConnect* connect) { + CFSTREAM_HANDLE_UNREF(connect->stream_handle, "async connect clean up"); + CFRelease(connect->read_stream); + CFRelease(connect->write_stream); + gpr_mu_destroy(&connect->mu); + delete connect; +} + +static void OnAlarm(void* arg, grpc_error_handle error) { + CFStreamConnect* connect = static_cast(arg); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnAlarm, error:%s", connect, + grpc_error_std_string(error).c_str()); + } + gpr_mu_lock(&connect->mu); + grpc_closure* closure = connect->closure; + connect->closure = nil; + const bool done = (--connect->refs == 0); + gpr_mu_unlock(&connect->mu); + // Only schedule a callback once, by either OnAlarm or OnOpen. The + // first one issues callback while the second one does cleanup. + if (done) { + CFStreamConnectCleanup(connect); + } else { + grpc_error_handle error = + GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out"); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); + } +} + +static void OnOpen(void* arg, grpc_error_handle error) { + CFStreamConnect* connect = static_cast(arg); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnOpen, error:%s", connect, + grpc_error_std_string(error).c_str()); + } + gpr_mu_lock(&connect->mu); + grpc_timer_cancel(&connect->alarm); + grpc_closure* closure = connect->closure; + connect->closure = nil; + + bool done = (--connect->refs == 0); + grpc_endpoint** endpoint = connect->endpoint; + + // Only schedule a callback once, by either OnAlarm or OnOpen. The + // first one issues callback while the second one does cleanup. + if (done) { + gpr_mu_unlock(&connect->mu); + CFStreamConnectCleanup(connect); + } else { + if (error == GRPC_ERROR_NONE) { + CFErrorRef stream_error = CFReadStreamCopyError(connect->read_stream); + if (stream_error == NULL) { + stream_error = CFWriteStreamCopyError(connect->write_stream); + } + if (stream_error) { + error = GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "connect() error"); + CFRelease(stream_error); + } + if (error == GRPC_ERROR_NONE) { + *endpoint = grpc_cfstream_endpoint_create( + connect->read_stream, connect->write_stream, + connect->addr_name.c_str(), connect->stream_handle); + } + } else { + (void)GRPC_ERROR_REF(error); + } + gpr_mu_unlock(&connect->mu); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); + } +} + +static void ParseResolvedAddress(const grpc_resolved_address* addr, + CFStringRef* host, int* port) { + std::string host_port = grpc_sockaddr_to_string(addr, true); + std::string host_string; + std::string port_string; + grpc_core::SplitHostPort(host_port, &host_string, &port_string); + *host = CFStringCreateWithCString(NULL, host_string.c_str(), + kCFStringEncodingUTF8); + *port = grpc_sockaddr_get_port(addr); +} + +static void CFStreamClientConnect(grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* resolved_addr, + grpc_millis deadline) { + CFStreamConnect* connect = new CFStreamConnect(); + connect->closure = closure; + connect->endpoint = ep; + connect->addr_name = grpc_sockaddr_to_uri(resolved_addr); + connect->refs = 2; // One for the connect operation, one for the timer. + gpr_ref_init(&connect->refcount, 1); + gpr_mu_init(&connect->mu); + + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %p, %s: asynchronously connecting", + connect, connect->addr_name.c_str()); + } + + CFReadStreamRef read_stream; + CFWriteStreamRef write_stream; + + CFStringRef host; + int port; + ParseResolvedAddress(resolved_addr, &host, &port); + CFStreamCreatePairWithSocketToHost(NULL, host, port, &read_stream, + &write_stream); + CFRelease(host); + connect->read_stream = read_stream; + connect->write_stream = write_stream; + connect->stream_handle = + CFStreamHandle::CreateStreamHandle(read_stream, write_stream); + GRPC_CLOSURE_INIT(&connect->on_open, OnOpen, static_cast(connect), + grpc_schedule_on_exec_ctx); + connect->stream_handle->NotifyOnOpen(&connect->on_open); + GRPC_CLOSURE_INIT(&connect->on_alarm, OnAlarm, connect, + grpc_schedule_on_exec_ctx); + gpr_mu_lock(&connect->mu); + CFReadStreamOpen(read_stream); + CFWriteStreamOpen(write_stream); + grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm); + gpr_mu_unlock(&connect->mu); +} + +grpc_tcp_client_vtable grpc_cfstream_client_vtable = {CFStreamClientConnect}; + +#endif /* GRPC_CFSTREAM_CLIENT */ diff --git a/pool/shard009/C++/0110114_encryption_header_parsers.cc b/pool/shard009/C++/0110114_encryption_header_parsers.cc new file mode 100644 index 0000000000000000000000000000000000000000..829b71750fd9efbffacbdf2e29d88885d5a149ae --- /dev/null +++ b/pool/shard009/C++/0110114_encryption_header_parsers.cc @@ -0,0 +1,224 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/gcm_driver/crypto/encryption_header_parsers.h" + +#include "base/base64.h" +#include "base/numerics/safe_math.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" +#include "base/strings/string_util.h" +#include "net/http/http_util.h" + +namespace gcm { + +namespace { + +// The default record size in bytes, as defined in section two of +// https://tools.ietf.org/html/draft-thomson-http-encryption-01. +const uint64_t kDefaultRecordSizeBytes = 4096; + +// TODO(peter): Unify the base64url implementations. https://crbug.com/536745 +bool Base64URLDecode(const base::StringPiece& input, std::string* output) { + // Bail on malformed strings, which already contain a '+' or a '/'. All valid + // strings should escape these special characters as '-' and '_', + // respectively. + if (input.find_first_of("+/") != std::string::npos) + return false; + + base::CheckedNumeric checked_padded_size = input.size(); + if (input.size() % 4) + checked_padded_size += 4 - (input.size() % 4); + + // Add padding to |input|. + std::string padded_input(input.begin(), input.end()); + padded_input.resize(checked_padded_size.ValueOrDie(), '='); + + // Convert to standard base64 alphabet. + base::ReplaceChars(padded_input, "-", "+", &padded_input); + base::ReplaceChars(padded_input, "_", "/", &padded_input); + + return base::Base64Decode(padded_input, output); +} + +// Decodes the string between |begin| and |end| using base64url, and writes the +// decoded value to |*salt|. Returns whether the string could be decoded. +bool ValueToDecodedString(const std::string::const_iterator& begin, + const std::string::const_iterator& end, + std::string* salt) { + const base::StringPiece value(begin, end); + if (value.empty()) + return false; + + return Base64URLDecode(value, salt); +} + +// Parses the record size between |begin| and |end|, and writes the value to +// |*rs|. The value must be an unsigned, 64-bit integer greater than zero that +// does not start with a plus. Returns whether the record size was valid. +bool RecordSizeToInt(const std::string::const_iterator& begin, + const std::string::const_iterator& end, + uint64_t* rs) { + const base::StringPiece value(begin, end); + if (value.empty()) + return false; + + // Parsing the "rs" parameter uses stricter semantics than parsing rules for + // normal integers, in that we want to reject values such as "+5" for + // compatibility with UAs that use other number parsing mechanisms. + if (value[0] == '+') + return false; + + if (!base::StringToUint64(value, rs)) + return false; + + // The record size MUST be greater than 1. + return *rs > 1; +} + +// Parses the string between |input_begin| and |input_end| according to the +// extended ABNF syntax for the Encryption HTTP header, per the "parameter" +// rule from RFC 7231 (https://tools.ietf.org/html/rfc7231). +// +// encryption_params = [ parameter *( ";" parameter ) ] +// +// This implementation applies the parameters defined in section 3.1 of the +// HTTP encryption encoding document: +// +// https://tools.ietf.org/html/draft-thomson-http-encryption-01#section-3.1 +// +// This means that the three supported parameters are: +// +// [ "keyid" "=" string ] +// [ ";" "salt" "=" base64url ] +// [ ";" "rs" "=" octet-count ] +bool ParseEncryptionHeaderValuesImpl(std::string::const_iterator input_begin, + std::string::const_iterator input_end, + EncryptionHeaderValues* values) { + net::HttpUtil::NameValuePairsIterator name_value_pairs( + input_begin, input_end, ';', + net::HttpUtil::NameValuePairsIterator::VALUES_NOT_OPTIONAL); + + while (name_value_pairs.GetNext()) { + const base::StringPiece name(name_value_pairs.name_begin(), + name_value_pairs.name_end()); + + if (base::LowerCaseEqualsASCII(name, "keyid")) { + values->keyid.assign(name_value_pairs.value_begin(), + name_value_pairs.value_end()); + } else if (base::LowerCaseEqualsASCII(name, "salt")) { + if (!ValueToDecodedString(name_value_pairs.value_begin(), + name_value_pairs.value_end(), &values->salt)) { + return false; + } + } else if (base::LowerCaseEqualsASCII(name, "rs")) { + if (!RecordSizeToInt(name_value_pairs.value_begin(), + name_value_pairs.value_end(), &values->rs)) { + return false; + } + } else { + // Silently ignore unknown directives for forward compatibility. + } + } + + return name_value_pairs.valid(); +} + +// Parses the string between |input_begin| and |input_end| according to the +// extended ABNF syntax for the Encryption-Key HTTP header, per the "parameter" +// rule from RFC 7231 (https://tools.ietf.org/html/rfc7231). +// +// encryption_params = [ parameter *( ";" parameter ) ] +// +// This implementation applies the parameters defined in section 4 of the +// HTTP encryption encoding document: +// +//https://tools.ietf.org/html/draft-thomson-http-encryption-01#section-4 +// +// This means that the three supported parameters are: +// +// [ "keyid" "=" string ] +// [ ";" "key" "=" base64url ] +// [ ";" "dh" "=" base64url ] +bool ParseEncryptionKeyHeaderValuesImpl(std::string::const_iterator input_begin, + std::string::const_iterator input_end, + EncryptionKeyHeaderValues* values) { + net::HttpUtil::NameValuePairsIterator name_value_pairs( + input_begin, input_end, ';', + net::HttpUtil::NameValuePairsIterator::VALUES_NOT_OPTIONAL); + + while (name_value_pairs.GetNext()) { + const base::StringPiece name(name_value_pairs.name_begin(), + name_value_pairs.name_end()); + + if (base::LowerCaseEqualsASCII(name, "keyid")) { + values->keyid.assign(name_value_pairs.value_begin(), + name_value_pairs.value_end()); + } else if (base::LowerCaseEqualsASCII(name, "key")) { + if (!ValueToDecodedString(name_value_pairs.value_begin(), + name_value_pairs.value_end(), &values->key)) { + return false; + } + } else if (base::LowerCaseEqualsASCII(name, "dh")) { + if (!ValueToDecodedString(name_value_pairs.value_begin(), + name_value_pairs.value_end(), &values->dh)) { + return false; + } + } else { + // Silently ignore unknown directives for forward compatibility. + } + } + + return name_value_pairs.valid(); +} + +} // namespace + +bool ParseEncryptionHeader(const std::string& input, + std::vector* values) { + DCHECK(values); + + std::vector candidate_values; + + net::HttpUtil::ValuesIterator value_iterator(input.begin(), input.end(), ','); + while (value_iterator.GetNext()) { + EncryptionHeaderValues candidate_value; + candidate_value.rs = kDefaultRecordSizeBytes; + + if (!ParseEncryptionHeaderValuesImpl(value_iterator.value_begin(), + value_iterator.value_end(), + &candidate_value)) { + return false; + } + + candidate_values.push_back(candidate_value); + } + + values->swap(candidate_values); + return true; +} + +bool ParseEncryptionKeyHeader(const std::string& input, + std::vector* values) { + DCHECK(values); + + std::vector candidate_values; + + net::HttpUtil::ValuesIterator value_iterator(input.begin(), input.end(), ','); + while (value_iterator.GetNext()) { + EncryptionKeyHeaderValues candidate_value; + if (!ParseEncryptionKeyHeaderValuesImpl(value_iterator.value_begin(), + value_iterator.value_end(), + &candidate_value)) { + return false; + } + + candidate_values.push_back(candidate_value); + } + + values->swap(candidate_values); + return true; +} + +} // namespace gcm diff --git a/pool/shard009/C++/0110115_variantmap.cpp b/pool/shard009/C++/0110115_variantmap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..115b81d0399b281f4c615f22dcdfd03944c2ec2d --- /dev/null +++ b/pool/shard009/C++/0110115_variantmap.cpp @@ -0,0 +1,99 @@ +/****************************************************************************** + + This source file is part of the Avogadro project. + + Copyright 2011-2012 Kitware, Inc. + + This source code is released under the New BSD License, (the "License"). + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +******************************************************************************/ + +#include "variantmap.h" + +namespace Avogadro { +namespace Core { + +VariantMap::VariantMap() +{ +} + +VariantMap::~VariantMap() +{ +} + +size_t VariantMap::size() const +{ + return m_map.size(); +} + +bool VariantMap::isEmpty() const +{ + return m_map.empty(); +} + +std::vector VariantMap::names() const +{ + std::vector result; + result.reserve(size()); + for (const_iterator it = constBegin(), itEnd = constEnd(); it != itEnd; ++it) + result.push_back((*it).first); + return result; +} + +void VariantMap::setValue(const std::string &name, const Variant &v) +{ + m_map[name] = v; +} + +Variant VariantMap::value(const std::string &name) const +{ + std::map::const_iterator iter = m_map.find(name); + if (iter == m_map.end()) + return Variant(); + + return iter->second; +} + +bool VariantMap::hasValue(const std::string &name) const +{ + return m_map.find(name) != m_map.end(); +} + +VariantMap::iterator VariantMap::begin() +{ + return m_map.begin(); +} + +VariantMap::const_iterator VariantMap::begin() const +{ + return m_map.begin(); +} + +VariantMap::const_iterator VariantMap::constBegin() const +{ + return m_map.begin(); +} + +VariantMap::iterator VariantMap::end() +{ + return m_map.end(); +} + +VariantMap::const_iterator VariantMap::end() const +{ + return m_map.end(); +} + +VariantMap::const_iterator VariantMap::constEnd() const +{ + return m_map.end(); +} + +} // end Core namespace +} // end Avogadro namespace diff --git a/pool/shard009/C++/0110121_FileSystem.cpp b/pool/shard009/C++/0110121_FileSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69613581d1937cfc995ed42868b18ceef06ac3af --- /dev/null +++ b/pool/shard009/C++/0110121_FileSystem.cpp @@ -0,0 +1,144 @@ +#include "FileSystem.h" +#include "Config.h" +#include "AIMPSoundcloud.h" +#include +#include + +HRESULT WINAPI FileSystem::HTTPStream::SetSize(const INT64 Value) { + m_size = Value; + if (m_buffer) { + delete[] m_buffer; + } + m_buffer = new unsigned char[m_size]; + return S_OK; +} +FileSystem::HTTPStream::~HTTPStream() { + delete[] m_buffer; +} +void FileSystem::HTTPStream::Wait() { + std::unique_lock lock(m_mutex); + m_cv.wait(lock); +} +void FileSystem::HTTPStream::Signal() { + std::unique_lock lock(m_mutex); + m_cv.notify_all(); +} +HRESULT WINAPI FileSystem::HTTPStream::Seek(const INT64 Offset, int Mode) { + switch (Mode) { + case AIMP_STREAM_SEEKMODE_FROM_CURRENT: m_position += Offset; break; + case AIMP_STREAM_SEEKMODE_FROM_BEGINNING: m_position = Offset; break; + case AIMP_STREAM_SEEKMODE_FROM_END: m_position = m_size - Offset; break; + } + return S_OK; +} +int WINAPI FileSystem::HTTPStream::Read(unsigned char *Buffer, unsigned int Count) { + while (m_bufferSize - m_position <= 0 && m_bufferSize < m_size) + Wait(); + + Count = min(Count, m_bufferSize - m_position); + + memcpy(Buffer, m_buffer + m_position, Count); + m_position += Count; + + return Count; +} +HRESULT WINAPI FileSystem::HTTPStream::Write(unsigned char *Buffer, unsigned int Count, unsigned int *Written) { + memcpy(m_buffer + m_bufferSize, Buffer, Count); + m_bufferSize += Count; + Signal(); + + return S_OK; +} + +FileSystem::EventListener::EventListener() { + m_stream = new FileSystem::HTTPStream(); + m_stream->AddRef(); +} +void WINAPI FileSystem::EventListener::OnAccept(IAIMPString *ContentType, const INT64 ContentSize, BOOL *Allow) { + ContentType->AddRef(); + ContentType->Release(); + *Allow = true; + m_stream->SetSize(ContentSize); + m_stream->Signal(); +} +void WINAPI FileSystem::EventListener::OnComplete(IAIMPErrorInfo *ErrorInfo, BOOL Canceled) { + +} +void WINAPI FileSystem::EventListener::OnProgress(const INT64 Downloaded, const INT64 Total) { + +} + +FileSystem::FileSystem(IAIMPCore *core) : m_core(core) { + m_core->QueryInterface(IID_IAIMPServiceHTTPClient, reinterpret_cast(&m_httpClient)); +} + +HRESULT WINAPI FileSystem::GetValueAsInt32(int PropertyID, int *Value) { + if (PropertyID == AIMP_FILESYSTEM_PROPID_READONLY) { + *Value = 1; + return S_OK; + } else { + return E_INVALIDARG; + } +} + +HRESULT WINAPI FileSystem::GetValueAsObject(int PropertyID, REFIID IID, void **Value) { + if (PropertyID == AIMP_FILESYSTEM_PROPID_SCHEME) { + static AIMPString name(L"soundcloud"); + name->AddRef(); + *Value = name; + return S_OK; + } else { + return E_INVALIDARG; + } +} + +HRESULT WINAPI FileSystem::CreateStream(IAIMPString *FileName, IAIMPStream **Stream) { + HRESULT ret = E_FAIL; + if (Config::TrackInfo *ti = Tools::TrackInfo(FileName)) { + EventListener *listener = new EventListener(); + *Stream = listener->m_stream; + + std::wstring url = ti->Stream + L"?client_id=" TEXT(STREAM_CLIENT_ID); + + uintptr_t *taskId = nullptr; + ret = m_httpClient->Get(AIMPString(url), 0, *Stream, listener, nullptr, reinterpret_cast(&taskId)); + if (ret == S_OK) { + listener->m_stream->Wait(); + } + } + return ret; +} + +HRESULT WINAPI FileSystem::Process(IAIMPString *FileName) { + if (Config::TrackInfo *ti = Tools::TrackInfo(FileName)) { + ShellExecute(Plugin::instance()->GetMainWindowHandle(), L"open", ti->Permalink.c_str(), NULL, NULL, SW_SHOWNORMAL); + return S_OK; + } + return E_FAIL; +} + +HRESULT WINAPI FileSystem::CopyToClipboard(IAIMPObjectList *Files) { + std::string text; + for (int i = 0, n = Files->GetCount(); i < n; ++i) { + IAIMPString *str = nullptr; + Files->GetObject(i, IID_IAIMPString, reinterpret_cast(&str)); + if (Config::TrackInfo *ti = Tools::TrackInfo(str)) { + text += Tools::ToString(ti->Permalink) + "\r\n"; + } + str->Release(); + } + + OpenClipboard(Plugin::instance()->GetMainWindowHandle()); + EmptyClipboard(); + HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, text.size() + 1); + if (!hg) { + CloseClipboard(); + return E_FAIL; + } + memcpy(GlobalLock(hg), text.c_str(), text.size() + 1); + GlobalUnlock(hg); + SetClipboardData(CF_TEXT, hg); + CloseClipboard(); + GlobalFree(hg); + return S_OK; +} diff --git a/pool/shard009/C++/0110129_CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43.cpp b/pool/shard009/C++/0110129_CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23eb1ec49dc8c6f185b05a4f7279e25758dcf441 --- /dev/null +++ b/pool/shard009/C++/0110129_CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43.cpp @@ -0,0 +1,135 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43.cpp +Label Definition File: CWE124_Buffer_Underwrite__malloc.label.xml +Template File: sources-sink-43.tmpl.cpp +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: loop + * BadSink : Copy string to data using a loop + * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43 +{ + +#ifndef OMITBAD + +static void badSource(wchar_t * &data) +{ + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } +} + +void bad() +{ + wchar_t * data; + data = NULL; + badSource(data); + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSource(wchar_t * &data) +{ + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } +} + +static void goodG2B() +{ + wchar_t * data; + data = NULL; + goodG2BSource(data); + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard009/C++/0110130_Nes_Mmc3.cpp b/pool/shard009/C++/0110130_Nes_Mmc3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92e8b01f4a98ef07a247e74089d39216fe8b1784 --- /dev/null +++ b/pool/shard009/C++/0110130_Nes_Mmc3.cpp @@ -0,0 +1,252 @@ + +// Nes_Emu 0.7.0. http://www.slack.net/~ant/ + +#include "Nes_Mapper.h" + +#include +#include "Nes_Core.h" + +/* Copyright (C) 2004-2006 Shay Green. This module 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; either +version 2.1 of the License, or (at your option) any later version. This +module 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 Lesser General Public License for +more details. You should have received a copy of the GNU Lesser General +Public License along with this module; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#include "blargg_source.h" + +// 264 or less breaks Gargoyle's Quest II +// 267 or less breaks Magician +int const irq_fine_tune = 268; +nes_time_t const first_scanline = 20 * Nes_Ppu::scanline_len + irq_fine_tune; +nes_time_t const last_scanline = first_scanline + 240 * Nes_Ppu::scanline_len; + +class Mapper_Mmc3 : public Nes_Mapper, mmc3_state_t { + nes_time_t next_time; + int counter_just_clocked; // used only for debugging +public: + Mapper_Mmc3() + { + mmc3_state_t* state = this; + register_state( state, sizeof *state ); + } + + virtual void reset_state() + { + memcpy( banks, "\0\2\4\5\6\7\0\1", sizeof banks ); + + counter_just_clocked = 0; + next_time = 0; + mirror = 1; + if ( cart().mirroring() & 1 ) + { + mirror = 0; + //dprintf( "cart specified vertical mirroring\n" ); + } + } + + void update_chr_banks(); + void update_prg_banks(); + void write_irq( nes_addr_t addr, int data ); + void write( nes_time_t, nes_addr_t, int ); + + void start_frame() { next_time = first_scanline; } + + virtual void apply_mapping() + { + write( 0, 0xA000, mirror ); + write( 0, 0xA001, sram_mode ); + update_chr_banks(); + update_prg_banks(); + start_frame(); + } + + void clock_counter() + { + if ( counter_just_clocked ) + counter_just_clocked--; + + if ( !irq_ctr-- ) + { + irq_ctr = irq_latch; + //if ( !irq_latch ) + //dprintf( "MMC3 IRQ counter reloaded with 0\n" ); + } + + //dprintf( "%6d MMC3 IRQ clocked\n", time / ppu_overclock ); + if ( irq_ctr == 0 ) + { + //if ( irq_enabled && !irq_flag ) + //dprintf( "%6d MMC3 IRQ triggered: %f\n", time / ppu_overclock, time / scanline_len.0 - 20 ); + irq_flag = irq_enabled; + } + } + + virtual void run_until( nes_time_t ); + + virtual void a12_clocked() + { + clock_counter(); + if ( irq_enabled ) + irq_changed(); + } + + virtual void end_frame( nes_time_t end_time ) + { + run_until( end_time ); + start_frame(); + } + + virtual nes_time_t next_irq( nes_time_t present ) + { + run_until( present ); + + if ( !irq_enabled ) + return no_irq; + + if ( irq_flag ) + return 0; + + if ( !ppu_enabled() ) + return no_irq; + + int remain = irq_ctr - 1; + if ( remain < 0 ) + remain = irq_latch; + + assert( remain >= 0 ); + + long time = remain * 341L + next_time; + if ( time > last_scanline ) + return no_irq; + + return time / ppu_overclock + 1; + } +}; + +void Mapper_Mmc3::run_until( nes_time_t end_time ) +{ + bool bg_enabled = ppu_enabled(); + + end_time *= ppu_overclock; + while ( next_time < end_time && next_time <= last_scanline ) + { + if ( bg_enabled ) + clock_counter(); + next_time += Nes_Ppu::scanline_len; + } +} + +void Mapper_Mmc3::update_chr_banks() +{ + int chr_xor = (mode >> 7 & 1) * 0x1000; + set_chr_bank( 0x0000 ^ chr_xor, bank_2k, banks [0] >> 1 ); + set_chr_bank( 0x0800 ^ chr_xor, bank_2k, banks [1] >> 1 ); + set_chr_bank( 0x1000 ^ chr_xor, bank_1k, banks [2] ); + set_chr_bank( 0x1400 ^ chr_xor, bank_1k, banks [3] ); + set_chr_bank( 0x1800 ^ chr_xor, bank_1k, banks [4] ); + set_chr_bank( 0x1c00 ^ chr_xor, bank_1k, banks [5] ); +} + +void Mapper_Mmc3::update_prg_banks() +{ + set_prg_bank( 0xA000, bank_8k, banks [7] ); + nes_addr_t addr = 0x8000 + 0x4000 * (mode >> 6 & 1); + set_prg_bank( addr, bank_8k, banks [6] ); + set_prg_bank( addr ^ 0x4000, bank_8k, last_bank - 1 ); +} + +void Mapper_Mmc3::write_irq( nes_addr_t addr, int data ) +{ + switch ( addr & 0xE001 ) + { + case 0xC000: + irq_latch = data; + break; + + case 0xC001: + if ( counter_just_clocked == 1 ) + dprintf( "MMC3 IRQ counter pathological behavior triggered\n" ); + counter_just_clocked = 2; + irq_ctr = 0; + break; + + case 0xE000: + irq_flag = false; + irq_enabled = false; + break; + + case 0xE001: + irq_enabled = true; + break; + } + if ( irq_enabled ) + irq_changed(); +} + +void Mapper_Mmc3::write( nes_time_t time, nes_addr_t addr, int data ) +{ + check( !(addr & ~0xe001) ); // writes to mirrored registers are rare + //dprintf( "%6d %02X->%04X\n", time, data, addr ); + + switch ( addr & 0xE001 ) + { + case 0x8000: { + int changed = mode ^ data; + mode = data; + // avoid unnecessary bank updates + if ( changed & 0x80 ) + update_chr_banks(); + if ( changed & 0x40 ) + update_prg_banks(); + break; + } + + case 0x8001: { + int bank = mode & 7; + banks [bank] = data; + if ( bank < 6 ) + update_chr_banks(); + else + update_prg_banks(); + break; + } + + case 0xA000: + mirror = data; + if ( !(cart().mirroring() & 0x08) ) + { + if ( mirror & 1 ) + mirror_horiz(); + else + mirror_vert(); + } + break; + + case 0xA001: + sram_mode = data; + //dprintf( "%02X->%04X\n", data, addr ); + + // Startropics 1 & 2 use MMC6 and always enable low 512 bytes of SRAM + if ( (data & 0x3F) == 0x30 ) + enable_sram( true ); + else + enable_sram( data & 0x80, data & 0x40 ); + break; + + default: + run_until( time ); + write_irq( addr, data ); + break; + } +} + +Nes_Mapper* Nes_Mapper::make_mmc3() +{ + return BLARGG_NEW Mapper_Mmc3; +} + diff --git a/pool/shard009/C++/0110133_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52a.cpp b/pool/shard009/C++/0110133_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23254182484d272d84a99b5513698fb41d72e775 --- /dev/null +++ b/pool/shard009/C++/0110133_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52a.cpp @@ -0,0 +1,92 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52a.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml +Template File: sources-sink-52a.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sink: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink_b(wchar_t * data); + +void bad() +{ + wchar_t * data; + data = new wchar_t[100]; + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + wmemset(data, L'A', 100-1); /* fill with L'A's */ + data[100-1] = L'\0'; /* null terminate */ + badSink_b(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ +void goodG2BSink_b(wchar_t * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + data = new wchar_t[100]; + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + goodG2BSink_b(data); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_52; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard009/C++/0110135_version.cc b/pool/shard009/C++/0110135_version.cc new file mode 100644 index 0000000000000000000000000000000000000000..494e2334f2a3bd6803c5ba1030b9a89447663c94 --- /dev/null +++ b/pool/shard009/C++/0110135_version.cc @@ -0,0 +1,81 @@ +// version.c -- print gold version information + +// Copyright (C) 2006-2020 Free Software Foundation, Inc. +// Written by Ian Lance Taylor . + +// This file is part of gold. + +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, +// MA 02110-1301, USA. + +#include "gold.h" + +#include +#include + +#include "../bfd/bfdver.h" + +namespace gold +{ + +// The version of gold. + +// FIXME: This should eventually be PACKAGE_VERSION, and get the +// version number from configure.ac. But it's easier to just change +// this file for now. + +static const char* version_string = "1.16"; + +// Report version information. + +void +print_version(bool print_short) +{ + // The --version output is intended to follow the GNU coding + // standards. We want to print something like: + // GNU gold (GNU binutils 2.19) 1.4 + // BFD_VERSION_STRING looks like "(GNU Binutils) 2.19". We take off + // those parentheses. + std::string bfd_version(BFD_VERSION_STRING); + if (bfd_version[0] == '(') + { + bfd_version.erase(0, 1); + size_t pos = bfd_version.find(')'); + if (pos != std::string::npos) + bfd_version.erase(pos, 1); + } + + printf("GNU gold (%s) %s\n", bfd_version.c_str(), version_string); + + if (!print_short) + { + // This output is intended to follow the GNU standards. + printf(_("Copyright (C) 2020 Free Software Foundation, Inc.\n")); + printf(_("\ +This program is free software; you may redistribute it under the terms of\n\ +the GNU General Public License version 3 or (at your option) a later version.\n\ +This program has absolutely no warranty.\n")); + } +} + +// Return the version string. + +const char* +get_version_string() +{ + return version_string; +} + +} // End namespace gold. diff --git a/pool/shard009/C++/0110140_Response.cpp b/pool/shard009/C++/0110140_Response.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3b6468b449440f55ed0be3b118e6a8238f2ef78 --- /dev/null +++ b/pool/shard009/C++/0110140_Response.cpp @@ -0,0 +1,173 @@ +// Copyright (c) 2014, Ruslan Baratov +// All rights reserved. + +#include + +#include +#include +# include // std::max +# include // BOOST_LOG +#include + +#include +#include +#include + +namespace sober { +namespace network { +namespace http { + +Response::Response(): + delegate_(nullptr), + log_("sober.network.http.Response", this), + buffer_size_(DEFAULT_BUFFER_SIZE) { +} + +void Response::set_buffer_size(std::size_t buffer_size) { + buffer_size_ = (buffer_size > 0) ? buffer_size : DEFAULT_BUFFER_SIZE; +} + +void Response::set_delegate(delegate::Interface& delegate) { + delegate_ = std::addressof(delegate); +} + +bool Response::on_read(std::size_t bytes_transferred) BOOST_NOEXCEPT { + using Encoding = response::attribute::TransferEncoding; + + buffer_.commit(bytes_transferred); + + if (buffer_.size() == 0) { + BOOST_LOG(log_.debug) << "Need more data (buffer is empty)"; + return false; + } + + assert(buffer_.size() > 0); + + if (!header_parsed_) { + BOOST_LOG(log_.debug) << "Try parse:" << std::endl << + std::string(data_ptr(), data_ptr() + buffer_.size()); + + const std::size_t len = parse(header_grammar_, header_); + header_parsed_ = (len != 0); + + const char* message = + header_parsed_ ? "Header successfully parsed" : "Header parse failed"; + BOOST_LOG(log_.debug) << message; + + if (!header_parsed_) { + // Need more data (TODO: or incorrect response?) + return false; + } + + // Note: if encoding is chunked, content_length is zero + bytes_left_ = header_.content_length; + } + + if (header_.transfer_encoding == Encoding::OTHER) { + // If message body is not chunked then it has a fixed length. + // bytes_left_ is number of bytes left to read. + // Send all buffer to user and reduce bytes_left_ correspondingly. + const std::size_t avail = std::min(bytes_left_, buffer_.size()); + bytes_left_ -= avail; + const bool finish = (bytes_left_ == 0); + if (delegate_ != nullptr) { + delegate_->body_write(data_ptr(), avail); + if (finish) { + delegate_->body_finish(); + } + } + + buffer_.consume(avail); + return finish; + } + + assert(header_.transfer_encoding == Encoding::CHUNKED); + for (;;) { + if (!chunk_size_done_) { + const std::size_t len = parse(chunk_size_grammar_, chunk_size_); + if (len == 0) { + // Need more data (TODO: or incorrect response?) + return false; + } + chunk_size_done_ = true; + bytes_left_ = chunk_size_; + } + + assert(chunk_size_done_); + if (bytes_left_ == 0) { + // No more data left in chunk, expected crlf + boost::spirit::unused_type attribute; + const std::size_t len = parse(crlf_grammar_, attribute); + if (len == 0) { + // Need more data (TODO: or incorrect response?) + return false; + } + if (chunk_size_ == 0) { + // This is the last chunk + if (delegate_ != nullptr) { + delegate_->body_finish(); + } + return true; + } + chunk_size_done_ = false; + continue; + } + + assert(chunk_size_done_); + assert(bytes_left_ > 0); + const std::size_t avail = std::min(bytes_left_, buffer_.size()); + if (avail == 0) { + // Need more data + return false; + } + bytes_left_ -= avail; + if (delegate_ != nullptr) { + delegate_->body_write(data_ptr(), avail); + } + buffer_.consume(avail); + } +} + +void Response::clear() BOOST_NOEXCEPT { + if (delegate_ != nullptr) { + delegate_->body_start(); + } + header_parsed_ = false; + chunk_size_done_ = false; + chunk_size_ = 0; + bytes_left_ = 0; + buffer_.consume(buffer_.size()); +} + +const response::attribute::Header& Response::header() const { + if (!header_parsed_) { + throw std::runtime_error("Header not parsed"); + } + return header_; +} + +Response::Iterator Response::data_ptr() const BOOST_NOEXCEPT { + return boost::asio::buffer_cast(buffer_.data()); +} + +Response::Response(const std::string& input, delegate::Interface& delegate): + Response() { + set_delegate(delegate); + clear(); + + std::ostream os(&buffer_); + os << input; + os.flush(); + + assert(buffer_.size() == input.size()); + + // Bytes already commited, so transfer zero bytes + const bool finish = on_read(0); + if (!finish) { + throw std::runtime_error("Parse failed"); + } +} + +} // namespace http +} // namespace network +} // namespace sober diff --git a/pool/shard009/C++/0110145_stock_sprite.cpp b/pool/shard009/C++/0110145_stock_sprite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca036df1030530e9faa7877488fcf638c25c56f3 --- /dev/null +++ b/pool/shard009/C++/0110145_stock_sprite.cpp @@ -0,0 +1,79 @@ + +#include "stdafx.h" + +#include "stock_sprite.h" +#include "level_sprite.h" +#include "sprite_property.h" +#include "rom_file.h" + +bool StockSprite::Load(CartFile& cart) +{ + // 0x00F540 + CartFile::Scope scope(cart); + + cart.Seek(0x00F540); + SpritePropertyPool props(cart); + + for (UINT i = 0; i < 64; i++) { + WORD string_id, cast_type, prop_id; + if (!cart.Readf("HHH", + &string_id, &cast_type, &prop_id)) + { + return false; + } + if (cast_type == 0xffff) { + break ; + } + if (cast_type != 0x0140) { + // not a character presentation + continue ; + } + SceneCast c; + DWORD addr = 0x000000; + if (!cart.Read(0x00F6CE + string_id * 2, &addr, 2)) { + return false; + } + if (!cart.ReadString(addr, c.name)) { + return false; + } + Ref prop = props.NewFromID2(prop_id); + if (!prop) { + return false; + } + SpriteGraphicDef gfx; + if (!prop->GetGraphics(cart, gfx)) { + continue ; + } + c.animation_id = gfx.anim_id; + c.palette_id = gfx.palette_id; + c.sprite_id = gfx.sprite_id; + characters.push_back(c); + } + return true; +} + +bool StockSprite::GetName(std::string& in_name, + WORD animation_id, WORD sprite_id) +{ + std::vector::iterator i; + for (i = characters.begin(); i != characters.end(); ++i) { + if ((animation_id != 0 && i->animation_id == animation_id) || + (sprite_id != 0 && i->sprite_id == sprite_id)) + { + in_name = i->name; + return true; + } + } + return false; +} + +bool StockSprite::GetName(std::string& in_name, + Ref prop) +{ + SpriteGraphicDef gfx; +// if (!prop->GetGraphics(gfx)) +// { +// return false; +// } + return GetName(in_name, gfx.anim_id, gfx.sprite_id); +} diff --git a/pool/shard009/C++/0110146_audio_encoder_pcm.cc b/pool/shard009/C++/0110146_audio_encoder_pcm.cc new file mode 100644 index 0000000000000000000000000000000000000000..284a086db489a867c9190b20a39492d37c2dd2ba --- /dev/null +++ b/pool/shard009/C++/0110146_audio_encoder_pcm.cc @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h" + +#include + +#include "webrtc/base/checks.h" +#include "webrtc/modules/audio_coding/codecs/g711/include/g711_interface.h" + +namespace webrtc { + +namespace { +int16_t NumSamplesPerFrame(int num_channels, + int frame_size_ms, + int sample_rate_hz) { + int samples_per_frame = num_channels * frame_size_ms * sample_rate_hz / 1000; + CHECK_LE(samples_per_frame, std::numeric_limits::max()) + << "Frame size too large."; + return static_cast(samples_per_frame); +} +} // namespace + +AudioEncoderPcm::AudioEncoderPcm(const Config& config, int sample_rate_hz) + : sample_rate_hz_(sample_rate_hz), + num_channels_(config.num_channels), + payload_type_(config.payload_type), + num_10ms_frames_per_packet_(config.frame_size_ms / 10), + full_frame_samples_(NumSamplesPerFrame(config.num_channels, + config.frame_size_ms, + sample_rate_hz_)), + first_timestamp_in_buffer_(0) { + CHECK_GT(sample_rate_hz, 0) << "Sample rate must be larger than 0 Hz"; + CHECK_EQ(config.frame_size_ms % 10, 0) + << "Frame size must be an integer multiple of 10 ms."; + speech_buffer_.reserve(full_frame_samples_); +} + +AudioEncoderPcm::~AudioEncoderPcm() { +} + +int AudioEncoderPcm::SampleRateHz() const { + return sample_rate_hz_; +} +int AudioEncoderPcm::NumChannels() const { + return num_channels_; +} +int AudioEncoderPcm::Num10MsFramesInNextPacket() const { + return num_10ms_frames_per_packet_; +} + +int AudioEncoderPcm::Max10MsFramesInAPacket() const { + return num_10ms_frames_per_packet_; +} + +void AudioEncoderPcm::EncodeInternal(uint32_t rtp_timestamp, + const int16_t* audio, + size_t max_encoded_bytes, + uint8_t* encoded, + EncodedInfo* info) { + const int num_samples = SampleRateHz() / 100 * NumChannels(); + if (speech_buffer_.empty()) { + first_timestamp_in_buffer_ = rtp_timestamp; + } + for (int i = 0; i < num_samples; ++i) { + speech_buffer_.push_back(audio[i]); + } + if (speech_buffer_.size() < static_cast(full_frame_samples_)) { + info->encoded_bytes = 0; + return; + } + CHECK_EQ(speech_buffer_.size(), static_cast(full_frame_samples_)); + int16_t ret = EncodeCall(&speech_buffer_[0], full_frame_samples_, encoded); + CHECK_GE(ret, 0); + speech_buffer_.clear(); + info->encoded_timestamp = first_timestamp_in_buffer_; + info->payload_type = payload_type_; + info->encoded_bytes = static_cast(ret); +} + +int16_t AudioEncoderPcmA::EncodeCall(const int16_t* audio, + size_t input_len, + uint8_t* encoded) { + return WebRtcG711_EncodeA(audio, static_cast(input_len), encoded); +} + +int16_t AudioEncoderPcmU::EncodeCall(const int16_t* audio, + size_t input_len, + uint8_t* encoded) { + return WebRtcG711_EncodeU(audio, static_cast(input_len), encoded); +} + +} // namespace webrtc diff --git a/pool/shard009/C++/0110147_Model.cpp b/pool/shard009/C++/0110147_Model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1409d948fc3ab92afca81a45f88ff38efb465c5 --- /dev/null +++ b/pool/shard009/C++/0110147_Model.cpp @@ -0,0 +1,168 @@ +#include "Model.h" +#include "Spawnable/GameObject/GameObject.h" + +void Model::calculateBounds() { + glm::vec3 min(0.0f, 0.0f, 0.0f); + glm::vec3 max(0.0f, 0.0f, 0.0f); + + assert(m_vertices.size() % 3 == 0); + + for (uint32_t i = 0; i < m_vertices.size(); i += 3) { + float x = m_vertices[i]; + float y = m_vertices[i + 1]; + float z = m_vertices[i + 2]; + + min.x = glm::min(x, min.x); + min.y = glm::min(y, min.y); + min.z = glm::min(z, min.z); + + max.x = glm::max(x, max.x); + max.y = glm::max(y, max.y); + max.z = glm::max(z, max.z); + } + + m_bounds.min = min; + m_bounds.max = max; +} + +void Model::load() { + if (!m_material || m_vertices.size() == 0 || (m_material->getTexture() && m_texCoords.size() == 0)) { + Debug::log("Failed to load model\n"); + + return; + } + + glGenVertexArrays(1, &m_vertexArrayID); + glBindVertexArray(m_vertexArrayID); + + glGenBuffers(1, &m_vertexBufferID); + glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID); + glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(GLuint), m_vertices.data(), GL_STATIC_DRAW); + + glGenBuffers(1, &m_UVBufferID); + glBindBuffer(GL_ARRAY_BUFFER, m_UVBufferID); + glBufferData(GL_ARRAY_BUFFER, m_texCoords.size() * sizeof(GLuint), m_texCoords.data(), GL_STATIC_DRAW); + + calculateBounds(); +} + +void Model::unLoad() { + glDeleteBuffers(1, &m_UVBufferID); + glDeleteBuffers(1, &m_vertexBufferID); + glDeleteVertexArrays(1, &m_vertexArrayID); +} + +void Model::tick(float deltaTime) { + m_transform.rebuildMatrix(); + + if (getOwner() != nullptr) { + m_worldTransformMatrix = getOwner()->getTransformMatrix() * getLocalTransformMatrix(); + } +} + +void Model::setVertices(std::vector vertices) { + m_vertices = vertices; +} + +void Model::setTexCoords(std::vector texCoords) { + m_texCoords = texCoords; +} + +void Model::setMaterial(std::shared_ptr material) { + m_material = material; +} + +std::shared_ptr Model::getMaterial() { + return m_material; +} + +Transform& Model::getTransform() { + return m_transform; +} + +glm::mat4 Model::getLocalTransformMatrix() const { + return m_transform.getMatrix(); +} + +glm::mat4 Model::getWorldTransformMatrix() const { + return m_worldTransformMatrix; +} + +Bounds Model::getBounds() const { + return m_bounds; +} + +void Model::beginRender() { + assert(!m_rendering); + + m_rendering = true; + + glUseProgram(getMaterial()->getShader()); +} + +void Model::draw() { + assert(m_rendering); + + glDrawArrays(GL_TRIANGLES, 0, 12 * 3); +} + +void Model::endRender() { + assert(m_rendering); + + m_rendering = false; + + for (GLuint index : m_attribArraysInUse) { + glDisableVertexAttribArray(index); + } + + m_attribArraysInUse.clear(); +} + +void Model::writeMVPToShader(glm::mat4 mvp) { + glUniformMatrix4fv( + glGetUniformLocation(getMaterial()->getShader(), "MVP"), + 1, + GL_FALSE, + &mvp[0][0] + ); +} + +void Model::writeTextureToShader() { + assert(m_rendering); + + if (!m_material->getTexture()) { + return; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_material->getTexture()); + glUniform1i(glGetUniformLocation(getMaterial()->getShader(), "textureSampler"), 0); +} + +void Model::writeVerticesToShader() { + assert(m_rendering); + + GLuint verticesIndex = getMaterial()->getShaderVerticesIndex(); + + m_attribArraysInUse.push_back(verticesIndex); + + glEnableVertexAttribArray(verticesIndex); + glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID); + glVertexAttribPointer(verticesIndex, 3, GL_FLOAT, GL_FALSE, 0, nullptr); +} + +void Model::writeTexCoordsToShader() { + assert(m_rendering); + + if (!m_material->getTexture()) { + return; + } + + GLuint texCoordsIndex = getMaterial()->getShaderTexCoordsIndex(); + + m_attribArraysInUse.push_back(texCoordsIndex); + + glEnableVertexAttribArray(texCoordsIndex); + glBindBuffer(GL_ARRAY_BUFFER, m_UVBufferID); + glVertexAttribPointer(texCoordsIndex, 2, GL_FLOAT, GL_FALSE, 0, nullptr); +} diff --git a/pool/shard009/C++/0110149_InputMgr.cpp b/pool/shard009/C++/0110149_InputMgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52c0e6dde8990868d143e54df2757d7314bf515f --- /dev/null +++ b/pool/shard009/C++/0110149_InputMgr.cpp @@ -0,0 +1,134 @@ +/** +* Copyright (C) 2012 Henry Carlson +* +* This file is part of the Firestarter engine. +* +* The Firestarter engine 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, either version 3 of the License, or +* (at your option) any later version. +* +* The Firestarter engine 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 Lesser 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, see . +*/ + +#include "managers/InputMgr.hpp" + +#include "Shared.hpp" + + +namespace Firestarter { namespace Managers { + +InputMgr::InputMgr() + : p_mouseFactor(10), p_mouseYaw(0.22f), p_mousePitch(0.22f) { + p_lock = new boost::mutex(); + + clearKeys(); + updateMouseScaling(); +} + + +InputMgr::~InputMgr() { + delete p_lock; +} + + +void InputMgr::setKeyDown(SDLKey key) { + assertKeyInRange(key); + + p_lock->lock(); + p_keyDown[key] = true; + p_lock->unlock(); +} + + +void InputMgr::setKeyUp(SDLKey key) { + assertKeyInRange(key); + + p_lock->lock(); + p_keyDown[key] = false; + p_lock->unlock(); +} + + +bool InputMgr::isKeyDown(SDLKey key) { + assertKeyInRange(key); + + return p_keyDown[key]; +} + + +void InputMgr::clearKeys() { + p_lock->lock(); + for (int i = 0; i < SDLK_LAST; ++i) + p_keyDown[i] = false; + p_lock->unlock(); +} + + +void InputMgr::updateMouse(const SDL_MouseMotionEvent *event) { + p_lock->lock(); + p_mousePos.setX(event->x); + p_mousePos.setY(event->y); + + p_mouseRel.setX(event->xrel * p_mouseScaling.getX()); + p_mouseRel.setY(event->yrel * p_mouseScaling.getY()); + p_lock->unlock(); +} + + +void InputMgr::setMouseSensitivity(float sens) { + p_lock->lock(); + p_mouseFactor = sens; + + updateMouseScaling(); + p_lock->unlock(); +} + + +void InputMgr::setMouseYawFactor(float m_yaw) { + p_lock->lock(); + p_mouseYaw = m_yaw; + + updateMouseScaling(); + p_lock->unlock(); +} + + +void InputMgr::setMousePitchFactor(float m_pitch) { + p_lock->lock(); + p_mousePitch = m_pitch; + + updateMouseScaling(); + p_lock->unlock(); +} + + +Lib::Vec2D* InputMgr::getMousePosition() { + return &p_mousePos; +} + + +Lib::Vec2D* InputMgr::getMouseMovement() { + return &p_mouseRel; +} + + +void InputMgr::assertKeyInRange(SDLKey key) { + if (key >= SDLK_LAST) + throw Lib::FirestarterException("Key ID out of range"); +} + + +void InputMgr::updateMouseScaling() { + p_mouseScaling.setX(p_mouseYaw); + p_mouseScaling.setY(p_mousePitch); + p_mouseScaling.multiply(p_mouseFactor); +} + +}} // Firestarter::Managers diff --git a/pool/shard009/C++/0110153_ossl_bc.cpp b/pool/shard009/C++/0110153_ossl_bc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36f78205fce7f73d7c447239379af05aed2f66fb --- /dev/null +++ b/pool/shard009/C++/0110153_ossl_bc.cpp @@ -0,0 +1,248 @@ +/* +* OpenSSL Block Cipher +* (C) 1999-2010 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +#include +#include + +namespace Botan { + +namespace { + +/* +* EVP Block Cipher +*/ +class EVP_BlockCipher : public BlockCipher + { + public: + void clear(); + std::string name() const { return cipher_name; } + BlockCipher* clone() const; + + size_t block_size() const { return block_sz; } + + EVP_BlockCipher(const EVP_CIPHER*, const std::string&); + + EVP_BlockCipher(const EVP_CIPHER*, const std::string&, + size_t, size_t, size_t); + + Key_Length_Specification key_spec() const { return cipher_key_spec; } + + ~EVP_BlockCipher(); + private: + void encrypt_n(const byte in[], byte out[], size_t blocks) const; + void decrypt_n(const byte in[], byte out[], size_t blocks) const; + void key_schedule(const byte[], size_t); + + size_t block_sz; + Key_Length_Specification cipher_key_spec; + std::string cipher_name; + mutable EVP_CIPHER_CTX encrypt, decrypt; + }; + +/* +* EVP Block Cipher Constructor +*/ +EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, + const std::string& algo_name) : + block_sz(EVP_CIPHER_block_size(algo)), + cipher_key_spec(EVP_CIPHER_key_length(algo)), + cipher_name(algo_name) + { + if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) + throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); + + EVP_CIPHER_CTX_init(&encrypt); + EVP_CIPHER_CTX_init(&decrypt); + + EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); + EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); + + EVP_CIPHER_CTX_set_padding(&encrypt, 0); + EVP_CIPHER_CTX_set_padding(&decrypt, 0); + } + +/* +* EVP Block Cipher Constructor +*/ +EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, + const std::string& algo_name, + size_t key_min, size_t key_max, + size_t key_mod) : + block_sz(EVP_CIPHER_block_size(algo)), + cipher_key_spec(key_min, key_max, key_mod), + cipher_name(algo_name) + { + if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) + throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); + + EVP_CIPHER_CTX_init(&encrypt); + EVP_CIPHER_CTX_init(&decrypt); + + EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); + EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); + + EVP_CIPHER_CTX_set_padding(&encrypt, 0); + EVP_CIPHER_CTX_set_padding(&decrypt, 0); + } + +/* +* EVP Block Cipher Destructor +*/ +EVP_BlockCipher::~EVP_BlockCipher() + { + EVP_CIPHER_CTX_cleanup(&encrypt); + EVP_CIPHER_CTX_cleanup(&decrypt); + } + +/* +* Encrypt a block +*/ +void EVP_BlockCipher::encrypt_n(const byte in[], byte out[], + size_t blocks) const + { + int out_len = 0; + EVP_EncryptUpdate(&encrypt, out, &out_len, in, blocks * block_sz); + } + +/* +* Decrypt a block +*/ +void EVP_BlockCipher::decrypt_n(const byte in[], byte out[], + size_t blocks) const + { + int out_len = 0; + EVP_DecryptUpdate(&decrypt, out, &out_len, in, blocks * block_sz); + } + +/* +* Set the key +*/ +void EVP_BlockCipher::key_schedule(const byte key[], size_t length) + { + SecureVector full_key(key, length); + + if(cipher_name == "TripleDES" && length == 16) + { + full_key += std::make_pair(key, 8); + } + else + if(EVP_CIPHER_CTX_set_key_length(&encrypt, length) == 0 || + EVP_CIPHER_CTX_set_key_length(&decrypt, length) == 0) + throw Invalid_Argument("EVP_BlockCipher: Bad key length for " + + cipher_name); + + if(cipher_name == "RC2") + { + EVP_CIPHER_CTX_ctrl(&encrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); + EVP_CIPHER_CTX_ctrl(&decrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); + } + + EVP_EncryptInit_ex(&encrypt, 0, 0, full_key.begin(), 0); + EVP_DecryptInit_ex(&decrypt, 0, 0, full_key.begin(), 0); + } + +/* +* Return a clone of this object +*/ +BlockCipher* EVP_BlockCipher::clone() const + { + return new EVP_BlockCipher(EVP_CIPHER_CTX_cipher(&encrypt), + cipher_name, + cipher_key_spec.minimum_keylength(), + cipher_key_spec.maximum_keylength(), + cipher_key_spec.keylength_multiple()); + } + +/* +* Clear memory of sensitive data +*/ +void EVP_BlockCipher::clear() + { + const EVP_CIPHER* algo = EVP_CIPHER_CTX_cipher(&encrypt); + + EVP_CIPHER_CTX_cleanup(&encrypt); + EVP_CIPHER_CTX_cleanup(&decrypt); + EVP_CIPHER_CTX_init(&encrypt); + EVP_CIPHER_CTX_init(&decrypt); + EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); + EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); + EVP_CIPHER_CTX_set_padding(&encrypt, 0); + EVP_CIPHER_CTX_set_padding(&decrypt, 0); + } + +} + +/* +* Look for an algorithm with this name +*/ +BlockCipher* +OpenSSL_Engine::find_block_cipher(const SCAN_Name& request, + Algorithm_Factory&) const + { +#define HANDLE_EVP_CIPHER(NAME, EVP) \ + if(request.algo_name() == NAME && request.arg_count() == 0) \ + return new EVP_BlockCipher(EVP, NAME); + +#define HANDLE_EVP_CIPHER_KEYLEN(NAME, EVP, MIN, MAX, MOD) \ + if(request.algo_name() == NAME && request.arg_count() == 0) \ + return new EVP_BlockCipher(EVP, NAME, MIN, MAX, MOD); + +#if !defined(OPENSSL_NO_AES) + /* + Using OpenSSL's AES causes crashes inside EVP on x86-64 with OpenSSL 0.9.8g + cause is unknown + */ + HANDLE_EVP_CIPHER("AES-128", EVP_aes_128_ecb()); + HANDLE_EVP_CIPHER("AES-192", EVP_aes_192_ecb()); + HANDLE_EVP_CIPHER("AES-256", EVP_aes_256_ecb()); +#endif + +#if !defined(OPENSSL_NO_DES) + HANDLE_EVP_CIPHER("DES", EVP_des_ecb()); + HANDLE_EVP_CIPHER_KEYLEN("TripleDES", EVP_des_ede3_ecb(), 16, 24, 8); +#endif + +#if !defined(OPENSSL_NO_BF) + HANDLE_EVP_CIPHER_KEYLEN("Blowfish", EVP_bf_ecb(), 1, 56, 1); +#endif + +#if !defined(OPENSSL_NO_CAST) + HANDLE_EVP_CIPHER_KEYLEN("CAST-128", EVP_cast5_ecb(), 1, 16, 1); +#endif + +#if !defined(OPENSSL_NO_CAMELLIA) + HANDLE_EVP_CIPHER("Camellia-128", EVP_camellia_128_ecb()); + HANDLE_EVP_CIPHER("Camellia-192", EVP_camellia_192_ecb()); + HANDLE_EVP_CIPHER("Camellia-256", EVP_camellia_256_ecb()); +#endif + +#if !defined(OPENSSL_NO_RC2) + HANDLE_EVP_CIPHER_KEYLEN("RC2", EVP_rc2_ecb(), 1, 32, 1); +#endif + +#if !defined(OPENSSL_NO_RC5) && 0 + if(request.algo_name() == "RC5") + if(request.arg_as_integer(0, 12) == 12) + return new EVP_BlockCipher(EVP_rc5_32_12_16_ecb(), + "RC5(12)", 1, 32, 1); +#endif + +#if !defined(OPENSSL_NO_IDEA) && 0 + HANDLE_EVP_CIPHER("IDEA", EVP_idea_ecb()); +#endif + +#if !defined(OPENSSL_NO_SEED) + HANDLE_EVP_CIPHER("SEED", EVP_seed_ecb()); +#endif + +#undef HANDLE_EVP_CIPHER +#undef HANDLE_EVP_CIPHER_KEYLEN + + return 0; + } + +} diff --git a/pool/shard009/C++/0110154_lookup_stub_factory.cc b/pool/shard009/C++/0110154_lookup_stub_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..42c98b0dc043008115865e91630db46ac7730091 --- /dev/null +++ b/pool/shard009/C++/0110154_lookup_stub_factory.cc @@ -0,0 +1,65 @@ +// Copyright 2022 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. + +// Generated by the Codegen C++ plugin. +// If you make any local changes, they will be lost. +// source: google/cloud/servicedirectory/v1/lookup_service.proto + +#include "google/cloud/servicedirectory/internal/lookup_stub_factory.h" +#include "google/cloud/servicedirectory/internal/lookup_auth_decorator.h" +#include "google/cloud/servicedirectory/internal/lookup_logging_decorator.h" +#include "google/cloud/servicedirectory/internal/lookup_metadata_decorator.h" +#include "google/cloud/servicedirectory/internal/lookup_stub.h" +#include "google/cloud/common_options.h" +#include "google/cloud/grpc_options.h" +#include "google/cloud/internal/algorithm.h" +#include "google/cloud/log.h" +#include "google/cloud/options.h" +#include +#include + +namespace google { +namespace cloud { +namespace servicedirectory_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +std::shared_ptr CreateDefaultLookupServiceStub( + google::cloud::CompletionQueue cq, Options const& options) { + auto auth = google::cloud::internal::CreateAuthenticationStrategy( + std::move(cq), options); + auto channel = auth->CreateChannel(options.get(), + internal::MakeChannelArguments(options)); + auto service_grpc_stub = + google::cloud::servicedirectory::v1::LookupService::NewStub(channel); + std::shared_ptr stub = + std::make_shared(std::move(service_grpc_stub)); + + if (auth->RequiresConfigureContext()) { + stub = + std::make_shared(std::move(auth), std::move(stub)); + } + stub = std::make_shared(std::move(stub)); + if (internal::Contains(options.get(), "rpc")) { + GCP_LOG(INFO) << "Enabled logging for gRPC calls"; + stub = std::make_shared( + std::move(stub), options.get(), + options.get()); + } + return stub; +} + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace servicedirectory_internal +} // namespace cloud +} // namespace google diff --git a/pool/shard009/C++/0110155_postSubscribeContext.cpp b/pool/shard009/C++/0110155_postSubscribeContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae891a6fe3d321e6d4fa44cf5596a31f1d7cf35a --- /dev/null +++ b/pool/shard009/C++/0110155_postSubscribeContext.cpp @@ -0,0 +1,90 @@ +/* +* +* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U +* +* This file is part of Orion Context Broker. +* +* Orion Context Broker is free software: you can redistribute it and/or +* modify it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 3 of the +* License, or (at your option) any later version. +* +* Orion Context Broker 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 Affero +* General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. +* +* For those usages not covered by this license please contact with +* iot_support at tid dot es +* +* Author: Ken Zangelin +*/ +#include +#include + +#include "common/statistics.h" +#include "common/clockFunctions.h" +#include "common/limits.h" +#include "alarmMgr/alarmMgr.h" + +#include "mongoBackend/mongoSubscribeContext.h" +#include "ngsi/ParseData.h" +#include "ngsi10/SubscribeContextResponse.h" +#include "rest/ConnectionInfo.h" +#include "rest/uriParamNames.h" +#include "rest/OrionError.h" +#include "serviceRoutines/postSubscribeContext.h" + + + +/* **************************************************************************** +* +* postSubscribeContext - +* +* POST /v1/subscribeContext +* POST /ngsi10/subscribeContext +* +* Payload In: SubscribeContextRequest +* Payload Out: SubscribeContextResponse +* +*/ +std::string postSubscribeContext +( + ConnectionInfo* ciP, + int components, + std::vector& compV, + ParseData* parseDataP +) +{ + SubscribeContextResponse scr; + std::string answer; + + // + // FIXME P0: Only *one* service path is allowed for subscriptions. + // Personally (kz) I kind of like that. If you want additional service-paths, just add another subscription! + // However, we need to at least state that HERE is where we limit the number of service paths to *one*. + // + if (ciP->servicePathV.size() > 1) + { + char noOfV[STRING_SIZE_FOR_INT]; + snprintf(noOfV, sizeof(noOfV), "%lu", ciP->servicePathV.size()); + std::string details = std::string("max *one* service-path allowed for subscriptions (") + noOfV + " given"; + + alarmMgr.badInput(clientIp, details); + + scr.subscribeError.errorCode.fill(SccBadRequest, "max one service-path allowed for subscriptions"); + + TIMED_RENDER(answer = scr.render(SubscribeContext, "")); + return answer; + } + + TIMED_MONGO(ciP->httpStatusCode = mongoSubscribeContext(&parseDataP->scr.res, &scr, ciP->tenant, ciP->uriParam, ciP->httpHeaders.xauthToken, ciP->servicePathV, ciP->httpHeaders.correlator)); + TIMED_RENDER(answer = scr.render(SubscribeContext, "")); + + parseDataP->scr.res.release(); + + return answer; +} diff --git a/pool/shard009/C++/0110156_KeySwitchMatrixManipulator.cpp b/pool/shard009/C++/0110156_KeySwitchMatrixManipulator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4746e7c887ece77d9f714100939702bf7e5d8406 --- /dev/null +++ b/pool/shard009/C++/0110156_KeySwitchMatrixManipulator.cpp @@ -0,0 +1,75 @@ +#include + +#define OBJECT_CAST dynamic_cast + +#include +#include +#include + +static bool checkKeyManipMap( const osgGA::KeySwitchMatrixManipulator& kwmm ) +{ + return !kwmm.getKeyManipMap().empty(); +} + +static bool readKeyManipMap( osgDB::InputStream& is, osgGA::KeySwitchMatrixManipulator& kwmm ) +{ + int activeCameraManipulatorIndex = -1; is>>activeCameraManipulatorIndex; + unsigned int size = 0; is >> size >> is.BEGIN_BRACKET; + for ( unsigned int i=0; i> key; + std::string name; is >> name; + + osg::ref_ptr obj = is.readObject(); + osgGA::CameraManipulator* child = dynamic_cast( obj.get() ); + if ( child ) kwmm.addMatrixManipulator( key, name, child ); + } + + if (activeCameraManipulatorIndex>=0) kwmm.selectMatrixManipulator(activeCameraManipulatorIndex); + + return true; +} + +static bool writeKeyManipMap( osgDB::OutputStream& os, const osgGA::KeySwitchMatrixManipulator& kwmm ) +{ + const osgGA::KeySwitchMatrixManipulator::KeyManipMap& kmm = kwmm.getKeyManipMap(); + unsigned int size = kmm.size(); + + // find out what num the active camera manipulator is + const osgGA::CameraManipulator* cm = kwmm.getCurrentMatrixManipulator(); + int index = 0; + int activeCameraManipulatorIndex = -1; + for ( osgGA::KeySwitchMatrixManipulator::KeyManipMap::const_iterator itr = kmm.begin(); + itr != kmm.end(); + ++itr, ++index) + { + if (itr->second.second==cm) + { + activeCameraManipulatorIndex = index; + break; + } + } + + os << activeCameraManipulatorIndex; + os << size << os.BEGIN_BRACKET << std::endl; + + for ( osgGA::KeySwitchMatrixManipulator::KeyManipMap::const_iterator itr = kmm.begin(); + itr != kmm.end(); + ++itr) + { + os << itr->first; + os << itr->second.first; + os.writeObject(itr->second.second.get()); + } + os << os.END_BRACKET << std::endl; + + return true; +} + +REGISTER_OBJECT_WRAPPER( osgGA_KeySwitchMatrixManipulator, + new osgGA::KeySwitchMatrixManipulator, + osgGA::KeySwitchMatrixManipulator, + "osg::Object osgGA::KeySwitchMatrixManipulator" ) +{ + ADD_USER_SERIALIZER( KeyManipMap ); // _children +} diff --git a/pool/shard009/C++/0110157_bson.cpp b/pool/shard009/C++/0110157_bson.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c55e4f3165d9b9a544ebcc5edb5203c69aa9ecaf --- /dev/null +++ b/pool/shard009/C++/0110157_bson.cpp @@ -0,0 +1,104 @@ +#include "hphp/runtime/ext/extension.h" +#include "hphp/runtime/base/array-iterator.h" +#include +#include "encode.h" +#include "decode.h" + +namespace HPHP { +////////////////////////////////////////////////////////////////////////////// +// functions +static Array HHVM_FUNCTION(bson_decode, const String& bson) { + bson_reader_t * reader; + const bson_t * bsonObj; + bool reached_eof; + + Array output = Array::Create(); + + reader = bson_reader_new_from_data((uint8_t *)bson.c_str(), bson.size()); + bsonObj = bson_reader_read(reader, &reached_eof); + + bsonToVariant(bsonObj, &output); + bson_reader_destroy(reader); + + return output; +} + +static Array HHVM_FUNCTION(bson_decode_multiple, const String& bson) { + bson_reader_t * reader; + const bson_t * bsonObj; + bool reached_eof; + + int i = 0; + Array output = Array::Create(); + + reader = bson_reader_new_from_data((uint8_t *)bson.c_str(), bson.size()); + while ((bsonObj = bson_reader_read(reader, &reached_eof))) { + Array document = Array::Create(); + bsonToVariant(bsonObj, &document); + output.add(i++, document); + } + + bson_reader_destroy(reader); + + return output; +} + +static String encode(const Variant& anything) { + bson_t bson; + bson_init(&bson); + + fillBSONWithArray(anything.toArray(), &bson); + + const char* output = (const char*) bson_get_data(&bson); + return String(output, bson.len, CopyString); +} + +static String HHVM_FUNCTION(bson_encode, const Variant& anything) { + return encode(anything); +} + +static String HHVM_FUNCTION(bson_encode_multiple, const Array& documents) { + String output; + + for (ArrayIter iter(documents); iter; ++iter) { + output = output + f_bson_encode(iter.secondRef()); + } + + return output; +} + +////////////////////////////////////////////////////////////////////////////// + +class mongoExtension : public Extension { + public: + mongoExtension() : Extension("mongo", "1.4.5") {} + + virtual void moduleLoad(const IniSetting::Map& ini, Hdf hdf) { + EnableApc = true; + auto ini_val = Config::Get(ini, hdf, "apc.enable"); + if (ini_val != nullptr) { + ini_on_update(*ini_val, EnableApc); + } + } + + virtual void moduleInit() { + HHVM_FE(bson_decode); + HHVM_FE(bson_encode); + HHVM_FE(bson_decode_multiple); + HHVM_FE(bson_encode_multiple); + +#define C(name, value) Native::registerConstant(makeStaticString("MONGOFILL_" #name), (value)) + C(USE_APC, EnableApc); +#undef C + + loadSystemlib(); + } + private: + bool EnableApc; +} s_mongo_extension; + +// Uncomment for non-bundled module +HHVM_GET_MODULE(mongo); + +////////////////////////////////////////////////////////////////////////////// +} // namespace HPHP diff --git a/pool/shard009/C++/0110159_message_center_settings_controller.cc b/pool/shard009/C++/0110159_message_center_settings_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..a1cea8f629e1656ee6d5a0d0eefbb3a6815e75c1 --- /dev/null +++ b/pool/shard009/C++/0110159_message_center_settings_controller.cc @@ -0,0 +1,234 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/notifications/message_center_settings_controller.h" + +#include + +#include "base/i18n/string_compare.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/extensions/app_icon_loader_impl.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/favicon/favicon_service.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/favicon/favicon_types.h" +#include "chrome/browser/history/history_types.h" +#include "chrome/browser/notifications/desktop_notification_service.h" +#include "chrome/browser/notifications/desktop_notification_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/common/cancelable_task_tracker.h" +#include "chrome/common/extensions/extension_constants.h" +#include "grit/theme_resources.h" +#include "grit/ui_strings.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/gfx/image/image.h" +#include "ui/message_center/message_center_constants.h" + +using message_center::Notifier; + +namespace { + +class NotifierComparator { + public: + explicit NotifierComparator(icu::Collator* collator) : collator_(collator) {} + + bool operator() (Notifier* n1, Notifier* n2) { + return base::i18n::CompareString16WithCollator( + collator_, n1->name, n2->name) == UCOL_LESS; + } + + private: + icu::Collator* collator_; +}; + +bool SimpleCompareNotifiers(Notifier* n1, Notifier* n2) { + return n1->name < n2->name; +} + +} // namespace + +MessageCenterSettingsController::MessageCenterSettingsController() + : delegate_(NULL) { +} + +MessageCenterSettingsController::~MessageCenterSettingsController() { +} + +void MessageCenterSettingsController::ShowSettingsDialog( + gfx::NativeView context) { + delegate_ = message_center::ShowSettings(this, context); +} + +void MessageCenterSettingsController::GetNotifierList( + std::vector* notifiers) { + DCHECK(notifiers); + // TODO(mukai): Fix this for multi-profile. + Profile* profile = ProfileManager::GetDefaultProfile(); + DesktopNotificationService* notification_service = + DesktopNotificationServiceFactory::GetForProfile(profile); + + UErrorCode error; + scoped_ptr collator(icu::Collator::createInstance(error)); + scoped_ptr comparator; + if (!U_FAILURE(error)) + comparator.reset(new NotifierComparator(collator.get())); + + ExtensionService* extension_service = profile->GetExtensionService(); + const ExtensionSet* extension_set = extension_service->extensions(); + // The extension icon size has to be 32x32 at least to load bigger icons if + // the icon doesn't exist for the specified size, and in that case it falls + // back to the default icon. The fetched icon will be resized in the settings + // dialog. See chrome/browser/extensions/extension_icon_image.cc and + // crbug.com/222931 + app_icon_loader_.reset(new extensions::AppIconLoaderImpl( + profile, extension_misc::EXTENSION_ICON_SMALL, this)); + for (ExtensionSet::const_iterator iter = extension_set->begin(); + iter != extension_set->end(); ++iter) { + const extensions::Extension* extension = *iter; + if (!extension->HasAPIPermission( + extensions::APIPermission::kNotification)) { + continue; + } + + notifiers->push_back(new message_center::Notifier( + extension->id(), + UTF8ToUTF16(extension->name()), + notification_service->IsExtensionEnabled(extension->id()))); + app_icon_loader_->FetchImage(extension->id()); + } + if (comparator) + std::sort(notifiers->begin(), notifiers->end(), *comparator); + else + std::sort(notifiers->begin(), notifiers->end(), SimpleCompareNotifiers); + int app_count = notifiers->size(); + + ContentSettingsForOneType settings; + notification_service->GetNotificationsSettings(&settings); + FaviconService* favicon_service = FaviconServiceFactory::GetForProfile( + profile, Profile::EXPLICIT_ACCESS); + favicon_tracker_.reset(new CancelableTaskTracker()); + patterns_.clear(); + for (ContentSettingsForOneType::const_iterator iter = settings.begin(); + iter != settings.end(); ++iter) { + if (iter->primary_pattern == ContentSettingsPattern::Wildcard() && + iter->secondary_pattern == ContentSettingsPattern::Wildcard() && + iter->source != "preference") { + continue; + } + + std::string url_pattern = iter->primary_pattern.ToString(); + string16 name = UTF8ToUTF16(url_pattern); + GURL url(url_pattern); + notifiers->push_back(new message_center::Notifier( + url, + name, + notification_service->GetContentSetting(url) == CONTENT_SETTING_ALLOW)); + patterns_[name] = iter->primary_pattern; + FaviconService::FaviconForURLParams favicon_params( + profile, url, chrome::FAVICON | chrome::TOUCH_ICON, + message_center::kSettingsIconSize); + // Note that favicon service obtains the favicon from history. This means + // that it will fail to obtain the image if there are no history data for + // that URL. + favicon_service->GetFaviconImageForURL( + favicon_params, + base::Bind(&MessageCenterSettingsController::OnFaviconLoaded, + base::Unretained(this), url), + favicon_tracker_.get()); + } + + // Screenshot notification feature is only for ChromeOS. See crbug.com/238358 +#if defined(OS_CHROMEOS) + const string16 screenshot_name = + l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_NOTIFIER_SCREENSHOT_NAME); + message_center::Notifier* const screenshot_notifier = + new message_center::Notifier( + message_center::Notifier::SCREENSHOT, + screenshot_name, + notification_service->IsSystemComponentEnabled( + message_center::Notifier::SCREENSHOT)); + screenshot_notifier->icon = + ui::ResourceBundle::GetSharedInstance().GetImageNamed( + IDR_SCREENSHOT_NOTIFICATION_ICON); + notifiers->push_back(screenshot_notifier); +#endif + + if (comparator) { + std::sort(notifiers->begin() + app_count, notifiers->end(), *comparator); + } else { + std::sort(notifiers->begin() + app_count, notifiers->end(), + SimpleCompareNotifiers); + } +} + +void MessageCenterSettingsController::SetNotifierEnabled( + const Notifier& notifier, + bool enabled) { + // TODO(mukai): Fix this for multi-profile. + Profile* profile = ProfileManager::GetDefaultProfile(); + DesktopNotificationService* notification_service = + DesktopNotificationServiceFactory::GetForProfile(profile); + + switch (notifier.type) { + case Notifier::APPLICATION: + notification_service->SetExtensionEnabled(notifier.id, enabled); + break; + case Notifier::WEB_PAGE: { + ContentSetting default_setting = + notification_service->GetDefaultContentSetting(NULL); + DCHECK(default_setting == CONTENT_SETTING_ALLOW || + default_setting == CONTENT_SETTING_BLOCK || + default_setting == CONTENT_SETTING_ASK); + if ((enabled && default_setting != CONTENT_SETTING_ALLOW) || + (!enabled && default_setting == CONTENT_SETTING_ALLOW)) { + if (notifier.url.is_valid()) { + if (enabled) + notification_service->GrantPermission(notifier.url); + else + notification_service->DenyPermission(notifier.url); + } else { + LOG(ERROR) << "Invalid url pattern: " << notifier.url.spec(); + } + } else { + std::map::const_iterator iter = + patterns_.find(notifier.name); + if (iter != patterns_.end()) { + notification_service->ClearSetting(iter->second); + } else { + LOG(ERROR) << "Invalid url pattern: " << notifier.url.spec(); + } + } + break; + } + case message_center::Notifier::SYSTEM_COMPONENT: + notification_service->SetSystemComponentEnabled( + notifier.system_component_type, enabled); + break; + } +} + +void MessageCenterSettingsController::OnNotifierSettingsClosing() { + delegate_ = NULL; + DCHECK(favicon_tracker_.get()); + favicon_tracker_->TryCancelAll(); + patterns_.clear(); +} + +void MessageCenterSettingsController::OnFaviconLoaded( + const GURL& url, + const chrome::FaviconImageResult& favicon_result) { + if (!delegate_) + return; + delegate_->UpdateFavicon(url, favicon_result.image); +} + + +void MessageCenterSettingsController::SetAppImage(const std::string& id, + const gfx::ImageSkia& image) { + if (!delegate_) + return; + delegate_->UpdateIconImage(id, gfx::Image(image) ); +} diff --git a/pool/shard009/C++/0110160_BitserySerializer.cpp b/pool/shard009/C++/0110160_BitserySerializer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce812bb03414b7ce1fa2095b87e4ef529e8173f0 --- /dev/null +++ b/pool/shard009/C++/0110160_BitserySerializer.cpp @@ -0,0 +1,148 @@ +/** This software is distributed under BSD 3-clause license (see LICENSE file). + * + * Authors: Viktor Gal + */ + +#include +#include +#include +#include +#include + +#include +#include + +using namespace bitsery; +using namespace shogun; +using namespace shogun::io; +using namespace std; + +template +class BitseryWriterVisitor : public detail::BitseryVisitor> +{ +public: + BitseryWriterVisitor(Writer& w): + detail::BitseryVisitor>(w) {} + + void on_complex(Writer& writer, complex128_t* v) + { + writer.value8b(v->real()); + writer.value8b(v->imag()); + } + + void on_floatmax(Writer& writer, floatmax_t* v) + { + SG_DEBUG("writing floatmax_t with value {}", *v); + uint64_t msb, lsb; + uint64_t *array = reinterpret_cast(v); + auto array_size = sizeof(floatmax_t)/sizeof(uint64_t); + if (array_size == 2) + { + msb = utils::is_big_endian() ? array[1] : array[0]; + lsb = utils::is_big_endian() ? array[0] : array[1]; + } + if (array_size < 2) + { + msb = array[0]; + lsb = array[0]; + } + else + { + overflow_error("Could not represent floatmax_t with with 2 uint64_t!"); + } + // write in little endian format + writer.value8b(msb); + writer.value8b(lsb); + } + + void on_object(Writer& writer, shared_ptr* v) + { + if (*v) + { + SG_DEBUG("writing SGObject: {}", (*v)->get_name()); + write_object(writer, this, *v); + } + else + { + // nullptr + writer.value8b(detail::kNullObjectMagic); + } + } + + void on_enter_auto_value(Writer& writer, bool* is_empty) + { + } + + std::optional m_auto_value; +}; + +struct OutputStreamAdapter +{ + typedef void TValue; + + void write(const TValue* buffer, size_t bytes) + { + auto ec = m_stream->write(buffer, bytes); + if(ec) + throw io::to_system_error(ec); + written_bytes += bytes; + } + + void flush() + { + m_stream->flush(); + } + + size_t writtenBytesCount() const + { + return written_bytes; + } + + shared_ptr m_stream; + size_t written_bytes = 0; +}; + +// cannot use context because of circular dependency :( +template +void write_object(Writer& writer, BitseryWriterVisitor* visitor, const shared_ptr& o) noexcept(false) +{ + pre_serialize(o); + writer.value8b(sizeof(o.get())); + string name(o->get_name()); + writer.text1b(name, 64); + writer.value2b(static_cast(o->get_generic())); + auto params = o->get_params(); + for (auto it = params.begin(); it != params.end();) + { + if (!it->second->get_value().visitable() || !it->second->get_value().cloneable()) + it = params.erase(it); + else + ++it; + } + writer.value8b(params.size()); + for (const auto& p: params) + { + writer.text1b(p.first, 64); + p.second->get_value().visit(visitor); + } + post_serialize(o); +} + +using OutputAdapter = AdapterWriter; +using BitserySer = BasicSerializer; + +BitserySerializer::BitserySerializer() : Serializer() +{ +} + +BitserySerializer::~BitserySerializer() +{ +} + +void BitserySerializer::write(const shared_ptr& object) noexcept(false) +{ + OutputStreamAdapter adapter { stream() }; + BitserySer serializer {std::move(adapter)}; + BitseryWriterVisitor writer_visitor(serializer); + write_object(serializer, addressof(writer_visitor), object); +} diff --git a/pool/shard009/C++/0110161_QuartzCrystalRenderer.cpp b/pool/shard009/C++/0110161_QuartzCrystalRenderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a959ec92339db2bffe871537f2f5a28738c83e0f --- /dev/null +++ b/pool/shard009/C++/0110161_QuartzCrystalRenderer.cpp @@ -0,0 +1,220 @@ +/* + * QuartzCrystalRenderer.cpp + * + * Copyright (C) 2018 by VISUS (Universitaet Stuttgart) + * Alle Rechte vorbehalten. + */ +#include "QuartzCrystalRenderer.h" +#include "QuartzCrystalDataCall.h" +#include "mmcore/factories/CallAutoDescription.h" +#include "mmcore/param/IntParam.h" +#include "mmcore/utility/log/Log.h" +#include "mmcore/view/light/PointLight.h" +#include "mmcore_gl/view/CallRender3DGL.h" +#include "stdafx.h" +#include "vislib_gl/graphics/gl/IncludeAllGL.h" + +#include + +namespace megamol { +namespace demos_gl { + +/* + * CrystalRenderer::CrystalRenderer + */ +CrystalRenderer::CrystalRenderer(void) + : core_gl::view::Renderer3DModuleGL() + , dataInSlot("datain", "slot to get the data") + , lightsSlot("lights", "Lights are retrieved over this slot.") + , crystalIdx("idx", "The index of the selected crystal") { + + this->dataInSlot.SetCompatibleCall>(); + this->MakeSlotAvailable(&this->dataInSlot); + + this->lightsSlot.SetCompatibleCall(); + this->MakeSlotAvailable(&this->lightsSlot); + + this->crystalIdx << new core::param::IntParam(0, 0); + this->MakeSlotAvailable(&this->crystalIdx); +} + + +/* + * CrystalRenderer::~CrystalRenderer + */ +CrystalRenderer::~CrystalRenderer(void) { + this->Release(); +} + + +/* + * CrystalRenderer::GetExtents + */ +bool CrystalRenderer::GetExtents(core_gl::view::CallRender3DGL& call) { + + call.AccessBoundingBoxes().Clear(); + call.SetTimeFramesCount(1); + + return true; +} + + +/* + * CrystalRenderer::Render + */ +bool CrystalRenderer::Render(core_gl::view::CallRender3DGL& call) { + + unsigned int idx = static_cast(this->crystalIdx.Param()->Value()); + + CrystalDataCall* cdc = this->dataInSlot.CallAs(); + if ((cdc == NULL) || (!(*cdc)(0))) + return false; + + if (cdc->GetCount() == 0) + return false; // no data :-( + + idx = idx % cdc->GetCount(); + const CrystalDataCall::Crystal& c = cdc->GetCrystals()[idx]; + + c.AssertMesh(); + + core::view::Camera cam = call.GetCamera(); + auto view = cam.getViewMatrix(); + auto proj = cam.getProjectionMatrix(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadMatrixf(glm::value_ptr(proj)); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadMatrixf(glm::value_ptr(view)); + + ::glEnable(GL_NORMALIZE); + ::glDisable(GL_BLEND); + ::glEnable(GL_LIGHTING); + ::glEnable(GL_DEPTH_TEST); + ::glEnable(GL_COLOR_MATERIAL); + ::glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); + + ::glPointSize(8.0f); + ::glLineWidth(4.0f); + + ::glDisable(GL_LIGHTING); + ::glColor3ub(255, 128, 0); + ::glBegin(GL_LINES); + for (unsigned int i = 0; i < c.GetFaceCount(); i++) { + vislib::math::Vector v = c.GetFace(i); + ::glVertex3fv(v.PeekComponents()); + v *= 1.1f; + ::glVertex3fv(v.PeekComponents()); + } + ::glEnd(); + ::glBegin(GL_POINTS); + for (unsigned int i = 0; i < c.GetFaceCount(); i++) { + vislib::math::Vector v = c.GetFace(i); + ::glVertex3fv(v.PeekComponents()); + } + ::glEnd(); + + ::glColor3ub(0, 255, 0); + ::glBegin(GL_POINTS); + const float* verts = c.GetMeshVertexData(); + for (unsigned int i = 0; i < c.GetFaceCount(); i++) { + unsigned int cnt = c.GetMeshTriangleCounts()[i]; + for (unsigned int j = 0; j < cnt; j++) { + ::glVertex3fv(verts + 3 * c.GetMeshTriangles()[i][j]); + } + } + ::glEnd(); + + ::glColor3ub(0, 0, 255); + for (unsigned int i = 0; i < c.GetFaceCount(); i++) { + ::glBegin(GL_LINE_LOOP); + unsigned int cnt = c.GetMeshTriangleCounts()[i]; + for (unsigned int j = 0; j < cnt; j++) { + ::glVertex3fv(verts + 3 * c.GetMeshTriangles()[i][j]); + } + ::glEnd(); + } + + + // determine position of point light + std::array lightPos = {0.0f, 0.0f, 0.0f}; + + auto call_light = lightsSlot.CallAs(); + if (call_light != nullptr) { + if (!(*call_light)(0)) { + return false; + } + + auto lights = call_light->getData(); + auto point_lights = lights.get(); + + if (point_lights.size() > 1) { + megamol::core::utility::log::Log::DefaultLog.WriteWarn( + "[CartoonTessellationRenderer2000GT] Only one single 'Point Light' source is supported by this " + "renderer"); + } else if (point_lights.empty()) { + megamol::core::utility::log::Log::DefaultLog.WriteWarn( + "[CartoonTessellationRenderer2000GT] No 'Point Light' found"); + } + + for (auto const& light : point_lights) { + // light.second.lightColor; + // light.second.lightIntensity; + lightPos[0] = light.position[0]; + lightPos[1] = light.position[1]; + lightPos[2] = light.position[2]; + break; + } + } + const float lp[4] = {-lightPos[0], -lightPos[1], -lightPos[1], 0.0f}; + const float zeros[4] = {0.0f, 0.0f, 0.0f, 1.0f}; + const float ones[4] = {1.0f, 1.0f, 1.0f, 1.0f}; + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glLightfv(GL_LIGHT0, GL_AMBIENT, zeros); + glLightfv(GL_LIGHT0, GL_DIFFUSE, ones); + glLightfv(GL_LIGHT0, GL_SPECULAR, ones); + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zeros); + + ::glColor3ub(192, 192, 192); + //verts = c.GetMeshVertexData(); + for (unsigned int i = 0; i < c.GetFaceCount(); i++) { + ::glNormal3fv(c.GetFace(i).PeekComponents()); + ::glBegin(GL_TRIANGLE_FAN); + unsigned int cnt = c.GetMeshTriangleCounts()[i]; + for (unsigned int j = 0; j < cnt; j++) { + ::glVertex3fv(verts + 3 * c.GetMeshTriangles()[i][j]); + } + ::glEnd(); + } + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + return true; +} + + +/* + * CrystalRenderer::create + */ +bool CrystalRenderer::create(void) { + // intentionally empty + return true; +} + + +/* + * CrystalRenderer::release + */ +void CrystalRenderer::release(void) { + // intentionally empty +} + +} // namespace demos_gl +} /* end namespace megamol */ diff --git a/pool/shard009/C++/0110164_BaseClickableWithKeyInputType.cpp b/pool/shard009/C++/0110164_BaseClickableWithKeyInputType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..329c512ed22ccf64f2641db16d5ab2ed079edb50 --- /dev/null +++ b/pool/shard009/C++/0110164_BaseClickableWithKeyInputType.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2010, 2012 Google Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "BaseClickableWithKeyInputType.h" + +#include "HTMLInputElement.h" +#include "KeyboardEvent.h" + +namespace WebCore { + +using namespace HTMLNames; + +void BaseClickableWithKeyInputType::handleKeydownEvent(HTMLInputElement* element, KeyboardEvent* event) +{ + const String& key = event->keyIdentifier(); + if (key == "U+0020") { + element->setActive(true, true); + // No setDefaultHandled(), because IE dispatches a keypress in this case + // and the caller will only dispatch a keypress if we don't call setDefaultHandled(). + } +} + +void BaseClickableWithKeyInputType::handleKeypressEvent(HTMLInputElement* element, KeyboardEvent* event) +{ + int charCode = event->charCode(); + if (charCode == '\r') { + element->dispatchSimulatedClick(event); + event->setDefaultHandled(); + return; + } + if (charCode == ' ') { + // Prevent scrolling down the page. + event->setDefaultHandled(); + } +} + +void BaseClickableWithKeyInputType::handleKeyupEvent(InputType& inputType, KeyboardEvent* event) +{ + const String& key = event->keyIdentifier(); + if (key != "U+0020") + return; + // Simulate mouse click for spacebar for button types. + inputType.dispatchSimulatedClickIfActive(event); +} + +// FIXME: Could share this with BaseCheckableInputType and RangeInputType if we had a common base class. +void BaseClickableWithKeyInputType::accessKeyAction(HTMLInputElement* element, bool sendMouseEvents) +{ + // Send mouse button events if the caller specified sendMouseEvents. + // FIXME: The comment above is no good. It says what we do, but not why. + element->dispatchSimulatedClick(0, sendMouseEvents); +} + +void BaseClickableWithKeyInputType::handleKeydownEvent(KeyboardEvent* event) +{ + handleKeydownEvent(element(), event); +} + +void BaseClickableWithKeyInputType::handleKeypressEvent(KeyboardEvent* event) +{ + handleKeypressEvent(element(), event); +} + +void BaseClickableWithKeyInputType::handleKeyupEvent(KeyboardEvent* event) +{ + handleKeyupEvent(*this, event); +} + +void BaseClickableWithKeyInputType::accessKeyAction(bool sendMouseEvents) +{ + InputType::accessKeyAction(sendMouseEvents); + accessKeyAction(element(), sendMouseEvents); +} + +} // namespace WebCore diff --git a/pool/shard009/C++/0110169_MultipleDrawBuffers.cpp b/pool/shard009/C++/0110169_MultipleDrawBuffers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b129072f08fbb8a723f0070799879d9d046a9b5e --- /dev/null +++ b/pool/shard009/C++/0110169_MultipleDrawBuffers.cpp @@ -0,0 +1,218 @@ +// +// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// + +// Based on Simple_Texture2D.c from +// Book: OpenGL(R) ES 2.0 Programming Guide +// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner +// ISBN-10: 0321502795 +// ISBN-13: 9780321502797 +// Publisher: Addison-Wesley Professional +// URLs: http://safari.informit.com/9780321563835 +// http://www.opengles-book.com + +#include "SampleApplication.h" +#include "shader_utils.h" +#include "system_utils.h" +#include "texture_utils.h" + +#include +#include + +class MultipleDrawBuffersSample : public SampleApplication +{ + public: + MultipleDrawBuffersSample() + : SampleApplication("MultipleDrawBuffers", 1280, 720) + { + } + + virtual bool initialize() + { + // Check EXT_draw_buffers is supported + char *extensionString = (char*)glGetString(GL_EXTENSIONS); + if (strstr(extensionString, "GL_EXT_draw_buffers") != NULL) + { + // Retrieve the address of glDrawBuffersEXT from EGL + mDrawBuffers = (PFNGLDRAWBUFFERSEXTPROC)eglGetProcAddress("glDrawBuffersEXT"); + } + else + { + mDrawBuffers = glDrawBuffers; + } + + if (!mDrawBuffers) + { + std::cerr << "Unable to load glDrawBuffers[EXT] entry point."; + return false; + } + + mMRTProgram = CompileProgramFromFiles(angle::GetExecutableDirectory() + "/multiple_draw_buffers_vs.glsl", + angle::GetExecutableDirectory() + "/multiple_draw_buffers_fs.glsl"); + if (!mMRTProgram) + { + return false; + } + + mCopyProgram = CompileProgramFromFiles(angle::GetExecutableDirectory() + "/multiple_draw_buffers_vs.glsl", + angle::GetExecutableDirectory() + "/multiple_draw_buffers_copy_fs.glsl"); + if (!mCopyProgram) + { + return false; + } + + // Get the attribute locations + mPositionLoc = glGetAttribLocation(mCopyProgram, "a_position"); + mTexCoordLoc = glGetAttribLocation(mCopyProgram, "a_texCoord"); + + // Get the sampler location + mSamplerLoc = glGetUniformLocation(mCopyProgram, "s_texture"); + + // Load the texture + mTexture = CreateSimpleTexture2D(); + + // Initialize the user framebuffer + glGenFramebuffers(1, &mFramebuffer); + glGenTextures(mFramebufferAttachmentCount, mFramebufferTextures); + + glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer); + for (size_t i = 0; i < mFramebufferAttachmentCount; i++) + { + // Create textures for the four color attachments + glBindTexture(GL_TEXTURE_2D, mFramebufferTextures[i]); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWindow()->getWidth(), getWindow()->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glFramebufferTexture2D(GL_FRAMEBUFFER, + static_cast(GL_COLOR_ATTACHMENT0_EXT + i), GL_TEXTURE_2D, + mFramebufferTextures[i], 0); + } + + glBindTexture(GL_TEXTURE_2D, 0); + + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + return true; + } + + virtual void destroy() + { + glDeleteProgram(mCopyProgram); + glDeleteProgram(mMRTProgram); + glDeleteTextures(1, &mTexture); + glDeleteTextures(mFramebufferAttachmentCount, mFramebufferTextures); + glDeleteFramebuffers(1, &mFramebuffer); + } + + virtual void draw() + { + GLfloat vertices[] = + { + -0.8f, 0.8f, 0.0f, // Position 0 + 0.0f, 0.0f, // TexCoord 0 + -0.8f, -0.8f, 0.0f, // Position 1 + 0.0f, 1.0f, // TexCoord 1 + 0.8f, -0.8f, 0.0f, // Position 2 + 1.0f, 1.0f, // TexCoord 2 + 0.8f, 0.8f, 0.0f, // Position 3 + 1.0f, 0.0f // TexCoord 3 + }; + GLushort indices[] = { 0, 1, 2, 0, 2, 3 }; + GLenum drawBuffers[mFramebufferAttachmentCount] = + { + GL_COLOR_ATTACHMENT0_EXT, + GL_COLOR_ATTACHMENT1_EXT, + GL_COLOR_ATTACHMENT2_EXT, + GL_COLOR_ATTACHMENT3_EXT + }; + + // Enable drawing to the four color attachments of the user framebuffer + glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer); + mDrawBuffers(mFramebufferAttachmentCount, drawBuffers); + + // Set the viewport + GLint width = static_cast(getWindow()->getWidth()); + GLint height = static_cast(getWindow()->getHeight()); + glViewport(0, 0, width, height); + + // Clear the color buffer + glClear(GL_COLOR_BUFFER_BIT); + + // Use the program object + glUseProgram(mMRTProgram); + + // Load the vertex position + glVertexAttribPointer(mPositionLoc, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), vertices); + glEnableVertexAttribArray(mPositionLoc); + + // Load the texture coordinate + glVertexAttribPointer(mTexCoordLoc, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), vertices + 3); + glEnableVertexAttribArray(mTexCoordLoc); + + // Bind the texture + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, mTexture); + + // Set the sampler texture unit to 0 + glUniform1i(mSamplerLoc, 0); + + // Draw the textured quad to the four render targets + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices); + + // Enable the default framebuffer and single textured drawing + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glUseProgram(mCopyProgram); + + // Draw the four textured quads to a separate region in the viewport + glBindTexture(GL_TEXTURE_2D, mFramebufferTextures[0]); + glViewport(0, 0, width / 2, height / 2); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices); + + glBindTexture(GL_TEXTURE_2D, mFramebufferTextures[1]); + glViewport(width / 2, 0, width / 2, height / 2); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices); + + glBindTexture(GL_TEXTURE_2D, mFramebufferTextures[2]); + glViewport(0, height / 2, width / 2, height / 2); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices); + + glBindTexture(GL_TEXTURE_2D, mFramebufferTextures[3]); + glViewport(width / 2, height / 2, width / 2, height / 2); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices); + } + + private: + // Handle to a program object + GLuint mMRTProgram; + GLuint mCopyProgram; + + // Attribute locations + GLint mPositionLoc; + GLint mTexCoordLoc; + + // Sampler location + GLint mSamplerLoc; + + // Texture handle + GLuint mTexture; + + // Framebuffer object handle + GLuint mFramebuffer; + + // Framebuffer color attachments + static const size_t mFramebufferAttachmentCount = 4; + GLuint mFramebufferTextures[mFramebufferAttachmentCount]; + + // Loaded draw buffer entry points + PFNGLDRAWBUFFERSEXTPROC mDrawBuffers; +}; + +int main(int argc, char **argv) +{ + MultipleDrawBuffersSample app; + return app.run(); +} diff --git a/pool/shard009/C++/0110170_buffer_value.cc b/pool/shard009/C++/0110170_buffer_value.cc new file mode 100644 index 0000000000000000000000000000000000000000..b76f5a72657dda6423f8c293e97d2da20af86bbd --- /dev/null +++ b/pool/shard009/C++/0110170_buffer_value.cc @@ -0,0 +1,66 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/compiler/xla/service/buffer_value.h" + +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/xla/service/hlo_computation.h" +#include "tensorflow/compiler/xla/service/hlo_instruction.h" +#include "tensorflow/compiler/xla/types.h" + +namespace xla { + +BufferValue::BufferValue(HloInstruction* instruction, const ShapeIndex& index, + Id id) + : id_(id) { + const Shape& shape = ShapeUtil::GetSubshape(instruction->shape(), index); + is_array_ = shape.IsArray(); + is_tuple_ = shape.IsTuple(); +} + +BufferValue::~BufferValue() {} + +std::ostream& operator<<(std::ostream& out, const BufferValue& buffer) { + out << buffer.ToString(); + return out; +} + +/*static*/ LogicalBufferProto::Location BufferValue::ToLocationProto( + const HloInstruction& instruction, const ShapeIndex& index) { + LogicalBufferProto::Location proto; + proto.set_computation_name(instruction.parent()->name()); + proto.set_instruction_name(instruction.name()); + for (const int64_t index_entry : index) { + proto.add_shape_index(index_entry); + } + return proto; +} + +LogicalBufferProto BufferValue::ToProto(const SizeFunction& size_fn) const { + LogicalBufferProto proto; + proto.set_id(id()); + proto.set_size(size_fn(*this)); + LogicalBufferProto::Location proto_location = + ToLocationProto(*instruction(), index()); + proto.mutable_defined_at()->Swap(&proto_location); + if (has_color()) { + proto.set_color(color()); + } + return proto; +} + +} // namespace xla diff --git a/pool/shard009/C++/0110172_test_proxytoggle.cpp b/pool/shard009/C++/0110172_test_proxytoggle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fb2b567c071e820d5a32105a7a77f47af95b4a3 --- /dev/null +++ b/pool/shard009/C++/0110172_test_proxytoggle.cpp @@ -0,0 +1,112 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#include "cbase.h" +#include "basenetworkable.h" + + + +class CTest_ProxyToggle_Networkable; +static CTest_ProxyToggle_Networkable *g_pTestObj = 0; +static bool g_bEnableProxy = true; + + +// ---------------------------------------------------------------------------------------- // +// CTest_ProxyToggle_Networkable +// ---------------------------------------------------------------------------------------- // + +class CTest_ProxyToggle_Networkable : public CBaseNetworkable +{ +public: + DECLARE_CLASS( CTest_ProxyToggle_Networkable, CBaseNetworkable ); + DECLARE_SERVERCLASS(); + + CTest_ProxyToggle_Networkable() + { + m_WithProxy = 1241; + g_pTestObj = this; + } + + ~CTest_ProxyToggle_Networkable() + { + g_pTestObj = NULL; + } + + bool ShouldTransmit( + const edict_t *recipient, + const void *pvs, + int clientArea + ) + { + return true; + } + + CNetworkVar( int, m_WithProxy ); +}; + +void* SendProxy_TestProxyToggle( const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID ) +{ + if ( g_bEnableProxy ) + { + return (void*)pData; + } + else + { + pRecipients->ClearAllRecipients(); + return NULL; + } +} + + +// ---------------------------------------------------------------------------------------- // +// Datatables. +// ---------------------------------------------------------------------------------------- // + +LINK_ENTITY_TO_CLASS( test_proxytoggle, CTest_ProxyToggle_Networkable ); + +BEGIN_SEND_TABLE_NOBASE( CTest_ProxyToggle_Networkable, DT_ProxyToggle_ProxiedData ) + SendPropInt( SENDINFO( m_WithProxy ) ) +END_SEND_TABLE() + +IMPLEMENT_SERVERCLASS_ST( CTest_ProxyToggle_Networkable, DT_ProxyToggle ) + SendPropDataTable( "blah", 0, &REFERENCE_SEND_TABLE( DT_ProxyToggle_ProxiedData ), SendProxy_TestProxyToggle ) +END_SEND_TABLE() + + + +// ---------------------------------------------------------------------------------------- // +// Console commands for this test. +// ---------------------------------------------------------------------------------------- // + +void Test_ProxyToggle_EnableProxy() +{ + if ( engine->Cmd_Argc() < 2 ) + { + Error( "Test_ProxyToggle_EnableProxy: requires parameter (0 or 1)." ); + } + + g_bEnableProxy = !!atoi( engine->Cmd_Argv( 1 ) ); +} + +void Test_ProxyToggle_SetValue() +{ + if ( engine->Cmd_Argc() < 2 ) + { + Error( "Test_ProxyToggle_SetValue: requires value parameter." ); + } + else if ( !g_pTestObj ) + { + Error( "Test_ProxyToggle_SetValue: no entity present." ); + } + + g_pTestObj->m_WithProxy = atoi( engine->Cmd_Argv( 1 ) ); +} + +ConCommand cc_Test_ProxyToggle_EnableProxy( "Test_ProxyToggle_EnableProxy", Test_ProxyToggle_EnableProxy, 0, FCVAR_CHEAT ); +ConCommand cc_Test_ProxyToggle_SetValue( "Test_ProxyToggle_SetValue", Test_ProxyToggle_SetValue, 0, FCVAR_CHEAT ); + + diff --git a/pool/shard009/C++/0110175_Service.FtpServerEndpoint.cpp b/pool/shard009/C++/0110175_Service.FtpServerEndpoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd56d6aa9aa506aff398a29d198dfb846b197326 --- /dev/null +++ b/pool/shard009/C++/0110175_Service.FtpServerEndpoint.cpp @@ -0,0 +1,21 @@ +// Copyright © 2014 Brian Spanton + +#include "stdafx.h" +#include "Service.FtpServerEndpoint.h" +#include "Ftp.Server.h" + +namespace Service +{ + using namespace Basic; + + FtpServerEndpoint::FtpServerEndpoint(ListenSocket::Face face, short port) : + Endpoint(face, port) + { + } + + void FtpServerEndpoint::SpawnListener() + { + std::shared_ptr protocol = std::make_shared(this->shared_from_this(), ByteStringRef()); + protocol->start(this->listener.get()); + } +} \ No newline at end of file diff --git a/pool/shard009/C++/0110176_EventHub.cpp b/pool/shard009/C++/0110176_EventHub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22620ef3d8d262e2adb9055c2637aa019c61b50b --- /dev/null +++ b/pool/shard009/C++/0110176_EventHub.cpp @@ -0,0 +1,163 @@ +/* + * Coral Qt Module + * See copyright notice in LICENSE.md + */ + +#include "EventHub.h" +#include +#include +#include +#include +#include +#include +#include +#include + +QMetaEnum EventHub::sm_qtKeyMetaEnum; + +void EventHub::fillKeyboardModifiers( Qt::KeyboardModifiers modifiers, co::Any& any ) +{ + qt::KeyboardModifiers& km = any.createComplexValue(); + fillKeyboardModifiers( modifiers, km ); +} + +void EventHub::fillKeyboardModifiers( Qt::KeyboardModifiers modifiers, qt::KeyboardModifiers& km ) +{ + km.alt = modifiers & Qt::AltModifier; + km.meta = modifiers & Qt::MetaModifier; + km.shift = modifiers & Qt::ShiftModifier; + km.keypad = modifiers & Qt::KeypadModifier; + km.control = modifiers & Qt::ControlModifier; + km.groupSwitch = modifiers & Qt::GroupSwitchModifier; +} + +void EventHub::fillKeyCodeString( int keyCode, co::Any& any ) +{ + const char* name = sm_qtKeyMetaEnum.valueToKey( keyCode ); + if( name ) + any.createString() = name; +} + +EventHub::EventHub() +{ + if( !sm_qtKeyMetaEnum.isValid() ) + sm_qtKeyMetaEnum = createKeyMetaEnum(); +} + +EventHub::~EventHub() +{ + // empty +} + +co::int64 EventHub::installEventHandler( const qt::Object& watched, qt::IEventHandler* handler ) +{ + QObject* obj = watched.get(); + if( !isObjectFiltered( obj ) ) + obj->installEventFilter( this ); + + // sets/replaces event handler for the object + _filteredObjects[obj] = handler; + + return reinterpret_cast( obj ); +} + +void EventHub::removeEventHandler( const qt::Object& watched ) +{ + QObject* obj = watched.get(); + if( isObjectFiltered( obj ) ) + { + obj->removeEventFilter( this ); + _filteredObjects.erase( obj ); + } +} + +bool EventHub::eventFilter( QObject* watched, QEvent* event ) +{ + assert( _filteredObjects[watched] ); + + co::Any args[MAX_ARGS]; + extractArguments( event, args, MAX_ARGS ); + + if( !_filteredObjects[watched]->onEvent( reinterpret_cast( watched ), event->type(), + args[0], args[1], args[2], args[3], args[4], args[5] ) ) + { + event->ignore(); + return true; + } + + return false; +} + +// Extract event-specific arguments to co::Any array +void EventHub::extractArguments( QEvent* event, co::Any* args, int maxArgs ) +{ + QEvent::Type ev = event->type(); + switch( ev ) + { + case QEvent::MouseButtonDblClick: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseMove: + { + QMouseEvent* mouseEvent = static_cast( event ); + + // extract (x and y), button, modifiers + const QPoint& pos = mouseEvent->pos(); + args[0].set( pos.x() ); + args[1].set( pos.y() ); + args[2].set( static_cast( ev == QEvent::MouseMove ? + mouseEvent->buttons() : mouseEvent->button() ) ); + fillKeyboardModifiers( mouseEvent->modifiers(), args[3] ); + } + break; + case QEvent::KeyPress: + case QEvent::KeyRelease: + { + QKeyEvent* keyEvent = static_cast( event ); + fillKeyCodeString( keyEvent->key(), args[0] ); + fillKeyboardModifiers( keyEvent->modifiers(), args[1] ); + } + break; + case QEvent::Wheel: + { + QWheelEvent* wheelEvent = static_cast( event ); + + // extract position (x and y ), delta, modifiers + const QPoint& pos = wheelEvent->pos(); + args[0].set( pos.x() ); + args[1].set( pos.x() ); + args[2].set( wheelEvent->delta() ); + fillKeyboardModifiers( wheelEvent->modifiers(), args[3] ); + } + break; + case QEvent::Resize: + { + QResizeEvent* resizeEvent = static_cast( event ); + + // extract size (width and height) and oldSize (width and height) + const QSize& size = resizeEvent->size(); + const QSize& oldSize = resizeEvent->oldSize(); + args[0].set( size.width() ); + args[1].set( size.height() ); + args[2].set( oldSize.width() ); + args[3].set( oldSize.height() ); + } + break; + default: + // Close, Show and Hide require no arguments + return; + } +} + +bool EventHub::isObjectFiltered( QObject* watched ) +{ + return _filteredObjects.find( watched ) != _filteredObjects.end(); +} + +QMetaEnum EventHub::createKeyMetaEnum() +{ + const QMetaObject &mo = EventHub::staticMetaObject; + int prop_index = mo.indexOfProperty( "_qtKeyEnum" ); + QMetaProperty metaProperty = mo.property( prop_index ); + return metaProperty.enumerator(); +} diff --git a/pool/shard009/C++/0110177_filter_analyzer.cc b/pool/shard009/C++/0110177_filter_analyzer.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b890d74746c9de1bccfc5f2ae3134803bc31bd5 --- /dev/null +++ b/pool/shard009/C++/0110177_filter_analyzer.cc @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "modules/audio_processing/aec3/filter_analyzer.h" +#include + +#include +#include +#include + +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" +#include "rtc_base/atomicops.h" +#include "rtc_base/checks.h" +#include "system_wrappers/include/field_trial.h" + +namespace webrtc { +namespace { + +size_t FindPeakIndex(rtc::ArrayView filter_time_domain) { + size_t peak_index = 0; + float max_h2 = filter_time_domain[0] * filter_time_domain[0]; + for (size_t k = 1; k < filter_time_domain.size(); ++k) { + float tmp = filter_time_domain[k] * filter_time_domain[k]; + if (tmp > max_h2) { + peak_index = k; + max_h2 = tmp; + } + } + + return peak_index; +} + +bool EnableFilterPreprocessing() { + return !field_trial::IsEnabled( + "WebRTC-Aec3FilterAnalyzerPreprocessorKillSwitch"); +} + +} // namespace + +int FilterAnalyzer::instance_count_ = 0; + +FilterAnalyzer::FilterAnalyzer(const EchoCanceller3Config& config) + : data_dumper_( + new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + use_preprocessed_filter_(EnableFilterPreprocessing()), + bounded_erl_(config.ep_strength.bounded_erl), + default_gain_(config.ep_strength.lf), + active_render_threshold_(config.render_levels.active_render_limit * + config.render_levels.active_render_limit * + kFftLengthBy2), + h_highpass_(GetTimeDomainLength(config.filter.main.length_blocks), 0.f), + filter_length_blocks_(config.filter.main_initial.length_blocks) { + Reset(); +} + +void FilterAnalyzer::PreProcessFilter( + rtc::ArrayView filter_time_domain) { + RTC_DCHECK_GE(h_highpass_.capacity(), filter_time_domain.size()); + h_highpass_.resize(filter_time_domain.size()); + // Minimum phase high-pass filter with cutoff frequency at about 600 Hz. + constexpr std::array h = {{0.7929742f, -0.36072128f, -0.47047766f}}; + + std::fill(h_highpass_.begin(), h_highpass_.end(), 0.f); + for (size_t k = h.size() - 1; k < filter_time_domain.size(); ++k) { + for (size_t j = 0; j < h.size(); ++j) { + h_highpass_[k] += filter_time_domain[k - j] * h[j]; + } + } +} + +FilterAnalyzer::~FilterAnalyzer() = default; + +void FilterAnalyzer::Reset() { + delay_blocks_ = 0; + consistent_estimate_ = false; + blocks_since_reset_ = 0; + consistent_estimate_ = false; + consistent_estimate_counter_ = 0; + consistent_delay_reference_ = -10; + gain_ = default_gain_; +} + +void FilterAnalyzer::Update( + rtc::ArrayView filter_time_domain, + const std::vector>& + filter_freq_response, + const RenderBuffer& render_buffer) { + // Preprocess the filter to avoid issues with low-frequency components in the + // filter. + PreProcessFilter(filter_time_domain); + data_dumper_->DumpRaw("aec3_linear_filter_processed_td", h_highpass_); + + const auto& filter_to_analyze = + use_preprocessed_filter_ ? h_highpass_ : filter_time_domain; + RTC_DCHECK_EQ(filter_to_analyze.size(), filter_time_domain.size()); + + size_t peak_index = FindPeakIndex(filter_to_analyze); + delay_blocks_ = peak_index >> kBlockSizeLog2; + UpdateFilterGain(filter_to_analyze, peak_index); + + float filter_floor = 0; + float filter_secondary_peak = 0; + size_t limit1 = peak_index < 64 ? 0 : peak_index - 64; + size_t limit2 = + peak_index > filter_to_analyze.size() - 129 ? 0 : peak_index + 128; + + for (size_t k = 0; k < limit1; ++k) { + float abs_h = fabsf(filter_to_analyze[k]); + filter_floor += abs_h; + filter_secondary_peak = std::max(filter_secondary_peak, abs_h); + } + for (size_t k = limit2; k < filter_to_analyze.size(); ++k) { + float abs_h = fabsf(filter_to_analyze[k]); + filter_floor += abs_h; + filter_secondary_peak = std::max(filter_secondary_peak, abs_h); + } + + filter_floor /= (limit1 + filter_to_analyze.size() - limit2); + + float abs_peak = fabsf(filter_to_analyze[peak_index]); + bool significant_peak_index = + abs_peak > 10.f * filter_floor && abs_peak > 2.f * filter_secondary_peak; + + if (consistent_delay_reference_ != delay_blocks_ || !significant_peak_index) { + consistent_estimate_counter_ = 0; + consistent_delay_reference_ = delay_blocks_; + } else { + const auto& x = render_buffer.Block(-delay_blocks_)[0]; + const float x_energy = + std::inner_product(x.begin(), x.end(), x.begin(), 0.f); + const bool active_render_block = x_energy > active_render_threshold_; + + if (active_render_block) { + ++consistent_estimate_counter_; + } + } + + consistent_estimate_ = + consistent_estimate_counter_ > 1.5f * kNumBlocksPerSecond; + + filter_length_blocks_ = filter_time_domain.size() * (1.f / kBlockSize); +} + +void FilterAnalyzer::UpdateFilterGain( + rtc::ArrayView filter_time_domain, + size_t peak_index) { + bool sufficient_time_to_converge = + ++blocks_since_reset_ > 5 * kNumBlocksPerSecond; + + if (sufficient_time_to_converge && consistent_estimate_) { + gain_ = fabsf(filter_time_domain[peak_index]); + } else { + if (gain_) { + gain_ = std::max(gain_, fabsf(filter_time_domain[peak_index])); + } + } + + if (bounded_erl_ && gain_) { + gain_ = std::max(gain_, 0.01f); + } +} + +} // namespace webrtc diff --git a/pool/shard009/C++/0110179_ROOM.cpp b/pool/shard009/C++/0110179_ROOM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f72a92cd0637f1543b20291c7e7624aa72386ab8 --- /dev/null +++ b/pool/shard009/C++/0110179_ROOM.cpp @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include "ROOM.h" +#include +#include + +//#define DEBUG +#define AVERAGE_CHANS -1 /* average input chans flag value */ + + +ROOM::ROOM() : Instrument() +{ + in = NULL; + echo = NULL; + branch = 0; +} + + +ROOM::~ROOM() +{ + delete [] in; + delete [] echo; +} + + +int ROOM::init(double p[], int n_args) +{ + float outskip = p[0]; + float inskip = p[1]; + float dur = p[2]; + amp = p[3]; + inchan = n_args > 4 ? (int)p[4] : AVERAGE_CHANS; + + if (outputchans != 2) + return die("ROOM", "Output must be stereo."); + + if (rtsetinput(inskip, this) == -1) + return DONT_SCHEDULE; + insamps = (int) (dur * SR + 0.5); + + if (inchan >= inputChannels()) + return die("ROOM", "You asked for channel %d of a %d-channel input file.", + inchan, inputChannels()); + if (inputChannels() == 1) + inchan = 0; + + nmax = get_room(ipoint, lamp, ramp, SR); + if (nmax == 0) + return die("ROOM", "You need to call roomset before ROOM."); + + echo = new float[nmax]; + for (int i = 0; i < nmax; i++) + echo[i] = 0.0; + jpoint = 0; + +#ifdef DEBUG + printf("maximum delay = %d samples.\n", nmax); +#endif + + float ringdur = (float) nmax / SR; + if (rtsetoutput(outskip, dur + ringdur, this) == -1) + return DONT_SCHEDULE; + + amparray = floc(1); + if (amparray) { + int amplen = fsize(1); + tableset(SR, dur + ringdur, amplen, amptabs); + } + else + rtcmix_advise("ROOM", "Setting phrase curve to all 1's."); + aamp = amp; /* in case amparray == NULL */ + + skip = (int)(SR / (float)resetval); + + return nSamps(); +} + + +int ROOM::configure() +{ + in = new float [RTBUFSAMPS * inputChannels()]; + return in ? 0 : -1; +} + + +int ROOM::run() +{ + const int samps = framesToRun() * inputChannels(); + + rtgetin(in, this, samps); + + for (int i = 0; i < samps; i += inputChannels()) { + if (--branch <= 0) { + if (amparray) + aamp = tablei(currentFrame(), amparray, amptabs) * amp; + branch = skip; + } + + float insig; + if (currentFrame() < insamps) { /* still taking input */ + if (inchan == AVERAGE_CHANS) { + insig = 0.0; + for (int n = 0; n < inputChannels(); n++) + insig += in[i + n]; + insig /= (float) inputChannels(); + } + else + insig = in[i + inchan]; + } + else /* in ring-down phase */ + insig = 0.0; + + echo[jpoint++] = insig; + if (jpoint >= nmax) + jpoint -= nmax; + + float out[2]; + out[0] = out[1] = 0.0; + for (int j = 0; j < NTAPS; j++) { + float e = echo[ipoint[j]]; + out[0] += e * lamp[j]; + out[1] += e * ramp[j]; + ipoint[j]++; + if (ipoint[j] >= nmax) + ipoint[j] -= nmax; + } + + if (aamp != 1.0) { + out[0] *= aamp; + out[1] *= aamp; + } + + rtaddout(out); + increment(); + } + + return framesToRun(); +} + + +Instrument *makeROOM() +{ + ROOM *inst; + + inst = new ROOM(); + inst->set_bus_config("ROOM"); + + return inst; +} + +#ifndef EMBEDDED +void rtprofile() +{ + RT_INTRO("ROOM", makeROOM); +} +#endif diff --git a/pool/shard009/C++/0110183_gpu_stream_util.cc b/pool/shard009/C++/0110183_gpu_stream_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf988bd1309bcb2a7b8027f572cc14d8b342bcad --- /dev/null +++ b/pool/shard009/C++/0110183_gpu_stream_util.cc @@ -0,0 +1,116 @@ +/* Copyright 2015 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/core/common_runtime/gpu/gpu_stream_util.h" + +#include +#include +#include +#include + +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/strings/strcat.h" + +#ifdef _MSC_VER +#undef max +#endif + +namespace tensorflow { +namespace gpu_stream_util { + +Status AssignStreams(const Graph* graph, const AssignStreamsOpts& opts, + std::unordered_map* node_to_stream_id) { + VLOG(1) << "AssignStreams"; + Status status; + + // Sanity check arguments. + if (graph == nullptr) + status.Update(errors::InvalidArgument("Bad graph argument supplied.")); + if (node_to_stream_id == nullptr) { + status.Update( + errors::InvalidArgument("Bad node_to_stream_id argument supplied.")); + } + if ((opts.max_streams < 1) || (opts.send_stream >= opts.max_streams) || + (opts.recv_stream >= opts.max_streams) || + (opts.const_stream >= opts.max_streams) || + (opts.compute_stream >= opts.max_streams)) { + status.Update(errors::InvalidArgument("Bad graph argument supplied.")); + } + TF_RETURN_IF_ERROR(status); + + // Topologically sort the nodes. + std::vector order; + GetReversePostOrder(*graph, &order); + if (VLOG_IS_ON(2)) { + for (Node* n : order) { + const int node_id = n->id(); + VLOG(2) << "Node " << node_id << " " << n->type_string() << " " + << n->name() << " " << n->in_edges().size() << " inputs"; + for (const Edge* e : n->in_edges()) { + VLOG(2) << " Edge from " << e->src()->id() << " " << e->src()->name() + << " fanout " << e->src()->out_edges().size(); + } + } + } + // We perform stream assignment assuming a large number of + // stream IDs and then map these down to the required number of streams + // using simple round-robin. + // Stream Assignment strategy: + // 1. Nodes with zero inputs are always be executed on a + // fresh stream. + // 2. Try to execute a node on the same stream as one of its + // inputs to avoid inter-stream dependencies. + // 3. If any input comes from a node with a large fanout then + // perhaps an indication that it is shared between parallel + // streams of work. We choose a new stream here so that all consumers + // of the tensor are likely to run in parallel. + int highest_stream_id = -1; + for (Node* n : order) { + VLOG(3) << "Inspecting node " << n->DebugString(); + const int node_id = n->id(); + const string& op = n->type_string(); + + // Determine a suitable stream to use. + int stream_id = highest_stream_id + 1; + for (const Edge* e : n->in_edges()) { + const int fanout = e->src()->out_edges().size(); + if (fanout == 1) { + stream_id = (*node_to_stream_id)[e->src()->id()]; + break; + } + } + // Override stream for specific op types. + if (op == "_Send") { + if (opts.send_stream >= 0) stream_id = opts.send_stream; + } else if (op == "_Recv") { + if (opts.recv_stream >= 0) stream_id = opts.recv_stream; + } else if (op == "Const") { + if (opts.const_stream >= 0) stream_id = opts.const_stream; + } else { + if (opts.compute_stream >= 0) stream_id = opts.compute_stream; + } + + (*node_to_stream_id)[node_id] = stream_id % opts.max_streams; + highest_stream_id = std::max(stream_id, highest_stream_id); + } + VLOG(1) << "Identified " << highest_stream_id << " candidate streams for " + << order.size() << " nodes."; + + return Status::OK(); +} + +} // namespace gpu_stream_util +} // namespace tensorflow diff --git a/pool/shard009/C++/0110184_device_orientation_absolute_controller.cc b/pool/shard009/C++/0110184_device_orientation_absolute_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..810ee484c37943ee4f32bd98a69b013041c41480 --- /dev/null +++ b/pool/shard009/C++/0110184_device_orientation_absolute_controller.cc @@ -0,0 +1,89 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h" + +#include "third_party/blink/public/mojom/feature_policy/feature_policy_feature.mojom-blink.h" +#include "third_party/blink/renderer/core/frame/settings.h" +#include "third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" + +namespace blink { + +DeviceOrientationAbsoluteController::DeviceOrientationAbsoluteController( + LocalDOMWindow& window) + : DeviceOrientationController(window) {} + +DeviceOrientationAbsoluteController::~DeviceOrientationAbsoluteController() = + default; + +const char DeviceOrientationAbsoluteController::kSupplementName[] = + "DeviceOrientationAbsoluteController"; + +DeviceOrientationAbsoluteController& DeviceOrientationAbsoluteController::From( + LocalDOMWindow& window) { + DeviceOrientationAbsoluteController* controller = + Supplement::From( + window); + if (!controller) { + controller = + MakeGarbageCollected(window); + Supplement::ProvideTo(window, controller); + } + return *controller; +} + +void DeviceOrientationAbsoluteController::DidAddEventListener( + LocalDOMWindow* window, + const AtomicString& event_type) { + if (event_type != EventTypeName()) + return; + + // The window could be detached, e.g. if it is the `contentWindow` of an + //