diff --git a/pool/shard008/C++/0096630_multiprocess_test_helper.cc b/pool/shard008/C++/0096630_multiprocess_test_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..b462893ff6d28b728c61c286dc49162cd083b67a --- /dev/null +++ b/pool/shard008/C++/0096630_multiprocess_test_helper.cc @@ -0,0 +1,99 @@ +// Copyright 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 "third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h" + +#include "base/command_line.h" +#include "base/logging.h" +#include "base/process/kill.h" +#include "base/process/process_handle.h" +#include "build/build_config.h" +#include "third_party/mojo/src/mojo/edk/embedder/platform_channel_pair.h" + +namespace mojo { +namespace test { + +MultiprocessTestHelper::MultiprocessTestHelper() { + platform_channel_pair_.reset(new embedder::PlatformChannelPair()); + server_platform_handle = platform_channel_pair_->PassServerHandle(); +} + +MultiprocessTestHelper::~MultiprocessTestHelper() { + CHECK(!test_child_.IsValid()); + server_platform_handle.reset(); + platform_channel_pair_.reset(); +} + +void MultiprocessTestHelper::StartChild(const std::string& test_child_name) { + StartChildWithExtraSwitch(test_child_name, std::string(), std::string()); +} + +void MultiprocessTestHelper::StartChildWithExtraSwitch( + const std::string& test_child_name, + const std::string& switch_string, + const std::string& switch_value) { + CHECK(platform_channel_pair_); + CHECK(!test_child_name.empty()); + CHECK(!test_child_.IsValid()); + + std::string test_child_main = test_child_name + "TestChildMain"; + + base::CommandLine command_line( + base::GetMultiProcessTestChildBaseCommandLine()); + embedder::HandlePassingInformation handle_passing_info; + platform_channel_pair_->PrepareToPassClientHandleToChildProcess( + &command_line, &handle_passing_info); + + if (!switch_string.empty()) { + CHECK(!command_line.HasSwitch(switch_string)); + if (!switch_value.empty()) + command_line.AppendSwitchASCII(switch_string, switch_value); + else + command_line.AppendSwitch(switch_string); + } + + base::LaunchOptions options; +#if defined(OS_POSIX) + options.fds_to_remap = &handle_passing_info; +#elif defined(OS_WIN) + options.start_hidden = true; + options.handles_to_inherit = &handle_passing_info; +#else +#error "Not supported yet." +#endif + + test_child_ = + base::SpawnMultiProcessTestChild(test_child_main, command_line, options); + platform_channel_pair_->ChildProcessLaunched(); + + CHECK(test_child_.IsValid()); +} + +int MultiprocessTestHelper::WaitForChildShutdown() { + CHECK(test_child_.IsValid()); + + int rv = -1; + CHECK( + test_child_.WaitForExitWithTimeout(TestTimeouts::action_timeout(), &rv)); + test_child_.Close(); + return rv; +} + +bool MultiprocessTestHelper::WaitForChildTestShutdown() { + return WaitForChildShutdown() == 0; +} + +// static +void MultiprocessTestHelper::ChildSetup() { + CHECK(base::CommandLine::InitializedForCurrentProcess()); + client_platform_handle = + embedder::PlatformChannelPair::PassClientHandleFromParentProcess( + *base::CommandLine::ForCurrentProcess()); +} + +// static +embedder::ScopedPlatformHandle MultiprocessTestHelper::client_platform_handle; + +} // namespace test +} // namespace mojo diff --git a/pool/shard008/C++/0096632_aoj1275_3.cpp b/pool/shard008/C++/0096632_aoj1275_3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0983b818f0279e16f5536a80ddb9fecf730da29 --- /dev/null +++ b/pool/shard008/C++/0096632_aoj1275_3.cpp @@ -0,0 +1,23 @@ +#include + +using namespace std; +#define FOR(i,s,x) for(int i=s;i<(int)(x);i++) +#define REP(i,x) FOR(i,0,x) + +int main() { + // use scanf in CodeForces! + cin.tie(0); + ios_base::sync_with_stdio(false); + while (1) { + int N, K, M; cin >> N >> K >> M; + if (N == 0 and K == 0 and M == 0) break; + M--; + vector stones(N); REP(i, N) stones[i] = i; + while (stones.size() > 1) { + stones.erase(stones.begin() + M); + M = (M + K - 1 + stones.size()) % stones.size(); + } + cout << stones[0] + 1 << endl; + } + return 0; +} diff --git a/pool/shard008/C++/0096635_ToolWorld.cpp b/pool/shard008/C++/0096635_ToolWorld.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1bba9f86669bd324d01b0c741bee4632c6ad61db --- /dev/null +++ b/pool/shard008/C++/0096635_ToolWorld.cpp @@ -0,0 +1,72 @@ +/* + * ToolWorld.cpp + * + * Created on: Jul 4, 2015 + * Author: dwarf + */ + +#include +#include "World.h" +#include "Mouse.h" +#include "CoordinateConverter.h" +#include + +namespace gui { + +ToolWorld::ToolWorld() : path("./level/lvl1"), width(0), height(0){ + +} + +ToolWorld::~ToolWorld() { +} + +void ToolWorld::begin(float x, float y, int button){ + if(button == 1){ + game::world::loadWorld(path, x, y); + } + else if(button == 3){ + game::world::unloadWorld(x, y); + } + + +} + +void ToolWorld::step(float x, float y, int button){ +} + +void ToolWorld::stop(float x, float y, int button){ + +} + +std::string ToolWorld::getName(){ + return "World"; +} + +std::string ToolWorld::setParameter(std::string name, std::string value){ + if(name == "path"){ + path = value; + std::pair p = game::world::getWorldSizeFromFile(path); + width = p.first; + height = p.second; + return "set path"; + } + else{ + return "options: path"; + } +} + +void ToolWorld::render(float upateFactor){ + + float *f = getMousePosition(); + float *v = screenToWorldSpace(f[0], f[1]); + float x, y; + x = floor(v[0]); + y = floor(v[1]); + + render::drawRect(x + width / 2, y + height / 2, width, height, 0, toolOverlayColor); + + delete[] v; + +} + +} /* namespace gui */ diff --git a/pool/shard008/C++/0096639_gf2m.cpp b/pool/shard008/C++/0096639_gf2m.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f4b5605279b5a82dc21b0a618358a769cd3d00a --- /dev/null +++ b/pool/shard008/C++/0096639_gf2m.cpp @@ -0,0 +1,132 @@ + +/* + * This file is part of Codecrypt. + * + * Codecrypt 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. + * + * Codecrypt 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 Codecrypt. If not, see . + */ + +#include "gf2m.h" + +/* + * helpful stuff for arithmetic in GF(2^m) - polynomials over GF(2). + */ + +int gf2p_degree (uint p) +{ + int r = 0; + while (p) { + ++r; + p >>= 1; + } + return r - 1; +} + +uint gf2p_mod (uint a, uint p) +{ + if (!p) return 0; + int t, degp = gf2p_degree (p); + while ( (t = gf2p_degree (a) ) >= degp) { + a ^= (p << (t - degp) ); + } + return a; +} + +uint gf2p_gcd (uint a, uint b) +{ + uint c; + if (!a) return b; + while (b) { + c = gf2p_mod (a, b); + a = b; + b = c; + } + return a; +} + +uint gf2p_modmult (uint a, uint b, uint p) +{ + a = gf2p_mod (a, p); + b = gf2p_mod (b, p); + uint r = 0; + uint d = 1 << gf2p_degree (p); + if (b) while (a) { + if (a & 1) r ^= b; + a >>= 1; + b <<= 1; + if (b >= d) b ^= p; + } + return r; +} + +bool is_irreducible_gf2_poly (uint p) +{ + if (!p) return false; + int d = gf2p_degree (p) / 2; + uint test = 2; //x^1+0 + for (int i = 1; i <= d; ++i) { + test = gf2p_modmult (test, test, p); + + if (gf2p_gcd (test ^ 2 /* test - x^1 */, p) != 1) + return false; + } + return true; +} + +bool gf2m::create (uint M) +{ + if (M < 1) return false; //too small. + m = M; + n = 1 << m; + if (!n) return false; //too big. + poly = 0; + + /* + * find a conway polynomial for given degree. First we "filter out" the + * possibilities that cannot be conway (reducible ones), then we check + * that Z2[x]/poly is a field. + */ + for (uint t = (1 << m) + 1, e = 1 << (m + 1); t < e; t += 2) { + + if (!is_irreducible_gf2_poly (t) ) continue; + + //try to prepare log and antilog tables + log.resize (n, 0); + antilog.resize (n, 0); + log[0] = n - 1; + antilog[n - 1] = 0; + + uint i, xi = 1; //x^0 + for (i = 0; i < n - 1; ++i) { + if (log[xi] != 0) { //not a cyclic group + log.clear(); + antilog.clear(); + break; + } + log[xi] = i; + antilog[i] = xi; + + xi <<= 1; //multiply by x + xi = gf2p_mod (xi, t); + } + + //if it broke... + if (i < n - 1) continue; + poly = t; + break; + } + + if (!poly) return false; + + return true; +} diff --git a/pool/shard008/C++/0096640_test_photos.cpp b/pool/shard008/C++/0096640_test_photos.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc48a5b0097517080ec42cd2efc1566281119881 --- /dev/null +++ b/pool/shard008/C++/0096640_test_photos.cpp @@ -0,0 +1,110 @@ +/* + * Unit tests for libkvkontakte. + * Copyright (C) 2015 Alexander Potashev + * + * 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 "test_photos.h" + +#include +#include +#include +#include + +#include + +#include + +#define ALBUM1_NAME "__album for unit testing of libkvkontakte #1" + +using namespace Vkontakte; + +TestPhotos::TestPhotos() + : VkTestBase() + , m_albumId(-1) + , m_photoId(-1) +{ +} + +void TestPhotos::initTestCase() +{ + authenticate(AppPermissions::Photos); + + // Create album for testing + CreateAlbumJob* const albumJob = new CreateAlbumJob( + accessToken(), ALBUM1_NAME, QString("Description for %1").arg(ALBUM1_NAME), + AlbumInfo::PRIVACY_PRIVATE, AlbumInfo::PRIVACY_PRIVATE); + albumJob->exec(); + QVERIFY(!albumJob->error()); + + m_albumId = albumJob->album()->aid(); + + // Upload photo for testing + UploadPhotosJob* const job = new UploadPhotosJob( + accessToken(), + QStringList() << QString(AUTOTESTS_DATA_DIR) + "/image1.png", + true, m_albumId); + job->exec(); + QVERIFY(!job->error()); + + QList list = job->list(); + QCOMPARE(list.size(), 1); + + const PhotoInfoPtr photo = list.at(0); + m_photoId = photo->pid(); +} + +void TestPhotos::testPhotoListJob() +{ + PhotoListJob* const job = new PhotoListJob( + accessToken(), 0, m_albumId, QIntList() << m_photoId); + job->exec(); + QVERIFY(!job->error()); + + QList list = job->list(); + QCOMPARE(list.size(), 1); + + const PhotoInfoPtr photo = list.at(0); + QCOMPARE(photo->pid(), m_photoId); + + // Download the image + PhotoJob* const photoJob = new PhotoJob(photo->src()); + photoJob->exec(); + QVERIFY(!photoJob->error()); + + QImage image = photoJob->photo(); + QCOMPARE(image.size(), QSize(10, 10)); +} + +void TestPhotos::testUploadMultiple() +{ + // Upload multiple photos at once + const int count = 10; + + QStringList files; + for (int i = 0; i < count; ++i) + files << QString(AUTOTESTS_DATA_DIR) + "/image1.png"; + + UploadPhotosJob* const job = new UploadPhotosJob( + accessToken(), files, true, m_albumId); + job->exec(); + QVERIFY(!job->error()); + + QList list = job->list(); + QCOMPARE(list.size(), count); +} + +QTEST_KDEMAIN(TestPhotos, GUI) diff --git a/pool/shard008/C++/0096642_storage_notification_service_impl.cc b/pool/shard008/C++/0096642_storage_notification_service_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..62c1950144a435848045e4d0c83b1036a3014a0f --- /dev/null +++ b/pool/shard008/C++/0096642_storage_notification_service_impl.cc @@ -0,0 +1,52 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/storage/storage_notification_service_impl.h" + +#include "base/command_line.h" +#include "base/strings/string_number_conversions.h" +#include "base/time/time.h" +#include "build/build_config.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/chrome_switches.h" + +#if !defined(OS_ANDROID) +#include "chrome/browser/ui/storage_pressure_bubble.h" +#endif + +namespace { + +// Minimum interval between consecutive storage pressure notifications. +const base::TimeDelta kDiskPressureNotificationInterval = base::Days(1); + +const base::TimeDelta GetThrottlingInterval() { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + int int_value; + if (command_line->HasSwitch(switches::kStoragePressureNotificationInterval)) { + const std::string string_value = command_line->GetSwitchValueASCII( + switches::kStoragePressureNotificationInterval); + if (base::StringToInt(string_value, &int_value) && int_value >= 0) { + return base::Minutes(int_value); + } + } + return kDiskPressureNotificationInterval; +} + +} // namespace + +void StorageNotificationServiceImpl::MaybeShowStoragePressureNotification( + const url::Origin origin) { + if (!disk_pressure_notification_last_sent_at_.is_null() && + base::TimeTicks::Now() - disk_pressure_notification_last_sent_at_ < + GetThrottlingInterval()) { + return; + } + + chrome::ShowStoragePressureBubble(origin); + disk_pressure_notification_last_sent_at_ = base::TimeTicks::Now(); +} + +StorageNotificationServiceImpl::StorageNotificationServiceImpl() = default; + +StorageNotificationServiceImpl::~StorageNotificationServiceImpl() = default; diff --git a/pool/shard008/C++/0096648_mac_traj2_test.cc b/pool/shard008/C++/0096648_mac_traj2_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..700087bd259c856f18b5caa5f9f0901fb8f31807 --- /dev/null +++ b/pool/shard008/C++/0096648_mac_traj2_test.cc @@ -0,0 +1,137 @@ +/*********************************************************************** + + Copyright 2007-2010 Carnegie Mellon University and Intel Corporation + Author: Mike Vande Weghe + + This file is part of owd. + + owd 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. + + owd 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 "MacJointTraj.hh" +#include + +const double MacAccelElement::epsilon; + +int main(int argc, char **argv) { + if (argc < 2) { + printf("Usage: mac_traj_test \n"); + exit(1); + } + char *filename = argv[1]; + FILE *csv = fopen(filename,"r"); + if (!csv) { + printf("Cannot open csv file %s\n",argv[1]); + exit(1); + } + TrajPoint tp; + TrajType traj; + TrajType traj2; + tp.resize(2); + while (fscanf(csv,"%lf: %lf, %lf\n", + &tp.blend_radius, &tp[0],&tp[1]) == 3) { + traj.push_back(tp); + tp.blend_radius=0.0; + traj2.push_back(tp); + } + fclose(csv); + + // wipe out the previous output file, if any + unlink("traj.csv"); + + JointPos max_v; + +// max_v.push_back(40); +// max_v.push_back(30); +// max_v.push_back(30); +// max_v.push_back(60); +// max_v.push_back(80); +// max_v.push_back(80); +// max_v.push_back(90); + max_v.push_back(60); + max_v.push_back(120); + // max_v *= 4; + max_v *= 3.141592654/180; // degrees to radians + JointPos max_a(max_v); // accels as a function of vels + double max_j = max_a[0]*10.0; // jerk is 10x accel + + MacJointTraj *mjt,*mjt2; + try { + mjt = new MacJointTraj(traj,max_v,max_a,max_j,true,false,1); + mjt2= new MacJointTraj(traj2,max_v,max_a,max_j,true,false,1); + } catch (char *errstr) { + printf("Error: %s\n",errstr); + exit(1); + } + + printf("Trajectory computation done:\n"); + mjt->dump(); + + try { + FILE *csv = fopen("traj.csv","w"); + if (!csv) { + printf("Cannot output to traj.csv\n"); + exit(1); + } + double y[3],yd[3],ydd[3]; + double y2[3],yd2[3],ydd2[3]; + double delta_t = mjt->traj_duration/1000; + double elapsed_time=0; + double path_vel, path_accel, path_vel2, path_accel2; + double max_path_vel,max_path_accel; + mjt->run(); mjt2->run(); + mjt->evaluate(y,yd,ydd,0); + mjt2->evaluate(y2,yd2,ydd2,0); + mjt->get_path_values(&path_vel2,&path_accel2); + double y_sum = *y - *yd*delta_t; // initial position at -delta_t + double yd_sum = *yd - *ydd*delta_t; // initial velocity at -delta_t + while ((mjt->state() != MacJointTraj::DONE) + || (mjt2->state() != MacJointTraj::DONE)) { + y_sum += *(yd+1) * delta_t; // integrate the velocity + yd_sum += *(ydd+1) * delta_t; // integrate the acceleration + fprintf(csv,"%3.4f, ",elapsed_time); + for (unsigned int j=1; j<=max_v.size(); ++j) { + fprintf(csv,"%2.8f, ",y[j]); + } + for (unsigned int j=1; j<=max_v.size(); ++j) { + fprintf(csv,"%2.8f, ",yd[j]); + } + for (unsigned int j=1; j<=max_v.size(); ++j) { + fprintf(csv,"%2.8f, ",ydd[j]); + } + fprintf(csv,"%2.8f, ",y_sum); // double-check vs. y[0] + fprintf(csv,"%2.8f, ",yd_sum); // double_check vs. yd[0] + fprintf(csv,"%2.8f, %2.8f, ",path_vel, path_accel); + fprintf(csv,"%2.8f, %2.8f, %2.8f, ",max_path_vel, max_path_accel, -max_path_accel); + + fprintf(csv,"%2.8f, %2.8f, %2.8f, %2.8f\n", + y2[1],y2[2],path_vel2, path_accel2); + // next sample + mjt->evaluate(y,yd,ydd,delta_t); + mjt2->evaluate(y2,yd2,ydd2,delta_t); + mjt->get_path_values(&path_vel,&path_accel); + mjt2->get_path_values(&path_vel2,&path_accel2); + mjt->get_limits(&max_path_vel,&max_path_accel); + elapsed_time += delta_t; + } + fclose(csv); + } catch (char *errstr) { + printf("Error during eval loop: %s\n",errstr); + exit(1); + } + + exit(0); +} + diff --git a/pool/shard008/C++/0096655_boss_grobbulus.cpp b/pool/shard008/C++/0096655_boss_grobbulus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5d01c03edfc6ca8e0923bd4b69778aba93f7600 --- /dev/null +++ b/pool/shard008/C++/0096655_boss_grobbulus.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2011-2014 Project SkyFire + * Copyright (C) 2008-2014 TrinityCore + * Copyright (C) 2005-2014 MaNGOS + * Copyright (C) 2006-2014 ScriptDev2 + * + * 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 "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "naxxramas.h" +#include "SpellInfo.h" + +enum Spells +{ + SPELL_BOMBARD_SLIME = 28280, + SPELL_POISON_CLOUD = 28240, + SPELL_MUTATING_INJECTION = 28169, + SPELL_SLIME_SPRAY = 28157, + H_SPELL_SLIME_SPRAY = 54364, + SPELL_BERSERK = 26662, + SPELL_POISON_CLOUD_ADD = 59116 +}; + +enum Events +{ + EVENT_BERSERK = 1, + EVENT_CLOUD = 2, + EVENT_INJECT = 3, + EVENT_SPRAY = 4 +}; + +enum CreatureId +{ + NPC_FALLOUT_SLIME = 16290 +}; + +class boss_grobbulus : public CreatureScript +{ +public: + boss_grobbulus() : CreatureScript("boss_grobbulus") { } + + CreatureAI* GetAI(Creature* creature) const OVERRIDE + { + return new boss_grobbulusAI(creature); + } + + struct boss_grobbulusAI : public BossAI + { + boss_grobbulusAI(Creature* creature) : BossAI(creature, BOSS_GROBBULUS) + { + me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_POISON_CLOUD_ADD, true); + } + + void EnterCombat(Unit* /*who*/) OVERRIDE + { + _EnterCombat(); + events.ScheduleEvent(EVENT_CLOUD, 15000); + events.ScheduleEvent(EVENT_INJECT, 20000); + events.ScheduleEvent(EVENT_SPRAY, 15000+rand()%15000); //not sure + events.ScheduleEvent(EVENT_BERSERK, 12*60000); + } + + void SpellHitTarget(Unit* target, const SpellInfo* spell) OVERRIDE + { + if (spell->Id == uint32(SPELL_SLIME_SPRAY)) + { + if (TempSummon* slime = me->SummonCreature(NPC_FALLOUT_SLIME, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 0)) + DoZoneInCombat(slime); + } + } + + void UpdateAI(uint32 diff) OVERRIDE + { + if (!UpdateVictim()) + return; + + events.Update(diff); + + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_CLOUD: + DoCastAOE(SPELL_POISON_CLOUD); + events.ScheduleEvent(EVENT_CLOUD, 15000); + return; + case EVENT_BERSERK: + DoCastAOE(SPELL_BERSERK); + return; + case EVENT_SPRAY: + DoCastAOE(SPELL_SLIME_SPRAY); + events.ScheduleEvent(EVENT_SPRAY, 15000+rand()%15000); + return; + case EVENT_INJECT: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1)) + if (!target->HasAura(SPELL_MUTATING_INJECTION)) + DoCast(target, SPELL_MUTATING_INJECTION); + events.ScheduleEvent(EVENT_INJECT, 8000 + uint32(120 * me->GetHealthPct())); + return; + } + } + + DoMeleeAttackIfReady(); + } + }; + +}; + +class npc_grobbulus_poison_cloud : public CreatureScript +{ +public: + npc_grobbulus_poison_cloud() : CreatureScript("npc_grobbulus_poison_cloud") { } + + CreatureAI* GetAI(Creature* creature) const OVERRIDE + { + return new npc_grobbulus_poison_cloudAI(creature); + } + + struct npc_grobbulus_poison_cloudAI : public ScriptedAI + { + npc_grobbulus_poison_cloudAI(Creature* creature) : ScriptedAI(creature) + { + SetCombatMovement(false); + } + + uint32 Cloud_Timer; + + void Reset() OVERRIDE + { + Cloud_Timer = 1000; + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + } + + void UpdateAI(uint32 diff) OVERRIDE + { + if (Cloud_Timer <= diff) + { + DoCast(me, SPELL_POISON_CLOUD_ADD); + Cloud_Timer = 10000; + } else Cloud_Timer -= diff; + } + }; + +}; + +void AddSC_boss_grobbulus() +{ + new boss_grobbulus(); + new npc_grobbulus_poison_cloud(); +} diff --git a/pool/shard008/C++/0096661_loop_tests.cpp b/pool/shard008/C++/0096661_loop_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d1837a0baedc12591f92c8f0f8ea83d0aa44ab0 --- /dev/null +++ b/pool/shard008/C++/0096661_loop_tests.cpp @@ -0,0 +1,138 @@ +// 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 +#include + +#include +#include +#include +#include + +using process::Break; +using process::Continue; +using process::ControlFlow; +using process::Future; +using process::loop; +using process::Promise; +using process::Queue; + +using std::string; + + +TEST(LoopTest, Sync) +{ + std::atomic_int value = ATOMIC_VAR_INIT(1); + + Future future = loop( + [&]() { + return value.load(); + }, + [](int i) -> ControlFlow { + if (i != 0) { + return Continue(); + } + return Break(); + }); + + EXPECT_TRUE(future.isPending()); + + value.store(0); + + AWAIT_READY(future); +} + + +TEST(LoopTest, Async) +{ + Queue queue; + + Promise promise1; + Promise promise2; + + Future future = loop( + [&]() { + return queue.get(); + }, + [&](int i) { + promise1.set(i); + return promise2.future() + .then([](const string& s) -> ControlFlow { + return Break(s); + }); + }); + + EXPECT_TRUE(future.isPending()); + + queue.put(1); + + AWAIT_EQ(1, promise1.future()); + + EXPECT_TRUE(future.isPending()); + + string s = "Hello world!"; + + promise2.set(s); + + AWAIT_EQ(s, future); +} + + +TEST(LoopTest, DiscardIterate) +{ + Promise promise; + + promise.future().onDiscard([&]() { promise.discard(); }); + + Future future = loop( + [&]() { + return promise.future(); + }, + [&](int i) -> ControlFlow { + return Break(); + }); + + EXPECT_TRUE(future.isPending()); + + future.discard(); + + AWAIT_DISCARDED(future); + EXPECT_TRUE(promise.future().hasDiscard()); +} + + +TEST(LoopTest, DiscardBody) +{ + Promise promise; + + promise.future().onDiscard([&]() { promise.discard(); }); + + Future future = loop( + [&]() { + return 42; + }, + [&](int i) { + return promise.future() + .then([]() -> ControlFlow { + return Break(); + }); + }); + + EXPECT_TRUE(future.isPending()); + + future.discard(); + + AWAIT_DISCARDED(future); + EXPECT_TRUE(promise.future().hasDiscard()); +} diff --git a/pool/shard008/C++/0096662_CWE190_Integer_Overflow__short_fscanf_multiply_84a.cpp b/pool/shard008/C++/0096662_CWE190_Integer_Overflow__short_fscanf_multiply_84a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1531ef5608366b1cd4c3eea3b8baf7c13deaf030 --- /dev/null +++ b/pool/shard008/C++/0096662_CWE190_Integer_Overflow__short_fscanf_multiply_84a.cpp @@ -0,0 +1,92 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__short_fscanf_multiply_84a.cpp +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-84a.tmpl.cpp +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: multiply + * GoodSink: Ensure there will not be an overflow before multiplying data by 2 + * BadSink : If data is positive, multiply by 2, which can cause an overflow + * 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 "CWE190_Integer_Overflow__short_fscanf_multiply_84.h" + +namespace CWE190_Integer_Overflow__short_fscanf_multiply_84 +{ + +#ifndef OMITBAD + +void bad() +{ + short data; + data = 0; + CWE190_Integer_Overflow__short_fscanf_multiply_84_bad * badObject = new CWE190_Integer_Overflow__short_fscanf_multiply_84_bad(data); + delete badObject; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + short data; + data = 0; + CWE190_Integer_Overflow__short_fscanf_multiply_84_goodG2B * goodG2BObject = new CWE190_Integer_Overflow__short_fscanf_multiply_84_goodG2B(data); + delete goodG2BObject; +} + +/* goodG2B uses the BadSource with the GoodSink */ +static void goodB2G() +{ + short data; + data = 0; + CWE190_Integer_Overflow__short_fscanf_multiply_84_goodB2G * goodB2GObject = new CWE190_Integer_Overflow__short_fscanf_multiply_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 CWE190_Integer_Overflow__short_fscanf_multiply_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/shard008/C++/0096663_TestApplication.cpp b/pool/shard008/C++/0096663_TestApplication.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd01b9b85de5b994a4f38fa3f82ac802c458df2c --- /dev/null +++ b/pool/shard008/C++/0096663_TestApplication.cpp @@ -0,0 +1,64 @@ +// TestApplication.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include +#include + +#include "../TelemetryProvider/MappedTelemetryData.h" + +float MetersPerSecondToKilometersPerHour(float metersPerSecond) +{ + return metersPerSecond * 3.6f; +} + +void DisplaySpeedFromMappedFile() +{ + auto mappedFile = CreateFileMapping( + INVALID_HANDLE_VALUE, // use paging file + NULL, // default security + PAGE_READWRITE, // read/write access + 0, // maximum object size (high-order DWORD) + sizeof(MappedTelemetryData), // maximum object size (low-order DWORD) + L"SCS_Telemetry_Data_OG"); // name of mapping object + + while (true) + { + auto filePtr = MapViewOfFile(mappedFile, FILE_MAP_READ, 0, 0, sizeof(MappedTelemetryData)); + + MappedTelemetryData* data = (MappedTelemetryData*)filePtr; + + if (data->gamePaused) + { + std::cout << "The game is paused ..." << std::endl; + } + else + { + std::cout << "You're driving " << MetersPerSecondToKilometersPerHour(data->speed) << " kph" << std::endl; + } + + UnmapViewOfFile(filePtr); + + Sleep(20); + } + + CloseHandle(mappedFile); +} + +int _tmain(int argc, _TCHAR* argv[]) +{ + //auto mmf = new MemoryMappedFile(); + //auto mapped = mmf->IsFileMapped(); + + //MappedTelemetryData data; + //data.speed = 12.34f; + + //mmf->UpdateMappedFile(data); + + //delete mmf; + + while (true) + { + DisplaySpeedFromMappedFile(); + } +} diff --git a/pool/shard008/C++/0096664_main.cpp b/pool/shard008/C++/0096664_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6092659c2cea14c774dbb5f441581a4298bf7133 --- /dev/null +++ b/pool/shard008/C++/0096664_main.cpp @@ -0,0 +1,82 @@ + // This autogenerated skeleton file illustrates how to build a server. +// You should copy it to another filename to avoid overwriting it. + +#include "rsg/actor.hpp" +#include "rsg/mailbox.hpp" +#include "rsg/comm.hpp" +#include "rsg/host.hpp" +#include "../../../src/common.hpp" + +#include "xbt.h" +#include "simgrid/s4u.hpp" + +#include +#include +#include +#include +#include +#include + +#include // uuid class +#include // generators +#include // streaming operators etc. + +XBT_LOG_NEW_CATEGORY(RSG_THRIFT_CLIENT, "Remote SimGrid"); +XBT_LOG_NEW_DEFAULT_SUBCATEGORY(RSG_THRIFT_REMOTE_CLIENT, RSG_THRIFT_CLIENT , "RSG server (Remote SimGrid)"); + + +using boost::shared_ptr; +using namespace ::simgrid; + +#define UNUSED(x) (void)(x) + +class PidComp { + public: + PidComp(std::string name) : pName(name) {} + std::string pName; + int operator()(void * ) { + rsg::MailboxPtr mbox = rsg::Mailbox::byName(this->pName.c_str()); + int *pid = (int*) rsg::this_actor::recv(*mbox); + int id = rsg::this_actor::getPid(); + XBT_INFO("PidComp -> [%d:%d] %d",id, *pid ,id - *pid); + free(pid); + rsg::this_actor::quit(); + return 1; + } +}; + + +int Spwaner(void * ) { + rsg::HostPtr host1 = rsg::Host::by_name("host1"); + + for(int i = 0; i < 100; i++) { + std::string name = "PidComp" + std::to_string(i) + "__" + std::to_string(rsg::this_actor::getPid()); + rsg::MailboxPtr mbox = rsg::Mailbox::byName(name.c_str()); + + rsg::Actor* actor = rsg::Actor::createActor("hello" , host1 , PidComp(name), NULL); + int pid = actor->getPid(); + rsg::this_actor::send(*mbox, (char*) &(pid), sizeof(int)); + actor->join(); + delete actor; + + } + + rsg::this_actor::quit(); + return 1; +} + +int main(int argc, char **argv) { + rsg::HostPtr host1 = rsg::Host::by_name("host1"); + + for(int i = 0; i < 4; i++) { + rsg::Actor* actor = rsg::Actor::createActor("spawner" , host1 , Spwaner, NULL); + UNUSED(actor); + actor->join(); + delete actor; + } + + rsg::this_actor::sleep(1000); + rsg::this_actor::quit(); + + return 0; +} diff --git a/pool/shard008/C++/0096665_unsafe_test.cc b/pool/shard008/C++/0096665_unsafe_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b0cf235a6019a4907992777248f7957b12d5d3c --- /dev/null +++ b/pool/shard008/C++/0096665_unsafe_test.cc @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "art_method-inl.h" +#include "jni.h" +#include "mirror/array.h" +#include "mirror/class.h" +#include "mirror/class-inl.h" +#include "mirror/object-inl.h" +#include "scoped_thread_state_change.h" + +namespace art { + +extern "C" JNIEXPORT jint JNICALL Java_Main_vmArrayBaseOffset(JNIEnv* env, jclass, jobject classObj) { + ScopedObjectAccess soa(env); + mirror::Class* klass = soa.Decode(classObj); + return mirror::Array::DataOffset( + Primitive::ComponentSize(klass->GetComponentType()->GetPrimitiveType())).Int32Value(); +} + +extern "C" JNIEXPORT jint JNICALL Java_Main_vmArrayIndexScale(JNIEnv* env, jclass, jobject classObj) { + ScopedObjectAccess soa(env); + mirror::Class* klass = soa.Decode(classObj); + return Primitive::ComponentSize(klass->GetComponentType()->GetPrimitiveType()); +} + +} // namespace art diff --git a/pool/shard008/C++/0096666_get_numvols.cc b/pool/shard008/C++/0096666_get_numvols.cc new file mode 100644 index 0000000000000000000000000000000000000000..85c5dd1860b424320be97580d3f2c6db8f7b1d91 --- /dev/null +++ b/pool/shard008/C++/0096666_get_numvols.cc @@ -0,0 +1,73 @@ +/* + * @BEGIN LICENSE + * + * Psi4: an open-source quantum chemistry software package + * + * Copyright (c) 2007-2019 The Psi4 Developers. + * + * The copyrights for code used from other parties are included in + * the corresponding files. + * + * This file is part of Psi4. + * + * Psi4 is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * @END LICENSE + */ + +/*! + \file + \ingroup PSIO + */ + +#include "psi4/pragma.h" +PRAGMA_WARNING_PUSH +PRAGMA_WARNING_IGNORE_DEPRECATED_DECLARATIONS +#include +PRAGMA_WARNING_POP +#include +#include +#include "psi4/libpsio/psio.h" +#include "psi4/libpsio/psio.hpp" + +namespace psi { + +size_t PSIO::get_numvols(size_t unit) { + std::string charnum; + charnum = filecfg_kwd("PSI", "NVOLUME", unit); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + charnum = filecfg_kwd("PSI", "NVOLUME", -1); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + charnum = filecfg_kwd("DEFAULT", "NVOLUME", unit); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + charnum = filecfg_kwd("DEFAULT", "NVOLUME", -1); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + + // assume that the default has been provided already + abort(); +} + +size_t psio_get_numvols_default() { + std::string charnum; + + charnum = _default_psio_lib_->filecfg_kwd("PSI", "NVOLUME", -1); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + charnum = _default_psio_lib_->filecfg_kwd("DEFAULT", "NVOLUME", -1); + if (!charnum.empty()) return ((size_t)atoi(charnum.c_str())); + + // assume that the default has been provided already + abort(); +} + +} // namespace psi diff --git a/pool/shard008/C++/0096670_fetch.cpp b/pool/shard008/C++/0096670_fetch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4f3316f1dcc6b739cac65d2f2a574a8cc6079ad --- /dev/null +++ b/pool/shard008/C++/0096670_fetch.cpp @@ -0,0 +1,37 @@ +#include + +#include "ocilib.hpp" + +/* requires script demo/products.sql */ + +using namespace ocilib; + +int main(void) +{ + try + { + Environment::Initialize(); + + Connection con("db", "usr", "pwd"); + + Statement st(con); + st.Execute("select * from products"); + + Resultset rs = st.GetResultset(); + while (rs++) + { + std::cout << "code:" << rs.Get(1) << " name:" << rs.Get(2) << std::endl; + } + + std::cout << "=> Total fetched rows : " << rs.GetCount() << std::endl; + + } + catch (std::exception &ex) + { + std::cout << ex.what() << std::endl; + } + + Environment::Cleanup(); + + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C++/0096672_MediaFile.cpp b/pool/shard008/C++/0096672_MediaFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e2e83c917a7f57eb42bb9ce352e9111e0dea03c --- /dev/null +++ b/pool/shard008/C++/0096672_MediaFile.cpp @@ -0,0 +1,190 @@ +/***************************************************************************** + * Media Explorer + *****************************************************************************/ + +#include "stdafx.h" +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "Media.h" +#include "MediaFile.h" +#include "MediaFolder.h" +#include "database/SqliteTools.h" + +using mxp::policy::MediaFileTable; +const std::string MediaFileTable::Name = "MediaFile"; +const std::string MediaFileTable::PrimaryKeyColumn = "id_file"; +int64_t mxp::MediaFile::* const MediaFileTable::PrimaryKey = &mxp::MediaFile::m_id; + +mxp::MediaFile::MediaFile(MediaExplorerPtr ml, sqlite::Row& row) + : m_ml(ml) + , m_id{} + , m_mediaId{} + , m_mrl{} + , m_type{} + , m_lastModificationDate{} + , m_numServicesParsed{} + , m_folderId{} + , m_isPresent{} + , m_isRemovable{} { + row >> m_id + >> m_mediaId + >> m_mrl + >> m_type + >> m_lastModificationDate + >> m_numServicesParsed + >> m_folderId + >> m_isPresent + >> m_isRemovable; +} + +mxp::MediaFile::MediaFile(MediaExplorerPtr ml, int64_t mediaId, MediaFileType type, const fs::IFile& file, int64_t folderId, bool isRemovable) + : m_ml(ml) + , m_id(0) + , m_mediaId(mediaId) + , m_mrl(isRemovable == true ? file.GetName() : file.GetFullPath()) + , m_type(type) + , m_lastModificationDate(file.GetLastModificationDate()) + , m_numServicesParsed(0) + , m_folderId(folderId) + , m_isPresent(true) + , m_isRemovable(isRemovable) { +} + +int64_t mxp::MediaFile::Id() const { + return m_id; +} + +const std::string& mxp::MediaFile::GetMrl() const { + if (m_isRemovable == false) + return m_mrl; + + auto lock = m_fullPath.Lock(); + if (m_fullPath.IsCached()) + return m_fullPath; + + auto folder = MediaFolder::Fetch(m_ml, m_folderId); + if (folder == nullptr) + return m_mrl; + + m_fullPath = folder->path() + m_mrl; + + return m_fullPath; +} + +mxp::MediaFileType mxp::MediaFile::GetType() const { + return m_type; +} + +time_t mxp::MediaFile::LastModificationDate() const { + return m_lastModificationDate; +} + +void mxp::MediaFile::SetServicesParsedCount(unsigned int value) { + if(m_numServicesParsed == value) { + return; + } + + static const auto req = "UPDATE " + MediaFileTable::Name + " SET services_parsed_count=? WHERE " + MediaFileTable::PrimaryKeyColumn + "=?"; + if(sqlite::Tools::ExecuteUpdate(m_ml->GetConnection(), req, value, m_id) == false) { + return; + } + + m_numServicesParsed = value; +} + +unsigned int mxp::MediaFile::GetServicesParsedCount() const { + return m_numServicesParsed; +} + +std::shared_ptr mxp::MediaFile::GetMedia() const { + auto lock = m_media.Lock(); + if (m_media.IsCached() == false) { + m_media = Media::Fetch(m_ml, m_mediaId); + } + + return m_media.Get().lock(); +} + +bool mxp::MediaFile::Destroy() const { + return DatabaseHelpers::destroy(m_ml, m_id); +} + +bool mxp::MediaFile::CreateTable(DBConnection connection) noexcept { + static const auto req = "CREATE TABLE IF NOT EXISTS " + MediaFileTable::Name + "(" + + MediaFileTable::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT," + "media_id INT NOT NULL," + "mrl TEXT," + "type UNSIGNED INTEGER," + "last_modification_date UNSIGNED INT," + "services_parsed_count UNSIGNED INT NOT NULL DEFAULT 0," + "folder_id UNSIGNED INTEGER," + "is_present BOOLEAN NOT NULL DEFAULT 1," + "is_removable BOOLEAN NOT NULL," + "FOREIGN KEY (media_id) REFERENCES " + policy::MediaTable::Name + "(" + policy::MediaTable::PrimaryKeyColumn + ") ON DELETE CASCADE," + "FOREIGN KEY (folder_id) REFERENCES " + policy::MediaFolderTable::Name + "(" + policy::MediaFolderTable::PrimaryKeyColumn + ") ON DELETE CASCADE," + "UNIQUE(mrl, folder_id) ON CONFLICT FAIL" + ")"; + static const auto triggerReq = "CREATE TRIGGER IF NOT EXISTS is_folder_present AFTER UPDATE OF is_present ON " + + policy::MediaFolderTable::Name + + " BEGIN" + " UPDATE " + MediaFileTable::Name + " SET is_present = new.is_present WHERE folder_id = new.id_folder;" + " END"; + static const auto indexReq = "CREATE INDEX IF NOT EXISTS file_media_id_index ON " + MediaFileTable::Name + "(media_id)"; + + bool success; + try { + success = sqlite::Tools::ExecuteRequest(connection, req) && + sqlite::Tools::ExecuteRequest(connection, triggerReq) && + sqlite::Tools::ExecuteRequest(connection, indexReq); + } catch (std::exception& ex) { + LOG_ERROR("Failed to create table for ", policy::MediaTable::Name, ": ", ex.what()); + success = false; + } + + return success; +} + +std::shared_ptr mxp::MediaFile::Create(MediaExplorerPtr ml, int64_t mediaId, MediaFileType type, const fs::IFile& fileFs, int64_t folderId, bool isRemovable) noexcept { + std::shared_ptr self; + static const auto req = "INSERT INTO " + MediaFileTable::Name + "(media_id, mrl, type, folder_id, last_modification_date, is_removable) VALUES(?, ?, ?, ?, ?, ?)"; + + try { + self = std::make_shared(ml, mediaId, type, fileFs, folderId, isRemovable); + +#pragma warning( suppress : 4244 ) + if(insert(ml, self, req, mediaId, self->m_mrl, type, sqlite::ForeignKey(folderId), self->m_lastModificationDate, isRemovable) == false) { + self = nullptr; + } else { + self->m_fullPath = fileFs.GetFullPath(); + } + } catch (std::exception& ex) { + LOG_ERROR("Failed to create MediaFile: ", ex.what()); + self = nullptr; + } + + return self; +} + +std::shared_ptr mxp::MediaFile::FindByPath(MediaExplorerPtr ml, const std::string& path) { + static const auto req = "SELECT * FROM " + MediaFileTable::Name + " WHERE mrl = ?"; + auto file = Fetch(ml, req, path); + if(file == nullptr) + return nullptr; + // safety checks: since this only works for files on non removable devices, isPresent must be true + // and isRemovable must be false + assert(file->m_isPresent == true); + assert(file->m_isRemovable == false); + return file; +} + +std::shared_ptr mxp::MediaFile::FindByFileName(MediaExplorerPtr ml, const std::string& fileName, int64_t folderId) { + static const auto req = "SELECT * FROM " + MediaFileTable::Name + " WHERE mrl = ? AND folder_id = ?"; + auto file = Fetch(ml, req, fileName, folderId); + if(file == nullptr) + return nullptr; + + assert(file->m_isRemovable == true); + return file; +} diff --git a/pool/shard008/C++/0096675_console_reporter.cc b/pool/shard008/C++/0096675_console_reporter.cc new file mode 100644 index 0000000000000000000000000000000000000000..61c34da8227e852da51fe139032e25d5270fd82f --- /dev/null +++ b/pool/shard008/C++/0096675_console_reporter.cc @@ -0,0 +1,190 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "string_util.h" +#include "timers.h" + +namespace benchmark { + +bool ConsoleReporter::ReportContext(const Context& context) { + name_field_width_ = context.name_field_width; + printed_header_ = false; + prev_counters_.clear(); + + PrintBasicContext(&GetErrorStream(), context); + +#ifdef BENCHMARK_OS_WINDOWS + if ((output_options_ & OO_Color) && &std::cout != &GetOutputStream()) { + GetErrorStream() + << "Color printing is only supported for stdout on windows." + " Disabling color printing\n"; + output_options_ = static_cast< OutputOptions >(output_options_ & ~OO_Color); + } +#endif + + return true; +} + +void ConsoleReporter::PrintHeader(const Run& run) { + std::string str = FormatString("%-*s %13s %15s %12s", static_cast(name_field_width_), + "Benchmark", "Time", "CPU", "Iterations"); + if(!run.counters.empty()) { + if(output_options_ & OO_Tabular) { + for(auto const& c : run.counters) { + str += FormatString(" %10s", c.first.c_str()); + } + } else { + str += " UserCounters..."; + } + } + std::string line = std::string(str.length(), '-'); + GetOutputStream() << line << "\n" << str << "\n" << line << "\n"; +} + +void ConsoleReporter::ReportRuns(const std::vector& reports) { + for (const auto& run : reports) { + // print the header: + // --- if none was printed yet + bool print_header = !printed_header_; + // --- or if the format is tabular and this run + // has different fields from the prev header + print_header |= (output_options_ & OO_Tabular) && + (!internal::SameNames(run.counters, prev_counters_)); + if (print_header) { + printed_header_ = true; + prev_counters_ = run.counters; + PrintHeader(run); + } + // As an alternative to printing the headers like this, we could sort + // the benchmarks by header and then print. But this would require + // waiting for the full results before printing, or printing twice. + PrintRunData(run); + } +} + +static void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt, + ...) { + va_list args; + va_start(args, fmt); + out << FormatString(fmt, args); + va_end(args); +} + + +static std::string FormatTime(double time) { + // Align decimal places... + if (time < 1.0) { + return FormatString("%10.3f", time); + } + if (time < 10.0) { + return FormatString("%10.2f", time); + } + if (time < 100.0) { + return FormatString("%10.1f", time); + } + return FormatString("%10.0f", time); +} + +void ConsoleReporter::PrintRunData(const Run& result) { + typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...); + auto& Out = GetOutputStream(); + PrinterFn* printer = (output_options_ & OO_Color) ? + (PrinterFn*)ColorPrintf : IgnoreColorPrint; + auto name_color = + (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN; + printer(Out, name_color, "%-*s ", name_field_width_, + result.benchmark_name().c_str()); + + if (result.error_occurred) { + printer(Out, COLOR_RED, "ERROR OCCURRED: \'%s\'", + result.error_message.c_str()); + printer(Out, COLOR_DEFAULT, "\n"); + return; + } + + const double real_time = result.GetAdjustedRealTime(); + const double cpu_time = result.GetAdjustedCPUTime(); + const std::string real_time_str = FormatTime(real_time); + const std::string cpu_time_str = FormatTime(cpu_time); + + + if (result.report_big_o) { + std::string big_o = GetBigOString(result.complexity); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", real_time, big_o.c_str(), + cpu_time, big_o.c_str()); + } else if (result.report_rms) { + printer(Out, COLOR_YELLOW, "%10.0f %-4s %10.0f %-4s ", real_time * 100, "%", + cpu_time * 100, "%"); + } else if (result.run_type != Run::RT_Aggregate || + result.aggregate_unit == StatisticUnit::kTime) { + const char* timeLabel = GetTimeUnitString(result.time_unit); + printer(Out, COLOR_YELLOW, "%s %-4s %s %-4s ", real_time_str.c_str(), timeLabel, + cpu_time_str.c_str(), timeLabel); + } else { + assert(result.aggregate_unit == StatisticUnit::kPercentage); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", + (100. * result.real_accumulated_time), "%", + (100. * result.cpu_accumulated_time), "%"); + } + + if (!result.report_big_o && !result.report_rms) { + printer(Out, COLOR_CYAN, "%10lld", result.iterations); + } + + for (auto& c : result.counters) { + const std::size_t cNameLen = std::max(std::string::size_type(10), + c.first.length()); + std::string s; + const char* unit = ""; + if (result.run_type == Run::RT_Aggregate && + result.aggregate_unit == StatisticUnit::kPercentage) { + s = StrFormat("%.2f", 100. * c.second.value); + unit = "%"; + } else { + s = HumanReadableNumber(c.second.value, c.second.oneK); + if (c.second.flags & Counter::kIsRate) + unit = (c.second.flags & Counter::kInvert) ? "s" : "/s"; + } + if (output_options_ & OO_Tabular) { + printer(Out, COLOR_DEFAULT, " %*s%s", cNameLen - strlen(unit), s.c_str(), + unit); + } else { + printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), unit); + } + } + + if (!result.report_label.empty()) { + printer(Out, COLOR_DEFAULT, " %s", result.report_label.c_str()); + } + + printer(Out, COLOR_DEFAULT, "\n"); +} + +} // end namespace benchmark diff --git a/pool/shard008/C++/0096676_mock_media_stream_video_source.cc b/pool/shard008/C++/0096676_mock_media_stream_video_source.cc new file mode 100644 index 0000000000000000000000000000000000000000..24ec9b5434eec85ae9e1eabf33e8d8849c037048 --- /dev/null +++ b/pool/shard008/C++/0096676_mock_media_stream_video_source.cc @@ -0,0 +1,152 @@ +// 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 "third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h" + +#include "base/bind.h" +#include "base/location.h" +#include "base/task/single_thread_task_runner.h" +#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-blink.h" +#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" + +namespace blink { + +MockMediaStreamVideoSource::MockMediaStreamVideoSource() + : MockMediaStreamVideoSource(false) {} + +MockMediaStreamVideoSource::MockMediaStreamVideoSource( + bool respond_to_request_refresh_frame) + : MediaStreamVideoSource(scheduler::GetSingleThreadTaskRunnerForTesting()), + respond_to_request_refresh_frame_(respond_to_request_refresh_frame), + max_requested_height_(0), + max_requested_width_(0), + max_requested_frame_rate_(0.0), + attempted_to_start_(false) {} + +MockMediaStreamVideoSource::MockMediaStreamVideoSource( + const media::VideoCaptureFormat& format, + bool respond_to_request_refresh_frame) + : MediaStreamVideoSource(scheduler::GetSingleThreadTaskRunnerForTesting()), + format_(format), + respond_to_request_refresh_frame_(respond_to_request_refresh_frame), + max_requested_height_(format.frame_size.height()), + max_requested_width_(format.frame_size.width()), + max_requested_frame_rate_(format.frame_rate), + attempted_to_start_(false) {} + +MockMediaStreamVideoSource::~MockMediaStreamVideoSource() {} + +void MockMediaStreamVideoSource::StartMockedSource() { + DCHECK(attempted_to_start_); + attempted_to_start_ = false; + OnStartDone(mojom::blink::MediaStreamRequestResult::OK); +} + +void MockMediaStreamVideoSource::FailToStartMockedSource() { + DCHECK(attempted_to_start_); + attempted_to_start_ = false; + OnStartDone( + mojom::blink::MediaStreamRequestResult::TRACK_START_FAILURE_VIDEO); +} + +void MockMediaStreamVideoSource::RequestRefreshFrame() { + DCHECK(!frame_callback_.is_null()); + if (respond_to_request_refresh_frame_) { + const scoped_refptr frame = + media::VideoFrame::CreateColorFrame(format_.frame_size, 0, 0, 0, + base::TimeDelta()); + PostCrossThreadTask( + *io_task_runner(), FROM_HERE, + CrossThreadBindOnce(frame_callback_, frame, + std::vector>(), + base::TimeTicks())); + } + OnRequestRefreshFrame(); +} + +void MockMediaStreamVideoSource::OnHasConsumers(bool has_consumers) { + is_suspended_ = !has_consumers; +} + +VideoCaptureFeedbackCB MockMediaStreamVideoSource::GetFeedbackCallback() const { + return WTF::BindRepeating(&MockMediaStreamVideoSource::OnFrameFeedback, + WTF::Unretained(this)); +} + +base::WeakPtr MockMediaStreamVideoSource::GetWeakPtr() + const { + return weak_factory_.GetWeakPtr(); +} + +void MockMediaStreamVideoSource::DoChangeSource( + const MediaStreamDevice& new_device) { + ChangeSourceImpl(new_device); +} + +void MockMediaStreamVideoSource::StartSourceImpl( + VideoCaptureDeliverFrameCB frame_callback, + EncodedVideoFrameCB encoded_frame_callback) { + DCHECK(frame_callback_.is_null()); + DCHECK(encoded_frame_callback_.is_null()); + attempted_to_start_ = true; + frame_callback_ = std::move(frame_callback); + encoded_frame_callback_ = std::move(encoded_frame_callback); +} + +void MockMediaStreamVideoSource::StopSourceImpl() {} + +absl::optional +MockMediaStreamVideoSource::GetCurrentFormat() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return absl::optional(format_); +} + +absl::optional +MockMediaStreamVideoSource::GetCurrentCaptureParams() const { + media::VideoCaptureParams params; + params.requested_format = format_; + return params; +} + +void MockMediaStreamVideoSource::DeliverVideoFrame( + scoped_refptr frame) { + DCHECK(!is_stopped_for_restart_); + DCHECK(!frame_callback_.is_null()); + PostCrossThreadTask( + *io_task_runner(), FROM_HERE, + CrossThreadBindOnce(frame_callback_, std::move(frame), + std::vector>(), + base::TimeTicks())); +} + +void MockMediaStreamVideoSource::DeliverEncodedVideoFrame( + scoped_refptr frame) { + DCHECK(!is_stopped_for_restart_); + DCHECK(!encoded_frame_callback_.is_null()); + PostCrossThreadTask(*io_task_runner(), FROM_HERE, + CrossThreadBindOnce(encoded_frame_callback_, + std::move(frame), base::TimeTicks())); +} + +void MockMediaStreamVideoSource::StopSourceForRestartImpl() { + if (can_stop_for_restart_) + is_stopped_for_restart_ = true; + OnStopForRestartDone(is_stopped_for_restart_); +} + +void MockMediaStreamVideoSource::RestartSourceImpl( + const media::VideoCaptureFormat& new_format) { + DCHECK(is_stopped_for_restart_); + if (!can_restart_) { + OnRestartDone(false); + return; + } + is_stopped_for_restart_ = false; + format_ = new_format; + OnRestartDone(true); +} + +} // namespace blink diff --git a/pool/shard008/C++/0096679_exE.cpp b/pool/shard008/C++/0096679_exE.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba3e89b4af3d6f4c619c4f1a5ee8c09472c412e7 --- /dev/null +++ b/pool/shard008/C++/0096679_exE.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//tamanho maximo do numero analisado +#define MAX 2000000 + +using namespace std; + +//fila como variavel global +deque fila; +vector< deque > resposta; + + +void verifica(int ini, int aux){ + + //fazendo o for ate a quantidade maxima de vezes do mesmo i aparecer + for (int i = ini; i * i <= aux; i++){ + if (aux%i == 0) { + fila.push_back(i); + verifica(i, aux/i); + fila.pop_back(); + } + //caso nao seja divisivel, o for continua e vai para o proximo numero + } + //armazenar o ultimo antes de colocar no vector de fils + fila.push_back(aux); + resposta.push_back(fila); + fila.pop_back(); + +} + + +int main(int argc, char const *argv[]){ + + int num; + int aux; + int tam_total, tam_parcial; + int inicio_contagem; + + //analisando caso por caso até o zero + while(cin >> num){ + //parando quando achar o zero + if(num == 0){ + break; + } + //antes de comecar zera a fila + fila.clear(); + resposta.clear(); + //anotando o valor em uma variavel reserva + aux = num; + inicio_contagem = 2; + + //chama se tiver para fatorar + if(num < 2){ + //nao faz nada pois nao tem como fatorar + cout << "0" << endl; + }else{ + //chama a funcao recursiva + verifica(inicio_contagem, aux); + + tam_total = resposta.size(); + cout << tam_total - 1 << endl; + + //imprimir os valores + for(int i = 0; i < tam_total - 1; i++){ + //pegando o tamanho parcial + tam_parcial = resposta[i].size(); + for(int j = 0; j < tam_parcial; j++){ + //exibindo fila por fila salva no set + if(j > 0){ + cout << " " << resposta[i][j]; + }else{ + cout << resposta[i][j]; + } + } + //pula uma linha + cout << endl; + } + } + } + + + + + return 0; +} diff --git a/pool/shard008/C++/0096680_A.cpp b/pool/shard008/C++/0096680_A.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20e9c583abec61f4042a01addf97f81a4a2db152 --- /dev/null +++ b/pool/shard008/C++/0096680_A.cpp @@ -0,0 +1,103 @@ +#include +using namespace std; + +typedef long long ll; +#define INF 0x3f3f3f3f3f3f3f3f +#define MOD 1000000007 +#define rep(i,a,n) for (int i=a;i=a;i--) +#define pb push_back +#define foreach(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); ++ i) +const double pi = acos(-1.0); + +// r x c +// rice +// k chicken <= rice +// same chicken 连通图 + +int t; +int r,c,k; + +char farm[110][110]; +int ans[110][110]; + +// min(max rice- min rice) + +// 26*2+10 = 62 + +char s[]="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + +int minr ; +int maxr ; +int maxcnt ; +int mincnt ; +int nowcnt ; +int nowidx ; + + +void addnowidx(){ + if(nowidx+1 < k){ + nowidx++; + } +} + +void op(int i,int j){ + ans[i][j] = nowidx; + if(farm[i][j] !='R')return; + nowcnt++; + if(nowcnt <= minr*mincnt){ + if(nowcnt % minr != 0){ + return ; + } + addnowidx(); + }else{ + if((nowcnt-minr*mincnt) % maxr != 0){ + return ; + } + addnowidx(); + } +} + +int main(){ + cin>>t; + + while(t--){ + scanf("%d %d %d",&r,&c,&k); + int rice = 0; + rep(i,0,r){ + scanf("%s",farm[i]); + rep(j,0,c){ + rice+=farm[i][j] == 'R'; + } + } + minr = rice/k; // >= 1 + maxr = minr+ !!(rice%k); + maxcnt = rice%k; + mincnt = k-maxcnt; + assert(minr*mincnt+maxr*maxcnt == rice); + + // printf("m m m m = %d %d %d %d\n",minr,mincnt,maxr,maxcnt); + nowcnt = 0; + nowidx = 0; + rep(i,0,r){ + if(i %2 == 0){ + rep(j,0,c){ + op(i,j); + } + }else { + per(j,0,c){ + op(i,j); + } + } + } + rep(i,0,r){ + rep(j,0,c){ + printf("%c",s[ans[i][j]]); + } + printf("\n"); + } + } + + return 0; +} diff --git a/pool/shard008/C++/0096682_tst_qsysteminfo.cpp b/pool/shard008/C++/0096682_tst_qsysteminfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c229689fab56303ddff0db71fcbc31ddc8e3c1ef --- /dev/null +++ b/pool/shard008/C++/0096682_tst_qsysteminfo.cpp @@ -0,0 +1,297 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//TESTED_COMPONENT=src/systeminfo + +#include +#include "qsysteminfo.h" +#include "qsysteminfo_simulator_p.h" +#include + +QTM_USE_NAMESPACE +Q_DECLARE_METATYPE(QSystemInfo::Version); +Q_DECLARE_METATYPE(QSystemInfo::Feature); + +/** + * Starts an event loop that runs until the given signal is received. + * Optionally the event loop can return earlier on a timeout. + * + * \return \p true if the requested signal was received + * \p false on timeout + */ +#ifdef TESTR + +static bool waitForSignal(QObject *obj, const char *signal, int timeout = 0) +{ + QEventLoop loop; + QObject::connect(obj, signal, &loop, SLOT(quit())); + QTimer timer; + QSignalSpy timeoutSpy(&timer, SIGNAL(timeout())); + if (timeout > 0) { + QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); + timer.setSingleShot(true); + timer.start(timeout); + } + loop.exec(); + return timeoutSpy.isEmpty(); +} + +//static void setLanguage(const QString & lang) +//{ +// QSystemInfoPrivate *s = getSystemInfoPrivate(); +// s->setCurrentLanguage(lang); +//} + + +class ChangeLanguageThread : public QThread +{ +public: + void run() + { + SystemInfoConnection si; + QSystemInfoPrivate *d = si.systeminfoPrivate(); + d->setCurrentLanguage(lang); + + } + QString lang; +}; +#endif + +class tst_QSystemInfo : public QObject +{ + Q_OBJECT + +public: + tst_QSystemInfo(); + virtual ~tst_QSystemInfo(); + + friend class QSystemInfo; + +private slots: + void initTestCase(); + + void tst_currentLanguage(); + void tst_availableLanguages(); + + void tst_versions_data(); + void tst_versions(); + + void tst_countryCode(); + + void tst_hasFeatures_data(); + void tst_hasFeatures(); + + void tst_detailFeatures_data(); + void tst_detailFeatures(); +#ifdef TESTR + void currentLanguageChanged(); + + void slotCurrentLanguageChanged(const QString &); +#endif +private: +#ifdef TESTR + ChangeLanguageThread *changeLangThread; +#endif +}; + +tst_QSystemInfo::tst_QSystemInfo() +{ +#ifdef TESTR + changeLangThread = new ChangeLanguageThread(); +#endif +} + +tst_QSystemInfo::~tst_QSystemInfo() +{ +#ifdef TESTR + delete changeLangThread, changeLangThread = 0; +#endif +} + +void tst_QSystemInfo::initTestCase() +{ + qRegisterMetaType("QSystemInfo::Version"); + qRegisterMetaType("QSystemInfo::Feature"); +} + +void tst_QSystemInfo::tst_currentLanguage() +{ + QSystemInfo si; +#ifdef TESTR + SystemInfoConnection sic; + QSystemInfoPrivate *d = sic.systeminfoPrivate(); + d->setInitialData(); +#endif + QVERIFY(!si.currentLanguage().isEmpty()); + QCOMPARE(si.currentLanguage().length(), 2); + QVERIFY(si.currentLanguage() == si.currentLanguage().toLower()); + +} + +void tst_QSystemInfo::tst_availableLanguages() +{ + QSystemInfo si; +#ifdef TESTR + SystemInfoConnection sic; + QSystemInfoPrivate *d = sic.systeminfoPrivate(); + d->setInitialData(); +#endif + QVERIFY(!si.availableLanguages().isEmpty()); + QStringList available = si.availableLanguages(); + foreach(QString lang, available) { + QCOMPARE(lang.length(), 2); + QVERIFY(lang == lang.toLower()); + } +} + +void tst_QSystemInfo::tst_versions_data() +{ + QTest::addColumn("version"); + QTest::addColumn("parameter"); + + QTest::newRow("Os") << QSystemInfo::Os << ""; + QTest::newRow("QtCore") << QSystemInfo::QtCore << ""; + QTest::newRow("Firmware") << QSystemInfo::Firmware << ""; + +} + +void tst_QSystemInfo::tst_versions() +{ + { + QFETCH(QSystemInfo::Version, version); + QFETCH(QString, parameter); + QSystemInfo si; +#ifdef TESTR + SystemInfoConnection sic; + QSystemInfoPrivate *d = sic.systeminfoPrivate(); + d->setInitialData(); +#endif + QString vers = si.version(version, parameter); + QVERIFY(!vers.isEmpty() + || vers.isEmpty()); + } +} + +void tst_QSystemInfo::tst_countryCode() +{ + QSystemInfo si; +#ifdef TESTR + SystemInfoConnection sic; + QSystemInfoPrivate *d = sic.systeminfoPrivate(); + d->setInitialData(); +#endif + QVERIFY(!si.currentCountryCode().isEmpty()); + QCOMPARE(si.currentCountryCode().length(),2); + QVERIFY(si.currentCountryCode() == si.currentCountryCode().toUpper()); +} + +void tst_QSystemInfo::tst_hasFeatures_data() +{ + QTest::addColumn("feature"); + + QTest::newRow("Bluetooth") << QSystemInfo::BluetoothFeature; + QTest::newRow("CameraFeature") << QSystemInfo::CameraFeature; + QTest::newRow("FmradioFeature") << QSystemInfo::FmradioFeature; + QTest::newRow("IrFeature") << QSystemInfo::IrFeature; + QTest::newRow("LedFeature") << QSystemInfo::LedFeature; + QTest::newRow("MemcardFeature") << QSystemInfo::MemcardFeature; + QTest::newRow("UsbFeature") << QSystemInfo::UsbFeature; + QTest::newRow("VibFeature") << QSystemInfo::VibFeature; + QTest::newRow("WlanFeature") << QSystemInfo::WlanFeature; + QTest::newRow("SimFeature") << QSystemInfo::SimFeature; + QTest::newRow("LocationFeature") << QSystemInfo::LocationFeature; + QTest::newRow("VideoOutFeature") << QSystemInfo::VideoOutFeature; + QTest::newRow("HapticsFeature") << QSystemInfo::HapticsFeature; + QTest::newRow("FmTransmitterFeature") << QSystemInfo::FmTransmitterFeature; +} + +void tst_QSystemInfo::tst_hasFeatures() +{ + { + QFETCH(QSystemInfo::Feature, feature); + QSystemInfo si; +#ifdef TESTR + SystemInfoConnection sic; + QSystemInfoPrivate *d = sic.systeminfoPrivate(); + d->setInitialData(); +#endif + QVERIFY(si.hasFeatureSupported(feature) == false + || si.hasFeatureSupported(feature) == true); + } +} + +void tst_QSystemInfo::tst_detailFeatures_data() +{ + tst_hasFeatures_data(); +} + +void tst_QSystemInfo::tst_detailFeatures() +{ +// { +// QFETCH(QSystemInfo::Feature, feature); +// QSystemInfo si; +// QVERIFY(!si.getDetailOfFeature(feature).isEmpty()); +// } +} +#ifdef TESTR + +void tst_QSystemInfo::currentLanguageChanged() +{ + QSystemInfo si; + connect(&si,SIGNAL(currentLanguageChanged(const QString &)),this, + SLOT(slotCurrentLanguageChanged(const QString &))); + + changeLangThread->lang = "kl"; + changeLangThread->start(); + QSignalSpy errorSpy(&si, SIGNAL(currentLanguageChanged(const QString &))); + QVERIFY(::waitForSignal(&si, SIGNAL(currentLanguageChanged(const QString &)), 10 * 1000)); + QVERIFY(errorSpy.count() == 1); +} + +void tst_QSystemInfo::slotCurrentLanguageChanged(const QString &lang) +{ + QVERIFY(lang == "kl"); +} +#endif + +QTEST_MAIN(tst_QSystemInfo) +#include "tst_qsysteminfo.moc" + diff --git a/pool/shard008/C++/0096684_OpenCLGpuRegistry.cpp b/pool/shard008/C++/0096684_OpenCLGpuRegistry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9068c3d3e488a0e57725c3b13067386110895757 --- /dev/null +++ b/pool/shard008/C++/0096684_OpenCLGpuRegistry.cpp @@ -0,0 +1,119 @@ +/** + * UGENE - Integrated Bioinformatics Tools. + * Copyright (C) 2008-2022 UniPro + * http://ugene.net + * + * 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. + */ + +#ifdef OPENCL_SUPPORT + +# include +# include + +# include +# include +# include + +# include "OpenCLGpuRegistry.h" + +namespace U2 { + +OpenCLGpuRegistry::OpenCLGpuRegistry() + : openCLHelper(nullptr) { +} + +OpenCLGpuRegistry::~OpenCLGpuRegistry() { + qDeleteAll(gpus.values()); +} + +void OpenCLGpuRegistry::registerOpenCLGpu(OpenCLGpuModel* gpu) { + assert(!gpus.contains(gpu->getId())); + gpus.insert(gpu->getId(), gpu); +} + +void OpenCLGpuRegistry::unregisterOpenCLGpu(OpenCLGpuModel* gpu) { + CHECK(gpus.contains(gpu->getId()), ); + delete gpus.take(gpu->getId()); +} + +OpenCLGpuModel* OpenCLGpuRegistry::getGpuById(cl_device_id id) const { + return gpus.value(id, 0); +} + +OpenCLGpuModel* OpenCLGpuRegistry::getGpuByName(const QString& name) const { + OpenCLGpuModel* gpu = nullptr; + foreach (OpenCLGpuModel* m, gpus.values()) { + CHECK_CONTINUE(m->getName() == name); + + gpu = m; + break; + } + + return gpu; +} + +QList OpenCLGpuRegistry::getRegisteredGpus() const { + return gpus.values(); +} + +OpenCLGpuModel* OpenCLGpuRegistry::getEnabledGpu() const { + QList registeredGpus = getRegisteredGpus(); + + OpenCLGpuModel* enabledGpu = nullptr; + foreach (OpenCLGpuModel* m, registeredGpus) { + if (m && m->isEnabled()) { + enabledGpu = m; + break; + } + } + + return enabledGpu; +} + +QString OpenCLGpuRegistry::getEnabledGpuName() const { + OpenCLGpuModel* enabledGpu = getEnabledGpu(); + CHECK(nullptr != enabledGpu, QString()); + + return enabledGpu->getName(); +} + +OpenCLGpuModel* OpenCLGpuRegistry::acquireEnabledGpuIfReady() { + OpenCLGpuModel* model = nullptr; + foreach (OpenCLGpuModel* gpuModel, gpus.values()) { + CHECK_CONTINUE(gpuModel->isEnabled()); + CHECK_BREAK(gpuModel->isReady()); + + gpuModel->setAcquired(true); + model = gpuModel; + } + + return model; +} + +void OpenCLGpuRegistry::saveGpusSettings() const { + Settings* s = AppContext::getSettings(); + foreach (OpenCLGpuModel* m, gpus) { + CHECK_CONTINUE(m->isEnabled()); + + s->setValue(OPENCL_GPU_REGISTRY_SETTINGS_GPU_ENABLED, QVariant(m->getName())); + break; + } +} + +} // namespace U2 + +#endif /*OPENCL_SUPPORT*/ diff --git a/pool/shard008/C++/0096686_remote_command_job.cc b/pool/shard008/C++/0096686_remote_command_job.cc new file mode 100644 index 0000000000000000000000000000000000000000..15e89a3f14ce0e2b63122d35eb015c262ba08aea --- /dev/null +++ b/pool/shard008/C++/0096686_remote_command_job.cc @@ -0,0 +1,169 @@ +// 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/policy/core/common/remote_commands/remote_command_job.h" + +#include + +#include "base/bind.h" +#include "base/syslog_logging.h" + +namespace policy { + +namespace { + +constexpr base::TimeDelta kDefaultCommandTimeout = base::Minutes(10); +constexpr base::TimeDelta kDefaultCommandExpirationTime = base::Minutes(10); + +} // namespace + +RemoteCommandJob::~RemoteCommandJob() { + DCHECK(thread_checker_.CalledOnValidThread()); + if (status_ == RUNNING) + Terminate(); +} + +bool RemoteCommandJob::Init( + base::TimeTicks now, + const enterprise_management::RemoteCommand& command, + const enterprise_management::SignedData* signed_command) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_EQ(NOT_INITIALIZED, status_); + + status_ = INVALID; + + if (!command.has_type() || !command.has_command_id()) + return false; + DCHECK_EQ(command.type(), GetType()); + + unique_id_ = command.command_id(); + if (signed_command) + signed_command_ = *signed_command; + + if (command.has_age_of_command()) { + // Use age of command provided by server to estimate the command issued time + // as a local TimeTick. We need to store issued time instead of age of + // command, since the execution time of command might be different from the + // time we got it from server. + // It's just an estimation since we lost the time the response was + // transmitted over the network. + issued_time_ = now - base::Milliseconds(command.age_of_command()); + } else { + SYSLOG(WARNING) << "No age_of_command provided by server for command " + << unique_id_ << "."; + // Otherwise, assuming the command was issued just now. + issued_time_ = now; + } + + if (!ParseCommandPayload(command.payload())) { + SYSLOG(ERROR) << "Unable to parse command payload for type " + << command.type() << ": " << command.payload(); + return false; + } + + SYSLOG(INFO) << "Remote command type " << command.type() << " with id " + << command.command_id() << " initialized."; + + status_ = NOT_STARTED; + return true; +} + +bool RemoteCommandJob::Run(base::Time now, + base::TimeTicks now_ticks, + FinishedCallback finished_callback) { + DCHECK(thread_checker_.CalledOnValidThread()); + + if (status_ == INVALID) { + SYSLOG(ERROR) << "Remote command " << unique_id_ << " is invalid."; + return false; + } + + DCHECK_EQ(NOT_STARTED, status_); + + if (IsExpired(now_ticks)) { + SYSLOG(ERROR) << "Remote command " << unique_id_ + << " expired (it was issued " << now_ticks - issued_time_ + << " ago)."; + status_ = EXPIRED; + return false; + } + + execution_started_time_ = now; + status_ = RUNNING; + finished_callback_ = std::move(finished_callback); + + RunImpl( + base::BindOnce(&RemoteCommandJob::OnCommandExecutionFinishedWithResult, + weak_factory_.GetWeakPtr(), true), + base::BindOnce(&RemoteCommandJob::OnCommandExecutionFinishedWithResult, + weak_factory_.GetWeakPtr(), false)); + + // The command is expected to run asynchronously. + DCHECK_EQ(RUNNING, status_); + + return true; +} + +void RemoteCommandJob::Terminate() { + DCHECK(thread_checker_.CalledOnValidThread()); + + if (IsExecutionFinished()) + return; + + DCHECK_EQ(RUNNING, status_); + + status_ = TERMINATED; + weak_factory_.InvalidateWeakPtrs(); + + TerminateImpl(); + + if (finished_callback_) + std::move(finished_callback_).Run(); +} + +base::TimeDelta RemoteCommandJob::GetCommandTimeout() const { + return kDefaultCommandTimeout; +} + +bool RemoteCommandJob::IsExecutionFinished() const { + return status_ == SUCCEEDED || status_ == FAILED || status_ == TERMINATED; +} + +std::unique_ptr RemoteCommandJob::GetResultPayload() const { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(status_ == SUCCEEDED || status_ == FAILED); + + if (!result_payload_) + return nullptr; + + return result_payload_->Serialize(); +} + +RemoteCommandJob::RemoteCommandJob() : status_(NOT_INITIALIZED) {} + +bool RemoteCommandJob::ParseCommandPayload(const std::string& command_payload) { + return true; +} + +bool RemoteCommandJob::IsExpired(base::TimeTicks now) { + return now > issued_time() + kDefaultCommandExpirationTime; +} + +void RemoteCommandJob::TerminateImpl() { +} + +void RemoteCommandJob::OnCommandExecutionFinishedWithResult( + bool succeeded, + std::unique_ptr result_payload) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_EQ(RUNNING, status_); + status_ = succeeded ? SUCCEEDED : FAILED; + + result_payload_ = std::move(result_payload); + + if (finished_callback_) + std::move(finished_callback_).Run(); +} + +} // namespace policy diff --git a/pool/shard008/C++/0096687_stream_infra.cpp b/pool/shard008/C++/0096687_stream_infra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..845c828d98f2923dbb0b96778b0abbd024e5fd15 --- /dev/null +++ b/pool/shard008/C++/0096687_stream_infra.cpp @@ -0,0 +1,110 @@ +#include +#include +#include +#include +#include + +namespace { + +streams_t join(const streams_t & left, const streams_t & right) { + + streams_t stream; + + stream.insert(stream.end(), left.begin(), left.end()); + stream.insert(stream.end(), right.begin(), right.end()); + + return std::move(stream); +} + +fwd_new_stream_fn_t forward(streams_t::iterator begin, streams_t::iterator end) +{ + + streams_t s; + std::copy(begin, end, back_inserter(s)); + + return [=]() mutable -> forward_fn_t + { + + init_streams(s); + + return [=](next_events_t events) + { + for (const auto & event : events) { + push_event(s, event); + } + }; + + }; + +} + +} + +streams_t create_stream(const on_event_fn_t fn) { + + return {{[=](fwd_new_stream_fn_t){ return fn; }, fn}}; + +} + +streams_t create_stream(const on_init_simple_fn_t fn) { + + return {{[=](fwd_new_stream_fn_t){ return fn(); }, {}}}; + +} + +streams_t create_stream(const on_init_fn_t fn) { + + return {{fn, {}}}; + +} + + + +void init_streams(streams_t & streams) { + + for (size_t j = 0, i = streams.size() - 1; j < streams.size() ; i--, j++) { + + auto & node = streams[i]; + + node.on_event = node.on_init(forward(streams.end() - j , streams.end())); + + } + +} + +streams_t operator>>(const streams_t & left, const streams_t & right) { + return std::move(join(left, right)); +} + +next_events_t push_event(const streams_t & stream, const Event & event) { + + next_events_t next_events; + + for (const auto & node: stream) { + + if (next_events.empty()) { // First iteration + + next_events = node.on_event(event); + + } else { + + const auto aux_next_events(next_events); + next_events.clear(); + + for (const auto & e : aux_next_events) { + + const auto res = node.on_event(e); + std::copy(begin(res), end(res), back_inserter(next_events)); + + } + + } + + if (next_events.empty()) { + return {}; + } + + } + + return next_events; +} diff --git a/pool/shard008/C++/0096690_jinvoker.cpp b/pool/shard008/C++/0096690_jinvoker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1d1f1abfd6beeae7f4fd183831ffa349368688a --- /dev/null +++ b/pool/shard008/C++/0096690_jinvoker.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2006, 2011, Oracle and/or its affiliates. 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 Oracle 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. + */ + +/* + * This source code is provided to illustrate the usage of a given feature + * or technique and has been deliberately simplified. Additional steps + * required for a production-quality application, such as security checks, + * input validation and proper error handling, might not be present in + * this sample code. + */ + + +#include +#include +#include "jinvokerExp.h" + +static int g_nExitCode = 0; + +void system_exit(jint nCode){ + g_nExitCode = nCode; +} + +/* +Allocating and providing the JVM init argumets. +By MakeJavaVMInitArgs() it is provided two options: providing CLASSPATH +environment variable value and function java.lang.System.exit() +redefinition in order to get the exit code. +See the description of the JNI API in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/invocation.html#wp9502 +*/ + +int MakeJavaVMInitArgs( void** ppArgs ){ + + int nOptSize = 2; + JavaVMInitArgs* pArgs = new JavaVMInitArgs(); + JavaVMOption* pOptions = new JavaVMOption[nOptSize]; + + //provide CLASSPATH value to java.class.path + + char* szClassPath = getenv("CLASSPATH"); + if( szClassPath == NULL ) + szClassPath = "."; + + pOptions[0].optionString = new char[strlen("-Djava.class.path=")+ + strlen(szClassPath)+1]; + sprintf( pOptions[0].optionString, "-Djava.class.path=%s", szClassPath ); + + //redefine java.lang.System.exit() + + pOptions[1].optionString = "exit"; + pOptions[1].extraInfo = system_exit; + + //Fill the arguments + + memset(pArgs, 0, sizeof(JavaVMInitArgs)); + pArgs->version = 0x00010002; + pArgs->options = pOptions; + pArgs->nOptions = nOptSize; + pArgs->ignoreUnrecognized = JNI_TRUE; + + *ppArgs = pArgs; + + return 0; +} + +/* +Free the allocated JVM init argumets +*/ + +void FreeJavaVMInitArgs( void* pArgs ){ + delete ((JavaVMInitArgs*)pArgs)->options[0].optionString; + delete ((JavaVMInitArgs*)pArgs)->options; + delete pArgs; +} + +/* +Static wrapper on FindClass() JNI function. +See the description in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/functions.html#wp16027 +*/ + +int FindClass( JNIEnv* pEnv, + const char* szClass, + jclass* pClass ){ + + *pClass = pEnv->FindClass( szClass ); + + if(pEnv->ExceptionCheck() == JNI_TRUE){ + pEnv->ExceptionDescribe(); + return -1; + } + if(*pClass != NULL) + return 0; + else + return -2; + +} + +/* +Static wrapper on GetStaticMethodID() JNI function. +See the description in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/functions.html#wp20949 +*/ + +int GetStaticMethodID(JNIEnv* pEnv, + jclass pClass, + const char* szName, + const char* szArgs, + jmethodID* pMid){ + + *pMid = pEnv->GetStaticMethodID( pClass, szName, szArgs); + + if(pEnv->ExceptionCheck() == JNI_TRUE){ + pEnv->ExceptionDescribe(); + return -1; + } + + if( *pMid != NULL ) + return 0; + else + return -2; +} + +/* +Static wrapper on NewObjectArray() JNI function. +See the description in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/functions.html#wp21619 +*/ + +int NewObjectArray( JNIEnv* pEnv, + int nDimension, + const char* szType, + jobjectArray* pArray ){ + + *pArray = pEnv->NewObjectArray( nDimension, pEnv->FindClass( szType ), NULL); + + if(pEnv->ExceptionCheck() == JNI_TRUE){ + pEnv->ExceptionDescribe(); + return -1; + } + + if( pArray != NULL ) + return 0; + else + return -2; + +} + +/* +Static wrapper on CallStaticVoidMethod() JNI function. +See the description in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/functions.html#wp4796 +*/ + +int CallStaticVoidMethod( JNIEnv* pEnv, + jclass pClass, + jmethodID pMid, + void* pArgs){ + + g_nExitCode = 0; + pEnv->CallStaticVoidMethod( pClass, pMid, pArgs); + if( pEnv->ExceptionCheck() == JNI_TRUE ){ + pEnv->ExceptionDescribe(); + return -1; + }else + return g_nExitCode; +} + +/* +Static wrapper on DestroyJavaVM() JNI function. +See the description in +http://jre.sfbay/java/re/jdk/6/promoted/latest/docs/technotes/guides/jni/spec/invocation.html#destroy_java_vm +*/ + +int DestroyJavaVM( JavaVM* pJVM ){ + pJVM->DestroyJavaVM(); + return 0; +} diff --git a/pool/shard008/C++/0096693_search-a-range-sorted-array.cc b/pool/shard008/C++/0096693_search-a-range-sorted-array.cc new file mode 100644 index 0000000000000000000000000000000000000000..63b9a276c6c468284bf142dd09ed582bdc761608 --- /dev/null +++ b/pool/shard008/C++/0096693_search-a-range-sorted-array.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved. + +#include +#include +#include +#include +#include +#include +#include + +using std::cout; +using std::default_random_engine; +using std::endl; +using std::pair; +using std::random_device; +using std::stoul; +using std::uniform_int_distribution; +using std::vector; + +// @include +pair search_range(const vector& A, int target) { + auto result = equal_range(A.cbegin(), A.cend(), target); + if (*result.first != target) { + return {-1, -1}; + } + return {distance(A.begin(), result.first), + distance(A.begin(), result.second - 1)}; +} +// @exclude + +pair check_ans(const vector& A, int target) { + size_t a = 0; + while (a < A.size() && A[a] < target) { + ++a; + } + if (A[a] != target) { + return {-1, -1}; + } + int b = A.size() - 1; + while (b >= 0 && A[b] > target) { + --b; + } + return {a, b}; +} + +int main(int argc, char** argv) { + default_random_engine gen((random_device())()); + for (int times = 0; times < 1000; ++times) { + size_t n; + if (argc == 2) { + n = stoul(argv[1]); + } else { + uniform_int_distribution n_dis(0, 100000); + n = n_dis(gen); + } + uniform_int_distribution A_dis(0, static_cast(n)); + vector A; + generate_n(back_inserter(A), n, [&] { return A_dis(gen); }); + sort(A.begin(), A.end()); + /* + for (int a : A) { + cout << a << " "; + } + cout << endl; + */ + int target = A_dis(gen); + // cout << "target = " << target << endl; + auto result = search_range(A, target), ans = check_ans(A, target); + /* + cout << result.first << ", " << result.second << endl; + cout << ans.first << ", " << ans.second << endl; + */ + assert(result == ans); + } + return 0; +} diff --git a/pool/shard008/C++/0096695_preload_request.cc b/pool/shard008/C++/0096695_preload_request.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e199eb84d371d7a5cedf6473ebee1dad50489c9 --- /dev/null +++ b/pool/shard008/C++/0096695_preload_request.cc @@ -0,0 +1,158 @@ +// 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/core/html/parser/preload_request.h" + +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/settings.h" +#include "third_party/blink/renderer/core/loader/document_loader.h" +#include "third_party/blink/renderer/core/loader/preload_helper.h" +#include "third_party/blink/renderer/core/script/document_write_intervention.h" +#include "third_party/blink/renderer/core/script/script_loader.h" +#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h" +#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h" +#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" +#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" +#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" +#include "third_party/blink/renderer/platform/network/network_state_notifier.h" +#include "third_party/blink/renderer/platform/weborigin/security_policy.h" + +namespace blink { + +PreloadRequest::ExclusionInfo::ExclusionInfo(const KURL& document_url, + HashSet scopes, + HashSet resources) + : document_url_(document_url), + scopes_(std::move(scopes)), + resources_(std::move(resources)) {} + +PreloadRequest::ExclusionInfo::~ExclusionInfo() = default; + +bool PreloadRequest::ExclusionInfo::ShouldExclude( + const KURL& base_url, + const String& resource_url) const { + if (resources_.IsEmpty() && scopes_.IsEmpty()) + return false; + KURL url = KURL(base_url.IsEmpty() ? document_url_ : base_url, resource_url); + if (resources_.Contains(url)) + return true; + for (const auto& scope : scopes_) { + if (url.GetString().StartsWith(scope.GetString())) + return true; + } + return false; +} + +KURL PreloadRequest::CompleteURL(Document* document) { + if (!base_url_.IsEmpty()) + return document->CompleteURLWithOverride(resource_url_, base_url_); + return document->CompleteURL(resource_url_); +} + +// static +std::unique_ptr PreloadRequest::CreateIfNeeded( + const String& initiator_name, + const TextPosition& initiator_position, + const String& resource_url, + const KURL& base_url, + ResourceType resource_type, + const network::mojom::ReferrerPolicy referrer_policy, + ResourceFetcher::IsImageSet is_image_set, + const ExclusionInfo* exclusion_info, + const FetchParameters::ResourceWidth& resource_width, + const ClientHintsPreferences& client_hints_preferences, + RequestType request_type) { + // Never preload data URLs. We also disallow relative ref URLs which become + // data URLs if the document's URL is a data URL. We don't want to create + // extra resource requests with data URLs to avoid copy / initialization + // overhead, which can be significant for large URLs. + if (resource_url.IsEmpty() || resource_url.StartsWith("#") || + ProtocolIs(resource_url, "data")) { + return nullptr; + } + + if (exclusion_info && exclusion_info->ShouldExclude(base_url, resource_url)) + return nullptr; + + return base::WrapUnique(new PreloadRequest( + initiator_name, initiator_position, resource_url, base_url, resource_type, + resource_width, client_hints_preferences, request_type, referrer_policy, + is_image_set)); +} + +Resource* PreloadRequest::Start(Document* document) { + DCHECK(document->domWindow()); + + FetchInitiatorInfo initiator_info; + initiator_info.name = AtomicString(initiator_name_); + initiator_info.position = initiator_position_; + + const KURL& url = CompleteURL(document); + // Data URLs are filtered out in the preload scanner. + DCHECK(!url.ProtocolIsData()); + + ResourceRequest resource_request(url); + resource_request.SetReferrerPolicy(referrer_policy_); + + resource_request.SetRequestContext( + ResourceFetcher::DetermineRequestContext(resource_type_, is_image_set_)); + resource_request.SetRequestDestination( + ResourceFetcher::DetermineRequestDestination(resource_type_)); + + resource_request.SetFetchPriorityHint(fetch_priority_hint_); + + ResourceLoaderOptions options(document->domWindow()->GetCurrentWorld()); + options.initiator_info = initiator_info; + FetchParameters params(std::move(resource_request), options); + + auto* origin = document->domWindow()->GetSecurityOrigin(); + if (script_type_ == mojom::blink::ScriptType::kModule) { + DCHECK_EQ(resource_type_, ResourceType::kScript); + params.SetCrossOriginAccessControl( + origin, ScriptLoader::ModuleScriptCredentialsMode(cross_origin_)); + params.SetModuleScript(); + } else if (cross_origin_ != kCrossOriginAttributeNotSet) { + params.SetCrossOriginAccessControl(origin, cross_origin_); + } + + params.SetDefer(defer_); + params.SetResourceWidth(resource_width_); + params.GetClientHintsPreferences().UpdateFrom(client_hints_preferences_); + params.SetIntegrityMetadata(integrity_metadata_); + params.SetContentSecurityPolicyNonce(nonce_); + params.SetParserDisposition(kParserInserted); + + if (request_type_ == kRequestTypeLinkRelPreload) + params.SetLinkPreload(true); + + if (script_type_ == mojom::blink::ScriptType::kModule) { + DCHECK_EQ(resource_type_, ResourceType::kScript); + params.SetDecoderOptions(TextResourceDecoderOptions::CreateUTF8Decode()); + } else if (resource_type_ == ResourceType::kScript || + resource_type_ == ResourceType::kCSSStyleSheet) { + params.SetCharset(charset_.IsEmpty() ? document->Encoding() + : WTF::TextEncoding(charset_)); + } + FetchParameters::SpeculativePreloadType speculative_preload_type = + FetchParameters::SpeculativePreloadType::kInDocument; + if (from_insertion_scanner_) { + speculative_preload_type = + FetchParameters::SpeculativePreloadType::kInserted; + } + params.SetSpeculativePreloadType(speculative_preload_type); + + if (resource_type_ == ResourceType::kScript) { + // We intentionally ignore the returned value, because we don't resend + // the async request to the blocked script here. + MaybeDisallowFetchForDocWrittenScript(params, *document); + } + params.SetRenderBlockingBehavior(render_blocking_behavior_); + + return PreloadHelper::StartPreload(resource_type_, params, *document); +} + +} // namespace blink diff --git a/pool/shard008/C++/0096696_collection.cpp b/pool/shard008/C++/0096696_collection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f55461e8b7949e765facdd68b1b2748257a7495 --- /dev/null +++ b/pool/shard008/C++/0096696_collection.cpp @@ -0,0 +1,122 @@ +/* + * Copyright 2006-2008 The FLWOR Foundation. + * + * 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 "collection.h" + +#include "store/api/item.h" +#include "store/api/ic.h" + +#include "node_items.h" +#include "simple_store.h" +#include "simple_index.h" + +namespace zorba { +namespace simplestore { + + +/******************************************************************************* + +*******************************************************************************/ +void Collection::getIndexes(std::vector& indexes) +{ + getIndexes(getName(), indexes); +} + + +/******************************************************************************* + Static method +*******************************************************************************/ +void Collection::getIndexes( + const store::Item* name, + std::vector& indexes) +{ + const IndexSet& availableIndexes = GET_STORE().getIndices(); + + IndexSet::iterator idxIte = availableIndexes.begin(); + IndexSet::iterator idxEnd = availableIndexes.end(); + + for (; idxIte != idxEnd; ++idxIte) + { + IndexImpl* index = static_cast((*idxIte).second.getp()); + const store::IndexSpecification& indexSpec = index->getSpecification(); + + const std::vector& indexSources = indexSpec.theSources; + csize numIndexSources = indexSources.size(); + + for (csize i = 0; i < numIndexSources; ++i) + { + if (indexSources[i]->equals(name)) + { + indexes.push_back(index); + break; + } + } + } +} + + +/******************************************************************************* + +*******************************************************************************/ +void Collection::getActiveICs(std::vector& ics) +{ + getActiveICs(getName(), ics); +} + + +/******************************************************************************* + Static method +*******************************************************************************/ +void Collection::getActiveICs( + const store::Item* name, + std::vector& ics) +{ + store::Iterator_t activeICNames = GET_STORE().listActiveICNames(); + + store::Item_t activeICName; + activeICNames->open(); + + while ( activeICNames->next(activeICName) ) + { + + store::IC* activeIC = GET_STORE().getIC(activeICName); + + switch( activeIC->getICKind() ) + { + case store::IC::ic_collection: + if ( activeIC->getCollectionName()->equals(name) ) + ics.push_back(activeIC); + break; + + case store::IC::ic_foreignkey: + if ( activeIC->getToCollectionName()->equals(name) ) + ics.push_back(activeIC); + + if ( activeIC->getFromCollectionName()->equals(name) ) + ics.push_back(activeIC); + break; + + default: + ZORBA_ASSERT(false); + } + } + + activeICNames->close(); +} + + +} /* namespace simplestore */ +} /* namespace zorba */ diff --git a/pool/shard008/C++/0096697_rendezvous.cpp b/pool/shard008/C++/0096697_rendezvous.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0113b98f8c667ab4bb4907eeb74f133489e3689 --- /dev/null +++ b/pool/shard008/C++/0096697_rendezvous.cpp @@ -0,0 +1,32 @@ +//Jakub Michalec +#include "Semaphore.h" +#include +#include +//Task: A1 always prints before B1, and B2 always prints before A2. + +void taskOne(std::shared_ptr sem1,std::shared_ptr sem2){ + std::cout << "A1"<Signal(); + sem2->Wait(); + std::cout << "A2"< sem1,std::shared_ptr sem2){ + std::cout << "B1"<Signal(); + sem1->Wait(); + std::cout << "B2"< sem1( new Semaphore); + std::shared_ptr sem2( new Semaphore); + /**< Launch the threads */ + threadOne=std::thread(taskTwo, sem1, sem2); + threadTwo=std::thread(taskOne, sem1, sem2); + + std::cout << "Launched from the main\n"; + threadOne.join(); + threadTwo.join(); + return 0; +} diff --git a/pool/shard008/C++/0096701_Resources.cpp b/pool/shard008/C++/0096701_Resources.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50c08922fa1acc66f61960ce45eb8057ee84272e --- /dev/null +++ b/pool/shard008/C++/0096701_Resources.cpp @@ -0,0 +1,32 @@ +/* + * Copyright 2014 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "Resources.h" +#include "SkBitmap.h" +#include "SkCommandLineFlags.h" +#include "SkData.h" +#include "SkDecodingImageGenerator.h" +#include "SkOSFile.h" + +DEFINE_string2(resourcePath, i, "resources", "Directory with test resources: images, fonts, etc."); + +SkString GetResourcePath(const char* resource) { + return SkOSPath::Join(FLAGS_resourcePath[0], resource); +} + +void SetResourcePath(const char* resource) { + FLAGS_resourcePath.set(0, resource); +} + +bool GetResourceAsBitmap(const char* resource, SkBitmap* dst) { + SkString resourcePath = GetResourcePath(resource); + SkAutoTUnref resourceData( + SkData::NewFromFileName(resourcePath.c_str())); + return resourceData && SkInstallDiscardablePixelRef( + SkDecodingImageGenerator::Create( + resourceData, SkDecodingImageGenerator::Options()), dst); +} diff --git a/pool/shard008/C++/0096704_SkXfermodeImageFilter.cpp b/pool/shard008/C++/0096704_SkXfermodeImageFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1334a2c94f32fde66f22f6d7ac3e2a00e51bb13 --- /dev/null +++ b/pool/shard008/C++/0096704_SkXfermodeImageFilter.cpp @@ -0,0 +1,211 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SkXfermodeImageFilter.h" +#include "SkCanvas.h" +#include "SkDevice.h" +#include "SkColorPriv.h" +#include "SkReadBuffer.h" +#include "SkWriteBuffer.h" +#include "SkXfermode.h" +#if SK_SUPPORT_GPU +#include "GrContext.h" +#include "GrDrawContext.h" +#include "effects/GrTextureDomain.h" +#include "SkGr.h" +#endif + +/////////////////////////////////////////////////////////////////////////////// + +SkXfermodeImageFilter::SkXfermodeImageFilter(SkXfermode* mode, + SkImageFilter* inputs[2], + const CropRect* cropRect) + : INHERITED(2, inputs, cropRect), fMode(mode) { + SkSafeRef(fMode); +} + +SkXfermodeImageFilter::~SkXfermodeImageFilter() { + SkSafeUnref(fMode); +} + +SkFlattenable* SkXfermodeImageFilter::CreateProc(SkReadBuffer& buffer) { + SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 2); + SkAutoTUnref mode(buffer.readXfermode()); + return Create(mode, common.getInput(0), common.getInput(1), &common.cropRect()); +} + +void SkXfermodeImageFilter::flatten(SkWriteBuffer& buffer) const { + this->INHERITED::flatten(buffer); + buffer.writeFlattenable(fMode); +} + +bool SkXfermodeImageFilter::onFilterImage(Proxy* proxy, + const SkBitmap& src, + const Context& ctx, + SkBitmap* dst, + SkIPoint* offset) const { + SkBitmap background = src, foreground = src; + SkImageFilter* backgroundInput = getInput(0); + SkImageFilter* foregroundInput = getInput(1); + SkIPoint backgroundOffset = SkIPoint::Make(0, 0); + if (backgroundInput && + !backgroundInput->filterImage(proxy, src, ctx, &background, &backgroundOffset)) { + background.reset(); + } + SkIPoint foregroundOffset = SkIPoint::Make(0, 0); + if (foregroundInput && + !foregroundInput->filterImage(proxy, src, ctx, &foreground, &foregroundOffset)) { + foreground.reset(); + } + + SkIRect bounds, foregroundBounds; + if (!applyCropRect(ctx, foreground, foregroundOffset, &foregroundBounds)) { + foregroundBounds.setEmpty(); + foreground.reset(); + } + if (!applyCropRect(ctx, background, backgroundOffset, &bounds)) { + bounds.setEmpty(); + background.reset(); + } + bounds.join(foregroundBounds); + if (bounds.isEmpty()) { + return false; + } + + SkAutoTUnref device(proxy->createDevice(bounds.width(), bounds.height())); + if (NULL == device.get()) { + return false; + } + SkCanvas canvas(device); + canvas.translate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); + SkPaint paint; + paint.setXfermodeMode(SkXfermode::kSrc_Mode); + canvas.drawBitmap(background, SkIntToScalar(backgroundOffset.fX), + SkIntToScalar(backgroundOffset.fY), &paint); + paint.setXfermode(fMode); + canvas.drawBitmap(foreground, SkIntToScalar(foregroundOffset.fX), + SkIntToScalar(foregroundOffset.fY), &paint); + canvas.clipRect(SkRect::Make(foregroundBounds), SkRegion::kDifference_Op); + paint.setColor(SK_ColorTRANSPARENT); + canvas.drawPaint(paint); + *dst = device->accessBitmap(false); + offset->fX = bounds.left(); + offset->fY = bounds.top(); + return true; +} + +#ifndef SK_IGNORE_TO_STRING +void SkXfermodeImageFilter::toString(SkString* str) const { + str->appendf("SkXfermodeImageFilter: ("); + str->appendf("xfermode: ("); + if (fMode) { + fMode->toString(str); + } + str->append(")"); + if (this->getInput(0)) { + str->appendf("foreground: ("); + this->getInput(0)->toString(str); + str->appendf(")"); + } + if (this->getInput(1)) { + str->appendf("background: ("); + this->getInput(1)->toString(str); + str->appendf(")"); + } + str->append(")"); +} +#endif + +#if SK_SUPPORT_GPU + +bool SkXfermodeImageFilter::canFilterImageGPU() const { + return fMode && fMode->asFragmentProcessor(NULL, NULL, NULL) && !cropRectIsSet(); +} + +bool SkXfermodeImageFilter::filterImageGPU(Proxy* proxy, + const SkBitmap& src, + const Context& ctx, + SkBitmap* result, + SkIPoint* offset) const { + SkBitmap background = src; + SkIPoint backgroundOffset = SkIPoint::Make(0, 0); + if (getInput(0) && !getInput(0)->getInputResultGPU(proxy, src, ctx, &background, + &backgroundOffset)) { + return onFilterImage(proxy, src, ctx, result, offset); + } + GrTexture* backgroundTex = background.getTexture(); + + if (NULL == backgroundTex) { + SkASSERT(false); + return false; + } + + SkBitmap foreground = src; + SkIPoint foregroundOffset = SkIPoint::Make(0, 0); + if (getInput(1) && !getInput(1)->getInputResultGPU(proxy, src, ctx, &foreground, + &foregroundOffset)) { + return onFilterImage(proxy, src, ctx, result, offset); + } + GrTexture* foregroundTex = foreground.getTexture(); + GrContext* context = foregroundTex->getContext(); + + GrFragmentProcessor* xferProcessor = NULL; + + GrSurfaceDesc desc; + desc.fFlags = kRenderTarget_GrSurfaceFlag; + desc.fWidth = src.width(); + desc.fHeight = src.height(); + desc.fConfig = kSkia8888_GrPixelConfig; + SkAutoTUnref dst(context->textureProvider()->refScratchTexture( + desc, GrTextureProvider::kApprox_ScratchTexMatch)); + if (!dst) { + return false; + } + + GrPaint paint; + if (!fMode || !fMode->asFragmentProcessor(&xferProcessor, paint.getProcessorDataManager(), + backgroundTex)) { + // canFilterImageGPU() should've taken care of this + SkASSERT(false); + return false; + } + + SkMatrix foregroundMatrix = GrCoordTransform::MakeDivByTextureWHMatrix(foregroundTex); + foregroundMatrix.preTranslate(SkIntToScalar(backgroundOffset.fX-foregroundOffset.fX), + SkIntToScalar(backgroundOffset.fY-foregroundOffset.fY)); + + + SkRect srcRect; + src.getBounds(&srcRect); + + SkAutoTUnref foregroundDomain(GrTextureDomainEffect::Create( + paint.getProcessorDataManager(), + foregroundTex, foregroundMatrix, + GrTextureDomain::MakeTexelDomain(foregroundTex, foreground.bounds()), + GrTextureDomain::kDecal_Mode, + GrTextureParams::kNone_FilterMode) + ); + + paint.addColorProcessor(foregroundDomain.get()); + paint.addColorProcessor(xferProcessor)->unref(); + + GrDrawContext* drawContext = context->drawContext(); + if (!drawContext) { + return false; + } + + drawContext->drawRect(dst->asRenderTarget(), GrClip::WideOpen(), paint, + SkMatrix::I(), srcRect); + + offset->fX = backgroundOffset.fX; + offset->fY = backgroundOffset.fY; + WrapTexture(dst, src.width(), src.height(), result); + return true; +} + +#endif + diff --git a/pool/shard008/C++/0096710_version_tests.cpp b/pool/shard008/C++/0096710_version_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8f8358f3c113b4e21e30cb5e9d6a3d229191484 --- /dev/null +++ b/pool/shard008/C++/0096710_version_tests.cpp @@ -0,0 +1,66 @@ +/** + * 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 +#include +#include + + +// Verify version comparison operations. +TEST(VersionTest, Comparison) +{ + Version version1(0, 10, 4); + Version version2(0, 20, 3); + Try version3 = Version::parse("0.20.3"); + + EXPECT_EQ(version2, version3.get()); + EXPECT_NE(version1, version2); + EXPECT_LT(version1, version2); + EXPECT_LE(version1, version2); + EXPECT_LE(version2, version3.get()); + EXPECT_GT(version2, version1); + EXPECT_GE(version2, version1); + EXPECT_GE(version3.get(), version1); + + EXPECT_EQ(stringify(version2), "0.20.3"); +} + + +// Verify version parser. +TEST(VersionTest, Parse) +{ + Try version1 = Version::parse("1.20.3"); + Try version2 = Version::parse("1.20"); + Try version3 = Version::parse("1"); + + EXPECT_GT(version1.get(), version2.get()); + EXPECT_GT(version2.get(), version3.get()); + EXPECT_EQ(stringify(version2.get()), "1.20.0"); + EXPECT_EQ(stringify(version3.get()), "1.0.0"); + + // Verify that tagged/labeled versions work. + Try version4 = Version::parse("1.20.3-rc1"); + EXPECT_SOME(version4); + EXPECT_EQ(version4.get(), version1.get()); + EXPECT_EQ(stringify(version4.get()), "1.20.3"); + + EXPECT_ERROR(Version::parse("0.a.b")); + EXPECT_ERROR(Version::parse("")); + EXPECT_ERROR(Version::parse("a")); + EXPECT_ERROR(Version::parse("1.")); + EXPECT_ERROR(Version::parse(".1.2")); + EXPECT_ERROR(Version::parse("0.1.2.3")); +} diff --git a/pool/shard008/C++/0096711_ContactPublisher.cc b/pool/shard008/C++/0096711_ContactPublisher.cc new file mode 100644 index 0000000000000000000000000000000000000000..7ef840801731a8da14d300f400fc13b45450262e --- /dev/null +++ b/pool/shard008/C++/0096711_ContactPublisher.cc @@ -0,0 +1,82 @@ +#include "ContactPublisher.hh" +// Declaration of the objects used from standard libraries +using std::string; +using std::cout; + +namespace gazebo{ +ContactSensor::ContactSensor() : SensorPlugin() +{ +} // ContactSensor::ContactSensor +ContactSensor::~ContactSensor() +{ + parentSensor.reset(); + updateConnection.reset(); + collisionPub.reset(); +} // ContactSensor::~ContactSensor +void ContactSensor::Load(sensors::SensorPtr _sensor, sdf::ElementPtr /*_sdf*/) +{ + // Get the parent sensor. This code from gazebo wiki. + this->parentSensor = + boost::dynamic_pointer_cast(_sensor); + // Make sure the parent sensor is valid. + if (!this->parentSensor) + { + gzerr << "ContactSensor requires a ContactSensor.\n"; + return; + } + // Connect to the sensor update event. + this->updateConnection = this->parentSensor->ConnectUpdated( + boost::bind(&ContactSensor::OnUpdate, this)); + // Make sure the parent sensor is active. + this->parentSensor->SetActive(true); + // Create a new transport node + transport::NodePtr node(new transport::Node()); + // Get the parent model name + string parent_model_name = + parentSensor->GetParentName() + .substr(0,(parentSensor->GetParentName()).find("::")); + // Initialize the node with the model name + node->Init(parent_model_name); + // Setting up the publisher + string topic_name = + "~/" + parentSensor->GetParentName() + "::" + parentSensor->GetName(); + this->collisionPub = node->Advertise(topic_name); +} // ContactSensor::Load +void ContactSensor::OnUpdate() +{ + // Get all the contacts. + msgs::Contacts contacts = this->parentSensor->GetContacts(); + for (unsigned int i = 0; i < contacts.contact_size(); ++i) + { + if (contacts.contact(i).collision1().find("ground_plane") == string::npos + && contacts.contact(i).collision2().find("ground_plane") == string::npos) + // Get rid of the collision with ground plane + { + // Publish the topic to model + string collision_msgs = + contacts.contact(i).collision1() + "," + contacts.contact(i).collision2(); + msgs::GzString gzstr_collision_message; + gzstr_collision_message.set_data(collision_msgs); + collisionPub->Publish(gzstr_collision_message); + + //+++++++++++++++ Showing the position of the contact points +++++++++++++++ + // for (unsigned int j = 0; j < contacts.contact(i).position_size(); ++j) + // { + // cout << j << " Position:" + // << contacts.contact(i).position(j).x() << " " + // << contacts.contact(i).position(j).y() << " " + // << contacts.contact(i).position(j).z() << "\n"; + // cout << " Normal:" + // << contacts.contact(i).normal(j).x() << " " + // << contacts.contact(i).normal(j).y() << " " + // << contacts.contact(i).normal(j).z() << "\n"; + // cout << " Depth:" << contacts.contact(i).depth(j) << "\n"; + // } + //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + break; + } + } +} // ContactSensor::OnUpdate + +GZ_REGISTER_SENSOR_PLUGIN(ContactSensor) +} // namespace gazebo \ No newline at end of file diff --git a/pool/shard008/C++/0096712_ash_touch_exploration_manager_chromeos.cc b/pool/shard008/C++/0096712_ash_touch_exploration_manager_chromeos.cc new file mode 100644 index 0000000000000000000000000000000000000000..c9ed6c238f7c63c532872d726e9708fb5f1e0bda --- /dev/null +++ b/pool/shard008/C++/0096712_ash_touch_exploration_manager_chromeos.cc @@ -0,0 +1,127 @@ +// 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 "ash/ash_touch_exploration_manager_chromeos.h" + +#include "ash/accessibility_delegate.h" +#include "ash/audio/sounds.h" +#include "ash/root_window_controller.h" +#include "ash/shell.h" +#include "ash/system/tray/system_tray_notifier.h" +#include "ash/wm/window_util.h" +#include "base/command_line.h" +#include "chromeos/audio/chromeos_sounds.h" +#include "chromeos/audio/cras_audio_handler.h" +#include "chromeos/chromeos_switches.h" +#include "ui/chromeos/touch_exploration_controller.h" +#include "ui/wm/public/activation_client.h" + +namespace ash { + +AshTouchExplorationManager::AshTouchExplorationManager( + RootWindowController* root_window_controller) + : root_window_controller_(root_window_controller), + audio_handler_(chromeos::CrasAudioHandler::Get()) { + Shell::GetInstance()->system_tray_notifier()->AddAccessibilityObserver(this); + ash::Shell::GetInstance()->activation_client()->AddObserver(this); + UpdateTouchExplorationState(); +} + +AshTouchExplorationManager::~AshTouchExplorationManager() { + SystemTrayNotifier* system_tray_notifier = + Shell::GetInstance()->system_tray_notifier(); + if (system_tray_notifier) + system_tray_notifier->RemoveAccessibilityObserver(this); + ash::Shell::GetInstance()->activation_client()->RemoveObserver(this); +} + +void AshTouchExplorationManager::OnAccessibilityModeChanged( + ui::AccessibilityNotificationVisibility notify) { + UpdateTouchExplorationState(); +} + +void AshTouchExplorationManager::SetOutputLevel(int volume) { + if (volume > 0) { + if (audio_handler_->IsOutputMuted()) { + audio_handler_->SetOutputMute(false); + } + } + audio_handler_->SetOutputVolumePercent(volume); + // Avoid negative volume. + if (audio_handler_->IsOutputVolumeBelowDefaultMuteLevel()) + audio_handler_->SetOutputMute(true); +} + +void AshTouchExplorationManager::SilenceSpokenFeedback() { + AccessibilityDelegate* delegate = + Shell::GetInstance()->accessibility_delegate(); + if (!delegate->IsSpokenFeedbackEnabled()) + return; + delegate->SilenceSpokenFeedback(); +} + +void AshTouchExplorationManager::PlayVolumeAdjustEarcon() { + if (!VolumeAdjustSoundEnabled()) + return; + if (!audio_handler_->IsOutputMuted() && + audio_handler_->GetOutputVolumePercent() != 100) + PlaySystemSoundIfSpokenFeedback(chromeos::SOUND_VOLUME_ADJUST); +} + +void AshTouchExplorationManager::PlayPassthroughEarcon() { + Shell::GetInstance()->accessibility_delegate()->PlayEarcon( + chromeos::SOUND_PASSTHROUGH); +} + +void AshTouchExplorationManager::PlayExitScreenEarcon() { + Shell::GetInstance()->accessibility_delegate()->PlayEarcon( + chromeos::SOUND_EXIT_SCREEN); +} + +void AshTouchExplorationManager::PlayEnterScreenEarcon() { + Shell::GetInstance()->accessibility_delegate()->PlayEarcon( + chromeos::SOUND_ENTER_SCREEN); +} + +void AshTouchExplorationManager::HandleAccessibilityGesture( + ui::AXGesture gesture) { + Shell::GetInstance()->accessibility_delegate()->HandleAccessibilityGesture( + gesture); +} + +void AshTouchExplorationManager::OnWindowActivated( + aura::client::ActivationChangeObserver::ActivationReason reason, + aura::Window* gained_active, + aura::Window* lost_active) { + UpdateTouchExplorationState(); +} + +void AshTouchExplorationManager::UpdateTouchExplorationState() { + // Comes from components/exo/shell_surface.cc. + const char kExoShellSurfaceWindowName[] = "ExoShellSurface"; + + // See crbug.com/603745 for more details. + bool pass_through_surface = + wm::GetActiveWindow() && + wm::GetActiveWindow()->name() == kExoShellSurfaceWindowName; + + AccessibilityDelegate* delegate = + Shell::GetInstance()->accessibility_delegate(); + bool enabled = delegate->IsSpokenFeedbackEnabled(); + + if (!pass_through_surface && enabled && + !touch_exploration_controller_.get()) { + touch_exploration_controller_.reset(new ui::TouchExplorationController( + root_window_controller_->GetRootWindow(), this)); + } else if (!enabled || pass_through_surface) { + touch_exploration_controller_.reset(); + } +} + +bool AshTouchExplorationManager::VolumeAdjustSoundEnabled() { + return !base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kDisableVolumeAdjustSound); +} + +} // namespace ash diff --git a/pool/shard008/C++/0096713_TillageParameter.cpp b/pool/shard008/C++/0096713_TillageParameter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67f96e1b3946b5267c7cb2fd288e05700638f45b --- /dev/null +++ b/pool/shard008/C++/0096713_TillageParameter.cpp @@ -0,0 +1,33 @@ +#include "TillageParameter.h" +#include "stdlib.h" + +using namespace MainBMP; +using namespace BMPParameter; + +#define TILLAGE_PARAMETER_COUNT 5 + +#define TILLAGE_PARAMETER_INDEX_EFFMIX 3 +#define TILLAGE_PARAMETER_INDEX_DEPTIL 4 + +TillageParameter::TillageParameter(vector *oneRow):ArealParameter(oneRow) +{ + if(int(oneRow->size()) < TILLAGE_PARAMETER_COUNT) throw ModelException("TillageParameter","TillageParameter","oneRow should have 5 parameters at least!"); + + this->m_mixingEfficiency = (float)atof(oneRow->at(TILLAGE_PARAMETER_INDEX_EFFMIX).c_str()); + this->m_mixingDepth = (float)atof(oneRow->at(TILLAGE_PARAMETER_INDEX_DEPTIL).c_str()); +} + + +TillageParameter::~TillageParameter(void) +{ +} + +void TillageParameter::Dump(ostream* fs) +{ + if(fs == NULL) return; + + ArealParameter::Dump(fs); + + *fs << "EFFMIX:" << this->m_mixingEfficiency << endl; + *fs << "DEPTIL:" << this->m_mixingDepth << endl; +} diff --git a/pool/shard008/C++/0096715_ast.cpp b/pool/shard008/C++/0096715_ast.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37448dc2913a59f7d41dee3ed729408769bbef7a --- /dev/null +++ b/pool/shard008/C++/0096715_ast.cpp @@ -0,0 +1,34 @@ +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Constant.h" +#include "llvm/IR/Verifier.h" +#include "ast.hpp" +#include + +using namespace llvm; + +NumericLiteralAST::NumericLiteralAST(double v) { + std::cout << "Numeric value " << v << std::endl; +} + +Value *NumericLiteralAST::codegen(LLVMContext context) { + return ConstantFP::get(context, APFloat(value)); +} + +VariableDeclarationAST::VariableDeclarationAST(std::map symbolTable, std::string identifier, double val) { + variableIdentifier = identifier; + table = symbolTable; + symbolTable[identifier] = ConstantFP::get(Type::TypeID::FloatTyID, APFloat(val));; +} + +Value *VariableDeclarationAST::codegen(LLVMContext context) { + return table[variableIdentifier]; +} diff --git a/pool/shard008/C++/0096717_database.cpp b/pool/shard008/C++/0096717_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..792be6c6d7a0908da7c29c2f58974cf3f7e79f9f --- /dev/null +++ b/pool/shard008/C++/0096717_database.cpp @@ -0,0 +1,162 @@ +#include "database.h" + +#include +#include +#include +#include +#include + +Database::Database(QObject *parent) + : QObject(parent), + m_path(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)), + m_database(QSqlDatabase::addDatabase("QSQLITE")), m_query(), + m_database_name("/wordflow.sqlite3") { + openDatabase(); +} + +Database::~Database() { m_database.close(); } + +void Database::openDatabase() { + if (!m_path.mkpath(".")) + qFatal("Failed to create writable directory at %s", + qPrintable(m_path.absolutePath())); + const QString fileName = m_path.absolutePath() + m_database_name; + m_database.setDatabaseName(fileName); + if (!m_database.open()) { + qFatal("No database connection: %s", + qPrintable(m_database.lastError().text())); + QFile::remove(fileName); + QCoreApplication::quit(); + } +} + +bool Database::createVocabulary(QString vocabulary, QString description) { + m_query.prepare( + "INSERT INTO vocabularies (vocabulary_name, vocabulary_description) " + "VALUES (:vocabulary, :description)"); + m_query.bindValue(":vocabulary", vocabulary); + m_query.bindValue(":description", description); + return m_query.exec(); +} + +bool Database::createWord(QString origin, QString translated, + int vocabulary_id) { + m_query.prepare("INSERT INTO words (vocabulary, origin, translated) " + "VALUES (:vocabulary, :origin, :translated)"); + m_query.bindValue(":vocabulary", vocabulary_id); + m_query.bindValue(":origin", origin); + m_query.bindValue(":translated", translated); + return m_query.exec(); +} + +bool Database::updateWord(int word_id, QString origin, QString translated) { + m_query.prepare("UPDATE words SET origin = :origin, translated = :translated " + "WHERE id = :word_id"); + m_query.bindValue(":origin", origin); + m_query.bindValue(":translated", translated); + m_query.bindValue(":word_id", word_id); + return m_query.exec(); +} + +bool Database::deleteWord(int word_id) { + m_query.prepare("DELETE FROM words WHERE id = :word_id"); + m_query.bindValue(":word_id", word_id); + return m_query.exec(); +} + +bool Database::deleteAll(int vocabulary_id) { + m_query.prepare("DELETE FROM words WHERE vocabulary = :vocabulary_id"); + m_query.bindValue(":vocabulary_id", vocabulary_id); + return m_query.exec(); +} + +bool Database::updateProgress(int word_id, int progress) { + m_query.prepare("UPDATE words SET progress = :progress " + "WHERE id = :word_id"); + m_query.bindValue(":progress", progress); + m_query.bindValue(":word_id", word_id); + return m_query.exec(); +} + +bool Database::resetProgresses(int vocabulary_id) { + m_query.prepare("UPDATE words SET progress = 0 " + "WHERE vocabulary = :vocabulary_id"); + m_query.bindValue(":vocabulary_id", vocabulary_id); + return m_query.exec(); +} + +int Database::countWords(int vocabulary_id) { + QString query = + "SELECT COUNT(*) FROM words WHERE vocabulary = :vocabulary_id"; + m_query.prepare(query); + m_query.bindValue(":vocabulary_id", vocabulary_id); + m_query.exec(); + m_query.next(); + return m_query.value(0).toInt(); +} + +QVariantList Database::listWords(int vocabulary, int limit, bool sort, + bool onlyNotCompleted) { + QString query = "SELECT id, origin, translated, progress FROM words WHERE " + "vocabulary = :vocabulary "; + if (onlyNotCompleted) + query += "AND progress < 100 "; + if (sort) + query += "ORDER BY progress ASC "; + if (limit != std::numeric_limits::max()) + query += "LIMIT :limit"; + + m_query.prepare(query); + m_query.bindValue(":vocabulary", vocabulary); + if (limit != std::numeric_limits::max()) + m_query.bindValue(":limit", limit); + m_query.exec(); + QVariantList word_list; + while (m_query.next()) { + int id = m_query.value(0).toInt(); + QString origin = m_query.value(1).toString(); + QString translated = m_query.value(2).toString(); + int progress = m_query.value(3).toInt(); + QVariantMap map = {{"id", id}, + {"origin", origin}, + {"translated", translated}, + {"progress", progress}}; + word_list << QVariant::fromValue(map); + } + + return word_list; +} + +QString Database::path() const { + return m_path.absolutePath() + m_database_name; +} + +void Database::cleanTables() { + m_query.exec("SELECT name FROM sqlite_master WHERE type='table'"); + while (m_query.next()) { + m_query.exec("DROP TABLE " + m_query.value(0).toString()); + } +} + +void Database::removeDatabase() { + m_database.close(); + QFile file(m_path.absolutePath() + m_database_name); + if (file.exists()) + file.remove(); +} + +QVariantList Database::listVocabularies() { + QVariantList vocabulary_list; + m_query.exec( + "SELECT id, vocabulary_name, vocabulary_description FROM vocabularies"); + while (m_query.next()) { + int id = m_query.value(0).toInt(); + QString name = m_query.value(1).toString(); + QString description = m_query.value(2).toString(); + QVariantMap map = { + {"id", id}, {"name", name}, {"description", description}}; + vocabulary_list << QVariant::fromValue(map); + } + + return vocabulary_list; +} diff --git a/pool/shard008/C++/0096720_data_encryption_win_unittest.cc b/pool/shard008/C++/0096720_data_encryption_win_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..4fa525046057f1b26b19ae3ae34a02b33cab1b42 --- /dev/null +++ b/pool/shard008/C++/0096720_data_encryption_win_unittest.cc @@ -0,0 +1,31 @@ +// 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 "sync/util/data_encryption_win.h" + +#include +#include + +#include "testing/gtest/include/gtest/gtest.h" + +using std::string; +using std::vector; + +namespace { + +TEST(SyncDataEncryption, TestEncryptDecryptOfSampleString) { + vector example(EncryptData("example")); + ASSERT_FALSE(example.empty()); + string result; + ASSERT_TRUE(DecryptData(example, &result)); + ASSERT_TRUE(result == "example"); +} + +TEST(SyncDataEncryption, TestDecryptFailure) { + vector example(0, 0); + string result; + ASSERT_FALSE(DecryptData(example, &result)); +} + +} // namespace diff --git a/pool/shard008/C++/0096721_mitkGetSimulationDataNode.cpp b/pool/shard008/C++/0096721_mitkGetSimulationDataNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4a37fa0177dd16b16211cc3b9f5f39bd88358c0 --- /dev/null +++ b/pool/shard008/C++/0096721_mitkGetSimulationDataNode.cpp @@ -0,0 +1,45 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkGetDataStorage.h" +#include "mitkGetSimulationDataNode.h" +#include +#include + +mitk::DataNode::Pointer mitk::GetSimulationDataNode(sofa::core::objectmodel::BaseNode::SPtr rootNode) +{ + if (!rootNode) + return NULL; + + DataStorage::Pointer dataStorage = GetDataStorage(); + + if (dataStorage.IsNull()) + return NULL; + + TNodePredicateDataType::Pointer predicate = TNodePredicateDataType::New(); + DataStorage::SetOfObjects::ConstPointer subset = dataStorage->GetSubset(predicate); + + for (DataStorage::SetOfObjects::ConstIterator it = subset->Begin(); it != subset->End(); ++it) + { + DataNode::Pointer dataNode = it.Value(); + Simulation::Pointer simulation = static_cast(dataNode->GetData()); + + if (simulation->GetRootNode() == rootNode) + return dataNode; + } + + return NULL; +} diff --git a/pool/shard008/C++/0096722_CWE124_Buffer_Underwrite__malloc_char_ncpy_33.cpp b/pool/shard008/C++/0096722_CWE124_Buffer_Underwrite__malloc_char_ncpy_33.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e56cb0286e841e6055a307a623814b4e501fd12b --- /dev/null +++ b/pool/shard008/C++/0096722_CWE124_Buffer_Underwrite__malloc_char_ncpy_33.cpp @@ -0,0 +1,124 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__malloc_char_ncpy_33.cpp +Label Definition File: CWE124_Buffer_Underwrite__malloc.label.xml +Template File: sources-sink-33.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: ncpy + * BadSink : Copy string to data using strncpy + * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_33 +{ + +#ifndef OMITBAD + +void bad() +{ + char * data; + char * &dataRef = data; + data = NULL; + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + { + char * data = dataRef; + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + strncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; + printLine(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 goodG2B() +{ + char * data; + char * &dataRef = data; + data = NULL; + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + { + char * data = dataRef; + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + strncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; + printLine(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_char_ncpy_33; /* 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/shard008/C++/0096727_correctiq_swapiq_impl.cc b/pool/shard008/C++/0096727_correctiq_swapiq_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c7a9405dd439c86ecfef47ccf14b5a91e129e40 --- /dev/null +++ b/pool/shard008/C++/0096727_correctiq_swapiq_impl.cc @@ -0,0 +1,95 @@ +/* -*- c++ -*- */ +/* + * Copyright 2020 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "correctiq_swapiq_impl.h" +#include + +namespace gr { +namespace blocks { + +swap_iq::sptr swap_iq::make(int datatype, int datasize) +{ + return gnuradio::get_initial_sptr(new swap_iq_impl(datatype, datasize)); +} + +/* + * The private constructor + */ +swap_iq_impl::swap_iq_impl(int datatype, int datasize) + : gr::sync_block("swap_iq", + gr::io_signature::make(1, 1, datasize), + gr::io_signature::make(1, 1, datasize)), + d_datatype(datatype) +{ + if (d_datatype != SWAPTYPE_FLOATCOMPLEX) { + gr::block::set_output_multiple(2); // Make sure we work with pairs + } +} + +/* + * Our virtual destructor. + */ +swap_iq_impl::~swap_iq_impl() {} + +int swap_iq_impl::work(int noutput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) +{ + // Constructor guarantees we'll have pairs. + + long i; + long noi; + + switch (d_datatype) { + case SWAPTYPE_FLOATCOMPLEX: { + noi = noutput_items * 2; // Each complex is 2 floats + const float* in_float = (const float*)input_items[0]; + float* out_float = (float*)output_items[0]; + + for (i = 0; i < noi; i += 2) { + *out_float++ = in_float[i + 1]; + *out_float++ = in_float[i]; + } + } break; + case SWAPTYPE_SHORTCOMPLEX: { + noi = noutput_items; + const int16_t* in_short = (const int16_t*)input_items[0]; + int16_t* out_short = (int16_t*)output_items[0]; + + for (i = 0; i < noi; i += 2) { + *out_short++ = in_short[i + 1]; + *out_short++ = in_short[i]; + } + } break; + case SWAPTYPE_BYTECOMPLEX: { + noi = noutput_items; + const char* in_byte = (const char*)input_items[0]; + char* out_byte = (char*)output_items[0]; + + for (i = 0; i < noi; i += 2) { + *out_byte++ = in_byte[i + 1]; + *out_byte++ = in_byte[i]; + } + } break; + default: { + GR_LOG_ERROR(d_logger, "Unknown data type. Bytes not swapped."); + return WORK_DONE; + } + } + + // Tell runtime system how many output items we produced. + return noutput_items; +} +} /* namespace blocks */ +} /* namespace gr */ diff --git a/pool/shard008/C++/0096731_LinkParserImpl.cpp b/pool/shard008/C++/0096731_LinkParserImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4432e663ff7a2bd809c96fef7e7cb6d1a21e7fa --- /dev/null +++ b/pool/shard008/C++/0096731_LinkParserImpl.cpp @@ -0,0 +1,33 @@ +#include "stdafx.h" +#include "LinkParserImpl.h" + +#include "ParserUtil.h" +#include "../../ui/NLink.h" + +IMPLEMENT_REFLECTION(LinkParserImpl); + +using namespace nui; +using namespace Ui; +using namespace Base; +using namespace Data; + +LinkParserImpl::LinkParserImpl() +{ + creator_ = &NBaseParser::BaseCreator; +} + +bool LinkParserImpl::IsCorrectObj(nui::Base::NBaseObj* targetObj) +{ + return targetObj != NULL && dynamic_cast(targetObj) != NULL; +} + +void LinkParserImpl::FillAttr(nui::Base::NBaseObj* targetObj, nui::Data::NDataReader* styleNode) +{ + __super::FillAttr(targetObj, styleNode); + + NString tmpString; + NLink* targetLink = dynamic_cast(targetObj); + + if(styleNode->ReadValue(_T("url"), tmpString)) + targetLink->SetUrl(tmpString); +} diff --git a/pool/shard008/C++/0096738_zhtmllistmodel.cpp b/pool/shard008/C++/0096738_zhtmllistmodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..253e180f46ee936b0128df3b97782f0be25dc335 --- /dev/null +++ b/pool/shard008/C++/0096738_zhtmllistmodel.cpp @@ -0,0 +1,151 @@ +/****************************************************************************** +* This file is part of Zee. +* +* Zee 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. +* +* Zee 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 Zee. If not, see . +******************************************************************************/ + +#include "zhtmllistmodel.h" + +ZHTMLListModel::ZHTMLListModel(QObject *parent) + : QAbstractListModel(parent) +{ + init(); +} + +ZHTMLListModel::ZHTMLListModel(QUrl base, QObject *parent) + : QAbstractListModel(parent){ + setBaseUrl(base); + init(); +} + +void ZHTMLListModel::init(){ + _matchRx.setPattern(ZHTML_LIST_DEFAULT_MATCH_RX); + _excludeRx.setPattern(ZHTML_LIST_DEFAULT_EXCLD_RX); + + connect(&_net, SIGNAL(finished(QNetworkReply*)), + this, SLOT(_finished(QNetworkReply*))); +} + +void ZHTMLListModel::setBaseUrl(QUrl base){ + _base = base; + fetchBase(); +} + +void ZHTMLListModel::setMatchExpression(QRegExp rx){ + if(rx.isValid()) + _matchRx = rx; +} + +void ZHTMLListModel::setMatchExpression(QString rx){ + QRegExp trx(rx); + if(trx.isValid()) + _matchRx = trx; +} + +void ZHTMLListModel::setExcludeExpression(QRegExp rx){ + if(rx.isValid()) + _excludeRx = rx; +} + +void ZHTMLListModel::setExcludeExpression(QString rx){ + QRegExp erx(rx); + if(erx.isValid()) + _excludeRx = erx; +} + + +int ZHTMLListModel::rowCount(const QModelIndex &parent) const{ + return _data.size(); +} + +QVariant ZHTMLListModel::data(const QModelIndex &index, int role) const{ + if(!index.isValid()) + return QVariant(); + if(index.row() >= _data.size()) + return QVariant(); + + switch(role){ + case Qt::DisplayRole: + return _labels.value(_data.at(index.row())); + case Qt::UserRole+1: + return _data.at(index.row()); + default: + return QVariant(); + } +} + +QVariant ZHTMLListModel::headerData(int section, + Qt::Orientation orientation, + int role) const{ + return QVariant("__HEADER__"); +} + +void ZHTMLListModel::fetchBase(){ + if(_base.isValid()){ + _data.clear(); + _labels.clear(); + + if(_cache.contains(_base.toString())){ + _processReplyData(_cache.value(_base.toString())); + }else{ + QNetworkRequest req; + req.setUrl(_base); + downloadStarted(); + _net.get(req); + } + } +} + +void ZHTMLListModel::_finished(QNetworkReply *r){ + + if(!r->error()){ + QString data(r->readAll()); + _cache.insert(_base.toString(), data); + _processReplyData(data); + }else{ + + } + + r->deleteLater(); +} + +void ZHTMLListModel::_downloadProgress(qint64 in, qint64 total){ + qreal perc = (100.0 / total) * in; + emit downloadProgress(perc); +} + +void ZHTMLListModel::_processReplyData(QString data){ + int pos = 0; + while( (pos = _matchRx.indexIn(data,pos)) != -1){ + QString d = _matchRx.cap(1); + QUrl du; + + if(_excludeRx.isValid() && _excludeRx.indexIn(d) == -1){ + du.setUrl(d); + if(d[0]=='/') + du = _base.scheme()+"://"+_base.authority()+d; + else if(QUrl(d).isRelative()) + du = _base.toString()+d; + + qDebug() << "URL: " << du.toString(); + _data.append(du.toString()); + _labels.insert(du.toString(), du.toString()); + } + + pos += _matchRx.matchedLength(); + } + + reset(); + downloadFinished(); +} diff --git a/pool/shard008/C++/0096740_examples.cpp b/pool/shard008/C++/0096740_examples.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60a4fbf0badd85b30d889527064ba40e5278cc71 --- /dev/null +++ b/pool/shard008/C++/0096740_examples.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2015-2019 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include + +// Sanity test: this should loop ten times, and +// min/max/average should be close to 100ms. +static void Sleep100ms(benchmark::State& state) +{ + while (state.KeepRunning()) { + MilliSleep(100); + } +} + +BENCHMARK(Sleep100ms, 10); + +// Extremely fast-running benchmark: +#include + +volatile double sum = 0.0; // volatile, global so not optimized away + +static void Trig(benchmark::State& state) +{ + double d = 0.01; + while (state.KeepRunning()) { + sum += sin(d); + d += 0.000001; + } +} + +BENCHMARK(Trig, 12 * 1000 * 1000); diff --git a/pool/shard008/C++/0096741_SignatureBuilder.cpp b/pool/shard008/C++/0096741_SignatureBuilder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f056a933d19d38c00038ed15d14f824dae7e327 --- /dev/null +++ b/pool/shard008/C++/0096741_SignatureBuilder.cpp @@ -0,0 +1,29 @@ +#include + +#include "SignatureBuilder.h" + +SignatureBuilder::SignatureBuilder(const QByteArray &secret) + : m_secret(secret) +{ + +} + +void SignatureBuilder::setParameters(const QList &values) +{ + for(const as::KeyValue &value : values) + { + m_parameters << value.asJoined(); + } +} + +QString SignatureBuilder::signature() const +{ + const QByteArray &joined = m_parameters + .join(QString::null) + .toUtf8(); + + const QByteArray &hash = QCryptographicHash::hash(joined + m_secret, QCryptographicHash::Md5); + const QByteArray &hex = hash.toHex(); + + return hex; +} diff --git a/pool/shard008/C++/0096747_CPStringTools.cpp b/pool/shard008/C++/0096747_CPStringTools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab4a97a4096e1a03f3697598984c0a92b12d1cfa --- /dev/null +++ b/pool/shard008/C++/0096747_CPStringTools.cpp @@ -0,0 +1,85 @@ +#include "CPStringTools.hpp" +#include +#include +#include +#include + +#include +#include + +#include "wiiu/types.h" + +bool CPStringTools::EndsWith(const std::string& a, const std::string& b) { + if (b.size() > a.size()) return false; + return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin()); +} + +std::vector CPStringTools::StringSplit(const std::string & inValue, const std::string & splitter){ + std::string value = inValue; + std::vector result; + while (true) { + u32 index = value.find(splitter); + if (index == std::string::npos) { + result.push_back(value); + break; + } + std::string first = value.substr(0, index); + result.push_back(first); + if (index + splitter.size() == value.length()) { + result.push_back(""); + break; + } + if(index + splitter.size() > value.length()) { + break; + } + value = value.substr(index + splitter.size(), value.length()); + } + return result; +} + +const char * CPStringTools::byte_to_binary(s32 x){ + static char b[9]; + b[0] = '\0'; + + s32 z; + for (z = 128; z > 0; z >>= 1) + { + strcat(b, ((x & z) == z) ? "1" : "0"); + } + + return b; +} + +std::string CPStringTools::removeCharFromString(std::string& input,char toBeRemoved){ + std::string output = input; + size_t position; + while(1){ + position = output.find(toBeRemoved); + if(position == std::string::npos) + break; + output.erase(position, 1); + } + return output; +} + + +std::string CPStringTools::strfmt(const char * format, ...){ + std::string str; + char * tmp = NULL; + + va_list va; + va_start(va, format); + if((vasprintf(&tmp, format, va) >= 0) && tmp) + { + str = tmp; + } + va_end(va); + + if(tmp){ + free(tmp); + tmp = NULL; + } + + return str; +} +//CPStringTools diff --git a/pool/shard008/C++/0096748_chordsdescriptors.cpp b/pool/shard008/C++/0096748_chordsdescriptors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69bd5b2fdcec4c69ea543b446c9b1d2c4374458d --- /dev/null +++ b/pool/shard008/C++/0096748_chordsdescriptors.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra + * + * This file is part of Essentia + * + * Essentia 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 (FSF), 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 Affero GNU General Public License + * version 3 along with this program. If not, see http://www.gnu.org/licenses/ + */ + +#include "chordsdescriptors.h" +#include "stringutil.h" + +using namespace std; + +namespace essentia { +namespace standard { + +const char* ChordsDescriptors::name = "ChordsDescriptors"; +const char* ChordsDescriptors::category = "Tonal"; +const char* ChordsDescriptors::description = DOC("Given a chord progression this algorithm describes it by means of key, scale, histogram, and rate of change.\n" +"Note:\n" +" - chordsHistogram indexes follow the circle of fifths order, while being shifted to the input key and scale\n" +" - key and scale are taken from the most frequent chord. In the case where multiple chords are equally frequent, the chord is hierarchically chosen from the circle of fifths.\n" +" - chords should follow this name convention `[<#/b>]` (i.e. C, C# or C#m are valid chords). Chord names not fitting this convention will throw an exception.\n" +"\n" +"Input chords vector may not be empty, otherwise an exception is thrown.\n" +"\n" +"References:\n" +" [1] Chord progression - Wikipedia, the free encyclopedia,\n" +" http://en.wikipedia.org/wiki/Chord_progression\n\n" +" [2] Circle of fifths - Wikipedia, the free encyclopedia,\n" +" http://en.wikipedia.org/wiki/Circle_of_fifths"); + +const char* ChordsDescriptors::circleOfFifth[] = { "C", "Em", "G", "Bm", "D", "F#m", "A", "C#m", "E", "Abm", "B", "Ebm", "F#", "Bbm", "C#", "Fm", "Ab", "Cm", "Eb", "Gm", "Bb", "Dm", "F", "Am"}; +const char* ChordsDescriptors::circleOfFifthAlternativeNames[] = { "C", "Em", "G", "Bm", "D", "Gbm", "A", "Dbm", "E", "G#m", "B", "D#m", "Gb", "A#m", "Db", "Fm", "G#", "Cm", "D#", "Gm", "A#", "Dm", "F", "Am"}; + + + +int ChordsDescriptors::chordIndex(const string& chord) { + for (int i=0; i ChordsDescriptors::chordsHistogram(const vector& chords) { + map histogram; + + // Initialize + for (int i=0; i ChordsDescriptors::chordsHistogramNorm(map& histogram, const string& key) { + int keyIndex = chordIndex(key); + map histogramNorm = histogram; + + for (int i=0; i& chords = _chords.get(); + + if (chords.empty()) { + throw EssentiaException("ChordsDescriptors: Chords input empty"); + } + + string key = _key.get(); + + if (key.empty()) { + throw EssentiaException("ChordsDescriptors: Key input empty"); + } + + key[0] = toUpper(string(1, key[0]))[0]; + + string scale = toLower(_scale.get()); + + if (scale.empty()) { + throw EssentiaException("ChordsDescriptors: Scale input empty"); + } + + if (_scale.get() == "minor") { + key += "m"; + } + + // Chords Histogram + map chordsHist = chordsHistogram(chords); + map chordsHistNorm = chordsHistogramNorm(chordsHist, key); + + vector& chordsHistNormVect = _chordsHistogram.get(); + chordsHistNormVect.resize(0); // erase anything that was in there + for (int i=0; i 1.0) { + chordNumberRate += 1.0; + } + } + chordNumberRate /= (Real)chords.size(); + + // Chords Changes Rate + Real& chordChangesRate = _chordsChangesRate.get(); + chordChangesRate = 0.0; + for (int i=1; i maxValue) { + maxValue = chordsHist[i]; + chordsKey = circleOfFifth[i]; + } + } + + bool major = true; + string::size_type position = chordsKey.find("m"); + + if ((position == 1) || (position == 2)) { + major = false; + } + + if (major) { + chordsKey = chordsKey; + chordsScale = "major"; + } + else { + chordsKey = chordsKey.substr(0, position); + chordsScale = "minor"; + } +} + +} // namespace standard +} // namespace essentia + + + +namespace essentia { +namespace streaming { + +const char* ChordsDescriptors::name = standard::ChordsDescriptors::name; +const char* ChordsDescriptors::description = standard::ChordsDescriptors::description; + + +AlgorithmStatus ChordsDescriptors::process() { + // this could be implemented as a composite, but it is kept like this for + // historical and demonstrations reasons + while (_chords.acquire(1)) { + _accu.push_back(*(std::string*)_chords.getFirstToken()); + _chords.release(1); + } + + if (!shouldStop()) return PASS; + + // make sure we have one value for key and scale + if (!_key.acquire(1) || !_scale.acquire(1)) { + return NO_INPUT; + } + + standard::Algorithm* algo = _chordsAlgo; + string key = *(string*)_key.getFirstToken(); + string scale = *(string*)_scale.getFirstToken(); + vector chordsHist; + Real cnr, ccr; + string ckey, cscale; + + algo->input("chords").set(_accu); + algo->input("key").set(key); + algo->input("scale").set(scale); + algo->output("chordsHistogram").set(chordsHist); + algo->output("chordsNumberRate").set(cnr); + algo->output("chordsChangesRate").set(ccr); + algo->output("chordsKey").set(ckey); + algo->output("chordsScale").set(cscale); + algo->compute(); + + _chordsHistogram.push(chordsHist); + _chordsNumberRate.push(cnr); + _chordsChangesRate.push(ccr); + _chordsKey.push(ckey); + _chordsScale.push(cscale); + + return FINISHED; +} + +void ChordsDescriptors::reset() { + Algorithm::reset(); + _accu.clear(); + if (_chordsAlgo) _chordsAlgo->reset(); +} + + +} // namespace streaming +} // namespace essentia diff --git a/pool/shard008/C++/0096750_web_task_runner_impl.cc b/pool/shard008/C++/0096750_web_task_runner_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..922ca4a95ed81793f7c6b432c13549c611d3d8bb --- /dev/null +++ b/pool/shard008/C++/0096750_web_task_runner_impl.cc @@ -0,0 +1,73 @@ +// 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/scheduler/child/web_task_runner_impl.h" + +#include "base/bind.h" +#include "base/location.h" +#include "components/scheduler/base/task_queue.h" +#include "components/scheduler/base/time_domain.h" +#include "third_party/WebKit/public/platform/WebTraceLocation.h" + +namespace scheduler { + +WebTaskRunnerImpl::WebTaskRunnerImpl(scoped_refptr task_queue) + : task_queue_(task_queue) {} + +WebTaskRunnerImpl::~WebTaskRunnerImpl() {} + +void WebTaskRunnerImpl::postTask(const blink::WebTraceLocation& web_location, + blink::WebTaskRunner::Task* task) { + tracked_objects::Location location(web_location.functionName(), + web_location.fileName(), -1, nullptr); + task_queue_->PostTask( + location, + base::Bind( + &WebTaskRunnerImpl::runTask, + base::Passed(std::unique_ptr(task)))); +} + +void WebTaskRunnerImpl::postDelayedTask( + const blink::WebTraceLocation& web_location, + blink::WebTaskRunner::Task* task, + double delayMs) { + DCHECK_GE(delayMs, 0.0); + tracked_objects::Location location(web_location.functionName(), + web_location.fileName(), -1, nullptr); + task_queue_->PostDelayedTask( + location, + base::Bind( + &WebTaskRunnerImpl::runTask, + base::Passed(std::unique_ptr(task))), + base::TimeDelta::FromMillisecondsD(delayMs)); +} + +double WebTaskRunnerImpl::virtualTimeSeconds() const { + return (Now() - base::TimeTicks::UnixEpoch()).InSecondsF(); +} + +double WebTaskRunnerImpl::monotonicallyIncreasingVirtualTimeSeconds() const { + return Now().ToInternalValue() / + static_cast(base::Time::kMicrosecondsPerSecond); +} + +base::TimeTicks WebTaskRunnerImpl::Now() const { + TimeDomain* time_domain = task_queue_->GetTimeDomain(); + // It's possible task_queue_ has been Unregistered which can lead to a null + // TimeDomain. If that happens just return the current real time. + if (!time_domain) + return base::TimeTicks::Now(); + return time_domain->Now(); +} + +blink::WebTaskRunner* WebTaskRunnerImpl::clone() { + return new WebTaskRunnerImpl(task_queue_); +} + +void WebTaskRunnerImpl::runTask( + std::unique_ptr task) { + task->run(); +} + +} // namespace scheduler diff --git a/pool/shard008/C++/0096756_stylemodel.cpp b/pool/shard008/C++/0096756_stylemodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe11f60f0c301d6646dd0b987cd65d07e2d7e528 --- /dev/null +++ b/pool/shard008/C++/0096756_stylemodel.cpp @@ -0,0 +1,236 @@ +/* + * + * Copyright (C) 2016 Arek + * + * 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 "stylemodel.h" +#include +#include +#include + +StyleModel *StyleModel::model; + +StyleModel::StyleModel() +{ + loadColors(); +} + +StyleModel::~StyleModel() +{ + +} + +void StyleModel::loadColors() +{ + QFile f(QDir::currentPath() + "/defaultstyles.xml"); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) + { + surpressSignals = true; + addStyle("default", Qt::black, Qt::white); + addStyle("black", Qt::white, Qt::black); + addStyle("lightgray", Qt::black, Qt::lightGray); + addStyle("darkgray", Qt::white, Qt::darkGray); + addStyle("brownish", Qt::black, Qt::darkYellow); + addStyle("cyan", Qt::black, Qt::cyan); + addStyle("red", Qt::white, Qt::darkRed); + //addColor("", Qt::, Qt::); + surpressSignals = false; + return; + } + QXmlStreamReader reader(&f); + QXmlStreamAttributes attr; + + while (!reader.atEnd()) { + reader.readNext(); + if (reader.isStartElement() && reader.name() == "styles") + loadStyles(reader); + } + f.close(); + surpressSignals = false; + emit stylesChanged(All, nullptr); +} + +void StyleModel::addStyle(QString name, QColor fg, QColor bg) +{ + while (styles.contains(name)) + name += "_"; + Style *newStyle = new Style(name, fg, bg); + styles.insert(name, newStyle); + stylesByPointer[newStyle] = name; + if (!surpressSignals) + emit stylesChanged(StyleModel::New, newStyle); +} + +void StyleModel::addStyle(Style* style) +{ + while (styles.contains(style->name)) + style->name += "_"; + styles.insert(style->name, style); + stylesByPointer[style] = style->name; + if (!surpressSignals) + emit stylesChanged(StyleModel::New, style); +} + + +QVariant StyleModel::getBrushV(QString name, int role) const +{ + if (name == "") + return getBrushV("default", role); + QBrush brush; + if (role == Qt::ForegroundRole) + brush.setColor(styles[name]->fg.color()); + else + brush = styles[name]->bg; + return QVariant(brush); +} + +QColor StyleModel::getColor(QString name, int role) +{ + if (name == "") + return getColor("default", role); + if (!styles.contains(name)) { + qDebug() << "no style named " << name; + return QColor(); + } + if (role == Qt::ForegroundRole) + return styles[name]->fg.color(); + else if (role == Qt::BackgroundRole) + return styles[name]->bg.color(); + else + qDebug() << "WTF???"; +} + +void StyleModel::deleteStyle(Style* style) +{ + if (style->name == "default") + return; + if (styles[style->name] == style) + delete styles.take(style->name); + else { + QString name = stylesByPointer[style]; + delete styles.take(name); + } + stylesByPointer.remove(style); + if (!surpressSignals) + emit stylesChanged(StyleModel::Delete, style); +} + +void StyleModel::deleteStyle(QString style) +{ + deleteStyle(styles[style]); +} + + +bool StyleModel::styleChangedOk(Style* style) +{ + if (styles.value(style->name) == style) { + if (!surpressSignals) + emit stylesChanged(StyleModel::Edit, style); + return true; + } + bool result = true; + while (styles.contains(style->name)) { + result = false; + style->name += "_"; + } + + QString name = stylesByPointer.take(style); + styles.remove(name); + styles[style->name] = style; + stylesByPointer[style] = name; + if (!surpressSignals) + emit stylesChanged(StyleModel::Name, style); + return result; +} + +QFont StyleModel::getFont(QString name) const +{ + if (styles.contains(name)) + return styles[name]->font; + return QFont(); +} + +bool StyleModel::loadStyles(QXmlStreamReader& reader) +{ + surpressSignals = true; + foreach (Style *style, stylesByPointer.keys()) + delete style; + stylesByPointer.clear(); + styles.clear(); + + QXmlStreamAttributes attr; + while (!reader.atEnd()) { + reader.readNext(); + + if (reader.isEndElement() && reader.name() == "styles" ) + break; + if ( (reader.isEndElement() && reader.name() != "style" ) + || reader.isEndDocument()) { + qDebug() << "not ok"; + surpressSignals = false; + return false; + } + if (!reader.isStartElement() || reader.name() != "style") + continue; + + attr = reader.attributes(); + Style *style = new Style( + attr.value("name").toString(), + QColor(attr.value("fg").toString()), + QColor(attr.value("bg").toString()) + ); + style->setFont(attr.value("font").toString()); + style->setSize(attr.value("maxFontSize").toDouble()); + addStyle(style); + } + surpressSignals = false; + emit stylesChanged(All, nullptr); +} + +void StyleModel::saveStyles(QXmlStreamWriter& writer) +{ + writer.writeStartElement("styles"); + foreach(Style *style, stylesByPointer.keys()) { + writer.writeStartElement("style"); + writer.writeAttribute("name", style->name); + writer.writeAttribute("fg", style->fg.color().name()); + writer.writeAttribute("bg", style->bg.color().name()); + writer.writeAttribute("font", style->font.family()); + writer.writeAttribute("maxFontSize", QString::number(style->font.pointSizeF())); + writer.writeEndElement(); + } + writer.writeEndElement(); +} + +void StyleModel::saveDefaultStyles() +{ + QFile f(QDir::currentPath() + "/defaultstyles.xml"); + if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) + { + qDebug() << "could not open \"defaultstyles.xml\" for writing"; + return; + } + QXmlStreamWriter writer(&f); + writer.setAutoFormatting(true); + writer.writeStartDocument(); + saveStyles(writer); + writer.writeEndDocument(); + f.close(); +} + + + diff --git a/pool/shard008/C++/0096760_Wizard.cc b/pool/shard008/C++/0096760_Wizard.cc new file mode 100644 index 0000000000000000000000000000000000000000..0c5cb78118a4beceaed0bc7e796756242ef119b7 --- /dev/null +++ b/pool/shard008/C++/0096760_Wizard.cc @@ -0,0 +1,29 @@ +#include "Wizard.hh" + +Wizard::Wizard(string alias, int wisdom) : Character(alias){ + this->wisdom = wisdom; +} + +int Wizard::getDefensePts(){ + return (int)Character::getDefensePts()+(wisdom/2); +} + +void Wizard::addWisdom(int w){ + wisdom += w; + if(wisdom>100){wisdom = 100;} +} + +bool Wizard::special(Team* team){ + if(MP < 100){return false;} + MP -= 100-wisdom; + int i=0; + while(!team->getChar(i)->isAlive()){i++;} + team->getChar(i)->receiveDamage(100); + return true; +} + +string Wizard::specialDesc(){ + + return "2 - Necromancia: Retira a alma de um oponente. (aprox. -100MP)\n"; + +} diff --git a/pool/shard008/C++/0096762_Ultosc.cpp b/pool/shard008/C++/0096762_Ultosc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf8bd8560db38791e5e6acd7b323db126931cb17 --- /dev/null +++ b/pool/shard008/C++/0096762_Ultosc.cpp @@ -0,0 +1,91 @@ +// Ultosc.cpp: implementation of the Ultosc class. +// +////////////////////////////////////////////////////////////////////// + +#include "Ultosc.h" +#include "CandleData.h" +#include "ta_libc.h" + +double getULTOSC(const unsigned int period1, const unsigned int period2, const unsigned int period3, CandleData * data, long numSticks) +{ + double ultosc = 0.0; + + double * highData = CandleData::getData(data, CandleData::HIGH,numSticks); + double * lowData = CandleData::getData(data, CandleData::LOW, numSticks); + double * closeData = CandleData::getData(data, CandleData::CLOSE, numSticks); + + int outNbElement = 0; + int outBeg = 0; + + double * ultoscDataOut = new double[numSticks + period3]; + + TA_RetCode ultoscRet = + TA_ULTOSC( 0, + numSticks -1, + highData, + lowData, + closeData, + period1, + period2, + period3, + &outBeg, + &outNbElement, + ultoscDataOut); + + if(outNbElement == 0) + { + ultosc = 0.0; + } + else + { + ultosc = ultoscDataOut[outNbElement - 1]; + } + + delete [] highData; + delete [] lowData; + delete [] closeData; + delete [] ultoscDataOut; + + return ultosc; +} + +double * getAllULTOSC(const unsigned int period1, const unsigned int period2, const unsigned int period3, CandleData * data, long numSticks) +{ + double ultosc = 0.0; + + double * highData = CandleData::getData(data, CandleData::HIGH,numSticks); + double * lowData = CandleData::getData(data, CandleData::LOW, numSticks); + double * closeData = CandleData::getData(data, CandleData::CLOSE, numSticks); + + int outNbElement = 0; + int outBeg = 0; + + int arraySize = numSticks + period1; + double * ultoscDataOut = new double[arraySize]; + memset(ultoscDataOut,0,arraySize * sizeof(double)); + + TA_RetCode ultoscRet = + TA_ULTOSC( 0, + numSticks -1, + highData, + lowData, + closeData, + period1, + period2, + period3, + &outBeg, + &outNbElement, + ultoscDataOut); + + double * ret = new double[arraySize + outBeg]; + memset(ret,0,(arraySize + outBeg) * sizeof(double)); + memcpy(&ret[outBeg],ultoscDataOut,arraySize*sizeof(double)); + + delete [] highData; + delete [] lowData; + delete [] closeData; + delete [] ultoscDataOut; + + return ret; +} + diff --git a/pool/shard008/C++/0096765_2.cc b/pool/shard008/C++/0096765_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..cf7ac4cde10e420c648a29a76844021192c01f07 --- /dev/null +++ b/pool/shard008/C++/0096765_2.cc @@ -0,0 +1,64 @@ +// 2002-05-24 bkoz + +// Copyright (C) 2002, 2003, 2009 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 +// . + + +// 22.2.1.3.2 ctype members + +#include +#include +#include + +void test02() +{ + using namespace std; + typedef wchar_t wide_type; + + bool test __attribute__((unused)) = true; + const char dfault = '?'; + const locale loc_c = locale::classic(); + const ctype& ctype_c = use_facet >(loc_c); + + // Construct non-asci string. + basic_string wide(L"wibble"); + wide += wide_type(1240); + wide += L"kibble"; + basic_string narrow("wibble"); + narrow += dfault; + narrow += "kibble"; + vector narrow_chars(wide.length() + 1); + + // narrow(charT c, char dfault) const + for (size_t i = 0; i < wide.length(); ++i) + { + char c = ctype_c.narrow(wide[i], dfault); + VERIFY( c == narrow[i] ); + } + + // narrow(const charT* low, const charT* high, char dfault, char* dest) const + ctype_c.narrow(&wide[0], &wide[0] + wide.length(), dfault, &narrow_chars[0]); + VERIFY( narrow_chars[0] != dfault ); + for (size_t i = 0; i < wide.length(); ++i) + VERIFY( narrow_chars[i] == narrow[i] ); +} + +int main() +{ + test02(); + return 0; +} diff --git a/pool/shard008/C++/0096766_debugger_x64.cc b/pool/shard008/C++/0096766_debugger_x64.cc new file mode 100644 index 0000000000000000000000000000000000000000..883880f1fbb2d3f4333aa3f81d2ea6cc8d8962d6 --- /dev/null +++ b/pool/shard008/C++/0096766_debugger_x64.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "vm/globals.h" +#if defined(TARGET_ARCH_X64) + +#include "vm/debugger.h" + +#include "vm/code_patcher.h" +#include "vm/compiler/assembler/assembler.h" +#include "vm/cpu.h" +#include "vm/instructions.h" +#include "vm/stub_code.h" + +namespace dart { + +#ifndef PRODUCT + +RawCode* CodeBreakpoint::OrigStubAddress() const { + return saved_value_; +} + +void CodeBreakpoint::PatchCode() { + ASSERT(!is_enabled_); + Code& stub_target = Code::Handle(); + switch (breakpoint_kind_) { + case RawPcDescriptors::kIcCall: + stub_target = StubCode::ICCallBreakpoint().raw(); + break; + case RawPcDescriptors::kUnoptStaticCall: + stub_target = StubCode::UnoptStaticCallBreakpoint().raw(); + break; + case RawPcDescriptors::kRuntimeCall: + stub_target = StubCode::RuntimeCallBreakpoint().raw(); + break; + default: + UNREACHABLE(); + } + const Code& code = Code::Handle(code_); + saved_value_ = CodePatcher::GetStaticCallTargetAt(pc_, code); + CodePatcher::PatchPoolPointerCallAt(pc_, code, stub_target); + is_enabled_ = true; +} + +void CodeBreakpoint::RestoreCode() { + ASSERT(is_enabled_); + const Code& code = Code::Handle(code_); + switch (breakpoint_kind_) { + case RawPcDescriptors::kIcCall: + case RawPcDescriptors::kUnoptStaticCall: + case RawPcDescriptors::kRuntimeCall: { + CodePatcher::PatchPoolPointerCallAt(pc_, code, + Code::Handle(saved_value_)); + break; + } + default: + UNREACHABLE(); + } + is_enabled_ = false; +} + +#endif // !PRODUCT + +} // namespace dart + +#endif // defined TARGET_ARCH_X64 diff --git a/pool/shard008/C++/0096767_timing.cpp b/pool/shard008/C++/0096767_timing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91513d0b9288fb6aa165b36cd32ac24aa215a50e --- /dev/null +++ b/pool/shard008/C++/0096767_timing.cpp @@ -0,0 +1,36 @@ +extern "C" { +#include "mexutil.h" +} +#include "string.h" + +void DoWork(double *outp, double *inp, int sz, int ntrials); + +void mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[]) +{ + mxArray *result, *addrs; + double *paddr; + int i,niter; + mwSize m, n; + double *outp, *inp; + mwSize sz; + m = mxGetM(prhs[0]); + n = mxGetN(prhs[0]); + niter = (int)*mxGetPr(prhs[1]); + if(nlhs > 1) { + addrs = mxCreateDoubleMatrix(niter,1,mxREAL); + paddr = mxGetPr(addrs); + } + for(i=0;i 0) mxDestroyArray(result); + result = mxCreateDoubleMatrix(m,n,mxREAL); + outp = mxGetPr(result); + //inp = mxGetPr(prhs[0]); + //sz = mxGetNumberOfElements(prhs[0]); + //memcpy(outp, inp, sz*sizeof(double)); + //DoWork(outp, inp, sz, 1); + if(nlhs > 1) paddr[i] = (double)(long)outp; + } + if(nlhs > 0) plhs[0] = result; + if(nlhs > 1) plhs[1] = addrs; +} diff --git a/pool/shard008/C++/0096771_InputStringBuf.cc b/pool/shard008/C++/0096771_InputStringBuf.cc new file mode 100644 index 0000000000000000000000000000000000000000..6252cb2fe1ab7a83b0114d1191eeb12b2b8881e5 --- /dev/null +++ b/pool/shard008/C++/0096771_InputStringBuf.cc @@ -0,0 +1,33 @@ +// +// InputStringBuf +// taskwarrior-ios +// +// Created by david on 5/7/14. +// Copyright 2014 David Whetstone. All rights reserved. +// + +#include +#include "InputStringBuf.h" + +InputStringBuf::InputStringBuf() : _waiting_for_input(false) +{ + +} + +InputStringBuf::int_type InputStringBuf::underflow() +{ + std::unique_lock lock(_input_mutex); + + _waiting_for_input = true; + _has_input.wait(lock, [this](){ return !str().empty(); }); + _waiting_for_input = false; + + return basic_stringbuf::underflow(); +} + + +void InputStringBuf::set_str(std::string const &__s) +{ + basic_stringbuf::str(__s + "\n"); + _has_input.notify_one(); +} diff --git a/pool/shard008/C++/0096772_updateenvironmentresponse.cpp b/pool/shard008/C++/0096772_updateenvironmentresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40d7b11707097d8828af5ac7605f0a70c2eeeaa4 --- /dev/null +++ b/pool/shard008/C++/0096772_updateenvironmentresponse.cpp @@ -0,0 +1,101 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws 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. + + QtAws 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 the QtAws. If not, see . +*/ + +#include "updateenvironmentresponse.h" +#include "updateenvironmentresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace finspace { + +/*! + * \class QtAws::finspace::UpdateEnvironmentResponse + * \brief The UpdateEnvironmentResponse class provides an interace for finspace UpdateEnvironment responses. + * + * \inmodule QtAwsfinspace + * + * The FinSpace management service provides the APIs for managing the FinSpace environments. + * + * \sa finspaceClient::updateEnvironment + */ + +/*! + * Constructs a UpdateEnvironmentResponse object for \a reply to \a request, with parent \a parent. + */ +UpdateEnvironmentResponse::UpdateEnvironmentResponse( + const UpdateEnvironmentRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : finspaceResponse(new UpdateEnvironmentResponsePrivate(this), parent) +{ + setRequest(new UpdateEnvironmentRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const UpdateEnvironmentRequest * UpdateEnvironmentResponse::request() const +{ + Q_D(const UpdateEnvironmentResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful finspace UpdateEnvironment \a response. + */ +void UpdateEnvironmentResponse::parseSuccess(QIODevice &response) +{ + //Q_D(UpdateEnvironmentResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::finspace::UpdateEnvironmentResponsePrivate + * \brief The UpdateEnvironmentResponsePrivate class provides private implementation for UpdateEnvironmentResponse. + * \internal + * + * \inmodule QtAwsfinspace + */ + +/*! + * Constructs a UpdateEnvironmentResponsePrivate object with public implementation \a q. + */ +UpdateEnvironmentResponsePrivate::UpdateEnvironmentResponsePrivate( + UpdateEnvironmentResponse * const q) : finspaceResponsePrivate(q) +{ + +} + +/*! + * Parses a finspace UpdateEnvironment response element from \a xml. + */ +void UpdateEnvironmentResponsePrivate::parseUpdateEnvironmentResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("UpdateEnvironmentResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace finspace +} // namespace QtAws diff --git a/pool/shard008/C++/0096778_matmul_wrapper.cpp b/pool/shard008/C++/0096778_matmul_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a98f6ec206f3a9695a0bcbcb3da2512013a0643 --- /dev/null +++ b/pool/shard008/C++/0096778_matmul_wrapper.cpp @@ -0,0 +1,85 @@ +#include +#include +#include "generated_matmul.o.h" +#include "../../benchmarks.h" +#include "configure.h" +#include + + +int matmul_ref(Halide::Buffer A, Halide::Buffer B, Halide::Buffer C) +{ + for (int i = 0; i < LL; i++){ + for (int j = 0; j < NN; j++){ + C(j, i) = 0; + for (int k = 0; k < MM; k++){ + C(j, i) += A(k, i)* B(j, k); + } + } + } + + + return 0; +} + +int main(int argc, char** argv) +{ + std::vector> duration_vector_1, duration_vector_2; + Halide::Buffer b_A(MM, LL), b_B(NN, MM), b_C(NN, MM), b_C_ref(NN, MM); + + + // --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // --------------------------------------------------------------------- + //REFERENCE + { + for (int i = 0; i < 1; ++i) + { + init_buffer(b_A, (double) 5); + b_A (1,2) = 11; + init_buffer(b_B, (double) 3); + + auto start = std::chrono::high_resolution_clock::now(); + + + matmul_ref(b_A, b_B, b_C_ref); + + auto end = std::chrono::high_resolution_clock::now(); + duration_vector_1.push_back(end - start); + } + + } + + //TIRAMISU + { + for (int i = 0; i < NB_TESTS; ++i) + { + init_buffer(b_A, (double) 5); + b_A (1,2)=11; + init_buffer(b_B, (double) 3); + auto start = std::chrono::high_resolution_clock::now(); + + matmul(b_A.raw_buffer(), b_B.raw_buffer(), b_C.raw_buffer()); + + auto end = std::chrono::high_resolution_clock::now(); + duration_vector_2.push_back(end - start); + } + } + + print_time("performance_cpu.csv", "matmul", + {"Ref", "Tiramisu"}, + {median(duration_vector_1), median(duration_vector_2)}); + + if (CHECK_CORRECTNESS) + compare_buffers("matmul", b_C_ref, b_C); + + if (PRINT_OUTPUT) + { + std::cout << "Tiramisu " << std::endl; + print_buffer(b_C); + std::cout << "Reference " << std::endl; + print_buffer(b_C_ref); + } + + + return 0; +} diff --git a/pool/shard008/C++/0096783_ofstream_insert_int.cc b/pool/shard008/C++/0096783_ofstream_insert_int.cc new file mode 100644 index 0000000000000000000000000000000000000000..cd1363cdf53eebf2f2f199691af79b7abf354296 --- /dev/null +++ b/pool/shard008/C++/0096783_ofstream_insert_int.cc @@ -0,0 +1,41 @@ +// Copyright (C) 2003-2021 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 +#include + +// libstdc++/8761 poor fstream performance +int main() +{ + using namespace std; + using namespace __gnu_test; + + time_counter time; + resource_counter resource; + const int iterations = 10000000; + + ofstream out("tmp_perf_int.txt"); + start_counters(time, resource); + for (int i = 0; i < iterations; ++i) + out << i << "\n"; + stop_counters(time, resource); + report_performance(__FILE__, "", time, resource); + + unlink("tmp_perf_int.txt"); + return 0; +} diff --git a/pool/shard008/C++/0096787_random.cpp b/pool/shard008/C++/0096787_random.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c461b45ad2fa77a2a347a128e96d2ce1205f2db --- /dev/null +++ b/pool/shard008/C++/0096787_random.cpp @@ -0,0 +1,95 @@ +/****************************************************************************** + * Wormux is a convivial mass murder game. + * Copyright (C) 2001-2007 Wormux 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + ****************************************************************************** + * Functions to generate random datas (number, boolean, etc.). + *****************************************************************************/ + +#include +#include +#include +#include +#include "random.h" + +Random randomObj; + +Random::Random() +{ + srand(time(NULL)); +} + +int Random::GetSign() +{ + if(rand() % 2) return 1; + else return -1; +} + +bool Random::GetBool() +{ + return rand() % 2 == 0; +} + +// Get a random value between min and max +long Random::GetLong(long min, long max) +{ + return min + (long)GetDouble(max - min + 1); +} + +int Random::GetInt(int min, int max) +{ + return GetLong(min, max); +} + +double Random::GetDouble(double min, double max) +{ + return min + GetDouble(max - min); +} + +double Random::GetDouble(double max) +{ + return max * GetDouble(); +} + +/** + * Get a random number between 0.0 and 1.0 + * + * @return A number between 0.0 and 1.0 + */ +double Random::GetDouble() +{ + return 1.0 * rand() / (RAND_MAX + 1.0); +} + +/** + * Return a random point in the given rectangle. + * + * @param rect The rectangle in which the returned point will be. + * @return a random point. + */ +Point2i Random::GetPoint(const Rectanglei &rect) +{ + Point2i topPoint = rect.GetPosition(); + Point2i bottomPoint = rect.GetBottomRightPoint(); + + return Point2i( GetLong(topPoint.x, bottomPoint.x), + GetLong(topPoint.y, bottomPoint.y) ); +} + +Point2i Random::GetPoint(const Point2i &pt) +{ + return Point2i( GetLong(0, pt.x - 1), GetLong(0, pt.y - 1) ); +} diff --git a/pool/shard008/C++/0096789_engineMain.cpp b/pool/shard008/C++/0096789_engineMain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e428323fa3db35ed467593fe6d42d98ac83caa0e --- /dev/null +++ b/pool/shard008/C++/0096789_engineMain.cpp @@ -0,0 +1,99 @@ + +#include "engine.h" +#include "../input/keyboard.h" +#include "../input/mouse.h" + +extern void engineMain(int argc, char** argv); + +TR_CHANNEL(CGE_Main); + +#ifdef WIN32 + +int WINAPI WinMain(HINSTANCE instance, HINSTANCE oldinstance, LPTSTR cmdline, int cmdShow){ + //_CrtSetBreakAlloc(729); + std::vector args; + std::vector argv; + args.push_back("Captains Game Engine"); +#ifdef UNDER_CE + char tmp[1024]; + wcstombs(tmp, cmdline, 1024); + args.push_back(tmp); +#else + int len = (int)strlen(cmdline); + std::string curr; + bool acceptWs = false; + for (int i = 0; i < len; ++i){ + if (cmdline[i] == '"'){ + acceptWs = !acceptWs; + continue; + } + if (!acceptWs && cmdline[i] == ' ' && !curr.empty()){ + args.push_back(curr); + curr.clear(); + } + else + curr.append(1, cmdline[i]); + } + if (!curr.empty()){ + args.push_back(curr); + curr.clear(); + } +#endif + argv.resize(args.size()); + for (unsigned i = 0; i < args.size(); ++i){ + argv[i] = args[i].c_str(); + } + return CGE::Engine::mainLoop((int)argv.size(), (char**)&argv[0], engineMain); +} +#endif + +/*#include "../window/nativeLinux.h" +#include "../input/keyboard.h" +#include "../renderer/renderer.h" +#include "../renderer/font.h" +#include "../gui/gui.h"*/ + +#if defined(LINUX) && !defined(NO_X11) +#include +#include + +int main(int argc, char** argv){ + return CGE::Engine::mainLoop(argc, argv, engineMain); +} +#endif + +#ifdef ANDROID +#include + +__attribute__((visibility("default"))) +void android_main(struct android_app* app){ + TR_USE(CGE_Main); + app_dummy(); + + /*JNIEnv *env; +app->activity->vm->AttachCurrentThread(&env, 0); + +jobject me = app->activity->clazz; + +jclass acl = env->GetObjectClass(me); //class pointer of NativeActivity +jmethodID giid = env->GetMethodID(acl, "getIntent", "()Landroid/content/Intent;"); +jobject intent = env->CallObjectMethod(me, giid); //Got our intent + +jclass icl = env->GetObjectClass(intent); //class pointer of Intent +jmethodID gseid = env->GetMethodID(icl, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;"); + +jstring jsParam1 = (jstring) env->CallObjectMethod(intent, gseid, env->NewStringUTF("arguments")); +const char *param = env->GetStringUTFChars(jsParam1, 0); +TR_INFO("args %s\n", param); +//When done with it, or when you've made a copy +env->ReleaseStringUTFChars(jsParam1, param); + +//Same for Param2*/ + + int argc = 1; + char* arg = "cge"; + char** argv = &arg; + CGE::Engine::mainLoop(argc, argv, engineMain, app); +} + +#endif \ No newline at end of file diff --git a/pool/shard008/C++/0096792_customcomputeshaderrenderer.cpp b/pool/shard008/C++/0096792_customcomputeshaderrenderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b8dd87d377713d455419b4a6a3a4d577b71a5cb --- /dev/null +++ b/pool/shard008/C++/0096792_customcomputeshaderrenderer.cpp @@ -0,0 +1,164 @@ +#include "pch.h" +#include "CustomComputeShaderRenderer.h" +#include "DirectXHelper.h" + +using namespace CustomComputeShader; + +using namespace DirectX; +using namespace Microsoft::WRL; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::Graphics::Display; +using namespace Windows::UI::Core; + +CustomComputeShaderRenderer::CustomComputeShaderRenderer(const std::shared_ptr& deviceResources) : + m_deviceResources(deviceResources) +{ + CreateDeviceIndependentResources(); + CreateDeviceDependentResources(); + CreateWindowSizeDependentResources(); +} + +void CustomComputeShaderRenderer::CreateDeviceIndependentResources() +{ + auto wicFactory = m_deviceResources->GetWicImagingFactory(); + auto d2dFactory = m_deviceResources->GetD2DFactory(); + + // Create WIC Decoder to read JPG file. + ComPtr decoder; + DX::ThrowIfFailed( + wicFactory->CreateDecoderFromFilename( + L"Assets\\mammoth.jpg", + nullptr, + GENERIC_READ, + WICDecodeMetadataCacheOnDemand, + &decoder + )); + + ComPtr frame; + DX::ThrowIfFailed(decoder->GetFrame(0, &frame)); + + DX::ThrowIfFailed(wicFactory->CreateFormatConverter(&m_formatConvert)); + DX::ThrowIfFailed(m_formatConvert->Initialize( + frame.Get(), + GUID_WICPixelFormat32bppPBGRA, // 32bppPBGRA is used by Direct2D. + WICBitmapDitherTypeNone, + nullptr, + 0.0f, + WICBitmapPaletteTypeCustom + )); + + UINT width; + UINT height; + DX::ThrowIfFailed(m_formatConvert->GetSize(&width, &height)); + m_imageSize = D2D1::SizeU(width, height); + + // Register the custom discrete Fourier transform effect. + DX::ThrowIfFailed(DftEffect::Register(d2dFactory)); +} + +void CustomComputeShaderRenderer::CreateDeviceDependentResources() +{ + auto d2dContext = m_deviceResources->GetD2DDeviceContext(); + + // Load the image from WIC using ImageSource. The image is scaled using + // ID2D1TransformedImageSource which is dependent on the scale factor. + DX::ThrowIfFailed(d2dContext->CreateImageSourceFromWic(m_formatConvert.Get(), &m_imageSource)); + + DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_CustomDftEffect, &m_dftEffect)); +} + +void CustomComputeShaderRenderer::ReleaseDeviceDependentResources() +{ + m_imageSource.Reset(); + m_transformedImage.Reset(); + m_dftEffect.Reset(); +} + +void CustomComputeShaderRenderer::CreateWindowSizeDependentResources() +{ + // Scale using pixel (not DIPs) because layout calculations are pixel-dependent. + auto size = m_deviceResources->GetOutputSize(); + + m_scale = min( + (size.Width / m_imageSize.width) / 2.0f, + (size.Height / m_imageSize.height) / 2.0f + ); + + UpdateImageScale(m_scale); +} + +// Sets up the image effect pipeline to reflect the new scale factor. +void CustomComputeShaderRenderer::UpdateImageScale(float scale) +{ + auto d2dContext = m_deviceResources->GetD2DDeviceContext(); + + // When using ID2D1ImageSource, the recommend method of applying a transform + // is to use ID2D1TransformedImageSource. It is inexpensive to recreate this object. + D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES props = + { + D2D1_ORIENTATION_DEFAULT, + scale, + scale, + D2D1_INTERPOLATION_MODE_LINEAR, // This is ignored when using DrawImage. + D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_DISABLE_DPI_SCALE // Does not apply the context's DPI. + }; + + DX::ThrowIfFailed(d2dContext->CreateTransformedImageSource( + m_imageSource.Get(), + &props, + &m_transformedImage)); + + m_dftEffect->SetInput(0, m_transformedImage.Get()); +} + +void CustomComputeShaderRenderer::Render() +{ + auto d2dContext = m_deviceResources->GetD2DDeviceContext(); + auto renderTargetSize = m_deviceResources->GetOutputSize(); + + d2dContext->BeginDraw(); + m_deviceResources->GetD2DDeviceContext()->SetTransform(m_deviceResources->GetOrientationTransform2D()); + d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue)); + + // Calculate display positioning for the scaled image and DFT effect. + float scaledWidth = m_imageSize.width * m_scale; + float scaledHeight = m_imageSize.height * m_scale; + float horizontalMargin = ((renderTargetSize.Width / 2 - scaledWidth) / 2.0f); + + // Clip values nearest whole pixel to prevent effect output from being anti-aliased. + scaledWidth = floor(scaledWidth); + scaledHeight = floor(scaledHeight); + horizontalMargin = floor(horizontalMargin); + + // Convert values to DIPs to preserve layout at different DPIs. + scaledHeight = DX::ConvertPixelsToDips(scaledHeight); + scaledWidth = DX::ConvertPixelsToDips(scaledWidth); + horizontalMargin = DX::ConvertPixelsToDips(horizontalMargin); + + // Calculate whole pixel offset of screen midpoint before converting to DIPs to + // prevent effect output from being antialiased. + float screenMidpoint = floor(DX::ConvertPixelsToDips(renderTargetSize.Width / 2.0f)); + + // Draw the original image on the left side of the window. + d2dContext->DrawImage(m_transformedImage.Get(), D2D1::Point2F(horizontalMargin, 0.0f)); + + // Draw the DFT of the image on the right side of the window. + // Because image output is fully opaque, it should be blended with BOUNDED_SOURCE_COPY, which allows + // the compute shader output to be written directly to the render target instead of blended. + d2dContext->DrawImage( + m_dftEffect.Get(), + D2D1::Point2F(screenMidpoint + horizontalMargin, 0.0f), + D2D1::RectF(0.0f, 0.0f, scaledWidth, scaledHeight), + D2D1_INTERPOLATION_MODE_LINEAR, + D2D1_COMPOSITE_MODE_BOUNDED_SOURCE_COPY + ); + + // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device + // is lost. It will be handled during the next call to Present. + HRESULT hr = d2dContext->EndDraw(); + if (hr != D2DERR_RECREATE_TARGET) + { + DX::ThrowIfFailed(hr); + } +} diff --git a/pool/shard008/C++/0096794_InterfaceSelectDialog.cpp b/pool/shard008/C++/0096794_InterfaceSelectDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20c7d7ab07e748a52c67756e8e6bb6a57329db25 --- /dev/null +++ b/pool/shard008/C++/0096794_InterfaceSelectDialog.cpp @@ -0,0 +1,187 @@ +/** +******************************************************************************** +\file InterfaceSelectDialog.cpp + +\brief Implementation of the interface selection dialog class + +This file contains the implementation of the interface selection dialog class. +*******************************************************************************/ +/*------------------------------------------------------------------------------ +Copyright (c) 2014, Bernecker+Rainer Industrie-Elektronik Ges.m.b.H. (B&R) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holders 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 COPYRIGHT HOLDERS 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. +------------------------------------------------------------------------------*/ + +#if (TARGET_SYSTEM == _WIN32_) +#define _WINSOCKAPI_ // prevent windows.h from including winsock.h +#endif // (TARGET_SYSTEM == _WIN32_) + +//------------------------------------------------------------------------------ +// includes +//------------------------------------------------------------------------------ +#include +#include "InterfaceSelectDialog.h" +#include +#include + +//------------------------------------------------------------------------------ +// const defines +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// class definitions +//------------------------------------------------------------------------------ + +//============================================================================// +// P U B L I C M E M B E R F U N C T I O N S // +//============================================================================// + +//------------------------------------------------------------------------------ +/** +\brief constructor + +Constructs an interface selection dialog. +*/ +//------------------------------------------------------------------------------ +InterfaceSelectDialog::InterfaceSelectDialog() +{ + QVBoxLayout* mainLayout = new QVBoxLayout; + + /* create labels */ + QLabel* label = new QLabel("Select network Interface:"); + QPushButton* okButton = new QPushButton("OK"); + QPushButton* cancelButton = new QPushButton("Cancel"); + + + /* create listbox */ + deviceListWidget = new QListWidget; + deviceListWidget->setSelectionMode(QAbstractItemView::SingleSelection); + + /* create buttons */ + QHBoxLayout* buttonLayout = new QHBoxLayout(); + buttonLayout->addStretch(1); + buttonLayout->addWidget(okButton); + buttonLayout->addWidget(cancelButton); + + connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + connect(deviceListWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), + this, SLOT(itemChanged(QListWidgetItem*, QListWidgetItem*))); + + /* create main layout */ + mainLayout->addWidget(label); + mainLayout->addWidget(deviceListWidget); + mainLayout->addStretch(0); + mainLayout->addLayout(buttonLayout); + + setLayout(mainLayout); + setWindowTitle("Select PCAP Interface"); +} + +//------------------------------------------------------------------------------ +/** +\brief setup the process image + +SetupProcessImage() sets up the process image used by the application. + +\retval -1 if interface list couldn't be filled +\retval 0 if interface list was successfully filled +*/ +//------------------------------------------------------------------------------ +int InterfaceSelectDialog::fillList(void) +{ + char sErr_Msg[PCAP_ERRBUF_SIZE]; + pcap_if_t* alldevs; + pcap_if_t* seldev; + int numIntf = 0; + + /* Retrieve the device list on the local machine */ + if (pcap_findalldevs(&alldevs, sErr_Msg) == -1) + { + return -1; + } + + /* Add the list to the listbox */ + for (seldev = alldevs; seldev != NULL; seldev = seldev->next) + { + numIntf++; + QListWidgetItem* newItem = new QListWidgetItem; + + QString devName(seldev->name); + QVariant data(devName); + + QString devDesc; + if (seldev->description) + { + devDesc = seldev->description; + } + else + { + devDesc = seldev->name; + } + newItem->setData(Qt::UserRole, data); + newItem->setText(devDesc); + deviceListWidget->addItem(newItem); + + } + pcap_freealldevs(alldevs); + + if (numIntf > 0) + return 0; + else + return -1; +} + +//------------------------------------------------------------------------------ +/** +\brief itemChanged handler + +Will be called if another list item was selected. + +\param current current selected list item +\param previous previous selected list item +*/ +//------------------------------------------------------------------------------ +void InterfaceSelectDialog::itemChanged(QListWidgetItem* current, + QListWidgetItem* previous) +{ + // set devName to the current Item + devDesc = current->text(); + devName = current->data(Qt::UserRole).toString(); +} + +//------------------------------------------------------------------------------ +/** +\brief get interface device name + +getDevName() returns the name of the selected interface. + +\return name of selected interface +*/ +//------------------------------------------------------------------------------ +QString InterfaceSelectDialog::getDevName(void) +{ + return devName; +} + diff --git a/pool/shard008/C++/0096796_SamplePictFile.cpp b/pool/shard008/C++/0096796_SamplePictFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..453624ec7421c55214eebdde3f415b0ded3d2278 --- /dev/null +++ b/pool/shard008/C++/0096796_SamplePictFile.cpp @@ -0,0 +1,198 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SampleCode.h" +#include "SkDumpCanvas.h" +#include "SkView.h" +#include "SkCanvas.h" +#include "SkGradientShader.h" +#include "SkGraphics.h" +#include "SkImageDecoder.h" +#include "SkOSFile.h" +#include "SkPath.h" +#include "SkPicture.h" +#include "SkPictureRecorder.h" +#include "SkRandom.h" +#include "SkRegion.h" +#include "SkShader.h" +#include "SkUtils.h" +#include "SkColorPriv.h" +#include "SkColorFilter.h" +#include "SkTime.h" +#include "SkTypeface.h" +#include "SkXfermode.h" + +#include "SkStream.h" +#include "SkSurface.h" +#include "SkXMLParser.h" + +class PictFileView : public SampleView { +public: + PictFileView(const char name[] = NULL) + : fFilename(name) + , fBBox(kNo_BBoxType) + , fTileSize(SkSize::Make(0, 0)) { + for (int i = 0; i < kBBoxTypeCount; ++i) { + fPictures[i] = NULL; + } + } + + virtual ~PictFileView() { + for (int i = 0; i < kBBoxTypeCount; ++i) { + SkSafeUnref(fPictures[i]); + } + } + + virtual void onTileSizeChanged(const SkSize &tileSize) SK_OVERRIDE { + if (tileSize != fTileSize) { + fTileSize = tileSize; + SkSafeSetNull(fPictures[kTileGrid_BBoxType]); + } + } + +protected: + // overrides from SkEventSink + virtual bool onQuery(SkEvent* evt) SK_OVERRIDE { + if (SampleCode::TitleQ(*evt)) { + SkString name("P:"); + const char* basename = strrchr(fFilename.c_str(), SkPATH_SEPARATOR); + name.append(basename ? basename+1: fFilename.c_str()); + switch (fBBox) { + case kNo_BBoxType: + // No name appended + break; + case kRTree_BBoxType: + name.append(" "); + break; + case kTileGrid_BBoxType: + name.append(" "); + break; + default: + SkASSERT(false); + break; + } + SampleCode::TitleR(evt, name.c_str()); + return true; + } + return this->INHERITED::onQuery(evt); + } + + virtual bool onEvent(const SkEvent& evt) SK_OVERRIDE { + if (evt.isType("PictFileView::toggleBBox")) { + fBBox = (BBoxType)((fBBox + 1) % kBBoxTypeCount); + return true; + } + return this->INHERITED::onEvent(evt); + } + + virtual void onDrawContent(SkCanvas* canvas) SK_OVERRIDE { + SkASSERT(static_cast(fBBox) < kBBoxTypeCount); + SkPicture** picture = fPictures + fBBox; + + if (!*picture) { + *picture = LoadPicture(fFilename.c_str(), fBBox); + } + if (*picture) { + canvas->drawPicture(*picture); + } + } + +private: + enum BBoxType { + kNo_BBoxType, + kRTree_BBoxType, + kTileGrid_BBoxType, + + kLast_BBoxType = kTileGrid_BBoxType + }; + static const int kBBoxTypeCount = kLast_BBoxType + 1; + + SkString fFilename; + SkPicture* fPictures[kBBoxTypeCount]; + BBoxType fBBox; + SkSize fTileSize; + + SkPicture* LoadPicture(const char path[], BBoxType bbox) { + SkAutoTUnref pic; + + SkBitmap bm; + if (SkImageDecoder::DecodeFile(path, &bm)) { + bm.setImmutable(); + SkPictureRecorder recorder; + SkCanvas* can = recorder.beginRecording(SkIntToScalar(bm.width()), + SkIntToScalar(bm.height()), + NULL, 0); + can->drawBitmap(bm, 0, 0, NULL); + pic.reset(recorder.endRecording()); + } else { + SkFILEStream stream(path); + if (stream.isValid()) { + pic.reset(SkPicture::CreateFromStream(&stream)); + } else { + SkDebugf("coun't load picture at \"path\"\n", path); + } + + if (false) { // re-record + SkPictureRecorder recorder; + pic->playback(recorder.beginRecording(pic->cullRect().width(), + pic->cullRect().height(), + NULL, 0)); + SkAutoTUnref p2(recorder.endRecording()); + + SkString path2(path); + path2.append(".new.skp"); + SkFILEWStream writer(path2.c_str()); + p2->serialize(&writer); + } + } + + if (NULL == pic) { + return NULL; + } + + SkAutoTDelete factory; + switch (bbox) { + case kNo_BBoxType: + // no bbox playback necessary + return pic.detach(); + case kRTree_BBoxType: + factory.reset(SkNEW(SkRTreeFactory)); + break; + case kTileGrid_BBoxType: { + SkASSERT(!fTileSize.isEmpty()); + SkTileGridFactory::TileGridInfo gridInfo; + gridInfo.fMargin = SkISize::Make(0, 0); + gridInfo.fOffset = SkIPoint::Make(0, 0); + gridInfo.fTileInterval = fTileSize.toRound(); + factory.reset(SkNEW_ARGS(SkTileGridFactory, (gridInfo))); + break; + } + default: + SkASSERT(false); + } + + SkPictureRecorder recorder; + pic->playback(recorder.beginRecording(pic->cullRect().width(), + pic->cullRect().height(), + factory.get(), 0)); + return recorder.endRecording(); + } + + typedef SampleView INHERITED; +}; + +SampleView* CreateSamplePictFileView(const char filename[]); +SampleView* CreateSamplePictFileView(const char filename[]) { + return new PictFileView(filename); +} + +////////////////////////////////////////////////////////////////////////////// + +#if 0 +static SkView* MyFactory() { return new PictFileView; } +static SkViewRegister reg(MyFactory); +#endif diff --git a/pool/shard008/C++/0096800_server_config_selector_filter.cc b/pool/shard008/C++/0096800_server_config_selector_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f54ad52959ae8169c769c4e1f053090052fbc17 --- /dev/null +++ b/pool/shard008/C++/0096800_server_config_selector_filter.cc @@ -0,0 +1,265 @@ +// +// +// Copyright 2021 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/ext/filters/server_config_selector/server_config_selector_filter.h" + +#include "src/core/ext/filters/server_config_selector/server_config_selector.h" +#include "src/core/ext/service_config/service_config_call_data.h" +#include "src/core/lib/transport/error_utils.h" + +namespace grpc_core { + +namespace { + +class ChannelData { + public: + static grpc_error_handle Init(grpc_channel_element* elem, + grpc_channel_element_args* args); + static void Destroy(grpc_channel_element* elem); + + absl::StatusOr> config_selector() { + MutexLock lock(&mu_); + return config_selector_; + } + + private: + class ServerConfigSelectorWatcher + : public ServerConfigSelectorProvider::ServerConfigSelectorWatcher { + public: + explicit ServerConfigSelectorWatcher(ChannelData* chand) : chand_(chand) {} + void OnServerConfigSelectorUpdate( + absl::StatusOr> update) override { + MutexLock lock(&chand_->mu_); + chand_->config_selector_ = std::move(update); + } + + private: + ChannelData* chand_; + }; + + explicit ChannelData(RefCountedPtr + server_config_selector_provider); + ~ChannelData(); + + RefCountedPtr server_config_selector_provider_; + Mutex mu_; + absl::StatusOr> config_selector_ + ABSL_GUARDED_BY(mu_); +}; + +class CallData { + public: + static grpc_error_handle Init(grpc_call_element* elem, + const grpc_call_element_args* args); + static void Destroy(grpc_call_element* elem, + const grpc_call_final_info* /* final_info */, + grpc_closure* /* then_schedule_closure */); + static void StartTransportStreamOpBatch(grpc_call_element* elem, + grpc_transport_stream_op_batch* op); + + private: + CallData(grpc_call_element* elem, const grpc_call_element_args& args); + ~CallData(); + static void RecvInitialMetadataReady(void* user_data, + grpc_error_handle error); + static void RecvTrailingMetadataReady(void* user_data, + grpc_error_handle error); + void MaybeResumeRecvTrailingMetadataReady(); + + grpc_call_context_element* call_context_; + grpc_core::CallCombiner* call_combiner_; + ServiceConfigCallData service_config_call_data_; + // Overall error for the call + grpc_error_handle error_ = GRPC_ERROR_NONE; + // State for keeping track of recv_initial_metadata + grpc_metadata_batch* recv_initial_metadata_ = nullptr; + grpc_closure* original_recv_initial_metadata_ready_ = nullptr; + grpc_closure recv_initial_metadata_ready_; + // State for keeping of track of recv_trailing_metadata + grpc_closure* original_recv_trailing_metadata_ready_; + grpc_closure recv_trailing_metadata_ready_; + grpc_error_handle recv_trailing_metadata_ready_error_; + bool seen_recv_trailing_metadata_ready_ = false; +}; + +// ChannelData + +grpc_error_handle ChannelData::Init(grpc_channel_element* elem, + grpc_channel_element_args* args) { + GPR_ASSERT(elem->filter = &kServerConfigSelectorFilter); + RefCountedPtr server_config_selector_provider = + ServerConfigSelectorProvider::GetFromChannelArgs(*args->channel_args); + if (server_config_selector_provider == nullptr) { + return GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "No ServerConfigSelectorProvider object found"); + } + new (elem->channel_data) + ChannelData(std::move(server_config_selector_provider)); + return GRPC_ERROR_NONE; +} + +void ChannelData::Destroy(grpc_channel_element* elem) { + auto* chand = static_cast(elem->channel_data); + chand->~ChannelData(); +} + +ChannelData::ChannelData( + RefCountedPtr server_config_selector_provider) + : server_config_selector_provider_( + std::move(server_config_selector_provider)) { + GPR_ASSERT(server_config_selector_provider_ != nullptr); + auto server_config_selector_watcher = + absl::make_unique(this); + config_selector_ = server_config_selector_provider_->Watch( + std::move(server_config_selector_watcher)); +} + +ChannelData::~ChannelData() { server_config_selector_provider_->CancelWatch(); } + +// CallData + +grpc_error_handle CallData::Init(grpc_call_element* elem, + const grpc_call_element_args* args) { + new (elem->call_data) CallData(elem, *args); + return GRPC_ERROR_NONE; +} + +void CallData::Destroy(grpc_call_element* elem, + const grpc_call_final_info* /*final_info*/, + grpc_closure* /*then_schedule_closure*/) { + auto* calld = static_cast(elem->call_data); + calld->~CallData(); +} + +void CallData::StartTransportStreamOpBatch(grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + CallData* calld = static_cast(elem->call_data); + if (op->recv_initial_metadata) { + calld->recv_initial_metadata_ = + op->payload->recv_initial_metadata.recv_initial_metadata; + calld->original_recv_initial_metadata_ready_ = + op->payload->recv_initial_metadata.recv_initial_metadata_ready; + op->payload->recv_initial_metadata.recv_initial_metadata_ready = + &calld->recv_initial_metadata_ready_; + } + if (op->recv_trailing_metadata) { + // We might generate errors on receiving initial metadata which we need to + // bubble up through recv_trailing_metadata_ready + calld->original_recv_trailing_metadata_ready_ = + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &calld->recv_trailing_metadata_ready_; + } + // Chain to the next filter. + grpc_call_next_op(elem, op); +} + +CallData::CallData(grpc_call_element* elem, const grpc_call_element_args& args) + : call_context_(args.context), call_combiner_(args.call_combiner) { + GRPC_CLOSURE_INIT(&recv_initial_metadata_ready_, RecvInitialMetadataReady, + elem, grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReady, + elem, grpc_schedule_on_exec_ctx); +} + +CallData::~CallData() { + // Remove the entry from call context, just in case anyone above us + // tries to look at it during call stack destruction. + call_context_[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value = nullptr; + GRPC_ERROR_UNREF(error_); +} + +void CallData::RecvInitialMetadataReady(void* user_data, + grpc_error_handle error) { + grpc_call_element* elem = static_cast(user_data); + CallData* calld = static_cast(elem->call_data); + ChannelData* chand = static_cast(elem->channel_data); + if (error == GRPC_ERROR_NONE) { + auto config_selector = chand->config_selector(); + if (config_selector.ok()) { + auto call_config = + config_selector.value()->GetCallConfig(calld->recv_initial_metadata_); + if (call_config.error != GRPC_ERROR_NONE) { + calld->error_ = call_config.error; + error = call_config.error; // Does not take a ref + } else { + calld->service_config_call_data_ = + ServiceConfigCallData(std::move(call_config.service_config), + call_config.method_configs, {}); + calld->call_context_[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value = + &calld->service_config_call_data_; + } + } else { + calld->error_ = absl_status_to_grpc_error(config_selector.status()); + error = calld->error_; + } + } + calld->MaybeResumeRecvTrailingMetadataReady(); + grpc_closure* closure = calld->original_recv_initial_metadata_ready_; + calld->original_recv_initial_metadata_ready_ = nullptr; + Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); +} + +void CallData::RecvTrailingMetadataReady(void* user_data, + grpc_error_handle error) { + grpc_call_element* elem = static_cast(user_data); + CallData* calld = static_cast(elem->call_data); + if (calld->original_recv_initial_metadata_ready_ != nullptr) { + calld->seen_recv_trailing_metadata_ready_ = true; + calld->recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error); + GRPC_CALL_COMBINER_STOP(calld->call_combiner_, + "Deferring RecvTrailingMetadataReady until after " + "RecvInitialMetadataReady"); + return; + } + error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_); + calld->error_ = GRPC_ERROR_NONE; + grpc_closure* closure = calld->original_recv_trailing_metadata_ready_; + calld->original_recv_trailing_metadata_ready_ = nullptr; + Closure::Run(DEBUG_LOCATION, closure, error); +} + +void CallData::MaybeResumeRecvTrailingMetadataReady() { + if (seen_recv_trailing_metadata_ready_) { + seen_recv_trailing_metadata_ready_ = false; + grpc_error_handle error = recv_trailing_metadata_ready_error_; + recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE; + GRPC_CALL_COMBINER_START(call_combiner_, &recv_trailing_metadata_ready_, + error, "Continuing RecvTrailingMetadataReady"); + } +} + +} // namespace + +const grpc_channel_filter kServerConfigSelectorFilter = { + CallData::StartTransportStreamOpBatch, + grpc_channel_next_op, + sizeof(CallData), + CallData::Init, + grpc_call_stack_ignore_set_pollset_or_pollset_set, + CallData::Destroy, + sizeof(ChannelData), + ChannelData::Init, + ChannelData::Destroy, + grpc_channel_next_get_info, + "server_config_selector_filter", +}; + +} // namespace grpc_core diff --git a/pool/shard008/C++/0096803_ic-ia32.cc b/pool/shard008/C++/0096803_ic-ia32.cc new file mode 100644 index 0000000000000000000000000000000000000000..4bf0eaee923144792b06de2ee4d8007a82239b64 --- /dev/null +++ b/pool/shard008/C++/0096803_ic-ia32.cc @@ -0,0 +1,130 @@ +// Copyright 2012 the V8 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. + +#if V8_TARGET_ARCH_IA32 + +#include "src/codegen.h" +#include "src/ic/ic.h" +#include "src/ic/ic-compiler.h" +#include "src/ic/stub-cache.h" + +namespace v8 { +namespace internal { + +// ---------------------------------------------------------------------------- +// Static IC stub generators. +// + +#define __ ACCESS_MASM(masm) + +static void StoreIC_PushArgs(MacroAssembler* masm) { + Register receiver = StoreWithVectorDescriptor::ReceiverRegister(); + Register name = StoreWithVectorDescriptor::NameRegister(); + + STATIC_ASSERT(StoreWithVectorDescriptor::kStackArgumentsCount == 3); + // Current stack layout: + // - esp[12] -- value + // - esp[8] -- slot + // - esp[4] -- vector + // - esp[0] -- return address + + Register return_address = StoreWithVectorDescriptor::SlotRegister(); + __ pop(return_address); + __ push(receiver); + __ push(name); + __ push(return_address); +} + +void KeyedStoreIC::GenerateMiss(MacroAssembler* masm) { + // Return address is on the stack. + StoreIC_PushArgs(masm); + + // Do tail-call to runtime routine. + __ TailCallRuntime(Runtime::kKeyedStoreIC_Miss); +} + +void KeyedStoreIC::GenerateSlow(MacroAssembler* masm) { + // Return address is on the stack. + StoreIC_PushArgs(masm); + + // Do tail-call to runtime routine. + __ TailCallRuntime(Runtime::kKeyedStoreIC_Slow); +} + +#undef __ + + +Condition CompareIC::ComputeCondition(Token::Value op) { + switch (op) { + case Token::EQ_STRICT: + case Token::EQ: + return equal; + case Token::LT: + return less; + case Token::GT: + return greater; + case Token::LTE: + return less_equal; + case Token::GTE: + return greater_equal; + default: + UNREACHABLE(); + return no_condition; + } +} + + +bool CompareIC::HasInlinedSmiCode(Address address) { + // The address of the instruction following the call. + Address test_instruction_address = + address + Assembler::kCallTargetAddressOffset; + + // If the instruction following the call is not a test al, nothing + // was inlined. + return *test_instruction_address == Assembler::kTestAlByte; +} + + +void PatchInlinedSmiCode(Isolate* isolate, Address address, + InlinedSmiCheck check) { + // The address of the instruction following the call. + Address test_instruction_address = + address + Assembler::kCallTargetAddressOffset; + + // If the instruction following the call is not a test al, nothing + // was inlined. + if (*test_instruction_address != Assembler::kTestAlByte) { + DCHECK(*test_instruction_address == Assembler::kNopByte); + return; + } + + Address delta_address = test_instruction_address + 1; + // The delta to the start of the map check instruction and the + // condition code uses at the patched jump. + uint8_t delta = *reinterpret_cast(delta_address); + if (FLAG_trace_ic) { + PrintF("[ patching ic at %p, test=%p, delta=%d\n", + static_cast(address), + static_cast(test_instruction_address), delta); + } + + // Patch with a short conditional jump. Enabling means switching from a short + // jump-if-carry/not-carry to jump-if-zero/not-zero, whereas disabling is the + // reverse operation of that. + Address jmp_address = test_instruction_address - delta; + DCHECK((check == ENABLE_INLINED_SMI_CHECK) + ? (*jmp_address == Assembler::kJncShortOpcode || + *jmp_address == Assembler::kJcShortOpcode) + : (*jmp_address == Assembler::kJnzShortOpcode || + *jmp_address == Assembler::kJzShortOpcode)); + Condition cc = + (check == ENABLE_INLINED_SMI_CHECK) + ? (*jmp_address == Assembler::kJncShortOpcode ? not_zero : zero) + : (*jmp_address == Assembler::kJnzShortOpcode ? not_carry : carry); + *jmp_address = static_cast(Assembler::kJccShortPrefix | cc); +} +} // namespace internal +} // namespace v8 + +#endif // V8_TARGET_ARCH_IA32 diff --git a/pool/shard008/C++/0096805_cubic_hermite_test.cc b/pool/shard008/C++/0096805_cubic_hermite_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..74ef8a310ace51d21f6335130e02d286e8c49ccf --- /dev/null +++ b/pool/shard008/C++/0096805_cubic_hermite_test.cc @@ -0,0 +1,214 @@ +// Copyright 2019 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. + +#include +#include + +using Point = std::array; // {t, s, s_dot} + +TEST(TestCubicHermiteInterpolation, ConstAccelTest) { + Point start = {0, 0, 0}; + Point end = {1, 1, 2}; + + // interpolate at start + double t_interpolate = 0; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 0); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 0); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2); + + // interpolate at end + t_interpolate = 1; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2); + + // interpolate in middle + t_interpolate = 0.5; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 0.25); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2); +} + +TEST(TestCubicHermiteInterpolation, CubicTest) { + // testing polynomial s(t) = 0.5*t^3 + 2*t^2 + t + 5 + Point start = {0, 5, 1}; + Point end = {1, 8.5, 6.5}; + + // interpolate at start + double t_interpolate = 0; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 5); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 4); + + // interpolate at end + t_interpolate = 1; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 8.5); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 6.5); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 7); + + // interpolate in middle + t_interpolate = 0.5; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 6.0625); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 3.375); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 5.5); +} + +TEST(TestCubicHermiteInterpolation, ZeroAccelNonUnitIntervalTest) { + Point start = {0, 0, 1}; + Point end = {3.5, 3.5, 1}; + + // interpolate at start + double t_interpolate = 0; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 0); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 0); + + // interpolate at end + t_interpolate = 3.5; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 3.5); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 0); + + // interpolate in middle + t_interpolate = 1.75; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 1.75); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 0); +} + +TEST(TestCubicHermiteInterpolation, CubicNonUnitIntervalTest) { + // testing polynomial s(t) = 0.1*t^3 + 0.5*t^2 + t + 1 + Point start = {0, 1, 1}; + Point end = {2.5, 8.1875, 5.375}; + + // interpolate at start + double t_interpolate = 0; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1); + + // interpolate at end + t_interpolate = 2.5; + EXPECT_EQ(bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 8.1875); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 5.375); + EXPECT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2.5); + + // interpolate in middle + t_interpolate = 1.1; + EXPECT_FLOAT_EQ( + bookbot::CubicHermiteInterpolate(t_interpolate, start[0], start[1], + start[2], end[0], end[1], end[2]), + 2.8381); + EXPECT_FLOAT_EQ( + bookbot::CubicHermiteInterpolateDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 2.463); + EXPECT_FLOAT_EQ( + bookbot::CubicHermiteInterpolateSecondDerivative( + t_interpolate, start[0], start[1], start[2], end[0], end[1], end[2]), + 1.66); +} + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/pool/shard008/C++/0096817_CNA.cpp b/pool/shard008/C++/0096817_CNA.cpp new file mode 100644 index 0000000000000000000000000000000000000000..586cfe00c8a37e515df7e2345d5bedaffeb6bfaa --- /dev/null +++ b/pool/shard008/C++/0096817_CNA.cpp @@ -0,0 +1,150 @@ +// Copyright (C) 2008-2011 Jakob Schiotz and Center for Individual +// Nanoparticle Functionality, Department of Physics, Technical +// University of Denmark. Email: schiotz@fysik.dtu.dk +// +// This file is part of Asap version 3. +// +// This program is free software: you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public License +// version 3 as published by the Free Software Foundation. Permission +// to use other versions of the GNU Lesser General Public License may +// granted by Jakob Schiotz or the head of department of the +// Department of Physics, Technical University of Denmark, as +// described in section 14 of the GNU General Public License. +// +// 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 +// and the GNU Lesser Public License along with this program. If not, +// see . + +#include "AsapPython.h" +#include "CNA.h" +#include "Atoms.h" +#include "NeighborList.h" +#include "Vec.h" +#include "Timing.h" +#include "Exception.h" +#include "GetNeighborList.h" + +namespace ASAPSPACE { + +void CNA(PyObject *py_atoms, double rCut, vector &cna) +{ + USETIMER("CNA"); + Atoms *atoms = NULL; + PyObject *py_nblist = NULL; + // Get an Atoms access object and a neighbor list with cutoff rCut or larger. + GetNbList_FromAtoms(py_atoms, rCut, &py_nblist, &atoms); + NeighborLocator *nl = ((PyAsap_NeighborLocatorObject*) py_nblist)->cobj; + assert(nl != NULL); + + int nAtoms = atoms->GetNumberOfAtoms(); + int nTotal = nAtoms + atoms->GetNumberOfGhostAtoms(); + + // The neighbor list is unlikely to support full lists, and it is + // likely to have a too long cutoff (if we reuse the one from the + // potential). So let us make a simple, sanitized copy of it here. + + // Build a sanitized full neighbor list here + vector< vector > neighborLists(nTotal); + int maxlistlen = nl->MaxNeighborListLength(); + vector nb_buffer(maxlistlen); + vector diffs(maxlistlen); + vector diffs2(maxlistlen); + double rC2 = rCut * rCut; + for (int a1 = 0; a1 < nTotal; a1++) + { + int size = maxlistlen; + int nnb; + nnb = nl->GetNeighbors(a1, &nb_buffer[0], &diffs[0], &diffs2[0], + size, rCut); + for (int n = 0; n < nnb; n++) + { + int a2 = nb_buffer[n]; + if (diffs2[n] <= rC2) + { + neighborLists[a1].push_back(a2); + neighborLists[a2].push_back(a1); + } + } + } + + vector numFCC(nTotal); + vector numHCP(nTotal); + for (unsigned int a2 = 0; a2 < nTotal; a2++) + { + vector& nbs2 = neighborLists[a2]; + for (unsigned int n2 = 0; n2 < nbs2.size(); n2++) + { + int a1 = nbs2[n2]; + assert(a1 < nTotal); + if (a1 < a2) + { + vector common; + vector& nbs1 = neighborLists[a1]; + for (unsigned int n1 = 0; n1 < nbs1.size(); n1++) + { + int a3 = nbs1[n1]; + for (unsigned int m2 = 0; m2 < nbs2.size(); m2++) + if (a3 == nbs2[m2]) + common.push_back(a3); + } + if (common.size() == 4) + { + int nBonds = 0; + int bondsSum = 0; + for (int j2 = 1; j2 < 4; j2++) + { + vector& nbs = neighborLists[common[j2]]; + for (unsigned int j1 = 0; j1 < j2; j1++) + for (unsigned int n = 0; n < nbs.size(); n++) + if (common[j1] == nbs[n]) + { + nBonds++; + bondsSum += j1 + j2; + break; + } + } + if (nBonds == 2) + { + if (bondsSum == 6) + { + numFCC[a1]++; + numFCC[a2]++; + } + else + { + numHCP[a1]++; + numHCP[a2]++; + } + } + } + } + } + } + // 0: fcc (421), 1: hcp (422), 2: other + cna.resize(nAtoms); + for (int a = 0; a < nAtoms; a++) + { + if (neighborLists[a].size() == 12) + { + if (numFCC[a] == 12) + cna[a] = 0; + else if (numFCC[a] == 6 && numHCP[a] == 6) + cna[a] = 1; + else + cna[a] = 2; + } + else + cna[a] = 2; + } + atoms->End(); + Py_DECREF(py_nblist); + AsapAtoms_DECREF(atoms); +} + +} // end namespace diff --git a/pool/shard008/C++/0096818_TankAIController.cpp b/pool/shard008/C++/0096818_TankAIController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b5a07011d4c248ebc99645e36eab1d9b5d6aa25 --- /dev/null +++ b/pool/shard008/C++/0096818_TankAIController.cpp @@ -0,0 +1,53 @@ +// Fill out your copyright notice in the Description page of Project Settings. + + +#include "BattleTank.h" +#include "TankAimingComponent.h" +#include "TankAIController.h" +#include "Tank.h" + +void ATankAIController::BeginPlay(){ + Super::BeginPlay(); +} + +void ATankAIController::SetPawn(APawn* inPawn){ + Super::SetPawn(inPawn); + if(inPawn){ + auto possessedTank = Cast(inPawn); + if (!ensure(possessedTank)) { return; } + + //TODO Subscribe our local method to the tank's death event. + possessedTank->OnDeath.AddUniqueDynamic(this, &ATankAIController::OnPossedTankDeath); + } +} + +void ATankAIController::OnPossedTankDeath(){ + + if(!ensure(GetPawn())){return;} //TODO remove if ok. + GetPawn()->DetachFromControllerPendingDestroy(); +} + +void ATankAIController::Tick(float DeltaTime){ + Super::Tick(DeltaTime); + + auto playerTank = GetWorld()->GetFirstPlayerController()->GetPawn(); + auto controlledTank = GetPawn(); + + + if (!ensure(playerTank && controlledTank)) { return; } + + //Move towards the player + MoveToActor(playerTank,acceptanceRadius); + + //Aim towards the player + auto aimingComponent = GetPawn()->FindComponentByClass(); + aimingComponent->AimAt(playerTank->GetActorLocation()); + + //Fire if ready. + if(aimingComponent->GetFiringState() == EFiringState::LOCKED) + aimingComponent->Fire();//TODO dont fire every frame. + + +} + + diff --git a/pool/shard008/C++/0096821_data.cpp b/pool/shard008/C++/0096821_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9ba9c67c7f2b0efdd9b0edc27a513730d5b28b8 --- /dev/null +++ b/pool/shard008/C++/0096821_data.cpp @@ -0,0 +1,253 @@ +/*************************************************************************** + data.cpp + ------------------- + Brewing data + ------------------- + Copyright 2001-2008 David Johnson + Please see the header file for copyright and license information. + ***************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "datareader.h" +#include "qbrew.h" +#include "recipe.h" +#include "resource.h" + +#include "data.h" + +using namespace Resource; + +Data *Data::instance_ = 0; +static QMutex instancelock; + +// Construction, Destruction ///////////////////////////////////////////////// + +// Private constructor +Data::Data() + : defaultsize_(Volume(5.0, Volume::gallon)), defaultstyle_(), + defaulthoptype_(Hop::PELLET_STRING), defaultgrainunit_(&Weight::pound), + defaulthopunit_(&Weight::ounce), defaultmiscunit_(&Quantity::generic), + grainmap_(), hopmap_(), miscmap_(), stylemap_(), utable_(), + steepyield_(0.5), efficiency_(0.75), tinseth_(true), morey_(true) +{ ; } + +// Private destructor +Data::~Data() { ; } + +// Return pointer to the data +Data *Data::instance() +{ + if (!instance_) { + QMutexLocker lock(&instancelock); + if (!instance_) instance_ = new Data(); + } + return instance_; +} + +// Initialize +void Data::initialize(const ConfigState &state) +{ + // set defaults + if (state.calc.units == UNIT_METRIC) { + setDefaultSize(Volume(state.recipe.batch, Volume::liter)); + setDefaultGrainUnit(Weight::kilogram); + setDefaultHopUnit(Weight::gram); + setDefaultTempUnit(Temperature::celsius); + } else if (state.calc.units == UNIT_US) { + setDefaultSize(Volume(state.recipe.batch, Volume::gallon)); + setDefaultGrainUnit(Weight::pound); + setDefaultHopUnit(Weight::ounce); + setDefaultTempUnit(Temperature::fahrenheit); + } + setDefaultStyle(state.recipe.style); + setDefaultHopType(state.recipe.hoptype); + setDefaultMiscUnit(Quantity::generic); + setEfficiency(state.calc.efficiency); + + // load data file - look in standard locations + // TODO: use QDesktopServices in next non-bugfix release (0.5.0) + bool status = false; + // try home directory first + if (!status) status = loadData(QDIR_HOME + "/." + DATA_FILE, true); + // then try system data directory + if (!status) status = loadData(QBrew::instance()->dataBase() + DATA_FILE); + + if (!status) { + qWarning() << "Warning: could not open data file"; + QMessageBox::warning(0, TITLE, QObject::tr("Could not open data file")); + } +} + +////////////////////////////////////////////////////////////////////////////// +// Data Access // +////////////////////////////////////////////////////////////////////////////// + +void Data::setDefaultStyle(const QString &style) +{ + if (stylemap_.contains(style)) defaultstyle_ = stylemap_.value(style); +} + +////////////////////////////////////////////////////////////////////////////// +// style() +// ------- +// Return a style given its name + +Style Data::style(const QString &name) +{ + if (stylemap_.contains(name)) return stylemap_.value(name); + return Style(); +} + +////////////////////////////////////////////////////////////////////////////// +// grain() +// ------- +// Return grain given its name + +Grain Data::grain(const QString &name) +{ + Grain grain; + if (grainmap_.contains(name)) grain = grainmap_.value(name); + grain.setWeight(Weight(1.0, *defaultgrainunit_)); + return grain; +} + +////////////////////////////////////////////////////////////////////////////// +// hop() +// ----- +// Return hop given its name + +Hop Data::hop(const QString &name) +{ + Hop hop; + if (hopmap_.contains(name)) hop = hopmap_.value(name); + hop.setWeight(Weight(1.0, *defaulthopunit_)); + hop.setType(defaulthoptype_); + return hop; +} + +////////////////////////////////////////////////////////////////////////////// +// misc() +// ------ +// Return misc ingredient given its name + +Misc Data::misc(const QString &name) +{ + Misc misc; + if (miscmap_.contains(name)) misc = miscmap_.value(name); + misc.setQuantity(Quantity(1.0, *defaultmiscunit_)); + return misc; +} + +////////////////////////////////////////////////////////////////////////////// +// utilization +// ----------- +// Look up the utilization for the given time + +double Data::utilization(unsigned time) +{ + foreach(UEntry entry, utable_) { + if (time >= entry.time) return (double(entry.utilization)); + } + return 0.0; +} + +////////////////////////////////////////////////////////////////////////////// +// addUEntry() +// ----------- +// Add an entry to the utilization table [static] + +void Data::addUEntry(const UEntry &entry) +{ + // keep the list sorted from highest time to lowest + QList::Iterator it; + if (utable_.isEmpty()) { + utable_.append(entry); + } else { + for (it=utable_.begin(); it != utable_.end(); ++it) { + if ((*it).time < entry.time) break; + } + utable_.insert(it, entry); + } +} + +////////////////////////////////////////////////////////////////////////////// +// Serialization // +////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////// +// loadData() +// ---------- +// Load the data + +bool Data::loadData(const QString &filename, bool quiet) +{ + // open file + QFile datafile(filename); + if (!datafile.open(QFile::ReadOnly | QFile::Text)) { + // error opening file + if (!quiet) { + qWarning() << "Error: Cannot read" << filename; + QMessageBox::warning(0, TITLE, + QObject::tr("Cannot read file %1:\n%2") + .arg(filename) + .arg(datafile.errorString())); + } + datafile.close(); + return false; + } + + QApplication::setOverrideCursor(Qt::WaitCursor); + + // parse file + DataReader reader(&datafile); + bool status = reader.readData(this); + datafile.close(); + + if (!status) { + qWarning() << "Error: Problem reading file" << filename; + qWarning() << reader.errorString(); + QMessageBox::warning(0, TITLE, + QObject::tr("Error reading file %1").arg(filename)); + QApplication::restoreOverrideCursor(); + return false; + } + + QApplication::restoreOverrideCursor(); + return true; +} + +////////////////////////////////////////////////////////////////////////////// +// saveData() +// ------------ +// Save info to data file + +bool Data::saveData(const QString &filename) +{ + // open file + QFile datafile(filename); + if (!datafile.open(QFile::WriteOnly | QFile::Text)) { + // error opening file + qWarning() << "Error: Cannot open file" << filename; + QMessageBox::warning(0, TITLE, + QObject::tr("Cannot write file %1:\n%2") + .arg(filename) + .arg(datafile.errorString())); + datafile.close(); + QApplication::restoreOverrideCursor(); + return false; + } + + // write it out + DataWriter writer(&datafile); + writer.writeData(this); + datafile.close(); + + QApplication::restoreOverrideCursor(); + return true; +} diff --git a/pool/shard008/C++/0096824_sitespage.cpp b/pool/shard008/C++/0096824_sitespage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a65a592f43fd4e908b77d8522f8544e1588f3f6 --- /dev/null +++ b/pool/shard008/C++/0096824_sitespage.cpp @@ -0,0 +1,355 @@ +/*************************************************************************** + * The FreeMedForms project is a set of free, open source medical * + * applications. * + * (C) 2008-2016 by Eric MAEKER, MD (France) * + * All rights reserved. * + * * + * The FreeAccount plugins are free, open source FreeMedForms' plugins. * + * (C) 2010-2011 by Pierre-Marie Desombre, MD * + * and Eric Maeker, MD * + * All rights reserved. * + * * + * 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 (COPYING.FREEMEDFORMS file). * + * If not, see . * + ***************************************************************************/ +/*************************************************************************** + * Main Developers: Pierre-Marie DESOMBRE , * + * Eric MAEKER, * + * Contributors: * + * NAME * + ***************************************************************************/ +#include "sitespage.h" + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "ui_sitespage.h" + +#include +#include +#include +#include +#include + +enum { WarnDebugMessage = true }; + +using namespace Account; +using namespace Account::Internal; +using namespace Trans::ConstantTranslations; + +static inline Core::ISettings *settings() { return Core::ICore::instance()->settings(); } +static inline Core::ITheme *theme() { return Core::ICore::instance()->theme(); } +static inline Core::IUser *user() { return Core::ICore::instance()->user(); } +const QString global_resourcesPath = qApp->applicationDirPath()+"/../../global_resources"; + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////// AccountUserPage ////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// +SitesPage::SitesPage(QObject *parent) : + IOptionsPage(parent), m_Widget(0) { setObjectName("SitesPage"); } + +SitesPage::~SitesPage() +{ + if (m_Widget) delete m_Widget; + m_Widget = 0; +} + +QString SitesPage::id() const { return objectName(); } +QString SitesPage::displayName() const { return tkTr(Trans::Constants::SITES); } +QString SitesPage::category() const { return tkTr(Trans::Constants::ACCOUNTANCY); } +int SitesPage::sortIndex() const +{ + return Core::Constants::OPTIONINDEX_ACCOUNT + 80; +} + +void SitesPage::resetToDefaults() +{ + m_Widget->writeDefaultSettings(settings()); + m_Widget->setDataToUi(); +} + +void SitesPage::apply() +{ + if (WarnDebugMessage) + LOG("applyChanges"); + if (!m_Widget) { + return; + } + m_Widget->saveToSettings(settings()); +} + +void SitesPage::finish() { delete m_Widget; } + +void SitesPage::checkSettingsValidity() +{ + QHash defaultvalues; +// defaultvalues.insert(DrugsDB::Constants::S_AVAILABLEDOSAGESBACKGROUNGCOLOR, DrugsDB::Constants::S_DEF_AVAILABLEDOSAGESBACKGROUNGCOLOR); + + foreach(const QString &k, defaultvalues.keys()) { + if (settings()->value(k) == QVariant()) + settings()->setValue(k, defaultvalues.value(k)); + } + settings()->sync(); +} + +QWidget *SitesPage::createPage(QWidget *parent) +{ + if (m_Widget) + delete m_Widget; + m_Widget = new SitesWidget(parent); + return m_Widget; +} + +SitesWidget::SitesWidget(QWidget *parent) : + QWidget(parent), m_Model(0), m_Mapper(0) +{ + setObjectName("SitesWidget"); + // Setup UI + ui = new Ui::SitesWidget; + ui->setupUi(this); + ui->tabWidget->setCurrentIndex(0); + + // Manage user + m_user_uid = user()->uuid(); + m_user_fullName = user()->value(Core::IUser::FullName).toString(); + if (m_user_fullName.isEmpty()) { + m_user_fullName = "Admin_Test"; + } + + // Add zipcodes auto-completer + ZipCodes::ZipCountryCompleters *c = new ZipCodes::ZipCountryCompleters(this); + c->setZipLineEdit(ui->zip); + c->setCityLineEdit(ui->cityEdit); + c->setCountryComboBox(ui->countryComboBox); + + // Create mapper + m_Model = new AccountDB::WorkingPlacesModel(this); + // TODO: m_Model->setUserUuid(); + m_Mapper = new QDataWidgetMapper(this); + m_Mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit); + m_Mapper->setModel(m_Model); + m_Mapper->setCurrentModelIndex(QModelIndex()); + //m_Mapper->addMapping(ui->mpIDLabel, AccountDB::Constants::SITE_ID, "ID"); + m_Mapper->addMapping(ui->nameEdit, AccountDB::Constants::SITES_NAME); + m_Mapper->addMapping(ui->adressEdit, AccountDB::Constants::SITES_ADRESS); + m_Mapper->addMapping(ui->cityEdit, AccountDB::Constants::SITES_CITY, "text"); + m_Mapper->addMapping(ui->zip, AccountDB::Constants::SITES_ZIPCODE, "text"); + m_Mapper->addMapping(ui->countryComboBox, AccountDB::Constants::SITES_COUNTRY,"currentIsoCountry"); + + m_Mapper->addMapping(ui->phoneEdit, AccountDB::Constants::SITES_TEL); + m_Mapper->addMapping(ui->faxEdit, AccountDB::Constants::SITES_FAX); + m_Mapper->addMapping(ui->mailEdit, AccountDB::Constants::SITES_MAIL); + + m_Mapper->addMapping(ui->contactEdit, AccountDB::Constants::SITES_CONTACT); + m_Mapper->toFirst(); + + ui->addRemoveCombo->setModel(m_Model); + ui->addRemoveCombo->setModelColumn(AccountDB::Constants::SITES_NAME); + ui->addRemoveCombo->setLabel(tr("&Working places:")); + + //hash of towns and zipcode + connect(ui->nameEdit, SIGNAL(textEdited(QString)), ui->addRemoveCombo, SLOT(setEditText(QString))); + connect(ui->addRemoveCombo, SIGNAL(itemAdded(QModelIndex)), ui->nameEdit, SLOT(setFocus())); + connect(ui->addRemoveCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateUi())); + connect(ui->addRemoveCombo, SIGNAL(currentIndexChanged(int)), m_Mapper, SLOT(setCurrentIndex(int))); + setDataToUi(); + updateUi(); +} + +SitesWidget::~SitesWidget() +{ + delete ui; + //saveModel(); +} + +//void SitesWidget::fillHugeWidgets(){ +// QStringList listOfZipcodes; +// listOfZipcodes = m_hashTownZip.keys(); +// listOfZipcodes.removeDuplicates(); +// listOfZipcodes.sort(); +// QLocale local; +// QString localCountry; +// localCountry = QLocale::countryToString(local.country()); +// if (WarnDebugMessage) +// qDebug() << __FILE__ << QString::number(__LINE__) << " country =" << localCountry ; +// QStringList listForCountry; +// listForCountry = listOfCountries(); +// listForCountry.sort(); +// listForCountry.prepend(localCountry); + +// zipComboBox->addItems(listOfZipcodes); + +// countryComboBox->addItems(listForCountry); +//} + +void SitesWidget::setDataToUi() +{ + if (WarnDebugMessage) + qDebug() << __FILE__ << QString::number(__LINE__) << "index row =" << QString::number(ui->addRemoveCombo->currentIndex()); + m_Mapper->setCurrentIndex(ui->addRemoveCombo->currentIndex()); +} + +void SitesWidget::saveModel() +{ + if (WarnDebugMessage) + qDebug() << __FILE__ << QString::number(__LINE__) << " currentIndex =" << QString::number(m_Mapper->currentIndex()); + + // FIXME: here you should have to check all cols isDirty state of the row + if (m_Model->isDirty(m_Model->index(m_Mapper->currentIndex(),0))) { + bool yes = Utils::yesNoMessageBox(tr("Save changes?"), + tr("You make changes into the sites table.\n" + "Do you want to save them?")); + if (yes) { + if (!m_Model->submitAll()) { + LOG_ERROR(tkTr(Trans::Constants::UNABLE_TO_SAVE_DATA_IN_DATABASE_1). + arg(tr("sites"))); + } + } + else { + m_Model->revert(); + } + } + if (WarnDebugMessage) + qDebug() << __FILE__ << QString::number(__LINE__) << " site error =" << m_Model->lastError().text(); +} + +void SitesWidget::on_addRemoveCombo_currentIndexChanged(int index) +{ + Q_UNUSED(index); + //saveModel(); + m_Mapper->setCurrentIndex(ui->addRemoveCombo->currentIndex()); +} + +void SitesWidget::saveToSettings(Core::ISettings *sets) +{ + Q_UNUSED(sets); + if (!m_Model->submitAll()) { + LOG_ERROR(tkTr(Trans::Constants::UNABLE_TO_SAVE_DATA_IN_DATABASE_1).arg(tr("sites"))); + Utils::warningMessageBox(tr("Cannot submit sites to your personal database."), + tr("An error occured during sites saving. Data are corrupted.")); + } + update(); +} + +void SitesWidget::writeDefaultSettings(Core::ISettings *s) +{ + Q_UNUSED(s); +// Utils::Log::addMessage("SitesWidget", tkTr(Trans::Constants::CREATING_DEFAULT_SETTINGS_FOR_1).arg("SitesWidget")); +// s->sync(); +} + +void SitesWidget::changeEvent(QEvent *e) +{ + QWidget::changeEvent(e); + switch (e->type()) { + case QEvent::LanguageChange: + ui->retranslateUi(this); +// int s = defaultCombo->currentIndex(); +// defaultCombo->clear(); +// defaultCombo->addItem(tkTr(Trans::Constants::NO)); +// defaultCombo->addItem(tkTr(Trans::Constants::YES)); +// defaultCombo->setCurrentIndex(s); + break; + default: + break; + } +} + +//void SitesWidget::showEvent(QShowEvent *event){ +// Q_UNUSED(event); +// if (WarnDebugMessage) +// qWarning() << __FILE__ << QString::number(__LINE__) << " sites activated " ; +// fillHugeWidgets(); +// update(); +//} + +//void SitesWidget::findCityFromZipCode(const QString & zipCodeText){ +// cityEdit->setFocus(); +// QString city = m_hashTownZip.value(zipCodeText); +// cityEdit->setText(city); +//} + +//QHash SitesWidget::parseZipcodeCsv(){ +// QHash hash; +// QString zipcodeStr = global_resourcesPath+"/textfiles/zipcodes.csv"; +// QFile zipcodeFile(zipcodeStr); +// if(!zipcodeFile.open(QIODevice::ReadOnly|QIODevice::Text)){ +// qWarning() << __FILE__ << QString::number(__LINE__) << "zipcode cannot open !" ; +// if (WarnDebugMessage) +// qDebug() << __FILE__ << QString::number(__LINE__) << " zipcodeFile =" << zipcodeStr ; +// } +// QTextStream stream(&zipcodeFile); +// while (!stream.atEnd()) +// { +// QString line = stream.readLine(); +// QString line2 = line; +// if (line.contains("FIN")|| line.contains("sum_loss; + all.sd->sum_loss = (double)accumulate_scalar(all, all.span_server, loss); + float weighted_examples = (float)all.sd->weighted_examples; + all.sd->weighted_examples = (double)accumulate_scalar(all, all.span_server, weighted_examples); + float weighted_labels = (float)all.sd->weighted_labels; + all.sd->weighted_labels = (double)accumulate_scalar(all, all.span_server, weighted_labels); + float weighted_unlabeled_examples = (float)all.sd->weighted_unlabeled_examples; + all.sd->weighted_unlabeled_examples = (double)accumulate_scalar(all, all.span_server, weighted_unlabeled_examples); + float example_number = (float)all.sd->example_number; + all.sd->example_number = (uint64_t)accumulate_scalar(all, all.span_server, example_number); + float total_features = (float)all.sd->total_features; + all.sd->total_features = (uint64_t)accumulate_scalar(all, all.span_server, total_features); + } + + + if (!all.quiet) + { + cerr.precision(6); + cerr << endl << "finished run"; + if(all.current_pass == 0) + cerr << endl << "number of examples = " << all.sd->example_number; + else{ + cerr << endl << "number of examples per pass = " << all.sd->example_number / all.current_pass; + cerr << endl << "passes used = " << all.current_pass; + } + cerr << endl << "weighted example sum = " << all.sd->weighted_examples; + cerr << endl << "weighted label sum = " << all.sd->weighted_labels; + if(all.holdout_set_off || (all.sd->holdout_best_loss == FLT_MAX)) + cerr << endl << "average loss = " << all.sd->sum_loss / all.sd->weighted_examples; + else + cerr << endl << "average loss = " << all.sd->holdout_best_loss << " h"; + + float best_constant; float best_constant_loss; + if (get_best_constant(all, best_constant, best_constant_loss)) + { + cerr << endl << "best constant = " << best_constant; + if (best_constant_loss != FLT_MIN) + cerr << endl << "best constant's loss = " << best_constant_loss; + } + + cerr << endl << "total feature number = " << all.sd->total_features; + if (all.sd->queries > 0) + cerr << endl << "total queries = " << all.sd->queries << endl; + cerr << endl; + } + + VW::finish(all); + } catch (exception& e) { + // vw is implemented as a library, so we use 'throw exception()' + // error 'handling' everywhere. To reduce stderr pollution + // everything gets caught here & the error message is printed + // sans the excess exception noise, and core dump. + cerr << "vw: " << e.what() << endl; + exit(1); + } + return 0; +} + diff --git a/pool/shard008/C++/0096826_main.cpp b/pool/shard008/C++/0096826_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aea87c42815a1c184d2148bc0b9a05d3da3aef2e --- /dev/null +++ b/pool/shard008/C++/0096826_main.cpp @@ -0,0 +1,50 @@ +#include +#include +#include + +using namespace std; + +int** alocaMatriz (int N) +{ + int **m; + int i; + m = new int*[N]; + for (i = 0; i < N; i++) + m[i] = new int[N]; + return (m); +} + +void desalocaMatriz (int **m, int N) +{ + int i; + for (i = 0; i < N; i++) + delete [] m[i]; + delete [] m; +} + +int main () +{ + int **m, i, j, lin, col; + int N; + cin >> N; + while (N != 0) + { + m = alocaMatriz(N); + for (i = 0; i < N; i++) + { + for (j = 0; j < N; j++) + { + lin = i+1; + col = j+1; + m[i][j] = abs(col-lin)+1; + if (j == N-1) + printf("%3d\n", m[i][j]); + else + printf("%3d ", m[i][j]); + } + } + printf("\n"); + desalocaMatriz(m,N); + cin >> N; + } +} diff --git a/pool/shard008/C++/0096827_daytime_client.cpp b/pool/shard008/C++/0096827_daytime_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62c669c20c1f3510c673cd3cf21c976469e7277a --- /dev/null +++ b/pool/shard008/C++/0096827_daytime_client.cpp @@ -0,0 +1,89 @@ +// +// daytime_client.cpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +// STL +#include +// Boost +#include +#include +#include "logger.hpp" +#include "stream_socket_service.hpp" + +typedef boost::asio::basic_stream_socket > debug_stream_socket; + +char read_buffer[1024]; + +void read_handler(const boost::system::error_code& e, + std::size_t bytes_transferred, debug_stream_socket* s) { + if (!e) { + std::cout.write(read_buffer, bytes_transferred); + + s->async_read_some(boost::asio::buffer(read_buffer), + boost::bind(read_handler, boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred, s)); + } +} + +void connect_handler (const boost::system::error_code& e, debug_stream_socket* s, + boost::asio::ip::tcp::resolver::iterator endpoint_iterator) { + if (!e) { + s->async_read_some(boost::asio::buffer(read_buffer), + boost::bind(read_handler, boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred, s)); + + } else if (endpoint_iterator != boost::asio::ip::tcp::resolver::iterator()) { + s->close(); + + boost::asio::ip::tcp::endpoint endpoint = *endpoint_iterator; + s->async_connect(endpoint, + boost::bind(connect_handler, + boost::asio::placeholders::error, s, ++endpoint_iterator)); + + } else { + std::cerr << e.message() << std::endl; + } +} + +int main(int argc, char* argv[]) { + try { + + if (argc != 2) { + std::cerr << "Usage: daytime_client " << std::endl; + return 1; + } + + boost::asio::io_service io_service; + + // Set the name of the file that all logger instances will use. + services::logger logger(io_service, ""); + logger.use_file("daytime_service.log"); + + // Resolve the address corresponding to the given host. + boost::asio::ip::tcp::resolver resolver (io_service); + boost::asio::ip::tcp::resolver::query query (argv[1], "aria"); + boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query); + boost::asio::ip::tcp::endpoint endpoint = *iterator; + + // Start an asynchronous connect. + debug_stream_socket socket(io_service); + socket.async_connect(endpoint, + boost::bind(connect_handler, + boost::asio::placeholders::error, &socket, ++iterator)); + + // Run the io_service until all operations have finished. + io_service.run(); + + } catch (std::exception& e) { + std::cerr << e.what() << std::endl; + } + + return 0; +} diff --git a/pool/shard008/C++/0096829_kexec.cc b/pool/shard008/C++/0096829_kexec.cc new file mode 100644 index 0000000000000000000000000000000000000000..c3c44e737bd148b6edcc956f8a3ca9abc4ab78dc --- /dev/null +++ b/pool/shard008/C++/0096829_kexec.cc @@ -0,0 +1,117 @@ +#include +#include +#include +#if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__) +#include +#endif + +//#ifdef __POSIX__ +#include +/*#else +#include +#endif*/ + +#include + + +using v8::Array; +using v8::FunctionTemplate; +using v8::Handle; +using v8::Integer; +using v8::Local; +using v8::Object; +using v8::String; + + +static int clear_cloexec (int desc) +{ + int flags = fcntl (desc, F_GETFD, 0); + if (flags < 0) + return flags; //return if reading failed + + flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit + return fcntl (desc, F_SETFD, flags); +} + +static int do_exec(char *argv[]) +{ + clear_cloexec(0); //stdin + clear_cloexec(1); //stdout + clear_cloexec(2); //stderr + return execvp(argv[0], argv); +} + +NAN_METHOD(kexec) { + /* + * Steve Blott: 17 Jan, 2014 + * Temporary comment by way of explanation... + * To be deleted. + * + * With a single argument: + * - pass it to execvp as "sh -c 'args[0]'" + * - this is the existing usage + * + * With exactly two arguments: + * - the first is the command name + * - the second is an array of arguments + * ...as in process.child_process.spawn() + * + * This approach is not great, but it allows the established usage to + * coexist with direct execvp-usage, and avoids making any changes to the + * established API. + */ + + if ( 1 == info.Length() && info[0]->IsString() ) + { + String::Utf8Value str(info[0]); + char* argv[] = { const_cast("/bin/sh"), const_cast("-c"), *str, NULL}; + + int err = do_exec(argv); + + info.GetReturnValue().Set(Nan::New(err)); + } + + if ( 2 == info.Length() && info[0]->IsString() && info[1]->IsArray() ) + { + String::Utf8Value str(info[0]); + + // Substantially copied from: + // https://github.com/joyent/node/blob/2944e03/src/node_child_process.cc#L92-104 + Local argv_handle = Local::Cast(info[1]); + int argc = argv_handle->Length(); + + int argv_length = argc + 1 + 1; + char **argv = new char*[argv_length]; + + argv[0] = *str; + argv[argv_length-1] = NULL; + for (int i = 0; i < argc; i++) { + String::Utf8Value arg(argv_handle->Get(Nan::New(i))->ToString()); + argv[i+1] = strdup(*arg); + } + + int err = do_exec(argv); + + // Failed...! + // FIXME: It might be better to raise an exception here. + for (int i = 0; i < argc; i++) + free(argv[i+1]); + delete [] argv; + + info.GetReturnValue().Set(Nan::New(err)); + } + + return Nan::ThrowTypeError("kexec: invalid arguments"); +} + + +#define EXPORT(name, symbol) exports->Set( \ + Nan::New(name).ToLocalChecked(), \ + Nan::New(symbol)->GetFunction() \ +) + +void init (Handle exports) { + EXPORT("kexec", kexec); +} + +NODE_MODULE(kexec, init); diff --git a/pool/shard008/C++/0096831_eigen.cc b/pool/shard008/C++/0096831_eigen.cc new file mode 100644 index 0000000000000000000000000000000000000000..f2249a32434efc7fb265fe879db87ef27be368f0 --- /dev/null +++ b/pool/shard008/C++/0096831_eigen.cc @@ -0,0 +1,91 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 1998 - 2016 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, 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. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +#include "../tests.h" +#include "../testmatrix.h" +#include +#include +#include +#include +#include +#include + +int main() +{ + std::ofstream logfile("output"); +// logfile.setf(std::ios::fixed); + deallog << std::setprecision(4); + deallog.attach(logfile); + + GrowingVectorMemory<> mem; + SolverControl control(1000, 1.e-5); + + const unsigned int size = 10; + const unsigned int dim = (size-1)*(size-1); + + /* + * Compute minimal and maximal + * eigenvalues of the 5-point + * stencil matrix + * (Hackbusch:Iterative Lösung..., + * Satz 4.1.1) + */ + const double h = 1./size; + const double s = std::sin(numbers::PI*h/2.); + const double c = std::cos(numbers::PI*h/2.); + const double lambda_max = 8.*c*c; + const double lambda_min = 8.*s*s; + + FDMatrix testproblem(size, size); + SparsityPattern structure(dim, dim, 5); + testproblem.five_point_structure(structure); + structure.compress(); + SparseMatrix A(structure); + testproblem.five_point(A); + + Vector u(dim); + u = 1.; + double lambda; + + EigenPower<> mises(control, mem); + mises.solve(lambda, A, u); + deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl; + + double lambda2; + u = 1.; + + EigenPower<> mises2(control, mem, -1.5*lambda); + mises2.solve(lambda2, A, u); + deallog << "Eigenvalue " << lambda2 << " Error " << lambda2-lambda_min << std::endl; + + u = 1.; + lambda = 0.; + EigenInverse<> wieland(control, mem); + wieland.solve(lambda, A, u); + deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_min << std::endl; + + u = 1.; + lambda = 10.; + wieland.solve(lambda, A, u); + deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl; + + u = 1.; + lambda = 10.; + EigenInverse<> wieland2(control, mem, .2); + wieland2.solve(lambda, A, u); + deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl; +} diff --git a/pool/shard008/C++/0096833_SoListenerPositionElement.cpp b/pool/shard008/C++/0096833_SoListenerPositionElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dcfbd9f41b0884cf0484938348c045cbd7b6351 --- /dev/null +++ b/pool/shard008/C++/0096833_SoListenerPositionElement.cpp @@ -0,0 +1,158 @@ +/**************************************************************************\ + * Copyright (c) Kongsberg Oil & Gas Technologies AS + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the copyright holder 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. +\**************************************************************************/ + +/*! + \class SoListenerPositionElement Inventor/elements/SoListenerPositionElement.h + \brief The SoListenerPositionElement holds the position of the current listener. + \ingroup elements + + This position is set by SoListener nodes and SoCamera Nodes during audio + rendering. When a SoListener is visited by the SoAudioRenderAction, + it will add a new SoListenerPositionElement to the state, holding it's + position and with the setbylistener flag set. When a SoCamera is visited + by SoAudioRenderAction, it will add a new SoListenerPositionElement only + if there are no previous elements with the setbylistener flag set. + + The SoListenerPositionElement is used when the SoVRMLSound nodes render + themselves. + + \COIN_CLASS_EXTENSION + + \since Coin 2.0 +*/ + +#include + +#include "coindefs.h" +#include "SbBasicP.h" + +#include + +/*! + \fn SoListenerPositionElement::position + + The position of the listener in world space. Can be set by the + SoListener class or the SoCamera class. +*/ + +SO_ELEMENT_SOURCE(SoListenerPositionElement); + +/*! + This static method initializes static data for the + SoListenerPositionElement class. +*/ + +void +SoListenerPositionElement::initClass(void) +{ + SO_ELEMENT_INIT_CLASS(SoListenerPositionElement, inherited); +} + +/*! + The destructor. +*/ + +SoListenerPositionElement::~SoListenerPositionElement(void) +{ +} + +/*! + Initializes the element to it's default value. The default + value for the position is (0.0f, 0.0f, 0.0f) and the + default value for the setByListener flag is FALSE. +*/ + +void +SoListenerPositionElement::init(SoState * state) +{ + inherited::init(state); + this->position = SbVec3f(0.0f, 0.0f, 0.0f); + this->setbylistener = FALSE; +} + +/*! + Sets the current listener position, and indicates if it was set + by a SoListener node or a SoCamera node. +*/ + +void +SoListenerPositionElement::set(SoState * const state, + SoNode * const COIN_UNUSED_ARG(node), + const SbVec3f & position, + SbBool setbylistener) +{ + SoListenerPositionElement * elem = + coin_safe_cast + ( + SoElement::getElement(state, classStackIndex) + ); + if (elem) { + elem->position = position; + elem->setbylistener = setbylistener; + } +} + +//! Returns the current listener position + +const SbVec3f & +SoListenerPositionElement::get(SoState * const state) +{ + const SoListenerPositionElement * elem = + coin_assert_cast + ( + SoElement::getConstElement(state, classStackIndex) + ); + return elem->position; +} + +/*! + Returns TRUE if the position was set by a SoListener node, + and FALSE if it was set by a SoCamera node +*/ + +SbBool +SoListenerPositionElement::isSetByListener(SoState * const state) +{ + const SoListenerPositionElement * elem = + coin_assert_cast + ( + SoElement::getConstElement(state, classStackIndex) + ); + return elem->setbylistener; +} + +//! Prints contents of element (not implemented) + +void +SoListenerPositionElement::print(FILE * /* file */) const +{ +} diff --git a/pool/shard008/C++/0096837_curl_handle.cpp b/pool/shard008/C++/0096837_curl_handle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..663a931ff2dbd04808da8ca035397f212b624074 --- /dev/null +++ b/pool/shard008/C++/0096837_curl_handle.cpp @@ -0,0 +1,64 @@ +/*************************************************************************** + * Copyright (C) 2008-2014 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. * + ***************************************************************************/ + +#include "curl_handle.h" + +#ifdef HAVE_CURL_CURL_H + +#include +#include + +namespace +{ + size_t write_data(char *buffer, size_t size, size_t nmemb, void *data) + { + size_t result = size*nmemb; + static_cast(data)->append(buffer, result); + return result; + } +} + +CURLcode Curl::perform(std::string &data, const std::string &URL, const std::string &referer, unsigned timeout) +{ + CURLcode result; + CURL *c = curl_easy_init(); + curl_easy_setopt(c, CURLOPT_URL, URL.c_str()); + curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(c, CURLOPT_WRITEDATA, &data); + curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, timeout); + curl_easy_setopt(c, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(c, CURLOPT_USERAGENT, "ncmpcpp " VERSION); + if (!referer.empty()) + curl_easy_setopt(c, CURLOPT_REFERER, referer.c_str()); + result = curl_easy_perform(c); + curl_easy_cleanup(c); + return result; +} + +std::string Curl::escape(const std::string &s) +{ + char *cs = curl_easy_escape(0, s.c_str(), s.length()); + std::string result(cs); + curl_free(cs); + return result; +} + +#endif // HAVE_CURL_CURL_H + diff --git a/pool/shard008/C++/0096839_NonSmoothDynamicalSystem.cpp b/pool/shard008/C++/0096839_NonSmoothDynamicalSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e76aee09cf364c00cf6c09755b28382e9faeb592 --- /dev/null +++ b/pool/shard008/C++/0096839_NonSmoothDynamicalSystem.cpp @@ -0,0 +1,197 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2016 INRIA. + * + * 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 "NonSmoothDynamicalSystem.hpp" +#include "Topology.hpp" +#include "Interaction.hpp" +#include "LagrangianLinearTIDS.hpp" +#include "FirstOrderLinearTIDS.hpp" +#include "Relation.hpp" + +#include +#if defined(SICONOS_STD_FUNCTIONAL) && !defined(SICONOS_USE_BOOST_FOR_CXX11) +#include +using namespace std::placeholders; +#else +#include +#include +#endif + +#include "debug.h" + + +using namespace RELATION; + +// --- CONSTRUCTORS/DESTRUCTOR --- + +// Default constructor +NonSmoothDynamicalSystem::NonSmoothDynamicalSystem(): _BVP(false), _mIsLinear(true) +{ + // === Builds an empty topology === + _topology.reset(new Topology()); +}; + + +NonSmoothDynamicalSystem::~NonSmoothDynamicalSystem() +{ + clear(); +} + +// === DynamicalSystems management === + +void NonSmoothDynamicalSystem::display() const +{ + std::cout << " ===== Non Smooth Dynamical System display ===== " < isBVP = " << _BVP <begin(); + _topology->indexSet0()->display(); + std::cout << "===================================================" < +double NonSmoothDynamicalSystem::nsdsConvergenceIndicator() +{ + // calculate the max value of all DS convergence indicators + double convergenceIndicator = -std::numeric_limits::infinity(); + double dsIndic ; + DynamicalSystemsGraph::VIterator vi; + for (vi = dynamicalSystems()->begin(); vi != dynamicalSystems()->end(); ++vi) + { + dsIndic = dynamicalSystems()->bundle(*vi)->dsConvergenceIndicator(); + if (dsIndic > convergenceIndicator) convergenceIndicator = dsIndic; + } + return(convergenceIndicator); +} + +void NonSmoothDynamicalSystem::link(SP::Interaction inter, SP::DynamicalSystem ds1, SP::DynamicalSystem ds2) +{ + _mIsLinear = ((inter)->relation()->isLinear() && _mIsLinear); + _topology->link(inter, ds1, ds2); +}; + + +void NonSmoothDynamicalSystem::clear() +{ + _topology->clear(); +} + +void NonSmoothDynamicalSystem::setSymmetric(bool val) +{ + _topology->setSymmetric(val); +} + + +void NonSmoothDynamicalSystem::reset() +{ + DynamicalSystemsGraph::VIterator vi; + for (vi = dynamicalSystems()->begin(); vi != dynamicalSystems()->end(); ++vi) + { + dynamicalSystems()->bundle(*vi)->resetNonSmoothPart(1); + } +} + +void NonSmoothDynamicalSystem::reset(unsigned int level) +{ + DynamicalSystemsGraph::VIterator vi; + for (vi = dynamicalSystems()->begin(); vi != dynamicalSystems()->end(); ++vi) + { + dynamicalSystems()->bundle(*vi)->resetNonSmoothPart(level); + } +} + +void NonSmoothDynamicalSystem::swapInMemory() +{ + //could be better to call bind method + DynamicalSystemsGraph::VIterator vi; + for (vi = dynamicalSystems()->begin(); vi != dynamicalSystems()->end(); ++vi) + { + dynamicalSystems()->bundle(*vi)->swapInMemory(); + } +} +void NonSmoothDynamicalSystem::pushInteractionsInMemory() +{ + // Save Interactions state into Memory. + + if (_topology->indexSet0()->size() > 0) + { + // Temp FP : saveInOldVar was called for each osns and each osns call + // swapInOldVar for all interactions in the nsds. + // ==> let's do it only once, by the simu. + + InteractionsGraph::VIterator ui, uiend; + SP::InteractionsGraph indexSet0 = _topology->indexSet0(); + for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui) + { + indexSet0->bundle(*ui)->swapInOldVariables(); + indexSet0->bundle(*ui)->swapInMemory(); + } + } +} + +void NonSmoothDynamicalSystem::updateInput(double time, unsigned int level) +{ + + DEBUG_BEGIN("Nonsmoothdynamicalsystem::updateInput(double time, unsigned int level)\n"); + DEBUG_PRINTF("with level = %i\n", level); + + + // To compute input(level) (ie with lambda[level]) for all Interactions. + // assert(level>=0); + + // Set dynamical systems non-smooth part to zero. + reset(level); + + // We compute input using lambda(level). + InteractionsGraph::VIterator ui, uiend; + SP::Interaction inter; + SP::InteractionsGraph indexSet0 = _topology->indexSet0(); + for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui) + { + inter = indexSet0->bundle(*ui); + assert(inter->lowerLevelForInput() <= level); + assert(inter->upperLevelForInput() >= level); + inter->computeInput(time, indexSet0->properties(*ui), level); + } + + DEBUG_END("Nonsmoothdynamicalsystem::updateInput(double time, unsigned int level)\n"); + +} + + +void NonSmoothDynamicalSystem::updateOutput(double time, unsigned int level) +{ + + // To compute output(level) (ie with y[level]) for all Interactions. + // assert(level>=0); + + DEBUG_BEGIN("NonSmoothDynamicalSystem::updateOutput(unsigned int level)\n"); + DEBUG_PRINTF("with level = %i\n", level); + InteractionsGraph::VIterator ui, uiend; + SP::Interaction inter; + SP::InteractionsGraph indexSet0 = _topology->indexSet0(); + for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui) + { + inter = indexSet0->bundle(*ui); + assert(inter->lowerLevelForOutput() <= level); + assert(inter->upperLevelForOutput() >= level); + inter->computeOutput(time, indexSet0->properties(*ui), level); + } + DEBUG_END("NonSmoothDynamicalSystem::updateOutput(unsigned int level)\n"); + +} + + diff --git a/pool/shard008/C++/0096841_numsys.cpp b/pool/shard008/C++/0096841_numsys.cpp new file mode 100644 index 0000000000000000000000000000000000000000..534ed156cefeb60318008e25bf57f7508f258f20 --- /dev/null +++ b/pool/shard008/C++/0096841_numsys.cpp @@ -0,0 +1,247 @@ +/* +******************************************************************************* +* Copyright (C) 2010, International Business Machines Corporation and +* others. All Rights Reserved. +******************************************************************************* +* +* +* File NUMSYS.CPP +* +* Modification History:* +* Date Name Description +* +******************************************************************************** +*/ + +#include "unicode/utypes.h" +#include "unicode/localpointer.h" +#include "unicode/uchar.h" +#include "unicode/unistr.h" +#include "unicode/ures.h" +#include "unicode/ustring.h" +#include "unicode/uloc.h" +#include "unicode/schriter.h" +#include "unicode/numsys.h" +#include "cstring.h" +#include "uresimp.h" + +#if !UCONFIG_NO_FORMATTING + +U_NAMESPACE_BEGIN + +// Useful constants + +#define DEFAULT_DIGITS UNICODE_STRING_SIMPLE("0123456789"); +static const char gNumberingSystems[] = "numberingSystems"; +static const char gNumberElements[] = "NumberElements"; +static const char gDefault[] = "default"; +static const char gDesc[] = "desc"; +static const char gRadix[] = "radix"; +static const char gAlgorithmic[] = "algorithmic"; +static const char gLatn[] = "latn"; + + +UOBJECT_DEFINE_RTTI_IMPLEMENTATION(NumberingSystem) + + /** + * Default Constructor. + * + * @draft ICU 4.2 + */ + +NumberingSystem::NumberingSystem() { + radix = 10; + algorithmic = FALSE; + UnicodeString defaultDigits = DEFAULT_DIGITS; + desc.setTo(defaultDigits); + uprv_strcpy(name,gLatn); +} + + /** + * Copy constructor. + * @draft ICU 4.2 + */ + +NumberingSystem::NumberingSystem(const NumberingSystem& other) +: UObject(other) { + *this=other; +} + +NumberingSystem* U_EXPORT2 +NumberingSystem::createInstance(int32_t radix_in, UBool isAlgorithmic_in, const UnicodeString & desc_in, UErrorCode &status) { + + if (U_FAILURE(status)) { + return NULL; + } + + if ( radix_in < 2 ) { + status = U_ILLEGAL_ARGUMENT_ERROR; + return NULL; + } + + if ( !isAlgorithmic_in ) { + if ( desc_in.countChar32() != radix_in || !isValidDigitString(desc_in)) { + status = U_ILLEGAL_ARGUMENT_ERROR; + return NULL; + } + } + + NumberingSystem *ns = new NumberingSystem(); + + ns->setRadix(radix_in); + ns->setDesc(desc_in); + ns->setAlgorithmic(isAlgorithmic_in); + ns->setName(NULL); + return ns; + +} + + +NumberingSystem* U_EXPORT2 +NumberingSystem::createInstance(const Locale & inLocale, UErrorCode& status) { + + if (U_FAILURE(status)) { + return NULL; + } + + char buffer[ULOC_KEYWORDS_CAPACITY]; + int32_t count = inLocale.getKeywordValue("numbers",buffer, sizeof(buffer),status); + if ( count > 0 ) { // @numbers keyword was specified in the locale + buffer[count] = '\0'; // Make sure it is null terminated. + return NumberingSystem::createInstanceByName(buffer,status); + } else { // Find the default numbering system for this locale. + UResourceBundle *resource = ures_open(NULL, inLocale.getName(), &status); + UResourceBundle *numberElementsRes = ures_getByKey(resource,gNumberElements,NULL,&status); + const UChar *defaultNSName = + ures_getStringByKeyWithFallback(numberElementsRes, gDefault, &count, &status); + ures_close(numberElementsRes); + ures_close(resource); + + if (U_FAILURE(status)) { + status = U_USING_FALLBACK_WARNING; + NumberingSystem *ns = new NumberingSystem(); + return ns; + } + + if ( count > 0 && count < ULOC_KEYWORDS_CAPACITY ) { // Default numbering system found + u_UCharsToChars(defaultNSName,buffer,count); + buffer[count] = '\0'; // Make sure it is null terminated. + return NumberingSystem::createInstanceByName(buffer,status); + } else { + status = U_USING_FALLBACK_WARNING; + NumberingSystem *ns = new NumberingSystem(); + return ns; + } + + } +} + +NumberingSystem* U_EXPORT2 +NumberingSystem::createInstance(UErrorCode& status) { + return NumberingSystem::createInstance(Locale::getDefault(), status); +} + +NumberingSystem* U_EXPORT2 +NumberingSystem::createInstanceByName(const char *name, UErrorCode& status) { + + UResourceBundle *numberingSystemsInfo = NULL; + UResourceBundle *nsTop, *nsCurrent; + const UChar* description = NULL; + int32_t radix = 10; + int32_t algorithmic = 0; + int32_t len; + + numberingSystemsInfo = ures_openDirect(NULL,gNumberingSystems, &status); + nsCurrent = ures_getByKey(numberingSystemsInfo,gNumberingSystems,NULL,&status); + nsTop = ures_getByKey(nsCurrent,name,NULL,&status); + description = ures_getStringByKey(nsTop,gDesc,&len,&status); + + ures_getByKey(nsTop,gRadix,nsCurrent,&status); + radix = ures_getInt(nsCurrent,&status); + + ures_getByKey(nsTop,gAlgorithmic,nsCurrent,&status); + algorithmic = ures_getInt(nsCurrent,&status); + + UBool isAlgorithmic = ( algorithmic == 1 ); + UnicodeString nsd; + nsd.setTo(description); + + ures_close(nsCurrent); + ures_close(nsTop); + ures_close(numberingSystemsInfo); + + if (U_FAILURE(status)) { + status = U_UNSUPPORTED_ERROR; + return NULL; + } + + NumberingSystem* ns = NumberingSystem::createInstance(radix,isAlgorithmic,nsd,status); + ns->setName(name); + return ns; +} + + /** + * Destructor. + * @draft ICU 4.2 + */ +NumberingSystem::~NumberingSystem() { +} + +int32_t NumberingSystem::getRadix() { + return radix; +} + +UnicodeString NumberingSystem::getDescription() { + return desc; +} + +const char * NumberingSystem::getName() { + return name; +} + +void NumberingSystem::setRadix(int32_t r) { + radix = r; +} + +void NumberingSystem::setAlgorithmic(UBool c) { + algorithmic = c; +} + +void NumberingSystem::setDesc(UnicodeString d) { + desc.setTo(d); +} +void NumberingSystem::setName(const char *n) { + if ( n == NULL ) { + name[0] = (char) 0; + } else { + uprv_strncpy(name,n,NUMSYS_NAME_CAPACITY); + name[NUMSYS_NAME_CAPACITY] = (char)0; // Make sure it is null terminated. + } +} +UBool NumberingSystem::isAlgorithmic() const { + return ( algorithmic ); +} + + +UBool NumberingSystem::isValidDigitString(const UnicodeString& str) { + + StringCharacterIterator it(str); + UChar32 c; + UChar32 prev = 0; + int32_t i = 0; + + for ( it.setToStart(); it.hasNext(); ) { + c = it.next32PostInc(); + if ( c > 0xFFFF ) { // Digits outside the BMP are not currently supported + return FALSE; + } + i++; + prev = c; + } + return TRUE; +} +U_NAMESPACE_END + +#endif /* #if !UCONFIG_NO_FORMATTING */ + +//eof diff --git a/pool/shard008/C++/0096843_MinHeap.cpp b/pool/shard008/C++/0096843_MinHeap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7036effebc738649f7f9129a92df4b29e2af1f5d --- /dev/null +++ b/pool/shard008/C++/0096843_MinHeap.cpp @@ -0,0 +1,75 @@ +// +// MinHeap.cpp +// +// Implementation of a min binary heap class +// See MinHeap.hpp +// +// Algorithms +// +// Created by Tyler Scott on 6/1/16. +// Copyright © 2016 Tyler Scott. All rights reserved. +// + +#include +#include "MinHeap.hpp" + +MinHeap::MinHeap() { + heapSize = 0; + heap = NULL; +} + +//Return the parent index for a given index in the array, i +int MinHeap::parent(int i) { + if(i % 2 == 0) + return (i / 2) - 1; + else + return i / 2; +} + +//Return the index of the left child for a given index in the array, i +int MinHeap::left(int i) { + return 2 * i + 1; +} + +//Return the index of the right child for a given index in the array, i +int MinHeap::right(int i) { + return 2 * i + 2; +} + +//Take an index in the heap and min heapify from that index +//Assume that the left index and right index are min heaps, themselves +void MinHeap::minHeapify(int i) { + if(i < heapSize) { + int smallest; + int left_index = left(i); + + if(left_index < heapSize && heap[left_index] < heap[i]) + smallest = left_index; + else + smallest = i; + + int right_index = right(i); + if(right_index < heapSize && heap[right_index] < heap[smallest]) + smallest = right_index; + + //If the heap was not a min heap, trickle down the child containing 'smallest', and min heapify that sub-heap + if(smallest != i) { + int temp = heap[i]; + heap[i] = heap[smallest]; + heap[smallest] = temp; + + minHeapify(smallest); + } + } +} + +//Build a min heap from an array +void MinHeap::buildMinHeap(int *arr, int n) { + heapSize = n; + heap = arr; + + //We only need to loop down from heapSize / 2 because all nodes above that are leaves + for(int i = heapSize / 2; i >= 0; i--) { + minHeapify(i); + } +} \ No newline at end of file diff --git a/pool/shard008/C++/0096845_qpaircontainer.cpp b/pool/shard008/C++/0096845_qpaircontainer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9de876796ff7ef29d4fe43af46882e9a45b3ea7a --- /dev/null +++ b/pool/shard008/C++/0096845_qpaircontainer.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtXmlPatterns module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qbuiltintypes_p.h" + +#include "qpaircontainer_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +PairContainer::PairContainer(const Expression::Ptr &operand1, + const Expression::Ptr &operand2) : m_operand1(operand1), + m_operand2(operand2) +{ + Q_ASSERT(m_operand1); + Q_ASSERT(m_operand2); +} + +Expression::List PairContainer::operands() const +{ + Expression::List list; + list.append(m_operand1); + list.append(m_operand2); + return list; +} + +void PairContainer::setOperands(const Expression::List &ops) +{ + Q_ASSERT(ops.count() == 2); + m_operand1 = ops.first(); + m_operand2 = ops.last(); + Q_ASSERT(m_operand1); + Q_ASSERT(m_operand2); +} + +bool PairContainer::compressOperands(const StaticContext::Ptr &context) +{ + Q_ASSERT(m_operand1); + Q_ASSERT(m_operand2); + rewrite(m_operand1, m_operand1->compress(context), context); + rewrite(m_operand2, m_operand2->compress(context), context); + + return m_operand1->isEvaluated() && m_operand2->isEvaluated(); +} + +QT_END_NAMESPACE diff --git a/pool/shard008/C++/0096851_benchmark.cpp b/pool/shard008/C++/0096851_benchmark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..276a0a075fb8133530469462c66460a390509880 --- /dev/null +++ b/pool/shard008/C++/0096851_benchmark.cpp @@ -0,0 +1,87 @@ +#include + +#include "../../benchmark.hpp" + +namespace compute = boost::compute; + +namespace aya +{ +namespace bench +{ +void ping() +{ + std::cout << "pong from boost compute benchmark backend" << std::endl; +} + +std::string name() +{ + return "boost"; +} + +template +struct BoostBenchmarkBackend : BenchmarkBackend +{ + BoostBenchmarkBackend() + { + // TODO: is there copy overhead when using assign? but those does not contains data, so I guess it's low + // for vector, maybe use swap? http://en.cppreference.com/w/cpp/container/vector/swap + gpu = compute::system::default_device(); + context = compute::context(gpu); + queue = compute::command_queue(context, gpu); + } + + ~BoostBenchmarkBackend() + { + std::cout << "boost benchmark backend destructor called\n"; + } + + void generate(int num) + { + std::cout << "generateing !\n"; + h_vec.resize(num); + std::generate(h_vec.begin(), h_vec.end(), rand); + // TODO: bechmark this assign operation? does it copy anything? + d_vec = compute::vector(num, context); + std::cout << "generated !\n"; + } + + void copy() + { + compute::copy(h_vec.begin(), h_vec.end(), d_vec.begin(), queue); + queue.finish(); + } + + void sort() + { + compute::sort(d_vec.begin(), d_vec.end(), queue); + queue.finish(); + } + + void reduce() + { + T x = 0; + compute::reduce(d_vec.begin(), d_vec.end(), &x, queue); + queue.finish(); + } + + private: + std::vector h_vec; + compute::vector d_vec; + compute::device gpu; + compute::context context; + compute::command_queue queue; +}; + +template +BenchmarkBackend *init() +{ + return new BoostBenchmarkBackend; +} + +} // bench +} // aya::bench + +int main(int argc, char **argv) +{ + return aya::bench::launch(argc, argv); +} diff --git a/pool/shard008/C++/0096852_ListReviewableHITsResult.cpp b/pool/shard008/C++/0096852_ListReviewableHITsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1968df4503aae28e53edc7c6e016a3a7ef052ba3 --- /dev/null +++ b/pool/shard008/C++/0096852_ListReviewableHITsResult.cpp @@ -0,0 +1,67 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::MTurk::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListReviewableHITsResult::ListReviewableHITsResult() : + m_numResults(0) +{ +} + +ListReviewableHITsResult::ListReviewableHITsResult(const Aws::AmazonWebServiceResult& result) : + m_numResults(0) +{ + *this = result; +} + +ListReviewableHITsResult& ListReviewableHITsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("NextToken")) + { + m_nextToken = jsonValue.GetString("NextToken"); + + } + + if(jsonValue.ValueExists("NumResults")) + { + m_numResults = jsonValue.GetInteger("NumResults"); + + } + + if(jsonValue.ValueExists("HITs")) + { + Array hITsJsonList = jsonValue.GetArray("HITs"); + for(unsigned hITsIndex = 0; hITsIndex < hITsJsonList.GetLength(); ++hITsIndex) + { + m_hITs.push_back(hITsJsonList[hITsIndex].AsObject()); + } + } + + + + return *this; +} diff --git a/pool/shard008/C++/0096858_EulerTour.cpp b/pool/shard008/C++/0096858_EulerTour.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f126de4444b173904ffb532cfb02d0647de875a --- /dev/null +++ b/pool/shard008/C++/0096858_EulerTour.cpp @@ -0,0 +1,174 @@ +/* + * EulerTour.cpp + * + * Copyright 2015 Robert Bakaric + * + * 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 + + +namespace po = boost::program_options; +using namespace std; + + + +void PrintAcknowledgements(){ + +cout <<"***************************************************************************************"<<"\n"; +cout <<" EulerTour - Euler Tour Tree Representation "<<"\n"; +cout <<" by "<<"\n"; +cout <<" Robert Bakaric "<<"\n\n"; +cout <<"CONTACT: "<<"\n"; +cout <<" Code written and maintained by Robert Bakaric, "<<"\n"; +cout <<" email: rbakaric@irb.hr , bakaric@evolbio.mpg.de "<<"\n\n"; +cout <<"ACKNOWLEDGEMENT: "<<"\n"; +cout <<" "<<"\n\n"; +cout <<"LICENSE: "<<"\n"; +cout <<" The program is distributed under the GNU General Public License. You should have "<<"\n"; +cout <<" received a copy of the licence together with this software. If not, see "<<"\n"; +cout <<" http://www.gnu.org/licenses/ "<<"\n"; +cout <<"***************************************************************************************"<<"\n\n\n"; +} + + +template +po::variables_map SetOptions(INT& argc, CHARA& argv){ + + try { + int opt; + string version = "1.02"; + po::options_description desc("Allowed options"); + desc.add_options() + ("help,h", "produce help message") + ("version,v", "print version information") + ("input-file,i", po::value< string >(), "input file") + ; + + po::positional_options_description p; + p.add("input-file,i", -1); + + po::variables_map vm; + po::store(po::command_line_parser(argc, argv). + options(desc).positional(p).run(), vm); + po::notify(vm); + + if (vm.count("help")) { + cout << "Usage: ./program [options]\n\n"; + PrintAcknowledgements(); + cout << desc; + exit(0); + }else if (vm.count("version")) { + cout << "Program version: " << version << "\n"; + exit(0); + } + if (!vm.count("input-file")){ + cout << "Input file is not defined \n"; + exit(0); + } + return vm; + } + catch(std::exception& e) + { + cout << e.what() << "\n"; + exit(0); + } +} + +template +ostream& operator<<(ostream& os, const vector& v) +{ + copy(v.begin(), v.end(), ostream_iterator(os, " ")); + return os; +} + + +template +void ReadGraph(const string & file, vector& parent, vector& child){ + + fstream fs; + fs.open (file.c_str(), ios::in); + if ( !fs.is_open()){ + cerr << "Cannot open file: "<> child[i]; + fs >> parent[i++] ; + } + + parent.resize(i-1); + child.resize(i-1); + fs.close(); +} + + + +int main (int argc, char** argv){ + +/* Get cmd Options */ + po::variables_map arg; + arg = SetOptions(argc,argv); + + string file = arg["input-file"].as(); + + vector parent; + vector child; + +/* Read Graph */ + ReadGraph(file, parent, child); + +/* Construct Euler Tour */ + Euler EObject(parent,child); + + + vector vec(parent); + sort( vec.begin(), vec.end() ); + vec.erase( unique( vec.begin(), vec.end() ), vec.end() ); + int start = 0; + + while(1){ + cout << "\nNOTE: Ctrl-c to quit!\n\n"; + cout<< "List of vertices:\n" << vec <> start; + EObject.Traverse(start); + +/* Print results */ + cout << "\n\nEuler Path:\n\n"; + cout << "Depth:\t" << EObject.GetDepthVec() << endl; + cout << "\nVertexId:\t" << EObject.GetVertexIdVec() << endl; + + EObject.Clean(); + } + return 0; +} diff --git a/pool/shard008/C++/0096863_clohessyWiltshirePropagator.cpp b/pool/shard008/C++/0096863_clohessyWiltshirePropagator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0966fda73e959424e463856417efeee6acf98ad7 --- /dev/null +++ b/pool/shard008/C++/0096863_clohessyWiltshirePropagator.cpp @@ -0,0 +1,84 @@ +/* Copyright (c) 2010-2019, Delft University of Technology + * All rigths reserved + * + * This file is part of the Tudat. Redistribution and use in source and + * binary forms, with or without modification, are permitted exclusively + * under the terms of the Modified BSD license. You should have received + * a copy of the license with this file. If not, please or visit: + * http://tudat.tudelft.nl/LICENSE. + * + * References + * Vallado, D.A. Fundamentals of Astrodynamics and Applications. Microcosm Press, 2001. + * + */ + +#include + +#include "Tudat/Astrodynamics/BasicAstrodynamics/clohessyWiltshirePropagator.h" + +namespace tudat +{ +namespace basic_astrodynamics +{ + +// Declare basic mathematical operations. +using std::sqrt; +using std::cos; +using std::sin; + +//! Propagate linearized relative motion. +Eigen::Vector6d propagateClohessyWiltshire( + const Eigen::Vector6d& initialState, + const double propagationDuration, + const double centralBodyGravitationalParameter, + const double referenceOrbitRadius ) +{ + // Initialize final state vector. + Eigen::Vector6d finalState; + + // Calculate mean angular motion of reference orbit. + const double meanAngularMotion = + sqrt( centralBodyGravitationalParameter + / ( referenceOrbitRadius * referenceOrbitRadius * referenceOrbitRadius ) ); + + // Calculate integration constants of Clohessy-Wiltshire equations. + const double integrationConstant1 = 4.0 * initialState( 0 ) + + 2.0 * initialState( 4 ) / meanAngularMotion; + const double integrationConstant2 = initialState( 1 ) + - 2.0 * initialState( 3 ) / meanAngularMotion; + const double integrationConstant3 = 3.0 * initialState( 0 ) + + 2.0 * initialState( 4 ) / meanAngularMotion; + const double integrationConstant4 = initialState( 3 ) / meanAngularMotion; + const double integrationConstant5 = initialState( 2 ); + const double integrationConstant6 = initialState( 5 ) / meanAngularMotion; + + // Calculate dynamical terms of Clohessy-Wiltshire equations. + const double cosineTerm = cos( meanAngularMotion * propagationDuration ); + const double sineTerm = sin( meanAngularMotion * propagationDuration ); + + // Calculate Cartesian position components with Clohessy-Wilthsire equations as given by + // by Vallado [2001, p. 382]. + finalState( 0 ) = integrationConstant1 - integrationConstant3 * cosineTerm + + integrationConstant4 * sineTerm; + finalState( 1 ) = integrationConstant2 + - 1.5 * integrationConstant1 * meanAngularMotion * propagationDuration + + 2.0 * integrationConstant3 * sineTerm + + 2.0 * integrationConstant4 * cosineTerm; + finalState( 2 ) = integrationConstant5 * cosineTerm + integrationConstant6 * sineTerm; + + // Calculate Cartesian velocity components with Clohessy-Wilthsire equations as given by + // by Vallado [2001, p. 382]. + finalState( 3 ) = meanAngularMotion * integrationConstant3 * sineTerm + + meanAngularMotion * integrationConstant4 * cosineTerm; + finalState( 4 ) = - 1.5 * meanAngularMotion * integrationConstant1 + + 2.0 * meanAngularMotion * integrationConstant3 * cosineTerm + - 2.0 * meanAngularMotion * integrationConstant4 * sineTerm; + finalState( 5 ) = - meanAngularMotion * integrationConstant5 * sineTerm + + meanAngularMotion * integrationConstant6 * cosineTerm; + + // Return final state. + return finalState; +} + +} // namespace basic_astrodynamics +} // namespace tudat diff --git a/pool/shard008/C++/0096865_mojo_buffer_backing.cc b/pool/shard008/C++/0096865_mojo_buffer_backing.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c908787ff5ca002f88637f300605c6853e56e14 --- /dev/null +++ b/pool/shard008/C++/0096865_mojo_buffer_backing.cc @@ -0,0 +1,36 @@ +// 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 "mojo/services/gles2/mojo_buffer_backing.h" + +#include "base/logging.h" + +namespace mojo { +namespace gles2 { + +MojoBufferBacking::MojoBufferBacking(mojo::ScopedSharedBufferHandle handle, + void* memory, + size_t size) + : handle_(handle.Pass()), memory_(memory), size_(size) {} + +MojoBufferBacking::~MojoBufferBacking() { mojo::UnmapBuffer(memory_); } + +// static +scoped_ptr MojoBufferBacking::Create( + mojo::ScopedSharedBufferHandle handle, + size_t size) { + void* memory = NULL; + MojoResult result = mojo::MapBuffer( + handle.get(), 0, size, &memory, MOJO_MAP_BUFFER_FLAG_NONE); + if (result != MOJO_RESULT_OK) + return scoped_ptr(); + DCHECK(memory); + return scoped_ptr( + new MojoBufferBacking(handle.Pass(), memory, size)); +} +void* MojoBufferBacking::GetMemory() const { return memory_; } +size_t MojoBufferBacking::GetSize() const { return size_; } + +} // namespace gles2 +} // namespace mojo diff --git a/pool/shard008/C++/0096867_splashscreen.cpp b/pool/shard008/C++/0096867_splashscreen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13e07875933f24b04913bdf6d4cfe5eb7a1bd64e --- /dev/null +++ b/pool/shard008/C++/0096867_splashscreen.cpp @@ -0,0 +1,52 @@ +#include "splashscreen.h" +#include "clientversion.h" +#include "util.h" + +#include +#undef loop /* ugh, remove this when the #define loop is gone from util.h */ +#include + +SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : + QSplashScreen(pixmap, f) +{ + // set reference point, paddings + int paddingLeftCol2 = 230; + int paddingTopCol2 = 376; + int line1 = 0; + int line2 = 13; + int line3 = 26; + + float fontFactor = 1.0; + + // define text to place + QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down + QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); + QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); + QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Wabcoin developers")); + + QString font = "Arial"; + + // load the bitmap for writing some text over it + QPixmap newPixmap; + if(GetBoolArg("-testnet")) { + newPixmap = QPixmap(":/images/splash_testnet"); + } + else { + newPixmap = QPixmap(":/images/splash"); + } + + QPainter pixPaint(&newPixmap); + pixPaint.setPen(QColor(70,70,70)); + + pixPaint.setFont(QFont(font, 9*fontFactor)); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); + + // draw copyright stuff + pixPaint.setFont(QFont(font, 9*fontFactor)); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); + pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); + + pixPaint.end(); + + this->setPixmap(newPixmap); +} diff --git a/pool/shard008/C++/0096868_proc-service.cc b/pool/shard008/C++/0096868_proc-service.cc new file mode 100644 index 0000000000000000000000000000000000000000..803c704e3f34b68f2c1fff185d9cea0d6a645fac --- /dev/null +++ b/pool/shard008/C++/0096868_proc-service.cc @@ -0,0 +1,165 @@ +/* libthread_db helper functions for the remote server for GDB. + Copyright (C) 2002-2020 Free Software Foundation, Inc. + + Contributed by MontaVista Software. + + This file is part of GDB. + + 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 "server.h" + +/* This file is currently tied to GNU/Linux. It should scale well to + another libthread_db implementation, with the appropriate gdbserver + hooks, but for now this means we can use GNU/Linux's target data. */ + +#include "linux-low.h" + +#include "gdb_proc_service.h" + +typedef struct ps_prochandle *gdb_ps_prochandle_t; +typedef void *gdb_ps_read_buf_t; +typedef const void *gdb_ps_write_buf_t; +typedef size_t gdb_ps_size_t; + +#ifdef HAVE_LINUX_REGSETS +#define HAVE_REGSETS +#endif + +#ifdef HAVE_REGSETS +static struct regset_info * +gregset_info (void) +{ + int i = 0; + const regs_info *regs_info = the_linux_target->get_regs_info (); + struct regsets_info *regsets_info = regs_info->regsets_info; + + while (regsets_info->regsets[i].size != -1) + { + if (regsets_info->regsets[i].type == GENERAL_REGS) + break; + i++; + } + + return ®sets_info->regsets[i]; +} +#endif + +/* Search for the symbol named NAME within the object named OBJ within + the target process PH. If the symbol is found the address of the + symbol is stored in SYM_ADDR. */ + +ps_err_e +ps_pglobal_lookup (gdb_ps_prochandle_t ph, const char *obj, + const char *name, psaddr_t *sym_addr) +{ + CORE_ADDR addr; + + if (thread_db_look_up_one_symbol (name, &addr) == 0) + return PS_NOSYM; + + *sym_addr = (psaddr_t) (unsigned long) addr; + return PS_OK; +} + +/* Read SIZE bytes from the target process PH at address ADDR and copy + them into BUF. */ + +ps_err_e +ps_pdread (gdb_ps_prochandle_t ph, psaddr_t addr, + gdb_ps_read_buf_t buf, gdb_ps_size_t size) +{ + if (read_inferior_memory ((uintptr_t) addr, (gdb_byte *) buf, size) != 0) + return PS_ERR; + return PS_OK; +} + +/* Write SIZE bytes from BUF into the target process PH at address ADDR. */ + +ps_err_e +ps_pdwrite (gdb_ps_prochandle_t ph, psaddr_t addr, + gdb_ps_write_buf_t buf, gdb_ps_size_t size) +{ + if (target_write_memory ((uintptr_t) addr, (const gdb_byte *) buf, size) + != 0) + return PS_ERR; + return PS_OK; +} + +/* Get the general registers of LWP LWPID within the target process PH + and store them in GREGSET. */ + +ps_err_e +ps_lgetregs (gdb_ps_prochandle_t ph, lwpid_t lwpid, prgregset_t gregset) +{ +#ifdef HAVE_REGSETS + struct lwp_info *lwp; + struct thread_info *reg_thread, *saved_thread; + struct regcache *regcache; + + lwp = find_lwp_pid (ptid_t (lwpid)); + if (lwp == NULL) + return PS_ERR; + + reg_thread = get_lwp_thread (lwp); + saved_thread = current_thread; + current_thread = reg_thread; + regcache = get_thread_regcache (current_thread, 1); + gregset_info ()->fill_function (regcache, gregset); + + current_thread = saved_thread; + return PS_OK; +#else + return PS_ERR; +#endif +} + +/* Set the general registers of LWP LWPID within the target process PH + from GREGSET. */ + +ps_err_e +ps_lsetregs (gdb_ps_prochandle_t ph, lwpid_t lwpid, const prgregset_t gregset) +{ + /* Unneeded. */ + return PS_ERR; +} + +/* Get the floating-point registers of LWP LWPID within the target + process PH and store them in FPREGSET. */ + +ps_err_e +ps_lgetfpregs (gdb_ps_prochandle_t ph, lwpid_t lwpid, prfpregset_t *fpregset) +{ + /* Unneeded. */ + return PS_ERR; +} + +/* Set the floating-point registers of LWP LWPID within the target + process PH from FPREGSET. */ + +ps_err_e +ps_lsetfpregs (gdb_ps_prochandle_t ph, lwpid_t lwpid, const prfpregset_t *fpregset) +{ + /* Unneeded. */ + return PS_ERR; +} + +/* Return overall process id of the target PH. Special for GNU/Linux + -- not used on Solaris. */ + +pid_t +ps_getpid (gdb_ps_prochandle_t ph) +{ + return pid_of (current_thread); +} diff --git a/pool/shard008/C++/0096872_C.cpp b/pool/shard008/C++/0096872_C.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4989f16b802f703c2267a343e910d284f4909d51 --- /dev/null +++ b/pool/shard008/C++/0096872_C.cpp @@ -0,0 +1,110 @@ +//#pragma comment(linker, "/STACK:1024000000,1024000000") +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define Msn(x,y) (memset((x),0,sizeof((x[0]))*(y+1))) +#define msn(x) (memset((x),0,sizeof((x)))) +#define msx(x) (memset((x),0x7f,sizeof(x))) +#define fuck(x) cerr << #x << " <- " << x << endl +#define acer cout<<"sb"<=0&&now.x=0&&now.yq; + queueQ; + q.push(x); + while(!q.empty()) + { + node now=q.front();q.pop(); + node nxt; + Q.push(now); + for(int d=0;d<4;d++) + { + nxt.x=now.x+dx[d]; + nxt.y=now.y+dy[d]; + if(ok(nxt)) + { + if(np[nxt.x][nxt.y]==-1)np[nxt.x][nxt.y]=0; + q.push(nxt); + } + } + } + while(!Q.empty()) + { + node now=Q.front();q.pop(); + node nxt; + for(int d=0;d<4;d++) + { + nxt.x=now.x+dx[d]; + nxt.y=now.y+dy[d]; + if(ok(nxt)) + { + if(np[nxt.x][nxt.y]==-1)np[nxt.x][nxt.y]=0; + q.push(nxt); + } + } + } +} +int main() +{ + scanf("%d%d",&n,&m); + for(int i=0;i +#include +#include + +#ifdef _UNICODE +#include +#endif + +static void +convert_string(char *dest, size_t size, const TCHAR *src) +{ +#ifdef _UNICODE + size_t length = _tcslen(src); + if (length >= size) + length = size - 1; + + int length2 = ::WideCharToMultiByte(CP_ACP, 0, src, length, dest, size, + nullptr, nullptr); + if (length2 < 0) + length2 = 0; + dest[length2] = '\0'; +#else + strncpy(dest, src, size - 1); + dest[size - 1] = '\0'; +#endif +} + +static bool +cai302DeclAddWaypoint(Port &port, int DeclIndex, const Waypoint &way_point, + OperationEnvironment &env) +{ + char Name[13]; + convert_string(Name, sizeof(Name), way_point.name.c_str()); + + return CAI302::DeclareTP(port, DeclIndex, way_point.location, + (int)way_point.elevation, + Name, env); +} + +static bool +DeclareInner(Port &port, const Declaration &declaration, + gcc_unused OperationEnvironment &env) +{ + using CAI302::UploadShort; + unsigned size = declaration.Size(); + + env.SetProgressRange(6 + size); + env.SetProgressPosition(0); + + CAI302::PilotMeta pilot_meta; + if (!CAI302::UploadPilotMeta(port, pilot_meta, env)) + return false; + + env.SetProgressPosition(1); + + CAI302::Pilot pilot; + if (!CAI302::UploadPilot(port, 0, pilot, env)) + return false; + + env.SetProgressPosition(2); + + CAI302::PolarMeta polar_meta; + if (!CAI302::UploadPolarMeta(port, polar_meta, env)) + return false; + + env.SetProgressPosition(3); + + CAI302::Polar polar; + if (!CAI302::UploadPolar(port, polar, env)) + return false; + + env.SetProgressPosition(4); + + if (!CAI302::DownloadMode(port, env)) + return false; + + convert_string(pilot.name, sizeof(pilot.name), declaration.pilot_name); + if (!CAI302::DownloadPilot(port, pilot, 0, env)) + return false; + + env.SetProgressPosition(5); + + convert_string(polar.glider_type, sizeof(polar.glider_type), + declaration.aircraft_type); + convert_string(polar.glider_id, sizeof(polar.glider_id), + declaration.aircraft_registration); + if (!CAI302::DownloadPolar(port, polar, env)) + return false; + + env.SetProgressPosition(6); + + for (unsigned i = 0; i < size; ++i) { + if (!cai302DeclAddWaypoint(port, i, declaration.GetWaypoint(i), env)) + return false; + + env.SetProgressPosition(7 + i); + } + + return CAI302::DeclareSave(port, env); +} + +bool +CAI302Device::Declare(const Declaration &declaration, + gcc_unused const Waypoint *home, + OperationEnvironment &env) +{ + if (!UploadMode(env)) + return false; + + if (!DeclareInner(port, declaration, env)) { + mode = Mode::UNKNOWN; + return false; + } + + return true; +} diff --git a/pool/shard008/C++/0096875_CollapseSelection.cpp b/pool/shard008/C++/0096875_CollapseSelection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40f93755c04d7635b69682c70ebb2f274b933221 --- /dev/null +++ b/pool/shard008/C++/0096875_CollapseSelection.cpp @@ -0,0 +1,80 @@ +/** + * 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 "query_optimizer/rules/CollapseSelection.hpp" + +#include + +#include "query_optimizer/expressions/Expression.hpp" +#include "query_optimizer/expressions/LogicalAnd.hpp" +#include "query_optimizer/expressions/NamedExpression.hpp" +#include "query_optimizer/expressions/PatternMatcher.hpp" +#include "query_optimizer/expressions/Predicate.hpp" +#include "query_optimizer/physical/PatternMatcher.hpp" +#include "query_optimizer/physical/Physical.hpp" +#include "query_optimizer/physical/Selection.hpp" +#include "query_optimizer/rules/RuleHelper.hpp" + +namespace quickstep { +namespace optimizer { + +namespace E = ::quickstep::optimizer::expressions; +namespace P = ::quickstep::optimizer::physical; + +P::PhysicalPtr CollapseSelection::applyToNode(const P::PhysicalPtr &input) { + P::SelectionPtr selection; + P::SelectionPtr child_selection; + + if (P::SomeSelection::MatchesWithConditionalCast(input, &selection) && + P::SomeSelection::MatchesWithConditionalCast(selection->input(), &child_selection)) { + E::PredicatePtr filter_predicate = selection->filter_predicate(); + + std::vector non_project_expressions; + if (filter_predicate) { + non_project_expressions.push_back(filter_predicate); + } + + std::vector project_expressions = + selection->project_expressions(); + PullUpProjectExpressions(child_selection->project_expressions(), + { &non_project_expressions }, { &project_expressions }); + + const E::PredicatePtr &child_filter_predicate = child_selection->filter_predicate(); + if (filter_predicate) { + CHECK(E::SomePredicate::MatchesWithConditionalCast(non_project_expressions[0], + &filter_predicate)) + << non_project_expressions[0]->toString(); + if (child_filter_predicate) { + filter_predicate = E::LogicalAnd::Create({ filter_predicate, child_filter_predicate }); + } + } else { + filter_predicate = child_filter_predicate; + } + + return P::Selection::Create(child_selection->input(), + project_expressions, + filter_predicate, + selection->cloneOutputPartitionSchemeHeader()); + } + + return input; +} + +} // namespace optimizer +} // namespace quickstep diff --git a/pool/shard008/C++/0096877_editaddressdialog.cpp b/pool/shard008/C++/0096877_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b1784c8b0373350cd32b951693f3019e5bc0649 --- /dev/null +++ b/pool/shard008/C++/0096877_editaddressdialog.cpp @@ -0,0 +1,137 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" + +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid CheckCoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard008/C++/0096878_nodegcplugin.cpp b/pool/shard008/C++/0096878_nodegcplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e99de63dbe45477de73ef9f4bf52b8acb37f3948 --- /dev/null +++ b/pool/shard008/C++/0096878_nodegcplugin.cpp @@ -0,0 +1,219 @@ +/******************************************************************************* + * Copyright 2014,2015 IBM Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +#include "ibmras/monitoring/AgentExtensions.h" +#include "Typesdef.h" +#include "v8.h" +#include "nan.h" +//#include "node_version.h" +#include +#include +#include +#if defined(_WINDOWS) +#include +#else +#include +#endif + +#define DEFAULT_CAPACITY 10240 + +#if defined(_WINDOWS) +#define NODEGCPLUGIN_DECL __declspec(dllexport) /* required for DLLs to export the plugin functions */ +#else +#define NODEGCPLUGIN_DECL +#endif + +namespace plugin { + agentCoreFunctions api; + uint32 provid = 0; + bool timingOK; + +#ifdef _WINDOWS + LARGE_INTEGER gcSteadyStart, gcSteadyEnd; +#elif defined(_LINUX) || defined(_AIX) + struct timespec gcSteadyStart, gcSteadyEnd; +#elif defined(__MACH__) || defined(__APPLE__) + struct timeval gcSteadyStart, gcSteadyEnd; +#endif +} + +using namespace v8; + +static char* NewCString(const std::string& s) { + char *result = new char[s.length() + 1]; + std::strcpy(result, s.c_str()); + return result; +} + +/* + * OSX + */ +#if defined(__MACH__) || defined(__APPLE__) +static bool GetSteadyTime(struct timeval* tv) { + //int rc = clock_gettime(CLOCK_MONOTONIC, tv); + int rc = gettimeofday(tv, 0); + return rc == 0; +} +static uint64 CalculateDuration(struct timeval start, struct timeval finish) { + return static_cast((finish.tv_sec - start.tv_sec) * 1000 + (finish.tv_usec - start.tv_usec) / 1000); +} +static unsigned long long GetRealTime() { + struct timeval tv; + gettimeofday(&tv, NULL); + return (unsigned long long)(tv.tv_sec) * 1000 + + (unsigned long long)(tv.tv_usec) / 1000; +} +#endif + +/* + * Linux + */ +#if defined(_LINUX) || defined(_AIX) +static bool GetSteadyTime(struct timespec* tv) { + int rc = clock_gettime(CLOCK_MONOTONIC, tv); + return rc == 0; +} +static uint64 CalculateDuration(struct timespec start, struct timespec finish) { + return static_cast((finish.tv_sec - start.tv_sec) * 1000 + (finish.tv_nsec - start.tv_nsec) / 1000000); +} +static unsigned long long GetRealTime() { + struct timeval tv; + gettimeofday(&tv, NULL); + return (unsigned long long)(tv.tv_sec) * 1000 + + (unsigned long long)(tv.tv_usec) / 1000; +} +#endif + +/* + * Windows + */ +#ifdef _WINDOWS +static LARGE_INTEGER freq; +static bool freqInitialized = FALSE; +static bool GetSteadyTime(LARGE_INTEGER* pcount) { + if (!freqInitialized) { + if (QueryPerformanceFrequency(&freq) == 0) { + return FALSE; + } + freqInitialized = TRUE; + } + BOOL rc = QueryPerformanceCounter(pcount); + return rc != 0; +} +static uint64 CalculateDuration(LARGE_INTEGER start, LARGE_INTEGER finish) { + if (!freqInitialized) return 0L; + LARGE_INTEGER elapsedMilliseconds; + elapsedMilliseconds.QuadPart = finish.QuadPart - start.QuadPart; + elapsedMilliseconds.QuadPart *= 1000; + elapsedMilliseconds.QuadPart /= freq.QuadPart; + return static_cast(elapsedMilliseconds.QuadPart); +} +static unsigned long long GetRealTime() { + SYSTEMTIME st; + GetSystemTime(&st); + return std::time(NULL) * 1000 + st.wMilliseconds; +} +#endif + +void beforeGC(GCType type, GCCallbackFlags flags) { + plugin::timingOK = GetSteadyTime(&plugin::gcSteadyStart); +} + +void afterGC(GCType type, GCCallbackFlags flags) { + unsigned long long gcRealEnd; + + // GC pause time + if (plugin::timingOK) { + plugin::timingOK = GetSteadyTime(&plugin::gcSteadyEnd); + } + const uint64 gcDuration = plugin::timingOK ? CalculateDuration(plugin::gcSteadyStart, plugin::gcSteadyEnd) : 0; + + // Get "real" time + gcRealEnd = GetRealTime(); + + // GC type + const char *gcType = (type == kGCTypeMarkSweepCompact) ? "M" : "S"; + + // GC heap stats + HeapStatistics hs; + + Nan::GetHeapStatistics(&hs); + + std::stringstream contentss; + contentss << "NodeGCData"; + contentss << "," << gcRealEnd; + contentss << "," << gcType; + contentss << "," << static_cast(hs.total_heap_size()); + contentss << "," << static_cast(hs.used_heap_size()); + contentss << "," << gcDuration; + contentss << '\n'; + + std::string content = contentss.str(); + + // Send data + monitordata data; + data.persistent = false; + data.provID = plugin::provid; + data.sourceID = 0; + data.size = static_cast(content.length()); + data.data = content.c_str(); + plugin::api.agentPushData(&data); +} + +pushsource* createPushSource(uint32 srcid, const char* name) { + pushsource *src = new pushsource(); + src->header.name = name; + std::string desc("Description for "); + desc.append(name); + src->header.description = NewCString(desc); + src->header.sourceID = srcid; + src->next = NULL; + src->header.capacity = DEFAULT_CAPACITY; + return src; +} + +extern "C" { + NODEGCPLUGIN_DECL pushsource* ibmras_monitoring_registerPushSource(agentCoreFunctions api, uint32 provID) { + plugin::api = api; + plugin::api.logMessage(debug, "[gc_node] Registering push sources"); + + pushsource *head = createPushSource(0, "gc_node"); + plugin::provid = provID; + return head; + } + + NODEGCPLUGIN_DECL int ibmras_monitoring_plugin_init(const char* properties) { + return 0; + } + + NODEGCPLUGIN_DECL int ibmras_monitoring_plugin_start() { + plugin::api.logMessage(fine, "[gc_node] Starting"); + + V8::AddGCPrologueCallback(beforeGC); + V8::AddGCEpilogueCallback(afterGC); + return 0; + } + + NODEGCPLUGIN_DECL int ibmras_monitoring_plugin_stop() { + plugin::api.logMessage(fine, "[gc_node] Stopping"); + // TODO Unhook GC hooks... + return 0; + } + + NODEGCPLUGIN_DECL const char* ibmras_monitoring_getVersion() { + return "1.0"; + } +} diff --git a/pool/shard008/C++/0096881_dialog_window.cpp b/pool/shard008/C++/0096881_dialog_window.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ae021765d0011c09ae308b0fc184e0d24a8471f --- /dev/null +++ b/pool/shard008/C++/0096881_dialog_window.cpp @@ -0,0 +1,58 @@ +#include "dialog_window.h" +#include "../components/dialog_component.h" +#include "../core/component_manager.h" +#include "../core/entity_manager.h" +#include "../core/event_manager.h" +#include "../widgets/frame.h" +#include "../widgets/label.h" +#include "../widgets/listbox.h" + +void DialogWindow::setup() { + setTitle("Dialog"); + setHeight(15); + setWidth(40); + + setEscapeBehaviour(Window::EscapeBehaviour::CloseWindow); +} + +void DialogWindow::registerWidgets() { + getWidget("frmBase")->setMergeBorders()->setMargin(); + + createWidget