diff --git a/pool/shard007/C++/0095105_boss_lockmaw.cpp b/pool/shard007/C++/0095105_boss_lockmaw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28822e4a3673a90412ccf517884ce9bb213df7a9 --- /dev/null +++ b/pool/shard007/C++/0095105_boss_lockmaw.cpp @@ -0,0 +1,160 @@ +/* + * + * Copyright (C) 2011-2012 ArkCORE2 + * Copyright (C) 2010-2012 Project SkyFire + * + * + * 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"ScriptPCH.h" +#include"WorldPacket.h" +#include"lost_city_of_the_tolvir.h" +#include"ScriptMgr.h" +#include"ScriptedCreature.h" +#include"SpellScript.h" +#include"SpellAuraEffects.h" + +enum Spells +{ + SPELL_DUST_FLAIL = 81642, + SPELL_SCENT_OF_BLOOD = 81690, + H_SPELL_SCENT_OF_BLOOD = 89998, + SPELL_VENOMOUS_RAGE = 81706, + SPELL_VISCOUS_POISON = 81630, + H_SPELL_VISCOUS_POISON = 90004, +}; + +enum Events +{ + EVENT_DUST_FLAIL = 1, + EVENT_SCENT_OF_BLOOD = 2, + EVENT_VENOMOUS_RAGE = 3, + EVENT_VISCOUS_POISON = 4, +}; + +enum SummonIds +{ + NPC_FRENZIED_CROCOLISK = 43658, +}; + +const Position SummonLocations[4] = +{ + //Frenzied Crocolisks + {-11033.29f, -1674.57f, -0.56f, 1.09f}, + {-11029.84f, -1673.09f, -0.37f, 2.33f}, + {-11007.25f, -1666.37f, -0.23f, 2.46f}, + {-11006.83f, -1666.85f, -0.25f, 2.23f}, +}; + +class boss_lockmaw : public CreatureScript +{ + public: + boss_lockmaw() : CreatureScript("boss_lockmaw") {} + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_lockmawAI(creature); + } + struct boss_lockmawAI : public ScriptedAI + { + boss_lockmawAI(Creature* creature) : ScriptedAI(creature), Summons(me) + { + instance = creature->GetInstanceScript(); + } + + InstanceScript* instance; + EventMap events; + SummonList Summons; + bool check_in; + + void Reset () + { + events.Reset(); + Summons.DespawnAll(); + + if (instance && (instance->GetData(DATA_LOCKMAW_EVENT) != DONE && !check_in)) + instance->SetData(DATA_LOCKMAW_EVENT, NOT_STARTED); + + check_in = false; + } + + void JustDied(Unit* /*Kill*/) + { + Summons.DespawnAll(); + if (instance) + instance->SetData(DATA_LOCKMAW_EVENT, DONE); + } + + void EnterCombat(Unit* /*Ent*/) + { + if (instance) + instance->SetData(DATA_LOCKMAW_EVENT, IN_PROGRESS); + + DoZoneInCombat(); + } + + void UpdateAI(const uint32 uiDiff) + { + if (!UpdateVictim()) /* No target to kill */ + return; + + events.Update(uiDiff); + + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_DUST_FLAIL: + DoCast(me->getVictim(), SPELL_DUST_FLAIL); + events.ScheduleEvent(EVENT_DUST_FLAIL, urand(6000, 10000)); + return; + case EVENT_VISCOUS_POISON: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true)) + DoCast(me->getVictim(), SPELL_VISCOUS_POISON); + events.ScheduleEvent(EVENT_VISCOUS_POISON, 2000); + return; + case EVENT_SCENT_OF_BLOOD: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true)) + DoCast(me->getVictim(), SPELL_SCENT_OF_BLOOD); + for (uint8 i=0; i<4; i++) + { + Creature* Crocolisk = me->SummonCreature(NPC_FRENZIED_CROCOLISK, SummonLocations[i], TEMPSUMMON_CORPSE_DESPAWN); + Crocolisk->AddThreat(me->getVictim(), 0.0f); + DoZoneInCombat(Crocolisk); + } + events.ScheduleEvent(EVENT_SCENT_OF_BLOOD, 6000); + return; + case EVENT_VENOMOUS_RAGE: + if (me->GetHealthPct() < 30) + DoCast(me, SPELL_VENOMOUS_RAGE); + events.ScheduleEvent(EVENT_VENOMOUS_RAGE, 1000); + return; + default: + break; + } + } + + DoMeleeAttackIfReady(); + } + }; +}; + +void AddSC_boss_lockmaw() +{ + new boss_lockmaw(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0095108_awt_Container.cpp b/pool/shard007/C++/0095108_awt_Container.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65ded5910963de3f43a41cc195e6f28e20d9a4f3 --- /dev/null +++ b/pool/shard007/C++/0095108_awt_Container.cpp @@ -0,0 +1,58 @@ +/* + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +#include "awt_Container.h" +#include "awt.h" + +/************************************************************************ + * AwtContainer fields + */ + +jfieldID AwtContainer::layoutMgrID; +jmethodID AwtContainer::findComponentAtMID; + +/************************************************************************ + * AwtContainer native methods + */ + +extern "C" { + +JNIEXPORT void JNICALL +Java_java_awt_Container_initIDs(JNIEnv *env, jclass cls) { + TRY; + + AwtContainer::layoutMgrID = + env->GetFieldID(cls, "layoutMgr", "Ljava/awt/LayoutManager;"); + + AwtContainer::findComponentAtMID = + env->GetMethodID(cls, "findComponentAt", "(IIZ)Ljava/awt/Component;"); + + DASSERT(AwtContainer::layoutMgrID != NULL); + DASSERT(AwtContainer::findComponentAtMID); + + CATCH_BAD_ALLOC; +} + +} /* extern "C" */ diff --git a/pool/shard007/C++/0095114_rssdownloadrulelist.cpp b/pool/shard007/C++/0095114_rssdownloadrulelist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55d52b2d844d5f398239fa970a8df606ed6b4b68 --- /dev/null +++ b/pool/shard007/C++/0095114_rssdownloadrulelist.cpp @@ -0,0 +1,185 @@ +/* + * Bittorrent Client using Qt and libtorrent. + * Copyright (C) 2010 Christophe Dumez + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * Contact : chris@qbittorrent.org + */ + +#include +#include +#include + +#include "base/preferences.h" +#include "base/qinisettings.h" +#include "rssdownloadrulelist.h" + +using namespace Rss; + +DownloadRuleList::DownloadRuleList() +{ + loadRulesFromStorage(); +} + +DownloadRulePtr DownloadRuleList::findMatchingRule(const QString &feedUrl, const QString &articleTitle) const +{ + Q_ASSERT(Preferences::instance()->isRssDownloadingEnabled()); + QStringList ruleNames = m_feedRules.value(feedUrl); + foreach (const QString &rule_name, ruleNames) { + DownloadRulePtr rule = m_rules[rule_name]; + if (rule->isEnabled() && rule->matches(articleTitle)) return rule; + } + return DownloadRulePtr(); +} + +void DownloadRuleList::replace(DownloadRuleList *other) +{ + m_rules.clear(); + m_feedRules.clear(); + foreach (const QString &name, other->ruleNames()) { + saveRule(other->getRule(name)); + } +} + +void DownloadRuleList::saveRulesToStorage() +{ + QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss"); + qBTRSS.setValue("download_rules", toVariantHash()); +} + +void DownloadRuleList::loadRulesFromStorage() +{ + QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss"); + loadRulesFromVariantHash(qBTRSS.value("download_rules").toHash()); +} + +QVariantHash DownloadRuleList::toVariantHash() const +{ + QVariantHash ret; + foreach (const DownloadRulePtr &rule, m_rules.values()) { + ret.insert(rule->name(), rule->toVariantHash()); + } + return ret; +} + +void DownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h) +{ + QVariantHash::ConstIterator it = h.begin(); + QVariantHash::ConstIterator itend = h.end(); + for ( ; it != itend; ++it) { + DownloadRulePtr rule = DownloadRule::fromVariantHash(it.value().toHash()); + if (rule && !rule->name().isEmpty()) + saveRule(rule); + } +} + +void DownloadRuleList::saveRule(const DownloadRulePtr &rule) +{ + qDebug() << Q_FUNC_INFO << rule->name(); + Q_ASSERT(rule); + if (m_rules.contains(rule->name())) { + qDebug("This is an update, removing old rule first"); + removeRule(rule->name()); + } + m_rules.insert(rule->name(), rule); + // Update feedRules hashtable + foreach (const QString &feedUrl, rule->rssFeeds()) { + m_feedRules[feedUrl].append(rule->name()); + } + qDebug() << Q_FUNC_INFO << "EXIT"; +} + +void DownloadRuleList::removeRule(const QString &name) +{ + qDebug() << Q_FUNC_INFO << name; + if (!m_rules.contains(name)) return; + DownloadRulePtr rule = m_rules.take(name); + // Update feedRules hashtable + foreach (const QString &feedUrl, rule->rssFeeds()) { + m_feedRules[feedUrl].removeOne(rule->name()); + } +} + +void DownloadRuleList::renameRule(const QString &oldName, const QString &newName) +{ + if (!m_rules.contains(oldName)) return; + + DownloadRulePtr rule = m_rules.take(oldName); + rule->setName(newName); + m_rules.insert(newName, rule); + // Update feedRules hashtable + foreach (const QString &feedUrl, rule->rssFeeds()) { + m_feedRules[feedUrl].replace(m_feedRules[feedUrl].indexOf(oldName), newName); + } +} + +DownloadRulePtr DownloadRuleList::getRule(const QString &name) const +{ + return m_rules.value(name); +} + +QStringList DownloadRuleList::ruleNames() const +{ + return m_rules.keys(); +} + +bool DownloadRuleList::isEmpty() const +{ + return m_rules.isEmpty(); +} + +bool DownloadRuleList::serialize(const QString &path) +{ + QFile f(path); + if (f.open(QIODevice::WriteOnly)) { + QDataStream out(&f); + out.setVersion(QDataStream::Qt_4_5); + out << toVariantHash(); + f.close(); + return true; + } + + return false; +} + +bool DownloadRuleList::unserialize(const QString &path) +{ + QFile f(path); + if (f.open(QIODevice::ReadOnly)) { + QDataStream in(&f); + in.setVersion(QDataStream::Qt_4_5); + QVariantHash tmp; + in >> tmp; + f.close(); + if (tmp.isEmpty()) + return false; + qDebug("Processing was successful!"); + loadRulesFromVariantHash(tmp); + return true; + } else { + qDebug("Error: could not open file at %s", qPrintable(path)); + return false; + } +} diff --git a/pool/shard007/C++/0095115_main.cpp b/pool/shard007/C++/0095115_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b348e569e0b3f50b61877592a55a66f2818ff68f --- /dev/null +++ b/pool/shard007/C++/0095115_main.cpp @@ -0,0 +1,68 @@ +#include "almath.h" +#include "vector" + +#include + +using namespace almath::network; + + +void print_table(Table t); + +int main() +{ + + + std::vector x = { 'a', 'b', 'c', 'd' }; + + + + almath::network::Table test(x, x, -1); + + print_table(test); + + test.editElement('a', 'a', 1); + + int newRow[4] = {5, 6, 3, 4}; + int newCol[4] = {5, 2, 3, 1}; + + print_table(test); + + test.addColumnData('b', newRow); + test.addRowData('d', newCol); + + test.addRow('e'); + + int newCol1[5] = {1, 2, 3, 4, 5}; + + test.addColumnData('e', newCol1); + + + return 0; +} + +void print_table(Table t) +{ + const std::vector *rows = t.getRows(); + const std::vector *columns = t.getColumns(); + + for(int i = 0; i < columns->size(); i++) + { + std::cout << "\t" << (*columns)[i]; + } + + std::cout << std::endl; + for(int i = 0; i < columns->size(); i++) + { + std::cout << "\t" << "__"; + } + std::cout << std::endl; + + for (int i = 0; i < rows->size(); i++) + { + std::cout << (*rows)[i] << "|\t"; + for(int x = 0; x < columns->size(); x++) + std::cout << t[(*rows)[i]][x] << "\t"; + + std::cout << std::endl; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc b/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..8a803c4712058bfa89e25f400d99fc12c15ad6d8 --- /dev/null +++ b/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc @@ -0,0 +1,94 @@ +// 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 "content/browser/browser_plugin/browser_plugin_geolocation_permission_context.h" + +#include "base/bind.h" +#include "content/browser/browser_plugin/browser_plugin_guest.h" +#include "content/browser/web_contents/web_contents_impl.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_view_host.h" + +namespace content { + +BrowserPluginGeolocationPermissionContext:: + BrowserPluginGeolocationPermissionContext() { +} + +BrowserPluginGeolocationPermissionContext:: + ~BrowserPluginGeolocationPermissionContext() { +} + +void BrowserPluginGeolocationPermissionContext::RequestGeolocationPermission( + int render_process_id, + int render_view_id, + int bridge_id, + const GURL& requesting_frame, + base::Callback callback) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind( + &BrowserPluginGeolocationPermissionContext:: + RequestGeolocationPermission, + this, + render_process_id, + render_view_id, + bridge_id, + requesting_frame, + callback)); + return; + } + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + + // Note that callback.Run(true) allows geolocation access, callback.Run(false) + // denies geolocation access. + // We need to go to the renderer to ask embedder's js if we are allowed to + // have geolocation access. + RenderViewHost* rvh = RenderViewHost::FromID(render_process_id, + render_view_id); + if (rvh) { + DCHECK(rvh->GetProcess()->IsGuest()); + WebContentsImpl* guest_web_contents = + static_cast(rvh->GetDelegate()->GetAsWebContents()); + BrowserPluginGuest* guest = guest_web_contents->GetBrowserPluginGuest(); + guest->AskEmbedderForGeolocationPermission(bridge_id, + requesting_frame, + callback); + } +} + +void BrowserPluginGeolocationPermissionContext:: + CancelGeolocationPermissionRequest(int render_process_id, + int render_view_id, + int bridge_id, + const GURL& requesting_frame) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind( + &BrowserPluginGeolocationPermissionContext:: + CancelGeolocationPermissionRequest, + this, + render_process_id, + render_view_id, + bridge_id, + requesting_frame)); + return; + } + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + RenderViewHost* rvh = RenderViewHost::FromID(render_process_id, + render_view_id); + if (rvh) { + DCHECK(rvh->GetProcess()->IsGuest()); + WebContentsImpl* guest_web_contents = + static_cast(rvh->GetDelegate()->GetAsWebContents()); + BrowserPluginGuest* guest = guest_web_contents->GetBrowserPluginGuest(); + if (guest) + guest->CancelGeolocationRequest(bridge_id); + } +} + +} // namespace content diff --git a/pool/shard007/C++/0095119_csg_dump.cc b/pool/shard007/C++/0095119_csg_dump.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9dd2614f448d10d5819a8228d0bc185ef4c56f5 --- /dev/null +++ b/pool/shard007/C++/0095119_csg_dump.cc @@ -0,0 +1,99 @@ +/* + * Copyright 2009-2021 The VOTCA Development Team (http://www.votca.org) + * + * 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. + * + */ + +// Standard includes +#include + +// Local VOTCA includes +#include "votca/csg/csgapplication.h" + +using namespace std; +using namespace votca::csg; + +class CsgDumpApp : public CsgApplication { + string ProgramName() override { return "csg_dump"; } + void HelpText(ostream &out) override { + out << "Print atoms that are read from topology file to help" + " debugging atom naming."; + } + void Initialize() override { + CsgApplication::Initialize(); + AddProgramOptions("Specific options")( + "excl", " display exclusion list instead of molecule list"); + } + + bool EvaluateTopology(Topology *top, Topology *top_ref) override; + + bool DoMapping() override { return true; } + bool DoMappingDefault(void) override { return false; } +}; + +int main(int argc, char **argv) { + CsgDumpApp app; + + return app.Exec(argc, argv); +} + +bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *) { + if (!OptionsMap().count("excl")) { + cout << "Boundary Condition: "; + if (top->getBoxType() == BoundaryCondition::typeAuto) { + cout << "auto"; + } else if (top->getBoxType() == BoundaryCondition::typeTriclinic) { + cout << "triclinic"; + } else if (top->getBoxType() == BoundaryCondition::typeOrthorhombic) { + cout << "orthorhombic"; + } else if (top->getBoxType() == BoundaryCondition::typeOpen) { + cout << "open"; + } + cout << endl; + if (top->getBoxType() != BoundaryCondition::typeOpen) { + cout << " Box matix:"; + Eigen::Matrix3d box = top->getBox(); + for (votca::Index i = 0; i < 3; i++) { + for (votca::Index j = 0; j < 3; j++) { + cout << " " << box(i, j); + } + cout << endl << " "; + } + } + + cout << "\nList of residues:\n"; + for (votca::Index i = 0; i < top->ResidueCount(); i++) { + cout << i << " name: " << top->getResidue(i).getName() + << " id: " << top->getResidue(i).getId() << endl; + } + + cout << "\nList of molecules:\n"; + for (const auto &mol : top->Molecules()) { + cout << "molecule: " << mol.getId() + 1 << " " << mol.getName() + << " beads: " << mol.BeadCount() << endl; + for (votca::Index i = 0; i < mol.BeadCount(); ++i) { + votca::Index resnr = mol.getBead(i)->getResnr(); + cout << mol.getBeadId(i) << " Name " << mol.getBeadName(i) << " Type " + << mol.getBead(i)->getType() << " Mass " + << mol.getBead(i)->getMass() << " Resnr " << resnr << " Resname " + << top->getResidue(resnr).getName() << " Charge " + << mol.getBead(i)->getQ() << endl; + } + } + } else { + cout << "\nList of exclusions:\n" << top->getExclusions(); + } + + return true; +} diff --git a/pool/shard007/C++/0095120_pair.cpp b/pool/shard007/C++/0095120_pair.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb60c8582fb4486b16d1dd7fcf7e7d622c7be709 --- /dev/null +++ b/pool/shard007/C++/0095120_pair.cpp @@ -0,0 +1,141 @@ +/* + Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file + + This file is part of libzmq, the ZeroMQ core engine in C++. + + libzmq is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + As a special exception, the Contributors give you permission to link + this library with independent modules to produce an executable, + regardless of the license terms of these independent modules, and to + copy and distribute the resulting executable under terms of your choice, + provided that you also meet, for each linked independent module, the + terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. + If you modify this library, you must extend this exception to your + version of the library. + + libzmq 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 "precompiled.hpp" +#include "macros.hpp" +#include "pair.hpp" +#include "err.hpp" +#include "pipe.hpp" +#include "msg.hpp" + +zmq::pair_t::pair_t (class ctx_t *parent_, uint32_t tid_, int sid_) : + socket_base_t (parent_, tid_, sid_), + pipe (NULL), + last_in (NULL) +{ + options.type = ZMQ_PAIR; +} + +zmq::pair_t::~pair_t () +{ + zmq_assert (!pipe); +} + +void zmq::pair_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) +{ + LIBZMQ_UNUSED (subscribe_to_all_); + + zmq_assert (pipe_ != NULL); + + // ZMQ_PAIR socket can only be connected to a single peer. + // The socket rejects any further connection requests. + if (pipe == NULL) + pipe = pipe_; + else + pipe_->terminate (false); +} + +void zmq::pair_t::xpipe_terminated (pipe_t *pipe_) +{ + if (pipe_ == pipe) { + if (last_in == pipe) { + saved_credential.set_deep_copy (last_in->get_credential ()); + last_in = NULL; + } + pipe = NULL; + } +} + +void zmq::pair_t::xread_activated (pipe_t *) +{ + // There's just one pipe. No lists of active and inactive pipes. + // There's nothing to do here. +} + +void zmq::pair_t::xwrite_activated (pipe_t *) +{ + // There's just one pipe. No lists of active and inactive pipes. + // There's nothing to do here. +} + +int zmq::pair_t::xsend (msg_t *msg_) +{ + if (!pipe || !pipe->write (msg_)) { + errno = EAGAIN; + return -1; + } + + if (!(msg_->flags () & msg_t::more)) + pipe->flush (); + + // Detach the original message from the data buffer. + int rc = msg_->init (); + errno_assert (rc == 0); + + return 0; +} + +int zmq::pair_t::xrecv (msg_t *msg_) +{ + // Deallocate old content of the message. + int rc = msg_->close (); + errno_assert (rc == 0); + + if (!pipe || !pipe->read (msg_)) { + // Initialise the output parameter to be a 0-byte message. + rc = msg_->init (); + errno_assert (rc == 0); + + errno = EAGAIN; + return -1; + } + last_in = pipe; + return 0; +} + +bool zmq::pair_t::xhas_in () +{ + if (!pipe) + return false; + + return pipe->check_read (); +} + +bool zmq::pair_t::xhas_out () +{ + if (!pipe) + return false; + + return pipe->check_write (); +} + +const zmq::blob_t &zmq::pair_t::get_credential () const +{ + return last_in ? last_in->get_credential () : saved_credential; +} diff --git a/pool/shard007/C++/0095121_put.cc b/pool/shard007/C++/0095121_put.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba86706efb62a32d4bcad9ca4c8b83ca6e97d7db --- /dev/null +++ b/pool/shard007/C++/0095121_put.cc @@ -0,0 +1,91 @@ +// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. +// This source code is licensed under both the GPLv2 (found in the +// COPYING file in the root directory) and Apache 2.0 License +// (found in the LICENSE.Apache file in the root directory). + +#include +#include "rocksdb/slice.h" +#include "rocksdb/merge_operator.h" +#include "utilities/merge_operators.h" + +namespace { // anonymous namespace + +using ROCKSDB_NAMESPACE::Logger; +using ROCKSDB_NAMESPACE::MergeOperator; +using ROCKSDB_NAMESPACE::Slice; + +// A merge operator that mimics Put semantics +// Since this merge-operator will not be used in production, +// it is implemented as a non-associative merge operator to illustrate the +// new interface and for testing purposes. (That is, we inherit from +// the MergeOperator class rather than the AssociativeMergeOperator +// which would be simpler in this case). +// +// From the client-perspective, semantics are the same. +class PutOperator : public MergeOperator { + public: + bool FullMerge(const Slice& /*key*/, const Slice* /*existing_value*/, + const std::deque& operand_sequence, + std::string* new_value, Logger* /*logger*/) const override { + // Put basically only looks at the current/latest value + assert(!operand_sequence.empty()); + assert(new_value != nullptr); + new_value->assign(operand_sequence.back()); + return true; + } + + bool PartialMerge(const Slice& /*key*/, const Slice& /*left_operand*/, + const Slice& right_operand, std::string* new_value, + Logger* /*logger*/) const override { + new_value->assign(right_operand.data(), right_operand.size()); + return true; + } + + using MergeOperator::PartialMergeMulti; + bool PartialMergeMulti(const Slice& /*key*/, + const std::deque& operand_list, + std::string* new_value, + Logger* /*logger*/) const override { + new_value->assign(operand_list.back().data(), operand_list.back().size()); + return true; + } + + static const char* kClassName() { return "PutOperator"; } + static const char* kNickName() { return "put_v1"; } + const char* Name() const override { return kClassName(); } + const char* NickName() const override { return kNickName(); } +}; + +class PutOperatorV2 : public PutOperator { + bool FullMerge(const Slice& /*key*/, const Slice* /*existing_value*/, + const std::deque& /*operand_sequence*/, + std::string* /*new_value*/, + Logger* /*logger*/) const override { + assert(false); + return false; + } + + bool FullMergeV2(const MergeOperationInput& merge_in, + MergeOperationOutput* merge_out) const override { + // Put basically only looks at the current/latest value + assert(!merge_in.operand_list.empty()); + merge_out->existing_operand = merge_in.operand_list.back(); + return true; + } + + static const char* kNickName() { return "put"; } + const char* NickName() const override { return kNickName(); } +}; + +} // end of anonymous namespace + +namespace ROCKSDB_NAMESPACE { + +std::shared_ptr MergeOperators::CreateDeprecatedPutOperator() { + return std::make_shared(); +} + +std::shared_ptr MergeOperators::CreatePutOperator() { + return std::make_shared(); +} +} // namespace ROCKSDB_NAMESPACE diff --git a/pool/shard007/C++/0095125_pmt_tests.cpp b/pool/shard007/C++/0095125_pmt_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1d216d09445b64d56bf6d6991e45daa5d678b17 --- /dev/null +++ b/pool/shard007/C++/0095125_pmt_tests.cpp @@ -0,0 +1,126 @@ +// Copyright (c) 2012-2016 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 "consensus/merkle.h" +#include "merkleblock.h" +#include "serialize.h" +#include "streams.h" +#include "uint256.h" +#include "arith_uint256.h" +#include "version.h" +#include "test/test_bitcoin.h" + +#include + +#include + +class CPartialMerkleTreeTester : public CPartialMerkleTree +{ +public: + // flip one bit in one of the hashes - this should break the authentication + void Damage() { + unsigned int n = InsecureRandRange(vHash.size()); + int bit = InsecureRandBits(8); + *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7); + } +}; + +BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup) + +BOOST_AUTO_TEST_CASE(pmt_test1) +{ + SeedInsecureRand(false); + static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095}; + + for (int i = 0; i < 12; i++) { + unsigned int nTx = nTxCounts[i]; + + // build a block with some dummy transactions + CBlock block; + for (unsigned int j=0; j vTxid(nTx, uint256()); + for (unsigned int j=0; jGetHash(); + int nHeight = 1, nTx_ = nTx; + while (nTx_ > 1) { + nTx_ = (nTx_+1)/2; + nHeight++; + } + + // check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128 + for (int att = 1; att < 15; att++) { + // build random subset of txid's + std::vector vMatch(nTx, false); + std::vector vMatchTxid1; + for (unsigned int j=0; j(nTx, 1 + vMatchTxid1.size()*nHeight); + BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8); + + // deserialize into a tester copy + CPartialMerkleTreeTester pmt2; + ss >> pmt2; + + // extract merkle root and matched txids from copy + std::vector vMatchTxid2; + std::vector vIndex; + uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex); + + // check that it has the same merkle root as the original, and a valid one + BOOST_CHECK(merkleRoot1 == merkleRoot2); + BOOST_CHECK(!merkleRoot2.IsNull()); + + // check that it contains the matched transactions (in the same order!) + BOOST_CHECK(vMatchTxid1 == vMatchTxid2); + + // check that random bit flips break the authentication + for (int j=0; j<4; j++) { + CPartialMerkleTreeTester pmt3(pmt2); + pmt3.Damage(); + std::vector vMatchTxid3; + uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex); + BOOST_CHECK(merkleRoot3 != merkleRoot1); + } + } + } +} + +BOOST_AUTO_TEST_CASE(pmt_malleability) +{ + std::vector vTxid = { + ArithToUint256(1), ArithToUint256(2), + ArithToUint256(3), ArithToUint256(4), + ArithToUint256(5), ArithToUint256(6), + ArithToUint256(7), ArithToUint256(8), + ArithToUint256(9), ArithToUint256(10), + ArithToUint256(9), ArithToUint256(10), + }; + std::vector vMatch = {false, false, false, false, false, false, false, false, false, true, true, false}; + + CPartialMerkleTree tree(vTxid, vMatch); + std::vector vIndex; + BOOST_CHECK(tree.ExtractMatches(vTxid, vIndex).IsNull()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard007/C++/0095127_simpledeformation.cpp b/pool/shard007/C++/0095127_simpledeformation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89a20788d60a15f6354644b54c9317933220f0cc --- /dev/null +++ b/pool/shard007/C++/0095127_simpledeformation.cpp @@ -0,0 +1,94 @@ +// Aqsis +// Copyright (C) 2001, Paul C. Gregory and the other authors and contributors +// 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 software's owners 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. +// +// (This is the New BSD license) + +#include "renderer.h" +#include "surfaces.h" + +static GeometryPtr createPatch(const float P[12], const float Cs[3], + const Mat4& trans = Mat4()) +{ + PrimvarStorageBuilder builder; + builder.add(Primvar::P, P, 12); + builder.add(PrimvarSpec(PrimvarSpec::Constant, PrimvarSpec::Color, 1, ustring("Cs")), + Cs, 3); + IclassStorage storReq(1,4,4,4,4); + GeometryPtr patch(new Patch(builder.build(storReq))); + patch->transform(trans); + return patch; +} + +void renderSimpleDeformationScene() +{ + Options opts; + opts.xRes = 1024; + opts.yRes = 1024; + opts.gridSize = 8; + opts.clipNear = 0.1; + opts.superSamp = Imath::V2i(4,4); + opts.pixelFilter = makeSincFilter(Vec2(3.0,3.0)); + opts.shutterMin = 0; + opts.shutterMax = 2; + + Attributes attrs; + attrs.shadingRate = 1; + attrs.smoothShading = true; + attrs.surfaceShader = createShader("default"); + + Mat4 camToScreen = perspectiveProjection(90, opts.clipNear, opts.clipFar); + + // Output variables. + VarList outVars; + outVars.push_back(Stdvar::Ci); + + Renderer renderer(opts, camToScreen, outVars); + + { + float Cs[3] = {1,1,1}; + GeometryKeys keys; + float P1[12] = {-0.4,-0.4,1, -0.4,-0.3,1, -0.3,-0.4,1, -0.3,-0.3,1}; + keys.push_back(GeometryKey(0, createPatch(P1,Cs))); + float P2[12] = {-0.1,-0.1,1, -0.1,0.1,1, 0.1,-0.1,1, 0.1,0.1,1}; + keys.push_back(GeometryKey(2, createPatch(P2,Cs))); + renderer.add(keys, attrs); + } + + { + float Cs[3] = {0.6,0.4,0.4}; + GeometryKeys keys; + float P1[12] = {1,0,2, 0,1.1,2, 0,-1.1,2, -1,0,2}; + keys.push_back(GeometryKey(0, createPatch(P1,Cs))); + float P2[12] = {1.5,0,2, 0,0.8,2, 0,-0.8,2, -1.5,0,2}; + keys.push_back(GeometryKey(2, createPatch(P2,Cs))); + renderer.add(keys, attrs); + } + + renderer.render(); +} + diff --git a/pool/shard007/C++/0095128_DemoColorImageByScore.cpp b/pool/shard007/C++/0095128_DemoColorImageByScore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef60244467c540579c158c5bbe96710a63dcb8fe --- /dev/null +++ b/pool/shard007/C++/0095128_DemoColorImageByScore.cpp @@ -0,0 +1,74 @@ +/*========================================================================= + * + * Copyright David Doria 2011 daviddoria@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +// Submodules +#include +#include + +// ITK +#include "itkImageFileReader.h" + +// Boost +#include + +int main(int argc, char *argv[]) +{ + if(argc != 3) + { + std::cerr << "Required arguments: image mask" << std::endl; + return EXIT_FAILURE; + } + std::string imageFilename = argv[1]; + std::string maskFilename = argv[2]; + std::cout << "Reading image: " << imageFilename << std::endl; + std::cout << "Reading mask: " << maskFilename << std::endl; + + typedef itk::VectorImage FloatVectorImageType; + typedef itk::ImageFileReader ImageReaderType; + ImageReaderType::Pointer imageReader = ImageReaderType::New(); + imageReader->SetFileName(imageFilename.c_str()); + imageReader->Update(); + + typedef itk::ImageFileReader MaskReaderType; + MaskReaderType::Pointer maskReader = MaskReaderType::New(); + maskReader->SetFileName(maskFilename.c_str()); + maskReader->Update(); + + std::shared_ptr patchCompare(new SelfPatchCompare); + patchCompare->SetNumberOfComponentsPerPixel(imageReader->GetOutput()->GetNumberOfComponentsPerPixel()); + //patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchAverageAbsoluteSourceDifference,patchCompare,_1)); + //patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchColorDifference,patchCompare,_1)); + patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchDepthDifference,patchCompare.get(),_1)); + //patchCompare->SetImage(imageReader->GetOutput()); + //patchCompare->SetMask(maskReader->GetOutput()); + + PatchBasedInpainting inpainting; + inpainting.SetMask(maskReader->GetOutput()); + inpainting.SetImage(imageReader->GetOutput()); + //inpainting.PatchSortFunction = &SortByDepthDifference; + //inpainting.SetPatchCompare(patchCompare); + inpainting.Initialize(); + inpainting.Iterate(); + + CandidatePairs candidatePairs = inpainting.GetPotentialCandidatePairs()[0]; + //patchCompare->SetPairs(&candidatePairs); + //patchCompare->ComputeAllSourceDifferences(); + WriteImageOfScores(candidatePairs, imageReader->GetOutput()->GetLargestPossibleRegion(), "ScoreImage_TargetPatch.mha"); + + return EXIT_SUCCESS; +} diff --git a/pool/shard007/C++/0095129_led.cpp b/pool/shard007/C++/0095129_led.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1e9551a29281bf5dc6c36db3e206d688f93dc94 --- /dev/null +++ b/pool/shard007/C++/0095129_led.cpp @@ -0,0 +1,62 @@ +/* + * led.cpp - Implementation of LED class which abstracts LED functionality with + * the naze32 + * + * Copyright (c) 2016 James Jackson + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "led.h" +#include "board.h" + +LED::LED(){} + +LED::LED(GPIO_TypeDef* port, uint16_t pin) : + gpio_(port, pin, GPIO_Mode_Out_PP) +{ + gpio_.write(HIGH); +} + +void LED::toggle() +{ + gpio_.toggle(); +} + +void LED::turn_on() +{ + gpio_.write(LOW); +} + +void LED::turn_off() +{ + gpio_.write(HIGH); +} + +void LED::blink(uint32_t ms_delay) +{ + static uint32_t last_time = 0; + uint32_t now = millis(); + + if(now - last_time > ms_delay) + { + toggle(); + last_time = now; + } +} diff --git a/pool/shard007/C++/0095136_websocket_server.cpp b/pool/shard007/C++/0095136_websocket_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26e847de6d77dfaee9c2fceb15b9f2002f6c6e3e --- /dev/null +++ b/pool/shard007/C++/0095136_websocket_server.cpp @@ -0,0 +1,172 @@ +#include "websocket_server.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +const QString kWebsocketCertPath = WEBSOCKET_CERT_PATH; + +// Names used for a websocket JSON object. +const QString kMessageType = "type"; +const QString kPayload = "data"; + +} // namespace + +WebsocketServer::WebsocketServer(quint16 port) + : m_websocket_server(new QWebSocketServer("PACC server", + QWebSocketServer::SecureMode)) +{ + QSslConfiguration sslConfiguration; + QFile cert_file(kWebsocketCertPath + "/localhost.crt"); + cert_file.open(QIODevice::ReadOnly); + QSslCertificate certificate(&cert_file, QSsl::Pem); + cert_file.close(); + + QFile key_file(kWebsocketCertPath + "/localhost.key"); + key_file.open(QIODevice::ReadOnly); + QSslKey ssl_key(&key_file, QSsl::Rsa, QSsl::Pem); + key_file.close(); + + if (certificate.isNull() || ssl_key.isNull()) { + qCritical() << QString("The websocket certificate could not be loaded. " + "Please verify that localhost.crt and " + "localhost.key exist in %s and are readable by " + "the pacc module.") + .arg(kWebsocketCertPath); + exit(1); + } + + sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone); + sslConfiguration.setLocalCertificate(certificate); + sslConfiguration.setPrivateKey(ssl_key); + sslConfiguration.setProtocol(QSsl::TlsV1SslV3); + m_websocket_server->setSslConfiguration(sslConfiguration); + + connect(m_websocket_server.data(), &QWebSocketServer::newConnection, + this, &WebsocketServer::onNewConnection); + connect(m_websocket_server.data(), &QWebSocketServer::sslErrors, + [](const QList &) { + qWarning() << "Ssl errors occurred"; + }); + connect(m_websocket_server.data(), &QWebSocketServer::acceptError, + [](QAbstractSocket::SocketError socketError) { + qWarning() << "SocketError: " << QString::number(socketError); + }); + connect(m_websocket_server.data(), &QWebSocketServer::serverError, + [](QWebSocketProtocol::CloseCode closeCode) { + qWarning() << "ServerError: " << QString::number(closeCode); + }); + connect(m_websocket_server.data(), &QWebSocketServer::peerVerifyError, + [](const QSslError &error) { + qWarning() << "PeerVerifyError: " << error.errorString(); + }); + + Q_ASSERT(m_websocket_server->listen(QHostAddress::Any, port) && + "Could not start the websocket server"); +} + +WebsocketServer::~WebsocketServer() { +} + +void WebsocketServer::onNewConnection() { + QWebSocket *socket = m_websocket_server->nextPendingConnection(); + + QMutexLocker l(&m_socket_mutex); + connect(socket, &QWebSocket::textMessageReceived, + this, &WebsocketServer::processTextMessage); + connect(socket, &QWebSocket::disconnected, + this, &WebsocketServer::socketDisconnected); + void (QWebSocket::*error)(QAbstractSocket::SocketError) = + &QWebSocket::error; + connect(socket, error, [](QAbstractSocket::SocketError error) { + qWarning() << "onError" << QString::number(error); + }); + + if (!m_socket.isNull()) { + qWarning() << "There is already a client connected!"; + } + m_socket.reset(socket); + + // Sends all the pending messages. + while (!m_pending_messages.isEmpty()) { + const QString &pending_message = m_pending_messages.takeFirst(); + m_socket->sendTextMessage(pending_message); + } + + emit clientConnected(); +} + +void WebsocketServer::sendMessage(const QString &type, + const QJsonValue &payload) { + // Assembles the message. + QJsonObject json_message; + json_message[kMessageType] = type; + json_message[kPayload] = payload; + + QJsonDocument document(json_message); + QString message = QString::fromUtf8(document.toJson()); + + // Sends the message if there is a socket connected or adds it to the + // pending queue. + QMutexLocker l(&m_socket_mutex); + if (m_socket) { + m_socket->sendTextMessage(message); + } else { + m_pending_messages.append(message); + } +} + +void WebsocketServer::processTextMessage(QString message) { + QWebSocket *socket = qobject_cast(sender()); + + // Checks if the socket matches. + if (socket != m_socket.data()) { + qWarning() << "Message from wrong socket. Ignoring."; + return; + } + + // Parses the message. + QJsonParseError parse_error; + QJsonDocument document = + QJsonDocument::fromJson(message.toUtf8(), &parse_error); + if (parse_error.error != QJsonParseError::NoError) { + qWarning() << "Failed to parse the websocket message: " + << parse_error.errorString(); + return; + } + if (!document.isObject()) { + qWarning() << "Invalid websocket message."; + return; + } + + QJsonObject msg_object = document.object(); + if (!msg_object.contains(kMessageType)) { + qWarning() << "Invalid websocket message."; + return; + } + + // Reads the message. + const QString &type = msg_object[kMessageType].toString(); + const QJsonValue &payload = msg_object[kPayload]; + + emit messageReceived(type, payload); +} + +void WebsocketServer::socketDisconnected() { + QWebSocket *socket = qobject_cast(sender()); + QMutexLocker l(&m_socket_mutex); + if (socket == m_socket.data()) { + m_socket.take(); + } + socket->deleteLater(); + + l.unlock(); + emit clientDisconnected(); +} diff --git a/pool/shard007/C++/0095139_test_thread_exit.cpp b/pool/shard007/C++/0095139_test_thread_exit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..577bcd05d036eba3dc8d2de28dbe7eb6cfa17829 --- /dev/null +++ b/pool/shard007/C++/0095139_test_thread_exit.cpp @@ -0,0 +1,63 @@ +// (C) Copyright 2009 Anthony Williams +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#include +#include +#include +#include +#include +#include +#include + +#define BOOST_TEST_MODULE Boost.Threads: thread exit test suite + +#include + +boost::thread::id exit_func_thread_id; + +void exit_func() +{ + exit_func_thread_id=boost::this_thread::get_id(); +} + +void tf1() +{ + boost::this_thread::at_thread_exit(exit_func); + BOOST_CHECK(exit_func_thread_id!=boost::this_thread::get_id()); +} + +BOOST_AUTO_TEST_CASE(test_thread_exit_func_runs_when_thread_exits) +{ + exit_func_thread_id=boost::thread::id(); + boost::thread t(&tf1); + boost::thread::id const t_id=t.get_id(); + t.join(); + BOOST_CHECK(exit_func_thread_id==t_id); +} + +struct fo +{ + void operator()() + { + exit_func_thread_id=boost::this_thread::get_id(); + } +}; + +void tf2() +{ + boost::this_thread::at_thread_exit(fo()); + BOOST_CHECK(exit_func_thread_id!=boost::this_thread::get_id()); +} + + +BOOST_AUTO_TEST_CASE(test_can_use_function_object_for_exit_func) +{ + exit_func_thread_id=boost::thread::id(); + boost::thread t(tf2); + boost::thread::id const t_id=t.get_id(); + t.join(); + BOOST_CHECK(exit_func_thread_id==t_id); +} diff --git a/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc b/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..7f0bb03232477d054dffed0d98ed7f27dda30835 --- /dev/null +++ b/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc @@ -0,0 +1,220 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.h" + +#include + +#include "base/notreached.h" +#include "third_party/webrtc/api/ice_transport_factory.h" + +namespace blink { + +IceTransportAdapterImpl::IceTransportAdapterImpl( + Delegate* delegate, + std::unique_ptr port_allocator, + std::unique_ptr async_resolver_factory) + : delegate_(delegate), + port_allocator_(std::move(port_allocator)), + async_resolver_factory_(std::move(async_resolver_factory)) { + // These settings are copied from PeerConnection: + // https://codesearch.chromium.org/chromium/src/third_party/webrtc/pc/peerconnection.cc?l=4708&rcl=820ebd0f661696043959b5105b2814e0edd8b694 + port_allocator_->set_step_delay(cricket::kMinimumStepDelay); + port_allocator_->set_flags(port_allocator_->flags() | + cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET | + cricket::PORTALLOCATOR_ENABLE_IPV6 | + cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + port_allocator_->Initialize(); + + webrtc::IceTransportInit ice_transport_init; + ice_transport_init.set_port_allocator(port_allocator_.get()); + ice_transport_init.set_async_resolver_factory(async_resolver_factory_.get()); + ice_transport_channel_ = + webrtc::CreateIceTransport(std::move(ice_transport_init)); + SetupIceTransportChannel(); + // We need to set the ICE role even before Start is called since the Port + // assumes that the role has been set before receiving incoming connectivity + // checks. These checks can race with the information signaled for Start. + ice_transport_channel()->SetIceRole(cricket::ICEROLE_CONTROLLING); + // The ICE tiebreaker is used to determine which side is controlling/ + // controlled when both sides start in the same role. The number is randomly + // generated so that each peer can calculate a.tiebreaker <= b.tiebreaker + // consistently. + ice_transport_channel()->SetIceTiebreaker(rtc::CreateRandomId64()); +} + +IceTransportAdapterImpl::IceTransportAdapterImpl( + Delegate* delegate, + rtc::scoped_refptr ice_transport) + : delegate_(delegate), ice_transport_channel_(ice_transport) { + // The native webrtc peer connection might have been closed in the meantime, + // clearing the ice transport channel; don't do anything in that case. |this| + // will eventually be destroyed when the blink layer gets notified by the + // webrtc layer that the transport has been cleared. + if (ice_transport_channel()) + SetupIceTransportChannel(); +} + +IceTransportAdapterImpl::~IceTransportAdapterImpl() = default; + +static uint32_t GetCandidateFilterForPolicy(IceTransportPolicy policy) { + switch (policy) { + case IceTransportPolicy::kRelay: + return cricket::CF_RELAY; + case IceTransportPolicy::kAll: + return cricket::CF_ALL; + } + NOTREACHED(); + return 0; +} + +void IceTransportAdapterImpl::StartGathering( + const cricket::IceParameters& local_parameters, + const cricket::ServerAddresses& stun_servers, + const WebVector& turn_servers, + IceTransportPolicy policy) { + if (port_allocator_) { + port_allocator_->set_candidate_filter(GetCandidateFilterForPolicy(policy)); + port_allocator_->SetConfiguration( + stun_servers, + const_cast&>(turn_servers) + .ReleaseVector(), + port_allocator_->candidate_pool_size(), + port_allocator_->prune_turn_ports()); + } + if (!ice_transport_channel()) { + LOG(ERROR) << "StartGathering called, but ICE transport released"; + return; + } + ice_transport_channel()->SetIceParameters(local_parameters); + ice_transport_channel()->MaybeStartGathering(); + DCHECK_EQ(ice_transport_channel()->gathering_state(), + cricket::kIceGatheringGathering); +} + +void IceTransportAdapterImpl::Start( + const cricket::IceParameters& remote_parameters, + cricket::IceRole role, + const Vector& initial_remote_candidates) { + if (!ice_transport_channel()) { + LOG(ERROR) << "Start called, but ICE transport released"; + return; + } + ice_transport_channel()->SetRemoteIceParameters(remote_parameters); + ice_transport_channel()->SetIceRole(role); + for (const auto& candidate : initial_remote_candidates) { + ice_transport_channel()->AddRemoteCandidate(candidate); + } +} + +void IceTransportAdapterImpl::HandleRemoteRestart( + const cricket::IceParameters& new_remote_parameters) { + if (!ice_transport_channel()) { + LOG(ERROR) << "HandleRemoteRestart called, but ICE transport released"; + return; + } + ice_transport_channel()->RemoveAllRemoteCandidates(); + ice_transport_channel()->SetRemoteIceParameters(new_remote_parameters); +} + +void IceTransportAdapterImpl::AddRemoteCandidate( + const cricket::Candidate& candidate) { + if (!ice_transport_channel()) { + LOG(ERROR) << "AddRemoteCandidate called, but ICE transport released"; + return; + } + ice_transport_channel()->AddRemoteCandidate(candidate); +} + +void IceTransportAdapterImpl::SetupIceTransportChannel() { + if (!ice_transport_channel()) { + LOG(ERROR) << "SetupIceTransportChannel called, but ICE transport released"; + return; + } + ice_transport_channel()->SignalGatheringState.connect( + this, &IceTransportAdapterImpl::OnGatheringStateChanged); + ice_transport_channel()->SignalCandidateGathered.connect( + this, &IceTransportAdapterImpl::OnCandidateGathered); + ice_transport_channel()->SignalIceTransportStateChanged.connect( + this, &IceTransportAdapterImpl::OnStateChanged); + ice_transport_channel()->SignalNetworkRouteChanged.connect( + this, &IceTransportAdapterImpl::OnNetworkRouteChanged); + ice_transport_channel()->SignalRoleConflict.connect( + this, &IceTransportAdapterImpl::OnRoleConflict); +} + +void IceTransportAdapterImpl::OnGatheringStateChanged( + cricket::IceTransportInternal* transport) { + DCHECK_EQ(transport, ice_transport_channel()); + delegate_->OnGatheringStateChanged( + ice_transport_channel()->gathering_state()); +} + +void IceTransportAdapterImpl::OnCandidateGathered( + cricket::IceTransportInternal* transport, + const cricket::Candidate& candidate) { + DCHECK_EQ(transport, ice_transport_channel()); + delegate_->OnCandidateGathered(candidate); +} + +void IceTransportAdapterImpl::OnStateChanged( + cricket::IceTransportInternal* transport) { + DCHECK_EQ(transport, ice_transport_channel()); + delegate_->OnStateChanged(ice_transport_channel()->GetIceTransportState()); +} + +void IceTransportAdapterImpl::OnNetworkRouteChanged( + absl::optional new_network_route) { + if (!ice_transport_channel()) { + LOG(ERROR) << "OnNetworkRouteChanged called, but ICE transport released"; + return; + } + const absl::optional selected_pair = + ice_transport_channel()->GetSelectedCandidatePair(); + if (!selected_pair) { + // The selected connection will only be null if the ICE connection has + // totally failed, at which point we'll get a StateChanged signal. The + // client will implicitly clear the selected candidate pair when it receives + // the failed state change, so we don't need to give an explicit callback + // here. + return; + } + delegate_->OnSelectedCandidatePairChanged(std::make_pair( + selected_pair->local_candidate(), selected_pair->remote_candidate())); +} + +static const char* IceRoleToString(cricket::IceRole role) { + switch (role) { + case cricket::ICEROLE_CONTROLLING: + return "controlling"; + case cricket::ICEROLE_CONTROLLED: + return "controlled"; + default: + return "unknown"; + } +} + +static cricket::IceRole IceRoleReversed(cricket::IceRole role) { + switch (role) { + case cricket::ICEROLE_CONTROLLING: + return cricket::ICEROLE_CONTROLLED; + case cricket::ICEROLE_CONTROLLED: + return cricket::ICEROLE_CONTROLLING; + default: + return cricket::ICEROLE_UNKNOWN; + } +} + +void IceTransportAdapterImpl::OnRoleConflict( + cricket::IceTransportInternal* transport) { + DCHECK_EQ(transport, ice_transport_channel()); + // This logic is copied from JsepTransportController. + cricket::IceRole reversed_role = + IceRoleReversed(ice_transport_channel()->GetIceRole()); + LOG(INFO) << "Got role conflict; switching to " + << IceRoleToString(reversed_role) << " role."; + ice_transport_channel()->SetIceRole(reversed_role); +} + +} // namespace blink diff --git a/pool/shard007/C++/0095151_ipc.cc b/pool/shard007/C++/0095151_ipc.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee98c5d0d50066be7cd2739b9c362fbf3b3a2942 --- /dev/null +++ b/pool/shard007/C++/0095151_ipc.cc @@ -0,0 +1,212 @@ +/* + * \brief Implementation of the Genode IPC-framework + * \author Martin Stein + * \date 2012-02-12 + */ + +/* + * Copyright (C) 2012-2013 Genode Labs GmbH + * + * This file is part of the Genode OS framework, which is distributed + * under the terms of the GNU General Public License version 2. + */ + +/* Genode includes */ +#include +#include +#include +#include +#include +#include +#include + +/* base-hw includes */ +#include +#include + +namespace Hw { extern Genode::Untyped_capability _main_thread_cap; } + +using namespace Genode; + +enum +{ + /* size of the callee-local name of a targeted RPC object */ + RPC_OBJECT_ID_SIZE = sizeof(Native_thread_id), + + /* + * The RPC framework marshalls a return value into reply messages to + * deliver exceptions, wich occured during the RPC call to the caller. + * This defines the size of this value. + */ + RPC_RETURN_VALUE_SIZE = sizeof(umword_t), +}; + + +/***************************** + ** IPC marshalling support ** + *****************************/ + +void Ipc_ostream::_marshal_capability(Native_capability const &cap) { + _snd_msg->cap_add(cap); } + + +void Ipc_istream::_unmarshal_capability(Native_capability &cap) { + cap = _rcv_msg->cap_get(); } + + +/***************** + ** Ipc_ostream ** + *****************/ + +Ipc_ostream::Ipc_ostream(Native_capability dst, Msgbuf_base *snd_msg) +: + Ipc_marshaller(&snd_msg->buf[0], snd_msg->size()), + _snd_msg(snd_msg), _dst(dst) +{ + _write_offset = align_natural(RPC_OBJECT_ID_SIZE); + _snd_msg->reset(); +} + + +/***************** + ** Ipc_istream ** + *****************/ + +void Ipc_istream::_wait() +{ + /* FIXME: this shall be not supported */ + Kernel::pause_current_thread(); +} + + +Ipc_istream::Ipc_istream(Msgbuf_base *rcv_msg) +: + Ipc_unmarshaller(&rcv_msg->buf[0], rcv_msg->size()), + Native_capability(Thread_base::myself() ? Thread_base::myself()->tid().cap + : Hw::_main_thread_cap), + _rcv_msg(rcv_msg), _rcv_cs(-1) +{ _read_offset = align_natural(RPC_OBJECT_ID_SIZE); } + + +Ipc_istream::~Ipc_istream() { } + + +/**************** + ** Ipc_client ** + ****************/ + +void Ipc_client::_call() +{ + retry( + [&] () { + + /* send request and receive corresponding reply */ + Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset); + + switch (Kernel::send_request_msg(Ipc_ostream::dst().dst(), + _rcv_msg->cap_rcv_window())) { + case -1: throw Blocking_canceled(); + case -2: throw Allocator::Out_of_memory(); + default: + _rcv_msg->reset(); + _snd_msg->reset(); + Thread_base::myself()->utcb()->copy_to(*_rcv_msg); + + /* reset unmarshaller */ + _write_offset = _read_offset = + align_natural(RPC_OBJECT_ID_SIZE); + } + + }, + [&] () { upgrade_pd_session_quota(3*4096); }); +} + + +Ipc_client::Ipc_client(Native_capability const &srv, Msgbuf_base *snd_msg, + Msgbuf_base *rcv_msg, unsigned short rcv_caps) +: Ipc_istream(rcv_msg), Ipc_ostream(srv, snd_msg), _result(0) { + rcv_msg->cap_rcv_window(rcv_caps); } + + +/**************** + ** Ipc_server ** + ****************/ + +Ipc_server::Ipc_server(Msgbuf_base *snd_msg, + Msgbuf_base *rcv_msg) : + Ipc_istream(rcv_msg), + Ipc_ostream(Native_capability(), snd_msg), + _reply_needed(false) { } + + +void Ipc_server::_prepare_next_reply_wait() +{ + /* now we have a request to reply */ + _reply_needed = true; + + /* leave space for RPC method return value */ + _write_offset = align_natural(RPC_OBJECT_ID_SIZE + + RPC_RETURN_VALUE_SIZE); + + /* reset unmarshaller */ + _read_offset = align_natural(RPC_OBJECT_ID_SIZE); +} + + +void Ipc_server::_wait() +{ + retry( + [&] () { + + /* receive request */ + switch (Kernel::await_request_msg(Msgbuf_base::MAX_CAP_ARGS)) { + case -1: throw Blocking_canceled(); + case -2: throw Allocator::Out_of_memory(); + default: + _rcv_msg->reset(); + Thread_base::myself()->utcb()->copy_to(*_rcv_msg); + + /* update server state */ + _prepare_next_reply_wait(); + } + + }, + [&] () { upgrade_pd_session_quota(3*4096); }); +} + + +void Ipc_server::_reply() +{ + Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset); + _snd_msg->reset(); + Kernel::send_reply_msg(0, false); +} + + +void Ipc_server::_reply_wait() +{ + /* if there is no reply, wait for request */ + if (!_reply_needed) { + _wait(); + return; + } + + retry( + [&] () { + /* send reply and receive next request */ + Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset); + switch (Kernel::send_reply_msg(Msgbuf_base::MAX_CAP_ARGS, true)) { + case -1: throw Blocking_canceled(); + case -2: throw Allocator::Out_of_memory(); + default: + _rcv_msg->reset(); + _snd_msg->reset(); + Thread_base::myself()->utcb()->copy_to(*_rcv_msg); + + /* update server state */ + _prepare_next_reply_wait(); + } + + }, + [&] () { upgrade_pd_session_quota(3*4096); }); +} diff --git a/pool/shard007/C++/0095153_sortstrategy.cpp b/pool/shard007/C++/0095153_sortstrategy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f85fe9ee58a7c9d985ee17e783adf09bdafbbc06 --- /dev/null +++ b/pool/shard007/C++/0095153_sortstrategy.cpp @@ -0,0 +1,90 @@ +/* + * (c) 2015 Raghavendra Nayak, All Rights Reserved. + * www.openguru.com/ + */ + +#include +#include + +// This abstract class provides the SortingAlgorithm interface +class SortingAlgorithms +{ +public: + SortingAlgorithms() {} + virtual ~SortingAlgorithms() {} + + virtual void sort(const std::string& arrayName) = 0; +}; + +// Implements the SortingAlgorithm interface via QuickSort +class QuickSort : public SortingAlgorithms +{ +public: + virtual void sort(const std::string& arrayName) { + std::cout << "Sorting " << arrayName << " using QuickSort." << std::endl; + } +}; + +// Implements the SortingAlgorithm interface via MergeSort +class MergeSort : public SortingAlgorithms +{ +public: + virtual void sort(const std::string& arrayName) { + std::cout << "Sorting " << arrayName << " using MergeSort." << std::endl; + } +}; + +// Implements the SortingAlgorithm interface via BubbleSort +class BubbleSort : public SortingAlgorithms +{ +public: + virtual void sort(const std::string& arrayName) { + std::cout << "Sorting " << arrayName << " using BubbleSort." << std::endl; + } +}; + +class Array +{ + SortingAlgorithms* sortStrategy; + std::string arrayName; +public: + enum SortStrategy + { + QUICK, MERGE, BUBBLE + }; + Array(const std::string& arrayName) + : sortStrategy(nullptr), arrayName(arrayName) { + } + void setStrategy(const int type) { + switch (type) { + case QUICK: + sortStrategy = new QuickSort(); + break; + case MERGE: + sortStrategy = new MergeSort(); + break; + case BUBBLE: + sortStrategy = new BubbleSort(); + default: + break; + } + } + void applyStrategy() { + if (sortStrategy != nullptr) { + sortStrategy->sort(arrayName); + } + } +}; + +int main(int argc, char **argv) +{ + Array intArray("integer array"); + int sortStrategy; + std::cout << "Enter the strategy for sorting: Quick(0) Merge(1) Bubble(2) : "; + std::cin >> sortStrategy; + + intArray.setStrategy(sortStrategy); + intArray.applyStrategy(); + + return 0; +} diff --git a/pool/shard007/C++/0095157_clippingPlane.cpp b/pool/shard007/C++/0095157_clippingPlane.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1d9cc08c111c819c3ea40e52010e3b6b0e3a4ce --- /dev/null +++ b/pool/shard007/C++/0095157_clippingPlane.cpp @@ -0,0 +1,101 @@ +/**************************************************************************** + + Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. + + This file is part of the QGLViewer library version 2.6.1. + + http://www.libqglviewer.com - contact@libqglviewer.com + + This file may be used under the terms of the GNU General Public License + versions 2.0 or 3.0 as published by the Free Software Foundation and + appearing in the LICENSE file included in the packaging of this file. + In addition, as a special exception, Gilles Debunne gives you certain + additional rights, described in the file GPL_EXCEPTION in this package. + + libQGLViewer uses dual licensing. Commercial/proprietary software must + purchase a libQGLViewer Commercial License. + + This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE + WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + +*****************************************************************************/ + +#include "clippingPlane.h" +#include "QGLViewer/manipulatedFrame.h" + +using namespace std; +using namespace qglviewer; + +// Draws a spiral +void Viewer::draw() +{ + const float nbSteps = 200.0; + + glBegin(GL_QUAD_STRIP); + for (int i=0; imatrix()); + // Since the Clipping Plane equation is multiplied by the current modelView, we can define a + // constant equation (plane normal along Z and passing by the origin) since we are here in the + // manipulatedFrame coordinates system (we glMultMatrixd() with the manipulatedFrame matrix()). + static const GLdouble equation[] = { 0.0, 0.0, 1.0, 0.0 }; + glClipPlane(GL_CLIP_PLANE0, equation); + + // Draw a plane representation: Its normal... + glColor3f(0.8f, 0.8f, 0.8f); + drawArrow(0.4f, 0.015f); + // ...and a quad (with a slightly shifted z so that it is not clipped). + glBegin(GL_QUADS); + glVertex3f(-1.0, -1.0, 0.001f); + glVertex3f(-1.0, 1.0, 0.001f); + glVertex3f( 1.0, 1.0, 0.001f); + glVertex3f( 1.0, -1.0, 0.001f); + glEnd(); + glPopMatrix(); +} + +void Viewer::init() +{ + // Restore previous viewer state. + restoreStateFromFile(); + + // Opens help window + help(); + + // The ManipulatedFrame will be used to position the clipping plane + setManipulatedFrame(new ManipulatedFrame()); + + // Enable plane clipping + glEnable(GL_CLIP_PLANE0); +} + +QString Viewer::helpString() const +{ + QString text("

C l i p p i n g P l a n e

"); + text += "The standard OpenGL GL_CLIP_PLANE feature is used to add an additionnal clipping "; + text += "plane in the scene, which position and orientation are set by a ManipulatedFrame.

"; + text += "Hold the Control key pressed down while using the mouse to modify the plane orientation (left button) "; + text += "and position (right button) and to interactively see the clipped result.

"; + text += "Since the plane equation is defined with respect to the current modelView matrix, a constant equation (normal"; + text += "along the Z axis) can be used since we transformed the coordinates system using the matrix() method."; + + return text; +} diff --git a/pool/shard007/C++/0095169_bitcoin.cpp b/pool/shard007/C++/0095169_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..464a0b37ff7fbe821776859cf28b5f7ff7830b06 --- /dev/null +++ b/pool/shard007/C++/0095169_bitcoin.cpp @@ -0,0 +1,270 @@ +/* + * W.J. van der Laan 2011-2012 + */ +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" + +#include "init.h" +#include "ui_interface.h" +#include "qtipcserver.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static QSplashScreen *splashref; + +static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + // in case of modal message, use blocking connection to wait for user to click OK + QMetaObject::invokeMethod(guiref, "error", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(bool, modal)); + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + } +} + +static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) +{ + if(!guiref) + return false; + if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) + return true; + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void ThreadSafeHandleURI(const std::string& strURI) +{ + if(!guiref) + return; + + QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(QString, QString::fromStdString(strURI))); +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); + QApplication::instance()->processEvents(); + } +} + +static void QueueShutdown() +{ + QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. EBT can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Do this early as we don't want to bother initializing if we are just calling IPC + ipcScanRelay(argc, argv); + + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // Command-line options take precedence: + ParseParameters(argc, argv); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "EBT", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + app.setOrganizationName("EBT"); + app.setOrganizationDomain("EBT.su"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + app.setApplicationName("EBT-Qt-testnet"); + else + app.setApplicationName("EBT-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.QueueShutdown.connect(QueueShutdown); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + + QSplashScreen splash(QPixmap(":/images/splash"), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + + app.setQuitOnLastWindowClosed(false); + + try + { + // Regenerate startup link, to fix links to old versions + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); + + BitcoinGUI window; + guiref = &window; + if(AppInit2()) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.setWalletModel(&walletModel); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Place this here as guiref has to be defined if we don't want to lose URIs + ipcInit(argc, argv); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.setWalletModel(0); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + Shutdown(NULL); + } + else + { + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard007/C++/0095170_rotatecamera.cpp b/pool/shard007/C++/0095170_rotatecamera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06d28dc363a7810f1d110798255afcbb4f3a7f3f --- /dev/null +++ b/pool/shard007/C++/0095170_rotatecamera.cpp @@ -0,0 +1,118 @@ + +#include "global.h" +#include "rotatecamera.h" + + +using namespace cv; + + +cRotateCamera::cRotateCamera() +{ + SimpleBlobDetector::Params params; + + // Change thresholds + params.minThreshold = 1; + params.maxThreshold = 20; + + // Filter by Area. + params.filterByArea = true; + params.minArea = g_config.m_detectPointMinArea; + params.maxArea = g_config.m_detectPointMaxArea; + + // Filter by Circularity + params.filterByCircularity = true; + params.minCircularity = 0.1f; + + // Filter by Convexity + params.filterByConvexity = true; + params.minConvexity = 0.87f; + + // Filter by Inertia + params.filterByInertia = true; + params.minInertiaRatio = 0.01f; + + + m_params = params; +} + +cRotateCamera::~cRotateCamera() +{ + +} + + +// Ä«¸Þ¶ó ȸÀüÀ» ÀνÄÇÑ´Ù. +void cRotateCamera::DetectCameraRotate(cCamera &camera0, const vector &contours, const Mat &skewTransform) +{ + int thresholdValue = g_config.m_binaryThreshold; // ÀÓ°è°ª(Threshold) ¼³Á¤ + int sensitive = g_config.m_rotateSensitivity; + + cRectContours origContours(contours); + cRectContours target = origContours; + target.ScaleCenter(0.2f); + + + cvNamedWindow("HUV05-binarization", 0); + cvResizeWindow("HUV05-binarization", 640, 480); + cvMoveWindow("HUV05-binarization", -660, 520); + cvCreateTrackbar("Threshold", "HUV05-binarization", &thresholdValue, 255, NULL); + cvCreateTrackbar("Sensitivity", "HUV05-binarization", &sensitive, 300, NULL); + + Mat src(camera0.Resolution().height, camera0.Resolution().width, CV_8UC(3)); + while (1) + { + Mat &cam = camera0.ShowCaptureUndistortion(skewTransform, src); + if (cam.empty()) + continue; + + Mat grayscaleMat = src.clone(); + cvtColor(src, grayscaleMat, CV_RGB2GRAY); // Ä÷¯¸¦ Èæ¹éÀ¸·Î º¯È¯ + + Mat binaryMat(grayscaleMat.size(), grayscaleMat.type()); + cv::threshold(grayscaleMat, binaryMat, thresholdValue, 255, cv::THRESH_BINARY); + + + //---------------------------------------------------------------------------------------------- + // À̹ÌÁö¿¡¼­ Æ÷ÀÎÅ͸¦ ã´Â´Ù. + SimpleBlobDetector detector(m_params); + + // Detect blobs. + std::vector keypoints; + detector.detect(binaryMat, keypoints); + + // Draw detected blobs as red circles. + // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures the size of the circle corresponds to the size of blob + Mat im_with_keypoints; + drawKeypoints(binaryMat, keypoints, im_with_keypoints, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS); + + origContours.Draw(im_with_keypoints, Scalar(0, 255, 0), 2); + target.Draw(im_with_keypoints, Scalar(0, 0, 255), 2); + + if (!keypoints.empty()) + { + if (keypoints.size() == 4) + { + // 4°³ÀÇ Æ÷ÀÎÆ®¸¦ ¾ÈÁ¤ÀûÀ¸·Î ãÀ¸¸é, À§Ä¡¸¦ ÀúÀåÇϰí, Detect¸¦ Á¾·áÇÑ´Ù. + cRectContours detectRect(keypoints); + detectRect.Draw(im_with_keypoints, Scalar(0, 255, 255), 2); + + // ¿øÁ¡¿¡¼­ ¹þ¾î³­ ±æÀ̸¦ Ãâ·ÂÇÑ´Ù. + vector centerLine; + centerLine.push_back(detectRect.Center()); + centerLine.push_back(origContours.Center()); + DrawLines(im_with_keypoints, centerLine, Scalar(255, 0, 0), 2); + // + + Point offset = (origContours.Center() - detectRect.Center()) * (sensitive / 100.f); + target.Init(origContours.Center() + offset, 10.f); + } + } + + imshow("HUV05-binarization", im_with_keypoints); + + if (cvWaitKey(10) == VK_ESCAPE) + break; + } + + cvDestroyWindow("HUV05-binarization"); +} diff --git a/pool/shard007/C++/0095178_hotmetadata.cpp b/pool/shard007/C++/0095178_hotmetadata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cdb3f709a57fba04000a2c228284fea105fc25d --- /dev/null +++ b/pool/shard007/C++/0095178_hotmetadata.cpp @@ -0,0 +1,86 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// +// File: HotMetaData.cpp +// + +// +// Class code:MetaData::HotMetaData represents a reader of hot data in MetaData hot stream. +// +// ====================================================================================== + +#include "external.h" + +#include "hotmetadata.h" +#include "hotdataformat.h" +#include "hotheapsdirectoryiterator.h" + +namespace MetaData +{ + +// -------------------------------------------------------------------------------------- +// +// Class code:MetaData::HotMetaData represents a reader of hot data in MetaData hot stream. +// +__checkReturn +HRESULT +HotMetaData::Initialize( + DataBuffer data) +{ + m_Data = data; + + return S_OK; +} // HotMetaData::Initialize + +// -------------------------------------------------------------------------------------- +// +// Returns iterator of stored hot heaps (code:HotHeap). +// +__checkReturn +HRESULT +HotMetaData::GetHeapsDirectoryIterator( + HotHeapsDirectoryIterator *pHeapsDirectoryIterator) +{ + if (m_Data.GetSize() < sizeof(struct HotMetaDataHeader)) + { + Debug_ReportError("Invalid hot MetaData format - header doesn't fit into the hot data."); + return METADATA_E_INVALID_FORMAT; + } + + struct HotMetaDataHeader *pHeader; + if (!m_Data.PeekDataAt( + m_Data.GetSize() - sizeof(struct HotMetaDataHeader), + &pHeader)) + { + Debug_ReportInternalError("There's a bug, because previous size check succeeded."); + return METADATA_E_INTERNAL_ERROR; + } + // Get rid of the read header + DataBuffer heapsData = m_Data; + if (!heapsData.TruncateBySize(sizeof(struct HotMetaDataHeader))) + { + Debug_ReportInternalError("There's a bug, because previous size check succeeded."); + return METADATA_E_INTERNAL_ERROR; + } + DataBuffer heapsDirectoryData = heapsData; + if (!heapsDirectoryData.SkipToExactSize(pHeader->m_nHeapsDirectoryStart_NegativeOffset)) + { + Debug_ReportError("Invalid hot MetaData format - heaps directory offset reaches in front of hot data."); + return METADATA_E_INVALID_FORMAT; + } + if (!heapsData.TruncateBySize(pHeader->m_nHeapsDirectoryStart_NegativeOffset)) + { + Debug_ReportInternalError("There's a bug, because previous call to SkipToExactSize succeeded."); + return METADATA_E_INVALID_FORMAT; + } + + pHeapsDirectoryIterator->Initialize( + heapsDirectoryData, + heapsData); + + return S_OK; +} // HotMetaData::GetHeapsDirectoryIterator + +}; // namespace MetaData diff --git a/pool/shard007/C++/0095185_test_window_manager.cc b/pool/shard007/C++/0095185_test_window_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef9cc1f41538bd47e83c9ecbac31483502ca804a --- /dev/null +++ b/pool/shard007/C++/0095185_test_window_manager.cc @@ -0,0 +1,112 @@ +// 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 "ui/ozone/platform/test/test_window_manager.h" + +#include "base/bind.h" +#include "base/file_util.h" +#include "base/location.h" +#include "base/stl_util.h" +#include "base/threading/worker_pool.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "ui/gfx/codec/png_codec.h" +#include "ui/gfx/skia_util.h" +#include "ui/gfx/vsync_provider.h" +#include "ui/ozone/public/surface_ozone_canvas.h" + +namespace ui { + +namespace { + +void WriteDataToFile(const base::FilePath& location, const SkBitmap& bitmap) { + DCHECK(!location.empty()); + std::vector png_data; + gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, true, &png_data); + base::WriteFile(location, + reinterpret_cast(vector_as_array(&png_data)), + png_data.size()); +} + +class FileSurface : public SurfaceOzoneCanvas { + public: + FileSurface(const base::FilePath& location) : location_(location) {} + virtual ~FileSurface() {} + + // SurfaceOzoneCanvas overrides: + virtual void ResizeCanvas(const gfx::Size& viewport_size) OVERRIDE { + surface_ = skia::AdoptRef(SkSurface::NewRaster(SkImageInfo::MakeN32Premul( + viewport_size.width(), viewport_size.height()))); + } + virtual skia::RefPtr GetCanvas() OVERRIDE { + return skia::SharePtr(surface_->getCanvas()); + } + virtual void PresentCanvas(const gfx::Rect& damage) OVERRIDE { + if (location_.empty()) + return; + SkBitmap bitmap; + bitmap.setInfo(surface_->getCanvas()->imageInfo()); + + // TODO(dnicoara) Use SkImage instead to potentially avoid a copy. + // See crbug.com/361605 for details. + if (surface_->getCanvas()->readPixels(&bitmap, 0, 0)) { + base::WorkerPool::PostTask( + FROM_HERE, base::Bind(&WriteDataToFile, location_, bitmap), true); + } + } + virtual scoped_ptr CreateVSyncProvider() OVERRIDE { + return scoped_ptr(); + } + + private: + base::FilePath location_; + skia::RefPtr surface_; +}; + +} // namespace + +TestWindowManager::TestWindowManager(const base::FilePath& dump_location) + : location_(dump_location) { +} + +TestWindowManager::~TestWindowManager() { +} + +void TestWindowManager::Initialize() { + if (location_.empty()) + return; + if (!DirectoryExists(location_) && !base::CreateDirectory(location_) && + location_ != base::FilePath("/dev/null")) + PLOG(FATAL) << "unable to create output directory"; + if (!base::PathIsWritable(location_)) + PLOG(FATAL) << "unable to write to output location"; +} + +int32_t TestWindowManager::AddWindow(TestWindow* window) { + return windows_.Add(window); +} + +void TestWindowManager::RemoveWindow(int32_t window_id, TestWindow* window) { + DCHECK_EQ(window, windows_.Lookup(window_id)); + windows_.Remove(window_id); +} + +base::FilePath TestWindowManager::base_path() const { + return location_; +} + +scoped_ptr TestWindowManager::CreateCanvasForWidget( + gfx::AcceleratedWidget widget) { + TestWindow* window = windows_.Lookup(widget); + DCHECK(window); + return make_scoped_ptr(new FileSurface(window->path())); +} + +bool TestWindowManager::LoadEGLGLES2Bindings( + AddGLLibraryCallback add_gl_library, + SetGLGetProcAddressProcCallback set_gl_get_proc_address) { + return false; +} + +} // namespace ui diff --git a/pool/shard007/C++/0095186_TcrDistributionManager.cpp b/pool/shard007/C++/0095186_TcrDistributionManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e5512dc0348cbad5fbbd9c0feb61eeb1fff4391 --- /dev/null +++ b/pool/shard007/C++/0095186_TcrDistributionManager.cpp @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "TcrDistributionManager.hpp" +#include "ThinClientRegion.hpp" +#include "TcrEndpoint.hpp" +#include +#include "Utils.hpp" +using namespace apache::geode::client; + +TcrDistributionManager::TcrDistributionManager( + ThinClientRegion* region, TcrConnectionManager& connManager) + : ThinClientDistributionManager(connManager, region) { + GF_R_ASSERT(region != nullptr); + m_clientNotification = + region->getAttributes().getClientNotificationEnabled(); +} + +void TcrDistributionManager::getEndpointNames( + std::unordered_set& endpointNames) { + Utils::parseEndpointNamesString(m_region->getAttributes().getEndpoints(), + endpointNames); +} + +void TcrDistributionManager::destroyAction() { + if (m_activeEndpoint >= 0) { + m_region->unregisterKeys(); + } +} + +void TcrDistributionManager::postUnregisterAction() { + if (m_clientNotification) { + m_region->localInvalidateFailover(); + } +} + +bool TcrDistributionManager::preFailoverAction() { + return !m_region->isDestroyed(); +} + +bool TcrDistributionManager::postFailoverAction(TcrEndpoint* endpoint) { + if (m_clientNotification) { + return (m_region->registerKeys(endpoint) == GF_NOERR); + } + return true; +} diff --git a/pool/shard007/C++/0095191_X3DShadersContext.cpp b/pool/shard007/C++/0095191_X3DShadersContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c04552a78b3cd203588eb32be9f4945dc9975d1 --- /dev/null +++ b/pool/shard007/C++/0095191_X3DShadersContext.cpp @@ -0,0 +1,230 @@ +/* -*- Mode: C++; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*- + ******************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011. + * + * All rights reserved. Holger Seelig . + * + * THIS IS UNPUBLISHED SOURCE CODE OF create3000. + * + * The copyright notice above does not evidence any actual of intended + * publication of such source code, and is an unpublished work by create3000. + * This material contains CONFIDENTIAL INFORMATION that is the property of + * create3000. + * + * No permission is granted to copy, distribute, or create derivative works from + * the contents of this software, in whole or in part, without the prior written + * permission of create3000. + * + * NON-MILITARY USE ONLY + * + * All create3000 software are effectively free software with a non-military use + * restriction. It is free. Well commented source is provided. You may reuse the + * source in any way you please with the exception anything that uses it must be + * marked to indicate is contains 'non-military use only' components. + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 1999, 2016 Holger Seelig . + * + * This file is part of the Titania Project. + * + * Titania is free software: you can redistribute it and/or modify it under the + * terms of the GNU General Public License version 3 only, as published by the + * Free Software Foundation. + * + * Titania is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License version 3 for more + * details (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License version 3 + * along with Titania. If not, see for a + * copy of the GPLv3 License. + * + * For Silvio, Joy and Adi. + * + ******************************************************************************/ + +#include "X3DShadersContext.h" + +#include "../../Browser/Core/BrowserOptions.h" +#include "../../Browser/Networking/config.h" +#include "../../Browser/Shaders/ShaderTest.h" +#include "../../Browser/X3DBrowser.h" +#include "../../Components/Networking/LoadSensor.h" +#include "../../Components/Shaders/ComposedShader.h" +#include "../../Components/Shaders/ShaderPart.h" +#include "../../Rendering/OpenGL.h" + +#include + +namespace titania { +namespace X3D { + +X3DShadersContext::X3DShadersContext () : + X3DBaseNode (), + shaders (true), + shadingLanguageVersion (), + maxVertexUniformVectors (0), + maxFragmentUniformVectors (0), + maxVertexAttributes (0), + pointShader (), + wireframeShader (), + gouraudShader (), + phongShader (), + defaultShader (), + shadowShader () +{ + addChildObjects (shaders, + pointShader, + wireframeShader, + gouraudShader, + phongShader, + defaultShader, + shadowShader); +} + +void +X3DShadersContext::initialize () +{ + if (getBrowser () -> getLoadUrlObjects ()) + { + std::istringstream shadingLanguageVersionStream ((const char*) glGetString (GL_SHADING_LANGUAGE_VERSION)); + + shadingLanguageVersionStream .imbue (std::locale::classic ()); + + shadingLanguageVersionStream >> shadingLanguageVersion; + + glGetIntegerv (GL_MAX_VERTEX_UNIFORM_VECTORS, &maxVertexUniformVectors); + glGetIntegerv (GL_MAX_FRAGMENT_UNIFORM_VECTORS, &maxFragmentUniformVectors); + glGetIntegerv (GL_MAX_VERTEX_ATTRIBS, &maxVertexAttributes); + + // Shaders + + if (getBrowser () -> getSharedContext ()) + { + pointShader = getBrowser () -> getSharedContext () -> getPointShader (); + wireframeShader = getBrowser () -> getSharedContext () -> getWireframeShader (); + gouraudShader = getBrowser () -> getSharedContext () -> getGouraudShader (); + phongShader = getBrowser () -> getSharedContext () -> getPhongShader (); + shadowShader = getBrowser () -> getSharedContext () -> getShadowShader (); + } + else + { + pointShader = createShader (getExecutionContext (), "TitaniaPointSet", { get_shader ("Shaders/PointSet.vs") .str () }, { get_shader ("Shaders/PointSet.fs") .str () }); + wireframeShader = createShader (getExecutionContext (), "TitaniaWireframe", { get_shader ("Shaders/Wireframe.vs") .str () }, { get_shader ("Shaders/Wireframe.fs") .str () }); + gouraudShader = createShader (getExecutionContext (), "TitaniaGouraud", { get_shader ("Shaders/Gouraud.vs") .str () }, { get_shader ("Shaders/Gouraud.fs") .str () }); + phongShader = createShader (getExecutionContext (), "TitaniaPhong", { get_shader ("Shaders/Phong.vs") .str () }, { get_shader ("Shaders/Phong.fs") .str () }); + shadowShader = createShader (getExecutionContext (), "TitaniaShadow", { get_shader ("Shaders/Phong.vs") .str () }, { get_shader ("Shaders/Phong.fs") .str () }, true); + + gouraudShader -> isValid () .addInterest (&X3DShadersContext::set_gouraud_shader_valid, this); + phongShader -> isValid () .addInterest (&X3DShadersContext::set_phong_shader_valid, this); + shadowShader -> isValid () .addInterest (&X3DShadersContext::set_shadow_shader_valid, this); + } + + // Shading + + getBrowser () -> getBrowserOptions () -> getShading () .addInterest (&X3DShadersContext::set_shading, this); + + set_shading (); + } +} + +X3DPtr +X3DShadersContext::createShader (X3DExecutionContext* const executionContext, + const std::string & name, + const MFString & vertexUrl, + const MFString & fragmentUrl, + const bool shadow) +{ + const auto vertexPart = MakePtr (executionContext); + const auto fragmentPart = MakePtr (executionContext); + const auto shaderNode = MakePtr (executionContext); + + fragmentPart -> setName (name + "FragmentShaderPart"); + vertexPart -> setName (name + "VertexShaderPart"); + shaderNode -> setName (name + "ComposedShader"); + + vertexPart -> setShadow (shadow); + fragmentPart -> setShadow (shadow); + + fragmentPart -> type () = "FRAGMENT"; + vertexPart -> url () = vertexUrl; + fragmentPart -> url () = fragmentUrl; + + shaderNode -> setCustom (false); + shaderNode -> parts () .emplace_back (vertexPart); + shaderNode -> parts () .emplace_back (fragmentPart); + + vertexPart -> setup (); + fragmentPart -> setup (); + shaderNode -> setup (); + + return shaderNode; +} + +void +X3DShadersContext::set_gouraud_shader_valid () +{ + gouraudShader -> isValid () .removeInterest (&X3DShadersContext::set_gouraud_shader_valid, this); + + if (gouraudShader -> isValid () and ShaderTest::verify (getBrowser (), gouraudShader)) + return; + + getBrowser () -> getConsole () -> warn ("*** Warning: All else fails, using fallback VRML shader.\n\n"); + + gouraudShader -> parts () [0] -> setField ("url", MFString ({ get_shader ("Shaders/Fallback.vs") .str () })); + gouraudShader -> parts () [1] -> setField ("url", MFString ({ get_shader ("Shaders/Fallback.fs") .str () })); +} + +void +X3DShadersContext::set_phong_shader_valid () +{ + phongShader -> isValid () .removeInterest (&X3DShadersContext::set_phong_shader_valid, this); + + if (phongShader -> isValid () and ShaderTest::verify (getBrowser (), phongShader)) + return; + + getBrowser () -> getConsole () -> warn ("*** Warning: Phong shading not possible, using Gouraud shading.\n\n"); + + phongShader = gouraudShader; + + set_shading (); +} + +void +X3DShadersContext::set_shadow_shader_valid () +{ + shadowShader -> isValid () .removeInterest (&X3DShadersContext::set_shadow_shader_valid, this); + + if (shadowShader -> isValid () and ShaderTest::verify (getBrowser (), shadowShader)) + return; + + getBrowser () -> getConsole () -> warn ("*** Warning: Shadow shading not possible, using Gouraud shading.\n\n"); + + shadowShader = gouraudShader; +} + +void +X3DShadersContext::set_shading () +{ + const auto & shading = getBrowser () -> getBrowserOptions () -> getShading (); + + if (shading == ShadingType::PHONG) + { + defaultShader = getPhongShader (); + } + else // GOURAUD + { + defaultShader = getGouraudShader (); + } +} + +X3DShadersContext::~X3DShadersContext () +{ } + +} // X3D +} // titania diff --git a/pool/shard007/C++/0095194_arcball.cpp b/pool/shard007/C++/0095194_arcball.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c8961ad86b697f006ae3b597964cddd5461588c --- /dev/null +++ b/pool/shard007/C++/0095194_arcball.cpp @@ -0,0 +1,132 @@ +#include "vixen.h" +#include "vxutil.h" +#include "util/vxarcball.h" + +namespace Vixen { +VX_IMPLEMENT_CLASSID(ArcBall, Engine, VX_ArcBall); + +ArcBall::ArcBall() : MouseEngine() +{ + m_Ball.Set(Vec3(0,0,0), 0); + m_Rotation.Set(Vec3(0,0,0), 1); + m_Button = MouseEvent::LEFT; + GetMessenger()->Observe(this, Event::MOUSE, NULL); +} + +Vec3 ArcBall::WhereOnSphere(const Vec2& pos) const +{ + Vec3 ballMouse; + float mag; + Model* mod = (Model*) GetTarget(); + + ballMouse.x = -(pos.x - m_Ball.Center.x) / m_Ball.Radius; + ballMouse.y = (pos.y - m_Ball.Center.y) / m_Ball.Radius; + mag = ballMouse.x * ballMouse.x + ballMouse.y * ballMouse.y; + if (mag > 1) + { + float scale = float(1 / sqrt(mag)); + ballMouse.x = ballMouse.x * scale; + ballMouse.y = ballMouse.y * scale; + ballMouse.z = 0; + } + else + ballMouse.z = sqrt(1.0f - mag); + return ballMouse; +} + +Quat ArcBall::QuatFromPoints(const Vec3& from, const Vec3& to) +{ + Quat qu; + qu.x = from.y * to.z - from.z * to.y; + qu.y = from.z * to.x - from.x * to.z; + qu.z = from.x * to.y - from.y * to.x; + qu.w = from.x * to.x + from.y * to.y + from.z * to.z; + return qu; +} + +void ArcBall::Initialize(const Vec2& pos) +{ + Model* model = (Model*) GetTarget(); + Scene* scene = GetMainScene(); + Sphere sphere; + + if (model && model->IsClass(VX_Model)) + { + if (model->IsClass(VX_Camera)) + { + Vec3 p; + scene->GetModels()->GetBound(&sphere, Model::WORLD); + sphere.Radius = model->GetTranslation().Distance(sphere.Center); + } + else + model->GetBound(&sphere, Model::WORLD); + m_Ball.Center.Set(sphere.Center.x, sphere.Center.y, sphere.Center.z); + m_Rotation.Set(model->GetRotation()); + m_Ball.Radius = sphere.Radius; + } + else + { + float w = scene->GetViewport().Width(); + float h = scene->GetViewport().Height(); + m_Ball.Center.Set(w / 2, h / 2, 0); + m_Rotation.Set(Vec3(0, 0, 0), 1); + m_Ball.Radius = (w > h) ? m_Ball.Center.x : m_Ball.Center.y; + } +} + +void ArcBall::OnMouse(const Vec2& pos, uint32 flags) +{ + SharedObj* target = GetTarget(); + int mouseflags = MouseFlags; + Vec2 oldpos = MousePos; + + MouseEngine::OnMouse(pos, flags); // update position and flags + if (flags != m_Button) // not dragging now? + return; + if ((mouseflags & m_Button) == 0) // starting a drag? + { + Initialize(pos); + return; + } + Vec3 from = WhereOnSphere(oldpos); // where we were on the sphere last event + Vec3 to = WhereOnSphere(pos); // where we are on the sphere now + m_Rotation = QuatFromPoints(from, to); // relative rotation quat + if (target && target->IsClass(VX_Model)) + { + Matrix mtx; + Model* mod = (Model*) target; + Vec3 t = mod->GetTranslation(); + + if (mod->IsClass(VX_Camera)) + { + mod->Translate(m_Ball.Center); + mod->Rotate(m_Rotation); + mod->Translate(-m_Ball.Center); + } + else + { + mtx.TranslationMatrix(-m_Ball.Center); + mtx.Rotate(m_Rotation); + mtx.SetTranslation(t); + ((Model*) target)->SetTransform(&mtx); + } + } + if (IsSet(SharedObj::DOEVENTS)) + LogEvent(); +} + +/* + * If we should be logging events, log the navigate event here + */ +void ArcBall::LogEvent() +{ + NavigateEvent* event = new NavigateEvent; + + event->Sender = this; + event->Time = 0; + event->Flags = NavigateEvent::ROTATION | NavigateEvent::YROTATION | NavigateEvent::XROTATION | NavigateEvent::ZROTATION; + event->Rot = m_Rotation; + event->Log(); +} + +} // end Vixen \ No newline at end of file diff --git a/pool/shard007/C++/0095197_ChunkChecksum.cc b/pool/shard007/C++/0095197_ChunkChecksum.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a0817782f381591b4861f0badd9efd3481df007 --- /dev/null +++ b/pool/shard007/C++/0095197_ChunkChecksum.cc @@ -0,0 +1,88 @@ +/* */ +#include "ChunkChecksum.h" +#include "A2STR.h" + +namespace aria2 { + +ChunkChecksum::ChunkChecksum():pieceLength_(0) {} + +ChunkChecksum::ChunkChecksum +(std::string hashType, + std::vector pieceHashes, + int32_t pieceLength) + : hashType_(std::move(hashType)), + pieceHashes_(std::move(pieceHashes)), + pieceLength_(pieceLength) +{} + +bool ChunkChecksum::validateChunk +(const std::string& actualDigest, + size_t index) const +{ + const std::string& digest = getPieceHash(index); + return !digest.empty() && actualDigest == digest; +} + +int64_t ChunkChecksum::getEstimatedDataLength() const +{ + return static_cast(pieceLength_)*pieceHashes_.size(); +} + +size_t ChunkChecksum::countPieceHash() const +{ + return pieceHashes_.size(); +} + +const std::string& ChunkChecksum::getPieceHash(size_t index) const +{ + if(index < pieceHashes_.size()) { + return pieceHashes_[index]; + } else { + return A2STR::NIL; + } +} + +void ChunkChecksum::setHashType(std::string hashType) +{ + hashType_ = std::move(hashType); +} + +void ChunkChecksum::setPieceHashes(std::vector pieceHashes) +{ + pieceHashes_ = std::move(pieceHashes); +} + +} // namespace aria2 diff --git a/pool/shard007/C++/0095209_Particle.cpp b/pool/shard007/C++/0095209_Particle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1004dafa02c2a509bbd701028fc954c6293dc7fa --- /dev/null +++ b/pool/shard007/C++/0095209_Particle.cpp @@ -0,0 +1,80 @@ +/* + * Particle.cpp + */ + +#include "Particle.h" +#include "map.h" +#include "Robot.h" +#include "Point.h" +#include "config.h" + +Particle::Particle(Point p_pPoint,double p_dYaw,double p_dBel) + :_particleLocation(p_pPoint), + _particleYaw(p_dYaw), + _particleBelief(p_dBel) +{ +} + +void Particle::update(Point p_dDeltaLocation, double p_dDeltaYaw) +{ + // Update The location according to delta + _particleLocation.x += p_dDeltaLocation.x; + _particleLocation.y += p_dDeltaLocation.y; + _particleYaw += p_dDeltaYaw; + + // Robot path posterior + double probOfPath = this->getParticleProbability(p_dDeltaLocation, p_dDeltaYaw); + + // Calculate new belief according to path, observations and previous belief + _particleBelief = SAFETY_FACTORY * _particleBelief * probOfPath ;//* ProbOfObs; + + // Check to see if particle exceeded the maximum probability + if (_particleBelief > 1) + { + _particleBelief = 1; + } +} + +// Calculates the probability that the movement is accurate +double Particle::getParticleProbability(Point p_pLocation, double p_dDeltaYaw) +{ + // Distance Traveled + double distance = sqrt(pow(p_pLocation.x, 2) + pow(p_pLocation.y, 2)); + + // Kept moving forward + if ((p_dDeltaYaw == 0) && (distance < DISTANCE_LIMIT)) + { + return 1; + } + else if ((distance < DISTANCE_LIMIT) && (p_dDeltaYaw < YAW_LIMIT)) + { + return 0.8; + } + else if (((distance > DISTANCE_LIMIT) && (p_dDeltaYaw < YAW_LIMIT)) || + ((distance < DISTANCE_LIMIT) && (p_dDeltaYaw > YAW_LIMIT))) + { + return 0.6; + } + else + { + return 0.2; + } +} + +Particle* Particle::CreateParticle() +{ + double newX = _particleLocation.x + (rand() % 21) / 100; + double newY = _particleLocation.y + (rand() % 21) / 100; + double newYaw = _particleYaw + (rand() % 61 - 30.0) * PI / 180.0; + return new Particle(Point(newX, newY), newYaw, _particleBelief);//, new Map(*_particleMap)); +} + + +double Particle::getBelief() +{ + return this->_particleBelief; +} + +Particle::~Particle() +{ +} diff --git a/pool/shard007/C++/0095217_propagateremotemove.cpp b/pool/shard007/C++/0095217_propagateremotemove.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b9af4eb12a39824dcdf79a940ce5a545f3b7cdb --- /dev/null +++ b/pool/shard007/C++/0095217_propagateremotemove.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (C) by Olivier Goffart + * + * 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. + */ + +#include "propagateremotemove.h" +#include "owncloudpropagator_p.h" +#include "account.h" +#include "syncjournalfilerecord.h" +#include "filesystem.h" +#include +#include + +namespace OCC { + +MoveJob::MoveJob(AccountPtr account, const QString& path, + const QString &destination, QObject* parent) + : AbstractNetworkJob(account, path, parent), _destination(destination) +{ } + + +void MoveJob::start() +{ + QNetworkRequest req; + req.setRawHeader("Destination", QUrl::toPercentEncoding(_destination, "/")); + setReply(davRequest("MOVE", path(), req)); + setupConnections(reply()); + + if( reply()->error() != QNetworkReply::NoError ) { + qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString(); + } + AbstractNetworkJob::start(); +} + + +QString MoveJob::errorString() +{ + if (_timedout) { + return tr("Connection timed out"); + } else if (reply()->hasRawHeader("OC-ErrorString")) { + return reply()->rawHeader("OC-ErrorString"); + } else { + return reply()->errorString(); + } +} + +bool MoveJob::finished() +{ + emit finishedSignal(); + return true; +} + +void PropagateRemoteMove::start() +{ + if (_propagator->_abortRequested.fetchAndAddRelaxed(0)) + return; + + qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget; + + QString targetFile(_propagator->getFilePath(_item->_renameTarget)); + + if (_item->_file == _item->_renameTarget) { + // The parents has been renamed already so there is nothing more to do. + finalize(); + return; + } + if (_item->_file == QLatin1String("Shared") ) { + // Before owncloud 7, there was no permissions system. At the time all the shared files were + // in a directory called "Shared" and were not supposed to be moved, otherwise bad things happens + + QString versionString = _propagator->account()->serverVersion(); + if (versionString.contains('.') && versionString.split('.')[0].toInt() < 7) { + QString originalFile(_propagator->getFilePath(QLatin1String("Shared"))); + _propagator->addTouchedFile(originalFile); + _propagator->addTouchedFile(targetFile); + QString renameError; + if( FileSystem::rename(targetFile, originalFile, &renameError) ) { + done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name.")); + } else { + done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared.")); + } + return; + } + } + + _job = new MoveJob(_propagator->account(), + _propagator->_remoteFolder + _item->_file, + _propagator->_remoteDir + _item->_renameTarget, + this); + connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished())); + _propagator->_activeJobs++; + _job->start(); + +} + +void PropagateRemoteMove::abort() +{ + if (_job && _job->reply()) + _job->reply()->abort(); +} + +void PropagateRemoteMove::slotMoveJobFinished() +{ + _propagator->_activeJobs--; + + Q_ASSERT(_job); + + qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS" + << _job->reply()->error() + << (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->reply()->errorString()); + + QNetworkReply::NetworkError err = _job->reply()->error(); + _item->_httpErrorCode = _job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + + if (err != QNetworkReply::NoError) { + + if( checkForProblemsWithShared(_item->_httpErrorCode, + tr("The file was renamed but is part of a read only share. The original file was restored."))) { + return; + } + + SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode); + done(status, _job->errorString()); + return; + } + + _item->_requestDuration = _job->duration(); + _item->_responseTimeStamp = _job->responseTimestamp(); + + if (_item->_httpErrorCode != 201 ) { + // Normaly we expect "201 Created" + // If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must + // throw an error. + done(SyncFileItem::NormalError, tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".") + .arg(_item->_httpErrorCode).arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); + return; + } + + finalize(); + +} + +void PropagateRemoteMove::finalize() +{ + _propagator->_journal->deleteFileRecord(_item->_originalFile); + SyncJournalFileRecord record(*_item, _propagator->getFilePath(_item->_renameTarget)); + record._path = _item->_renameTarget; + + _propagator->_journal->setFileRecord(record); + _propagator->_journal->commit("Remote Rename"); + done(SyncFileItem::Success); +} + + +} + diff --git a/pool/shard007/C++/0095224_TableViewPlugin.cpp b/pool/shard007/C++/0095224_TableViewPlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae569839e363c10b6a4296338d460f7a26fb69a6 --- /dev/null +++ b/pool/shard007/C++/0095224_TableViewPlugin.cpp @@ -0,0 +1,123 @@ +/*! + \file TableViewPlugin.cpp + \author Dane Gardner + + \section LICENSE + This file is part of the Parallel Tools GUI Framework (PTGF) + Copyright (C) 2010-2013 Argo Navis Technologies, LLC + + This library is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by the + Free Software Foundation; either version 2.1 of the License, or (at your + option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this library; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "TableViewPlugin.h" + +#include +#include + +#include "TableView.h" + +namespace Plugins { +namespace TableView { + +/*! \namespace Plugins::TableView + \brief Contains the TableViewPlugin. + */ + +/*! \class TableViewPlugin + \version 0.4.dev + \brief + + \par Depends on Plugins: + + \todo Document this more explicitly. + */ + +TableViewPlugin::TableViewPlugin(QObject *parent) : QObject(parent) +{ + m_Name = "TableView"; + m_Version = QString("%1.%2.%3").arg(VER_MAJ).arg(VER_MIN).arg(VER_PAT); +} + +TableViewPlugin::~TableViewPlugin() +{ +} + +bool TableViewPlugin::initialize(QStringList &args, QString *err) +{ + Q_UNUSED(args) + Q_UNUSED(err) + + try { + + Core::PluginManager::PluginManager &pluginManager = Core::PluginManager::PluginManager::instance(); + pluginManager.addObject(this); /* Register ourselves as an IViewFactory */ + + } catch(...) { + return false; + } + + return true; +} + +void TableViewPlugin::shutdown() +{ +} + +QString TableViewPlugin::name() +{ + return m_Name; +} + +QString TableViewPlugin::version() +{ + return m_Version; +} + +QList TableViewPlugin::dependencies() +{ + return m_Dependencies; +} + +QString TableViewPlugin::viewName() +{ + return "Table View"; +} + +bool TableViewPlugin::viewHandles(QAbstractItemModel *model) +{ + Q_UNUSED(model) + + /* We can handle pretty much anything, so there's no checking needed */ + return true; +} + +QAbstractItemView *TableViewPlugin::viewWidget(QAbstractItemModel *model) +{ + /* Check to see if we should even try to handle this model */ + if(!viewHandles(model)) { + return NULL; + } + + TableView *tableView = new TableView(); + tableView->setModel(model); + return tableView; +} + +} // namespace TableView +} // namespace Plugins + +#if QT_VERSION < 0x050000 +Q_EXPORT_PLUGIN(Plugins::TableView::TableViewPlugin) +#endif diff --git a/pool/shard007/C++/0095225_tmwxPrintout.cpp b/pool/shard007/C++/0095225_tmwxPrintout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ca4b2e0fdb86e3f60f7c706104ad26336a54c57 --- /dev/null +++ b/pool/shard007/C++/0095225_tmwxPrintout.cpp @@ -0,0 +1,89 @@ +/******************************************************************************* +File: tmwxPrintout.cpp +Project: TreeMaker 5.x +Purpose: Source file for TreeMaker printout class +Author: Robert J. Lang +Modified by: +Created: 2004-06-21 +Copyright: ©2004 Robert J. Lang. All Rights Reserved. +*******************************************************************************/ + +#include "tmwxPrintout.h" +#include "tmwxView.h" +#include "tmwxDesignCanvas.h" +#include "tmwxFoldedFormFrame.h" +#include "tmwxStr.h" +#include "tmModel.h" + +/********** +class tmwxPrintout +**********/ + +/***** +Constructor +*****/ +tmwxPrintout::tmwxPrintout(tmwxView* view, const wxString& title) + : wxDocPrintout(view, title), mDoc(view->GetDoc()), mView(view) +{ + TMASSERT(mView); + TMASSERT(mDoc); +} + + +/***** +Called by the framework to obtain information about page range. +*****/ +void tmwxPrintout::GetPageInfo(int* minPage, int* maxPage, int* selPageFrom, + int* selPageTo) +{ + *minPage = 1; + *maxPage = gFoldedFormFrame->CanPrint() ? 2 : 1; + *selPageFrom = 1; + *selPageTo = 1; +} + + +/***** +Return true if the printout can provide the given page. +*****/ +bool tmwxPrintout::HasPage(int pageNum) +{ + if (pageNum == 1) return true; + if (pageNum == 2 && gFoldedFormFrame->CanPrint()) return true; + return false; +} + + +/***** +Print a single page of the document. +*****/ +bool tmwxPrintout::OnPrintPage(int page) +{ + switch(page) { + case 1: { + // Draw the canvas image on the DC to create the printed image, letting + // the canvas know to tweak its presentation for printing and scale it to + // fit the DC. + tmwxDesignCanvas* canvas = mView->GetDesignCanvas(); + wxDC* dc = GetDC(); + canvas->SetPrinting(true); + canvas->OnDraw(*dc); + canvas->SetPrinting(false); + return true; + } + case 2: { + // Draw the folded form, if it exists; otherwise return false. + tmwxFoldedFormFrame* theFrame = gFoldedFormFrame; + if (theFrame->CanPrint()) { + wxDC* dc = GetDC(); + theFrame->SetPrinting(true); + theFrame->OnDraw(*dc); + theFrame->SetPrinting(false); + return true; + } + return false; + } + default: + return false; + } +} diff --git a/pool/shard007/C++/0095227_wizardpage.cpp b/pool/shard007/C++/0095227_wizardpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7acfd795e9706c13d636ed50a8cefd6ea31a5fb7 --- /dev/null +++ b/pool/shard007/C++/0095227_wizardpage.cpp @@ -0,0 +1,52 @@ +/* + * Cantata + * + * Copyright (c) 2011-2014 Craig Drummond + * + * ---- + * + * 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; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "wizardpage.h" +#include "support/icon.h" +#include "support/utils.h" +#include +#include + +void WizardPage::setBackground(const Icon &i) +{ + int size=fontMetrics().height()*10; + size=((int)(size/4))*4; + pix=i.pixmap(size, QIcon::Disabled); + if (pix.width()str = ""; +} + +String::String(char c) { + + this->str = (char*)c; +} + +String::String(const char* str) { + this->str = str; +} + +String::String(String& s) { + this->str = s.toCharArray(); +} + +String::String(bool b) { + if (b == true) { + this->str = "true"; + } else if (b == false) { + this->str = "false"; + } else { + this->str = "NULL"; + } +} + +String::String(int n) { + this->str = itoa(n, 10); +} + +int String::getLength() { + size_t len = 0; + while (this->str[len]) + len++; + return len; +} + +bool String::equals(const char* compare) { + String me(compare); + + + return (*this == me); +} + +bool String::equals(String& s) { + return (*this == s); +} + + +const char* String::toCharArray() { + return this->str; +} + +char String::operator[] (int j) +{ + if (j > this->getLength()) return 0; + return this->str[j]; +} + + +bool String::operator== (String& lhs) { + if (lhs.getLength() != this->getLength()) return false; + + unsigned cap = lhs.getLength(); + unsigned int n = 0; + while ((n < cap) && (lhs.toCharArray()[n] == this->toCharArray()[n])) n++; + return (n == cap); +} + +bool String::operator== (const char* str) { + + String nigga(str); + return (*this == nigga); +} + +String& String::operator+= (String& c) { + + String ret; + int length = this->getLength(); + int length2 = c.getLength(); + int len = length+length2; + char str[len]; + + for (int j=0; j < length; j++) + str[j] = this->str[j]; + + for (int i=0; i < c.getLength(); i++) + str[length+i] = c[i]; + + length = len; + ret = str; + return ret; +} diff --git a/pool/shard007/C++/0095231_line_following.cpp b/pool/shard007/C++/0095231_line_following.cpp new file mode 100644 index 0000000000000000000000000000000000000000..097ee99f1f1e4bec49ed6a638524954381e1ae6f --- /dev/null +++ b/pool/shard007/C++/0095231_line_following.cpp @@ -0,0 +1,206 @@ +#include "line_following.hh" + +//Follow line until junction reached +void lf_until_junction(void) +{ + #ifdef __virtual__ + cout << __PRETTY_FUNCTION__ << " was called\n"; + delay(1000); + return; + #endif + char left_speed, right_speed; + while(1)//!(get_linesensors()==0b111)) + { + get_linesensors(); + switch(line_sensors[0]) + { + case 0b000: + //All sensors off line + if(line_sensors[1]&0b100){ + //cout << __func__ << ": Detected end of stub"; + //set_motors(0, 0); + //return; + } + cout << __func__ << ": Lost line, calling lf_line_recovery()\n"; + lf_line_recovery(ROT_SPEED); + break; + + case 0b111: case 0b011: + //Both left and right high, must be at a junction + DEBUG("Junction detected"); + //if((line_sensors[1]==0b111)&(line_sensors[0]==0b111)) + return; + //delay(100); + break; + + case 0b100: + //Only centre sensor high, everything is happy + left_speed = right_speed = SPEED; + break; + case 0b101: case 0b001: + //Left on line, right off - Boost right motor + left_speed=SPEED-CORRECTION; + right_speed=SPEED; + break; + case 0b110: case 0b010: + //Right on line, left off - Boost left motor + left_speed=SPEED; + right_speed=SPEED-CORRECTION; + break; + default: + cout << " lf_until_junction(): get_linesensors() returned something funny: " << line_sensors[0] << endl; + break; + } + set_motors(left_speed, right_speed); + } + set_motors(0, 0); + return; +} + +//To be called only at a junction +void lf_turn(turning turn) +{ + #ifdef __virtual__ + cout << __PRETTY_FUNCTION__ << " was called with argument "; + print_turn(turn); cout << endl; + delay(1000); + return; + #endif + + bool reverse = false; + unsigned int node = status.current_node; + directions dir = status.direction; + if((node==4)&&(dir==WEST)) + reverse = true; + else if((node==11)&&(dir==SOUTH)) + reverse = true; + else if((node==10)&&(dir==EAST)) + reverse = true; + if((turn==FORWARD)|(turn==BACKWARD)) + reverse=false; + + if(reverse){ + cout << "reverse to turn called\n"; + reverse_to_line(turn); + return; //don't do another turn + } + + switch(turn) + { + case LEFT: + DEBUG("Performing left turn"); + unit_forwards(); + set_motors(128+127, 127); + delay(800); //wait for the sensors to clear the line + set_motors(128+20, 20); + while(!(get_linesensors()&0b100)); //wait for the center sensor to hit the line + break; + + case RIGHT: + DEBUG("Performing right turn"); + unit_forwards(); + set_motors(127, 128+127); + delay(800); //wait for the sensors to clear the line + set_motors(20, 128+20); + while(!(get_linesensors()&0b100)); //wait for the centre sensor to return to the line + break; + + case FORWARD: + DEBUG("Going straight on"); + set_motors(SPEED, SPEED); + delay(150); //just enough to advance past the junction + get_linesensors(); + return; + break; + + case BACKWARD: + DEBUG("Performing 180deg turn"); + unit_forwards(); + set_motors(127, 128+127); + delay(1800); //to find empirically - must go past a 90 deg line if there is one + set_motors(20, 128+20); + while(!(get_linesensors()&0b100)); + break; + + default: + cout << " lf_turn(): invalid turn asked for\n"; //Panic + //throw(INVALID_TURN); + + } + set_motors(0,0); + return; +} + + +void lf_line_recovery(char rot_speed) +{ + #ifdef __virtual__ + cout << __PRETTY_FUNCTION__ << " was called with argument " << int(rot_speed) << endl; + delay(1000); + return; + #endif +//we've lost the line +//rotate on the spot toward where the line last was + set_motors(0, 0); + DEBUG("Attempting to recover line"); + if(line_sensors[1]&0b001) //Left sensor before leaving was high + set_motors(128+rot_speed, rot_speed); + + else if(line_sensors[1]&0b010) //Right sensor before leaving was high + set_motors(rot_speed, 128+rot_speed); + + else + { + cout << " lf_line_recovery(): line_recovery() was called at an odd time\n"; + cout << " lf_line_recovery(): neither right nor left sensor was high last cycle\n"; + cout << " lf_line_recovery(): line_sensors[] are: " << line_sensors[0] << " " << line_sensors[1] << endl; + + //throw(WRONG_LINE_RECOVERY); + return; + } + + while(!(get_linesensors()&0b100)); //wait for centre line sensor to be high + + set_motors(0, 0); + cout << __func__ << ": Success\n"; + return; +} + +void unit_forwards(void) +{ + #ifdef __virtual__ + cout << __PRETTY_FUNCTION__ << "was called\n"; + delay(1000); + return; + #endif + DEBUG("Travelling a unit step forwards"); + set_motors(60, 60); + delay(1400); //empirically found + set_motors(0, 0); + return; +} +//called in perform_action, taking a left/right turn to get onto line +void reverse_to_line(turning turn) +{ + #ifdef __virtual__ + cout << __PRETTY_FUNCTION__ << "was called with argument "; + print_turn(turn); cout << endl; + delay(1000); + return; + #endif + set_motors(128+50, 128+50); + delay(1000); + set_conveyor(0); + if(turn == RIGHT) + { + set_motors(60,128+60); + } + else + { + set_motors(128+60,60); + } + delay(1700); + set_motors(80, 80); + while(!(get_linesensors()&0b100)); + set_motors(0,0); +} diff --git a/pool/shard007/C++/0095232_abstractliveedittool.cpp b/pool/shard007/C++/0095232_abstractliveedittool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..741804274932dfeaebd796cbe9477457b27c702a --- /dev/null +++ b/pool/shard007/C++/0095232_abstractliveedittool.cpp @@ -0,0 +1,185 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** 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. +** +****************************************************************************/ + +#include "abstractliveedittool.h" +#include "qdeclarativeviewinspector.h" +#include "../qdeclarativeviewinspector_p.h" + +#include + +#include +#include +#include + +namespace QmlJSDebugger { + +AbstractLiveEditTool::AbstractLiveEditTool(QDeclarativeViewInspector *editorView) + : QObject(editorView), m_inspector(editorView) +{ +} + + +AbstractLiveEditTool::~AbstractLiveEditTool() +{ +} + +QDeclarativeViewInspector *AbstractLiveEditTool::inspector() const +{ + return m_inspector; +} + +QDeclarativeView *AbstractLiveEditTool::view() const +{ + return m_inspector->declarativeView(); +} + +QGraphicsScene* AbstractLiveEditTool::scene() const +{ + return view()->scene(); +} + +void AbstractLiveEditTool::updateSelectedItems() +{ + selectedItemsChanged(items()); +} + +QList AbstractLiveEditTool::items() const +{ + return inspector()->selectedItems(); +} + +bool AbstractLiveEditTool::topItemIsMovable(const QList & itemList) +{ + QGraphicsItem *firstSelectableItem = topMovableGraphicsItem(itemList); + if (firstSelectableItem == 0) + return false; + if (toQDeclarativeItem(firstSelectableItem) != 0) + return true; + + return false; + +} + +bool AbstractLiveEditTool::topSelectedItemIsMovable(const QList &itemList) +{ + QList selectedItems = inspector()->selectedItems(); + + foreach (QGraphicsItem *item, itemList) { + QDeclarativeItem *declarativeItem = toQDeclarativeItem(item); + if (declarativeItem + && selectedItems.contains(declarativeItem) + /*&& (declarativeItem->qmlItemNode().hasShowContent() || selectNonContentItems)*/) + return true; + } + + return false; + +} + +bool AbstractLiveEditTool::topItemIsResizeHandle(const QList &/*itemList*/) +{ + return false; +} + +QDeclarativeItem *AbstractLiveEditTool::toQDeclarativeItem(QGraphicsItem *item) +{ + return qobject_cast(item->toGraphicsObject()); +} + +QGraphicsItem *AbstractLiveEditTool::topMovableGraphicsItem(const QList &itemList) +{ + foreach (QGraphicsItem *item, itemList) { + if (item->flags().testFlag(QGraphicsItem::ItemIsMovable)) + return item; + } + return 0; +} + +QDeclarativeItem *AbstractLiveEditTool::topMovableDeclarativeItem(const QList + &itemList) +{ + foreach (QGraphicsItem *item, itemList) { + QDeclarativeItem *declarativeItem = toQDeclarativeItem(item); + if (declarativeItem /*&& (declarativeItem->qmlItemNode().hasShowContent())*/) + return declarativeItem; + } + + return 0; +} + +QList AbstractLiveEditTool::toGraphicsObjectList(const QList + &itemList) +{ + QList gfxObjects; + foreach (QGraphicsItem *item, itemList) { + QGraphicsObject *obj = item->toGraphicsObject(); + if (obj) + gfxObjects << obj; + } + + return gfxObjects; +} + +QString AbstractLiveEditTool::titleForItem(QGraphicsItem *item) +{ + QString className("QGraphicsItem"); + QString objectStringId; + + QString constructedName; + + QGraphicsObject *gfxObject = item->toGraphicsObject(); + if (gfxObject) { + className = gfxObject->metaObject()->className(); + + className.remove(QRegExp("_QMLTYPE_\\d+")); + className.remove(QRegExp("_QML_\\d+")); + if (className.startsWith(QLatin1String("QDeclarative"))) + className = className.remove(QLatin1String("QDeclarative")); + + QDeclarativeItem *declarativeItem = qobject_cast(gfxObject); + if (declarativeItem) { + objectStringId = QDeclarativeViewInspector::idStringForObject(declarativeItem); + } + + if (!objectStringId.isEmpty()) { + constructedName = objectStringId + " (" + className + QLatin1Char(')'); + } else { + if (!gfxObject->objectName().isEmpty()) { + constructedName = gfxObject->objectName() + " (" + className + QLatin1Char(')'); + } else { + constructedName = className; + } + } + } + + return constructedName; +} + + +} // namespace QmlJSDebugger diff --git a/pool/shard007/C++/0095235_Map.cpp b/pool/shard007/C++/0095235_Map.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57766a4f9ebfe1ef4e787fcf5883665e22766f4c --- /dev/null +++ b/pool/shard007/C++/0095235_Map.cpp @@ -0,0 +1,79 @@ +#include + +#include "graphic/Map.hpp" + +namespace graphic +{ + +Map::Map(const algo::Map& map) : + m_width(map.getWidth()), + m_height(map.getHeight()), + m_shapes(new sf::RectangleShape[m_width * m_height]) +{ + this->initRectangles(map); + this->initCircles(map); +} + +Map::~Map() +{ + delete[] m_shapes; +} + + +void +Map::initRectangles(const algo::Map& map) +{ + unsigned int x, y; + sf::RectangleShape model; + + model.setSize(sf::Vector2f(TILE_SIZE, TILE_SIZE)); + model.setOutlineThickness(TILE_OUTLINE_THICKNESS); + model.setOutlineColor(TILE_OUTLINE_COLOR); + + for (x = 0; x < m_width; x++) + { + for (y = 0; y < m_height; y++) + { + sf::RectangleShape& shape = m_shapes[y * m_width + x]; + shape = model; + shape.setFillColor(map.at(x, y) == '0' ? WALL_COLOR : PATH_COLOR); + shape.setPosition(x * TILE_SIZE + TILE_OUTLINE_THICKNESS, y * TILE_SIZE + TILE_OUTLINE_THICKNESS); + } + } +} + + +void +Map::initCircles(const algo::Map& map) +{ + sf::CircleShape model; + + model.setRadius(POINT_RADIUS); + model.setOutlineThickness(POINT_OUTLINE_THICKNESS); + model.setOutlineColor(POINT_OUTLINE_COLOR); + + m_begin = model; + m_begin.setFillColor(BEGIN_FILL_COLOR); + m_begin.move(map.getBegin().x * TILE_SIZE + POINT_SHIFT, map.getBegin().y * TILE_SIZE + POINT_SHIFT); + + m_end = model; + m_end.setFillColor(END_FILL_COLOR); + m_end.move(map.getEnd().x * TILE_SIZE + POINT_SHIFT, map.getEnd().y * TILE_SIZE + POINT_SHIFT); +} + + +void +Map::draw(sf::RenderTarget& target, sf::RenderStates states) const +{ + unsigned int i; + + for (i = 0; i < m_width * m_height; i++) + { + target.draw(m_shapes[i], states); + } + + target.draw(m_begin, states); + target.draw(m_end, states); +} + +} diff --git a/pool/shard007/C++/0095236_SysClass.cpp b/pool/shard007/C++/0095236_SysClass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23453c2607f3ed9fc14e0d258750c20744599b33 --- /dev/null +++ b/pool/shard007/C++/0095236_SysClass.cpp @@ -0,0 +1,200 @@ +/* +This file is part of WME Lite. +http://dead-code.org/redir.php?target=wmelite + +Copyright (c) 2011 Jan Nedoma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +#include "persistent.h" +#include "SysInstance.h" +#include "SysClass.h" +#include "SysClassRegistry.h" +#include "BGame.h" +#include "BPersistMgr.h" + +namespace WinterMute { + +////////////////////////////////////////////////////////////////////////// +CSysClass::CSysClass(const AnsiString &name, PERSISTBUILD build, PERSISTLOAD load, bool persistent_class) { + m_Name = name; + + m_Build = build; + m_Load = load; + m_Next = NULL; + m_SavedID = -1; + m_Persistent = persistent_class; + m_NumInst = 0; + + CSysClassRegistry::GetInstance()->RegisterClass(this); +} + + +////////////////////////////////////////////////////////////////////////// +CSysClass::~CSysClass() { + CSysClassRegistry::GetInstance()->UnregisterClass(this); + RemoveAllInstances(); +} + +////////////////////////////////////////////////////////////////////////// +bool CSysClass::RemoveAllInstances() { + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + delete(*it); + } + m_Instances.clear(); + m_InstanceMap.clear(); + + return true; +} + +////////////////////////////////////////////////////////////////////////// +CSysInstance *CSysClass::AddInstance(void *instance, int id, int savedId) { + CSysInstance *inst = new CSysInstance(instance, id, this); + inst->SetSavedID(savedId); + m_Instances.insert(inst); + + m_InstanceMap[instance] = inst; + + CSysClassRegistry::GetInstance()->AddInstanceToTable(inst, instance); + + return inst; +} + + +////////////////////////////////////////////////////////////////////////// +bool CSysClass::RemoveInstance(void *instance) { + InstanceMap::iterator mapIt = m_InstanceMap.find(instance); + if (mapIt == m_InstanceMap.end()) return false; + + Instances::iterator it = m_Instances.find((*mapIt).second); + if (it != m_Instances.end()) { + delete(*it); + m_Instances.erase(it); + } + + m_InstanceMap.erase(mapIt); + + return false; +} + +////////////////////////////////////////////////////////////////////////// +int CSysClass::GetInstanceID(void *pointer) { + InstanceMap::iterator mapIt = m_InstanceMap.find(pointer); + if (mapIt == m_InstanceMap.end()) return -1; + else return (*mapIt).second->GetID(); +} + +////////////////////////////////////////////////////////////////////////// +void *CSysClass::IDToPointer(int savedID) { + //slow + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + if ((*it)->GetSavedID() == savedID) return (*it)->GetInstance(); + } + return NULL; +} + +////////////////////////////////////////////////////////////////////////// +int CSysClass::GetNumInstances() { + return m_Instances.size(); +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::Dump(FILE *stream) { + fprintf(stream, "%03d %c %-20s instances: %d\n", m_ID, m_Persistent ? 'p' : ' ', m_Name.c_str(), GetNumInstances()); +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::SaveTable(CBGame *Game, CBPersistMgr *PersistMgr) { + PersistMgr->PutString(m_Name.c_str()); + PersistMgr->PutDWORD(m_ID); + PersistMgr->PutDWORD(m_Instances.size()); + + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + PersistMgr->PutDWORD((*it)->GetID()); + } +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::LoadTable(CBGame *Game, CBPersistMgr *PersistMgr) { + m_SavedID = PersistMgr->GetDWORD(); + int numInstances = PersistMgr->GetDWORD(); + + for (int i = 0; i < numInstances; i++) { + if (m_Persistent) { + int instId = PersistMgr->GetDWORD(); + + if (i > 0) { + Game->LOG(0, "Warning: attempting to load multiple instances of persistent class %s (%d)", m_Name.c_str(), numInstances); + continue; + } + + Instances::iterator it = m_Instances.begin(); + if (it != m_Instances.end()) { + (*it)->SetSavedID(instId); + CSysClassRegistry::GetInstance()->AddInstanceToTable((*it), (*it)->GetInstance()); + } else Game->LOG(0, "Warning: instance %d of persistent class %s not found", i, m_Name.c_str()); + } + // normal instances, create empty objects + else { + void *emptyObject = m_Build(); + AddInstance(emptyObject, CSysClassRegistry::GetInstance()->GetNextID(), PersistMgr->GetDWORD()); + } + + } +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::SaveInstances(CBGame *Game, CBPersistMgr *PersistMgr) { + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + // write instace header + PersistMgr->PutDWORD(m_ID); + PersistMgr->PutDWORD((*it)->GetID()); + + m_Load((*it)->GetInstance(), PersistMgr); + } +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::LoadInstance(void *instance, CBPersistMgr *PersistMgr) { + m_Load(instance, PersistMgr); +} + + +////////////////////////////////////////////////////////////////////////// +void CSysClass::ResetSavedIDs() { + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + (*it)->SetSavedID(-1); + } +} + +////////////////////////////////////////////////////////////////////////// +void CSysClass::InstanceCallback(SYS_INSTANCE_CALLBACK lpCallback, void *lpData) { + Instances::iterator it; + for (it = m_Instances.begin(); it != m_Instances.end(); ++it) { + lpCallback((*it)->GetInstance(), lpData); + } +} + +} // end of namespace WinterMute diff --git a/pool/shard007/C++/0095238_background_application_loader.cc b/pool/shard007/C++/0095238_background_application_loader.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9a8533214cf6b6a1462076cb9e4f0dd438536db --- /dev/null +++ b/pool/shard007/C++/0095238_background_application_loader.cc @@ -0,0 +1,74 @@ +// 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/runner/android/background_application_loader.h" + +#include + +#include "base/bind.h" +#include "base/run_loop.h" +#include "mojo/shell/application_manager.h" + +namespace mojo { +namespace runner { + +BackgroundApplicationLoader::BackgroundApplicationLoader( + scoped_ptr real_loader, + const std::string& thread_name, + base::MessageLoop::Type message_loop_type) + : loader_(std::move(real_loader)), + message_loop_type_(message_loop_type), + thread_name_(thread_name), + message_loop_created_(true, false) {} + +BackgroundApplicationLoader::~BackgroundApplicationLoader() { + if (thread_) + thread_->Join(); +} + +void BackgroundApplicationLoader::Load( + const GURL& url, + InterfaceRequest application_request) { + DCHECK(application_request.is_pending()); + if (!thread_) { + // TODO(tim): It'd be nice if we could just have each Load call + // result in a new thread like DynamicService{Loader, Runner}. But some + // loaders are creating multiple ApplicationImpls (NetworkApplicationLoader) + // sharing a delegate (etc). So we have to keep it single threaded, wait + // for the thread to initialize, and post to the TaskRunner for subsequent + // Load calls for now. + thread_.reset(new base::DelegateSimpleThread(this, thread_name_)); + thread_->Start(); + message_loop_created_.Wait(); + DCHECK(task_runner_.get()); + } + + task_runner_->PostTask( + FROM_HERE, + base::Bind(&BackgroundApplicationLoader::LoadOnBackgroundThread, + base::Unretained(this), url, + base::Passed(&application_request))); +} + +void BackgroundApplicationLoader::Run() { + base::MessageLoop message_loop(message_loop_type_); + base::RunLoop loop; + task_runner_ = message_loop.task_runner(); + quit_closure_ = loop.QuitClosure(); + message_loop_created_.Signal(); + loop.Run(); + + // Destroy |loader_| on the thread it's actually used on. + loader_.reset(); +} + +void BackgroundApplicationLoader::LoadOnBackgroundThread( + const GURL& url, + InterfaceRequest application_request) { + DCHECK(task_runner_->RunsTasksOnCurrentThread()); + loader_->Load(url, std::move(application_request)); +} + +} // namespace runner +} // namespace mojo diff --git a/pool/shard007/C++/0095240_main.cpp b/pool/shard007/C++/0095240_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dadad5dbc16cf178719b2f63dd482cb6b01090af --- /dev/null +++ b/pool/shard007/C++/0095240_main.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "MainWindow.h" +#include "Session.h" +#include "ContactBook.h" +#include "Device.h" +#include "ExampleDevice.h" +#include "DeviceVcfFile.h" +#include "Exceptions.h" + + + + + +/** Creates a new session and fills it with example data. */ +std::unique_ptr makeExampleSession() +{ + std::unique_ptr session(new Session); + session->addDevice(std::unique_ptr(new ExampleDevice)); + + // Test: add a device based on a VCF file + QJsonObject cfg; + cfg["type"] = QString::fromUtf8("VcfFile"); + cfg["fileName"] = QString::fromUtf8("Contacts.vcf"); + session->addDevice(Device::createFromConfig(cfg)); + + return session; +} + + + + + +/** Loads the session, either from the current folder ("portable app") or from the user's home. +If neither contain any reasonable data, creates an empty data file. */ +std::unique_ptr loadSession() +{ + // First try loading from the current folder ("portable app"): + auto session = Session::loadFromFile("ContactBookSanitizer.cbsSession"); + if (session != nullptr) + { + return session; + } + + // No current folder data, load from user's home: + auto homePath = QDir::homePath() + "/"; + session = Session::loadFromFile(homePath + "ContactBookSanitizer.cbsSession"); + if (session != nullptr) + { + return session; + } + + // No data could be read, create a new example session file + qDebug() << "No session could be loaded. Creating a new session with example data."; + session = makeExampleSession(); + + // First try writing session to the current folder; if it fails, we're installed, if it succeeds, we're portable + try + { + session->saveToFile("ContactBookSanitizer.cbsSession"); + qDebug() << "Detected a portable installation, session will be stored in current folder."; + return session; + } + catch (const EFileError & exc) + { + qDebug() + << "Failed to write the session file to current folder: " << exc.m_Message + << "; this usually means we're running in installed mode. Will retry the home path."; + } + + // We're installed, save to local home: + try + { + session->saveToFile(homePath + "ContactBookSanitizer.cbsSession"); + qDebug() << "Detected an installed environment, session will be stored in home path: " << homePath; + return session; + } + catch (const EFileError & exc) + { + QString msg("Failed to write the session file to both current folder and the home path: %1; session data will be lost after you close the app."); + msg.arg(exc.m_Message); + qWarning() << msg; + QMessageBox::warning(nullptr, QString::fromUtf8("ContactBookSanitizer"), msg); + } + return session; +} + + + + + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + MainWindow w(loadSession()); + w.show(); + + return a.exec(); +} diff --git a/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc b/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..49e9eb9c5051adea44f55b886653d0d1e932081f --- /dev/null +++ b/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc @@ -0,0 +1,247 @@ +// 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 "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/extensions/extension_uninstall_dialog.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/common/extensions/extension.h" +#include "grit/generated_resources.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/compositor/compositor.h" +#include "ui/gfx/compositor/layer.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/layout_constants.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" +#include "ui/views/window/dialog_delegate.h" + +#if defined(USE_ASH) +#include "ash/shell.h" +#endif + +namespace { + +const int kRightColumnWidth = 210; +const int kIconSize = 69; + +class ExtensionUninstallDialogDelegateView; + +// Returns parent window for extension uninstall dialog. +// For ash, use app list window if it is visible. +// For other platforms or when app list is not visible on ash, +// use browser window of given |profile|. +// Note this function could return NULL if ash app list is not visible and +// there is no browser window open for |profile|. +gfx::NativeWindow GetParent(Profile* profile) { +#if defined(USE_ASH) + gfx::NativeWindow app_list = ash::Shell::GetInstance()->GetAppListWindow(); + if (app_list) + return app_list; +#endif + + Browser* browser = BrowserList::GetLastActiveWithProfile(profile); + if (browser && browser->window()) + return browser->window()->GetNativeHandle(); + + return NULL; +} + +// Views implementation of the uninstall dialog. +class ExtensionUninstallDialogViews : public ExtensionUninstallDialog { + public: + ExtensionUninstallDialogViews(Profile* profile, + ExtensionUninstallDialog::Delegate* delegate); + virtual ~ExtensionUninstallDialogViews(); + + // Forwards the accept and cancels to the delegate. + void ExtensionUninstallAccepted(); + void ExtensionUninstallCanceled(); + + ExtensionUninstallDialogDelegateView* view() { return view_; } + + private: + void Show() OVERRIDE; + + ExtensionUninstallDialogDelegateView* view_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionUninstallDialogViews); +}; + +// The dialog's view, owned by the views framework. +class ExtensionUninstallDialogDelegateView : public views::DialogDelegateView { + public: + ExtensionUninstallDialogDelegateView( + ExtensionUninstallDialogViews* dialog_view, + const Extension* extension, + SkBitmap* icon); + virtual ~ExtensionUninstallDialogDelegateView(); + + // Called when the ExtensionUninstallDialog has been destroyed to make sure + // we invalidate pointers. + void DialogDestroyed() { dialog_ = NULL; } + + private: + // views::DialogDelegate: + virtual string16 GetDialogButtonLabel(ui::DialogButton button) const OVERRIDE; + virtual int GetDefaultDialogButton() const OVERRIDE { + return ui::DIALOG_BUTTON_CANCEL; + } + virtual bool Accept() OVERRIDE; + virtual bool Cancel() OVERRIDE; + + // views::WidgetDelegate: + virtual ui::ModalType GetModalType() const OVERRIDE { + return ui::MODAL_TYPE_WINDOW; + } + virtual views::View* GetContentsView() OVERRIDE { return this; } + virtual string16 GetWindowTitle() const OVERRIDE; + + // views::View: + virtual gfx::Size GetPreferredSize() OVERRIDE; + + virtual void Layout() OVERRIDE; + + ExtensionUninstallDialogViews* dialog_; + + views::ImageView* icon_; + views::Label* heading_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionUninstallDialogDelegateView); +}; + +ExtensionUninstallDialogViews::ExtensionUninstallDialogViews( + Profile* profile, ExtensionUninstallDialog::Delegate* delegate) + : ExtensionUninstallDialog(profile, delegate), + view_(NULL) { +} + +ExtensionUninstallDialogViews::~ExtensionUninstallDialogViews() { + // Close the widget (the views framework will delete view_). + if (view_) { + view_->DialogDestroyed(); + view_->GetWidget()->CloseNow(); + } +} + +void ExtensionUninstallDialogViews::Show() { + gfx::NativeWindow parent = GetParent(profile_); + if (!parent) { + delegate_->ExtensionUninstallCanceled(); + return; + } + + view_ = new ExtensionUninstallDialogDelegateView(this, extension_, &icon_); + views::Widget::CreateWindowWithParent(view_, parent)->Show(); +} + +void ExtensionUninstallDialogViews::ExtensionUninstallAccepted() { + // The widget gets destroyed when the dialog is accepted. + view_ = NULL; + delegate_->ExtensionUninstallAccepted(); +} + +void ExtensionUninstallDialogViews::ExtensionUninstallCanceled() { + // The widget gets destroyed when the dialog is canceled. + view_ = NULL; + delegate_->ExtensionUninstallCanceled(); +} + +ExtensionUninstallDialogDelegateView::ExtensionUninstallDialogDelegateView( + ExtensionUninstallDialogViews* dialog_view, + const Extension* extension, + SkBitmap* icon) + : dialog_(dialog_view) { + // Scale down to icon size, but allow smaller icons (don't scale up). + gfx::Size size(icon->width(), icon->height()); + if (size.width() > kIconSize || size.height() > kIconSize) + size = gfx::Size(kIconSize, kIconSize); + icon_ = new views::ImageView(); + icon_->SetImageSize(size); + icon_->SetImage(*icon); + AddChildView(icon_); + + heading_ = new views::Label( + l10n_util::GetStringFUTF16(IDS_EXTENSION_UNINSTALL_PROMPT_HEADING, + UTF8ToUTF16(extension->name()))); + heading_->SetMultiLine(true); + AddChildView(heading_); +} + +ExtensionUninstallDialogDelegateView::~ExtensionUninstallDialogDelegateView() { +} + +string16 ExtensionUninstallDialogDelegateView::GetDialogButtonLabel( + ui::DialogButton button) const { + return l10n_util::GetStringUTF16((button == ui::DIALOG_BUTTON_OK) ? + IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON : IDS_CANCEL); +} + +bool ExtensionUninstallDialogDelegateView::Accept() { + if (dialog_) + dialog_->ExtensionUninstallAccepted(); + return true; +} + +bool ExtensionUninstallDialogDelegateView::Cancel() { + if (dialog_) + dialog_->ExtensionUninstallCanceled(); + return true; +} + +string16 ExtensionUninstallDialogDelegateView::GetWindowTitle() const { + return l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE); +} + + +gfx::Size ExtensionUninstallDialogDelegateView::GetPreferredSize() { + int width = kRightColumnWidth; + width += kIconSize; + width += views::kPanelHorizMargin * 3; + + int height = views::kPanelVertMargin * 2; + height += heading_->GetHeightForWidth(kRightColumnWidth); + + return gfx::Size(width, + std::max(height, kIconSize + views::kPanelVertMargin * 2)); +} + +void ExtensionUninstallDialogDelegateView::Layout() { + int x = views::kPanelHorizMargin; + int y = views::kPanelVertMargin; + + heading_->SizeToFit(kRightColumnWidth); + + if (heading_->height() <= kIconSize) { + icon_->SetBounds(x, y, kIconSize, kIconSize); + x += kIconSize; + x += views::kPanelHorizMargin; + + heading_->SetX(x); + heading_->SetY(y + (kIconSize - heading_->height()) / 2); + } else { + icon_->SetBounds(x, + y + (heading_->height() - kIconSize) / 2, + kIconSize, + kIconSize); + x += kIconSize; + x += views::kPanelHorizMargin; + + heading_->SetX(x); + heading_->SetY(y); + } +} + +} // namespace + +// static +ExtensionUninstallDialog* ExtensionUninstallDialog::Create( + Profile* profile, Delegate* delegate) { + return new ExtensionUninstallDialogViews(profile, delegate); +} diff --git a/pool/shard007/C++/0095243_memory.cpp b/pool/shard007/C++/0095243_memory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..971de3dce6cca6771d2cba400ef922eec2e6557d --- /dev/null +++ b/pool/shard007/C++/0095243_memory.cpp @@ -0,0 +1,129 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + http://lammps.sandia.gov, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +#include +#include +#include +#include "memory.h" +#include "error.h" + +#if defined(LMP_USER_INTEL) && defined(__INTEL_COMPILER) +#ifndef LMP_INTEL_NO_TBB +#define LMP_USE_TBB_ALLOCATOR +#include "tbb/scalable_allocator.h" +#else +#include +#endif +#endif + +#if defined(LMP_USER_INTEL) && !defined(LAMMPS_MEMALIGN) +#define LAMMPS_MEMALIGN 64 +#endif + +using namespace LAMMPS_NS; + +/* ---------------------------------------------------------------------- */ + +Memory::Memory(LAMMPS *lmp) : Pointers(lmp) {} + +/* ---------------------------------------------------------------------- + safe malloc +------------------------------------------------------------------------- */ + +void *Memory::smalloc(bigint nbytes, const char *name) +{ + if (nbytes == 0) return NULL; + +#if defined(LAMMPS_MEMALIGN) + void *ptr; + +#if defined(LMP_USE_TBB_ALLOCATOR) + ptr = scalable_aligned_malloc(nbytes, LAMMPS_MEMALIGN); +#else + int retval = posix_memalign(&ptr, LAMMPS_MEMALIGN, nbytes); + if (retval) ptr = NULL; +#endif + +#else + void *ptr = malloc(nbytes); +#endif + if (ptr == NULL) { + char str[128]; + sprintf(str,"Failed to allocate " BIGINT_FORMAT " bytes for array %s", + nbytes,name); + error->one(FLERR,str); + } + return ptr; +} + +/* ---------------------------------------------------------------------- + safe realloc +------------------------------------------------------------------------- */ + +void *Memory::srealloc(void *ptr, bigint nbytes, const char *name) +{ + if (nbytes == 0) { + destroy(ptr); + return NULL; + } + +#if defined(LMP_USE_TBB_ALLOCATOR) + ptr = scalable_aligned_realloc(ptr, nbytes, LAMMPS_MEMALIGN); +#elif defined(LMP_INTEL_NO_TBB) && defined(LAMMPS_MEMALIGN) && \ + defined(__INTEL_COMPILER) + + ptr = realloc(ptr, nbytes); + uintptr_t offset = ((uintptr_t)(const void *)(ptr)) % LAMMPS_MEMALIGN; + if (offset) { + void *optr = ptr; + ptr = smalloc(nbytes, name); + memcpy(ptr, optr, MIN(nbytes,malloc_usable_size(optr))); + free(optr); + } +#else + ptr = realloc(ptr,nbytes); +#endif + if (ptr == NULL) { + char str[128]; + sprintf(str,"Failed to reallocate " BIGINT_FORMAT " bytes for array %s", + nbytes,name); + error->one(FLERR,str); + } + return ptr; +} + +/* ---------------------------------------------------------------------- + safe free +------------------------------------------------------------------------- */ + +void Memory::sfree(void *ptr) +{ + if (ptr == NULL) return; + #if defined(LMP_USE_TBB_ALLOCATOR) + scalable_aligned_free(ptr); + #else + free(ptr); + #endif +} + +/* ---------------------------------------------------------------------- + erroneous usage of templated create/grow functions +------------------------------------------------------------------------- */ + +void Memory::fail(const char *name) +{ + char str[128]; + snprintf(str,128, + "Cannot create/grow a vector/array of pointers for %s",name); + error->one(FLERR,str); +} diff --git a/pool/shard007/C++/0095244_cmakeeditorfactory.cpp b/pool/shard007/C++/0095244_cmakeeditorfactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19ce5aa245e566efe6ab2be372d1d2aa35d0a577 --- /dev/null +++ b/pool/shard007/C++/0095244_cmakeeditorfactory.cpp @@ -0,0 +1,78 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** Commercial Usage +** +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** +**************************************************************************/ + +#include "cmakeeditorfactory.h" +#include "cmakeprojectconstants.h" +#include "cmakeeditor.h" + +#include +#include + +using namespace CMakeProjectManager; +using namespace CMakeProjectManager::Internal; + +CMakeEditorFactory::CMakeEditorFactory(CMakeManager *manager, TextEditor::TextEditorActionHandler *handler) + : m_mimeTypes(QStringList() << QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE)), + m_manager(manager), + m_actionHandler(handler) +{ + +} + +CMakeEditorFactory::~CMakeEditorFactory() +{ +} + +QString CMakeEditorFactory::id() const +{ + return QLatin1String(CMakeProjectManager::Constants::CMAKE_EDITOR_ID); +} + +QString CMakeEditorFactory::displayName() const +{ + return tr(CMakeProjectManager::Constants::CMAKE_EDITOR_DISPLAY_NAME); +} + +Core::IFile *CMakeEditorFactory::open(const QString &fileName) +{ + Core::IEditor *iface = Core::EditorManager::instance()->openEditor(fileName, id()); + return iface ? iface->file() : 0; +} + +Core::IEditor *CMakeEditorFactory::createEditor(QWidget *parent) +{ + CMakeEditor *rc = new CMakeEditor(parent, this, m_actionHandler); + TextEditor::TextEditorSettings::instance()->initializeEditor(rc); + return rc->editableInterface(); +} + +QStringList CMakeEditorFactory::mimeTypes() const +{ + return m_mimeTypes; +} diff --git a/pool/shard007/C++/0095245_bundle.cpp b/pool/shard007/C++/0095245_bundle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce429b8765225592ff93a0ede8a83d925d26931e --- /dev/null +++ b/pool/shard007/C++/0095245_bundle.cpp @@ -0,0 +1,141 @@ +/* + *** Pointer Bundle + *** src/model/bundle.cpp + Copyright T. Youngs 2007-2016 + + This file is part of Aten. + + Aten 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. + + Aten 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 Aten. If not, see . +*/ + +#include "model/bundle.h" +#include "model/model.h" +#include "math/constants.h" +#include + +ATEN_USING_NAMESPACE + +// Constructor +Bundle::Bundle() +{ + clear(); +} + +Bundle::Bundle(Forcefield* ptr) +{ + clear(); + ff = ptr; +} + +Bundle::Bundle(Model* ptr) +{ + clear(); + m = ptr; +} + +Bundle::Bundle(Pattern* ptr) +{ + clear(); + p = ptr; +} + +Bundle::Bundle(Atom* ptr) +{ + clear(); + i = ptr; +} + +Bundle::Bundle(Grid* ptr) +{ + clear(); + g = ptr; +} + +Bundle::Bundle(Glyph* ptr) +{ + clear(); + gl = ptr; +} + +// Return reendersource for stored model +Model* Bundle::rs() +{ + return (m == NULL ? NULL : m->renderSourceModel()); +} + +// Clear pointers +void Bundle::clear() +{ + m = 0; + s = 0; + ff = 0; + g = 0; + i = 0; + p = 0; + gl = 0; +} + +// Check for non-null pointers +bool Bundle::isNull(int ptrs) const +{ + if ((ptrs&Bundle::AtomPointer) && (i == 0)) return true; + if ((ptrs&Bundle::PatternPointer) && (p == 0)) return true; + if ((ptrs&Bundle::ModelPointer) && (m == 0)) return true; + if ((ptrs&Bundle::GridPointer) && (g == 0)) return true; + if ((ptrs&Bundle::SitePointer) && (s == 0)) return true; + if ((ptrs&Bundle::ForcefieldPointer) && (ff == 0)) return true; + if ((ptrs&Bundle::GlyphPointer) && (gl == 0)) return true; + return false; +} + +// Notify of non-null pointers +bool Bundle::notifyNull(int ptrs) const +{ + if ((ptrs&Bundle::AtomPointer) && (i == 0)) + { + printf("--> No active atom.\n"); + return true; + } + if ((ptrs&Bundle::PatternPointer) && (p == 0)) + { + printf("--> No active pattern.\n"); + return true; + } + if ((ptrs&Bundle::ModelPointer) && (m == 0)) + { + printf("--> No active model.\n"); + return true; + } + if ((ptrs&Bundle::GridPointer) && (g == 0)) + { + printf("--> No active grid.\n"); + return true; + } + if ((ptrs&Bundle::SitePointer) && (s == 0)) + { + printf("--> No active site.\n"); + return true; + } + if ((ptrs&Bundle::ForcefieldPointer) && (ff == 0)) + { + printf("--> No active forcefield.\n"); + return true; + } + if ((ptrs&Bundle::GlyphPointer) && (gl == 0)) + { + printf("--> No active glyph.\n"); + return true; + } + return false; +} diff --git a/pool/shard007/C++/0095246_AboutScreen.cpp b/pool/shard007/C++/0095246_AboutScreen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4185bb8f87a774208952a75086f40d64a927d16b --- /dev/null +++ b/pool/shard007/C++/0095246_AboutScreen.cpp @@ -0,0 +1,75 @@ +#include +#include // Core graphics library + +#include "AboutScreen.h" + +AboutScreen::AboutScreen(Adafruit_ILI9341* adafruitTft, ScreenUtils* sUtils, TimeUtils* tUtils, DateTimeCounter* counter) { + tft = adafruitTft; + screenUtils = sUtils; + timeUtils = tUtils; + dateTimeCounter = counter; +} + +void AboutScreen::open(String versionNumber) +{ + tft->fillScreen(ILI9341_BLACK); + + screenUtils->drawBatteryStateOfCharge(101); + + tft->setTextWrap(false); + tft->setFont(&DroidSansMono8pt7b); + + tft->setCursor(50, 30); + tft->setTextColor(ILI9341_GREEN, ILI9341_BLACK); + tft->println("www.diveino.hu"); + + screenUtils->drawBmpFile((char *)"Touch/logo.bmp", 50, 70); + screenUtils->drawButtonFrame(40, 60, 160, 160, 10, false); + + tft->setTextColor(ILI9341_WHITE, ILI9341_BLACK); + tft->setCursor(10, 310); + tft->println(versionNumber); + + dateTimeCounter->init(timeUtils->getCurrentTime()); +} + +int AboutScreen::handleTouch(Adafruit_FT6206* touchScreen) +{ + if (touchScreen->touched()) { + TS_Point touchPoint = touchScreen->getPoint(); + + // flip it around to match the screen. + touchPoint.x = map(touchPoint.x, 0, 240, 240, 0); + touchPoint.y = map(touchPoint.y, 0, 320, 320, 0); + + if (50 < touchPoint.x && touchPoint.x < 50+140 && + 70 < touchPoint.y && touchPoint.y < 70+140) { + drawButtonPress(BUTTON_HOME); + return GO_HOME; + } + delay(100); + } + + return NO_ACTION; +} + +void AboutScreen::drawButtonPress(int button) { + switch (button) { + case BUTTON_HOME: + screenUtils->drawButtonFrame(40, 60, 160, 160, 10, true); + break; + } + + delay(100); + + switch (button) { + case BUTTON_HOME: + screenUtils->drawButtonFrame(40, 60, 160, 160, 10, false); + break; + } +} + +void AboutScreen::drawCurrentTime() +{ + dateTimeCounter->update(timeUtils->getCurrentTime()); +} diff --git a/pool/shard007/C++/0095248_recursive_mutex_impl.cc b/pool/shard007/C++/0095248_recursive_mutex_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..29c4c680787ccb2aee767c2f778de72825240780 --- /dev/null +++ b/pool/shard007/C++/0095248_recursive_mutex_impl.cc @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2005, Eric Crahen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished + * to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "debug.h" + +#include "recursive_mutex_impl.h" +#include "thread_impl.h" + +#include "zthread/guard.h" + +#include +#include +#include + +namespace zthread { + +/** + * Create a new RecursiveMutexImpl + * + * @exception Initialization_Exception thrown if resources could not be + * properly allocated + */ +RecursiveMutexImpl::RecursiveMutexImpl() : _owner(0), _count(0) {} + +/** + * Destroy this RecursiveMutexImpl and release its resources + */ +RecursiveMutexImpl::~RecursiveMutexImpl() { +#ifndef NDEBUG + + // It is an error to destroy a mutex that has not been released + if (_owner != 0) { + ZTDEBUG("** You are destroying a mutex which was never released. **\n"); + assert(0); // Destroyed mutex while in use + } + + if (_waiters.size() > 0) { + ZTDEBUG("** You are destroying a mutex which is blocking %zd threads. **\n", + _waiters.size()); + assert(0); // Destroyed mutex while in use + } + +#endif +} + +void RecursiveMutexImpl::Acquire() { + // Get the monitor for the current thread + Monitor& m = ThreadImpl::current()->getMonitor(); + Monitor::STATE state; + + Guard g1(_lock); + + // If there is an entry count and the current thread is + // the owner, increment the count and continue. + if (_owner == &m) + _count++; + + else { + // Acquire the lock if it is free and there are no waiting threads + if (_owner == 0 && _waiters.empty()) { + assert(_count == 0); + + _owner = &m; + _count++; + + } else { // Otherwise, wait() + + _waiters.push_back(&m); + + m.Acquire(); + + { + Guard g2(g1); + state = m.wait(); + } + + m.Release(); + + // Remove from waiter list, regarless of weather release() is called or + // not. The monitor is sticky, so its possible a state 'stuck' from a + // previous operation and will leave the wait() w/o release() having + // been called. + List::iterator i = std::find(_waiters.begin(), _waiters.end(), &m); + if (i != _waiters.end()) _waiters.erase(i); + + // If awoke due to a notify(), take ownership. + switch (state) { + case Monitor::SIGNALED: + + assert(_owner == 0); + assert(_count == 0); + + _owner = &m; + _count++; + + break; + + case Monitor::INTERRUPTED: + throw InterruptedException(); + + default: + throw SynchronizationException(); + } + } + } +} + +bool RecursiveMutexImpl::tryAcquire(unsigned long timeout) { + // Get the monitor for the current thread + Monitor& m = ThreadImpl::current()->getMonitor(); + + Guard g1(_lock); + + // If there is an entry count and the current thread is + // the owner, increment the count and continue. + if (_owner == &m) + _count++; + + else { + // Acquire the lock if it is free and there are no waiting threads + if (_owner == 0 && _waiters.empty()) { + assert(_count == 0); + + _owner = &m; + _count++; + + } else { // Otherwise, wait() + + _waiters.push_back(&m); + + Monitor::STATE state = Monitor::TIMEDOUT; + + // Don't bother waiting if the timeout is 0 + if (timeout) { + m.Acquire(); + + { + Guard g2(g1); + state = m.wait(timeout); + } + + m.Release(); + } + + // Remove from waiter list, regarless of weather release() is called or + // not. The monitor is sticky, so its possible a state 'stuck' from a + // previous operation and will leave the wait() w/o release() having + // been called. + List::iterator i = std::find(_waiters.begin(), _waiters.end(), &m); + if (i != _waiters.end()) _waiters.erase(i); + + // If awoke due to a notify(), take ownership. + switch (state) { + case Monitor::SIGNALED: + + assert(_count == 0); + assert(_owner == 0); + + _owner = &m; + _count++; + + break; + + case Monitor::INTERRUPTED: + throw InterruptedException(); + + case Monitor::TIMEDOUT: + return false; + + default: + throw SynchronizationException(); + } + } + } + + return true; +} + +void RecursiveMutexImpl::release() { + // Get the monitor for the current thread + Monitor& m = ThreadImpl::current()->getMonitor(); + + Guard g1(_lock); + + // Make sure the operation is valid + if (!(_owner == &m)) throw InvalidOpException(); + + // Update the count, if it has reached 0, wake another waiter. + if (--_count == 0) { + _owner = 0; + + // Try to find a waiter with a backoff & retry scheme + for (;;) { + // Go through the list, attempt to notify() a waiter. + for (List::iterator i = _waiters.begin(); i != _waiters.end();) { + // Try the monitor lock, if it cant be locked skip to the next waiter + Monitor* n = *i; + if (n->TryAcquire()) { + // If notify() is not sucessful, it is because the wait() has already + // been ended (killed/interrupted/notify'd) + bool woke = n->notify(); + n->Release(); + + // Once notify() succeeds, return + if (woke) return; + + } else + ++i; + } + + if (_waiters.empty()) return; + + { // Backoff and try again + + Guard g2(g1); + ThreadImpl::yield(); + } + } + } +} + +} // namespace ZThread diff --git a/pool/shard007/C++/0095254_cmd_reverse_frames.cpp b/pool/shard007/C++/0095254_cmd_reverse_frames.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da468324f1b3de91b3b0d07549e543fdcf2e4552 --- /dev/null +++ b/pool/shard007/C++/0095254_cmd_reverse_frames.cpp @@ -0,0 +1,67 @@ +// Aseprite +// Copyright (C) 2001-2015 David Capello +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License version 2 as +// published by the Free Software Foundation. + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "app/app.h" +#include "app/commands/command.h" +#include "app/context_access.h" +#include "app/modules/gui.h" +#include "app/ui/main_window.h" +#include "app/ui/timeline.h" +#include "app/document_range_ops.h" + +namespace app { + +class ReverseFramesCommand : public Command { +public: + ReverseFramesCommand(); + Command* clone() const override { return new ReverseFramesCommand(*this); } + +protected: + bool onEnabled(Context* context); + void onExecute(Context* context); +}; + +ReverseFramesCommand::ReverseFramesCommand() + : Command("ReverseFrames", + "Reverse Frames", + CmdUIOnlyFlag) +{ +} + +bool ReverseFramesCommand::onEnabled(Context* context) +{ + DocumentRange range = App::instance()->getMainWindow()->getTimeline()->range(); + + return + context->checkFlags(ContextFlags::ActiveDocumentIsWritable) && + range.enabled() && + range.frames() >= 2; // We need at least 2 frames to reverse +} + +void ReverseFramesCommand::onExecute(Context* context) +{ + DocumentRange range = App::instance()->getMainWindow()->getTimeline()->range(); + if (!range.enabled()) + return; // Nothing to do + + Document* doc = context->activeDocument(); + + reverse_frames(doc, range); + + update_screen_for_document(doc); +} + +Command* CommandFactory::createReverseFramesCommand() +{ + return new ReverseFramesCommand; +} + +} // namespace app diff --git a/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp b/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f94909ea05104e44677cfa6fbdbd901ec0fb7f4 --- /dev/null +++ b/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp @@ -0,0 +1,72 @@ +/* +----------------------------------------------------------------------------- +This source file is part of OGRE + (Object-oriented Graphics Rendering Engine) +For the latest info, see http://www.ogre3d.org/ + +Copyright (c) 2000-2012 Torus Knot Software Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +----------------------------------------------------------------------------- +*/ + +#include "OgreStableHeaders.h" +#include "OgreCgPlugin.h" +#include "OgreCgProgram.h" +#include "OgreRoot.h" + +namespace Ogre { + + CgPlugin* cgPlugin; +#ifndef OGRE_STATIC_LIB + //----------------------------------------------------------------------- + extern "C" void _OgreCgPluginExport dllStartPlugin(void) + { + // Create new plugin + cgPlugin = OGRE_NEW CgPlugin(); + + // Register + Root::getSingleton().installPlugin(cgPlugin); + + + } + extern "C" void _OgreCgPluginExport dllStopPlugin(void) + { + Root::getSingleton().uninstallPlugin(cgPlugin); + OGRE_DELETE cgPlugin; + } +#endif + + void checkForCgError(const String& ogreMethod, const String& errorTextPrefix, CGcontext context) + { + CGerror error = cgGetError(); + if (error != CG_NO_ERROR) + { + String msg = errorTextPrefix + cgGetErrorString(error); + + if (error == CG_COMPILER_ERROR) + { + // Get listing with full compile errors + msg = msg + "\n" + cgGetLastListing(context); + } + OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, msg, ogreMethod); + } + } + +} diff --git a/pool/shard007/C++/0095259_animation-playlist.cpp b/pool/shard007/C++/0095259_animation-playlist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99a61ca9129360a9e0d5d7ab33e114c23181d1a2 --- /dev/null +++ b/pool/shard007/C++/0095259_animation-playlist.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// CLASS HEADER +#include + + +// INTERNAL INCLUDES +#include +#include +#include + + +namespace Dali +{ + +namespace Internal +{ + +AnimationPlaylist* AnimationPlaylist::New() +{ + return new AnimationPlaylist(); +} + +AnimationPlaylist::AnimationPlaylist() +{ +} + +AnimationPlaylist::~AnimationPlaylist() +{ +} + +void AnimationPlaylist::AnimationCreated( Animation& animation ) +{ + mAnimations.PushBack( &animation ); +} + +void AnimationPlaylist::AnimationDestroyed( Animation& animation ) +{ + Dali::Vector< Animation* >::Iterator iter = std::find( mAnimations.Begin(), mAnimations.End(), &animation ); + DALI_ASSERT_ALWAYS( iter != mAnimations.End() && "Animation not found" ); + + mAnimations.Remove( iter ); +} + +void AnimationPlaylist::OnPlay( Animation& animation ) +{ + mPlaylist.push_back( Dali::Animation(&animation) ); +} + +void AnimationPlaylist::OnClear( Animation& animation ) +{ + std::vector< Dali::Animation >::iterator iter = std::find( mPlaylist.begin(), mPlaylist.end(), Dali::Animation(&animation) ); + std::vector< Dali::Animation >::iterator last = mPlaylist.end(); + if( iter != last ) + { + --last; // move to real last + std::swap( *iter, *last ); // swap + mPlaylist.resize( mPlaylist.size() - 1u ); + } +} + +void AnimationPlaylist::NotifyCompleted() +{ + std::vector< Dali::Animation > finishedAnimations; + + // Since animations can be unreferenced during the signal emissions, iterators into animationPointers may be invalidated. + // First copy and reference the finished animations, then emit signals + for ( Dali::Vector< Animation* >::Iterator iter = mAnimations.Begin(); iter != mAnimations.End(); ++iter ) + { + Animation* animation = *iter; + + if ( animation->HasFinished() ) + { + finishedAnimations.push_back( Dali::Animation(animation) ); + + // The animation may be present in mPlaylist - remove if necessary + // Note that the animation "Finish" signal is emitted after Stop() has been called + std::vector< Dali::Animation >::iterator iter = std::find( mPlaylist.begin(), mPlaylist.end(), Dali::Animation(animation) ); + DALI_ASSERT_DEBUG(iter != mPlaylist.end()); + mPlaylist.erase( iter ); + } + } + + // Now it's safe to emit the signals + for ( std::vector< Dali::Animation >::iterator iter = finishedAnimations.begin(); iter != finishedAnimations.end(); ++iter ) + { + Dali::Animation& handle = *iter; + + GetImplementation(handle).EmitSignalFinish(); + } +} + +} // namespace Internal + +} // namespace Dali diff --git a/pool/shard007/C++/0095261_Http.cpp b/pool/shard007/C++/0095261_Http.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b5c0a91ca6a2e2eae3ba0dceb94c36da666e7fd --- /dev/null +++ b/pool/shard007/C++/0095261_Http.cpp @@ -0,0 +1,176 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2021 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "Http.hpp" +#include "Assert.hxx" +#include "Util.hxx" +#include "Class.hxx" +#include "Error.hxx" +#include "net/http/Easy.hxx" +#include "net/http/Adapter.hxx" +#include "net/http/Handler.hxx" + +extern "C" { +#include +} + +#include +#include + +class LuaHttpRequest final : CurlResponseHandler { + CurlEasy easy; + + CurlResponseHandlerAdapter adapter; + + int status; + std::multimap response_headers; + + std::string response_body; + + std::exception_ptr error; + +public: + explicit LuaHttpRequest(const char *url) + :easy(url), adapter(*this) + { + adapter.Install(easy); + } + +private: + int Perform(lua_State *L); + +public: + static int l_new(lua_State *L); + static int l_perform(lua_State *L); + +private: + /* virtual methods from class CurlResponseHandler */ + void OnHeaders(unsigned _status, + std::multimap &&_headers) override { + status = _status; + response_headers = std::move(_headers); + } + + void OnData(ConstBuffer data) override { + // TODO size check + response_body.append((const char *)data.data, data.size); + } + + void OnEnd() override { + } + + void OnError(std::exception_ptr e) noexcept override { + error = std::move(e); + } +}; + +static constexpr struct luaL_Reg http_request_funcs[] = { + {"new", LuaHttpRequest::l_new}, + {nullptr, nullptr} +}; + +static constexpr struct luaL_Reg http_request_methods[] = { + {"perform", LuaHttpRequest::l_perform}, + {nullptr, nullptr} +}; + +static constexpr char lua_http_request_class[] = "http.Request"; +using LuaHttpRequestClass = Lua::Class; + +int +LuaHttpRequest::l_new(lua_State *L) +{ + if (lua_gettop(L) != 2) + return luaL_error(L, "Invalid parameters"); + + if (!lua_isstring(L, 2)) + luaL_argerror(L, 2, "URL expected"); + + LuaHttpRequestClass::New(L, lua_tostring(L, 2)); + return 1; +} + +int +LuaHttpRequest::Perform(lua_State *L) +{ + using namespace Lua; + + easy.Perform(); + + // TODO: yield to the main event loop until the request is done + + if (error) + Lua::Raise(L, std::move(error)); + + lua_newtable(L); + SetTable(L, RelativeStackIndex{-1}, "status", status); + + lua_pushstring(L, "headers"); + lua_newtable(L); + for (const auto &i : response_headers) + SetTable(L, RelativeStackIndex{-1}, i.first, i.second); + lua_settable(L, -3); + + SetTable(L, RelativeStackIndex{-1}, "body", response_body); + + return 1; +} + +int +LuaHttpRequest::l_perform(lua_State *L) +{ + auto &request = LuaHttpRequestClass::Cast(L, 1); + return request.Perform(L); +} + +static void +CreateHttpRequestMetatable(lua_State *L) +{ + LuaHttpRequestClass::Register(L); + + /* metatable.__index = http_request_methods */ + luaL_newlib(L, http_request_methods); + lua_setfield(L, -2, "__index"); + + /* pop metatable */ + lua_pop(L, 1); +} + +void +Lua::InitHttp(lua_State *L) +{ + const Lua::ScopeCheckStack check_stack(L); + + lua_getglobal(L, "xcsoar"); + + /* create the "http" namespace */ + lua_newtable(L); + + luaL_newlib(L, http_request_funcs); // create 'request' + lua_setfield(L, -2, "Request"); // http.Request = request + + lua_setfield(L, -2, "http"); // xcsoar.http = http + lua_pop(L, 1); // pop global "xcsoar" + + CreateHttpRequestMetatable(L); +} diff --git a/pool/shard007/C++/0095264_chrome_elf_main.cc b/pool/shard007/C++/0095264_chrome_elf_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..c270132736010d0df988d17ac0533fb24576e3eb --- /dev/null +++ b/pool/shard007/C++/0095264_chrome_elf_main.cc @@ -0,0 +1,100 @@ +// 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 "chrome/chrome_elf/chrome_elf_main.h" + +#include +#include + +#include "chrome/chrome_elf/chrome_elf_security.h" +#include "chrome/chrome_elf/crash/crash_helper.h" +#include "chrome/chrome_elf/third_party_dlls/beacon.h" +#include "chrome/chrome_elf/third_party_dlls/main.h" +#include "chrome/install_static/install_details.h" +#include "chrome/install_static/install_util.h" +#include "chrome/install_static/product_install_details.h" +#include "chrome/install_static/user_data_dir.h" + +// This function is exported from the DLL so that it can be called by WinMain +// after startup has completed in the browser process. For non-browser processes +// it will be called inside the DLL loader lock so it should do as little as +// possible to prevent deadlocks. +void SignalInitializeCrashReporting() { + if (!elf_crash::InitializeCrashReporting()) { +#ifdef _DEBUG + assert(false); +#endif // _DEBUG + } +} + +void SignalChromeElf() { + third_party_dlls::ResetBeacon(); +} + +bool GetUserDataDirectoryThunk(wchar_t* user_data_dir, + size_t user_data_dir_length, + wchar_t* invalid_user_data_dir, + size_t invalid_user_data_dir_length) { + std::wstring user_data_dir_str, invalid_user_data_dir_str; + bool ret = install_static::GetUserDataDirectory(&user_data_dir_str, + &invalid_user_data_dir_str); + assert(ret); + install_static::IgnoreUnused(ret); + wcsncpy_s(user_data_dir, user_data_dir_length, user_data_dir_str.c_str(), + _TRUNCATE); + wcsncpy_s(invalid_user_data_dir, invalid_user_data_dir_length, + invalid_user_data_dir_str.c_str(), _TRUNCATE); + + return true; +} + +// DllMain +// ------- +// Warning: The OS loader lock is held during DllMain. Be careful. +// https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971.aspx +// +// - Note: Do not use install_static::GetUserDataDir from inside DllMain. +// This can result in path expansion that triggers secondary DLL loads, +// that will blow up with the loader lock held. +// https://bugs.chromium.org/p/chromium/issues/detail?id=748949#c18 +BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { + if (reason == DLL_PROCESS_ATTACH) { + install_static::InitializeProductDetailsForPrimaryModule(); + install_static::InitializeProcessType(); + + if (install_static::IsBrowserProcess()) { + __try { + // Disable third party extension points. + elf_security::EarlyBrowserSecurity(); + + // Initialize the blocking of third-party DLLs if the initialization of + // the safety beacon succeeds. + if (third_party_dlls::LeaveSetupBeacon()) + third_party_dlls::Init(); + } __except (elf_crash::GenerateCrashDump(GetExceptionInformation())) { + } + } else if (!install_static::IsCrashpadHandlerProcess()) { + SignalInitializeCrashReporting(); + // CRT on initialization installs an exception filter which calls + // TerminateProcess. We need to hook CRT's attempt to set an exception. + elf_crash::DisableSetUnhandledExceptionFilter(); + } + + } else if (reason == DLL_PROCESS_DETACH) { + elf_crash::ShutdownCrashReporting(); + } + return TRUE; +} + +void DumpProcessWithoutCrash() { + elf_crash::DumpWithoutCrashing(); +} + +void SetMetricsClientId(const char* client_id) { + elf_crash::SetMetricsClientIdImpl(client_id); +} + +bool IsBrowserProcess() { + return install_static::IsBrowserProcess(); +} diff --git a/pool/shard007/C++/0095271_test_size_handling.cpp b/pool/shard007/C++/0095271_test_size_handling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..195bac704c904dc3f16463916400c74b5c7e16b2 --- /dev/null +++ b/pool/shard007/C++/0095271_test_size_handling.cpp @@ -0,0 +1,169 @@ + +/*== +** +** #### ###### # # # #### +** # # # # ## ## # # +** # ### # # ## # ###### (C) 2019 Rene Eng +** # # # # # # # # LGPL +** #### ###### ###### # # # # +** +** +--*/ + + +// module to test header file include +#include "celma/format/size_handling.hpp" + + +// OS/C lib includes +#include + + +// C++ Standard Library includes +#include + + +// Boost includes +#define BOOST_TEST_MODULE SizeHandlingTest +#include + + +// project includes +#include "celma/test/check_return.hpp" + + +namespace { + + +/// Helper function to test the size formatting with streams and with the +/// printf()-like function. +/// +/// @tparam T The type of the value to format. +/// @param[in] value +/// The value to format. +/// @param[in] exp_result +/// The expected result of the formatting. +/// @return +/// \c false if the result of the formatting does not equal the given +/// expected result. +/// @since 1.24.0, 17.04.2019 +template< typename T> + bool checkFormatSize( const T& value, const std::string exp_result) +{ + + using celma::format::formatSize; + + // check with stream + std::ostringstream oss; + formatSize( oss, value); + CHECK_EQUAL_RETURN( exp_result, oss.str()); + + // check with printf format + char buffer[ 30]; + formatSize( buffer, value); + CHECK_EQUAL_RETURN( exp_result, buffer); + + return true; +} // checkFormatSize + + +} // namespace + + + +/// Test if div2unit() returns correct values. +/// +/// @since 1.24.0, 17.04.2019 +BOOST_AUTO_TEST_CASE( test_div2unit) +{ + + using celma::format::div2unit; + + + double testval = 0.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 0); + BOOST_REQUIRE_EQUAL( testval, 0.0); + + testval = 1.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 0); + BOOST_REQUIRE_EQUAL( testval, 1.0); + + testval = 1023.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 0); + BOOST_REQUIRE_EQUAL( testval, 1023.0); + + testval = 1024.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 1); + BOOST_REQUIRE_EQUAL( testval, 1.0); + + testval = 1025.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 1); + BOOST_REQUIRE_EQUAL( testval, 1025.0 / 1024.0); + + testval = 1024.0 * 1024.0 - 1; + BOOST_REQUIRE_EQUAL( div2unit( testval), 1); + BOOST_REQUIRE_EQUAL( testval, (1024.0 * 1024.0 - 1) / 1024.0); + + testval = 1024.0 * 1024.0; + BOOST_REQUIRE_EQUAL( div2unit( testval), 2); + BOOST_REQUIRE_EQUAL( testval, 1.0); + + testval = 1024.0 * 1024.0 + 1; + BOOST_REQUIRE_EQUAL( div2unit( testval), 2); + BOOST_REQUIRE_EQUAL( testval, (1024.0 * 1024.0 + 1) / 1024.0 / 1024.0); + +} // test_div2unit + + + +/// Test if numDivs2Name return correct values. +/// +/// @since 1.24.0, 17.04.2019 +BOOST_AUTO_TEST_CASE( test_numDivs2Name) +{ + + using celma::format::numDivs2Name; + + + BOOST_REQUIRE( ::strcmp( numDivs2Name( 0), "bytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 1), "kbytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 2), "Mbytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 3), "Gbytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 4), "Tbytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 5), "Pbytes") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 6), "Ebytes") == 0); + + BOOST_REQUIRE( ::strcmp( numDivs2Name( -1), "out of range") == 0); + BOOST_REQUIRE( ::strcmp( numDivs2Name( 7), "out of range") == 0); + +} // test_numDivs2Name + + + +/// Function formatSize() does the whole formatting. +/// +/// @since 1.24.0, 17.04.2019 +BOOST_AUTO_TEST_CASE( format_size) +{ + + BOOST_REQUIRE( checkFormatSize( 1000, "1000.0 bytes")); + BOOST_REQUIRE( checkFormatSize( 10000, " 9.8 kbytes")); + BOOST_REQUIRE( checkFormatSize( 100000, " 97.7 kbytes")); + BOOST_REQUIRE( checkFormatSize( 1000000, " 976.6 kbytes")); + BOOST_REQUIRE( checkFormatSize( 1024000, "1000.0 kbytes")); + BOOST_REQUIRE( checkFormatSize( 10000000, " 9.5 Mbytes")); + BOOST_REQUIRE( checkFormatSize( 100000000, " 95.4 Mbytes")); + BOOST_REQUIRE( checkFormatSize( 1000000000, " 953.7 Mbytes")); + BOOST_REQUIRE( checkFormatSize( 1048576000, "1000.0 Mbytes")); + BOOST_REQUIRE( checkFormatSize( 10000000000L, " 9.3 Gbytes")); + BOOST_REQUIRE( checkFormatSize( 100000000000L, " 93.1 Gbytes")); + BOOST_REQUIRE( checkFormatSize( 1000000000000L, " 931.3 Gbytes")); + BOOST_REQUIRE( checkFormatSize( 1073741824000L, "1000.0 Gbytes")); + BOOST_REQUIRE( checkFormatSize( 10000000000000L, " 9.1 Tbytes")); + +} // format_size + + + +// ===== END OF test_size_handling.cpp ===== + diff --git a/pool/shard007/C++/0095273_supervised_user_import_handler.cc b/pool/shard007/C++/0095273_supervised_user_import_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3cbf1165032408b69d3b9b897e455362b31e047 --- /dev/null +++ b/pool/shard007/C++/0095273_supervised_user_import_handler.cc @@ -0,0 +1,255 @@ +// 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 "chrome/browser/ui/webui/options/supervised_user_import_handler.h" + +#include + +#include "base/bind.h" +#include "base/prefs/pref_service.h" +#include "base/values.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_avatar_icon_util.h" +#include "chrome/browser/profiles/profile_info_cache.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" +#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/supervised_user/supervised_user_constants.h" +#include "chrome/browser/supervised_user/supervised_user_shared_settings_service.h" +#include "chrome/browser/supervised_user/supervised_user_shared_settings_service_factory.h" +#include "chrome/browser/supervised_user/supervised_user_sync_service.h" +#include "chrome/browser/supervised_user/supervised_user_sync_service_factory.h" +#include "chrome/common/pref_names.h" +#include "chrome/common/url_constants.h" +#include "chrome/grit/generated_resources.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "components/signin/core/browser/signin_error_controller.h" +#include "components/signin/core/browser/signin_manager.h" +#include "content/public/browser/web_ui.h" +#include "grit/theme_resources.h" + +namespace { + +scoped_ptr GetAvatarIcons() { + scoped_ptr avatar_icons(new base::ListValue); + for (size_t i = 0; i < profiles::GetDefaultAvatarIconCount(); ++i) { + std::string avatar_url = profiles::GetDefaultAvatarIconUrl(i); + avatar_icons->Append(new base::StringValue(avatar_url)); + } + + return avatar_icons.Pass(); +} + +} // namespace + +namespace options { + +SupervisedUserImportHandler::SupervisedUserImportHandler() + : observer_(this), + weak_ptr_factory_(this) {} + +SupervisedUserImportHandler::~SupervisedUserImportHandler() { + Profile* profile = Profile::FromWebUI(web_ui()); + if (!profile->IsSupervised()) { + SupervisedUserSyncService* service = + SupervisedUserSyncServiceFactory::GetForProfile(profile); + if (service) + service->RemoveObserver(this); + subscription_.reset(); + } +} + +void SupervisedUserImportHandler::GetLocalizedValues( + base::DictionaryValue* localized_strings) { + DCHECK(localized_strings); + + static OptionsStringResource resources[] = { + { "supervisedUserImportTitle", + IDS_IMPORT_EXISTING_SUPERVISED_USER_TITLE }, + { "supervisedUserImportText", IDS_IMPORT_EXISTING_SUPERVISED_USER_TEXT }, + { "createNewUserLink", IDS_CREATE_NEW_USER_LINK }, + { "supervisedUserImportOk", IDS_IMPORT_EXISTING_SUPERVISED_USER_OK }, + { "supervisedUserImportSigninError", + IDS_SUPERVISED_USER_IMPORT_SIGN_IN_ERROR }, + { "supervisedUserAlreadyOnThisDevice", + IDS_SUPERVISED_USER_ALREADY_ON_THIS_DEVICE }, + { "noExistingSupervisedUsers", IDS_SUPERVISED_USER_NO_EXISTING_ERROR }, + { "supervisedUserSelectAvatarTitle", + IDS_SUPERVISED_USER_SELECT_AVATAR_TITLE }, + { "supervisedUserSelectAvatarText", + IDS_SUPERVISED_USER_SELECT_AVATAR_TEXT }, + { "supervisedUserSelectAvatarOk", IDS_SUPERVISED_USER_SELECT_AVATAR_OK }, + }; + + RegisterStrings(localized_strings, resources, arraysize(resources)); + localized_strings->Set("avatarIcons", GetAvatarIcons().release()); +} + +void SupervisedUserImportHandler::InitializeHandler() { + Profile* profile = Profile::FromWebUI(web_ui()); + if (!profile->IsSupervised()) { + SupervisedUserSyncService* sync_service = + SupervisedUserSyncServiceFactory::GetForProfile(profile); + if (sync_service) { + sync_service->AddObserver(this); + observer_.Add(ProfileOAuth2TokenServiceFactory::GetForProfile(profile)-> + signin_error_controller()); + SupervisedUserSharedSettingsService* settings_service = + SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext( + profile); + subscription_ = settings_service->Subscribe( + base::Bind(&SupervisedUserImportHandler::OnSharedSettingChanged, + weak_ptr_factory_.GetWeakPtr())); + } else { + DCHECK(!SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext( + profile)); + DCHECK(!ProfileOAuth2TokenServiceFactory::GetForProfile(profile)); + } + } +} + +void SupervisedUserImportHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback("requestSupervisedUserImportUpdate", + base::Bind(&SupervisedUserImportHandler:: + RequestSupervisedUserImportUpdate, + base::Unretained(this))); +} + +void SupervisedUserImportHandler::OnSupervisedUsersChanged() { + FetchSupervisedUsers(); +} + +void SupervisedUserImportHandler::FetchSupervisedUsers() { + web_ui()->CallJavascriptFunction( + "options.SupervisedUserListData.resetPromise"); + RequestSupervisedUserImportUpdate(NULL); +} + +void SupervisedUserImportHandler::RequestSupervisedUserImportUpdate( + const base::ListValue* /* args */) { + if (Profile::FromWebUI(web_ui())->IsSupervised()) + return; + + if (!IsAccountConnected() || HasAuthError()) { + ClearSupervisedUsersAndShowError(); + } else { + SupervisedUserSyncService* supervised_user_sync_service = + SupervisedUserSyncServiceFactory::GetForProfile( + Profile::FromWebUI(web_ui())); + if (supervised_user_sync_service) { + supervised_user_sync_service->GetSupervisedUsersAsync( + base::Bind(&SupervisedUserImportHandler::SendExistingSupervisedUsers, + weak_ptr_factory_.GetWeakPtr())); + } + } +} + +void SupervisedUserImportHandler::SendExistingSupervisedUsers( + const base::DictionaryValue* dict) { + DCHECK(dict); + const ProfileInfoCache& cache = + g_browser_process->profile_manager()->GetProfileInfoCache(); + + // Collect the ids of local supervised user profiles. + std::set supervised_user_ids; + for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) { + if (cache.ProfileIsSupervisedAtIndex(i)) + supervised_user_ids.insert(cache.GetSupervisedUserIdOfProfileAtIndex(i)); + } + + base::ListValue supervised_users; + Profile* profile = Profile::FromWebUI(web_ui()); + SupervisedUserSharedSettingsService* service = + SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(profile); + for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { + const base::DictionaryValue* value = NULL; + bool success = it.value().GetAsDictionary(&value); + DCHECK(success); + std::string name; + value->GetString(SupervisedUserSyncService::kName, &name); + + base::DictionaryValue* supervised_user = new base::DictionaryValue; + supervised_user->SetString("id", it.key()); + supervised_user->SetString("name", name); + + int avatar_index = SupervisedUserSyncService::kNoAvatar; + const base::Value* avatar_index_value = + service->GetValue(it.key(), supervised_users::kChromeAvatarIndex); + if (avatar_index_value) { + success = avatar_index_value->GetAsInteger(&avatar_index); + } else { + // Check if there is a legacy avatar index stored. + std::string avatar_str; + value->GetString(SupervisedUserSyncService::kChromeAvatar, &avatar_str); + success = + SupervisedUserSyncService::GetAvatarIndex(avatar_str, &avatar_index); + } + DCHECK(success); + supervised_user->SetBoolean( + "needAvatar", + avatar_index == SupervisedUserSyncService::kNoAvatar); + + std::string supervised_user_icon = + std::string(chrome::kChromeUIThemeURL) + + "IDR_SUPERVISED_USER_PLACEHOLDER"; + std::string avatar_url = + avatar_index == SupervisedUserSyncService::kNoAvatar ? + supervised_user_icon : + profiles::GetDefaultAvatarIconUrl(avatar_index); + supervised_user->SetString("iconURL", avatar_url); + bool on_current_device = + supervised_user_ids.find(it.key()) != supervised_user_ids.end(); + supervised_user->SetBoolean("onCurrentDevice", on_current_device); + + supervised_users.Append(supervised_user); + } + + web_ui()->CallJavascriptFunction( + "options.SupervisedUserListData.receiveExistingSupervisedUsers", + supervised_users); +} + +void SupervisedUserImportHandler::ClearSupervisedUsersAndShowError() { + web_ui()->CallJavascriptFunction( + "options.SupervisedUserListData.onSigninError"); +} + +bool SupervisedUserImportHandler::IsAccountConnected() const { + Profile* profile = Profile::FromWebUI(web_ui()); + SigninManagerBase* signin_manager = + SigninManagerFactory::GetForProfile(profile); + return signin_manager && signin_manager->IsAuthenticated(); +} + +bool SupervisedUserImportHandler::HasAuthError() const { + Profile* profile = Profile::FromWebUI(web_ui()); + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile); + if (!token_service) + return true; + + SigninErrorController* error_controller = + token_service->signin_error_controller(); + + GoogleServiceAuthError::State state = error_controller->auth_error().state(); + + return state == GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS || + state == GoogleServiceAuthError::USER_NOT_SIGNED_UP || + state == GoogleServiceAuthError::ACCOUNT_DELETED || + state == GoogleServiceAuthError::ACCOUNT_DISABLED; +} + +void SupervisedUserImportHandler::OnSharedSettingChanged( + const std::string& supervised_user_id, + const std::string& key) { + if (key == supervised_users::kChromeAvatarIndex) + FetchSupervisedUsers(); +} + +void SupervisedUserImportHandler::OnErrorChanged() { + FetchSupervisedUsers(); +} + +} // namespace options diff --git a/pool/shard007/C++/0095274_test_AS_ALN_bruteforcedp.cpp b/pool/shard007/C++/0095274_test_AS_ALN_bruteforcedp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d6741e4c408bf49f684dca5ccd0258fc4e7d6fe --- /dev/null +++ b/pool/shard007/C++/0095274_test_AS_ALN_bruteforcedp.cpp @@ -0,0 +1,64 @@ +#include +#include "AS_global.H" +#include "AS_ALN_bruteforcedp.H" +#include "long_sequence_macro.H" + +int main() { + + //char *seq_a = "ACACACTAACACACT"; + //char *seq_b = "AGCACACAAGCACACA"; +// char *seq_a = LONGREADONE; +// char *seq_b = LONGREADTWO; + + char *seq_a = LONG_READ_ID_2; + char *seq_b = LONG_READ_ID_2; + + alignLinker_s al; + //dpCell M[AS_READ_MAX_NORMAL_LEN + 1][AS_READ_MAX_NORMAL_LEN + 1]; + + dpCell *M = (dpCell *) safe_calloc((AS_READ_MAX_NORMAL_LEN + 1) * (AS_READ_MAX_NORMAL_LEN + 1), sizeof(dpCell)); + + char *h_alignA = (char*) safe_calloc(2 * AS_READ_MAX_NORMAL_LEN + 2, sizeof(char)); + char *h_alignB = (char*) safe_calloc(2 * AS_READ_MAX_NORMAL_LEN + 2, sizeof(char)); + + +// for (int i = 0; i < 500; i++) { +// alignLinker_s aa; +// char h_alignA[AS_READ_MAX_NORMAL_LEN + AS_READ_MAX_NORMAL_LEN + 2] = {0}; +// char h_alignB[AS_READ_MAX_NORMAL_LEN + AS_READ_MAX_NORMAL_LEN + 2] = {0}; + +// alignLinker(h_alignA, +// h_alignB, +// seq_a, +// seq_b, +// M, +// &aa); +// al = aa; +// } + + for (int i = 0; i < 10; i++) { + alignLinker_s aa; + + alignLinker(h_alignA, + h_alignB, + seq_a, + seq_b, + (dpCell (*)[AS_READ_MAX_NORMAL_LEN + 1]) M, + &aa); + al = aa; + } + + printf("matches: %d\n", al.matches); + printf("alignLen: %d\n", al.alignLen); + printf("begI: %d\n", al.begI); + printf("begJ: %d\n", al.begJ); + printf("endI: %d\n", al.endI); + printf("endJ: %d\n", al.endJ); + printf("lenA: %d\n", al.lenA); + printf("lenB: %d\n", al.lenB); + printf("pIdentity: %f\n", al.pIdentity); + printf("pCoverageA: %f\n", al.pCoverageA); + printf("pCoverageB: %f\n", al.pCoverageB); + + return 0; +} diff --git a/pool/shard007/C++/0095275_AOChunk.cpp b/pool/shard007/C++/0095275_AOChunk.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32730072263cca63ea49ee0117dd33830eca172e --- /dev/null +++ b/pool/shard007/C++/0095275_AOChunk.cpp @@ -0,0 +1,126 @@ +#include "mmapwrapper.h" + +#include "AOChunk.hpp" +#include "global_metadata_heap.hpp" +#include "block_factory.hpp" + +AOChunk * AOChunk::_liveChunks[1ul<<(32-LOG_VALLOC_SIZE)]; + +AOChunk * AOChunk::fromPtr(LPCVOID ptr) { + AOChunk * bl = _liveChunks[(DWORD)ptr>>LOG_VALLOC_SIZE]; + + return bl; +} + +void * AOChunk::operator new(size_t sz) { + return GlobalMetadataHeap::getInstance()->New(sz); +} + +void AOChunk::operator delete(void * ptr) { + GlobalMetadataHeap::getInstance()->Delete(ptr); +} + + +AOChunk::AOChunk(size_t sz, size_t grain) : _sz(sz), _grain(grain), _numelts(sz/grain), + _pop(0), _ptr(0) { + //_start = (DWORD)VirtualAlloc(NULL, + // sz, + // MEM_RESERVE | MEM_COMMIT, + // PAGE_READWRITE); + + // this code isn't used right? + abort(); + + _start = (DWORD)HL::MmapWrapper::map(sz); + fprintf(stderr,"new chusdfnk: 0x%x, size %d\n",_start,sz); + + assert(_numelts <= 32); + + _elts = (AOCommon **)GlobalMetadataHeap::getInstance()->New(sizeof(PVOID)*_numelts,NULL,true); + + size_t chunkSpan = ((sz+VALLOC_GRAIN-1)/VALLOC_GRAIN); + + for(UINT i = 0; i < chunkSpan; i++) { + _liveChunks[((DWORD)_start>>LOG_VALLOC_SIZE) + i] = this; + } +} + +AOChunk::~AOChunk() { + GlobalMetadataHeap::getInstance()->Delete(_elts); + + assert(_liveChunks[(DWORD)_start>>LOG_VALLOC_SIZE]); + + size_t chunkSpan = ((_sz+VALLOC_GRAIN-1)/VALLOC_GRAIN); + + for(UINT i = 0; i < chunkSpan; i++) { + _liveChunks[((DWORD)_start>>LOG_VALLOC_SIZE) + i] = NULL; + } + + HL::MmapWrapper::unmap((PVOID)_start,_sz); + + //VirtualFree((LPVOID)_start,0,MEM_RELEASE); +} + +PVOID AOChunk::New(AOCommon * bl) { + DWORD ret; + + assert(_pop < _numelts); + + while(_used.test(_ptr)) { + _ptr++; + _ptr %= _numelts; + } + + _pop++; + ret = _start + _grain*_ptr; + _elts[_ptr] = bl; + + _used.set(_ptr); + + if(_pop == _numelts && _numelts > 1) { + // full, so remove from free list in block factory + BlockFactory::getInstance()->RemoveChunkFromList(this); + } + + return (PVOID)ret; +} + +size_t AOChunk::getIndex(LPCVOID ptr) { + char * cptr = (char *)ptr; + + cptr -= _start; + + size_t idx = (size_t)cptr / _grain; + assert(idx >= 0); + assert(idx < _numelts); + assert(_used.test(idx)); + + return idx; +} + +BOOL AOChunk::Delete(PVOID ptr) { + size_t idx = getIndex(ptr); + + _used.reset(idx); + _elts[idx] = NULL; + + if(_pop == _numelts && _numelts > 1) { + BlockFactory::getInstance()->AddChunkToList(this); + } + + _pop--; + + if(_pop == 0) { + if(_numelts > 1) + BlockFactory::getInstance()->RemoveChunkFromList(this); + delete this; + } + + return true; +} + +AOCommon * AOChunk::ptrToBlock(LPCVOID ptr) { + size_t idx = getIndex(ptr); + + return _elts[idx]; +} diff --git a/pool/shard007/C++/0095278_Parser.cpp b/pool/shard007/C++/0095278_Parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..322b08b9f439de09e854735861ed6dcee661cf10 --- /dev/null +++ b/pool/shard007/C++/0095278_Parser.cpp @@ -0,0 +1,135 @@ +/** + * @file Parser.cpp + * @date Mar 11, 2017 + * @author Lamar Simpson + * Copyright 2017 Lamar Simpson + *@brief Class that handles all input and parses it out into a format that Semantics class can use. + **@details implementation of Parser class. + */ +#include +#include +#include +#include +#include +#include +#include +#include + + +using std::cin; +using std::string; + +/** + * @brief Constructor Parser Class + */ +Parser::Parser() { + this->input = ""; +} + + +/** + * @brief setInput assigns a value to the Parser class member variable input. + * @param input std::string + */ + +void Parser::setInput(std::string input) { +this->input = input; +} + + /** + * @brief stringCoversion takes an input vector and returns string output + * @param input std::vector + * @return string + */ +std::string Parser::stringConversion(std::vector input) { +std::ostringstream oss; + +if(!input.empty()) { +std::copy(input.begin(), input.end(), +std::ostream_iterator(oss, " ")); +} + return oss.str(); +} + + + /** + * @brief Handles getting input from File exemplars or user specified files. + * @return std::vector that contains all input from files specified by the user or file exemplars. + */ + +std::vector Parser::getInput() { + string line; + string input = ""; + std::vector file; + + char c = std::cin.peek(); // peek character + + if (c == '\n') { + cin.ignore(); + } + + while ( getline(cin, line) ) { + if (line.empty()) + break; + std::stringstream ss(line); + string s; + + while (getline(ss, s, ' ')) { + file.push_back(s); + } + } + + return file; +} + + +/** + * @brief Handles getting input from File exemplars or user specified files. + * @return std::vector that contains all input from files specified by the user or file exemplars. + */ +std::vector Parser::getFileInput(std::string in ) { + // std::ifstream inputFile{"../Positive_Examples/Positive_Example_1.txt"}; + + std::ifstream inputFile{in}; + + + std::vector file; + + + // test file open + if (inputFile) { + string value; + + // read the elements in the file into a vector + while ( inputFile >> value ) { + file.push_back(value); + } + std::cin.clear(); + // input>>std:flush; + } + return file; +} + + + + /** + * @brief generateHistogram takes a input vector and counts the frequency of words in that input and return a map + * @param input std::vector + * @return map + */ +std::map Parser::generateHistogram(std::vector input) { +std::map histogram; + + for (const string & s : input) { ++histogram[s]; } + +/* + for (const auto & p : histogram) + { + std::cout << "Word '" << p.first << "' occurs " << p.second << " times.\n"; + } + */ + + return histogram; +} + + diff --git a/pool/shard007/C++/0095287_tcp_service.cc b/pool/shard007/C++/0095287_tcp_service.cc new file mode 100644 index 0000000000000000000000000000000000000000..f97a9ddf70c2fde5985504599cb4a5e2016b9a9b --- /dev/null +++ b/pool/shard007/C++/0095287_tcp_service.cc @@ -0,0 +1,133 @@ +/** +* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U +* +* This file is part of iotagent project. +* +* iotagent is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as published +* by the Free Software Foundation, either version 3 of the License, +* or (at your option) any later version. +* +* iotagent is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* See the GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with iotagent. If not, see http://www.gnu.org/licenses/. +* +* For those usages not covered by the GNU Affero General Public License +* please contact with iot_support at tid dot es +*/ + +#include "tcp_service.h" +#include "services/admin_service.h" +#include + +namespace iota { +extern std::string logger; +} + +iota::TcpService::TcpService(const boost::asio::ip::tcp::endpoint& endpoint): + pion::tcp::server(endpoint), m_logger(PION_GET_LOGGER(logger)) { +} + +iota::TcpService::~TcpService() {} + +boost::shared_ptr iota::TcpService::register_handler( + std::string client_name, + iota::TcpService::IotaRequestHandler client_handler) { + boost::shared_ptr your_tcp_service; + try { + c_handlers.insert(std::pair + (client_name, client_handler)); + your_tcp_service = shared_from_this(); + } + catch (std::exception& e) { + IOTA_LOG_ERROR(m_logger, e.what()); + } + return your_tcp_service; +} + +void iota::TcpService::handle_connection(pion::tcp::connection_ptr& tcp_conn) { + //tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_CLOSE); + tcp_conn->async_read_some(boost::bind( + &iota::TcpService::handle_read, + this, tcp_conn, + boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); +} + +void iota::TcpService::handle_read(pion::tcp::connection_ptr& tcp_conn, + const boost::system::error_code& read_error, + std::size_t bytes_read) { + IOTA_LOG_DEBUG(m_logger, + " read_error=" << read_error << " bytes_read=" << bytes_read); + std::string reading_buffer; + if (!read_error) { + std::string reading_buffer(tcp_conn->get_read_buffer().data(), + bytes_read); + print_buffer(reading_buffer, bytes_read); + } + + std::map::iterator it = + c_handlers.begin(); + while (it != c_handlers.end()) { + iota::TcpService::IotaRequestHandler h = it->second; + if (h) { + IOTA_LOG_DEBUG(m_logger, " client=" + it->first); + h(tcp_conn, reading_buffer, read_error); + } + ++it; + } + + //if (read_error) { + finish(tcp_conn); + //} + +}; + +void iota::TcpService::send_response(pion::tcp::connection_ptr& tcp_conn, + std::string& buffer_response, + bool close_connection) { + + print_buffer(buffer_response, buffer_response.size()); + // TODO ¿Pueden mezclarse? + if (tcp_conn->is_open()) { + tcp_conn->async_write(boost::asio::buffer(buffer_response.data(), + buffer_response.size()), + boost::bind(&iota::TcpService::finish, this, tcp_conn, close_connection)); + } + else { + IOTA_LOG_ERROR(m_logger, "Connection is closed"); + } + +} + + +void iota::TcpService::print_buffer(std::string& buffer, int bytes_read) { + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (int i = 0; i < bytes_read; ++i) { + ss << std::setw(2) << static_cast(buffer[i]); + } + IOTA_LOG_DEBUG(m_logger, ss.str()); +} + +void iota::TcpService::finish(pion::tcp::connection_ptr& tcp_conn, + bool close_connection) { + if (close_connection) { + tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_CLOSE); + tcp_conn->finish(); + IOTA_LOG_DEBUG(m_logger, "finish connection " << tcp_conn.use_count()); + } +} + +void iota::TcpService::close_connection(pion::tcp::connection_ptr& tcp_conn) { + finish(tcp_conn); +} + + + + + diff --git a/pool/shard007/C++/0095288_dungeonworld.cpp b/pool/shard007/C++/0095288_dungeonworld.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e3bf48fc0deccecbf7da2a530f838ad3d634164 --- /dev/null +++ b/pool/shard007/C++/0095288_dungeonworld.cpp @@ -0,0 +1,66 @@ +#include "dungeonworld.hpp" +#include + +/*DungeonWorld::DungeonWorld() { + +}*/ + +bool DungeonWorld::DiceRoll(float probability) { + int myRand = rand() % 100 + 1; + if (myRand <= static_cast(probability * 100)) { + return true; + } + + return false; +} + +void DungeonWorld::Generate(float density) { + //generate some noise + for (int y = 0; y < m_terrainMap.Height(); y++) { + for (int x = 0; x < m_terrainMap.Width(); x++) { + if (DiceRoll(density)) { + m_terrainMap.Set(x, y, '#'); + } + } + } + + //now join the noise in to more coherent walls and rooms + for (int y = 0; y < m_terrainMap.Height(); y++) { + for (int x = 0; x < m_terrainMap.Width(); x++) { + + //generate horizontal walls + if (m_terrainMap.Get(x - 1, y) == '#' || m_terrainMap.Get(x + 1, y) == '#' ) { + if (DiceRoll(density * 2)) { + m_terrainMap.Set(x, y, '#'); + } + } + + //generate vertical walls + if (m_terrainMap.Get(x, y - 1) == '#' || m_terrainMap.Get(x, y + 1) == '#' ) { + if (DiceRoll(density * 2)) { + m_terrainMap.Set(x, y, '#'); + } + } + } + } + + //done! +} + +void DungeonWorld::Render() { + m_renderMap = m_terrainMap; + for (int i = 0; i < m_characterList.size(); i++) + { + if (isprint(m_characterList[i]->Representation())) { + m_renderMap.Set(m_characterList[i]->GetPos().x, + m_characterList[i]->GetPos().y, + m_characterList[i]->Representation()); + } + } + m_renderMap.Display(); +} + +void DungeonWorld::Update() +{ + +} \ No newline at end of file diff --git a/pool/shard007/C++/0095289_mojo_host_resolver_impl.cc b/pool/shard007/C++/0095289_mojo_host_resolver_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf49c99ff1bfe0c00979a3adcc42268e485a2f52 --- /dev/null +++ b/pool/shard007/C++/0095289_mojo_host_resolver_impl.cc @@ -0,0 +1,136 @@ +// 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 "net/dns/mojo_host_resolver_impl.h" + +#include + +#include "base/stl_util.h" +#include "net/base/address_list.h" +#include "net/base/net_errors.h" +#include "net/dns/host_resolver.h" +#include "net/dns/mojo_host_type_converters.h" + +namespace net { + +// Handles host resolution for a single request and sends a response when done. +// Also detects connection errors for HostResolverRequestClient and cancels the +// outstanding resolve request. Owned by MojoHostResolverImpl. +class MojoHostResolverImpl::Job { + public: + Job(MojoHostResolverImpl* resolver_service, + net::HostResolver* resolver, + const net::HostResolver::RequestInfo& request_info, + const BoundNetLog& net_log, + interfaces::HostResolverRequestClientPtr client); + ~Job(); + + void Start(); + + private: + // Completion callback for the HostResolver::Resolve request. + void OnResolveDone(int result); + + // Mojo error handler. + void OnConnectionError(); + + MojoHostResolverImpl* resolver_service_; + net::HostResolver* resolver_; + net::HostResolver::RequestInfo request_info_; + const BoundNetLog net_log_; + interfaces::HostResolverRequestClientPtr client_; + net::HostResolver::RequestHandle handle_; + AddressList result_; + base::ThreadChecker thread_checker_; +}; + +MojoHostResolverImpl::MojoHostResolverImpl(net::HostResolver* resolver, + const BoundNetLog& net_log) + : resolver_(resolver), net_log_(net_log) { +} + +MojoHostResolverImpl::~MojoHostResolverImpl() { + DCHECK(thread_checker_.CalledOnValidThread()); + STLDeleteElements(&pending_jobs_); +} + +void MojoHostResolverImpl::Resolve( + interfaces::HostResolverRequestInfoPtr request_info, + interfaces::HostResolverRequestClientPtr client) { + DCHECK(thread_checker_.CalledOnValidThread()); + Job* job = new Job(this, resolver_, + request_info->To(), + net_log_, std::move(client)); + pending_jobs_.insert(job); + job->Start(); +} + +void MojoHostResolverImpl::DeleteJob(Job* job) { + DCHECK(thread_checker_.CalledOnValidThread()); + size_t num_erased = pending_jobs_.erase(job); + DCHECK(num_erased); + delete job; +} + +MojoHostResolverImpl::Job::Job( + MojoHostResolverImpl* resolver_service, + net::HostResolver* resolver, + const net::HostResolver::RequestInfo& request_info, + const BoundNetLog& net_log, + interfaces::HostResolverRequestClientPtr client) + : resolver_service_(resolver_service), + resolver_(resolver), + request_info_(request_info), + net_log_(net_log), + client_(std::move(client)), + handle_(nullptr) { + client_.set_connection_error_handler(base::Bind( + &MojoHostResolverImpl::Job::OnConnectionError, base::Unretained(this))); +} + +void MojoHostResolverImpl::Job::Start() { + DVLOG(1) << "Resolve " << request_info_.host_port_pair().ToString(); + int result = + resolver_->Resolve(request_info_, DEFAULT_PRIORITY, &result_, + base::Bind(&MojoHostResolverImpl::Job::OnResolveDone, + base::Unretained(this)), + &handle_, net_log_); + + if (result != ERR_IO_PENDING) + OnResolveDone(result); +} + +MojoHostResolverImpl::Job::~Job() { + DCHECK(thread_checker_.CalledOnValidThread()); + if (handle_) + resolver_->CancelRequest(handle_); +} + +void MojoHostResolverImpl::Job::OnResolveDone(int result) { + DCHECK(thread_checker_.CalledOnValidThread()); + handle_ = nullptr; + DVLOG(1) << "Resolved " << request_info_.host_port_pair().ToString() + << " with error " << result << " and " << result_.size() + << " results!"; + for (const auto& address : result_) { + DVLOG(1) << address.ToString(); + } + if (result == OK) + client_->ReportResult(result, interfaces::AddressList::From(result_)); + else + client_->ReportResult(result, nullptr); + + resolver_service_->DeleteJob(this); +} + +void MojoHostResolverImpl::Job::OnConnectionError() { + DCHECK(thread_checker_.CalledOnValidThread()); + // |resolver_service_| should always outlive us. + DCHECK(resolver_service_); + DVLOG(1) << "Connection error on request for " + << request_info_.host_port_pair().ToString(); + resolver_service_->DeleteJob(this); +} + +} // namespace net diff --git a/pool/shard007/C++/0095292_range.cpp b/pool/shard007/C++/0095292_range.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d818c34b98771c293228034b63642be99a556a52 --- /dev/null +++ b/pool/shard007/C++/0095292_range.cpp @@ -0,0 +1,144 @@ +/* + * 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 +#include +#include "range.h" +#include "stringutil.h" + + +using namespace std; +using namespace essentia; + +bool Everything::contains(const Parameter& param) const { + return true; +} + +Range* Range::create(const std::string& s) { + if (s.empty()) { + return new Everything; + } + else if (s[0] == '[' || s[0] == '(') { + return new Interval(s); + } + else if (s[0] == '{') { + return new Set(s); + } + else { + throw EssentiaException("Invalid range '" + s + "' for parameter. Should contain '[]', '()' or '{}' to specify the range of given parameter."); + } +} + +Interval::Interval(const string& strrange) { + string s = strrange; + + if(strrange.find_first_of(' ') != std::string::npos) { + throw EssentiaException("Invalid interval, should not contain space characters"); + } + + string::size_type idx = s.find(","); + if (idx == string::npos) { + throw EssentiaException("Invalid interval, should contain the ',' symbol to separate both ends of the interval"); + } + + string sleft = toLower(s.substr(0, idx)); + string sright = toLower(s.substr(idx+1)); + + if (sleft[0] == '[') { + _lincluded = true; + } + else if (sleft[0] == '(') { + _lincluded = false; + } + else { + throw EssentiaException("Invalid interval, should contain the '[' or '(' as first character"); + } + + int endIdx = sright.size()-1; + if (sright[endIdx] == ')') { + _uincluded = false; + } + else if (sright[endIdx] == ']') { + _uincluded = true; + } + else { + throw EssentiaException("Invalid interval, should contain the ']' or ')' as last character"); + } + + sleft = sleft.substr(1); + sright = sright.substr(0, sright.size()-1); + + if (sleft == "-inf") { + _lbound = false; + } + else { + _lbound = true; + std::istringstream isleft(sleft); + isleft.imbue(std::locale("C")); + isleft >> _lvalue; + } + + if (sright == "inf") { + _ubound = false; + } + else { + _ubound = true; + std::istringstream isright(sright); + isright.imbue(std::locale("C")); + isright >> _uvalue; + } +} + +bool Interval::contains(const Parameter& param) const { + Real value = param.toReal(); + + if (_lbound) { + if (_lincluded && !(value >= _lvalue)) return false; + if (!_lincluded && !(value > _lvalue)) return false; + } + + if (_ubound) { + if (_uincluded && !(value <= _uvalue)) return false; + if (!_uincluded && !(value < _uvalue)) return false; + } + + return true; +} + +Set::Set(const string& srange) { + if (srange[0] != '{') { + throw EssentiaException("Invalid set, should contain the '{' as first character"); + } + if (srange[srange.size() - 1] != '}') { + throw EssentiaException("Invalid set, should contain the '}' as last character"); + } + + string s = srange.substr(1, srange.size() - 2); + + if (s.empty()) { + throw EssentiaException("Invalid set, mustn't be empty"); + } + + vector elems = tokenize(s, ","); + _elements = set(elems.begin(), elems.end()); +} + +bool Set::contains(const Parameter& param) const { + return _elements.find(param.toString()) != _elements.end(); +} diff --git a/pool/shard007/C++/0095293_land_detector.cpp b/pool/shard007/C++/0095293_land_detector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3391d32dee3a34802458ca0180d4c5cf6daea239 --- /dev/null +++ b/pool/shard007/C++/0095293_land_detector.cpp @@ -0,0 +1,69 @@ +/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- + +#include "Sub.h" +#define LAND_END_DEPTH -20 //Landed at 20cm depth + +// Code to detect a crash main ArduCopter code +#define LAND_CHECK_ANGLE_ERROR_DEG 30.0f // maximum angle error to be considered landing +#define LAND_CHECK_LARGE_ANGLE_CD 1500.0f // maximum angle target to be considered landing +#define LAND_CHECK_ACCEL_MOVING 3.0f // maximum acceleration after subtracting gravity + +// counter to verify landings +static uint32_t land_detector_count = 0; + +// run land and crash detectors +// called at MAIN_LOOP_RATE +void Sub::update_land_and_crash_detectors() +{ + // update 1hz filtered acceleration + Vector3f accel_ef = ahrs.get_accel_ef_blended(); + accel_ef.z += GRAVITY_MSS; + land_accel_ef_filter.apply(accel_ef, MAIN_LOOP_SECONDS); + + update_land_detector(); + + crash_check(); +} + +// update_land_detector - checks if we have landed and updates the ap.land_complete flag +// called at MAIN_LOOP_RATE +void Sub::update_land_detector() +{ +// if(barometer.num_instances() > 1 && barometer.get_altitude() > LAND_END_DEPTH && ap.throttle_zero) { +// set_land_complete(true); +// } else { + set_land_complete(false); +// } +} + +void Sub::set_land_complete(bool b) +{ + // if no change, exit immediately + if( ap.land_complete == b ) + return; + + land_detector_count = 0; + + if(b){ + Log_Write_Event(DATA_LAND_COMPLETE); + } else { + Log_Write_Event(DATA_NOT_LANDED); + } + ap.land_complete = b; + + // trigger disarm-on-land if configured + bool disarm_on_land_configured = (g.throttle_behavior & THR_BEHAVE_DISARM_ON_LAND_DETECT) != 0; + bool mode_disarms_on_land = mode_allows_arming(control_mode,false) && !mode_has_manual_throttle(control_mode); + + if (ap.land_complete && motors.armed() && disarm_on_land_configured && mode_disarms_on_land) { + init_disarm_motors(); + } +} + +// update_throttle_thr_mix - sets motors throttle_low_comp value depending upon vehicle state +// low values favour pilot/autopilot throttle over attitude control, high values favour attitude control over throttle +// has no effect when throttle is above hover throttle +void Sub::update_throttle_thr_mix() +{ + return; // placeholder, was used by heli only +} diff --git a/pool/shard007/C++/0095298_multi_node_edit.cpp b/pool/shard007/C++/0095298_multi_node_edit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd4a4334fcc6a210f2bc734fd03856263b242300 --- /dev/null +++ b/pool/shard007/C++/0095298_multi_node_edit.cpp @@ -0,0 +1,194 @@ +/*************************************************************************/ +/* multi_node_edit.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "multi_node_edit.h" + +#include "core/math/math_fieldwise.h" +#include "editor_node.h" + +bool MultiNodeEdit::_set(const StringName &p_name, const Variant &p_value) { + return _set_impl(p_name, p_value, ""); +} + +bool MultiNodeEdit::_set_impl(const StringName &p_name, const Variant &p_value, const String &p_field) { + Node *es = EditorNode::get_singleton()->get_edited_scene(); + if (!es) { + return false; + } + + String name = p_name; + + if (name == "scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name + name = "script"; + } + + UndoRedo *ur = EditorNode::get_undo_redo(); + + ur->create_action(TTR("MultiNode Set") + " " + String(name), UndoRedo::MERGE_ENDS); + for (const NodePath &E : nodes) { + if (!es->has_node(E)) { + continue; + } + + Node *n = es->get_node(E); + if (!n) { + continue; + } + + if (p_value.get_type() == Variant::NODE_PATH) { + Node *tonode = n->get_node(p_value); + NodePath p_path = n->get_path_to(tonode); + ur->add_do_property(n, name, p_path); + } else { + Variant new_value; + if (p_field == "") { + // whole value + new_value = p_value; + } else { + // only one field + new_value = fieldwise_assign(n->get(name), p_value, p_field); + } + ur->add_do_property(n, name, new_value); + } + + ur->add_undo_property(n, name, n->get(name)); + } + ur->add_do_method(EditorNode::get_singleton()->get_inspector(), "refresh"); + ur->add_undo_method(EditorNode::get_singleton()->get_inspector(), "refresh"); + + ur->commit_action(); + return true; +} + +bool MultiNodeEdit::_get(const StringName &p_name, Variant &r_ret) const { + Node *es = EditorNode::get_singleton()->get_edited_scene(); + if (!es) { + return false; + } + + String name = p_name; + if (name == "scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name + name = "script"; + } + + for (const NodePath &E : nodes) { + if (!es->has_node(E)) { + continue; + } + + const Node *n = es->get_node(E); + if (!n) { + continue; + } + + bool found; + r_ret = n->get(name, &found); + if (found) { + return true; + } + } + + return false; +} + +void MultiNodeEdit::_get_property_list(List *p_list) const { + HashMap usage; + + Node *es = EditorNode::get_singleton()->get_edited_scene(); + if (!es) { + return; + } + + int nc = 0; + + List data_list; + + for (const NodePath &E : nodes) { + if (!es->has_node(E)) { + continue; + } + + Node *n = es->get_node(E); + if (!n) { + continue; + } + + List plist; + n->get_property_list(&plist, true); + + for (const PropertyInfo &F : plist) { + if (F.name == "script") { + continue; //added later manually, since this is intercepted before being set (check Variant Object::get() ) + } + if (!usage.has(F.name)) { + PLData pld; + pld.uses = 0; + pld.info = F; + usage[F.name] = pld; + data_list.push_back(usage.getptr(F.name)); + } + + // Make sure only properties with the same exact PropertyInfo data will appear + if (usage[F.name].info == F) { + usage[F.name].uses++; + } + } + + nc++; + } + + for (const PLData *E : data_list) { + if (nc == E->uses) { + p_list->push_back(E->info); + } + } + + p_list->push_back(PropertyInfo(Variant::OBJECT, "scripts", PROPERTY_HINT_RESOURCE_TYPE, "Script")); +} + +void MultiNodeEdit::add_node(const NodePath &p_node) { + nodes.push_back(p_node); +} + +int MultiNodeEdit::get_node_count() const { + return nodes.size(); +} + +NodePath MultiNodeEdit::get_node(int p_index) const { + ERR_FAIL_INDEX_V(p_index, nodes.size(), NodePath()); + return nodes[p_index]; +} + +void MultiNodeEdit::set_property_field(const StringName &p_property, const Variant &p_value, const String &p_field) { + _set_impl(p_property, p_value, p_field); +} + +MultiNodeEdit::MultiNodeEdit() { +} diff --git a/pool/shard007/C++/0095305_MeteorTowerShopItem.cpp b/pool/shard007/C++/0095305_MeteorTowerShopItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1470109b156f7e0cdf40c2adbaa7b8bf85863750 --- /dev/null +++ b/pool/shard007/C++/0095305_MeteorTowerShopItem.cpp @@ -0,0 +1,100 @@ +#include "MeteorTowerShopItem.h" +#include "Player.h" +#include "GUISystem.h" +#include +#include "ArenaHeap.h" +#include "TowerCreationTool.h" +#include "ToolManager.h" +#include "Container.h" +#include "Label.h" + +MeteorTowerShopItem::MeteorTowerShopItem(void) +{ + +} + + +MeteorTowerShopItem::~MeteorTowerShopItem(void) +{ + +} + + +void MeteorTowerShopItem::updateState(PlayerStat & stat) +{ + if(stat.gold < itemCost) + { + state = UNACTIVE; + button->loadImageFromFile("Data/ShopImages/meteorTurretUnavailable.png"); + } + else + { + state = ACTIVE; + button->loadImageFromFile("Data/ShopImages/meteorTurret.png"); + } + + button->setWidth(buttonW); + button->setHeight(buttonH); +} + +void MeteorTowerShopItem::init() +{ + initGUI("Meteor Tower","Data/ShopImages/meteorTurret.png"); + button->subsribeEvent(PRESS,new MemberSubsciber(&MeteorTowerShopItem::onClick,this)); + + tower = ArenaHeap::getPtr()->MeteorTowers.New(); + + tower->init(); +} + +void MeteorTowerShopItem::onDestroy() +{ + destroyGUI(); + + tower->destroy(); + ArenaHeap::getPtr()->MeteorTowers.Delete(tower); +} + + +void MeteorTowerShopItem::onClick(Widget * sender) +{ + if(state == ACTIVE) + { + TowerCreationTool * tool = new TowerCreationTool(); + tool->setTower(tower); + tool->setTowerCost(itemCost); + + ToolManager::getPtr()->setActiveTool(tool); + } +} + +void MeteorTowerShopItem::setSplashDamage(double damage) +{ + tower->setDamageValue(damage); +} + +void MeteorTowerShopItem::setAmmoSpeed(int speed) +{ + tower->setAmmoSpeed(speed); +} + +void MeteorTowerShopItem::setTowerRange(double range) +{ + tower->setRangeValue(range); +} + +void MeteorTowerShopItem::setShootRate(int ms) +{ + tower->setShootRate(ms); +} + +void MeteorTowerShopItem::setSplashRange(int range) +{ + tower->setSplashRange(range); +} + +void MeteorTowerShopItem::postPropertySet() +{ + ic.init(itemCost,tower); + ic.attach(info); +} diff --git a/pool/shard007/C++/0095306_process.cc b/pool/shard007/C++/0095306_process.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3c8ae448bcd170aa12f13ddc2e260e4c9b7893e --- /dev/null +++ b/pool/shard007/C++/0095306_process.cc @@ -0,0 +1,95 @@ +/* + * (C) 2007-2010 Taobao Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * + * Version: $Id$ + * + * Authors: + * duolong + * + */ + +#include "process.h" + +namespace tbsys { + +/** + * ÆðÒ»¸öÊØ»¤½ø³Ì, ·µ»ØÊØ»¤½ø³ÌID + */ +int CProcess::startDaemon(const char* szPidFile, const char* szLogFile) { + if (getppid() == 1) { + return 0; + } + + int pid = fork(); + if (pid < 0) exit(1); + if (pid > 0) return pid; + + writePidFile(szPidFile); + + int fd = open("/dev/null", 0); + if (fd != -1) { + dup2(fd, 0); + close(fd); + } + + TBSYS_LOGGER.setFileName(szLogFile); + + return pid; +} + +/** + * дpidÎļþ + */ +void CProcess::writePidFile(const char* szPidFile) { + char str[32]; + int lfp = open(szPidFile, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (lfp < 0) exit(1); + if (lockf(lfp, F_TLOCK, 0) < 0) { + fprintf(stderr, "Can't Open Pid File: %s", szPidFile); + exit(0); + } + sprintf(str, "%d\n", getpid()); + ssize_t len = strlen(str); + ssize_t ret = write(lfp, str, len); + if (ret != len) { + fprintf(stderr, "Can't Write Pid File: %s", szPidFile); + exit(0); + } + close(lfp); +} + +/** + * ÅжϽø³ÌÊÇ·ñ»¹»î×Å + * + * »î×Å: ·Ç0 + * ËÀµô: 0 + */ +int CProcess::existPid(const char* szPidFile) { + char buffer[64], *p; + int otherpid = 0, lfp; + lfp = open(szPidFile, O_RDONLY, 0); + if (lfp >= 0) { + ssize_t __attribute__((unused)) ret = read(lfp, buffer, 64); + close(lfp); + buffer[63] = '\0'; + p = strchr(buffer, '\n'); + if (p != NULL) + *p = '\0'; + otherpid = atoi(buffer); + } + if (otherpid > 0) { + if (kill(otherpid, 0) != 0) { + otherpid = 0; + } + } + return otherpid; +} +} + +/*END*/ + diff --git a/pool/shard007/C++/0095309_CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63a.cpp b/pool/shard007/C++/0095309_CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa201dfcca10839e6e1ecfebaa11e2dec59f4cd0 --- /dev/null +++ b/pool/shard007/C++/0095309_CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63a.cpp @@ -0,0 +1,122 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63a.cpp +Label Definition File: CWE23_Relative_Path_Traversal.label.xml +Template File: sources-sink-63a.tmpl.cpp +*/ +/* + * @description + * CWE: 23 Relative Path Traversal + * BadSource: console Read input from the console + * GoodSource: Use a fixed file name + * Sinks: ofstream + * BadSink : Open the file named in data using ofstream::open() + * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#define BASEPATH L"c:\\temp\\" +#else +#include +#define BASEPATH L"/tmp/" +#endif + +#include +using namespace std; + +namespace CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(wchar_t * * dataPtr); + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (FILENAME_MAX-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + badSink(&data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(wchar_t * * data); + +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + /* FIX: Use a fixed file name */ + wcscat(data, L"file.txt"); + goodG2BSink(&data); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE23_Relative_Path_Traversal__wchar_t_console_ofstream_63; /* 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/shard007/C++/0095311_quic_uint128_impl_unittest.cc b/pool/shard007/C++/0095311_quic_uint128_impl_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b3b99b1fe37a5f6dc052919780f9204368388c4 --- /dev/null +++ b/pool/shard007/C++/0095311_quic_uint128_impl_unittest.cc @@ -0,0 +1,191 @@ +// 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 + +#include "net/third_party/quic/platform/impl/quic_uint128_impl.h" +#include "starboard/types.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace quic { + +namespace test { + +constexpr QuicUint128Impl kuint128max(std::numeric_limits::max(), + std::numeric_limits::max()); + +TEST(Int128, AllTests) { + QuicUint128Impl zero(0); + QuicUint128Impl one(1); + QuicUint128Impl one_2arg(0, 1); + QuicUint128Impl two(0, 2); + QuicUint128Impl three(0, 3); + QuicUint128Impl big(2000, 2); + QuicUint128Impl big_minus_one(2000, 1); + QuicUint128Impl bigger(2001, 1); + QuicUint128Impl biggest(kuint128max); + QuicUint128Impl high_low(1, 0); + QuicUint128Impl low_high(0, std::numeric_limits::max()); + EXPECT_LT(one, two); + EXPECT_GT(two, one); + EXPECT_LT(one, big); + EXPECT_LT(one, big); + EXPECT_EQ(one, one_2arg); + EXPECT_NE(one, two); + EXPECT_GT(big, one); + EXPECT_GE(big, two); + EXPECT_GE(big, big_minus_one); + EXPECT_GT(big, big_minus_one); + EXPECT_LT(big_minus_one, big); + EXPECT_LE(big_minus_one, big); + EXPECT_NE(big_minus_one, big); + EXPECT_LT(big, biggest); + EXPECT_LE(big, biggest); + EXPECT_GT(biggest, big); + EXPECT_GE(biggest, big); + EXPECT_EQ(big, ~~big); + EXPECT_EQ(one, one | one); + EXPECT_EQ(big, big | big); + EXPECT_EQ(one, one | zero); + EXPECT_EQ(one, one & one); + EXPECT_EQ(big, big & big); + EXPECT_EQ(zero, one & zero); + EXPECT_EQ(zero, big & ~big); + EXPECT_EQ(zero, one ^ one); + EXPECT_EQ(zero, big ^ big); + EXPECT_EQ(one, one ^ zero); + EXPECT_EQ(big, big << 0); + EXPECT_EQ(big, big >> 0); + EXPECT_GT(big << 1, big); + EXPECT_LT(big >> 1, big); + EXPECT_EQ(big, (big << 10) >> 10); + EXPECT_EQ(big, (big >> 1) << 1); + EXPECT_EQ(one, (one << 80) >> 80); + EXPECT_EQ(zero, (one >> 80) << 80); + EXPECT_EQ(zero, big >> 128); + EXPECT_EQ(zero, big << 128); + EXPECT_EQ(QuicUint128High64Impl(biggest), + std::numeric_limits::max()); + EXPECT_EQ(QuicUint128Low64Impl(biggest), + std::numeric_limits::max()); + EXPECT_EQ(zero + one, one); + EXPECT_EQ(one + one, two); + EXPECT_EQ(big_minus_one + one, big); + EXPECT_EQ(one - one, zero); + EXPECT_EQ(one - zero, one); + EXPECT_EQ(zero - one, biggest); + EXPECT_EQ(big - big, zero); + EXPECT_EQ(big - one, big_minus_one); + EXPECT_EQ(big + std::numeric_limits::max(), bigger); + EXPECT_EQ(biggest + 1, zero); + EXPECT_EQ(zero - 1, biggest); + EXPECT_EQ(high_low - one, low_high); + EXPECT_EQ(low_high + one, high_low); + EXPECT_EQ(QuicUint128High64Impl((QuicUint128Impl(1) << 64) - 1), 0u); + EXPECT_EQ(QuicUint128Low64Impl((QuicUint128Impl(1) << 64) - 1), + std::numeric_limits::max()); + EXPECT_TRUE(!!one); + EXPECT_TRUE(!!high_low); + EXPECT_FALSE(!!zero); + EXPECT_FALSE(!one); + EXPECT_FALSE(!high_low); + EXPECT_TRUE(!zero); + EXPECT_TRUE(zero == 0); + EXPECT_FALSE(zero != 0); + EXPECT_FALSE(one == 0); + EXPECT_TRUE(one != 0); + + QuicUint128Impl test = zero; + EXPECT_EQ(++test, one); + EXPECT_EQ(test, one); + EXPECT_EQ(test++, one); + EXPECT_EQ(test, two); + EXPECT_EQ(test -= 2, zero); + EXPECT_EQ(test, zero); + EXPECT_EQ(test += 2, two); + EXPECT_EQ(test, two); + EXPECT_EQ(--test, one); + EXPECT_EQ(test, one); + EXPECT_EQ(test--, one); + EXPECT_EQ(test, zero); + EXPECT_EQ(test |= three, three); + EXPECT_EQ(test &= one, one); + EXPECT_EQ(test ^= three, two); + EXPECT_EQ(test >>= 1, one); + EXPECT_EQ(test <<= 1, two); + + EXPECT_EQ(big, -(-big)); + EXPECT_EQ(two, -((-one) - 1)); + EXPECT_EQ(kuint128max, -one); + EXPECT_EQ(zero, -zero); +} + +TEST(Int128, OperatorAssignReturnRef) { + QuicUint128Impl v(1); + (v += 4) -= 3; + EXPECT_EQ(2, v); +} + +TEST(Int128, Multiply) { + QuicUint128Impl a, b, c; + + // Zero test. + a = 0; + b = 0; + c = a * b; + EXPECT_EQ(0, c); + + // Max carries. + a = QuicUint128Impl(0) - 1; + b = QuicUint128Impl(0) - 1; + c = a * b; + EXPECT_EQ(1, c); + + // Self-operation with max carries. + c = QuicUint128Impl(0) - 1; + c *= c; + EXPECT_EQ(1, c); + + // 1-bit x 1-bit. + for (int i = 0; i < 64; ++i) { + for (int j = 0; j < 64; ++j) { + a = QuicUint128Impl(1) << i; + b = QuicUint128Impl(1) << j; + c = a * b; + EXPECT_EQ(QuicUint128Impl(1) << (i + j), c); + } + } + + // Verified with dc. + a = QuicUint128Impl(0xffffeeeeddddccccULL, 0xbbbbaaaa99998888ULL); + b = QuicUint128Impl(0x7777666655554444ULL, 0x3333222211110000ULL); + c = a * b; + EXPECT_EQ(QuicUint128Impl(0x530EDA741C71D4C3ULL, 0xBF25975319080000ULL), c); + EXPECT_EQ(0, c - b * a); + EXPECT_EQ(a * a - b * b, (a + b) * (a - b)); + + // Verified with dc. + a = QuicUint128Impl(0x0123456789abcdefULL, 0xfedcba9876543210ULL); + b = QuicUint128Impl(0x02468ace13579bdfULL, 0xfdb97531eca86420ULL); + c = a * b; + EXPECT_EQ(QuicUint128Impl(0x97a87f4f261ba3f2ULL, 0x342d0bbf48948200ULL), c); + EXPECT_EQ(0, c - b * a); + EXPECT_EQ(a * a - b * b, (a + b) * (a - b)); +} + +TEST(Int128, AliasTests) { + QuicUint128Impl x1(1, 2); + QuicUint128Impl x2(2, 4); + x1 += x1; + EXPECT_EQ(x2, x1); + + QuicUint128Impl x3(1, 1ull << 63); + QuicUint128Impl x4(3, 0); + x3 += x3; + EXPECT_EQ(x4, x3); +} + +} // namespace test + +} // namespace quic diff --git a/pool/shard007/C++/0095315_AbstractObjectSerializer.cpp b/pool/shard007/C++/0095315_AbstractObjectSerializer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60166e2fea6231e640e790464380bfdcda15ab5f --- /dev/null +++ b/pool/shard007/C++/0095315_AbstractObjectSerializer.cpp @@ -0,0 +1,183 @@ +/* The Butterfly Effect + * This file copyright (C) 2009 Klaas van Gend + * + * 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 + * applicable version is GPL version 2 only. + + * 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-1335, USA. + */ + +#include "AbstractObjectSerializer.h" +#include + +#include + +// these are all declared in Level.cpp +extern const char *theObjectString; +extern const char *theWidthAttributeString; +extern const char *theHeightAttributeString; +extern const char *theXAttributeString; +extern const char *theYAttributeString; +extern const char *theAngleAttributeString; +extern const char *theTypeAttributeString; +extern const char *theIDAttributeString; +extern const char *thePropertyString; +extern const char *theToolTipString; + +AbstractObjectSerializer::AbstractObjectSerializer(const AbstractObjectPtr anObjectPtr) + : theAbstractObjectPtr(anObjectPtr) +{ +} + + +void +AbstractObjectSerializer::serialize(QDomElement *aParent) const +{ + // do not serialize the object if it is a child. + // e.g. a PivotPoint created by an object as one of its properties + if (!theAbstractObjectPtr->theProps.getPropertyNoDefault( + Property::ISCHILD_STRING).isEmpty()) + return; + + // save basic values that are part of the object + // TODO: only save values that are different from default + QDomElement myNode = aParent->ownerDocument().createElement(theObjectString); + myNode.setAttribute(theTypeAttributeString, theAbstractObjectPtr->getInternalName()); + myNode.setAttribute(theXAttributeString, QString::number(theAbstractObjectPtr->getOrigCenter().x)); + myNode.setAttribute(theYAttributeString, QString::number(theAbstractObjectPtr->getOrigCenter().y)); + myNode.setAttribute(theAngleAttributeString, + QString::number(theAbstractObjectPtr->getOrigCenter().angle)); + myNode.setAttribute(theWidthAttributeString, QString::number(theAbstractObjectPtr->getTheWidth())); + myNode.setAttribute(theHeightAttributeString, + QString::number(theAbstractObjectPtr->getTheHeight())); + if (theAbstractObjectPtr->getID().isEmpty() == false) + myNode.setAttribute(theIDAttributeString, theAbstractObjectPtr->getID()); + + // save properties + // only save properties that are non-default + if (theAbstractObjectPtr->theProps.getPropertyCount() > 0) { + PropertyList::PropertyMap::const_iterator i; + for ( i = theAbstractObjectPtr->theProps.constBegin(); + i != theAbstractObjectPtr->theProps.constEnd(); + ++i) { + QString myDefValue = theAbstractObjectPtr->theProps.getDefaultProperty(i.key()); + // do not save default values + if (myDefValue == i.value()) + continue; + + QDomElement myProperty = aParent->ownerDocument().createElement(thePropertyString); + myProperty.setAttribute("key", i.key()); + QDomText myT = aParent->ownerDocument().createTextNode(i.value()); + myProperty.appendChild(myT); + myNode.appendChild(myProperty); + } + } + + // Save *custom* tooltips only, not the default ones + if (theAbstractObjectPtr->hasCustomToolTip) { + QString myTooltipTextString = theAbstractObjectPtr->theToolTip; + QDomElement myTooltip = aParent->ownerDocument().createElement(theToolTipString); + QDomText myTooltipText = aParent->ownerDocument().createTextNode(myTooltipTextString); + myTooltip.appendChild(myTooltipText); + myNode.appendChild(myTooltip); + } + + aParent->appendChild(myNode); +} + + +AbstractObjectPtr AbstractObjectSerializer::createObjectFromDom(const QDomNode &q, + bool isMovable, + bool isXYMandatory) +{ + QDomNamedNodeMap myNodeMap; + bool isOK1, isOK2; + QString myValue; + + /// simple sanity check first... + if (q.nodeName() != "object") { + DEBUG2("createObjectFromDom: expected but got <%s>", ASCII(q.nodeName())); + return nullptr; + } + + // the nodemap contains all the parameters, or not... + myNodeMap = q.attributes(); + + QString myObjectType = myNodeMap.namedItem(theTypeAttributeString).nodeValue(); + Position myObjectPosition( + myNodeMap.namedItem(theXAttributeString).nodeValue().toDouble(&isOK1), + myNodeMap.namedItem(theYAttributeString).nodeValue().toDouble(&isOK2), + myNodeMap.namedItem(theAngleAttributeString).nodeValue().toDouble()); + if (!isOK1 || !isOK2) { + if (isXYMandatory) { + DEBUG2("createObjectFromDom: '%s' has invalid X or Y", ASCII(myObjectType)); + return nullptr; + } + myObjectPosition = Position(0, 0, 0); + } + + AbstractObjectPtr myAOPtr = ObjectFactory::createObject(myObjectType, myObjectPosition); + if (myAOPtr == nullptr) { + DEBUG2("createObjectFromDom: '%s' has problems in its factory", ASCII(myObjectType)); + goto not_good; + } + + myAOPtr->setID(myNodeMap.namedItem(theIDAttributeString).nodeValue()); + myAOPtr->theIsMovable = isMovable; + + isOK1 = true; + myValue = myNodeMap.namedItem(theWidthAttributeString).nodeValue(); + if (myValue.isEmpty() == false) + myAOPtr->setTheWidth(myValue.toDouble(&isOK1)); + if (!isOK1) { + DEBUG2("createObjectFromDom: '%s' has invalid %s", ASCII(myObjectType), theWidthAttributeString); + goto not_good; + } + + isOK1 = true; + myValue = myNodeMap.namedItem(theHeightAttributeString).nodeValue(); + if (myValue.isEmpty() == false) + myAOPtr->setTheHeight(myValue.toDouble(&isOK1)); + if (!isOK1) { + DEBUG2("createObjectFromDom: '%s' has invalid %s", ASCII(myObjectType), theHeightAttributeString); + goto not_good; + } + if (q.hasChildNodes() == true) { + // to parse: used_wood_bar + QDomElement i; + for (i = q.firstChildElement(); !i.isNull(); i = i.nextSiblingElement()) { + QString myKey = i.attributes().item(0).nodeValue(); + QString myTValue = i.text(); + if (i.nodeName() == thePropertyString) { + DEBUG5(" %s", ASCII(QString("property: '%1'='%2'").arg(myKey).arg(myTValue))); + // make sure there's no 'Description' - that's now outlawed + Q_ASSERT(myKey != "Description"); + myAOPtr->theProps.setProperty(myKey, myTValue); + continue; + } + if (i.nodeName() == theToolTipString) { + DEBUG5(" %s", ASCII(QString("tooltip: '%1'").arg(myTValue))); + myAOPtr->theToolTip = myTValue; + myAOPtr->hasCustomToolTip = true; + continue; + } + // if we get here, nodeName is not something we know about + goto not_good; + } + } + + DEBUG5("createObjectFromDom for '%s' successful", ASCII(myObjectType)); + return myAOPtr; +not_good: + // myAOPtr is a shared_ptr - will take care of its own destruction if needed + return nullptr; +} diff --git a/pool/shard007/C++/0095318_cordz_sample_token.cc b/pool/shard007/C++/0095318_cordz_sample_token.cc new file mode 100644 index 0000000000000000000000000000000000000000..79e2ea5ef6b05be24e1e5f014084f701fb7340cb --- /dev/null +++ b/pool/shard007/C++/0095318_cordz_sample_token.cc @@ -0,0 +1,52 @@ +// Copyright 2019 The Abseil Authors. +// Licensed under the Apache License, Version 2.0 (the "License"); +// +#include "absl/absl-internal.h" +#pragma hdrstop +#include "absl/strings/internal/cordz_sample_token.h" +#include "absl/strings/internal/cordz_handle.h" +#include "absl/strings/internal/cordz_info.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace cord_internal { +CordzSampleToken::Iterator& CordzSampleToken::Iterator::operator++() { + if(current_) { + current_ = current_->Next(*token_); + } + return *this; +} + +CordzSampleToken::Iterator CordzSampleToken::Iterator::operator++(int) { + Iterator it(*this); + operator++(); + return it; +} + +bool operator==(const CordzSampleToken::Iterator& lhs, + const CordzSampleToken::Iterator& rhs) { + return lhs.current_ == rhs.current_ && + (lhs.current_ == nullptr || lhs.token_ == rhs.token_); +} + +bool operator!=(const CordzSampleToken::Iterator& lhs, + const CordzSampleToken::Iterator& rhs) { + return !(lhs == rhs); +} + +CordzSampleToken::Iterator::reference CordzSampleToken::Iterator::operator*() +const { + return *current_; +} + +CordzSampleToken::Iterator::pointer CordzSampleToken::Iterator::operator->() +const { + return current_; +} + +CordzSampleToken::Iterator::Iterator(const CordzSampleToken* token) + : token_(token), current_(CordzInfo::Head(*token)) { +} +} // namespace cord_internal +ABSL_NAMESPACE_END +} // namespace absl diff --git a/pool/shard007/C++/0095320_EncodersDataTransformAction.cpp b/pool/shard007/C++/0095320_EncodersDataTransformAction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..893b6ed8a079c68ee5f14f4f731a3dfb4accf2c1 --- /dev/null +++ b/pool/shard007/C++/0095320_EncodersDataTransformAction.cpp @@ -0,0 +1,150 @@ +#define _USE_MATH_DEFINES + +#include +#include +#include +#include + +#include +#include +#include + +#include "Common/CommonDefs.h" +#include "Common/Data/EncodersData.h" +#include "Common/Data/Vertex3D.h" +#include "Common/LinearAlgebra/Matrix.h" +#include "Common/LinearAlgebra/MatrixFactory.h" +#include "Common/Context.h" +#include "Common/IAction.h" +#include "EncodersDataTransformAction.h" + +namespace CalcApp +{ + +namespace +{ + +typedef QListContextItem EncodersDataContextItem; +typedef QListContextItem Vertex3DDataContextItem; + +Matrix CreateTransformation(EncodersData const &data, EncodersConstraints const &constraints) +{ + double globalTransferX = data.GlobalTransferX * constraints.GlobalTransferStep; + double globalTransferY = data.GlobalTransferY * constraints.GlobalTransferStep; + double globalTransferZ = data.GlobalTransferZ * constraints.GlobalTransferStep; + double localRotation = (2 * M_PI * data.LocalRotation) / constraints.LocalRotationLength; + double localTransfer = data.LocalTransfer * constraints.LocalTransferStep; + double sensorTransfer = data.SensorTransfer * constraints.SensorTransferStep; + return CreateXTransferMatrix(globalTransferX) * + CreateYTransferMatrix(globalTransferY) * + CreateZTransferMatrix(globalTransferZ) * + CreateZRotationMatrix(localRotation) * + CreateXTransferMatrix(localTransfer) * + CreateYTransferMatrix(sensorTransfer); +} + +Vertex3D CreateVertex(Matrix const &transformation, Matrix const &localColumn) +{ + Matrix globalColumn(transformation * localColumn); + return Vertex3D(globalColumn.GetValue(0, 0), globalColumn.GetValue(1, 0), globalColumn.GetValue(2, 0)); +} + +Vertex3DData CreateVertexData(EncodersData const &data, EncodersConstraints const &constraints) +{ + Matrix transformation(CreateTransformation(data, constraints)); + double sensorValue = data.Value * constraints.SensorResolution; + Vertex3D surfacePoint(CreateVertex(transformation, Matrix::CreateColumnMatrix({sensorValue, 0, 0, 1}))); + Vertex3D sensor(CreateVertex(transformation, Matrix::CreateColumnMatrix({0, 0, 0, 1}))); + return Vertex3DData(surfacePoint, sensor); +} + +void TransformData(EncodersDataContextItem *sourceItem, Vertex3DDataContextItem *destItem, int start, EncodersConstraints const &constraints) +{ + QReadLocker _readLocker(&sourceItem->Lock); + QWriteLocker _writeLocker(&destItem->Lock); + bool transformed = false; + for (int index = start; index < sourceItem->Data.length(); ++index) + { + transformed = true; + destItem->Data.append(CreateVertexData(sourceItem->Data[index], constraints)); + } + if (transformed) + emit destItem->NotifyDataChange(); +} + +} + +EncodersDataTransformAction::EncodersDataTransformAction(QString const &name, + QString const &sourceKey, + QString const &destKey, + EncodersConstraints const &constraints, + ContextPtr context, + ExecutionStatePtr state) : + IAction(context, state), + _name(name), + _sourceKey(sourceKey), + _destKey(destKey), + _constraints(constraints) +{ + context.get()->Set(_destKey, std::make_shared()); +} + +QString EncodersDataTransformAction::GetName() +{ + return _name; +} + +/*void EncodersDataTransformAction::StartAction(Context &context) +{ +}*/ + +/*void EncodersDataTransformAction::Run(Context &context) +{ +}*/ + +void EncodersDataTransformAction::ProcessStartImpl() +{ + ContextPtr context = GetContext(); + QObject::connect(context.get(), &Context::DataChanged, this, [this](QString const &key){ + if (key == _sourceKey) + ProcessData(); + }); + QObject::connect(context.get(), &Context::DataCompleted, this, [this](QString const &key){ + if (key == _sourceKey) + FinishProcessData(); + }); + _index = -1; +} + +void EncodersDataTransformAction::ProcessStopImpl() +{ + // do nothing +} + +void EncodersDataTransformAction::CleanupNonFinished() +{ + // do nothing +} + +void EncodersDataTransformAction::ProcessData() +{ + ProcessData(GetContext()); +} + +void EncodersDataTransformAction::FinishProcessData() +{ + ContextPtr context = GetContext(); + ProcessData(context); + emit context.get()->DataCompleted(_destKey); + emit ActionFinished(); +} + +void EncodersDataTransformAction::ProcessData(ContextPtr context) +{ + EncodersDataContextItem *sourceItem = context.get()->GetValue(_sourceKey); + Vertex3DDataContextItem *destItem = context.get()->GetValue(_destKey); + TransformData(sourceItem, destItem, _index + 1, _constraints); + _index = sourceItem->Data.length() - 1; +} + +} diff --git a/pool/shard007/C++/0095324_connectionlistener.cpp b/pool/shard007/C++/0095324_connectionlistener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ceac4a6b1a522dd79de1656577372325f036d4c2 --- /dev/null +++ b/pool/shard007/C++/0095324_connectionlistener.cpp @@ -0,0 +1,40 @@ +#include "connectionlistener.h" + +ConnListener::ConnListener( Bot* bot) +{ + m_bot = bot; +} + +void ConnListener::onConnect() +{ + cout << "ConnListener::onConnect()" << endl; + m_bot->list(); +} + +void ConnListener::onDisconnect(ConnectionError e) +{ + cout << "ConnListener::onDisconnect() " << e << endl; + if( e == 7) + m_bot->retry(); +} + +bool ConnListener::onTLSConnect( const CertInfo& info) +{ + cout << "ConnListener::onTLSConnect()" << endl; + return true; +} + +void ConnListener::onStreamEvent( StreamEvent event) +{ + cout << "ConnListener::onStreamEvent()" << endl; +} + +void ConnListener::onResourceBindError( const string& resource) +{ + cout << "ConnListener::onresourceBinError(" << resource << ")" << endl; +} + +void ConnListener::handlePresence( const Presence& presence) +{ +} + diff --git a/pool/shard007/C++/0095327_Navigation.cpp b/pool/shard007/C++/0095327_Navigation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9802257a89f5f1bfa674cba470c1344b8fa777f5 --- /dev/null +++ b/pool/shard007/C++/0095327_Navigation.cpp @@ -0,0 +1,249 @@ +#include "Navigation.h" + +Navigation::Navigation(GPS *withGPS, Waypoints *withWP) : + _gps(withGPS), + _wp(withWP), + _hold_course(-1) +{ +} + +void +Navigation::update_gps() +{ + location.alt = _gps->altitude; + location.lng = _gps->longitude; + location.lat = _gps->latitude; + + // target_bearing is where we should be heading + bearing = get_bearing(&location, &next_wp); + + // waypoint distance from plane + distance = get_distance(&location, &next_wp); + + calc_bearing_error(); + calc_altitude_error(); + altitude_above_home = location.alt - home.alt; + + // check if we have missed the WP + _loiter_delta = (bearing - _old_bearing) / 100; + + // reset the old value + _old_bearing = bearing; + + // wrap values + if (_loiter_delta > 170) _loiter_delta -= 360; + if (_loiter_delta < -170) _loiter_delta += 360; + loiter_sum += abs(_loiter_delta); + + if (distance <= 0){ + distance = -1; + Serial.print("MSG wp error "); + Serial.println(distance, DEC); + } +} + +void +Navigation::load_first_wp(void) +{ + set_next_wp(_wp->get_waypoint_with_index(1)); +} + +void +Navigation::load_home(void) +{ + home = _wp->get_waypoint_with_index(0); +} + +void +Navigation::return_to_home_with_alt(uint32_t alt) +{ + Waypoints::WP loc = _wp->get_waypoint_with_index(0); + loc.alt += alt; + set_next_wp(loc); +} + +void +Navigation::reload_wp(void) +{ + set_next_wp(_wp->get_current_waypoint()); +} + +void +Navigation::load_wp_index(uint8_t i) +{ + _wp->set_index(i); + set_next_wp(_wp->get_current_waypoint()); +} + +void +Navigation::hold_location() +{ + // set_next_wp() XXX needs to be implemented +} + +void +Navigation::set_home(Waypoints::WP loc) +{ + _wp->set_waypoint_with_index(loc, 0); + home = loc; + //location = home; +} + +void +Navigation::set_next_wp(Waypoints::WP loc) +{ + prev_wp = next_wp; + next_wp = loc; + + if(_scaleLongDown == 0) + calc_long_scaling(loc.lat); + + total_distance = get_distance(&location, &next_wp); + distance = total_distance; + + bearing = get_bearing(&location, &next_wp); + _old_bearing = bearing; + + // clear loitering code + _loiter_delta = 0; + loiter_sum = 0; + + // set a new crosstrack bearing + // ---------------------------- + reset_crosstrack(); +} + +void +Navigation::calc_long_scaling(int32_t lat) +{ + // this is used to offset the shrinking longitude as we go towards the poles + float rads = (abs(lat) / T7) * 0.0174532925; + _scaleLongDown = cos(rads); + _scaleLongUp = 1.0f / cos(rads); +} + +void +Navigation::set_hold_course(int16_t b) +{ + if(b) + _hold_course = bearing; + else + _hold_course = -1; +} + +int16_t +Navigation::get_hold_course(void) +{ + return _hold_course; +} + +void +Navigation::calc_distance_error() +{ + //distance_estimate += (float)_gps->ground_speed * .0002 * cos(radians(bearing_error * .01)); + //distance_estimate -= DST_EST_GAIN * (float)(distance_estimate - GPS_distance); + //distance = max(distance_estimate,10); +} + +void +Navigation::calc_bearing_error(void) +{ + if(_hold_course == -1){ + bearing_error = wrap_180(bearing - _gps->ground_course); + }else{ + bearing_error = _hold_course; + } +} + +int32_t +Navigation::wrap_180(int32_t error) +{ + if (error > 18000) error -= 36000; + if (error < -18000) error += 36000; + return error; +} + +int32_t +Navigation::wrap_360(int32_t angle) +{ + if (angle > 36000) angle -= 36000; + if (angle < 0) angle += 36000; + return angle; +} + +void +Navigation::set_bearing_error(int32_t error) +{ + bearing_error = wrap_180(error); +} + + +/***************************************** + * Altitude error with Airspeed correction + *****************************************/ +void +Navigation::calc_altitude_error(void) +{ + // limit climb rates + _target_altitude = next_wp.alt - ((float)((distance -20) * _offset_altitude) / (float)(total_distance - 20)); + if(prev_wp.alt > next_wp.alt){ + _target_altitude = constrain(_target_altitude, next_wp.alt, prev_wp.alt); + }else{ + _target_altitude = constrain(_target_altitude, prev_wp.alt, next_wp.alt); + } + altitude_error = _target_altitude - location.alt; +} + +void +Navigation::set_loiter_vector(int16_t v) +{ + // _vector = constrain(v, -18000, 18000); XXX needs to be implemented +} + +void +Navigation::update_crosstrack(void) +{ + // Crosstrack Error + // ---------------- + if (abs(bearing - _crosstrack_bearing) < 4500) { // If we are too far off or too close we don't do track following + _crosstrack_error = sin(radians((bearing - _crosstrack_bearing) / 100)) * distance; // Meters we are off track line + bearing += constrain(_crosstrack_error * XTRACK_GAIN, -XTRACK_ENTRY_ANGLE, XTRACK_ENTRY_ANGLE); + } +} + +void +Navigation::reset_crosstrack(void) +{ + _crosstrack_bearing = get_bearing(&location, &next_wp); // Used for track following +} + +long +Navigation::get_distance(Waypoints::WP *loc1, Waypoints::WP *loc2) +{ + if(loc1->lat == 0 || loc1->lng == 0) + return -1; + if(loc2->lat == 0 || loc2->lng == 0) + return -1; + if(_scaleLongDown == 0) + calc_long_scaling(loc2->lat); + float dlat = (float)(loc2->lat - loc1->lat); + float dlong = ((float)(loc2->lng - loc1->lng)) * _scaleLongDown; + return sqrt(sq(dlat) + sq(dlong)) * .01113195; +} + +long +Navigation::get_bearing(Waypoints::WP *loc1, Waypoints::WP *loc2) +{ + if(loc1->lat == 0 || loc1->lng == 0) + return -1; + if(loc2->lat == 0 || loc2->lng == 0) + return -1; + if(_scaleLongDown == 0) + calc_long_scaling(loc2->lat); + long off_x = loc2->lng - loc1->lng; + long off_y = (loc2->lat - loc1->lat) * _scaleLongUp; + long bearing = 9000 + atan2(-off_y, off_x) * 5729.57795; + if (bearing < 0) + bearing += 36000; + return bearing; +} diff --git a/pool/shard007/C++/0095329_KoMarkerSelector.cpp b/pool/shard007/C++/0095329_KoMarkerSelector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd631792bb801902d95e797f674b8b09e010565c --- /dev/null +++ b/pool/shard007/C++/0095329_KoMarkerSelector.cpp @@ -0,0 +1,114 @@ +/* This file is part of the KDE project + * Copyright (C) 2011 Thorsten Zachmann + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "KoMarkerSelector.h" + +#include "KoMarker.h" +#include "KoMarkerModel.h" +#include "KoMarkerItemDelegate.h" +#include "KoPathShape.h" + +#include +#include + +class KoMarkerSelector::Private +{ +public: + Private(KoMarkerData::MarkerPosition position, QWidget *parent) + : model(new KoMarkerModel(QList(), position, parent)) + {} + + KoMarkerModel *model; +}; + +KoMarkerSelector::KoMarkerSelector(KoMarkerData::MarkerPosition position, QWidget *parent) +: QComboBox(parent) +, d(new Private(position, this)) +{ + setModel(d->model); + setItemDelegate(new KoMarkerItemDelegate(position, this)); +} + +KoMarkerSelector::~KoMarkerSelector() +{ + delete d; +} + +void KoMarkerSelector::paintEvent(QPaintEvent *pe) +{ + QComboBox::paintEvent(pe); + + QStyleOptionComboBox option; + option.initFrom(this); + option.frame = hasFrame(); + QRect rect = style()->subControlRect(QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, this); + if (!option.frame) { // frameless combo boxes have smaller margins but styles do not take this into account + rect.adjust(-14, 0, 14, 1); + } + + QPainter painter(this); + bool antialiasing = painter.testRenderHint(QPainter::Antialiasing); + if (!antialiasing) { + painter.setRenderHint(QPainter::Antialiasing, true); + } + + KoPathShape pathShape; + pathShape.moveTo(QPointF(rect.left(), rect.center().y())); + pathShape.lineTo(QPointF(rect.right(), rect.center().y())); + + KoMarker *marker = itemData(currentIndex(), Qt::DecorationRole).value(); + if (marker != 0) { + pathShape.setMarker(marker, d->model->position()); + } + + // paint marker + QPen pen(option.palette.text(), 2); + QPainterPath path = pathShape.pathStroke(pen); + painter.fillPath(path, pen.brush()); + + if (!antialiasing) { + painter.setRenderHint(QPainter::Antialiasing, false); + } +} + +void KoMarkerSelector::setMarker(KoMarker *marker) +{ + int index = d->model->markerIndex(marker); + if (index >= 0) { + setCurrentIndex(index); + } +} + +KoMarker *KoMarkerSelector::marker() const +{ + return itemData(currentIndex(), Qt::DecorationRole).value(); +} + +void KoMarkerSelector::updateMarkers(const QList markers) +{ + KoMarkerModel *model = new KoMarkerModel(markers,d->model->position(), this); + d->model = model; + // this deletes the old model + setModel(model); +} + +QVariant KoMarkerSelector::itemData(int index, int role) const +{ + return d->model->marker(index, role); +} diff --git a/pool/shard007/C++/0095333_CaptureContentTypeHeader.cpp b/pool/shard007/C++/0095333_CaptureContentTypeHeader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af336eefb1494a59947ca370e299c28c6128c855 --- /dev/null +++ b/pool/shard007/C++/0095333_CaptureContentTypeHeader.cpp @@ -0,0 +1,100 @@ +/* +* 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 + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace SageMaker +{ +namespace Model +{ + +CaptureContentTypeHeader::CaptureContentTypeHeader() : + m_csvContentTypesHasBeenSet(false), + m_jsonContentTypesHasBeenSet(false) +{ +} + +CaptureContentTypeHeader::CaptureContentTypeHeader(JsonView jsonValue) : + m_csvContentTypesHasBeenSet(false), + m_jsonContentTypesHasBeenSet(false) +{ + *this = jsonValue; +} + +CaptureContentTypeHeader& CaptureContentTypeHeader::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("CsvContentTypes")) + { + Array csvContentTypesJsonList = jsonValue.GetArray("CsvContentTypes"); + for(unsigned csvContentTypesIndex = 0; csvContentTypesIndex < csvContentTypesJsonList.GetLength(); ++csvContentTypesIndex) + { + m_csvContentTypes.push_back(csvContentTypesJsonList[csvContentTypesIndex].AsString()); + } + m_csvContentTypesHasBeenSet = true; + } + + if(jsonValue.ValueExists("JsonContentTypes")) + { + Array jsonContentTypesJsonList = jsonValue.GetArray("JsonContentTypes"); + for(unsigned jsonContentTypesIndex = 0; jsonContentTypesIndex < jsonContentTypesJsonList.GetLength(); ++jsonContentTypesIndex) + { + m_jsonContentTypes.push_back(jsonContentTypesJsonList[jsonContentTypesIndex].AsString()); + } + m_jsonContentTypesHasBeenSet = true; + } + + return *this; +} + +JsonValue CaptureContentTypeHeader::Jsonize() const +{ + JsonValue payload; + + if(m_csvContentTypesHasBeenSet) + { + Array csvContentTypesJsonList(m_csvContentTypes.size()); + for(unsigned csvContentTypesIndex = 0; csvContentTypesIndex < csvContentTypesJsonList.GetLength(); ++csvContentTypesIndex) + { + csvContentTypesJsonList[csvContentTypesIndex].AsString(m_csvContentTypes[csvContentTypesIndex]); + } + payload.WithArray("CsvContentTypes", std::move(csvContentTypesJsonList)); + + } + + if(m_jsonContentTypesHasBeenSet) + { + Array jsonContentTypesJsonList(m_jsonContentTypes.size()); + for(unsigned jsonContentTypesIndex = 0; jsonContentTypesIndex < jsonContentTypesJsonList.GetLength(); ++jsonContentTypesIndex) + { + jsonContentTypesJsonList[jsonContentTypesIndex].AsString(m_jsonContentTypes[jsonContentTypesIndex]); + } + payload.WithArray("JsonContentTypes", std::move(jsonContentTypesJsonList)); + + } + + return payload; +} + +} // namespace Model +} // namespace SageMaker +} // namespace Aws diff --git a/pool/shard007/C++/0095346_mapped_region.cc b/pool/shard007/C++/0095346_mapped_region.cc new file mode 100644 index 0000000000000000000000000000000000000000..e56873a5e493c7af0fb806d4351021ede1da7548 --- /dev/null +++ b/pool/shard007/C++/0095346_mapped_region.cc @@ -0,0 +1,134 @@ +//---------------------------------------------------------- -*- Mode: C++ -*- +// Copyright (C) 2007 Josh Taylor (Kosmix Corporation) +// Created 2007-08-31 +// +// This file is part of the warp library. +// +// The warp 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 2 of the License, or any later +// version. +// +// The warp 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 program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +//---------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace warp; +using namespace ex; +using namespace std; + +MappedRegion::MappedRegion(string const & uri, int prot, int flags) : + mem(MAP_FAILED), sz(0), fd(-1) +{ + // Open file descriptor + string path = fs::path(uri); + fd = ::open(path.c_str(), O_RDONLY); + if(fd == -1) + raise("failed to open '%s' (path=%s): %s", + uri, path, getStdError()); + + // Get file size + struct stat st; + if(0 != ::fstat(fd, &st)) + { + int err = errno; + ::close(fd); + fd = -1; + raise("failed to stat '%s': %s", + path, getStdError(err)); + } + sz = st.st_size; + + // Map file + mem = ::mmap(0, sz, prot, flags, fd, 0); + if(mem == MAP_FAILED) + { + int err = errno; + ::close(fd); + fd = -1; + raise("failed to mmap %d bytes from '%s': %s", + sz, path, getStdError(err)); + } +} + +MappedRegion::MappedRegion(string const & uri, int prot, int flags, + size_t sz, off_t offset) : + mem(MAP_FAILED), sz(sz), fd(-1) +{ + // Open file descriptor + string path = fs::path(uri); + fd = ::open(path.c_str(), O_RDONLY); + if(fd == -1) + raise("failed to open '%s' (path=%s): %s", + uri, path, getStdError()); + + // Map file + mem = ::mmap(0, sz, prot, flags, fd, offset); + if(mem == MAP_FAILED) + { + int err = errno; + ::close(fd); + fd = -1; + raise("failed to mmap %d bytes from '%s' at offset %d: %s", + sz, path, offset, getStdError(err)); + } +} + +MappedRegion::MappedRegion(int prot, int flags, size_t sz) : + mem(MAP_FAILED), sz(sz), fd(-1) +{ + // Require anonymous mapping bit + flags |= MAP_ANONYMOUS; + + // Map region + mem = ::mmap(0, sz, prot, flags, -1, 0); + if(mem == MAP_FAILED) + raise("failed to mmap anonymous region of size %d: %s", + sz, getStdError()); +} + +MappedRegion::~MappedRegion() +{ + // Unmap region + if(mem != MAP_FAILED) + ::munmap(mem, sz); + + // Close file descriptor + if(fd != -1) + ::close(fd); +} + +void MappedRegion::prefault() const +{ + prefault(0, sz); +} + +void MappedRegion::prefault(size_t off, size_t len) const +{ + size_t const PAGE_SZ = getpagesize(); + + size_t base = alignDown(off, PAGE_SZ); + size_t end = alignUp(off + len, PAGE_SZ); + + volatile char c = 42; + for(size_t p = base; p < end; p += PAGE_SZ) + { + c += *getAs(p); + } +} diff --git a/pool/shard007/C++/0095350_lcd.cpp b/pool/shard007/C++/0095350_lcd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2a38209e2a5f5362a1e7f07786229221f2ae1a3 --- /dev/null +++ b/pool/shard007/C++/0095350_lcd.cpp @@ -0,0 +1,285 @@ +// +// OOSMOS lcd Class +// +// Copyright (C) 2014-2016 OOSMOS, LLC +// +// 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, version 2 of the License ("GPLv2"). +// +// This software may be used without the GPLv2 restrictions by entering +// into a commercial license agreement with OOSMOS, LLC. +// See . +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// + +#include +#include +#include "oosmos.h" +#include "lcd.h" + +#ifndef lcdMAX +#define lcdMAX 1 +#endif + +struct lcdTag +{ + pin * m_pRS; + pin * m_pRW; + pin * m_pE; + + pin * m_pData4; + pin * m_pData5; + pin * m_pData6; + pin * m_pData7; +}; + +typedef enum +{ + modeWriteCommand = 1, + modeWriteData, + modeReadStatus, + modeReadData, +} eMode; + +typedef enum +{ + bits4 = 1, + bits8, +} eBits; + +typedef enum +{ + font5x8 = 1, + font5x10, +} eFont; + +typedef enum +{ + lines1 = 1, + lines2, +} eLines; + +typedef enum +{ + displayOn = 1, + displayOff, +} eDisplay; + +typedef enum +{ + cursorOff = 1, + cursorOn, +} eCursor; + +typedef enum +{ + blinkingOff = 1, + blinkingOn, +} eBlinking; + +typedef enum +{ + entryIncrement = 1, + entryDecrement, +} eEntry; + +typedef enum +{ + shiftOn = 1, + shiftOff, +} eShift; + +static void SetMode(lcd * pLCD, const eMode Mode) +{ + switch (Mode) { + case modeWriteCommand: + pinOff(pLCD->m_pRS); + if (pLCD->m_pRW != NULL) pinOff(pLCD->m_pRW); + break; + case modeWriteData: + pinOn(pLCD->m_pRS); + if (pLCD->m_pRW != NULL) pinOff(pLCD->m_pRW); + break; + case modeReadStatus: + pinOff(pLCD->m_pRS); + if (pLCD->m_pRW != NULL) pinOn(pLCD->m_pRW); + break; + case modeReadData: + pinOn(pLCD->m_pRS); + if (pLCD->m_pRW != NULL) pinOn(pLCD->m_pRW); + break; + } +} + +static void Write4(lcd * pLCD, const uint8_t Value) +{ + (Value & 1 ? pinOn : pinOff)(pLCD->m_pData4); + (Value & 2 ? pinOn : pinOff)(pLCD->m_pData5); + (Value & 4 ? pinOn : pinOff)(pLCD->m_pData6); + (Value & 8 ? pinOn : pinOff)(pLCD->m_pData7); + + pinOn(pLCD->m_pE); + oosmos_DelayUS(1); + pinOff(pLCD->m_pE); +} + +static void WriteCommand4(lcd * pLCD, const uint8_t Command) +{ + SetMode(pLCD, modeWriteCommand); + Write4(pLCD, Command); +} + +static void WriteCommand(lcd * pLCD, const uint8_t Command) +{ + SetMode(pLCD, modeWriteCommand); + + Write4(pLCD, Command>>4); + Write4(pLCD, Command); +} + +static void WriteData(lcd * pLCD, const uint8_t Data) +{ + SetMode(pLCD, modeWriteData); + + Write4(pLCD, Data>>4); + Write4(pLCD, Data); +} + +static void CommandFunctionSetInit(lcd * pLCD, const eBits Bits) +{ + uint8_t Command = 0x20; + + Command |= (Bits == bits8) << 4; + + WriteCommand4(pLCD, Command >> 4); + oosmos_DelayUS(37); +} + +static void CommandFunctionSet(lcd * pLCD, const eBits Bits, const eLines Lines, const eFont Font) +{ + uint8_t Command = 0x20; + + Command |= (Bits == bits8) << 4; + Command |= (Lines == lines2) << 3; + Command |= (Font == font5x10) << 2; + + WriteCommand(pLCD, Command); + oosmos_DelayUS(37); +} + +static void CommandDisplaySet(lcd * pLCD, const eDisplay Display, const eCursor Underline, const eBlinking Blinking) +{ + uint8_t Command = 0x08; + + Command |= (Display == displayOn) << 2; + Command |= (Underline == cursorOn) << 1; + Command |= (Blinking == blinkingOn) << 0; + + WriteCommand(pLCD, Command); + oosmos_DelayUS(37); +} + +static void CommandClearDisplay(lcd * pLCD) +{ + const uint8_t Command = 0x01; + WriteCommand(pLCD, Command); +} + +static void CommandEntryModeSet(lcd * pLCD, const eEntry Entry, const eShift Shift) +{ + uint8_t Command = 0x04; + + Command |= (Entry == entryIncrement) << 1; + Command |= (Shift == shiftOn) << 0; + + WriteCommand(pLCD, Command); + oosmos_DelayUS(37); +} + +extern void lcdCursorHome(lcd * pLCD) +{ + const uint8_t Command = 0x02; + + WriteCommand(pLCD, Command); + oosmos_DelayUS(1520); +} + +extern void lcdClear(lcd * pLCD) +{ + CommandClearDisplay(pLCD); + oosmos_DelayUS(1520); +} + +extern void lcdPrint(lcd * pLCD, const char * pFormat, ...) +{ + char Buffer[80]; + va_list ArgList; + + va_start(ArgList, pFormat); + vsprintf(Buffer, pFormat, ArgList); + va_end(ArgList); + + const char * pString; + + for (pString = Buffer; *pString != '\0'; pString++) + WriteData(pLCD, *pString); +} + +extern void lcdSetCursor(lcd * pLCD, const int RowIndex, const int ColumnIndex) +{ + uint8_t Command = 0x80; + + const static int RowOffset[] = { 0x00, 0x40, 0x14, 0x54 }; + + Command |= RowOffset[RowIndex] + ColumnIndex; + + WriteCommand(pLCD, Command); + oosmos_DelayUS(37); +} + +extern lcd * lcdNew(pin * pRS, pin * pRW, pin * pE, + pin * pData4, pin * pData5, pin * pData6, pin * pData7) +{ + oosmos_Allocate(pLCD, lcd, lcdMAX, NULL); + + pLCD->m_pRS = pRS; + pLCD->m_pRW = pRW; + pLCD->m_pE = pE; + + pLCD->m_pData4 = pData4; + pLCD->m_pData5 = pData5; + pLCD->m_pData6 = pData6; + pLCD->m_pData7 = pData7; + + oosmos_DelayMS(50); + + CommandFunctionSetInit(pLCD, bits8); + oosmos_DelayUS(4100); + + // + // The data sheet does not say one needs to do this twice. However, + // the Arduino does it twice, and it definitely makes the display + // more stable when reloading new code without a cold reset. + // + CommandFunctionSetInit(pLCD, bits8); + oosmos_DelayUS(4100); + + CommandFunctionSetInit(pLCD, bits8); + oosmos_DelayUS(100); + + CommandFunctionSetInit(pLCD, bits4); + CommandFunctionSet(pLCD, bits4, lines2, font5x8); + CommandDisplaySet(pLCD, displayOn, cursorOff, blinkingOff); + CommandClearDisplay(pLCD); + CommandEntryModeSet(pLCD, entryIncrement, shiftOff); + + return pLCD; +} diff --git a/pool/shard007/C++/0095352_GstAudioEqualizer.cpp b/pool/shard007/C++/0095352_GstAudioEqualizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2239a6236fdf1dd9bacc24cb6d9999a74cf3f299 --- /dev/null +++ b/pool/shard007/C++/0095352_GstAudioEqualizer.cpp @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "GstAudioEqualizer.h" + +#include +#include +#include +#include + +/*********************************************************************************** + * CGstEqualizerBand + ***********************************************************************************/ +CGstEqualizerBand::CGstEqualizerBand() : m_Band(NULL), m_Equalizer(NULL) +{} + +CGstEqualizerBand::CGstEqualizerBand(double bandwidth, double gain, CGstAudioEqualizer* p_Equalizer) + : CEqualizerBand(bandwidth, gain), m_Band(NULL), m_Equalizer(p_Equalizer) +{} + +CGstEqualizerBand::CGstEqualizerBand(const CGstEqualizerBand& other) + : CEqualizerBand(other.m_Bandwidth, other.m_Gain) +{ + m_Band = (other.m_Band) ? G_OBJECT(g_object_ref(other.m_Band)) : NULL; + m_Equalizer = other.m_Equalizer; +} + +CGstEqualizerBand::~CGstEqualizerBand() +{ + if (m_Band) + g_object_unref(m_Band); +} + +double CGstEqualizerBand::GetCenterFrequency() +{ + gdouble result; + g_object_get(m_Band, "freq", &result, NULL); + return result; +} + +void CGstEqualizerBand::SetCenterFrequency(double centerFrequency) +{ + g_object_set(m_Band, "freq", centerFrequency, NULL); +} + +double CGstEqualizerBand::GetBandwidth() +{ + return m_Bandwidth; +} + +void CGstEqualizerBand::SetBandwidth(double bandwidth) +{ + if (m_Bandwidth != bandwidth) + { + m_Bandwidth = bandwidth; + g_object_set(m_Band, "bandwidth", bandwidth, NULL); + } +} + +double CGstEqualizerBand::GetGain() +{ + return m_Gain; +} + +void CGstEqualizerBand::SetGain(double gain) +{ + if (m_Gain != gain) + { + m_Gain = gain; + + if (m_Equalizer->m_IsEnabled) + g_object_set(m_Band, "gain", gain, NULL); + } +} + +void CGstEqualizerBand::ReplaceBand(GObject* p_Band) +{ + if (m_Band) + g_object_unref(m_Band); + + m_Band = p_Band; +} +/*********************************************************************************** + * CGstAudioEqualizer + ***********************************************************************************/ +CGstAudioEqualizer::CGstAudioEqualizer(GstElement *pEqualizer) + : m_IsEnabled(true) +{ + m_pEqualizer = GST_ELEMENT(gst_object_ref(pEqualizer)); +} + +CGstAudioEqualizer::~CGstAudioEqualizer() +{ + gst_object_unref(m_pEqualizer); +} + +bool CGstAudioEqualizer::IsEnabled() +{ + return m_BandMap.size() > 0 && m_IsEnabled; +} + +void CGstAudioEqualizer::SetEnabled(bool isEnabled) +{ + m_IsEnabled = isEnabled; + for (BandMap::iterator band_it = m_BandMap.begin(); band_it != m_BandMap.end(); band_it++) + g_object_set(band_it->second.m_Band, "gain", m_IsEnabled ? band_it->second.GetGain() : 0.0, NULL); +} + +int CGstAudioEqualizer::GetNumBands() +{ + return (int)m_BandMap.size(); +} + +void CGstAudioEqualizer::UpdateBands() +{ + g_object_set(m_pEqualizer, "num-bands", m_BandMap.size(), NULL); + + int index = 0; + for (BandMap::iterator band_it = m_BandMap.begin(); band_it != m_BandMap.end(); band_it++) + { + band_it->second.ReplaceBand(gst_child_proxy_get_child_by_index (GST_CHILD_PROXY (m_pEqualizer), index++)); + g_object_set(band_it->second.m_Band, "freq", band_it->first, + "bandwidth", band_it->second.GetBandwidth(), + "gain", m_IsEnabled ? band_it->second.GetGain() : 0.0, NULL); + } +} + +CEqualizerBand* CGstAudioEqualizer::AddBand(double frequency, double bandwidth, double gain) +{ + BandMap::iterator band_it = m_BandMap.find(frequency); + + if (band_it == m_BandMap.end()) // Add a new band + { + m_BandMap[frequency] = CGstEqualizerBand(bandwidth, gain, this); + UpdateBands(); + return &m_BandMap[frequency]; + } + else // Update an existing band + return NULL; +} + +bool CGstAudioEqualizer::RemoveBand(double frequency) +{ + BandMap::iterator band_it = m_BandMap.find(frequency); + + if (band_it != m_BandMap.end()) + { + m_BandMap.erase(band_it); + UpdateBands(); + return true; + } + else + return false; +} diff --git a/pool/shard007/C++/0095358_DrawCallPerf.cc b/pool/shard007/C++/0095358_DrawCallPerf.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba923b83570802700d798f7af10076e08e5a785b --- /dev/null +++ b/pool/shard007/C++/0095358_DrawCallPerf.cc @@ -0,0 +1,181 @@ +//------------------------------------------------------------------------------ +// DrawCallPerf.cc +//------------------------------------------------------------------------------ +#include "Pre.h" +#include "Core/App.h" +#include "Gfx/Gfx.h" +#include "Assets/Gfx/ShapeBuilder.h" +#include "Dbg/Dbg.h" +#include "Input/Input.h" +#include "Time/Clock.h" +#include "glm/mat4x4.hpp" +#include "glm/gtc/matrix_transform.hpp" +#include "glm/gtc/random.hpp" +#include "shaders.h" + +using namespace Oryol; + +class DrawCallPerfApp : public App { +public: + AppState::Code OnRunning(); + AppState::Code OnInit(); + AppState::Code OnCleanup(); + +private: + void updateCamera(); + void emitParticles(); + void updateParticles(); + + Id drawState; + glm::mat4 view; + glm::mat4 proj; + glm::mat4 model; + Shaders::Main::PerFrameParams perFrameParams; + Shaders::Main::PerParticleParams perParticleParams; + bool updateEnabled = true; + int32 frameCount = 0; + int32 curNumParticles = 0; + TimePoint lastFrameTimePoint; + static const int32 NumParticlesEmittedPerFrame = 100; + static const int32 MaxNumParticles = 1024 * 1024; + struct { + glm::vec4 pos; + glm::vec4 vec; + } particles[MaxNumParticles]; +}; +OryolMain(DrawCallPerfApp); + +//------------------------------------------------------------------------------ +AppState::Code +DrawCallPerfApp::OnRunning() { + + Duration updTime, drawTime; + this->frameCount++; + + // update block + this->updateCamera(); + if (this->updateEnabled) { + TimePoint updStart = Clock::Now(); + this->emitParticles(); + this->updateParticles(); + updTime = Clock::Since(updStart); + } + + // render block + TimePoint drawStart = Clock::Now(); + Gfx::ApplyDefaultRenderTarget(); + Gfx::ApplyDrawState(this->drawState); + Gfx::ApplyUniformBlock(this->perFrameParams); + for (int32 i = 0; i < this->curNumParticles; i++) { + this->perParticleParams.Translate = this->particles[i].pos; + Gfx::ApplyUniformBlock(this->perParticleParams); + Gfx::Draw(0); + } + drawTime = Clock::Since(drawStart); + + Dbg::DrawTextBuffer(); + Gfx::CommitFrame(); + + // toggle particle update + const Mouse& mouse = Input::Mouse(); + if (mouse.Attached && mouse.ButtonDown(Mouse::Button::LMB)) { + this->updateEnabled = !this->updateEnabled; + } + + Duration frameTime = Clock::LapTime(this->lastFrameTimePoint); + Dbg::TextColor(glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)); + Dbg::PrintF("\n %d draws\n\r upd=%.3fms\n\r draw=%.3fms\n\r frame=%.3fms\n\r" + " LMB/tap: toggle particle update", + this->curNumParticles, + updTime.AsMilliSeconds(), + drawTime.AsMilliSeconds(), + frameTime.AsMilliSeconds()); + Dbg::TextColor(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); + Dbg::PrintF("\n\n\r NOTE: this demo will bring down GL fairly quickly!\n"); + + return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running; +} + +//------------------------------------------------------------------------------ +void +DrawCallPerfApp::updateCamera() { + float32 angle = this->frameCount * 0.01f; + glm::vec3 pos(glm::sin(angle) * 10.0f, 2.5f, glm::cos(angle) * 10.0f); + this->view = glm::lookAt(pos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); + this->perFrameParams.ModelViewProjection = this->proj * this->view * this->model; +} + +//------------------------------------------------------------------------------ +void +DrawCallPerfApp::emitParticles() { + for (int32 i = 0; i < NumParticlesEmittedPerFrame; i++) { + if (this->curNumParticles < MaxNumParticles) { + this->particles[this->curNumParticles].pos = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); + glm::vec3 rnd = glm::ballRand(0.5f); + rnd.y += 2.0f; + this->particles[this->curNumParticles].vec = glm::vec4(rnd, 0.0f); + this->curNumParticles++; + } + } +} + +//------------------------------------------------------------------------------ +void +DrawCallPerfApp::updateParticles() { + const float32 frameTime = 1.0f / 60.0f; + for (int32 i = 0; i < this->curNumParticles; i++) { + auto& curParticle = this->particles[i]; + curParticle.vec.y -= 1.0f * frameTime; + curParticle.pos += curParticle.vec * frameTime; + if (curParticle.pos.y < -2.0f) { + curParticle.pos.y = -1.8f; + curParticle.vec.y = -curParticle.vec.y; + curParticle.vec *= 0.8f; + } + } +} + +//------------------------------------------------------------------------------ +AppState::Code +DrawCallPerfApp::OnInit() { + // setup rendering system + GfxSetup gfxSetup = GfxSetup::Window(800, 500, "Oryol DrawCallPerf Sample"); + gfxSetup.GlobalUniformBufferSize = 1024 * 1024 * 32; + Gfx::Setup(gfxSetup); + Dbg::Setup(); + Input::Setup(); + + // create resources + const glm::mat4 rot90 = glm::rotate(glm::mat4(), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); + ShapeBuilder shapeBuilder; + shapeBuilder.RandomColors = true; + shapeBuilder.Layout + .Add(VertexAttr::Position, VertexFormat::Float3) + .Add(VertexAttr::Color0, VertexFormat::Float4); + shapeBuilder.Transform(rot90).Sphere(0.05f, 3, 2).Build(); + Id mesh = Gfx::CreateResource(shapeBuilder.Result()); + Id shd = Gfx::CreateResource(Shaders::Main::Setup()); + auto dss = DrawStateSetup::FromMeshAndShader(mesh, shd); + dss.RasterizerState.CullFaceEnabled = true; + dss.DepthStencilState.DepthWriteEnabled = true; + dss.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; + this->drawState = Gfx::CreateResource(dss); + + // setup projection and view matrices + const float32 fbWidth = (const float32) Gfx::DisplayAttrs().FramebufferWidth; + const float32 fbHeight = (const float32) Gfx::DisplayAttrs().FramebufferHeight; + this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f); + this->view = glm::lookAt(glm::vec3(0.0f, 2.5f, 0.0f), glm::vec3(0.0f, 0.0f, -10.0f), glm::vec3(0.0f, 1.0f, 0.0f)); + this->model = glm::mat4(); + + return App::OnInit(); +} + +//------------------------------------------------------------------------------ +AppState::Code +DrawCallPerfApp::OnCleanup() { + Dbg::Discard(); + Input::Discard(); + Gfx::Discard(); + return App::OnCleanup(); +} diff --git a/pool/shard007/C++/0095359_bw_file_rd.cpp b/pool/shard007/C++/0095359_bw_file_rd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9149c43aab32747d16054a14ee288853fc09b7ef --- /dev/null +++ b/pool/shard007/C++/0095359_bw_file_rd.cpp @@ -0,0 +1,124 @@ +/* + * bw_file_rd.c - time reading & summing of a file + * + * Usage: bw_file_rd [-C] [-P ] [-N ] size file + * + * The intent is that the file is in memory. + * Disk benchmarking is done with lmdd. + * + * Copyright (c) 1994 Larry McVoy. Distributed under the FSF GPL with + * additional restriction that results may published only if + * (1) the benchmark is unmodified, and + * (2) the version in the sccsid below is included in the report. + * Support for this development by Sun Microsystems is gratefully acknowledged. + */ +// char *id = "$Id$\n"; + +#include "bench.h" + +#include "bench.h" + +#define CHK(x) if ((int)(x) == -1) { perror("x"); exit(1); } +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#define TYPE int +#define MINSZ (sizeof(TYPE) * 128) + +TYPE *buf; /* do the I/O here */ +TYPE *lastone; /* I/O ends here + MINSZ */ +int xfersize; /* do it in units of this */ +int count; /* bytes to move (can't be modified) */ + +void +bwfilerd_doit(int fd) +{ + int sum = 0, size; + register TYPE *p, *end; + + + size = count; + end = lastone; + while (size >= 0) { + if (read(fd, buf, MIN(size, xfersize)) <= 0) { + break; + } + for (p = buf; p <= end; ) { + sum += + p[0]+p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]+ + p[8]+p[9]+p[10]+p[11]+p[12]+p[13]+p[14]+ + p[15]+p[16]+p[17]+p[18]+p[19]+p[20]+p[21]+ + p[22]+p[23]+p[24]+p[25]+p[26]+p[27]+p[28]+ + p[29]+p[30]+p[31]+p[32]+p[33]+p[34]+p[35]+ + p[36]+p[37]+p[38]+p[39]+p[40]+p[41]+p[42]+ + p[43]+p[44]+p[45]+p[46]+p[47]+p[48]+p[49]+ + p[50]+p[51]+p[52]+p[53]+p[54]+p[55]+p[56]+ + p[57]+p[58]+p[59]+p[60]+p[61]+p[62]+p[63]+ + p[64]+p[65]+p[66]+p[67]+p[68]+p[69]+p[70]+ + p[71]+p[72]+p[73]+p[74]+p[75]+p[76]+p[77]+ + p[78]+p[79]+p[80]+p[81]+p[82]+p[83]+p[84]+ + p[85]+p[86]+p[87]+p[88]+p[89]+p[90]+p[91]+ + p[92]+p[93]+p[94]+p[95]+p[96]+p[97]+p[98]+ + p[99]+p[100]+p[101]+p[102]+p[103]+p[104]+ + p[105]+p[106]+p[107]+p[108]+p[109]+p[110]+ + p[111]+p[112]+p[113]+p[114]+p[115]+p[116]+ + p[117]+p[118]+p[119]+p[120]+p[121]+p[122]+ + p[123]+p[124]+p[125]+p[126]+p[127]; + p += 128; + } + size -= xfersize; + } + use_int(sum); +} + +void +bwfilerd_time_with_open(char *file) +{ + int fd = open(file, 0); + + bwfilerd_doit(fd); + close(fd); +} + +void +bwfilerd_time_io_only(int fd) +{ + lseek(fd, 0, 0); + bwfilerd_doit(fd); +} + +int +bwfilerd_main(int ac, char **av) +{ + int fd; + char *av3 = strdup(av[3]); + + if (ac != 4) { + fprintf(stderr, + "Usage: %s size open2close|io_only file, min size=%uk\n", + av[0], XFERSIZE>>10); + exit(1); + } + count = bytes(av[1]); + if (count < MINSZ) { + exit(1); /* I want this to be quiet */ + } + if (count < XFERSIZE) { + xfersize = count; + } else { + xfersize = XFERSIZE; + } + buf = (TYPE *)valloc(XFERSIZE); + lastone = (TYPE*)((char*)buf + xfersize - MINSZ); + bzero((void*)buf, XFERSIZE); + if (!strcmp("open2close", av[2])) { + BENCH(bwfilerd_time_with_open(av3), 0); + } else { + CHK(fd = open(av3, 0)); + BENCH(bwfilerd_time_io_only(fd), 0); + close(fd); + } + bandwidth(count, get_n(), 0); + return (0); +} diff --git a/pool/shard007/C++/0095363_sessions_page_revisit_observer.cc b/pool/shard007/C++/0095363_sessions_page_revisit_observer.cc new file mode 100644 index 0000000000000000000000000000000000000000..36a9a6c32e42c4e2eb9ca6762f0f4d00af5ac3b9 --- /dev/null +++ b/pool/shard007/C++/0095363_sessions_page_revisit_observer.cc @@ -0,0 +1,83 @@ +// 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/sync_sessions/revisit/sessions_page_revisit_observer.h" + +#include + +#include "base/metrics/histogram_macros.h" +#include "base/thread_task_runner_handle.h" +#include "base/time/time.h" +#include "components/sessions/core/session_types.h" +#include "components/sync_sessions/revisit/current_tab_matcher.h" +#include "components/sync_sessions/revisit/offset_tab_matcher.h" +#include "components/sync_sessions/revisit/page_equality.h" +#include "components/sync_sessions/synced_session.h" +#include "url/gurl.h" + +namespace sync_sessions { + +SessionsPageRevisitObserver::SessionsPageRevisitObserver( + scoped_ptr provider) + : provider_(std::move(provider)) {} + +SessionsPageRevisitObserver::~SessionsPageRevisitObserver() {} + +void SessionsPageRevisitObserver::OnPageVisit( + const GURL& url, + const PageVisitObserver::TransitionType transition) { + // We need to be invoked and eventually execute on the thread which owns the + // session objects the provider will give us. However, this work is not + // especially time sensitive, and so we post a task to perform this to get out + // of the way of any currently executing logic. + + // Bind this task to this->AsWeakPtr() so that if we're destructed this task + // just vanish instead of breaking things. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&SessionsPageRevisitObserver::CheckForRevisit, + this->AsWeakPtr(), url, transition)); +} + +void SessionsPageRevisitObserver::CheckForRevisit( + const GURL& url, + const PageVisitObserver::TransitionType transition) { + base::TimeTicks start(base::TimeTicks::Now()); + + // We want to match tabs/navigation entries in two slightly different ways. We + // value the current url/navigation entry of a tab more highly, and want to + // actually seperate metrics from the backwards/forwards entries. And then + // to make things a little bit messier, we only have an accurate modified time + // for the tabs/current entries. So use index offset for forward/back entries. + PageEquality page_equality(url); + CurrentTabMatcher current_matcher(page_equality); + OffsetTabMatcher offset_matcher(page_equality); + + std::vector foreign_sessions; + if (provider_->GetAllForeignSessions(&foreign_sessions)) { + for (const sync_driver::SyncedSession* session : foreign_sessions) { + for (const std::pair& + key_value : session->windows) { + for (const sessions::SessionTab* tab : key_value.second->tabs) { + // These matchers look identical and could easily implement an + // interface and we could iterate through a vector of matchers here. + // However this would cause quite a bit of overhead at the inner most + // loop of something that takes linear time in relation to the number + // of open foreign tabs. A small fraction of users have thousands of + // open tabs. + current_matcher.Check(tab); + offset_matcher.Check(tab); + } + } + } + } + + // emit even if there are no foreign sessions so that that counts all match. + current_matcher.Emit(transition); + offset_matcher.Emit(transition); + + base::TimeDelta duration(base::TimeTicks::Now() - start); + UMA_HISTOGRAM_TIMES("Sync.PageRevisitSessionDuration", duration); +} + +} // namespace sync_sessions diff --git a/pool/shard007/C++/0095367_prune_test.cc b/pool/shard007/C++/0095367_prune_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..8af7d2d510d36e4c24ce3ae8dbc13c24ad5d4a0f --- /dev/null +++ b/pool/shard007/C++/0095367_prune_test.cc @@ -0,0 +1,151 @@ +/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ + +#include "paddle/fluid/framework/prune.h" + +#include +#include + +#include "paddle/fluid/framework/attribute.h" +#include "paddle/fluid/framework/operator.h" + +#include "paddle/fluid/framework/block_desc.h" +#include "paddle/fluid/framework/op_desc.h" +#include "paddle/fluid/framework/program_desc.h" + +namespace f = paddle::framework; + +void AddOp(const std::string &type, const f::VariableNameMap &inputs, + const f::VariableNameMap &outputs, f::AttributeMap attrs, + paddle::framework::BlockDesc *block) { + // insert output + for (auto kv : outputs) { + for (auto v : kv.second) { + auto var = block->Var(v); + var->SetDataType(paddle::framework::proto::VarType::FP32); + } + } + + // insert op + auto op = block->AppendOp(); + op->SetType(type); + for (auto &kv : inputs) { + op->SetInput(kv.first, kv.second); + } + for (auto &kv : outputs) { + op->SetOutput(kv.first, kv.second); + } + op->SetAttrMap(attrs); +} + +TEST(Prune, one_operator) { + f::ProgramDesc program; + f::BlockDesc *block = program.MutableBlock(0); + + AddOp("one_one", {{"input", {"a"}}}, {{"output", {"b"}}}, f::AttributeMap{}, + block); + + f::proto::ProgramDesc *pdesc = program.Proto(); + f::proto::ProgramDesc pruned; + + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), 0); + + pdesc->mutable_blocks(0)->mutable_ops(0)->set_is_target(true); + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), 1); +} + +TEST(Prune, forward) { + f::ProgramDesc program; + f::BlockDesc *block = program.MutableBlock(0); + + AddOp("one_one", {{"input", {"a"}}}, {{"output", {"b"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"b"}}}, {{"output", {"c"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"c"}}}, {{"output", {"d"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"d"}}}, {{"output", {"e"}}}, f::AttributeMap{}, + block); + + f::proto::ProgramDesc *pdesc = program.Proto(); + + for (int i = 0; i < pdesc->blocks(0).ops_size(); ++i) { + f::proto::ProgramDesc pruned; + pdesc->mutable_blocks(0)->mutable_ops(i)->set_is_target(true); + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), i + 1); + } +} + +TEST(Prune, multi_input_op) { + f::ProgramDesc program; + f::BlockDesc *block = program.MutableBlock(0); + + AddOp("one_one", {{"input", {"a0"}}}, {{"output", {"b0"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"a1"}}}, {{"output", {"b1"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"a2"}}}, {{"output", {"b2"}}}, f::AttributeMap{}, + block); + AddOp("three_one", {{"input", {"b0", "b1", "b2"}}}, {{"output", {"c"}}}, + f::AttributeMap{}, block); + + f::proto::ProgramDesc *pdesc = program.Proto(); + pdesc->mutable_blocks(0)->mutable_ops(3)->set_is_target(true); + + f::proto::ProgramDesc pruned; + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), 4); +} + +TEST(Prune, multi_output_op) { + f::ProgramDesc program; + f::BlockDesc *block = program.MutableBlock(0); + + AddOp("one_two", {{"input", {"a"}}}, {{"output", {"b", "c"}}}, + f::AttributeMap{}, block); + AddOp("one_one", {{"input", {"b"}}}, {{"output", {"b1"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"c"}}}, {{"output", {"c1"}}}, f::AttributeMap{}, + block); + + f::proto::ProgramDesc *pdesc = program.Proto(); + pdesc->mutable_blocks(0)->mutable_ops(2)->set_is_target(true); + + f::proto::ProgramDesc pruned; + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), 2); +} + +TEST(Prune, multi_target) { + f::ProgramDesc program; + f::BlockDesc *block = program.MutableBlock(0); + + AddOp("one_two", {{"input", {"a"}}}, {{"output", {"b", "c"}}}, + f::AttributeMap{}, block); + AddOp("one_one", {{"input", {"b"}}}, {{"output", {"b1"}}}, f::AttributeMap{}, + block); + AddOp("one_one", {{"input", {"c"}}}, {{"output", {"c1"}}}, f::AttributeMap{}, + block); + + f::proto::ProgramDesc *pdesc = program.Proto(); + pdesc->mutable_blocks(0)->mutable_ops(1)->set_is_target(true); + pdesc->mutable_blocks(0)->mutable_ops(2)->set_is_target(true); + + f::proto::ProgramDesc pruned; + f::Prune(*pdesc, &pruned); + PADDLE_ENFORCE_EQ(pruned.blocks(0).ops_size(), 3); +} diff --git a/pool/shard007/C++/0095369_medianOfSortedArrays.cpp b/pool/shard007/C++/0095369_medianOfSortedArrays.cpp new file mode 100644 index 0000000000000000000000000000000000000000..770035a71d85898b745da5ac3e2794fdb7298aaa --- /dev/null +++ b/pool/shard007/C++/0095369_medianOfSortedArrays.cpp @@ -0,0 +1,138 @@ +#include +#include +#include // std::max +using namespace std; + +// A utility function to find median of two integers +double MO2(int a, int b) +{ return ( a + b ) / 2.0; } + +// A utility function to find median of three integers +double MO3(int a, int b, int c) +{ + return a + b + c - max(a, max(b, c)) + - min(a, min(b, c)); +} + +// A utility function to find median of four integers +double MO4(int a, int b, int c, int d) +{ + int Max = max( a, max( b, max( c, d ) ) ); + int Min = min( a, min( b, min( c, d ) ) ); + return ( a + b + c + d - Max - Min ) / 2.0; +} + +// Utility function to find median of single array +double medianSingle(int arr[], int n) +{ + if (n == 0) + return -1; + if (n%2 == 0) + return (arr[n/2] + arr[n/2-1])/2.0; + return arr[n/2]; +} + +// This function assumes that N is smaller than or equal to M +// This function returns -1 if both arrays are empty +double findMedianUtil( int A[], int N, int B[], int M ) +{ + cout << N << "," << M << endl; + + // If smaller array is empty, return median from second array + if (N == 0) + return medianSingle(B, M); + + // If the smaller array has only one element + if (N == 1) + { + // Case 1: If the larger array also has one element, + // simply call MO2() + if (M == 1) + return MO2(A[0], B[0]); + + // Case 2: If the larger array has odd number of elements, + // then consider the middle 3 elements of larger array and + // the only element of smaller array. Take few examples + // like following + // A = {9}, B[] = {5, 8, 10, 20, 30} and + // A[] = {1}, B[] = {5, 8, 10, 20, 30} + if (M & 1) + return MO2( B[M/2], MO3(A[0], B[M/2 - 1], B[M/2 + 1]) ); + + // Case 3: If the larger array has even number of element, + // then median will be one of the following 3 elements + // ... The middle two elements of larger array + // ... The only element of smaller array + return MO3( B[M/2], B[M/2 - 1], A[0] ); + } + + // If the smaller array has two elements + else if (N == 2) + { + // Case 4: If the larger array also has two elements, + // simply call MO4() + if (M == 2) + return MO4(A[0], A[1], B[0], B[1]); + + // Case 5: If the larger array has odd number of elements, + // then median will be one of the following 3 elements + // 1. Middle element of larger array + // 2. Max of first element of smaller array and element + // just before the middle in bigger array + // 3. Min of second element of smaller array and element + // just after the middle in bigger array + if (M & 1) + return MO3 ( B[M/2], + max(A[0], B[M/2 - 1]), + min(A[1], B[M/2 + 1]) + ); + + // Case 6: If the larger array has even number of elements, + // then median will be one of the following 4 elements + // 1) & 2) The middle two elements of larger array + // 3) Max of first element of smaller array and element + // just before the first middle element in bigger array + // 4. Min of second element of smaller array and element + // just after the second middle in bigger array + return MO4 ( B[M/2], + B[M/2 - 1], + max( A[0], B[M/2 - 2] ), + min( A[1], B[M/2 + 1] ) + ); + } + + int idxA = ( N - 1 ) / 2; + int idxB = ( M - 1 ) / 2; + + /* if A[idxA] <= B[idxB], then median must exist in + A[idxA....] and B[....idxB] */ + if (A[idxA] <= B[idxB] ) + return findMedianUtil(A + idxA, N/2 + 1, B, M - idxA ); + + /* if A[idxA] > B[idxB], then median must exist in + A[...idxA] and B[idxB....] */ + return findMedianUtil(A, N/2 + 1, B + idxA, M - idxA ); +} + +// A wrapper function around findMedianUtil(). This function +// makes sure that smaller array is passed as first argument +// to findMedianUtil +double findMedian( int A[], int N, int B[], int M ) +{ + if (N > M) + return findMedianUtil( B, M, A, N ); + + return findMedianUtil( A, N, B, M ); +} + +int main() +{ + int A[] = {1,2,3,4,5,6,7}; + int B[] = {1,2,3,4}; + + int N = sizeof(A) / sizeof(A[0]); + int M = sizeof(B) / sizeof(B[0]); + + printf("%f", findMedian( A, N, B, M ) ); + return 0; +} diff --git a/pool/shard007/C++/0095370_rpl_gtid_specification.cc b/pool/shard007/C++/0095370_rpl_gtid_specification.cc new file mode 100644 index 0000000000000000000000000000000000000000..7fde7441b736149e3d149804227e5add4b41c01d --- /dev/null +++ b/pool/shard007/C++/0095370_rpl_gtid_specification.cc @@ -0,0 +1,108 @@ +/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. 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, version 2.0, + as published by the Free Software Foundation. + + This program is also distributed with certain software (including + but not limited to OpenSSL) that is licensed under separate terms, + as designated in a particular file or component or in included license + documentation. The authors of MySQL hereby grant you an additional + permission to link the program and your derivative works with the + separately licensed software that they have included with MySQL. + + 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, version 2.0, 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 "rpl_gtid.h" + + +//const int Gtid_specification::MAX_TEXT_LENGTH; + +#ifndef MYSQL_CLIENT + +enum_return_status Gtid_specification::parse(Sid_map *sid_map, const char *text) +{ + DBUG_ENTER("Gtid_specification::parse"); + DBUG_ASSERT(text != NULL); + if (my_strcasecmp(&my_charset_latin1, text, "AUTOMATIC") == 0) + { + type= AUTOMATIC_GROUP; + gtid.sidno= 0; + gtid.gno= 0; + } + else if (my_strcasecmp(&my_charset_latin1, text, "ANONYMOUS") == 0) + { + type= ANONYMOUS_GROUP; + gtid.sidno= 0; + gtid.gno= 0; + } + else + { + PROPAGATE_REPORTED_ERROR(gtid.parse(sid_map, text)); + type= GTID_GROUP; + } + RETURN_OK; +}; + + +bool Gtid_specification::is_valid(const char *text) +{ + DBUG_ENTER("Gtid_specification::is_valid"); + DBUG_ASSERT(text != NULL); + if (my_strcasecmp(&my_charset_latin1, text, "AUTOMATIC") == 0) + DBUG_RETURN(true); + else if (my_strcasecmp(&my_charset_latin1, text, "ANONYMOUS") == 0) + DBUG_RETURN(true); + else + DBUG_RETURN(Gtid::is_valid(text)); +} + +#endif // ifndef MYSQL_CLIENT + + +int Gtid_specification::to_string(const rpl_sid *sid, char *buf) const +{ + DBUG_ENTER("Gtid_specification::to_string(char*)"); + switch (type) + { + case AUTOMATIC_GROUP: + strcpy(buf, "AUTOMATIC"); + DBUG_RETURN(9); + case NOT_YET_DETERMINED_GROUP: + /* + This can happen if user issues SELECT @@SESSION.GTID_NEXT + immediately after a BINLOG statement containing a + Format_description_log_event. + */ + strcpy(buf, "NOT_YET_DETERMINED"); + DBUG_RETURN(18); + case ANONYMOUS_GROUP: + strcpy(buf, "ANONYMOUS"); + DBUG_RETURN(9); + /* + UNDEFINED_GROUP must be printed like GTID_GROUP because of + SELECT @@SESSION.GTID_NEXT. + */ + case UNDEFINED_GROUP: + case GTID_GROUP: + DBUG_RETURN(gtid.to_string(*sid, buf)); + } + DBUG_ASSERT(0); + DBUG_RETURN(0); +} + + +int Gtid_specification::to_string(const Sid_map *sid_map, char *buf, bool need_lock) const +{ + return to_string(type == GTID_GROUP || type == UNDEFINED_GROUP ? + &sid_map->sidno_to_sid(gtid.sidno, need_lock) : NULL, + buf); +} diff --git a/pool/shard007/C++/0095371_cmd_merge_down_layer.cpp b/pool/shard007/C++/0095371_cmd_merge_down_layer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7a60676bac4b4e53534235646904adb79ca5164 --- /dev/null +++ b/pool/shard007/C++/0095371_cmd_merge_down_layer.cpp @@ -0,0 +1,194 @@ +/* Aseprite + * Copyright (C) 2001-2013 David Capello + * + * 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 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "app/app.h" +#include "app/commands/command.h" +#include "app/context_access.h" +#include "app/document.h" +#include "app/document_api.h" +#include "app/modules/gui.h" +#include "app/undo_transaction.h" +#include "app/undoers/add_cel.h" +#include "app/undoers/add_image.h" +#include "app/undoers/remove_layer.h" +#include "app/undoers/replace_image.h" +#include "app/undoers/set_cel_position.h" +#include "base/unique_ptr.h" +#include "raster/cel.h" +#include "raster/image.h" +#include "raster/layer.h" +#include "raster/primitives.h" +#include "raster/sprite.h" +#include "raster/stock.h" +#include "ui/ui.h" + +namespace app { + +class MergeDownLayerCommand : public Command { +public: + MergeDownLayerCommand(); + Command* clone() const override { return new MergeDownLayerCommand(*this); } + +protected: + bool onEnabled(Context* context); + void onExecute(Context* context); +}; + +MergeDownLayerCommand::MergeDownLayerCommand() + : Command("MergeDownLayer", + "Merge Down Layer", + CmdRecordableFlag) +{ +} + +bool MergeDownLayerCommand::onEnabled(Context* context) +{ + ContextWriter writer(context); + Sprite* sprite(writer.sprite()); + if (!sprite) + return false; + + Layer* src_layer = writer.layer(); + if (!src_layer || !src_layer->isImage()) + return false; + + Layer* dst_layer = src_layer->getPrevious(); + if (!dst_layer || !dst_layer->isImage()) + return false; + + return true; +} + +void MergeDownLayerCommand::onExecute(Context* context) +{ + ContextWriter writer(context); + Document* document(writer.document()); + Sprite* sprite(writer.sprite()); + UndoTransaction undo(writer.context(), "Merge Down Layer", undo::ModifyDocument); + Layer* src_layer = writer.layer(); + Layer* dst_layer = src_layer->getPrevious(); + int index; + + for (FrameNumber frpos(0); frpostotalFrames(); ++frpos) { + // Get frames + Cel* src_cel = static_cast(src_layer)->getCel(frpos); + Cel* dst_cel = static_cast(dst_layer)->getCel(frpos); + + // Get images + Image* src_image; + if (src_cel != NULL) + src_image = src_cel->image(); + else + src_image = NULL; + + Image* dst_image; + if (dst_cel != NULL) + dst_image = dst_cel->image(); + else + dst_image = NULL; + + // With source image? + if (src_image != NULL) { + // No destination image + if (dst_image == NULL) { // Only a transparent layer can have a null cel + // Copy this cel to the destination layer... + + // Creating a copy of the image + dst_image = Image::createCopy(src_image); + + // Adding it in the stock of images + index = sprite->stock()->addImage(dst_image); + if (undo.isEnabled()) + undo.pushUndoer(new undoers::AddImage( + undo.getObjects(), sprite->stock(), index)); + + // Creating a copy of the cell + dst_cel = new Cel(frpos, index); + dst_cel->setPosition(src_cel->x(), src_cel->y()); + dst_cel->setOpacity(src_cel->opacity()); + + if (undo.isEnabled()) + undo.pushUndoer(new undoers::AddCel(undo.getObjects(), dst_layer, dst_cel)); + + static_cast(dst_layer)->addCel(dst_cel); + } + // With destination + else { + int x1, y1, x2, y2; + + // Merge down in the background layer + if (dst_layer->isBackground()) { + x1 = 0; + y1 = 0; + x2 = sprite->width(); + y2 = sprite->height(); + } + // Merge down in a transparent layer + else { + x1 = MIN(src_cel->x(), dst_cel->x()); + y1 = MIN(src_cel->y(), dst_cel->y()); + x2 = MAX(src_cel->x()+src_image->width()-1, dst_cel->x()+dst_image->width()-1); + y2 = MAX(src_cel->y()+src_image->height()-1, dst_cel->y()+dst_image->height()-1); + } + + raster::color_t bgcolor = app_get_color_to_clear_layer(dst_layer); + + Image* new_image = raster::crop_image(dst_image, + x1-dst_cel->x(), + y1-dst_cel->y(), + x2-x1+1, y2-y1+1, bgcolor); + + // Merge src_image in new_image + raster::composite_image(new_image, src_image, + src_cel->x()-x1, + src_cel->y()-y1, + src_cel->opacity(), + static_cast(src_layer)->getBlendMode()); + + if (undo.isEnabled()) + undo.pushUndoer(new undoers::SetCelPosition(undo.getObjects(), dst_cel)); + + dst_cel->setPosition(x1, y1); + + if (undo.isEnabled()) + undo.pushUndoer(new undoers::ReplaceImage(undo.getObjects(), + sprite->stock(), dst_cel->imageIndex())); + + sprite->stock()->replaceImage(dst_cel->imageIndex(), new_image); + delete dst_image; + } + } + } + + document->notifyLayerMergedDown(src_layer, dst_layer); + document->getApi().removeLayer(src_layer); // src_layer is deleted inside removeLayer() + + undo.commit(); + update_screen_for_document(document); +} + +Command* CommandFactory::createMergeDownLayerCommand() +{ + return new MergeDownLayerCommand; +} + +} // namespace app diff --git a/pool/shard007/C++/0095372_bitcoin.cpp b/pool/shard007/C++/0095372_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b922848df8028dca1d7109e71f94070b33820ff --- /dev/null +++ b/pool/shard007/C++/0095372_bitcoin.cpp @@ -0,0 +1,304 @@ +/* + * W.J. van der Laan 2011-2012 + */ + +#include + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "init.h" +#include "util.h" +#include "ui_interface.h" +#include "paymentserver.h" +#include "splashscreen.h" + +#include +#if QT_VERSION < 0x050000 +#include +#endif +#include +#include +#include +#include + +#ifdef Q_OS_MAC +#include "macdockiconhandler.h" +#endif + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Declare meta types used for QMetaObject::invokeMethod +Q_DECLARE_METATYPE(bool*) + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static SplashScreen *splashref; + +static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + bool ret = false; + // In case of modal message, use blocking connection to wait for user to click a button + QMetaObject::invokeMethod(guiref, "message", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(unsigned int, style), + Q_ARG(bool*, &ret)); + return ret; + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + return false; + } +} + +static bool ThreadSafeAskFee(int64 nFeeRequired) +{ + if(!guiref) + return false; + if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) + return true; + + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); + qApp->processEvents(); + } + printf("init message: %s\n", message.c_str()); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Ponscoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Command-line options take precedence: + ParseParameters(argc, argv); + +#if QT_VERSION < 0x050000 + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); +#endif + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Register meta types used for QMetaObject::invokeMethod + qRegisterMetaType< bool* >(); + + // Do this early as we don't want to bother initializing if we are just calling IPC + // ... but do it after creating app, so QCoreApplication::arguments is initialized: + if (PaymentServer::ipcSendCommandLine()) + exit(0); + PaymentServer* paymentServer = new PaymentServer(&app); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "Ponscoin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + QApplication::setOrganizationName("Ponscoin"); + QApplication::setOrganizationDomain("ponscoin.org"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + QApplication::setApplicationName("Ponscoin-Qt-testnet"); + else + QApplication::setApplicationName("Ponscoin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + +#ifdef Q_OS_MAC + // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) + if(GetBoolArg("-testnet")) { + MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); + } +#endif + + SplashScreen splash(QPixmap(), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + app.setQuitOnLastWindowClosed(false); + + try + { +#ifndef Q_OS_MAC + // Regenerate startup link, to fix links to old versions + // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); +#endif + + boost::thread_group threadGroup; + + BitcoinGUI window; + guiref = &window; + + QTimer* pollShutdownTimer = new QTimer(guiref); + QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); + pollShutdownTimer->start(200); + + if(AppInit2(threadGroup)) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.addWallet("~Default", &walletModel); + window.setCurrentWallet("~Default"); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Now that initialization/startup is done, process any command-line + // bitcoin: URIs + QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); + QTimer::singleShot(100, paymentServer, SLOT(uiReady())); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.removeAllWallets(); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + } + else + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard007/C++/0095375_powerMotor.cpp b/pool/shard007/C++/0095375_powerMotor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b19031abdccbdd1289480fe99565e1c655433d4e --- /dev/null +++ b/pool/shard007/C++/0095375_powerMotor.cpp @@ -0,0 +1,164 @@ +/* Copyright 2013 - 2016 Yurii Litvinov, Anastasiia Kornilova and CyberTech Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + +#include "powerMotor.h" + +#include +#include +#include +#include +#include "mspI2cCommunicator.h" +#include "configurerHelper.h" + +using namespace trikControl; + +static const int maxControlValue = 100; +static const int minControlValue = -100; + +PowerMotor::PowerMotor(const QString &port, const trikKernel::Configurer &configurer + , MspCommunicatorInterface &communicator) + : mCommunicator(communicator) + , mInvert(configurer.attributeByPort(port, "invert") == "false") + , mCurrentPower(0) + , mState("Power Motor on" + port) +{ + mMspCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, "i2cCommandNumber"); + + mCurrentPeriod = ConfigurerHelper::configureInt(configurer, mState, port, "period"); + setPeriod(mCurrentPeriod); + + mPowerMap.reserve(maxControlValue + 1); + lineariseMotor(port, configurer); + + mState.ready(); +} + +PowerMotor::~PowerMotor() +{ +} + +PowerMotor::Status PowerMotor::status() const +{ + return combine(mCommunicator, mState.status()); +} + +void PowerMotor::setPower(int power, bool constrain) +{ + if (constrain) { + if (power > maxControlValue) { + power = maxControlValue; + } else if (power < minControlValue) { + power = minControlValue; + } + power = power <= 0 ? -mPowerMap[-power] : mPowerMap[power]; + } + + mCurrentPower = power; + + + power = mInvert ? -power : power; + + QByteArray command(3, '\0'); + command[0] = static_cast(mMspCommandNumber & 0xFF); + command[1] = static_cast((mMspCommandNumber >> 8) & 0xFF); + command[2] = static_cast(power & 0xFF); + + mCommunicator.send(command); +} + +int PowerMotor::power() const +{ + return mCurrentPower; +} + +int PowerMotor::period() const +{ + return mCurrentPeriod; +} + +void PowerMotor::powerOff() +{ + setPower(0, false); // ignore power units translation (linearisation) +} + +void PowerMotor::forceBreak(int durationMs) +{ + if (durationMs <= 0) + forceBreak(); + setPower(0x7f, false); + QTimer::singleShot(durationMs, this, SLOT(powerOff())); +} + +void PowerMotor::setPeriod(int period) +{ + mCurrentPeriod = period; + QByteArray command(4, '\0'); + command[0] = static_cast((mMspCommandNumber - 4) & 0xFF); + command[2] = static_cast(period & 0xFF); + command[3] = static_cast(period >> 8); + mCommunicator.send(command); +} + +void PowerMotor::lineariseMotor(const QString &port, const trikKernel::Configurer &configurer) +{ + QVector> powerGraph; + for (const QString &str : configurer.attributeByPort(port, "measures").split(")")) { + if (!str.isEmpty()) { + QPair temp; + temp.first = str.mid(1).split(";").at(0).toInt(); + temp.second = str.mid(1).split(";").at(1).toInt(); + powerGraph.append(temp); + } + } + + const int graphLength = powerGraph.size(); + const int maxValue = powerGraph[graphLength - 1].second; + + for (int i = 0; i < graphLength; i++) { + powerGraph[i].second *= maxControlValue; + powerGraph[i].second /= maxValue; + } + + for (int i = 0; i < maxControlValue; i++) { + int k = 0; + while (i >= powerGraph[k].second) { + k++; + } + + k--; + + const double measureDifference = powerGraph[k + 1].second - powerGraph[k].second; + const double axeDifferenece = powerGraph[k + 1].first - powerGraph[k].first; + + if (measureDifference < 0 || axeDifferenece < 0) { + throw trikKernel::MalformedConfigException("Nonmonotonic function"); + } + + const double coef = axeDifferenece / measureDifference; + const int power = powerGraph[k].first + coef * (i - powerGraph[k].second); + mPowerMap.append(power); + } + + mPowerMap.append(maxControlValue); +} + +int PowerMotor::minControl() const +{ + return minControlValue; +} + +int PowerMotor::maxControl() const +{ + return maxControlValue; +} diff --git a/pool/shard007/C++/0095378_main.cpp b/pool/shard007/C++/0095378_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c978fbe58bf26466bea3f2d20d96fc804543cbd4 --- /dev/null +++ b/pool/shard007/C++/0095378_main.cpp @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** 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, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +void mergeFormat(QTextEdit *edit) +{ +//! [0] + QTextDocument *document = edit->document(); + QTextCursor cursor(document); + + cursor.movePosition(QTextCursor::Start); + cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); + + QTextCharFormat format; + format.setFontWeight(QFont::Bold); + + cursor.mergeCharFormat(format); +//! [0] +} + +int main(int argc, char *argv[]) +{ + QWidget *parent = 0; + QString aStringContainingHTMLtext("

Scribe Overview

"); + + QApplication app(argc, argv); + +//! [1] + QTextEdit *editor = new QTextEdit(parent); + editor->setHtml(aStringContainingHTMLtext); + editor->show(); +//! [1] + + return app.exec(); +} diff --git a/pool/shard007/C++/0095381_00543_goldbach_conjecture.cpp b/pool/shard007/C++/0095381_00543_goldbach_conjecture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e3275f158b02976a10960b18e2f0f41d1b0bfd5 --- /dev/null +++ b/pool/shard007/C++/0095381_00543_goldbach_conjecture.cpp @@ -0,0 +1,90 @@ +/********************************************************************* +Goldbach's conjecture +--------------------- +UVa ID: 005 43 + +In 1742, Christian Goldbach, a German amateur mathematician, sent a +letter to Leonhard Euler in which he made the following conjecture: + Every number greater than 2 can be written + as the sum of three prime numbers. +Goldbach was considering 1 as a primer number, a convention that is +no longer followed. Later on, Euler re-expressed the conjecture as: + Every even number greater than or equal to 4 + can be expressed as the sum of two prime numbers. +Today it is still unproven whether the conjecture is right. Anyway, +your task is now to verify Goldbach's conjecture as expressed by +Euler for all even numbers less than a million. + +Input +----- +The input file will contain one or more test cases. Each test case +consists of one even integer n with 6 <= n < 1'000'000. Input will +be terminated by a value of 0 for n. + +Output +------ +For each test case, print one line of the form n = a + b, where +a and b are odd primes. Numbers and operators should be separated by +exactly one blank like in the sample output below. If there is more +than one pair of odd primes adding up to n, choose the pair where the +difference b - a is maximized. If there is no such pair, print a line +saying "Goldbach's conjecture is wrong.". + +This file is covered by the LICENSE file in the root of this project. +**********************************************************************/ + +#include "base.hpp" +#include +#include +#include + +constexpr std::size_t max_n = 1'000'000u; + +std::vector generate_prime_flags(std::size_t max) +{ + std::vector is_prime(max + 1, true); + + is_prime[0] = is_prime[1] = false; + for (std::size_t i = 4; i <= max; i += 2) + is_prime[i] = false; + + const auto sqrt_max = static_cast(std::sqrt(max)); + for (std::size_t i = 3; i <= sqrt_max; i += 2) + if (is_prime[i]) + for (auto j = i * i; j <= max; j += 2 * i) + is_prime[j] = false; + + return is_prime; +} + +class CP : public CP2 +{ +private: + virtual void init() override + { + prime_flags_ = generate_prime_flags(max_n); + } + + virtual bool read_input() override + { + return read(n_) && n_ != 0; + } + + virtual void solve(unsigned int) override + { + for (std::size_t i = 3; i <= n_ / 2; i += 2) + if (prime_flags_[i] && prime_flags_[n_ - i]) + { + write_ln(n_, " = ", i, " + ", n_ - i); + return; + } + + write_ln("Goldbach's conjecture is wrong."); // O'RLY? ;) + } + +private: + std::size_t n_; + std::vector prime_flags_; +}; + +MAIN diff --git a/pool/shard007/C++/0095383_BLECharacteristicMap.cpp b/pool/shard007/C++/0095383_BLECharacteristicMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e64f9ca9bc8c1ab48c0fca3811e3e7352c7fc49f --- /dev/null +++ b/pool/shard007/C++/0095383_BLECharacteristicMap.cpp @@ -0,0 +1,134 @@ +/* + * BLECharacteristicMap.cpp + * + * Created on: Jun 22, 2017 + * Author: kolban + */ +#include "sdkconfig.h" +#if defined(CONFIG_BT_ENABLED) +#include +#include +#include "BLECharacteristicMap.h" + +BLECharacteristicMap::BLECharacteristicMap() { +} + +BLECharacteristicMap::~BLECharacteristicMap() { +} + + +/** + * @brief Return the characteristic by UUID. + * @param [in] UUID The UUID to look up the characteristic. + * @return The characteristic. + */ +BLECharacteristic* BLECharacteristicMap::getByUUID(BLEUUID uuid) { + for (auto &myPair : m_uuidMap) { + if (myPair.second->getUUID().equals(uuid)) { + return myPair.second; + } + } + //return m_uuidMap.at(uuid.toString()); + return nullptr; +} // getByUUID + + +/** + * @brief Return the characteristic by handle. + * @param [in] handle The handle to look up the characteristic. + * @return The characteristic. + */ +BLECharacteristic* BLECharacteristicMap::getByHandle(uint16_t handle) { + return m_handleMap.at(handle); +} // getByHandle + + +/** + * @brief Set the characteristic by UUID. + * @param [in] uuid The uuid of the characteristic. + * @param [in] characteristic The characteristic to cache. + * @return N/A. + */ +void BLECharacteristicMap::setByUUID( + BLEUUID uuid, + BLECharacteristic *pCharacteristic) { + m_uuidMap.insert(std::pair(uuid.toString(), pCharacteristic)); +} // setByUUID + + +/** + * @brief Set the characteristic by handle. + * @param [in] handle The handle of the characteristic. + * @param [in] characteristic The characteristic to cache. + * @return N/A. + */ +void BLECharacteristicMap::setByHandle(uint16_t handle, + BLECharacteristic *characteristic) { + m_handleMap.insert(std::pair(handle, characteristic)); +} // setByHandle + + +/** + * @brief Return a string representation of the characteristic map. + * @return A string representation of the characteristic map. + */ +std::string BLECharacteristicMap::toString() { + std::stringstream stringStream; + stringStream << std::hex << std::setfill('0'); + int count=0; + for (auto &myPair: m_uuidMap) { + if (count > 0) { + stringStream << "\n"; + } + count++; + stringStream << "handle: 0x" << std::setw(2) << myPair.second->getHandle() << ", uuid: " + myPair.second->getUUID().toString(); + } + return stringStream.str(); +} // toString + + +/** + * @breif Pass the GATT server event onwards to each of the characteristics found in the mapping + * @param [in] event + * @param [in] gatts_if + * @param [in] param + */ +void BLECharacteristicMap::handleGATTServerEvent( + esp_gatts_cb_event_t event, + esp_gatt_if_t gatts_if, + esp_ble_gatts_cb_param_t *param) { + // Invoke the handler for every Service we have. + for (auto &myPair : m_uuidMap) { + myPair.second->handleGATTServerEvent(event, gatts_if, param); + } +} // handleGATTServerEvent + + +/** + * @brief Get the first characteristic in the map. + * @return The first characteristic in the map. + */ +BLECharacteristic* BLECharacteristicMap::getFirst() { + m_iterator = m_uuidMap.begin(); + if (m_iterator == m_uuidMap.end()) { + return nullptr; + } + BLECharacteristic *pRet = m_iterator->second; + m_iterator++; + return pRet; +} // getFirst + + +/** + * @brief Get the next characteristic in the map. + * @return The next characteristic in the map. + */ +BLECharacteristic* BLECharacteristicMap::getNext() { + if (m_iterator == m_uuidMap.end()) { + return nullptr; + } + BLECharacteristic *pRet = m_iterator->second; + m_iterator++; + return pRet; +} // getNext +#endif /* CONFIG_BT_ENABLED */ diff --git a/pool/shard007/C++/0095394_ResourceSetup.cpp b/pool/shard007/C++/0095394_ResourceSetup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..daa8738a3447eccb93228c1ba14cc4813c34d6ae --- /dev/null +++ b/pool/shard007/C++/0095394_ResourceSetup.cpp @@ -0,0 +1,176 @@ +/* + * Copyright 2020 Arx Libertatis Team (see the AUTHORS file) + * + * This file is part of Arx Libertatis. + * + * Arx Libertatis 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. + * + * Arx Libertatis 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 Arx Libertatis. If not, see . + */ + +#include "io/resource/ResourceSetup.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "io/fs/Filesystem.h" +#include "io/fs/SystemPaths.h" +#include "io/resource/PakReader.h" +#include "io/log/Logger.h" +#include "platform/Platform.h" + +namespace { + +struct ResourceEntry { + + int dir; + + int archive; // archive type + int subtype; // archive suffix + + std::string name; + fs::path path; + + ResourceEntry(int dir_, int archive_, int subtype_, const std::string & name_, const fs::path & path_) + : dir(dir_) + , archive(archive_) + , subtype(subtype_) + , name(name_) + , path(path_) + { } + + bool operator<(const ResourceEntry & o) const { + if(archive != o.archive) { + return archive < o.archive; + } + if(dir != o.dir) { + return dir < o.dir; + } + if(subtype != o.subtype) { + return subtype < o.subtype; + } + int n = name.compare(o.name); + if(n != 0) { + return n < 0; + } + return path.string().compare(o.path.string()) < 0; + } + +}; + +struct RequiredArchive { + + const char * name; + PakFilter * filter; + +}; + +} // anonymous namespace + +bool addDefaultResources(PakReader * reader) { + + PakFilter speechFilter; + // French version has French audio copied in the deutsch and english directories + { + std::vector & filter = speechFilter[util::md5::checksum("6d2cea5370477464b43353a637a18c0c")]; + filter.push_back("speech/deutsch"); + filter.push_back("speech/english"); + } + // German version has German audio partially copied in the english and francais directories + { + std::vector & filter = speechFilter[util::md5::checksum("499b08d1a365ebea74b23a8efc9a8302")]; + filter.push_back("speech/english"); + filter.push_back("speech/francais"); + } + // Italian version has German audio partially copied in the francais directory + { + std::vector & filter = speechFilter[util::md5::checksum("ca067587556a908be255e9244209fc47")]; + filter.push_back("speech/francais"); + } + // Spanish version has Spanish audio copied in the deustch (sic) and english directories + { + std::vector & filter = speechFilter[util::md5::checksum("975be9f2c6a952b4d014dfaf0d6f1882")]; + filter.push_back("speech/deustch"); + filter.push_back("speech/english"); + } + + const char * const directories[] = { "editor", "game", "graph", "localisation", "misc", "sfx", "speech" }; + const RequiredArchive archives[] = { + { "data", NULL }, { "loc", NULL }, { "data2", NULL }, { "sfx", NULL }, { "speech", &speechFilter } + }; + + std::set resources; + + int dirindex = 0; + BOOST_REVERSE_FOREACH(const fs::path & dir, fs::getDataDirs()) { + for(fs::directory_iterator it(dir); !it.end(); ++it) { + std::string file = it.name(); + std::string name = boost::to_lower_copy(file); + if(it.is_directory()) { + BOOST_FOREACH(const char * dirname, directories) { + if(name == dirname) { + resources.insert(ResourceEntry(dirindex, std::numeric_limits::max(), 0, name, dir / file)); + break; + } + } + } + if(it.is_regular_file() && boost::ends_with(name, ".pak")) { + name.resize(name.length() - 4); + for(size_t archive = 0; archive < size_t(boost::size(archives)); archive++) { + size_t length = std::strlen(archives[archive].name); + if(name.length() >= length && name.compare(0, length, archives[archive].name, length) == 0 + && (name.length() == length || name[length] == '_')) { + // Load name_default.pak → name_*.pak → name.pak + int subtype = 0; + if(name.length() != length) { + if(name.compare(length + 1, name.length() - length - 1, "default")) { + subtype = -2; + } else { + subtype = -1; + } + } + resources.insert(ResourceEntry(dirindex, int(archive), subtype, name, dir / file)); + } + } + } + } + dirindex++; + } + + bool ok[ARRAY_SIZE(archives)] = { false }; + BOOST_FOREACH(const ResourceEntry & entry, resources) { + if(entry.archive == std::numeric_limits::max()) { + reader->addFiles(entry.path, entry.name); + } else { + if(reader->addArchive(entry.path, archives[entry.archive].filter)) { + ok[entry.archive] = true; + } + } + } + + bool result = true; + for(size_t archive = 0; archive < size_t(boost::size(archives)); archive++) { + if(!ok[archive]) { + LogError << "Missing required data file: \"" << archives[archive].name << "*.pak\""; + result = false; + } + } + + return result; +} diff --git a/pool/shard007/C++/0095395_pusher.cpp b/pool/shard007/C++/0095395_pusher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d09dfbb8894ebf8019eb9060a389c060d47d1fbe --- /dev/null +++ b/pool/shard007/C++/0095395_pusher.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +/* + * push作为连接端,去连接多个pull端 + */ + +int main(int argc, char *argv[]) +{ + if (argc < 4) { + printf("usage : %s puller_cnt puller_ip1 puller_port1 puller_ip2 puller_port2\n", argv[0]); + printf("example : %s 2 127.0.0.1 36888 127.0.0.1 36889\n", argv[0]); + return -2; + } + + int puller_cnt = atoi(argv[1]); + if (puller_cnt * 2 != (argc -2)) + { + printf("puller addr invalid!\n"); + printf("usage : %s puller_cnt puller_ip1 puller_port1 puller_ip2 puller_port2\n", argv[0]); + printf("example : %s 2 127.0.0.1 36888 127.0.0.1 36889\n", argv[0]); + return -2; + } + int major, minor, patch; + zmq_version (&major, &minor, &patch); + printf("Current ZMQ version is %d.%d.%d\n", major, minor, patch); + printf("========================================\n\n"); + + //创建ZMQ_PUSH套接字 + void* context = zmq_ctx_new(); + void* pusher = zmq_socket(context, ZMQ_PUSH); + for (int i = 2; i < argc; i+=2) + { + char addr[128] = {0}; + snprintf(addr, sizeof(addr), "tcp://%s:%s", argv[i], argv[i+1]); + printf("connect %s ...\n", addr); + int rec = zmq_connect(pusher, addr); + if (rec) + { + printf("zmq_connect %s error(%d):%s\n", addr, rec, zmq_strerror(rec)); + zmq_close(pusher); + zmq_ctx_term(context); + return -3; + } + printf("connect %s ... success!\n", addr); + } + + char buf[128] = {0}; + uint8_t index = 0; + while(1) { + snprintf(buf, sizeof(buf), "taskid=%d&time=%ld", index++, time(NULL)); + int rec = zmq_send(pusher, buf, strlen(buf), 0); + + printf("[%ld] send task(%s) to puller, rec = %d, task.len= %lu\n", time(NULL), buf, rec, strlen(buf)); + printf("[%ld]--------------------------------\n\n", time(NULL)); + sleep(5); + } + + zmq_close(pusher); + zmq_ctx_term(context); + + printf("good bye and good luck, pusher\n"); + return 0; +} diff --git a/pool/shard007/C++/0095396_SQLExecDirectTest.cpp b/pool/shard007/C++/0095396_SQLExecDirectTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54e1993edc24ada8d08438bd526ed92433fc25cc --- /dev/null +++ b/pool/shard007/C++/0095396_SQLExecDirectTest.cpp @@ -0,0 +1,352 @@ +/* Copyright (C) 2003 MySQL AB + + 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; version 2 of the 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 + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ + + /** + * @file SQLExecDirectTest.cpp + */ +#include +#define EXD_MESSAGE_LENGTH 200 +#define EXD_NAME_LEN 10 +#define EXD_PHONE_LEN 10 +#define EXD_ADDRESS_LEN 10 +using namespace std; + +SQLHDBC EXD_hdbc; +SQLHSTMT EXD_hstmt; +SQLHENV EXD_henv; +SQLHDESC EXD_hdesc; +SQLRETURN EXD_ret, SQLSTATEs; + +void ExecDirect_DisplayError(SQLSMALLINT EXD_HandleType, + SQLHSTMT EXD_InputHandle); + +int EXD_Display_Result(SQLHSTMT EXDR_InputHandle); + +/** + * Test to execute a prepared ststement + * + * -# Normal case: Prepare and Execute a prepared statement + * -# Prepare and Execute an empty statement + * -# Prepare and Execute a statement with wrong henv handle + * -# Prepare and Execute a statement with wrong hdbc handle + * -# Prepare and Execute a statement with wrong hdesc handle + * @return Zero, if test succeeded + */ + +int SQLExecDirectTest() +{ + ndbout << endl << "Start ExecDirect Testing" << endl; + + //************************************ + //** Allocate An Environment Handle ** + //************************************ + EXD_ret = SQLAllocHandle(SQL_HANDLE_ENV, + SQL_NULL_HANDLE, + &EXD_henv); + +if (EXD_ret == SQL_SUCCESS || EXD_ret == SQL_SUCCESS_WITH_INFO) + ndbout << "Allocated an environment Handle!" << endl; + + //********************************************* + //** Set the ODBC application Version to 3.x ** + //********************************************* + EXD_ret = SQLSetEnvAttr(EXD_henv, + SQL_ATTR_ODBC_VERSION, + (SQLPOINTER) SQL_OV_ODBC3, + SQL_IS_UINTEGER); + +if (EXD_ret == SQL_SUCCESS || EXD_ret == SQL_SUCCESS_WITH_INFO) + ndbout << "Set the ODBC application Version to 3.x!" << endl; + + //********************************** + //** Allocate A Connection Handle ** + //********************************** + + EXD_ret = SQLAllocHandle(SQL_HANDLE_DBC, + EXD_henv, + &EXD_hdbc); + +if (EXD_ret == SQL_SUCCESS || EXD_ret == SQL_SUCCESS_WITH_INFO) + ndbout << "Allocated a connection Handle!" << endl; + + // ******************* + // ** Connect to DB ** + // ******************* + EXD_ret = SQLConnect(EXD_hdbc, + (SQLCHAR *) connectString(), + SQL_NTS, + (SQLCHAR *) "", + SQL_NTS, + (SQLCHAR *) "", + SQL_NTS); + +if (EXD_ret == SQL_SUCCESS || EXD_ret == SQL_SUCCESS_WITH_INFO) + ndbout << "Connected to DB : OK!" << endl; + else + { + ndbout << "Failure to Connect DB!" << endl; + return NDBT_FAILED; + } + + //******************************* + //** Allocate statement handle ** + //******************************* + + EXD_ret = SQLAllocHandle(SQL_HANDLE_STMT, + EXD_hdbc, + &EXD_hstmt); +if(EXD_ret == SQL_SUCCESS || EXD_ret == SQL_SUCCESS_WITH_INFO) + ndbout << "Allocated a statement handle!" << endl; + + //********************************************** + //** Test1 ** + //** Prepare and Execute a prepared statement ** + //********************************************** + EXD_ret = SQLExecDirect(EXD_hstmt, + (SQLCHAR*)"SELECT * FROM Customers", + SQL_NTS); + + if (EXD_ret == SQL_INVALID_HANDLE) + { + ndbout << "Handle Type is SQL_HANDLE_STMT, but SQL_INVALID_HANDLE" << endl; + ndbout << "still appeared. Please check program" << endl; + } + + if (EXD_ret == SQL_ERROR || EXD_ret == SQL_SUCCESS_WITH_INFO) + ExecDirect_DisplayError(SQL_HANDLE_STMT, EXD_hstmt); + + //************************* + //** Display the results ** + //************************* + + EXD_Display_Result(EXD_hstmt); + + //******************************************* + //** Test2 ** + //** Prepare and Execute an empty statement** + //** in order to see what will happen ** + //******************************************* + EXD_ret = SQLExecDirect(EXD_hstmt, + (SQLCHAR*)" ", + SQL_NTS); + + if (EXD_ret == SQL_ERROR || EXD_ret == SQL_SUCCESS_WITH_INFO) + { + ndbout << "Prepare and Execute an empty statement," << endl; + ndbout << "The following case happened!" << endl; + ExecDirect_DisplayError(SQL_HANDLE_STMT, EXD_hstmt); + } + + //*************************************************************** + //** Test3 ** + //** Prepare and Execute a statement with wrong henv handle ** + //** in order to see what will happen ** + //*************************************************************** + EXD_ret = SQLExecDirect(EXD_henv, + (SQLCHAR*)"SELECT * FROM Customers", + SQL_NTS); + + if (EXD_ret == SQL_SUCCESS_WITH_INFO || EXD_ret == SQL_SUCCESS) + { ndbout << "Handle Type is SQL_HANDLE_HENV, but SQL_INVALID_HANDLE" << endl; + ndbout << "still appeared. Please check programm" << endl; + ExecDirect_DisplayError(SQL_HANDLE_ENV, EXD_henv); + } + + //****************************************************************** + //** Test4 ** + //** Prepare and Execute a statement with wrong hdbc handle ** + //** in order to see what will happen ** + //****************************************************************** + + EXD_ret = SQLExecDirect(EXD_hdbc, + (SQLCHAR*)"SELECT * FROM Customers", + SQL_NTS); + + if (EXD_ret == SQL_SUCCESS_WITH_INFO || EXD_ret == SQL_SUCCESS) + ExecDirect_DisplayError(SQL_HANDLE_DBC, EXD_hdbc); + + //******************************************************************* + //** Test5 ** + //** Prepare and Execute a statement with wrong hdesc handle ** + //** in order to see what will happen ** + //******************************************************************* + + EXD_ret = SQLExecDirect(EXD_hdesc, + (SQLCHAR*)"SELECT * FROM Customers", + SQL_NTS); + + if (EXD_ret == SQL_SUCCESS_WITH_INFO || EXD_ret == SQL_SUCCESS) + { + ndbout << "Handle Type is SQL_HANDLE_DESC, but SQL_SUCCESS_WITH_INFO" <setupUi(this); + + this->c = new Compass(this->ui->centralWidget); + this->c->show(); +} + +MainWindow::~MainWindow() +{ + delete ui; +} + +void MainWindow::mouseMoveEvent(QMouseEvent *event) +{ + this->c->setBearing(event->pos().x()); +} diff --git a/pool/shard007/C++/0095399_bslmf_istriviallycopyable.t.cpp b/pool/shard007/C++/0095399_bslmf_istriviallycopyable.t.cpp new file mode 100644 index 0000000000000000000000000000000000000000..337d87acaddb8820daed5369432a0d4f6b9c3148 --- /dev/null +++ b/pool/shard007/C++/0095399_bslmf_istriviallycopyable.t.cpp @@ -0,0 +1,516 @@ +// bslmf_istriviallycopyable.t.cpp -*-C++-*- + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include // 'printf' +#include // 'atoi' + +using namespace BloombergLP; + +//============================================================================= +// TEST PLAN +//----------------------------------------------------------------------------- +// Overview +// -------- +// The component under test defines a meta-function, +// 'bsl::is_trivially_copyable', that determines whether a template parameter +// type is trivially copyable. By default, the meta-function supports a +// restricted set of type categories and can be extended to support other types +// through either template specialization or use of the +// 'BSLMF_NESTED_TRAIT_DECLARATION' macro. +// +// Thus, we need to ensure that the natively supported types are correctly +// identified by the meta-function by testing the meta-function with each of +// the supported type categories. We also need to verify that the +// meta-function can be correctly extended to support other types through +// either of the two supported mechanisms. Finally, we need to test correct +// support for cv-qualified and array types, where the underlying type may be +// trivially copyable. +// +// ---------------------------------------------------------------------------- +// PUBLIC CLASS DATA +// [ 1] bsl::is_trivially_copyable::value +// +// ---------------------------------------------------------------------------- +// [ 4] USAGE EXAMPLE +// [ 3] TESTING: 'bsl::is_trivially_copyable' +// [ 2] EXTENDING bsl::is_trivially_copyable + +// ============================================================================ +// STANDARD BSL ASSERT TEST FUNCTION +// ---------------------------------------------------------------------------- + +namespace { + +int testStatus = 0; + +void aSsErT(bool condition, const char *message, int line) +{ + if (condition) { + printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); + + if (0 <= testStatus && testStatus <= 100) { + ++testStatus; + } + } +} + +} // close unnamed namespace + +// ============================================================================ +// STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS +// ---------------------------------------------------------------------------- + +#define ASSERT BSLS_BSLTESTUTIL_ASSERT +#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV + +#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT +#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT +#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT +#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT +#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT +#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT +#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT +#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT + +#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. +#define P BSLS_BSLTESTUTIL_P // Print identifier and value. +#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. +#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). +#define L_ BSLS_BSLTESTUTIL_L_ // current Line number + +//============================================================================= +// COMPONENT SPECIFIC MACROS FOR TESTING +//----------------------------------------------------------------------------- + +// Each of the macros below will test the 'bsl::is_trivially_copyable' trait +// with a set of variations on a type. There are several layers of macros, as +// object types support the full range of variation, but function types cannot +// form an array, nor be cv-qualified. Similarly, 'void' may be cv-qualified +// but still cannot form an array. As macros are strictly text-substitution +// we must use the appropriate 'add_decoration' traits to transform types in a +// manner that is guaranteed to be syntactically valid. Note that these are +// not type-dependent contexts, so there is no need to use 'typename' when +// fetching the result from any of the queried traits. + +#define ASSERT_IS_TRIVIALLY_COPYABLE_TYPE(TYPE, RESULT) \ + ASSERT( bsl::is_trivially_copyable::value == RESULT); \ + ASSERT( bsl::is_trivially_copyable::type>::value); \ + ASSERT(!bsl::is_trivially_copyable< \ + bsl::add_lvalue_reference::type>::value); + +#define ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE(TYPE, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE(bsl::add_const::type, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE(bsl::add_volatile::type, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE(bsl::add_cv::type, RESULT); + +// Two additional macros will allow testing on old MSVC compilers when 'TYPE' +// is an array of unknown bound. + +#define ASSERT_IS_TRIVIALLY_COPYABLE_TYPE_NO_REF(TYPE, RESULT) \ + ASSERT( bsl::is_trivially_copyable::value == RESULT); \ + ASSERT( bsl::is_trivially_copyable::type>::value); + +#define ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE_NO_REF(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE_NO_REF(TYPE, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE_NO_REF( \ + bsl::add_const::type, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE_NO_REF( \ + bsl::add_volatile::type, RESULT); \ + ASSERT_IS_TRIVIALLY_COPYABLE_TYPE_NO_REF(bsl::add_cv::type, RESULT); + + +#if defined(BSLS_PLATFORM_CMP_IBM) +// Last checked with the xlC 12.1 compiler. The IBM xlC compiler has problems +// correctly handling arrays of unknown bound as template parameters. +# define ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[128], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[12][8], RESULT) + +#elif defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VERSION < 1700 +// Old microsoft compilers compilers do not support references to arrays of +// unknown bound. + +# define ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[128], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[12][8], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE_NO_REF(TYPE[], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE_NO_REF(TYPE[][8], RESULT) + +#else +# define ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE, RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[128], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[12][8], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[], RESULT) \ + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(TYPE[][8], RESULT) +#endif + +//============================================================================= +// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING +//----------------------------------------------------------------------------- + +namespace { + +class MyTriviallyCopyableType { +}; + +struct MyNonTriviallyCopyableType { + MyNonTriviallyCopyableType() {} + MyNonTriviallyCopyableType(const MyNonTriviallyCopyableType&) {} + //... +}; + +} // close unnamed namespace + +namespace bsl { + +template <> +struct is_trivially_copyable : bsl::true_type { + // This template specialization for 'is_trivially_copyable' indicates that + // 'MyTriviallyCopyableType' is a trivially copyable. +}; + +} // close namespace bsl + + +namespace { + +struct UserDefinedTcTestType { + // This user-defined type, which is marked to be trivially copyable using + // template specialization (below), is used for testing. + + UserDefinedTcTestType() {} + UserDefinedTcTestType(const UserDefinedTcTestType&) {} + // Explicitly supply constructors that do nothing, to ensure that this + // class has no trivial traits detected with a conforming C++11 library + // implementation. +}; + +struct UserDefinedTcTestType2 { + // This user-defined type, which is marked to be trivially copyable using + // the 'BSLMF_NESTED_TRAIT_DECLARATION' macro, is used for testing. + + BSLMF_NESTED_TRAIT_DECLARATION(UserDefinedTcTestType2, + bsl::is_trivially_copyable); + + UserDefinedTcTestType2() {} + UserDefinedTcTestType2(const UserDefinedTcTestType2&) {} + // Explicitly supply constructors that do nothing, to ensure that this + // class has no trivial traits detected with a conforming C++11 library + // implementation. +}; + +struct UserDefinedNonTcTestType { + // This user-defined type, which is not marked to be trivially copyable, is + // used for testing. + UserDefinedNonTcTestType() {} + UserDefinedNonTcTestType(const UserDefinedNonTcTestType&) {} +}; + +enum EnumTestType { + // This 'enum' type is used for testing. +}; + +typedef int (UserDefinedNonTcTestType::*MethodPtrTestType) (); + // This pointer to non-static function member type is used for testing. + +} // close unnamed namespace + + +namespace bsl { + +template <> +struct is_trivially_copyable : bsl::true_type { +}; + +} // close namespace bsl + + +//============================================================================= +// MAIN PROGRAM +//----------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + int test = argc > 1 ? atoi(argv[1]) : 0; + bool verbose = argc > 2; + bool veryVerbose = argc > 3; + bool veryVeryVerbose = argc > 4; + bool veryVeryVeryVerbose = argc > 5; + + (void) veryVerbose; // eliminate unused variable warning + (void) veryVeryVerbose; // eliminate unused variable warning + (void) veryVeryVeryVerbose; // eliminate unused variable warning + + setbuf(stdout, NULL); // Use unbuffered output + + printf("TEST " __FILE__ " CASE %d\n", test); + + switch (test) { case 0: + case 4: { + // -------------------------------------------------------------------- + // USAGE EXAMPLE + // + // Concerns: + //: 1 The usage example provided in the component header file compiles, + //: links, and runs as shown. + // + // Plan: + //: 1 Incorporate usage example from header into test driver, remove + //: leading comment characters, and replace 'assert' with 'ASSERT'. + //: (C-1) + // + // Testing: + // USAGE EXAMPLE + // -------------------------------------------------------------------- + + if (verbose) printf("\nUSAGE EXAMPLE" + "\n=============\n"); + +///Usage +///----- +// In this section we show intended use of this component. +// +///Example 1: Verify Whether Types are Trivially Copyable +/// - - - - - - - - - - - - - - - - - - - - - - - - - - - +// Suppose that we want to assert whether a type is trivially copyable. +// +// First, we define a set of types to evaluate: +//.. + typedef int MyFundamentalType; + typedef int& MyFundamentalTypeReference; +// +// class MyTriviallyCopyableType { +// }; +// +// struct MyNonTriviallyCopyableType { +// //... +// }; +//.. +// Then, since user-defined types cannot be automatically evaluated by +// 'is_trivially_copyable', we define a template specialization to specify that +// 'MyTriviallyCopyableType' is trivially copyable: +//.. +// namespace bsl { +// +// template <> +// struct is_trivially_copyable : bsl::true_type { +// // This template specialization for 'is_trivially_copyable' indicates +// // that 'MyTriviallyCopyableType' is a trivially copyable type. +// }; +// +// } // close namespace bsl +//.. +// Now, we verify whether each type is trivially copyable using +// 'bsl::is_trivially_copyable': +//.. + ASSERT(true == bsl::is_trivially_copyable::value); + ASSERT(false == bsl::is_trivially_copyable< + MyFundamentalTypeReference>::value); + ASSERT(true == bsl::is_trivially_copyable< + MyTriviallyCopyableType>::value); + ASSERT(false == bsl::is_trivially_copyable< + MyNonTriviallyCopyableType>::value); +//.. + + } break; + case 3: { + // -------------------------------------------------------------------- + // TESTING: 'bsl::is_trivially_copyable' + // Ensure that 'bsl::is_trivially_copyable' meta-function is + // specialized correctly for 'bsls::TimeInterval'. + // + // NOTE: This is not tested in 'bsls' for dependency reasons. + // + // Concerns: + //: 1 'bsl::is_trivially_copyable' is 'true' + // + // Plan: + //: 1 Verify 'bsl::is_trivially_copyable' is 'true' + // + // Testing: + // + // -------------------------------------------------------------------- + + if (verbose) + printf( + "\nTESTING: 'bsl::is_trivially_copyable'\n" + "\n=========================================================\n"); + + // C-1 + ASSERT(bsl::is_trivially_copyable::value); + + + } break; + case 2: { + // -------------------------------------------------------------------- + // EXTENDING 'bsl::is_trivially_copyable' + // Ensure the 'bsl::is_trivially_copyable' meta-function returns the + // correct value for types explicitly specified to be trivially + // copyable. + // + // Concerns: + //: 1 The meta-function returns 'false' for normal user-defined types. + //: + //: 2 The meta-function returns 'true' for a user-defined type, if a + //: specialization for 'bsl::is_trivially_copyable' on that type is + //: defined to inherit from 'bsl::true_type'. + //: + //: 3 The meta-function returns 'true' for a user-defined type that + //: specifies it has the trait using the + //: 'BSLMF_NESTED_TRAIT_DECLARATION' macro. + //: + //: 4 For cv-qualified types, the meta-function returns 'true' if the + //: corresponding cv-unqualified type is trivially copyable, and + //: 'false' otherwise. + //: + //: 5 For array types, the meta-function returns 'true' if the array + //: element is trivially copyable, and 'false' otherwise. + // + // Plan: + //: 1 Create a set of macros that will generate an 'ASSERT' test for + //: all variants of a type: (C4,5) + //: o reference and pointer types + //: o all cv-qualified combinations + //: o arrays, of fixed and runtime bounds, and multiple dimensions + //: + //: 2 For each category of type in concerns 1-3, use the appropriate + //: test macro for confirm the correct result for a representative + //: sample of types. + // + // Testing: + // EXTENDING 'bsl::is_trivially_copyable' + // -------------------------------------------------------------------- + + if (verbose) + printf("\nEXTENDING 'bsl::is_trivially_copyable'" + "\n======================================\n"); + + // C-1 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(UserDefinedNonTcTestType, + false); + + // C-2 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(UserDefinedTcTestType, true); + + // C-3 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(UserDefinedTcTestType2, true); + } break; + case 1: { + // -------------------------------------------------------------------- + // 'bsl::is_trivially_copyable::value' + // Ensure the 'bsl::is_trivially_copyable' meta-function + // returns the correct value for intrinsically supported types. + // + // Concerns: + //: 1 The meta-function returns 'true' for fundamental types. + //: + //: 2 The meta-function returns 'true' for enumerated types. + //: + //: 3 The meta-function returns 'true' for pointer to member types. + //: + //: 4 The meta-function returns 'false' for cv-qualified 'void' types. + //: + //: 5 The meta-function returns 'false' for function types. + // + //: 6 The meta-function returns 'true' for pointer types. + //: + //: 7 The meta-function returns 'false' for reference types. + //: + //: 8 The meta-function returns the same result for array types as it + //: would for the array's element type. + //: + //: 9 The meta-function returns the same result for cv-qualified + //: types that it would return 'true' for the corresponding + //: cv-unqualified type. + // + // Plan: + //: 1 Create a set of macros that will generate an 'ASSERT' test for + //: all variants of a type: (C6-9) + //: o reference and pointer types + //: o all cv-qualified combinations + //: o arrays, of fixed and runtime bounds, and multiple dimensions + //: + //: 2 For each category of type in concerns 1-5, use the appropriate + //: test macro for confirm the correct result for a representative + //: sample of types. + // + // Testing: + // bsl::is_trivially_copyable::value + // -------------------------------------------------------------------- + + if (verbose) + printf("\n'bsl::is_trivially_copyable::value'" + "\n===================================\n"); + + // C-1 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(int, true); + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(char, true); + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(long double, true); + + // C-2 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(EnumTestType, true); + + // C-3 + ASSERT_IS_TRIVIALLY_COPYABLE_OBJECT_TYPE(MethodPtrTestType, true); + + // C-4 : 'void' is not an object type, but can be cv-qualified. + ASSERT_IS_TRIVIALLY_COPYABLE_CV_TYPE(void, false); + + // C-5 : Function types are not object types, nor cv-qualifiable. + // Note that this particular test stresses compilers handling of + // function types, and function reference types, in the template type + // system. We incrementally disable tests for compilers known to have + // bugs that we cannot easily work around/ + ASSERT( bsl::is_trivially_copyable::value); + ASSERT( bsl::is_trivially_copyable::value); +#if !defined(BSLS_PLATFORM_CMP_SUN) // last tested for v12.3 + ASSERT(!bsl::is_trivially_copyable::value); + ASSERT(!bsl::is_trivially_copyable::value); +#if !defined(BSLS_PLATFORM_CMP_IBM) // last tested for v12.1 + ASSERT(!bsl::is_trivially_copyable::value); + ASSERT(!bsl::is_trivially_copyable::value); +#endif +#endif + } break; + default: { + fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); + testStatus = -1; + } + } + + if (testStatus > 0) { + fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); + } + return testStatus; +} + +// ---------------------------------------------------------------------------- +// Copyright 2013 Bloomberg Finance L.P. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ----------------------------- END-OF-FILE ---------------------------------- diff --git a/pool/shard007/C++/0095404_GDBPrint.cpp b/pool/shard007/C++/0095404_GDBPrint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..076dd93e0cb73ac27a2f0a4e05b2657d71860441 --- /dev/null +++ b/pool/shard007/C++/0095404_GDBPrint.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include + +int main() { + std::map map; + map[0] = 1; + map[2] = 3; + + std::set set; + set.insert(0); + set.insert(1); + + std::pair pair; + pair.first = 0; + pair.second = 1; + + std::vector vector; + vector.push_back(0); + vector.push_back(1); + + return 0; +} diff --git a/pool/shard007/C++/0095407_touch_log_source.cc b/pool/shard007/C++/0095407_touch_log_source.cc new file mode 100644 index 0000000000000000000000000000000000000000..29a37143e2719e8ca2c7f6768a92190476cf8c3b --- /dev/null +++ b/pool/shard007/C++/0095407_touch_log_source.cc @@ -0,0 +1,187 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ash/system_logs/touch_log_source.h" + +#include + +#include "base/bind.h" +#include "base/callback.h" +#include "base/callback_helpers.h" +#include "base/check_op.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/process/launch.h" +#include "base/strings/string_util.h" +#include "base/task/post_task.h" +#include "base/task/thread_pool.h" +#include "chromeos/login/login_state/login_state.h" +#include "content/public/browser/browser_thread.h" +#include "ui/ozone/public/input_controller.h" +#include "ui/ozone/public/ozone_platform.h" + +using content::BrowserThread; + +namespace { + +// The prefix "hack-33025" was historically chosen in http://crbug.com/139715. +// We continue to go with it in order to be compatible with the existing touch +// log processing toolchain. +const char kDeviceStatusLogDataKey[] = "hack-33025-touchpad"; +const char kTouchpadEventLogDataKey[] = "hack-33025-touchpad_activity"; +const char kTouchscreenEventLogDataKey[] = "hack-33025-touchscreen_activity"; + +// Directory for temp touch event logs. +constexpr char kTouchEventLogDir[] = "/home/chronos/user/log"; +constexpr char kNotLoggedInTouchEventLogDir[] = "/var/log/chrome"; + +// Prefixes of touch event logs. +const char kTouchpadGestureLogPrefix[] = "touchpad_activity_"; +const char kTouchscreenLogPrefix[] = "evdev_input_events_"; +const char kTouchpadEvdevLogPrefix[] = "cmt_input_events_"; + +// Binary paths. +const char kShellCommand[] = "/bin/sh"; +const char kTarCommand[] = "/bin/tar cf -"; +const char kUuencodeCommand[] = "/usr/bin/uuencode"; + +const int kMaxDeviceTouchEventLogs = 7; + +// Clean up intermediate log files dumped during feedback creation. +void CleanupEventLog(const std::vector& log_paths) { + for (const base::FilePath& path : log_paths) + base::DeleteFile(path); +} + +// Check for all known log paths and find the ones whose filenames match a +// prefix. Concatenate their filenames into one string. |max_log_count| is +// the maximum number of logs that we will collect. +// +// This is used to distinguish touchpad/mice logs from touchscreen logs. +std::string GetEventLogListOfOnePrefix( + const std::vector& log_paths, + const std::string& prefix, + const int max_log_count) { + int collected = 0; + std::string log_list; + for (size_t i = 0; i < log_paths.size(); ++i) { + const std::string basename = log_paths[i].BaseName().value(); + if (base::StartsWith(basename, prefix, base::CompareCase::SENSITIVE)) { + log_list.append(" " + log_paths[i].value()); + + // Limit the max number of collected logs to shorten the log collection + // process. + if (++collected >= max_log_count) + break; + } + } + + return log_list; +} + +// Pack the collected event logs in a way that is compatible with the log +// analysis tools. +void PackEventLog(system_logs::SystemLogsResponse* response, + const std::vector& log_paths) { + // Combine logs with a command line call that tars them up and uuencode the + // result in one string. + std::vector> commands; + base::CommandLine command = base::CommandLine(base::FilePath(kShellCommand)); + command.AppendArg("-c"); + + // Make a list that contains touchpad (and mouse) event logs only. + const std::string touchpad_log_list = + GetEventLogListOfOnePrefix(log_paths, kTouchpadGestureLogPrefix, + kMaxDeviceTouchEventLogs) + + GetEventLogListOfOnePrefix(log_paths, kTouchpadEvdevLogPrefix, + kMaxDeviceTouchEventLogs); + command.AppendArg(std::string(kTarCommand) + touchpad_log_list + + " 2>/dev/null | " + kUuencodeCommand + + " -m touchpad_activity_log.tar"); + + commands.push_back(std::make_pair(kTouchpadEventLogDataKey, command)); + + base::CommandLine ts_command = + base::CommandLine(base::FilePath(kShellCommand)); + ts_command.AppendArg("-c"); + + // Make a list that contains touchscreen event logs only. + const std::string touchscreen_log_list = GetEventLogListOfOnePrefix( + log_paths, kTouchscreenLogPrefix, kMaxDeviceTouchEventLogs); + ts_command.AppendArg(std::string(kTarCommand) + touchscreen_log_list + + " 2>/dev/null | " + kUuencodeCommand + + " -m touchscreen_activity_log.tar"); + + commands.push_back(std::make_pair(kTouchscreenEventLogDataKey, ts_command)); + + // For now only touchpad (and mouse) logs are actually collected. + for (size_t i = 0; i < commands.size(); ++i) { + std::string output; + base::GetAppOutput(commands[i].second, &output); + (*response)[commands[i].first] = output; + } + + // Cleanup these temporary log files. + base::ThreadPool::PostTask( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(CleanupEventLog, log_paths)); +} + +// Callback for handing the outcome of GetTouchEventLog(). +// +// This is the end of the whole touch log collection process. +void OnEventLogCollected( + std::unique_ptr response, + system_logs::SysLogsSourceCallback callback, + const std::vector& log_paths) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + system_logs::SystemLogsResponse* response_ptr = response.get(); + base::ThreadPool::PostTaskAndReply( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(&PackEventLog, response_ptr, log_paths), + base::BindOnce(std::move(callback), std::move(response))); +} + +// Callback for handing the outcome of GetTouchDeviceStatus(). +// +// Appends the collected log to the SystemLogsResponse map. Also goes on to +// collect touch event logs. +void OnStatusLogCollected( + std::unique_ptr response, + system_logs::SysLogsSourceCallback callback, + const std::string& log) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + (*response)[kDeviceStatusLogDataKey] = log; + + // Collect touch event logs. + // The user-specific log directory will not exist if we are not logged in + // yet, so choose the location based on that. + base::FilePath base_log_path(chromeos::LoginState::Get()->IsUserLoggedIn() + ? kTouchEventLogDir + : kNotLoggedInTouchEventLogDir); + ui::InputController* input_controller = + ui::OzonePlatform::GetInstance()->GetInputController(); + input_controller->GetTouchEventLog( + base_log_path, base::BindOnce(&OnEventLogCollected, std::move(response), + std::move(callback))); +} + +} // namespace + +namespace system_logs { + +void TouchLogSource::Fetch(SysLogsSourceCallback callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!callback.is_null()); + + // Collect touch device status logs. + auto response = std::make_unique(); + ui::InputController* input_controller = + ui::OzonePlatform::GetInstance()->GetInputController(); + input_controller->GetTouchDeviceStatus(base::BindOnce( + &OnStatusLogCollected, std::move(response), std::move(callback))); +} + +} // namespace system_logs diff --git a/pool/shard007/C++/0095409_ScriptComponent.cpp b/pool/shard007/C++/0095409_ScriptComponent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..336bd615bb171f7d7c41a028fab85c8a089a1636 --- /dev/null +++ b/pool/shard007/C++/0095409_ScriptComponent.cpp @@ -0,0 +1,168 @@ +#include "ScriptComponent.h" +#include "engine/Engine.h" +#include "engine/object/GameObject.h" +#include "core/base/Data.h" +#include "core/platform/FileUtils.h" + +#ifdef _WIN32 +#include "game/editor/manager/ScriptManager.h" +#endif + + +RE::ScriptComponent::ScriptComponent(Path path, class GameObject* go) { + this->path = path; + this->gameObject = go; + + auto bn = strrchr(path.data.c_str(), '/'); + if (bn != nullptr) { + this->baseName = bn+1; + } + else { + this->baseName = path.data; + } + + Class = Load(path); + + auto func = Class.getField("new"); + if (!func.isNilref()) { + Class = func(Class, gameObject); + } + else { + Class = kaguya::LuaTable(); + } + + setupFuncs(); + +#ifdef _WIN32 + ScriptManager::instance.Add(this); +#endif +} + +RE::ScriptComponent::~ScriptComponent() { +#ifdef _WIN32 + ScriptManager::instance.Remove(this); +#endif +} + +void RE::ScriptComponent::Awake() { + auto& func = luaFuncs[FuncType::AWAKE]; + if (!func.isNilref()) { + func(Class); + } +} + +void RE::ScriptComponent::Start() { + auto& func = luaFuncs[FuncType::START]; + if (!func.isNilref()) { + func(Class); + } +} + +void RE::ScriptComponent::Update(float dt) { + if (!isStart) { + Start(); + isStart = true; + return; + } + + auto& func = luaFuncs[FuncType::UPDATE]; + if (!func.isNilref()) { + func(Class, dt); + } +} + +void RE::ScriptComponent::OnDestroy() { + auto& func = luaFuncs[FuncType::ONDESTROY]; + if (!func.isNilref()) { + func(Class); + } + + Class = kaguya::LuaTable(); + setupFuncs(); +} + +void RE::ScriptComponent::OnEnable() { + isEnabled = true; + auto& func = luaFuncs[FuncType::ONENABLE]; + if (!func.isNilref()) { + func(Class); + } +} + +void RE::ScriptComponent::OnDisable() { + isEnabled = false; + auto& func = luaFuncs[FuncType::ONDISABLE]; + if (!func.isNilref()) { + func(Class); + } +} + +const char* RE::ScriptComponent::TypeName() { + return path.data.c_str(); +} + +void RE::ScriptComponent::Reload() { + kaguya::LuaTable cls = Load(path); + + if (cls.isNilref()) return; + + auto keys = cls.keys(); + + Clear(); + + for (auto& key : keys) { + if (Class[key].isNilref()) { + Class[key] = cls[key]; + } + else { + switch (cls[key].type()) + { + case LUA_TSTRING: { + break; + } + case LUA_TBOOLEAN: { + break; + } + case LUA_TNUMBER: { + break; + } + case LUA_TFUNCTION: { + Class[key] = cls[key]; + break; + } + case LUA_TNIL: { + break; + } + default: + break; + } + } + } + + setupFuncs(); +} + +kaguya::LuaTable RE::ScriptComponent::Load(Path& path) { + Data data = FileUtils::getInstance()->GetData(path); + + auto& state = Engine::instance.Lua; + auto func = state.loadstring((char*)data.getBytes()); + + if (func.isNilref()) return kaguya::LuaTable(); + + kaguya::LuaTable cls = func.call(); + return cls; +} + +void RE::ScriptComponent::Clear() { + +} + +void RE::ScriptComponent::setupFuncs() { + luaFuncs[FuncType::AWAKE] = Class.getField("Awake"); + luaFuncs[FuncType::START] = Class.getField("Start"); + luaFuncs[FuncType::UPDATE] = Class.getField("Update"); + luaFuncs[FuncType::ONDESTROY] = Class.getField("OnDestroy"); + luaFuncs[FuncType::ONENABLE] = Class.getField("OnEnable"); + luaFuncs[FuncType::ONDISABLE] = Class.getField("OnDisable"); +} diff --git a/pool/shard007/C++/0095410_ForestBench.cpp b/pool/shard007/C++/0095410_ForestBench.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cb2c9bb0bd8d37204acc8f412ed2b2ed0ce6597 --- /dev/null +++ b/pool/shard007/C++/0095410_ForestBench.cpp @@ -0,0 +1,160 @@ +/** + * Copyright (C) 2011 + * University of Rochester Department of Computer Science + * and + * Lehigh University Department of Computer Science and Engineering + * + * License: Modified BSD + * Please see the file LICENSE.RSTM for licensing information + */ + +#include +#if defined(STM_CPU_SPARC) +#include +#endif + +/** + * Step 1: + * Include the configuration code for the harness, and the API code. + */ +#include +#include +#include +#include "bmconfig.hpp" + +/** + * We provide the option to build the entire benchmark in a single + * source. The bmconfig.hpp include defines all of the important functions + * that are implemented in this file, and bmharness.cpp defines the + * execution infrastructure. + */ +#ifdef SINGLE_SOURCE_BUILD +#include "bmharness.cpp" +#endif + +/** + * Step 2: + * Declare the data type that will be stress tested via this benchmark. + * Also provide any functions that will be needed to manipulate the data + * type. Take care to avoid unnecessary indirection. + */ + +#include "Tree.hpp" + + + +/** + * Forest of RBTrees + * + * In the past, we made this have lots of different sized trees. That, in + * turn, led to a lot of complexity, and resulted in the benchmark not + * receiving much use. In this new instance, we make things less + * configurable, but hopefully more useful. + * + * The Forest holds many trees, all of which are exactly the same wrt key + * range and lookup ratio. A transaction performs a fixed number of tree + * ops on the forest, selecting trees at random (with replacement). + */ +struct CustomForest +{ + uint32_t keydepths; // how many keys in each tree? + uint32_t roratio; // lookup ratio for each tree + uint32_t insratio; // insert ratio for each tree + uint32_t total_trees; // total number of trees + uint32_t trees_per_tx; // random trees to touch per transaction + RBTree** trees; // set of trees + + // constructor: create all the trees, intiialize them + CustomForest(uint32_t keys, uint32_t ro, uint32_t numtrees, uint32_t per) + : keydepths(keys), roratio(ro), insratio(ro + (100 - ro)/2), + total_trees(numtrees), trees_per_tx(per), trees(new RBTree*[numtrees]) + { + // initialize the data structure + TM_BEGIN_FAST_INITIALIZATION(); + for (uint32_t i = 0; i < numtrees; ++i) { + // make new tree + trees[i] = new RBTree(); + // populate it + for (uint32_t w = 0; w < keys; w+=2) { + // NB: gross hack: we can cheat here to avoid + // instrumentation. it's safe since we're in the + // constructor, but not advised in general. + trees[i]->insert(w TM_PARAM); + } + } + TM_END_FAST_INITIALIZATION(); + } + + ~CustomForest() { + for (uint32_t i = 0; i < total_trees; ++i) + delete trees[i]; + delete[] trees; + } +}; + +/** + * Step 3: + * Declare an instance of the data type, and provide init, test, and verify + * functions + */ + +/*** the tree we will manipulate in the experiment */ +CustomForest* SET; + +/*** Initialize the counter */ +void bench_init() +{ + SET = new CustomForest(CFG.elements, CFG.lookpct, CFG.sets, CFG.ops); +} + +/*** Run a bunch of random transactions */ +void bench_test(uintptr_t, uint32_t* seed) +{ + // cache the seed locally so we can restore it on abort + // + // NB: volatile needed because using a non-volatile local in conjunction + // with a setjmp-longjmp control transfer is undefined, and gcc won't + // allow it with -Wall -Werror. + volatile uint32_t local_seed = *seed; + TM_BEGIN(atomic) { + if (CFG.running) { + local_seed = *seed; + for (uint32_t i = 0; i < SET->trees_per_tx; ++i) { + // pick a tree, a value, and a read-only ratio + int tree_idx = rand_r((uint32_t*)&local_seed) % SET->total_trees; + int val = rand_r((uint32_t*)&local_seed) % SET->keydepths; + uint32_t act = rand_r((uint32_t*)&local_seed) % 100; + // do a lookup? + if (act < SET->roratio) + SET->trees[tree_idx]->lookup(val TM_PARAM); + else if (act < SET->insratio) + SET->trees[tree_idx]->insert(val TM_PARAM); + else + SET->trees[tree_idx]->remove(val TM_PARAM); + } + } + } TM_END; + *seed = local_seed; +} + +/*** Ensure the final state of the benchmark satisfies all invariants */ +bool bench_verify() +{ + for (uint32_t i = 0; i < SET->total_trees; ++i) + if (!(SET->trees[i]->isSane())) + return false; + return true; +} + +/** + * Step 4: + * Include the code that has the main() function, and the code for creating + * threads and calling the three above-named functions. Don't forget to + * provide an arg reparser. + */ + +/*** Deal with special names that map to different M values */ +void bench_reparse() +{ + if (CFG.bmname == "") CFG.bmname = "Forest"; +} diff --git a/pool/shard007/C++/0095412_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memmove_72b.cpp b/pool/shard007/C++/0095412_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memmove_72b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee24ddcae6a09cac6a9e68d10f127dd9de131811 --- /dev/null +++ b/pool/shard007/C++/0095412_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memmove_72b.cpp @@ -0,0 +1,77 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memmove_72b.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-72b.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sinks: memmove + * BadSink : Copy twoIntsStruct array to data using memmove + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +using namespace std; + +namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memmove_72 +{ + +#ifndef OMITBAD + +void badSink(vector dataVector) +{ + /* copy data out of dataVector */ + twoIntsStruct * data = dataVector[2]; + { + twoIntsStruct source[100]; + { + size_t i; + /* Initialize array */ + for (i = 0; i < 100; i++) + { + source[i].intOne = 0; + source[i].intTwo = 0; + } + } + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memmove(data, source, 100*sizeof(twoIntsStruct)); + printStructLine(&data[0]); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector dataVector) +{ + twoIntsStruct * data = dataVector[2]; + { + twoIntsStruct source[100]; + { + size_t i; + /* Initialize array */ + for (i = 0; i < 100; i++) + { + source[i].intOne = 0; + source[i].intTwo = 0; + } + } + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memmove(data, source, 100*sizeof(twoIntsStruct)); + printStructLine(&data[0]); + free(data); + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard007/C++/0095415_Mouse.cpp b/pool/shard007/C++/0095415_Mouse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a654613ab853ab0ecbd44c240768ec070304300b --- /dev/null +++ b/pool/shard007/C++/0095415_Mouse.cpp @@ -0,0 +1,204 @@ +/* + Copyright (C) 2012 Rainmeter Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include "StdAfx.h" +#include "ConfigParser.h" +#include "MeterWindow.h" +#include "Litestep.h" +#include "Mouse.h" + +CMouse::CMouse() : + m_CursorType(MOUSECURSOR_HAND), + m_CustomCursor(), + m_CursorState(true) +{ +} + +CMouse::~CMouse() +{ + DestroyCustomCursor(); +} + +void CMouse::ReadOptions(CConfigParser& parser, const WCHAR* section, CMeterWindow* meterWindow) +{ + DestroyCustomCursor(); + + m_LeftDownAction = parser.ReadString(section, L"LeftMouseDownAction", L"", false); + m_RightDownAction = parser.ReadString(section, L"RightMouseDownAction", L"", false); + m_MiddleDownAction = parser.ReadString(section, L"MiddleMouseDownAction", L"", false); + m_LeftUpAction = parser.ReadString(section, L"LeftMouseUpAction", L"", false); + m_RightUpAction = parser.ReadString(section, L"RightMouseUpAction", L"", false); + m_MiddleUpAction = parser.ReadString(section, L"MiddleMouseUpAction", L"", false); + m_LeftDoubleClickAction = parser.ReadString(section, L"LeftMouseDoubleClickAction", L"", false); + m_RightDoubleClickAction = parser.ReadString(section, L"RightMouseDoubleClickAction", L"", false); + m_MiddleDoubleClickAction = parser.ReadString(section, L"MiddleMouseDoubleClickAction", L"", false); + m_OverAction = parser.ReadString(section, L"MouseOverAction", L"", false); + m_LeaveAction = parser.ReadString(section, L"MouseLeaveAction", L"", false); + + m_CursorState = 0!=parser.ReadInt(section, L"MouseActionCursor", meterWindow->GetMouse().GetCursorState()); + + const WCHAR* defaultMouseCursor = (section == L"Rainmeter") ? L"HAND" : L""; + const WCHAR* mouseCursor = parser.ReadString(section, L"MouseActionCursorName", defaultMouseCursor).c_str(); + if (_wcsicmp(mouseCursor, L"HAND") == 0) + { + m_CursorType = MOUSECURSOR_HAND; + } + else if (_wcsicmp(mouseCursor, L"TEXT") == 0) + { + m_CursorType = MOUSECURSOR_TEXT; + } + else if (_wcsicmp(mouseCursor, L"HELP") == 0) + { + m_CursorType = MOUSECURSOR_HELP; + } + else if (_wcsicmp(mouseCursor, L"BUSY") == 0) + { + m_CursorType = MOUSECURSOR_BUSY; + } + else if (_wcsicmp(mouseCursor, L"CROSS") == 0) + { + m_CursorType = MOUSECURSOR_CROSS; + } + else if (_wcsicmp(mouseCursor, L"PEN") == 0) + { + m_CursorType = MOUSECURSOR_PEN; + } + else if (wcschr(mouseCursor, L'.')) + { + m_CursorType = MOUSECURSOR_CUSTOM; + } + else + { + // Inherit from [Rainmeter]. + m_CursorType = meterWindow->GetMouse().GetCursorType(); + if (m_CursorType == MOUSECURSOR_CUSTOM) + { + mouseCursor = meterWindow->GetParser().ReadString(L"Rainmeter", L"MouseActionCursorName", L"").c_str(); + } + } + + if (m_CursorType == MOUSECURSOR_CUSTOM) + { + std::wstring cursorPath = meterWindow->GetResourcesPath(); + cursorPath += L"Cursors\\"; + cursorPath += mouseCursor; + m_CustomCursor = LoadCursorFromFile(cursorPath.c_str()); + if (!m_CustomCursor) + { + m_CursorType = MOUSECURSOR_ARROW; + LogWithArgs(LOG_ERROR, L"Invalid cursor: %s", cursorPath.c_str()); + } + } +} + +HCURSOR CMouse::GetCursor() const +{ + LPCWSTR name = IDC_ARROW; + switch (m_CursorType) + { + case MOUSECURSOR_HAND: + name = IDC_HAND; + break; + + case MOUSECURSOR_TEXT: + name = IDC_IBEAM; + break; + + case MOUSECURSOR_HELP: + name = IDC_HELP; + break; + + case MOUSECURSOR_BUSY: + name = IDC_APPSTARTING; + break; + + case MOUSECURSOR_CROSS: + name = IDC_CROSS; + break; + + case MOUSECURSOR_PEN: + name = MAKEINTRESOURCE(32631); + break; + + case MOUSECURSOR_CUSTOM: + { + if (m_CustomCursor) + { + return m_CustomCursor; + } + } + break; + } + + return LoadCursor(NULL, name); +} + +const WCHAR* CMouse::GetActionCommand(MOUSEACTION action) const +{ + const WCHAR* command = NULL; + + switch (action) + { + case MOUSE_LMB_DOWN: + command = m_LeftDownAction.c_str(); + break; + + case MOUSE_LMB_UP: + command = m_LeftUpAction.c_str(); + break; + + case MOUSE_LMB_DBLCLK: + command = m_LeftDoubleClickAction.c_str(); + break; + + case MOUSE_RMB_DOWN: + command = m_RightDownAction.c_str(); + break; + + case MOUSE_RMB_UP: + command = m_RightUpAction.c_str(); + break; + + case MOUSE_RMB_DBLCLK: + command = m_RightDoubleClickAction.c_str(); + break; + + case MOUSE_MMB_DOWN: + command = m_MiddleDownAction.c_str(); + break; + + case MOUSE_MMB_UP: + command = m_MiddleUpAction.c_str(); + break; + + case MOUSE_MMB_DBLCLK: + command = m_MiddleDoubleClickAction.c_str(); + break; + } + + return *command ? command : NULL; +} + +void CMouse::DestroyCustomCursor() +{ + if (m_CustomCursor) + { + DestroyCursor(m_CustomCursor); + m_CustomCursor = NULL; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0095426_cd_routing.cc b/pool/shard007/C++/0095426_cd_routing.cc new file mode 100644 index 0000000000000000000000000000000000000000..62917900870b4b04a39a0b7c531956e6c2c12350 --- /dev/null +++ b/pool/shard007/C++/0095426_cd_routing.cc @@ -0,0 +1,164 @@ +//-------------------------------------------------------------------------- +// Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. +// Copyright (C) 2002-2013 Sourcefire, Inc. +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License Version 2 as published +// by the Free Software Foundation. You may not use, modify or distribute +// this program under any other version 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 along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +//-------------------------------------------------------------------------- +// cd_routing.cc author Josh Rosenbaum + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "framework/codec.h" +#include "codecs/codec_module.h" +#include "protocols/protocol_ids.h" +#include "main/snort_config.h" +#include "protocols/ipv6.h" + +#define CD_IPV6_ROUTING_NAME "ipv6_routing" +#define CD_IPV6_ROUTING_HELP "support for IPv6 routing extension" + +namespace +{ +class Ipv6RoutingCodec : public Codec +{ +public: + Ipv6RoutingCodec() : Codec(CD_IPV6_ROUTING_NAME) { } + ~Ipv6RoutingCodec() { } + + bool decode(const RawData&, CodecData&, DecodeData&) override; + + void get_protocol_ids(std::vector&) override; +}; + +struct IP6Route +{ + uint8_t ip6rte_nxt; + uint8_t ip6rte_len; + uint8_t ip6rte_type; + uint8_t ip6rte_seg_left; + /* type specific data follows */ +}; + +#if 0 +// Keeping this around for future development +struct IP6Route0 +{ + uint8_t ip6rte0_nxt; + uint8_t ip6rte0_len; + uint8_t ip6rte0_type; + uint8_t ip6rte0_seg_left; + uint8_t ip6rte0_reserved; + uint8_t ip6rte0_bitmap[3]; + struct snort_in6_addr ip6rte0_addr[1]; /* Up to 23 IP6 addresses */ +}; +#endif +} // namespace + +void Ipv6RoutingCodec::get_protocol_ids(std::vector& v) +{ v.push_back(IPPROTO_ID_ROUTING); } + +bool Ipv6RoutingCodec::decode(const RawData& raw, CodecData& codec, DecodeData&) +{ + const IP6Route* const rte = reinterpret_cast(raw.data); + + if (raw.len < ip::MIN_EXT_LEN) + { + codec_event(codec, DECODE_IPV6_TRUNCATED_EXT); + return false; + } + + if ( snort_conf->hit_ip6_maxopts(codec.ip6_extension_count) ) + { + codec_event(codec, DECODE_IP6_EXCESS_EXT_HDR); + return false; + } + + if (raw.len < sizeof(IP6Route)) + { + codec_event(codec, DECODE_IPV6_TRUNCATED_EXT); + return false; + } + + /* Routing type 0 extension headers are evil creatures. */ + if (rte->ip6rte_type == 0) + codec_event(codec, DECODE_IPV6_ROUTE_ZERO); + + if (rte->ip6rte_nxt == IPPROTO_ID_HOPOPTS) + codec_event(codec, DECODE_IPV6_ROUTE_AND_HOPBYHOP); + + if (rte->ip6rte_nxt == IPPROTO_ID_ROUTING) + codec_event(codec, DECODE_IPV6_TWO_ROUTE_HEADERS); + + codec.lyr_len = ip::MIN_EXT_LEN + (rte->ip6rte_len << 3); + if (codec.lyr_len > raw.len) + { + codec_event(codec, DECODE_IPV6_TRUNCATED_EXT); + return false; + } + + codec.proto_bits |= PROTO_BIT__IP6_EXT; // check ip proto rules against this layer + codec.ip6_extension_count++; + codec.next_prot_id = rte->ip6rte_nxt; + codec.ip6_csum_proto = rte->ip6rte_nxt; + + // must be called AFTER setting next_prot_id + CheckIPv6ExtensionOrder(codec, IPPROTO_ID_ROUTING); + return true; +} + +//------------------------------------------------------------------------- +// api +//------------------------------------------------------------------------- + +static Codec* ctor(Module*) +{ return new Ipv6RoutingCodec(); } + +static void dtor(Codec* cd) +{ delete cd; } + +static const CodecApi ipv6_routing_api = +{ + { + PT_CODEC, + sizeof(CodecApi), + CDAPI_VERSION, + 0, + API_RESERVED, + API_OPTIONS, + CD_IPV6_ROUTING_NAME, + CD_IPV6_ROUTING_HELP, + nullptr, + nullptr, + }, + nullptr, // pinit + nullptr, // pterm + nullptr, // tinit + nullptr, // tterm + ctor, // ctor + dtor, // dtor +}; + +#ifdef BUILDING_SO +SO_PUBLIC const BaseApi* snort_plugins[] = +{ + &ipv6_routing_api.base, + nullptr +}; +#else +const BaseApi* cd_routing = &ipv6_routing_api.base; +#endif + diff --git a/pool/shard007/C++/0095429_PlayerShoot.cpp b/pool/shard007/C++/0095429_PlayerShoot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3acb4a92c150a538c42bf9ebd78ab262a4281d60 --- /dev/null +++ b/pool/shard007/C++/0095429_PlayerShoot.cpp @@ -0,0 +1,48 @@ +#include "PlayerShoot.h" + + +// Constructors +PlayerShoot::PlayerShoot() +{ + // Set packet id + this->type_ = PacketType::PLAYERSHOOT; +} +PlayerShoot::PlayerShoot(byte *b, int i) : Packet(b, i) +{ + // Set id and pass data to Parse + this->type_ = PacketType::PLAYERSHOOT; + read(); +} +PlayerShoot::PlayerShoot(Packet &p) : Packet(p) +{ + this->type_ = PacketType::PLAYERSHOOT; + read(); +} + + +Packet *PlayerShoot::write() +{ + // Clear the packet data just to be safe + this->clearData(); + // Write data + this->writeBytes(time); + this->writeBytes(bulletId); + this->writeBytes(containerType); + startingPos.Write(this); + this->writeBytes(static_cast(angle)); + // Send the packet + return this; +} + +void PlayerShoot::read() +{ + // Make sure the index is set to 0 + this->setIndex(0); + // Read in the data + time = this->readBytes(); + bulletId = this->readBytes(); + containerType = this->readBytes(); + startingPos.Read(this); + angle = static_cast(this->readBytes()); + // done! +} \ No newline at end of file diff --git a/pool/shard007/C++/0095432_UpdateRecommenderConfiguration.cpp b/pool/shard007/C++/0095432_UpdateRecommenderConfiguration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4842c31998ea3d748ed5a2bc9721a51c9d84e9a1 --- /dev/null +++ b/pool/shard007/C++/0095432_UpdateRecommenderConfiguration.cpp @@ -0,0 +1,189 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace Pinpoint +{ +namespace Model +{ + +UpdateRecommenderConfiguration::UpdateRecommenderConfiguration() : + m_attributesHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_nameHasBeenSet(false), + m_recommendationProviderIdTypeHasBeenSet(false), + m_recommendationProviderRoleArnHasBeenSet(false), + m_recommendationProviderUriHasBeenSet(false), + m_recommendationTransformerUriHasBeenSet(false), + m_recommendationsDisplayNameHasBeenSet(false), + m_recommendationsPerMessage(0), + m_recommendationsPerMessageHasBeenSet(false) +{ +} + +UpdateRecommenderConfiguration::UpdateRecommenderConfiguration(JsonView jsonValue) : + m_attributesHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_nameHasBeenSet(false), + m_recommendationProviderIdTypeHasBeenSet(false), + m_recommendationProviderRoleArnHasBeenSet(false), + m_recommendationProviderUriHasBeenSet(false), + m_recommendationTransformerUriHasBeenSet(false), + m_recommendationsDisplayNameHasBeenSet(false), + m_recommendationsPerMessage(0), + m_recommendationsPerMessageHasBeenSet(false) +{ + *this = jsonValue; +} + +UpdateRecommenderConfiguration& UpdateRecommenderConfiguration::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("Attributes")) + { + Aws::Map attributesJsonMap = jsonValue.GetObject("Attributes").GetAllObjects(); + for(auto& attributesItem : attributesJsonMap) + { + m_attributes[attributesItem.first] = attributesItem.second.AsString(); + } + m_attributesHasBeenSet = true; + } + + if(jsonValue.ValueExists("Description")) + { + m_description = jsonValue.GetString("Description"); + + m_descriptionHasBeenSet = true; + } + + if(jsonValue.ValueExists("Name")) + { + m_name = jsonValue.GetString("Name"); + + m_nameHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationProviderIdType")) + { + m_recommendationProviderIdType = jsonValue.GetString("RecommendationProviderIdType"); + + m_recommendationProviderIdTypeHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationProviderRoleArn")) + { + m_recommendationProviderRoleArn = jsonValue.GetString("RecommendationProviderRoleArn"); + + m_recommendationProviderRoleArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationProviderUri")) + { + m_recommendationProviderUri = jsonValue.GetString("RecommendationProviderUri"); + + m_recommendationProviderUriHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationTransformerUri")) + { + m_recommendationTransformerUri = jsonValue.GetString("RecommendationTransformerUri"); + + m_recommendationTransformerUriHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationsDisplayName")) + { + m_recommendationsDisplayName = jsonValue.GetString("RecommendationsDisplayName"); + + m_recommendationsDisplayNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("RecommendationsPerMessage")) + { + m_recommendationsPerMessage = jsonValue.GetInteger("RecommendationsPerMessage"); + + m_recommendationsPerMessageHasBeenSet = true; + } + + return *this; +} + +JsonValue UpdateRecommenderConfiguration::Jsonize() const +{ + JsonValue payload; + + if(m_attributesHasBeenSet) + { + JsonValue attributesJsonMap; + for(auto& attributesItem : m_attributes) + { + attributesJsonMap.WithString(attributesItem.first, attributesItem.second); + } + payload.WithObject("Attributes", std::move(attributesJsonMap)); + + } + + if(m_descriptionHasBeenSet) + { + payload.WithString("Description", m_description); + + } + + if(m_nameHasBeenSet) + { + payload.WithString("Name", m_name); + + } + + if(m_recommendationProviderIdTypeHasBeenSet) + { + payload.WithString("RecommendationProviderIdType", m_recommendationProviderIdType); + + } + + if(m_recommendationProviderRoleArnHasBeenSet) + { + payload.WithString("RecommendationProviderRoleArn", m_recommendationProviderRoleArn); + + } + + if(m_recommendationProviderUriHasBeenSet) + { + payload.WithString("RecommendationProviderUri", m_recommendationProviderUri); + + } + + if(m_recommendationTransformerUriHasBeenSet) + { + payload.WithString("RecommendationTransformerUri", m_recommendationTransformerUri); + + } + + if(m_recommendationsDisplayNameHasBeenSet) + { + payload.WithString("RecommendationsDisplayName", m_recommendationsDisplayName); + + } + + if(m_recommendationsPerMessageHasBeenSet) + { + payload.WithInteger("RecommendationsPerMessage", m_recommendationsPerMessage); + + } + + return payload; +} + +} // namespace Model +} // namespace Pinpoint +} // namespace Aws diff --git a/pool/shard007/C++/0095433_pendingLoginmgr.cpp b/pool/shard007/C++/0095433_pendingLoginmgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c56aadc69985d0b865c90471fa91229c14ddd646 --- /dev/null +++ b/pool/shard007/C++/0095433_pendingLoginmgr.cpp @@ -0,0 +1,137 @@ +/* +This source file is part of KBEngine +For the latest info, see http://www.kbengine.org/ + +Copyright (c) 2008-2012 KBEngine. + +KBEngine 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. + +KBEngine 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 KBEngine. If not, see . +*/ + + +#include "pendingLoginmgr.hpp" +#include "network/bundle.hpp" +#include "network/channel.hpp" +#include "network/event_dispatcher.hpp" +#include "network/network_interface.hpp" + +namespace KBEngine { +KBE_SINGLETON_INIT(PendingLoginMgr); + +#define OP_TIME_OUT_MAX 15 * stampsPerSecondD() + +//------------------------------------------------------------------------------------- +PendingLoginMgr::PendingLoginMgr(Mercury::NetworkInterface & networkInterface) : + Task(), + networkInterface_(networkInterface), + start_(false) +{ + // dispatcher().addFrequentTask(this); +} + +//------------------------------------------------------------------------------------- +PendingLoginMgr::~PendingLoginMgr() +{ + //dispatcher().cancelFrequentTask(this); +} + +//------------------------------------------------------------------------------------- +Mercury::EventDispatcher & PendingLoginMgr::dispatcher() +{ + return networkInterface_.dispatcher(); +} + +//------------------------------------------------------------------------------------- +bool PendingLoginMgr::add(PLInfos* infos) +{ + PTINFO_MAP::iterator iter = pPLMap_.find(infos->accountName); + if(iter != pPLMap_.end()) + { + return false; + } + + if(!start_) + { + //dispatcher().addFrequentTask(this); + start_ = true; + } + + pPLMap_[infos->accountName] = infos; + infos->lastProcessTime = timestamp(); + + DEBUG_MSG("PendingLoginMgr::add: size=%d.\n", pPLMap_.size()); + return true; +} + +//------------------------------------------------------------------------------------- +PendingLoginMgr::PLInfos* PendingLoginMgr::remove(std::string& accountName) +{ + PTINFO_MAP::iterator iter = pPLMap_.find(accountName); + if(iter != pPLMap_.end()) + { + PLInfos* infos = iter->second; + pPLMap_.erase(iter); + return infos; + } + + //ERROR_MSG("PendingLoginMgr::remove::not found accountName[%s].\n", accountName); + return NULL; +} + +//------------------------------------------------------------------------------------- +PendingLoginMgr::PLInfos* PendingLoginMgr::find(std::string& accountName) +{ + PTINFO_MAP::iterator iter = pPLMap_.find(accountName); + if(iter != pPLMap_.end()) + { + PLInfos* infos = iter->second; + return infos; + } + + return NULL; +} + +//------------------------------------------------------------------------------------- +bool PendingLoginMgr::process() +{ + if(pPLMap_.size() <= 0) + { + start_ = false; + return false; + } + + PTINFO_MAP::iterator iter = pPLMap_.begin(); + while (iter != pPLMap_.end()) + { + PLInfos* infos = iter->second; + + TimeStamp curr = timestamp(); + if(curr - infos->lastProcessTime >= OP_TIME_OUT_MAX) + { + iter = pPLMap_.erase(iter); + DEBUG_MSG("PendingLoginMgr::process: size=%d, remove=%s.\n", + pPLMap_.size(), infos->accountName.c_str()); + + SAFE_RELEASE(infos); + } + else + { + ++iter; + } + } + + return true; +} + +//------------------------------------------------------------------------------------- +} diff --git a/pool/shard007/C++/0095434_InputHooker.cpp b/pool/shard007/C++/0095434_InputHooker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01009ff6b902d32fc0090cf5eee097a961fa4573 --- /dev/null +++ b/pool/shard007/C++/0095434_InputHooker.cpp @@ -0,0 +1,214 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +// Part of Injectable Generic Camera System +// Copyright(c) 2017, Frans Bouma +// All rights reserved. +// https://github.com/FransBouma/InjectableGenericCameraSystem +// +// 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. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#include "stdafx.h" +#include "Utils.h" +#include "MinHook.h" +#include "Gamepad.h" +#include "Globals.h" +#include "input.h" + +using namespace std; + +namespace IGCS::InputHooker +{ + //-------------------------------------------------------------------------------------------------------------------------------- + // Forward declarations + void processMessage(LPMSG lpMsg, bool removeIfRequired); + + //-------------------------------------------------------------------------------------------------------------------------------- + // Typedefs of functions to hook + typedef DWORD(WINAPI *XINPUTGETSTATE)(DWORD, XINPUT_STATE*); + typedef BOOL(WINAPI *GETMESSAGEA)(LPMSG, HWND, UINT, UINT); + typedef BOOL(WINAPI *GETMESSAGEW)(LPMSG, HWND, UINT, UINT); + typedef BOOL(WINAPI *PEEKMESSAGEA)(LPMSG, HWND, UINT, UINT, UINT); + typedef BOOL(WINAPI *PEEKMESSAGEW)(LPMSG, HWND, UINT, UINT, UINT); + + //-------------------------------------------------------------------------------------------------------------------------------- + // Pointers to the original hooked functions + static XINPUTGETSTATE hookedXInputGetState = nullptr; + static GETMESSAGEA hookedGetMessageA = nullptr; + static GETMESSAGEW hookedGetMessageW = nullptr; + static PEEKMESSAGEA hookedPeekMessageA = nullptr; + static PEEKMESSAGEW hookedPeekMessageW = nullptr; + + //-------------------------------------------------------------------------------------------------------------------------------- + // Implementations + + // wrapper for easier setting up hooks for MinHook + template + inline MH_STATUS MH_CreateHookEx(LPVOID pTarget, LPVOID pDetour, T** ppOriginal) + { + return MH_CreateHook(pTarget, pDetour, reinterpret_cast(ppOriginal)); + } + + template + inline MH_STATUS MH_CreateHookApiEx( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, T** ppOriginal) + { + return MH_CreateHookApi( + pszModule, pszProcName, pDetour, reinterpret_cast(ppOriginal)); + } + + + // Our own version of XInputGetState + DWORD WINAPI detourXInputGetState(DWORD dwUserIndex, XINPUT_STATE* pState) + { + // first call the original function + DWORD toReturn = hookedXInputGetState(dwUserIndex, pState); + // check if the passed in pState is equal to our gamestate. If so, always allow. + if (g_cameraEnabled && pState != Globals::instance().gamePad().getState()) + { + // check if input is blocked. If so, zero the state, so the host will see no input data + if (Globals::instance().inputBlocked()) + { + ZeroMemory(pState, sizeof(XINPUT_STATE)); + } + } + return toReturn; + } + + + // Our own version of GetMessageA + BOOL WINAPI detourGetMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax) + { + // first call the original function + if (!hookedGetMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax)) + { + return FALSE; + } + processMessage(lpMsg, true); + return TRUE; + } + + + // Our own version of GetMessageW + BOOL WINAPI detourGetMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax) + { + // first call the original function + if (!hookedGetMessageW(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax)) + { + return FALSE; + } + processMessage(lpMsg, true); + return TRUE; + } + + + // Our own version of PeekMessageA + BOOL WINAPI detourPeekMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) + { + // first call the original function + if (!hookedPeekMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg)) + { + return FALSE; + } + processMessage(lpMsg, wRemoveMsg & PM_REMOVE); + return TRUE; + } + + // Our own version of PeekMessageW + BOOL WINAPI detourPeekMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) + { + // first call the original function + if (!hookedPeekMessageW(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg)) + { + return FALSE; + } + processMessage(lpMsg, wRemoveMsg & PM_REMOVE); + return TRUE; + } + + + void processMessage(LPMSG lpMsg, bool removeIfRequired) + { + if (lpMsg->hwnd != nullptr && removeIfRequired && Input::handleMessage(lpMsg)) + { + // message was handled by our code. This means it's a message we want to block if input blocking is enabled. + if (Globals::instance().inputBlocked()) + { + lpMsg->message = WM_NULL; // reset to WM_NULL so the host will receive a dummy message instead. + } + } + } + + + // Sets the input hooks for the various input related functions we defined own wrapper functions for. After a successful hook setup + // they're enabled. + void setInputHooks() + { + MH_Initialize(); + if (MH_CreateHookApiEx(L"xinput1_3", "XInputGetState", &detourXInputGetState, &hookedXInputGetState) != MH_OK) + { + Console::WriteError("Hooking XInput1_3 failed!"); + } +#ifdef _DEBUG + Console::WriteLine("Hook set to XInputSetState"); +#endif + + if (MH_CreateHookApiEx(L"user32", "GetMessageA", &detourGetMessageA, &hookedGetMessageA) != MH_OK) + { + Console::WriteError("Hooking GetMessageA failed!"); + } +#ifdef _DEBUG + Console::WriteLine("Hook set to GetMessageA"); +#endif + if (MH_CreateHookApiEx(L"user32", "GetMessageW", &detourGetMessageW, &hookedGetMessageW) != MH_OK) + { + Console::WriteError("Hooking GetMessageW failed!"); + } +#ifdef _DEBUG + Console::WriteLine("Hook set to GetMessageW"); +#endif + if (MH_CreateHookApiEx(L"user32", "PeekMessageA", &detourPeekMessageA, &hookedPeekMessageA) != MH_OK) + { + Console::WriteError("Hooking PeekMessageA failed!"); + } +#ifdef _DEBUG + Console::WriteLine("Hook set to PeekMessageA"); +#endif + if (MH_CreateHookApiEx(L"user32", "PeekMessageW", &detourPeekMessageW, &hookedPeekMessageW) != MH_OK) + { + Console::WriteError("Hooking PeekMessageW failed!"); + } +#ifdef _DEBUG + Console::WriteLine("Hook set to PeekMessageW"); +#endif + + // Enable all hooks + if (MH_EnableHook(MH_ALL_HOOKS) == MH_OK) + { +#ifdef _DEBUG + Console::WriteLine("All hooks enabled"); +#endif + } + else + { + Console::WriteError("Enabling hooks failed"); + } + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0095441_integration_tests.cpp b/pool/shard007/C++/0095441_integration_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54342bc97bf035799bec53172b726ea6b35107b6 --- /dev/null +++ b/pool/shard007/C++/0095441_integration_tests.cpp @@ -0,0 +1,102 @@ +//@author A0112054Y +#include "stdafx.h" +#include "CppUnitTest.h" +#include "common.h" + +#include "../You-DataStore/datastore.h" +#include "internal/state.h" +#include "api.h" + +using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; + +namespace You { +namespace QueryEngine { +namespace UnitTests { + +using boost::gregorian::date; +using boost::gregorian::max_date_time; + +using You::QueryEngine::Filter; +using You::QueryEngine::Task; +using You::QueryEngine::Response; +using You::QueryEngine::QueryEngine; +using You::DataStore::DataStore; + +/// Test the main \ref QueryEngine API +TEST_CLASS(IntegrateWithDataStoreTest) { + const Task::Description desc = L"Learn Haskell Lens"; + const Task::Description desc2 = L"Learn me"; + const Task::Time dead = Task::NEVER; + const Task::Priority prio = Task::Priority::HIGH; + + TEST_METHOD_INITIALIZE(cleanupBeforeTest) { + You::DataStore::DataStore::get().wipeData(); + Internal::State::clear(); + } + + TEST_METHOD_CLEANUP(cleanupAfterTest) { + You::DataStore::DataStore::get().wipeData(); + Internal::State::clear(); + } + + TEST_METHOD(initiallyDataStoreShouldBeEmpty) { + auto taskList = boost::get>( + QueryEngine::executeQuery( + QueryEngine::GetTask(Filter::anyTask()))); + Task::ID initialID = Internal::State::get().getMaxIDFromDataStore(); + Assert::AreEqual(taskList.size(), static_cast(0)); + Assert::IsTrue(initialID == -1L); + } + + TEST_METHOD(postTaskToDataStore) { + auto task = boost::get( + QueryEngine::executeQuery( + QueryEngine::AddTask(desc, dead, dead, prio, {}, {}))); + Internal::State::initialize(); + Task::ID initialID = Internal::State::get().getMaxIDFromDataStore(); + Assert::IsTrue(initialID == 1L); + auto taskList = boost::get>( + QueryEngine::executeQuery( + QueryEngine::GetTask(Filter::anyTask()))); + Assert::AreEqual(taskList.size(), static_cast(1)); + } + + TEST_METHOD(putTaskToDataStore) { + auto task = boost::get( + QueryEngine::executeQuery( + QueryEngine::AddTask(desc, dead, dead, prio, {}, {}))); + + Internal::State::initialize(); + task.setDescription(L"Hello World"); + QueryEngine::executeQuery(QueryEngine::UpdateTask(task)); + + Internal::State::initialize(); + auto taskList = boost::get>( + QueryEngine::executeQuery( + QueryEngine::GetTask(Filter::anyTask()))); + Assert::AreEqual(taskList[0].getDescription(), + std::wstring(L"Hello World")); + } + + TEST_METHOD(eraseTaskFromDataStore) { + auto task = boost::get( + QueryEngine::executeQuery( + QueryEngine::AddTask(desc, dead, dead, prio, {}, {}))); + + Internal::State::initialize(); + QueryEngine::executeQuery(QueryEngine::DeleteTask(task.getID())); + + Internal::State::initialize(); + auto taskList = boost::get>( + QueryEngine::executeQuery( + QueryEngine::GetTask(Filter::anyTask()))); + Assert::AreEqual(taskList.size(), static_cast(0)); + } + + IntegrateWithDataStoreTest& operator=( + const IntegrateWithDataStoreTest&) = delete; +}; + +} // namespace UnitTests +} // namespace QueryEngine +} // namespace You diff --git a/pool/shard007/C++/0095446_main.cpp b/pool/shard007/C++/0095446_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b21d1eca21abdb753c5381e7c76a0d4b821b2090 --- /dev/null +++ b/pool/shard007/C++/0095446_main.cpp @@ -0,0 +1,62 @@ +/* main.cpp + * + * This file is part of the EPICS QT Framework, initially developed at the + * Australian Synchrotron. + * + * Copyright (c) 2009-2018 Australian Synchrotron + * + * The EPICS QT Framework is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The EPICS QT Framework 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 EPICS QT Framework. If not, see . + * + * Author: + * Andrew Rhyder + * Contact details: + * andrew.rhyder@synchrotron.org.au + */ + +#include +#include +#include + +//------------------------------------------------------------------------------ +// +int main(int argc, char *argv[]) +{ + // Intercept help/verson arguments before QApplication created. + // + if (argc >= 2) { + const QString firstArg (argv[1]); + + if ((firstArg == "-h") || (firstArg == "--help")) { + QEGui::printHelp(); + return 0; + } + + if ((firstArg == "-v") || (firstArg == "--version")) { + QEGui::printVersion(); + return 0; + } + } + +#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) + // Avoid Qt WebEngine seems to be initialized from a plugin warning. + QCoreApplication::setAttribute( Qt::AA_ShareOpenGLContexts ); +#endif + + QEGui* app = new QEGui( argc, argv ); + int ret = app->run(); + delete app; + return ret; +} + +// end diff --git a/pool/shard007/C++/0095454_mouse_action_map_label.cpp b/pool/shard007/C++/0095454_mouse_action_map_label.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70fdc18877861ede65c0988c3f3c9e500d2a0677 --- /dev/null +++ b/pool/shard007/C++/0095454_mouse_action_map_label.cpp @@ -0,0 +1,132 @@ +/* + Copyright (C) 2008 - 2018 by Fabian Mueller + Part of the Battle for Wesnoth Project https://www.wesnoth.org/ + + 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. + + See the COPYING file for more details. +*/ +#define GETTEXT_DOMAIN "wesnoth-editor" + +#include "editor/action/mouse/mouse_action_map_label.hpp" +#include "editor/action/action_label.hpp" + +#include "editor/editor_display.hpp" +#include "editor/controller/editor_controller.hpp" +#include "editor/map/context_manager.hpp" + +#include "gui/dialogs/editor/edit_label.hpp" + +#include "font/standard_colors.hpp" +#include "color.hpp" + +namespace editor { + +editor_action* mouse_action_map_label::click_left(editor_display& disp, int x, int y) +{ + click_ = true; + map_location hex = disp.hex_clicked_on(x, y); + clicked_on_ = hex; + last_draged_ = hex; + return nullptr; +} + +editor_action* mouse_action_map_label::drag_left(editor_display& disp, int x, int y + , bool& partial, editor_action* /*last_undo*/) +{ + map_location hex = disp.hex_clicked_on(x, y); + + /* Cursor is still on old hex field */ + if (hex == last_draged_) + return nullptr; + click_ = false; + + editor_action_chain* chain = nullptr; + const terrain_label* label = disp.get_controller().get_current_map_context().get_labels().get_label(last_draged_); + + + if (label) { + partial = true; + chain = new editor_action_chain(new editor_action_label_delete(last_draged_)); + chain->append_action(new editor_action_label(hex, label->text(), label->team_name(), label->color(), + label->visible_in_fog(), label->visible_in_shroud(), label->immutable(), label->category())); + } + + last_draged_ = hex; + return chain; +} + +editor_action* mouse_action_map_label::up_left(editor_display& disp, int x, int y) +{ + if (!click_) return nullptr; + click_ = false; + + const map_location hex = disp.hex_clicked_on(x, y); + if (!disp.get_map().on_board(hex)) { + return nullptr; + } + + const terrain_label* old_label = disp.get_controller().get_current_map_context().get_labels().get_label(hex); + std::string label = old_label ? old_label->text() : ""; + std::string team_name = old_label ? old_label->team_name() : ""; + std::string category = old_label ? old_label->category() : ""; + bool visible_shroud = old_label ? old_label->visible_in_shroud() : false; + bool visible_fog = old_label ? old_label->visible_in_fog() : true; + bool immutable = old_label ? old_label->immutable() : true; + color_t color = old_label ? old_label->color() : font::NORMAL_COLOR; + + gui2::dialogs::editor_edit_label d(label, immutable, visible_fog, visible_shroud, color, category); + + editor_action* a = nullptr; + if(d.show()) { + a = new editor_action_label(hex, label, team_name, color + , visible_fog, visible_shroud, immutable, category); + update_brush_highlights(disp, hex); + } + return a; +} + +editor_action* mouse_action_map_label::click_right(editor_display& /*disp*/, int /*x*/, int /*y*/) +{ + return nullptr; +} + +editor_action* mouse_action_map_label::up_right(editor_display& disp, int x, int y) +{ + map_location hex = disp.hex_clicked_on(x, y); + + //TODO +// const terrain_label* clicked_label = disp.map().get_map_labels().get_label(hex); + //if (!clicked_label) + // return nullptr; + + return new editor_action_label_delete(hex); +} + +void mouse_action_map_label::set_mouse_overlay(editor_display& disp) +{ + surface image60 = image::get_image("icons/action/editor-tool-label_60.png"); + + //TODO avoid hardcoded hex field size + surface image(72,72); + + SDL_Rect r {6, 6, 0, 0}; + sdl_blit(image60, nullptr, image, &r); + + uint8_t alpha = 196; + int size = image->w; + int zoom = static_cast(size * disp.get_zoom_factor()); + + // Add the alpha factor and scale the image + adjust_surface_alpha(image, alpha); + image = scale_surface(image, zoom, zoom); + disp.set_mouseover_hex_overlay(image); +} + + +} //end namespace editor diff --git a/pool/shard007/C++/0095457_pepper_permission_util.cc b/pool/shard007/C++/0095457_pepper_permission_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..167687ced298a2377614af8ea891a60bb0c95422 --- /dev/null +++ b/pool/shard007/C++/0095457_pepper_permission_util.cc @@ -0,0 +1,111 @@ +// 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 "chrome/common/pepper_permission_util.h" + +#include + +#include "base/command_line.h" +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_tokenizer.h" +#include "extensions/common/constants.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_set.h" +#include "extensions/common/manifest_handlers/shared_module_info.h" + +using extensions::Extension; +using extensions::Manifest; +using extensions::SharedModuleInfo; + +namespace chrome { + +namespace { + +std::string HashHost(const std::string& host) { + const std::string id_hash = base::SHA1HashString(host); + DCHECK_EQ(id_hash.length(), base::kSHA1Length); + return base::HexEncode(id_hash.c_str(), id_hash.length()); +} + +bool HostIsInSet(const std::string& host, const std::set& set) { + return set.count(host) > 0 || set.count(HashHost(host)) > 0; +} + +} // namespace + +bool IsExtensionOrSharedModuleWhitelisted( + const GURL& url, + const extensions::ExtensionSet* extension_set, + const std::set& whitelist) { + if (!url.is_valid() || !url.SchemeIs(extensions::kExtensionScheme)) + return false; + + const std::string host = url.host(); + if (HostIsInSet(host, whitelist)) + return true; + + // Check the modules that are imported by this extension to see if any of them + // is whitelisted. + const Extension* extension = extension_set ? extension_set->GetByID(host) + : NULL; + if (!extension) + return false; + + typedef std::vector ImportInfoVector; + const ImportInfoVector& imports = SharedModuleInfo::GetImports(extension); + for (ImportInfoVector::const_iterator it = imports.begin(); + it != imports.end(); + ++it) { + const Extension* imported_extension = + extension_set->GetByID(it->extension_id); + if (imported_extension && + SharedModuleInfo::IsSharedModule(imported_extension) && + // We check the whitelist explicitly even though the extension should + // never have been allowed to be installed in the first place if this + // fails. See SharedModuleService::CheckImports for details. + SharedModuleInfo::IsExportAllowedByWhitelist(imported_extension, + host) && + HostIsInSet(it->extension_id, whitelist)) { + return true; + } + } + + return false; +} + +bool IsHostAllowedByCommandLine(const GURL& url, + const extensions::ExtensionSet* extension_set, + const char* command_line_switch) { + if (!url.is_valid()) + return false; + + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + const std::string allowed_list = + command_line.GetSwitchValueASCII(command_line_switch); + if (allowed_list.empty()) + return false; + + const std::string host = url.host(); + if (allowed_list == "*") { + // For now, we only allow packaged and platform apps in this wildcard. + if (!extension_set || !url.SchemeIs(extensions::kExtensionScheme)) + return false; + + const Extension* extension = extension_set->GetByID(host); + return extension && + (extension->GetType() == Manifest::TYPE_LEGACY_PACKAGED_APP || + extension->GetType() == Manifest::TYPE_PLATFORM_APP); + } + + base::StringTokenizer t(allowed_list, ","); + while (t.GetNext()) { + if (t.token() == host) + return true; + } + + return false; +} + +} // namespace chrome diff --git a/pool/shard007/C++/0095463_CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03.cpp b/pool/shard007/C++/0095463_CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e506ba1ecdd0f1af8a9d361a384c1cec919b716a --- /dev/null +++ b/pool/shard007/C++/0095463_CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03.cpp @@ -0,0 +1,199 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03.cpp +Label Definition File: CWE457_Use_of_Uninitialized_Variable__twointsclass_array.label.xml +Template File: sources-sinks-03.tmpl.cpp +*/ +/* + * @description + * CWE: 457 Use of Uninitialized Variable + * BadSource: no_init Don't initialize data + * GoodSource: Initialize data + * Sinks: use + * GoodSink: Initialize then use data + * BadSink : Use data + * Flow Variant: 03 Control flow: if(5==5) and if(5!=5) + * + * */ + +#include "std_testcase.h" + +namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03 +{ + +#ifndef OMITBAD + +void bad() +{ + TwoIntsClass * data; + data = new TwoIntsClass[10]; + if(5==5) + { + /* POTENTIAL FLAW: Don't initialize data */ + ; /* empty statement needed for some flow variants */ + } + if(5==5) + { + /* POTENTIAL FLAW: Use data without initializing it */ + for(int i=0; i<10; i++) + { + printIntLine(data[i].intOne); + printIntLine(data[i].intTwo); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodB2G1() - use badsource and goodsink by changing the second 5==5 to 5!=5 */ +static void goodB2G1() +{ + TwoIntsClass * data; + data = new TwoIntsClass[10]; + if(5==5) + { + /* POTENTIAL FLAW: Don't initialize data */ + ; /* empty statement needed for some flow variants */ + } + if(5!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Ensure data is initialized before use */ + for(int i=0; i<10; i++) + { + data[i].intOne = i; + data[i].intTwo = i; + } + for(int i=0; i<10; i++) + { + printIntLine(data[i].intOne); + printIntLine(data[i].intTwo); + } + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + TwoIntsClass * data; + data = new TwoIntsClass[10]; + if(5==5) + { + /* POTENTIAL FLAW: Don't initialize data */ + ; /* empty statement needed for some flow variants */ + } + if(5==5) + { + /* FIX: Ensure data is initialized before use */ + for(int i=0; i<10; i++) + { + data[i].intOne = i; + data[i].intTwo = i; + } + for(int i=0; i<10; i++) + { + printIntLine(data[i].intOne); + printIntLine(data[i].intTwo); + } + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first 5==5 to 5!=5 */ +static void goodG2B1() +{ + TwoIntsClass * data; + data = new TwoIntsClass[10]; + if(5!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Completely initialize data */ + for(int i=0; i<10; i++) + { + data[i].intOne = i; + data[i].intTwo = i; + } + } + if(5==5) + { + /* POTENTIAL FLAW: Use data without initializing it */ + for(int i=0; i<10; i++) + { + printIntLine(data[i].intOne); + printIntLine(data[i].intTwo); + } + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + TwoIntsClass * data; + data = new TwoIntsClass[10]; + if(5==5) + { + /* FIX: Completely initialize data */ + for(int i=0; i<10; i++) + { + data[i].intOne = i; + data[i].intTwo = i; + } + } + if(5==5) + { + /* POTENTIAL FLAW: Use data without initializing it */ + for(int i=0; i<10; i++) + { + printIntLine(data[i].intOne); + printIntLine(data[i].intTwo); + } + } +} + +void good() +{ + goodB2G1(); + goodB2G2(); + goodG2B1(); + goodG2B2(); +} + +#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 CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_03; /* 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/shard007/C++/0095464_local_ads_mark.cpp b/pool/shard007/C++/0095464_local_ads_mark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e990d132f363eb55db171be76e46d6b4ac5edd82 --- /dev/null +++ b/pool/shard007/C++/0095464_local_ads_mark.cpp @@ -0,0 +1,68 @@ +#include "map/local_ads_mark.hpp" + +#include "drape_frontend/color_constants.hpp" + +#include + +namespace +{ +static std::string const kLocalAdsPrimaryText = "LocalAdsPrimaryText"; +static std::string const kLocalAdsPrimaryTextOutline = "LocalAdsPrimaryTextOutline"; +static std::string const kLocalAdsSecondaryText = "LocalAdsSecondaryText"; +static std::string const kLocalAdsSecondaryTextOutline = "LocalAdsSecondaryTextOutline"; + +float const kLocalAdsPrimaryTextSize = 11.0f; +float const kLocalAdsSecondaryTextSize = 10.0f; +float const kSecondaryOffsetY = 2.0; +} // namespace + +LocalAdsMark::LocalAdsMark(m2::PointD const & ptOrg, + UserMarkContainer * container) + : UserMark(ptOrg, container) +{ + m_titleDecl.m_anchor = dp::Top; + m_titleDecl.m_primaryTextFont.m_color = df::GetColorConstant(kLocalAdsPrimaryText); + m_titleDecl.m_primaryTextFont.m_outlineColor = df::GetColorConstant(kLocalAdsPrimaryTextOutline); + m_titleDecl.m_primaryTextFont.m_size = kLocalAdsPrimaryTextSize; + m_titleDecl.m_secondaryTextFont.m_color = df::GetColorConstant(kLocalAdsSecondaryText); + m_titleDecl.m_secondaryTextFont.m_outlineColor = df::GetColorConstant(kLocalAdsSecondaryTextOutline); + m_titleDecl.m_secondaryTextFont.m_size = kLocalAdsSecondaryTextSize; + m_titleDecl.m_secondaryOffset = m2::PointF(0, kSecondaryOffsetY); +} + +drape_ptr LocalAdsMark::GetSymbolNames() const +{ + auto symbol = make_unique_dp(); + symbol->insert(std::make_pair(1 /* zoomLevel */, m_data.m_symbolName)); + return symbol; +} + +df::RenderState::DepthLayer LocalAdsMark::GetDepthLayer() const +{ + return df::RenderState::LocalAdsMarkLayer; +} + +drape_ptr LocalAdsMark::GetTitleDecl() const +{ + auto titles = make_unique_dp(); + titles->push_back(m_titleDecl); + return titles; +} + +void LocalAdsMark::SetData(LocalAdsMarkData && data) +{ + SetDirty(); + m_data = std::move(data); + + m_titleDecl.m_primaryText = m_data.m_mainText; + if (!m_titleDecl.m_primaryText.empty()) + m_titleDecl.m_secondaryText = m_data.m_auxText; + else + m_titleDecl.m_secondaryText.clear(); +} + +void LocalAdsMark::SetFeatureId(FeatureID const & id) +{ + SetDirty(); + m_featureId = id; +} diff --git a/pool/shard007/C++/0095465_ConfigFileReader.cpp b/pool/shard007/C++/0095465_ConfigFileReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfec3986f7022540a457e2c1b27319bdea26a10c --- /dev/null +++ b/pool/shard007/C++/0095465_ConfigFileReader.cpp @@ -0,0 +1,97 @@ +#include "Globals.h" +#include "ConfigFileReader.h" +#include "ConfigFileException.h" +#include + + +using namespace std; +using namespace Skyward; +using namespace Exception; +ConfigFileReader::ConfigFileReader(string c_path) +{ + this->open_config(c_path); +} + +ConfigFileReader::~ConfigFileReader() +{ + //dtor +} + +void ConfigFileReader::reset_position() +{ + m_infile_statement->seekg(0, ios::beg); + m_infile_line->seekg(0, ios::beg); +} + +void ConfigFileReader::open_config(string a_path) +{ + this->m_infile_line = new ifstream(a_path.c_str()); + this->m_infile_statement = new ifstream(a_path.c_str()); +} + +string ConfigFileReader::get_next_line() +{ + if (!m_infile_line->is_open()) + { + throw new ConfigFileException("Error in accessing config file"); + } + string config_data; + getline((*m_infile_line), config_data); + this->m_current_line = config_data; + return this->m_current_line; +} + +string ConfigFileReader::get_next_statement() +{ + if (!m_infile_statement->is_open()) + { + throw new ConfigFileException("Error in accessing config file"); + } + + char t_data[2048]; + + m_infile_statement->get(t_data, 2048, ';'); + + string tt_data = t_data; + m_current_statement = tt_data; + m_infile_statement->get(); + return tt_data; +} + +string ConfigFileReader::get_current_parameter() +{ + int t_first = m_current_statement.find(':', 0); + string _param = m_current_statement.substr(0, t_first); + return _param; +} + +string ConfigFileReader::get_current_attribute(int a_index) +{ + //const char* _char22 = m_current_statement.c_str(); + int t_first = m_current_statement.find(':', 0); + int _end_count = m_current_statement.size() - t_first; + string _attrs = m_current_statement.substr(t_first, _end_count); + const char* _char = _attrs.c_str(); + int c_count = 0; + vector positions; + positions.push_back(0); + for (unsigned int for_index = 0; for_index < _attrs.size(); for_index++) + { + if (_char[for_index] == ',') + { + c_count++; + positions.push_back(for_index); + } + } + int attr_count = c_count + 1; + if (a_index > (attr_count - 1)) + { + myProg->s_log->error("get_current_attribute a_index > size in config file. Returning empty string."); + string retv(""); + return retv; + } + + if (a_index == attr_count - 2) _end_count = _attrs.size() - positions[a_index]; + string ret_attr = _attrs.substr(positions[a_index] + 1, positions[a_index + 1] - positions[a_index] - 1); + return ret_attr; +} diff --git a/pool/shard007/C++/0095467_Display.cpp b/pool/shard007/C++/0095467_Display.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0d8b44c3156a4c4e2fda6a40d06e0dd68c7756b --- /dev/null +++ b/pool/shard007/C++/0095467_Display.cpp @@ -0,0 +1,172 @@ +/* + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include +#include +#include + +static bool get_brightness(GUID *pwrGUID, UINT32 *val) +{ + DWORD r, size; + SYSTEM_POWER_STATUS pwr_status; + + GetSystemPowerStatus(&pwr_status); + + bool dc = pwr_status.ACLineStatus == 0; + + size = sizeof(*val); + + if (dc) + r = PowerReadDCValue(NULL, pwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, NULL, + (unsigned char *)val, &size); + else + r = PowerReadACValue(NULL, pwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, NULL, + (unsigned char *)val, &size); + + if (r != ERROR_SUCCESS) + { + printf("PowerReadDC/ACValue failed: %u\n", r); + return false; + } + + return true; +} + +static bool set_brightness(GUID *pwrGUID, UINT32 val) +{ + DWORD r, size; + SYSTEM_POWER_STATUS pwr_status; + + GetSystemPowerStatus(&pwr_status); + + bool dc = pwr_status.ACLineStatus == 0; + + size = sizeof(val); + + if (dc) + r = PowerWriteDCValueIndex(NULL, pwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, val); + else + r = PowerWriteACValueIndex(NULL, pwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, val); + + if (r != ERROR_SUCCESS) + { + printf("PowerWriteDC/ACValueIndex failed: %u\n", r); + return false; + } + + r = PowerSetActiveScheme(NULL, pwrGUID); + if (r != ERROR_SUCCESS) + { + printf("PowerSetActiveScheme failed: %u\n", r); + return false; + } + + return true; +} + +static void display_bl_set() +{ + GUID *pPwrGUID; + DWORD r; + DWORD size; + UINT32 v; + + r = PowerGetActiveScheme(NULL, &pPwrGUID); + if (r != ERROR_SUCCESS) + { + printf("PowerGetActiveScheme failed: %u\n", r); + return; + } + + size = sizeof(v); + + r = PowerReadDCValue(NULL, pPwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, NULL, + (unsigned char *)&v, &size); + if (r != ERROR_SUCCESS) + { + printf("PowerReadDCValue failed: %u\n", r); + return; + } + + v = 0; + + r = PowerWriteDCValueIndex(NULL, pPwrGUID, &GUID_VIDEO_SUBGROUP, &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS, v); + if (r != ERROR_SUCCESS) + { + printf("PowerWriteDCValueIndex failed: %u\n", r); + return; + } + + r = PowerSetActiveScheme(NULL, pPwrGUID); + if (r != ERROR_SUCCESS) + { + printf("PowerSetActiveScheme failed: %u\n", r); + return; + } +} + +void display_bl_inc() +{ + GUID *pwrGUID; + DWORD r; + + r = PowerGetActiveScheme(NULL, &pwrGUID); + if (r != ERROR_SUCCESS) + { + printf("PowerGetActiveScheme failed: %u\n", r); + return; + } + + UINT32 val; + + get_brightness(pwrGUID, &val); + + if (val == 100) + return; + + if (val > 90) + val = 100; + else + val += 10; + + set_brightness(pwrGUID, val); +} + +void display_bl_dec() +{ + GUID *pwrGUID; + DWORD r; + + r = PowerGetActiveScheme(NULL, &pwrGUID); + if (r != ERROR_SUCCESS) + { + printf("PowerGetActiveScheme failed: %u\n", r); + return; + } + + UINT32 val; + + get_brightness(pwrGUID, &val); + + if (val == 0) + return; + + if (val < 10) + val = 0; + else + val -= 10; + + set_brightness(pwrGUID, val); +} diff --git a/pool/shard007/C++/0095471_DeleteWithNonVirtualDtorChecker.cpp b/pool/shard007/C++/0095471_DeleteWithNonVirtualDtorChecker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45c1984c5e157b176fc0ad00f6c0304239fd13cf --- /dev/null +++ b/pool/shard007/C++/0095471_DeleteWithNonVirtualDtorChecker.cpp @@ -0,0 +1,153 @@ +//===-- DeleteWithNonVirtualDtorChecker.cpp -----------------------*- C++ -*--// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Defines a checker for the OOP52-CPP CERT rule: Do not delete a polymorphic +// object without a virtual destructor. +// +// Diagnostic flags -Wnon-virtual-dtor and -Wdelete-non-virtual-dtor report if +// an object with a virtual function but a non-virtual destructor exists or is +// deleted, respectively. +// +// This check exceeds them by comparing the dynamic and static types of the +// object at the point of destruction and only warns if it happens through a +// pointer to a base type without a virtual destructor. The check places a note +// at the last point where the conversion from derived to base happened. +// +//===----------------------------------------------------------------------===// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/CheckerManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" + +using namespace clang; +using namespace ento; + +namespace { +class DeleteWithNonVirtualDtorChecker + : public Checker> { + mutable std::unique_ptr BT; + + class DeleteBugVisitor : public BugReporterVisitor { + public: + DeleteBugVisitor() : Satisfied(false) {} + void Profile(llvm::FoldingSetNodeID &ID) const override { + static int X = 0; + ID.AddPointer(&X); + } + PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, + BugReporterContext &BRC, + PathSensitiveBugReport &BR) override; + + private: + bool Satisfied; + }; + +public: + void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const; +}; +} // end anonymous namespace + +void DeleteWithNonVirtualDtorChecker::checkPreStmt(const CXXDeleteExpr *DE, + CheckerContext &C) const { + const Expr *DeletedObj = DE->getArgument(); + const MemRegion *MR = C.getSVal(DeletedObj).getAsRegion(); + if (!MR) + return; + + const auto *BaseClassRegion = MR->getAs(); + const auto *DerivedClassRegion = MR->getBaseRegion()->getAs(); + if (!BaseClassRegion || !DerivedClassRegion) + return; + + const auto *BaseClass = BaseClassRegion->getValueType()->getAsCXXRecordDecl(); + const auto *DerivedClass = + DerivedClassRegion->getSymbol()->getType()->getPointeeCXXRecordDecl(); + if (!BaseClass || !DerivedClass) + return; + + if (!BaseClass->hasDefinition() || !DerivedClass->hasDefinition()) + return; + + if (BaseClass->getDestructor()->isVirtual()) + return; + + if (!DerivedClass->isDerivedFrom(BaseClass)) + return; + + if (!BT) + BT.reset(new BugType(this, + "Destruction of a polymorphic object with no " + "virtual destructor", + "Logic error")); + + ExplodedNode *N = C.generateNonFatalErrorNode(); + auto R = std::make_unique(*BT, BT->getDescription(), N); + + // Mark region of problematic base class for later use in the BugVisitor. + R->markInteresting(BaseClassRegion); + R->addVisitor(std::make_unique()); + C.emitReport(std::move(R)); +} + +PathDiagnosticPieceRef +DeleteWithNonVirtualDtorChecker::DeleteBugVisitor::VisitNode( + const ExplodedNode *N, BugReporterContext &BRC, + PathSensitiveBugReport &BR) { + // Stop traversal after the first conversion was found on a path. + if (Satisfied) + return nullptr; + + const Stmt *S = N->getStmtForDiagnostics(); + if (!S) + return nullptr; + + const auto *CastE = dyn_cast(S); + if (!CastE) + return nullptr; + + // Only interested in DerivedToBase implicit casts. + // Explicit casts can have different CastKinds. + if (const auto *ImplCastE = dyn_cast(CastE)) { + if (ImplCastE->getCastKind() != CK_DerivedToBase) + return nullptr; + } + + // Region associated with the current cast expression. + const MemRegion *M = N->getSVal(CastE).getAsRegion(); + if (!M) + return nullptr; + + // Check if target region was marked as problematic previously. + if (!BR.isInteresting(M)) + return nullptr; + + // Stop traversal on this path. + Satisfied = true; + + SmallString<256> Buf; + llvm::raw_svector_ostream OS(Buf); + OS << "Conversion from derived to base happened here"; + PathDiagnosticLocation Pos(S, BRC.getSourceManager(), + N->getLocationContext()); + return std::make_shared(Pos, OS.str(), true); +} + +void ento::registerDeleteWithNonVirtualDtorChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterDeleteWithNonVirtualDtorChecker( + const LangOptions &LO) { + return true; +} diff --git a/pool/shard007/C++/0095472_vfat.cpp b/pool/shard007/C++/0095472_vfat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ff7074e1736538aaa6ff1a2b9a39ec3af4a9cf6 --- /dev/null +++ b/pool/shard007/C++/0095472_vfat.cpp @@ -0,0 +1,258 @@ +/* + Copyright (C) 2006 yopyop + Copyright (C) 2006 Mic + Copyright (C) 2010-2016 DeSmuME team + + This file is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This file is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the this software. If not, see . +*/ + +#include +#include +#include +#include +#include +#include + +#include "../types.h" +#include "../debug.h" +#include "../emufile.h" +#include "retro_dirent.h" +#include "retro_stat.h" +#include "file/file_path.h" + +#include "emufat.h" +#include "vfat.h" +#include "libfat/libfat_public_api.h" + + +enum EListCallbackArg { + EListCallbackArg_Item, EListCallbackArg_Pop +}; + +typedef void (*ListCallback)(RDIR* rdir, EListCallbackArg); + +// List all files and subdirectories recursively +//TODO: clunky architecture. we've combined the callbacks into one handler. +//we could merge the callback and list_files function, or refactor the callback into one for each enum which receives a unit of work after +//the more detailed recursing logic (caused by libretro-common integration) is handled in the lister +static void list_files(const char *filepath, ListCallback list_callback) +{ + void * hFind; + char *fname; + u32 dwError; + + RDIR* rdir = retro_opendir(filepath); + if(!rdir) return; + if(retro_dirent_error(rdir)) + { + retro_closedir(rdir); + return; + } + + for(;;) + { + if(!retro_readdir(rdir)) + break; + + const char* fname = retro_dirent_get_name(rdir); + list_callback(rdir,EListCallbackArg_Item); + printf("cflash added %s\n",fname); + + if (retro_dirent_is_dir(rdir, fname) && (strcmp(fname, ".")) && strcmp(fname, "..")) + { + std::string subdir = (std::string)filepath + path_default_slash() + fname; + list_files(subdir.c_str(), list_callback); + list_callback(rdir, EListCallbackArg_Pop); + } + } + + retro_closedir(rdir); +} + +enum eCallbackType +{ + eCallbackType_Count, eCallbackType_Build +}; + +static eCallbackType callbackType; + +//for eCallbackType_Count: +static bool count_failed = false; +static u64 dataSectors = 0; + +//recursing related.. really ought to be merged with list_files functionality +static std::string currPath; +static std::stack pathStack; +static std::stack virtPathStack; +static std::string currVirtPath; + +static void DirectoryListCallback(RDIR* rdir, EListCallbackArg arg) +{ + const char* fname = retro_dirent_get_name(rdir); + + if(arg == EListCallbackArg_Pop) + { + currPath = pathStack.top(); + pathStack.pop(); + currVirtPath = virtPathStack.top(); + virtPathStack.pop(); + return; + } + + if(retro_dirent_is_dir(rdir,currVirtPath.c_str())) + { + if(!strcmp(fname,".")) return; + if(!strcmp(fname,"..")) return; + + pathStack.push(currPath); + virtPathStack.push(currVirtPath); + + currVirtPath = currVirtPath + "/" + fname; + + if(callbackType == eCallbackType_Build) + { + bool ok = LIBFAT::MkDir(currVirtPath.c_str()); + + if(!ok) + printf("ERROR adding dir %s via libfat\n",currVirtPath.c_str()); + } + else + { + dataSectors++; //directories take one sector + } + + currPath = currPath + path_default_slash() + fname; + return; + } + else + { + std::string path = currPath + path_default_slash() + fname; + + if(callbackType == eCallbackType_Build) + { + FILE* inf = fopen(path.c_str(),"rb"); + if(inf) + { + fseek(inf,0,SEEK_END); + long len = ftell(inf); + fseek(inf,0,SEEK_SET); + u8 *buf = new u8[len]; + fread(buf,1,len,inf); + fclose(inf); + + std::string path = currVirtPath + "/" + fname; + printf("FAT + (%10.2f KB) %s \n",len/1024.f,path.c_str()); + bool ok = LIBFAT::WriteFile(path.c_str(),buf,len); + if(!ok) + printf("ERROR adding file to fat\n"); + delete[] buf; + } else printf("ERROR opening file for fat\n"); + } + else + { + //allocate sectors for file + int32_t fileSize = path_get_size(path.c_str()); + if(fileSize == -1) { count_failed = true; dataSectors = 0; } + else dataSectors += (fileSize+511)/512 + 1; + } + } + +} + +bool VFAT::build(const char* path, int extra_MB) +{ + dataSectors = 0; + currVirtPath = ""; + currPath = path; + + count_failed = false; + callbackType = eCallbackType_Count; + list_files(path, DirectoryListCallback); + + if(count_failed) + { + printf("FAILED enumerating files for fat\n"); + return false; + } + + dataSectors += 8; //a few for reserved sectors, etc. + + + dataSectors += extra_MB*1024*1024/512; //add extra write space + //dataSectors += 16*1024*1024/512; //add 16MB worth of write space. this is probably enough for anyone, but maybe it should be configurable. + //we could always suggest to users to add a big file to their directory to overwrite (that would cause the image to get padded) + + //this seems to be the minimum size that will turn into a solid fat32 + if(dataSectors<36*1024*1024/512) + dataSectors = 36*1024*1024/512; + + if(dataSectors>=(0x80000000>>9)) + { + printf("error allocating memory for fat (%llu KBytes)\n",(dataSectors*512)/1024); + printf("total fat sizes > 2GB are never going to work\n"); + } + + delete file; + try + { + file = new EMUFILE_MEMORY(dataSectors*512); + } + catch(std::bad_alloc) + { + printf("error allocating memory for fat (%llu KBytes)\n",(dataSectors*512)/1024); + printf("(out of memory)\n"); + return false; + } + + //debug.. + //file = new EMUFILE_FILE("c:\\temp.ima","rb+"); + + //format the disk + { + EmuFat fat(file); + EmuFatVolume vol; + u8 ok = vol.init(&fat); + vol.formatNew(dataSectors); + + //ensure we are working in memory, just in case we were testing with a disk file. + //libfat will need to go straight to memory (for now; we could easily change it to work with the disk) + file = file->memwrap(); + } + EMUFILE_MEMORY* memf = (EMUFILE_MEMORY*)file; + + //setup libfat and write all the files through it + LIBFAT::Init(memf->buf(),memf->size()); + callbackType = eCallbackType_Build; + list_files(path, DirectoryListCallback); + LIBFAT::Shutdown(); + + return true; +} + +VFAT::VFAT() + : file(NULL) +{ +} + +VFAT::~VFAT() +{ + delete file; +} + +EMUFILE* VFAT::detach() +{ + EMUFILE* ret = file; + file = NULL; + return ret; +} diff --git a/pool/shard007/C++/0095481_mpriscontrolplugin.cpp b/pool/shard007/C++/0095481_mpriscontrolplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dba821e8cae1015d2f48040a08e4c88d952a704e --- /dev/null +++ b/pool/shard007/C++/0095481_mpriscontrolplugin.cpp @@ -0,0 +1,211 @@ +/** + * Copyright 2013 Albert Vaca + * + * 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) version 3 or any later version + * accepted by the membership of KDE e.V. (or its successor approved + * by the membership of KDE e.V.), which shall act as a proxy + * defined in Section 14 of version 3 of the 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 + * along with this program. If not, see . + */ + +#include "mpriscontrolplugin.h" + + +#include +#include +#include +#include +#include +#include + +#include +#include +#include "mprisdbusinterface.h" +#include "propertiesdbusinterface.h" + +K_PLUGIN_FACTORY( KdeConnectPluginFactory, registerPlugin< MprisControlPlugin >(); ) +K_EXPORT_PLUGIN( KdeConnectPluginFactory("kdeconnect_mpriscontrol", "kdeconnect-plugins") ) + +MprisControlPlugin::MprisControlPlugin(QObject* parent, const QVariantList& args) + : KdeConnectPlugin(parent, args) +{ + + //Detect new interfaces + connect(QDBusConnection::sessionBus().interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)), + this, SLOT(serviceOwnerChanged(QString,QString,QString))); + + //Add existing interfaces + QStringList interfaces = QDBusConnection::sessionBus().interface()->registeredServiceNames().value(); + Q_FOREACH (const QString& iface, interfaces) { + if (iface.startsWith("org.mpris.MediaPlayer2")) { + addPlayer(iface); + } + } + +} + +void MprisControlPlugin::serviceOwnerChanged(const QString &name, + const QString &oldOwner, + const QString &newOwner) +{ + Q_UNUSED(oldOwner); + + if (name.startsWith("org.mpris.MediaPlayer2")) { + + kDebug(debugArea()) << "Mpris (un)registered in bus" << name << oldOwner << newOwner; + + if (oldOwner.isEmpty()) { + addPlayer(name); + } else if (newOwner.isEmpty()) { + removePlayer(name); + } + } +} + +void MprisControlPlugin::addPlayer(const QString& service) +{ + QDBusInterface mprisInterface(service, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2"); + //FIXME: This call hangs and returns an empty string if KDED is still starting! + const QString identity = mprisInterface.property("Identity").toString(); + playerList[identity] = service; + kDebug(debugArea()) << "Mpris addPlayer" << service << "->" << identity; + sendPlayerList(); + + OrgFreedesktopDBusPropertiesInterface* freedesktopInterface = new OrgFreedesktopDBusPropertiesInterface(service, "/org/mpris/MediaPlayer2", QDBusConnection::sessionBus(), this); + connect(freedesktopInterface, SIGNAL(PropertiesChanged(QString, QVariantMap, QStringList)), this, SLOT(propertiesChanged(QString, QVariantMap))); + +} + +void MprisControlPlugin::propertiesChanged(const QString& propertyInterface, const QVariantMap& properties) +{ + Q_UNUSED(propertyInterface); + + NetworkPackage np(PACKAGE_TYPE_MPRIS); + bool somethingToSend = false; + if (properties.contains("Volume")) { + int volume = (int) (properties["Volume"].toDouble()*100); + if (volume != prevVolume) { + np.set("volume",volume); + prevVolume = volume; + somethingToSend = true; + } + } + if (properties.contains("Metadata")) { + QDBusArgument bullshit = qvariant_cast(properties["Metadata"]); + QVariantMap nowPlayingMap; + bullshit >> nowPlayingMap; + if (nowPlayingMap.contains("xesam:title")) { + QString nowPlaying = nowPlayingMap["xesam:title"].toString(); + if (nowPlayingMap.contains("xesam:artist")) { + nowPlaying = nowPlayingMap["xesam:artist"].toString() + " - " + nowPlaying; + } + np.set("nowPlaying",nowPlaying); + somethingToSend = true; + } + + } + if (properties.contains("PlaybackStatus")) { + bool playing = (properties["PlaybackStatus"].toString() == "Playing"); + np.set("isPlaying", playing); + somethingToSend = true; + } + + if (somethingToSend) { + OrgFreedesktopDBusPropertiesInterface* interface = (OrgFreedesktopDBusPropertiesInterface*)sender(); + const QString& service = interface->service(); + const QString& player = playerList.key(service); + np.set("player", player); + sendPackage(np); + } +} + +void MprisControlPlugin::removePlayer(const QString& ifaceName) +{ + const QString identity = playerList.key(ifaceName); + kDebug(debugArea()) << "Mpris removePlayer" << ifaceName << "->" << identity; + playerList.remove(identity); + sendPlayerList(); +} + +bool MprisControlPlugin::receivePackage (const NetworkPackage& np) +{ + if (np.has("playerList")) { + return false; //Whoever sent this is an mpris client and not an mpris control! + } + + //Send the player list + const QString player = np.get("player"); + bool valid_player = playerList.contains(player); + if (!valid_player || np.get("requestPlayerList")) { + sendPlayerList(); + if (!valid_player) { + return true; + } + } + + //Do something to the mpris interface + OrgMprisMediaPlayer2PlayerInterface mprisInterface(playerList[player], "/org/mpris/MediaPlayer2", QDBusConnection::sessionBus()); + if (np.has("action")) { + const QString& action = np.get("action"); + kDebug(debugArea()) << "Calling action" << action << "in" << playerList[player]; + //TODO: Check for valid actions + mprisInterface.call(action); + } + if (np.has("setVolume")) { + double volume = np.get("setVolume")/100.f; + kDebug(debugArea()) << "Setting volume" << volume << "to" << playerList[player]; + mprisInterface.setVolume(volume); + } + if (np.has("Seek")) { + int offset = np.get("Seek"); + kDebug(debugArea()) << "Seeking" << offset << "to" << playerList[player]; + mprisInterface.Seek(offset); + } + + //Send something read from the mpris interface + NetworkPackage answer(PACKAGE_TYPE_MPRIS); + bool somethingToSend = false; + if (np.get("requestNowPlaying")) { + + QVariantMap nowPlayingMap = mprisInterface.metadata(); + QString nowPlaying = nowPlayingMap["xesam:title"].toString(); + if (nowPlayingMap.contains("xesam:artist")) { + nowPlaying = nowPlayingMap["xesam:artist"].toString() + " - " + nowPlaying; + } + + answer.set("nowPlaying",nowPlaying); + + bool playing = (mprisInterface.playbackStatus() == QLatin1String("Playing")); + answer.set("isPlaying", playing); + + somethingToSend = true; + } + if (np.get("requestVolume")) { + int volume = (int)(mprisInterface.volume() * 100); + answer.set("volume",volume); + somethingToSend = true; + } + if (somethingToSend) { + answer.set("player", player); + sendPackage(answer); + } + + return true; +} + +void MprisControlPlugin::sendPlayerList() +{ + NetworkPackage np(PACKAGE_TYPE_MPRIS); + np.set("playerList",playerList.keys()); + sendPackage(np); +} diff --git a/pool/shard007/C++/0095485_TextCodecUTF8Test.cpp b/pool/shard007/C++/0095485_TextCodecUTF8Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b59d2fb6b43619814613ea84c08669823b536c9c --- /dev/null +++ b/pool/shard007/C++/0095485_TextCodecUTF8Test.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2013 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +#include "sky/engine/wtf/text/TextCodecUTF8.h" + +#include +#include "sky/engine/wtf/OwnPtr.h" +#include "sky/engine/wtf/text/TextCodec.h" +#include "sky/engine/wtf/text/TextEncoding.h" +#include "sky/engine/wtf/text/TextEncodingRegistry.h" +#include "sky/engine/wtf/text/WTFString.h" + +namespace WTF { + +namespace { + +TEST(TextCodecUTF8, DecodeAscii) +{ + TextEncoding encoding("UTF-8"); + OwnPtr codec(newTextCodec(encoding)); + + const char testCase[] = "HelloWorld"; + size_t testCaseSize = sizeof(testCase) - 1; + + bool sawError = false; + const String& result = codec->decode(testCase, testCaseSize, DataEOF, false, sawError); + EXPECT_FALSE(sawError); + ASSERT_EQ(testCaseSize, result.length()); + for (size_t i = 0; i < testCaseSize; ++i) { + EXPECT_EQ(testCase[i], result[i]); + } +} + +TEST(TextCodecUTF8, DecodeChineseCharacters) +{ + TextEncoding encoding("UTF-8"); + OwnPtr codec(newTextCodec(encoding)); + + // "Kanji" in Chinese characters. + const char testCase[] = "\xe6\xbc\xa2\xe5\xad\x97"; + size_t testCaseSize = sizeof(testCase) - 1; + + bool sawError = false; + const String& result = codec->decode(testCase, testCaseSize, DataEOF, false, sawError); + EXPECT_FALSE(sawError); + ASSERT_EQ(2u, result.length()); + EXPECT_EQ(0x6f22U, result[0]); + EXPECT_EQ(0x5b57U, result[1]); +} + +TEST(TextCodecUTF8, Decode0xFF) +{ + TextEncoding encoding("UTF-8"); + OwnPtr codec(newTextCodec(encoding)); + + bool sawError = false; + const String& result = codec->decode("\xff", 1, DataEOF, false, sawError); + EXPECT_TRUE(sawError); + ASSERT_EQ(1u, result.length()); + EXPECT_EQ(0xFFFDU, result[0]); +} + +} // namespace + +} // namespace WTF diff --git a/pool/shard007/C++/0095489_ZipCipher.cpp b/pool/shard007/C++/0095489_ZipCipher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47e2e712e569be0b0badf3af56d21f8bc55504dc --- /dev/null +++ b/pool/shard007/C++/0095489_ZipCipher.cpp @@ -0,0 +1,106 @@ +// Crypto/ZipCipher.h + +#include "StdAfx.h" + +#include "ZipCipher.h" +#include "Windows/Defs.h" + +#include "../../Common/StreamUtils.h" + +namespace NCrypto { +namespace NZip { + +/* +const int kBufferSize = 1 << 17; + +CBuffer2::CBuffer2(): + _buffer(0) +{ + _buffer = new Byte[kBufferSize]; +} + +CBuffer2::~CBuffer2() +{ + delete []_buffer; +} +*/ + +STDMETHODIMP CEncoder::CryptoSetPassword(const Byte *data, UInt32 size) +{ + _cipher.SetPassword(data, size); + return S_OK; +} + +STDMETHODIMP CEncoder::CryptoSetCRC(UInt32 crc) +{ + _crc = crc; + return S_OK; +} + +STDMETHODIMP CEncoder::Init() +{ + return S_OK; +} + +HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) +{ + CRandom random; + random.Init(::GetTickCount()); + + UInt64 nowPos = 0; + Byte header[kHeaderSize]; + for (int i = 0; i < kHeaderSize - 2; i++) + { + header[i] = Byte(random.Generate()); + } + header[kHeaderSize - 1] = Byte(_crc >> 24); + header[kHeaderSize - 2] = Byte(_crc >> 16); + + UInt32 processedSize; + _cipher.EncryptHeader(header); + RINOK(WriteStream(outStream, header, kHeaderSize, &processedSize)); + if (processedSize != kHeaderSize) + return E_FAIL; + return S_OK; +} + +STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) +{ + UInt32 i; + for (i = 0; i < size; i++) + data[i] = _cipher.EncryptByte(data[i]); + return i; +} + +STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) +{ + _cipher.SetPassword(data, size); + return S_OK; +} + +HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) +{ + UInt64 nowPos = 0; + Byte header[kHeaderSize]; + UInt32 processedSize; + RINOK(ReadStream(inStream, header, kHeaderSize, &processedSize)); + if (processedSize != kHeaderSize) + return E_FAIL; + _cipher.DecryptHeader(header); + return S_OK; +} + +STDMETHODIMP CDecoder::Init() +{ + return S_OK; +} + +STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) +{ + UInt32 i; + for (i = 0; i < size; i++) + data[i] = _cipher.DecryptByte(data[i]); + return i; +} + +}} diff --git a/pool/shard007/C++/0095494_BugDriver.cpp b/pool/shard007/C++/0095494_BugDriver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030749fa9ea08f163b7fa7ea831e9630e6498d9a --- /dev/null +++ b/pool/shard007/C++/0095494_BugDriver.cpp @@ -0,0 +1,248 @@ +//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This class contains all of the shared state and information that is used by +// the BugPoint tool to track down errors in optimizations. This class is the +// main driver class that invokes all sub-functionality. +// +//===----------------------------------------------------------------------===// + +#include "BugDriver.h" +#include "ToolRunner.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Verifier.h" +#include "llvm/IRReader/IRReader.h" +#include "llvm/Linker/Linker.h" +#include "llvm/Pass.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/FileUtilities.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/SourceMgr.h" +#include "llvm/Support/raw_ostream.h" +#include +using namespace llvm; + +namespace llvm { + Triple TargetTriple; +} + +// Anonymous namespace to define command line options for debugging. +// +namespace { + // Output - The user can specify a file containing the expected output of the + // program. If this filename is set, it is used as the reference diff source, + // otherwise the raw input run through an interpreter is used as the reference + // source. + // + cl::opt + OutputFile("output", cl::desc("Specify a reference program output " + "(for miscompilation detection)")); +} + +/// setNewProgram - If we reduce or update the program somehow, call this method +/// to update bugdriver with it. This deletes the old module and sets the +/// specified one as the current program. +void BugDriver::setNewProgram(Module *M) { + delete Program; + Program = M; +} + + +/// getPassesString - Turn a list of passes into a string which indicates the +/// command line options that must be passed to add the passes. +/// +std::string llvm::getPassesString(const std::vector &Passes) { + std::string Result; + for (unsigned i = 0, e = Passes.size(); i != e; ++i) { + if (i) Result += " "; + Result += "-"; + Result += Passes[i]; + } + return Result; +} + +BugDriver::BugDriver(const char *toolname, bool find_bugs, + unsigned timeout, unsigned memlimit, bool use_valgrind, + LLVMContext& ctxt) + : Context(ctxt), ToolName(toolname), ReferenceOutputFile(OutputFile), + Program(nullptr), Interpreter(nullptr), SafeInterpreter(nullptr), + cc(nullptr), run_find_bugs(find_bugs), Timeout(timeout), + MemoryLimit(memlimit), UseValgrind(use_valgrind) {} + +BugDriver::~BugDriver() { + delete Program; + if (Interpreter != SafeInterpreter) + delete Interpreter; + delete SafeInterpreter; + delete cc; +} + +std::unique_ptr llvm::parseInputFile(StringRef Filename, + LLVMContext &Ctxt) { + SMDiagnostic Err; + std::unique_ptr Result = parseIRFile(Filename, Err, Ctxt); + if (!Result) { + Err.print("bugpoint", errs()); + return Result; + } + + if (verifyModule(*Result, &errs())) { + errs() << "bugpoint: " << Filename << ": error: input module is broken!\n"; + return std::unique_ptr(); + } + + // If we don't have an override triple, use the first one to configure + // bugpoint, or use the host triple if none provided. + if (TargetTriple.getTriple().empty()) { + Triple TheTriple(Result->getTargetTriple()); + + if (TheTriple.getTriple().empty()) + TheTriple.setTriple(sys::getDefaultTargetTriple()); + + TargetTriple.setTriple(TheTriple.getTriple()); + } + + Result->setTargetTriple(TargetTriple.getTriple()); // override the triple + return Result; +} + +// This method takes the specified list of LLVM input files, attempts to load +// them, either as assembly or bitcode, then link them together. It returns +// true on failure (if, for example, an input bitcode file could not be +// parsed), and false on success. +// +bool BugDriver::addSources(const std::vector &Filenames) { + assert(!Program && "Cannot call addSources multiple times!"); + assert(!Filenames.empty() && "Must specify at least on input filename!"); + + // Load the first input file. + Program = parseInputFile(Filenames[0], Context).release(); + if (!Program) return true; + + outs() << "Read input file : '" << Filenames[0] << "'\n"; + + for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { + std::unique_ptr M = parseInputFile(Filenames[i], Context); + if (!M.get()) return true; + + outs() << "Linking in input file: '" << Filenames[i] << "'\n"; + if (Linker::linkModules(*Program, std::move(M))) + return true; + } + + outs() << "*** All input ok\n"; + + // All input files read successfully! + return false; +} + + + +/// run - The top level method that is invoked after all of the instance +/// variables are set up from command line arguments. +/// +bool BugDriver::run(std::string &ErrMsg) { + if (run_find_bugs) { + // Rearrange the passes and apply them to the program. Repeat this process + // until the user kills the program or we find a bug. + return runManyPasses(PassesToRun, ErrMsg); + } + + // If we're not running as a child, the first thing that we must do is + // determine what the problem is. Does the optimization series crash the + // compiler, or does it produce illegal code? We make the top-level + // decision by trying to run all of the passes on the input program, + // which should generate a bitcode file. If it does generate a bitcode + // file, then we know the compiler didn't crash, so try to diagnose a + // miscompilation. + if (!PassesToRun.empty()) { + outs() << "Running selected passes on program to test for crash: "; + if (runPasses(Program, PassesToRun)) + return debugOptimizerCrash(); + } + + // Set up the execution environment, selecting a method to run LLVM bitcode. + if (initializeExecutionEnvironment()) return true; + + // Test to see if we have a code generator crash. + outs() << "Running the code generator to test for a crash: "; + std::string Error; + compileProgram(Program, &Error); + if (!Error.empty()) { + outs() << Error; + return debugCodeGeneratorCrash(ErrMsg); + } + outs() << '\n'; + + // Run the raw input to see where we are coming from. If a reference output + // was specified, make sure that the raw output matches it. If not, it's a + // problem in the front-end or the code generator. + // + bool CreatedOutput = false; + if (ReferenceOutputFile.empty()) { + outs() << "Generating reference output from raw program: "; + if (!createReferenceFile(Program)) { + return debugCodeGeneratorCrash(ErrMsg); + } + CreatedOutput = true; + } + + // Make sure the reference output file gets deleted on exit from this + // function, if appropriate. + std::string ROF(ReferenceOutputFile); + FileRemover RemoverInstance(ROF, CreatedOutput && !SaveTemps); + + // Diff the output of the raw program against the reference output. If it + // matches, then we assume there is a miscompilation bug and try to + // diagnose it. + outs() << "*** Checking the code generator...\n"; + bool Diff = diffProgram(Program, "", "", false, &Error); + if (!Error.empty()) { + errs() << Error; + return debugCodeGeneratorCrash(ErrMsg); + } + if (!Diff) { + outs() << "\n*** Output matches: Debugging miscompilation!\n"; + debugMiscompilation(&Error); + if (!Error.empty()) { + errs() << Error; + return debugCodeGeneratorCrash(ErrMsg); + } + return false; + } + + outs() << "\n*** Input program does not match reference diff!\n"; + outs() << "Debugging code generator problem!\n"; + bool Failure = debugCodeGenerator(&Error); + if (!Error.empty()) { + errs() << Error; + return debugCodeGeneratorCrash(ErrMsg); + } + return Failure; +} + +void llvm::PrintFunctionList(const std::vector &Funcs) { + unsigned NumPrint = Funcs.size(); + if (NumPrint > 10) NumPrint = 10; + for (unsigned i = 0; i != NumPrint; ++i) + outs() << " " << Funcs[i]->getName(); + if (NumPrint < Funcs.size()) + outs() << "... <" << Funcs.size() << " total>"; + outs().flush(); +} + +void llvm::PrintGlobalVariableList(const std::vector &GVs) { + unsigned NumPrint = GVs.size(); + if (NumPrint > 10) NumPrint = 10; + for (unsigned i = 0; i != NumPrint; ++i) + outs() << " " << GVs[i]->getName(); + if (NumPrint < GVs.size()) + outs() << "... <" << GVs.size() << " total>"; + outs().flush(); +} diff --git a/pool/shard007/C++/0095501_checkqueue.cpp b/pool/shard007/C++/0095501_checkqueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5f96a0136ed911c1c5f89fc50a3965765a30312 --- /dev/null +++ b/pool/shard007/C++/0095501_checkqueue.cpp @@ -0,0 +1,61 @@ +// 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 +#include +#include +#include +#include +#include + + +static const int MIN_CORES = 2; +static const size_t BATCHES = 101; +static const size_t BATCH_SIZE = 30; +static const int PREVECTOR_SIZE = 28; +static const unsigned int QUEUE_BATCH_SIZE = 128; + +// This Benchmark tests the CheckQueue with a slightly realistic workload, +// where checks all contain a prevector that is indirect 50% of the time +// and there is a little bit of work done between calls to Add. +static void CCheckQueueSpeedPrevectorJob(benchmark::State& state) +{ + struct PrevectorJob { + prevector p; + PrevectorJob(){ + } + explicit PrevectorJob(FastRandomContext& insecure_rand){ + p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2)); + } + bool operator()() + { + return true; + } + void swap(PrevectorJob& x){p.swap(x.p);}; + }; + CCheckQueue queue {QUEUE_BATCH_SIZE}; + boost::thread_group tg; + for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) { + tg.create_thread([&]{queue.Thread();}); + } + while (state.KeepRunning()) { + // Make insecure_rand here so that each iteration is identical. + FastRandomContext insecure_rand(true); + CCheckQueueControl control(&queue); + std::vector> vBatches(BATCHES); + for (auto& vChecks : vBatches) { + vChecks.reserve(BATCH_SIZE); + for (size_t x = 0; x < BATCH_SIZE; ++x) + vChecks.emplace_back(insecure_rand); + control.Add(vChecks); + } + // control waits for completion by RAII, but + // it is done explicitly here for clarity + control.Wait(); + } + tg.interrupt_all(); + tg.join_all(); +} +BENCHMARK(CCheckQueueSpeedPrevectorJob, 1400); diff --git a/pool/shard007/C++/0095507_CrossSectionRenderer.cpp b/pool/shard007/C++/0095507_CrossSectionRenderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..019d5ae1e46fc2acd54b267580d68e709fed64a9 --- /dev/null +++ b/pool/shard007/C++/0095507_CrossSectionRenderer.cpp @@ -0,0 +1,175 @@ +/* + Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2013 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "CrossSectionRenderer.hpp" +#include "Renderer/ChartRenderer.hpp" +#include "Renderer/GradientRenderer.hpp" +#include "Screen/Canvas.hpp" +#include "Look/CrossSectionLook.hpp" +#include "Terrain/RasterTerrain.hpp" +#include "Units/Units.hpp" +#include "NMEA/Aircraft.hpp" +#include "Navigation/Aircraft.hpp" +#include "Engine/GlideSolvers/GlideState.hpp" +#include "Engine/GlideSolvers/MacCready.hpp" + +CrossSectionRenderer::CrossSectionRenderer(const CrossSectionLook &_look, + const AirspaceLook &_airspace_look, + const ChartLook &_chart_look) + :look(_look), chart_look(_chart_look), airspace_renderer(_airspace_look), + terrain_renderer(look), terrain(NULL), airspace_database(NULL), + start(GeoPoint::Invalid()), + vec(fixed(50000), Angle::Zero()) {} + +void +CrossSectionRenderer::ReadBlackboard(const MoreData &_gps_info, + const DerivedInfo &_calculated_info, + const GlideSettings &_glide_settings, + const GlidePolar &_glide_polar, + const AirspaceRendererSettings &ar_settings) +{ + gps_info = _gps_info; + calculated_info = _calculated_info; + glide_settings = _glide_settings; + glide_polar = _glide_polar; + airspace_renderer.SetSettings(ar_settings); +} + +void +CrossSectionRenderer::Paint(Canvas &canvas, const PixelRect rc) const +{ + DrawVerticalGradient(canvas, rc, + look.sky_color, look.background_color, + look.background_color); + + canvas.SetTextColor(look.text_color); + canvas.Select(*look.grid_font); + + ChartRenderer chart(chart_look, canvas, rc); + + if (!vec.IsValid() || !start.IsValid()) { + chart.DrawNoData(); + return; + } + + const fixed nav_altitude = gps_info.NavAltitudeAvailable() + ? gps_info.nav_altitude + : fixed(0); + fixed hmin = std::max(fixed(0), nav_altitude - fixed(3300)); + fixed hmax = std::max(fixed(3300), nav_altitude + fixed(1000)); + + chart.ResetScale(); + chart.ScaleXFromValue(fixed(0)); + chart.ScaleXFromValue(vec.distance); + chart.ScaleYFromValue(hmin); + chart.ScaleYFromValue(hmax); + + short elevations[NUM_SLICES]; + UpdateTerrain(elevations); + + if (airspace_database != nullptr) { + const AircraftState aircraft = ToAircraftState(Basic(), Calculated()); + airspace_renderer.Draw(canvas, chart, *airspace_database, start, vec, + aircraft); + } + + terrain_renderer.Draw(canvas, chart, elevations); + PaintGlide(chart); + PaintAircraft(canvas, chart, rc); + PaintGrid(canvas, chart); +} + +void +CrossSectionRenderer::UpdateTerrain(short *elevations) const +{ + if (terrain == NULL) { + const auto invalid = RasterBuffer::TERRAIN_INVALID; + std::fill_n(elevations, NUM_SLICES, invalid); + return; + } + + const GeoPoint point_diff = vec.EndPoint(start) - start; + + RasterTerrain::Lease map(*terrain); + for (unsigned i = 0; i < NUM_SLICES; ++i) { + const fixed slice_distance_factor = fixed(i) / (NUM_SLICES - 1); + const GeoPoint slice_point = start + point_diff * slice_distance_factor; + + elevations[i] = map->GetHeight(slice_point); + } +} + +void +CrossSectionRenderer::PaintGlide(ChartRenderer &chart) const +{ + if (!gps_info.NavAltitudeAvailable() || !glide_polar.IsValid()) + return; + + const fixed altitude = gps_info.nav_altitude; + + const MacCready mc(glide_settings, glide_polar); + const GlideState task(vec, fixed(0), altitude, + calculated_info.GetWindOrZero()); + const GlideResult result = mc.SolveStraight(task); + if (!result.IsOk()) + return; + + chart.DrawLine(fixed(0), altitude, result.vector.distance, + result.GetArrivalAltitude(), + ChartLook::STYLE_BLUETHIN); +} + +void +CrossSectionRenderer::PaintAircraft(Canvas &canvas, const ChartRenderer &chart, + const PixelRect rc) const +{ + if (!gps_info.NavAltitudeAvailable()) + return; + + canvas.Select(look.aircraft_brush); + canvas.SelectNullPen(); + + RasterPoint line[4]; + line[0] = chart.ToScreen(fixed(0), gps_info.nav_altitude); + line[1].x = rc.left; + line[1].y = line[0].y; + line[2].x = line[1].x; + line[2].y = line[0].y - (line[0].x - line[1].x) / 2; + line[3].x = (line[1].x + line[0].x) / 2; + line[3].y = line[0].y; + canvas.DrawTriangleFan(line, 4); +} + +void +CrossSectionRenderer::PaintGrid(Canvas &canvas, ChartRenderer &chart) const +{ + canvas.SetTextColor(look.text_color); + + chart.DrawXGrid(Units::ToSysDistance(fixed(5)), + look.grid_pen, fixed(5), true); + chart.DrawYGrid(Units::ToSysAltitude(fixed(1000)), + look.grid_pen, fixed(1000), true); + + chart.DrawXLabel(_T("D"), Units::GetDistanceName()); + chart.DrawYLabel(_T("h"), Units::GetAltitudeName()); +} diff --git a/pool/shard007/C++/0095508_pthread_util_test.cpp b/pool/shard007/C++/0095508_pthread_util_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd41ac8bbe42e1dc2bad58cf879c340639995119 --- /dev/null +++ b/pool/shard007/C++/0095508_pthread_util_test.cpp @@ -0,0 +1,76 @@ +#include +#include +#include "pthread_util_test.h" + +CPPUNIT_TEST_SUITE_REGISTRATION(PthreadUtilTest); + +void +PthreadUtilTest::setUp() +{ +} + +void +PthreadUtilTest::tearDown() +{ +} + +struct TestThread { + TestThread(LockWrappedQueue *q_, bool rdr) : q(q_), reader(rdr) {} + void start(); + void Run(); + void join(); + + LockWrappedQueue *q; + bool reader; + pthread_t tid; +}; + +static void *Runner(struct TestThread *thread) +{ + thread->Run(); + return NULL; +} + +void TestThread::start() +{ + (void)pthread_create(&tid, NULL, (void*(*)(void*))&Runner, this); +} + +void TestThread::Run() +{ + if (reader) { + int last = 0; + while (last != 7) { + int next; + q->pop(next); + CPPUNIT_ASSERT(next == (last + 1)); + last = next; + } + } else { + for (int i = 1; i <= 7; ++i) { + q->push(i); + + // sleep a bit; make the reader wait + struct timeval to = {1, 0}; + (void)select(0, NULL, NULL, NULL, &to); + } + } +} + +void TestThread::join() +{ + (void)pthread_join(tid, NULL); +} + +void +PthreadUtilTest::testQueue() +{ + LockWrappedQueue q; + TestThread reader(&q, true); + TestThread writer(&q, false); + reader.start(); + sleep(1); + writer.start(); + writer.join(); + reader.join(); +} diff --git a/pool/shard007/C++/0095510_uploadfile.cpp b/pool/shard007/C++/0095510_uploadfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e4711d1786ed3f30eeb84c4a6d533c8855d0432 --- /dev/null +++ b/pool/shard007/C++/0095510_uploadfile.cpp @@ -0,0 +1,133 @@ +/* + * Copyright 2014 Canonical Ltd. + * + * 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; version 3. + * + * 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 . + * + * Authors: + * Roberto Mier + * Tiago Herrmann + */ + +#include "uploadfile.h" + +#include + +UploadFile::UploadFile(Session *session, CryptoUtils *crypto, UploadFile::FileType fileType, const QByteArray &buffer, QObject *parent) : + File(session, buffer.size(), parent), + mCrypto(crypto), + mFileType(fileType), + mRelatedFileId(0), + mName(""), + mBytes(buffer), + mFilePath(""), + mNParts(0), + mCurrentPart(0), + mUploadedParts(0), + mKrypt(QCryptographicHash::Md5) +{ + calculatePartsCount(); +} + +UploadFile::UploadFile(Session *session, CryptoUtils *crypto, UploadFile::FileType fileType, const QString &filePath, QObject *parent) : + File(session, QFileInfo(filePath).size(), parent), + mCrypto(crypto), + mFileType(fileType), + mRelatedFileId(0), + mName(QFileInfo(filePath).fileName()), + mFilePath(filePath), + mNParts(0), + mCurrentPart(0), + mUploadedParts(0), + mIODevice(filePath), + mKrypt(QCryptographicHash::Md5) +{ + openIODevice(); + calculatePartsCount(); +} + +UploadFile::~UploadFile() { +} + +void UploadFile::openIODevice() { + if (mIODevice.open(QIODevice::ReadOnly)) { + // get file size with file open + mLength = mIODevice.size(); + } else { + Q_EMIT fileNotFound(); + } +} + +bool UploadFile::hasMoreParts() const { + return mCurrentPart < mNParts; +} + +QByteArray UploadFile::nextPart() { + QByteArray partBytes(mPartLength, Qt::Uninitialized); + + //let's see if the file content is loaded or a filepath is set + if (!mBytes.isEmpty()) { + qint32 k = 0; + if (mCurrentPart < mNParts -1) { + // if not the last part + qint32 n = (mCurrentPart + 1) * mPartLength; + for (qint32 j = (mCurrentPart * mPartLength); j < n; j++) { + partBytes[k++] = mBytes[j]; + } + } else { + // if last part + qint32 lastPartSize = mLength % mPartLength; + // if not the last part + qint32 n = (mCurrentPart * mPartLength) + lastPartSize; + for (qint32 j = (mCurrentPart * mPartLength); j < n; j++) { + partBytes[k++] = mBytes[j]; + } + } + } else { + // in this case we're reading an open file from a local path + if (mIODevice.isOpen()) { + mIODevice.seek(mCurrentPart * mPartLength); //set offset + partBytes = mIODevice.read(mPartLength); + if (!hasMoreParts()) { + mIODevice.close(); + } + } else { + Q_EMIT fileNotOpen(); + } + } + mCurrentPart++; + + QByteArray processedBytes; + if (mEncrypted) { + processedBytes = mCrypto->encryptFilePart(partBytes, mKey, mIv); + } else { + processedBytes = partBytes; + } + + // add the new data to cryptographic hash before return it + mKrypt.addData(processedBytes, processedBytes.length()); + return processedBytes; +} + +void UploadFile::increaseUploadedParts() { + mUploadedParts++; +} + +QByteArray UploadFile::md5() { + return mKrypt.result(); +} + +void UploadFile::calculatePartsCount() { + // calculate number of parts to be uploaded + mNParts = mLength / mPartLength; + if (mNParts * mPartLength < mLength) mNParts++; +} diff --git a/pool/shard007/C++/0095511_EllysTwinLetters.cc b/pool/shard007/C++/0095511_EllysTwinLetters.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5093db4bfd86380314ec20903147f8e34fe8433 --- /dev/null +++ b/pool/shard007/C++/0095511_EllysTwinLetters.cc @@ -0,0 +1,188 @@ +/* ======================================== + + ID: mathema6 + TASK: + LANG: C++14 + + * File Name : + * Creation Date : + * Last Modified : + * Created By : Karel Ha + * URL : + * Points/Time : 303.09 (~26m) :-/ + * Total/ETA : 500 + * Status : AC !!! (passed all 107 testcases) + ==========================================*/ + +#include +#define PROBLEMNAME "TASK_PLACEHOLDER_FOR_VIM" + +#include + +using namespace std; + +#define REP(i,n) for(int i=0;i<(n);i++) +#define FOR(i,a,b) for(int i=(a);i<=(b);i++) +#define FORD(i,a,b) for(int i=(a);i>=(b);i--) +#define ALL(A) (A).begin(), (A).end() +#define REVALL(A) (A).rbegin(), (A).rend() +#define F first +#define S second +#define PB push_back +#define MP make_pair +#define MTP make_tuple +#define MINUPDATE(A,B) A = min((A), (B)); +#define MAXUPDATE(A,B) A = max((A), (B)); +#define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0) +#define CONTAINS(S,E) ((S).find(E) != (S).end()) +#define SZ(x) ((int) (x).size()) + +using ll = long long; +using ul = unsigned long long; +using llll = pair; +using ulul = pair; + +#ifdef ONLINE_JUDGE + #undef MATHEMAGE_DEBUG +#endif + +#ifdef MATHEMAGE_DEBUG + #define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl; + #define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n"; (print_vector_vector(cerr, (v))) << endl; + #define MSG_VEC_PAIRS(v) print_vector_pairs((v), (#v)); + #define LINESEP1 cerr << "----------------------------------------------- " << endl; + #define LINESEP2 cerr << "_________________________________________________________________" << endl; + + #define MSG_VEC(v) cerr << "> " << (#v) << ": "; (print_vector(cerr, (v))) << endl; + #define MSG_VEC_STR(v) cerr << "> " << (#v) << ": "; (print_vector_string(cerr, (v))) << endl; +#else + #define MSG(a) + #define MSG_VEC_VEC(v) + #define MSG_VEC_PAIRS(v) + #define LINESEP1 + #define LINESEP2 + + #define MSG_VEC(v) + #define MSG_VEC_STR(v) +#endif + +inline ostream& print_vector_string(ostream& os, const vector & vec) { + os << endl; + for (const auto & s: vec) cerr << s << endl; + return os; +} + +template +inline ostream& print_vector(ostream& os, const vector & vec) { + for (const auto & x: vec) os << x << " "; + return os; +} + +template +inline ostream& print_vector_vector(ostream& os, const vector> & vec) { + for (const auto & line: vec) { + for (const auto & it: line) { + os << it << " "; + } + os << endl; + } + return os; +} + +// template +// ostream& operator<<(ostream& os, const set& vec) { +// os << "{ | "; +// for (const auto & x: vec) os << x << "| "; +// os << "}"; +// return os; +// } +// +// template +// ostream& operator<<(ostream& os, const multiset& vec) { +// os << "{ | "; +// for (const auto & x: vec) os << x << "| "; +// os << "}"; +// return os; +// } +// +// template +// void print_vector_pairs(const vector> & vec, const string & name) { +// cerr << "> " << name << ": "; +// for (const auto & x: vec) cerr << "(" << x.F << ", " << x.S << ")\t"; +// cerr << endl; +// } + +template +inline bool bounded(const T & x, const T & u, const T & l=0) { + return min(l,u)<=x && x DX4 = { 0, 0, -1, 1}; +const vector DY4 = {-1, 1, 0, 0}; +const vector> DXY4 = { {0,-1}, {0,1}, {-1,0}, {1,0} }; +const vector DX8 = {-1, -1, -1, 0, 0, 1, 1, 1}; +const vector DY8 = {-1, 0, 1, -1, 1, -1, 0, 1}; +const vector> DXY8 = { + {-1,-1}, {-1,0}, {-1,1}, + { 0,-1}, { 0,1}, + { 1,-1}, { 1,0}, { 1,1} +}; + +class EllysTwinLetters { +public: + int getMin(string S) { + LINESEP2; + + int nRows=1+SZ(S); + int nCols=26; + vector> singles(nRows, vector(nCols)); + vector> twins(nRows, vector(nCols)); + + int cost, prevRowMin=0; + FOR(r,1,nRows-1) { + REP(c,nCols) { + cost=abs(int(S[r-1]-'A') - c); + + if (r>=2) { + twins[r][c] = singles[r-1][c]; + if (r-1>=2) { + MINUPDATE(twins[r][c], twins[r-1][c]); + } + twins[r][c]+=cost; + } + + singles[r][c] = singles[r-1][c]; + if (r-1>=2) { + MINUPDATE(singles[r][c], prevRowMin); + } + singles[r][c]+=cost; + } + + prevRowMin=*min_element(ALL(twins[r])); + MSG(prevRowMin); + } + MSG_VEC_VEC(singles); + MSG_VEC_VEC(twins); + + return prevRowMin; + } +}; + +/* +Remember: + +1) (RE-)COMPILE LAST VERSION BEFORE SUBMITTING!!!!! +2) CHECK ADDITIONALLY IN THE ROOM SUMMARY (whether CORRECT source code was submitted)!!!! + - Or `vimdiff solutionName*` should produce no diffs! +3) Never submit brute-force/inferior solution when it might be too slow!! + - Or always re-compile again! +*/ diff --git a/pool/shard007/C++/0095512_volume.cc b/pool/shard007/C++/0095512_volume.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c637c9735f1a7cbf954a6460a5b9d4933c94945 --- /dev/null +++ b/pool/shard007/C++/0095512_volume.cc @@ -0,0 +1,37 @@ +#include "volume.h" +#include + +namespace volume +{ + std::map settings_t::create () + { + std::map res; + if(CFPropertyListRef cfPlist = CFPreferencesCopyAppValue(CFSTR("volumeSettings"), kCFPreferencesCurrentApplication)) + { + citerate(pair, plist::convert(cfPlist)) + { + settings_t info; + plist::get_key_path(pair->second, "extendedAttributes", info._extended_attributes); + plist::get_key_path(pair->second, "scmBadges", info._scm_badges); + plist::get_key_path(pair->second, "displayNames", info._display_names); + res.emplace(pair->first, info); + } + CFRelease(cfPlist); + } + return res; + } + + volume::settings_t const& settings (std::string const& path) + { + static std::map userSettings = settings_t::create(); + iterate(pair, userSettings) + { + if(path.find(pair->first) == 0) + return pair->second; + } + + static volume::settings_t defaultSettings; + return defaultSettings; + } + +} /* volume */ diff --git a/pool/shard007/C++/0095515_nckDemo_Animation.cpp b/pool/shard007/C++/0095515_nckDemo_Animation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..365a69026075578a1ac7c9a8346ca30693af2896 --- /dev/null +++ b/pool/shard007/C++/0095515_nckDemo_Animation.cpp @@ -0,0 +1,75 @@ + +/** +* NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license. +* https://github.com/nczeroshift/nctoolkit +*/ + +#include "nckDemo_Animation.h" + +Demo_Animation::Demo_Animation(Core::Window * wnd, Graph::Device * dev){ + this->dev = dev; + this->wnd = wnd; + time = 0; +} + +Demo_Animation::~Demo_Animation(){ +} + +void Demo_Animation::Load(){ + // Enable z test + dev->Enable(Graph::STATE_DEPTH_TEST); + + // Set correct states for alpha blending. + dev->Enable(Graph::STATE_BLEND); + dev->BlendFunc(Graph::BLEND_SRC_ALPHA, Graph::BLEND_INV_SRC_ALPHA); + +} + +void Demo_Animation::Render(float dt){ + // Clear graphics rendering buffer. + dev->Clear(); + + // Define the rendering area in window space. + dev->Viewport(0,0,wnd->GetWidth(),wnd->GetHeight()); + + // Set projection matrix. + dev->MatrixMode(Graph::MATRIX_PROJECTION); + dev->Identity(); + + dev->Ortho2D(wnd->GetWidth(),wnd->GetHeight()); + + // Set the view (camera) matrix. + dev->MatrixMode(Graph::MATRIX_VIEW); + dev->Identity(); + + + // Set the model matrix. + dev->MatrixMode(Graph::MATRIX_MODEL); + dev->Identity(); + + + time += dt; + + // Finish rendering and present the graphics. + dev->PresentAll(); +} + +void Demo_Animation::UpdateWndEvents(){ + +} + +std::vector Demo_Animation::GetKeywords() { + std::vector ret; + ret.push_back("TODO"); + //ret.push_back("Basic"); + //ret.push_back("Animation"); + return ret; +} + +std::string Demo_Animation::GetDescription() { + return "Objects Animation"; +} + +Demo * CreateDemo_Animation(Core::Window * wnd, Graph::Device * dev){ + return new Demo_Animation(wnd,dev); +} diff --git a/pool/shard007/C++/0095520_Installer.cpp b/pool/shard007/C++/0095520_Installer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb93206f82a8bc8af9b625ec3a6564ea63806bd8 --- /dev/null +++ b/pool/shard007/C++/0095520_Installer.cpp @@ -0,0 +1,141 @@ +// SvcInstaller.cpp : DLL ƒAƒvƒŠƒP[ƒVƒ‡ƒ“—p‚ɃGƒNƒXƒ|[ƒg‚³‚ê‚éŠÖ”‚ð’è‹`‚µ‚Ü‚·B +// + +#include "stdafx.h" +#include "Installer.hpp" +#include +#include + +static std::string GetErrorMessageA() { + char* lpMessageBuffer = nullptr; + const DWORD code = GetLastError(); + const DWORD length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, LANG_USER_DEFAULT, (LPSTR)&lpMessageBuffer, 0, NULL); + if (length == 0) throw std::runtime_error("ƒGƒ‰[ƒƒbƒZ[ƒWŽæ“¾Žž‚ɃGƒ‰[‚ª”­¶‚µ‚Ü‚µ‚½B\nƒGƒ‰[ƒR[ƒh : " + std::to_string(GetLastError())); + DWORD i = length - 3; + for (; '\r' != lpMessageBuffer[i] && '\n' != lpMessageBuffer[i] && '\0' != lpMessageBuffer[i]; i++);//‰üs•¶Žšíœ + lpMessageBuffer[i] = '\0'; + std::string s = "ƒGƒ‰[ƒR[ƒh : " + std::to_string(code) + "@" + lpMessageBuffer; + LocalFree(lpMessageBuffer); + return s; +} + + +namespace WinSvcLib { + namespace Installer { + struct ServiceInfo { + std::basic_string ServiceName; // ƒT[ƒrƒX‚Ì–¼‘O + std::basic_string DisplayName; // ƒT[ƒrƒX‚Ì•\ަ–¼ + LPTSTR Description; // ƒT[ƒrƒX‚Ìà–¾BSERVICE_DESCRIPTION\‘¢‘Ì‚ÌlpDescription‚ÌŒ^‚ªLPCTSTR‚łȂ¢‚½‚ßstd::basic_stringŽg—p•s‰Â + std::basic_string ExecuteFilePath; // ŽÀsƒtƒ@ƒCƒ‹‚̃pƒX + ServiceType Type; // ƒT[ƒrƒX‚ÌŽí—Þ + ServiceStartType StartType; // ƒT[ƒrƒX‚ÌŠJŽn‚ÌŽí—Þ + ServiceErrorControlType ErrorControl; // ƒGƒ‰[”­¶Žž‚̐[‚³ + std::basic_string LoadOrderGroup; // ƒT[ƒrƒX‚ÌŠ‘®‚µ‚Ä‚¢‚郍[ƒh‡˜Œˆ’èƒOƒ‹[ƒv–¼ + LPCTSTR Dependencies; // •¡”‚̈ˑ¶–¼‚©‚ç‚È‚é”z—ñ + std::basic_string ExecuteUser; // ŽÀsƒ†[ƒU[–¼ + std::basic_string ExecuteUserPassword; // ŽÀsƒ†[ƒU[‚̃pƒXƒ[ƒh + bool DeviceDriver; + } inf; + static inline std::basic_string ChangeUserEnumToString(const ExecuteUser User) { + switch (User) { + case ExecuteUser::LocalService: return TEXT("NT AUTHORITY\\LocalService"); + case ExecuteUser::NetworkService: return TEXT("NT AUTHORITY\\NetworkService"); + default: return TEXT("NT AUTHORITY\\SYSTEM"); + } + } + static inline bool IsAuthorityUser() { + return inf.ExecuteUser == ChangeUserEnumToString(ExecuteUser::System) + || inf.ExecuteUser == ChangeUserEnumToString(ExecuteUser::LocalService) + || inf.ExecuteUser == ChangeUserEnumToString(ExecuteUser::NetworkService); + } + void InstallerLibInit(const std::basic_string ServiceName, const std::basic_string ExecuteFilePath, bool IsDeviceDriver) { + inf.DeviceDriver = IsDeviceDriver; + inf.ServiceName = inf.DisplayName = ServiceName; + inf.Type = ServiceType::Win32OwnProcess; + inf.ErrorControl = ServiceErrorControlType::Normal; + inf.Description = NULL; + if (ExecuteFilePath.empty()) { + LPTSTR Buffer = new TCHAR[MAX_PATH]; + GetModuleFileName(NULL, Buffer, sizeof(Buffer) / sizeof(Buffer[0])); + inf.ExecuteFilePath = Buffer; + delete[] Buffer; + } + else inf.ExecuteFilePath = ExecuteFilePath; + inf.StartType = ServiceStartType::AutoStart; + inf.ExecuteUser = ChangeUserEnumToString(ExecuteUser::System); + inf.ExecuteUserPassword = TEXT(""); + } + void SetServiceDescription(LPTSTR Description) { inf.Description = Description; } + void ChangeServiceType(const ServiceType Type) { inf.Type = Type; } + void ChangeStartType(const ServiceStartType StartType) { + if (!inf.DeviceDriver && (StartType == ServiceStartType::BootStart || StartType == ServiceStartType::SystemStart)) return; + inf.StartType = StartType; + } + void ChangeDisplayName(const std::basic_string DisplayName) { inf.DisplayName = DisplayName; } + void SetLoadOrderGroup(const std::basic_string LoadOrderGroup) { inf.LoadOrderGroup = LoadOrderGroup; } + void SetDependencies(LPCTSTR Dependencies) { inf.Dependencies = Dependencies; } + void ChangeExecuteUser(const std::basic_string UserName) { inf.ExecuteUser = UserName; } + void ChangeExecuteUser(const ExecuteUser User) { inf.ExecuteUser = ChangeUserEnumToString(User); } + void SetUserPassword(const std::basic_string Password) { + if (IsAuthorityUser()) return; + inf.ExecuteUserPassword = Password; + } + static void CloseServiceHandles(SC_HANDLE &Service, SC_HANDLE &scm) { + CloseServiceHandle(Service); + CloseServiceHandle(scm); + } + void InstallerLibEnd(LPDWORD lpdwTagId) { + if (FALSE == IsUserAnAdmin()) throw std::runtime_error("ŠÇ—ŽÒŒ ŒÀ‚ł̋N“®‚ª•K—v‚Å‚·B"); + SC_HANDLE Service = NULL, scm = NULL; + SERVICE_DESCRIPTION ServiceDescription; + if ((scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) { + CloseServiceHandles(Service, scm); + throw std::runtime_error( + "Failed In OpenSCManager Function\n" + + GetErrorMessageA() + ); + } + if ((Service = CreateService( + scm, + inf.ServiceName.c_str(), + inf.DisplayName.c_str(), + SERVICE_CHANGE_CONFIG, + static_cast(inf.Type), + static_cast(inf.StartType == ServiceStartType::DelayStart ? ServiceStartType::AutoStart : inf.StartType), + static_cast(inf.ErrorControl), + inf.ExecuteFilePath.c_str(), + inf.LoadOrderGroup.empty() ? NULL : inf.LoadOrderGroup.c_str(), + lpdwTagId, + inf.Dependencies, + inf.ExecuteUser.c_str(), + inf.ExecuteUserPassword.c_str() + )) == NULL) { + CloseServiceHandles(Service, scm); + throw std::runtime_error( + "Failed In CreateService Function\n" + + GetErrorMessageA() + ); + } + ServiceDescription.lpDescription = inf.Description; + if (inf.StartType == ServiceStartType::DelayStart) { + SERVICE_DELAYED_AUTO_START_INFO info = { TRUE }; + if (ChangeServiceConfig2(Service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &info)) { + CloseServiceHandles(Service, scm); + throw std::runtime_error( + "Failed Set Service Delay Start\n" + + GetErrorMessageA() + ); + } + } + if (0 == ChangeServiceConfig2(Service, SERVICE_CONFIG_DESCRIPTION, &ServiceDescription)) { + CloseServiceHandles(Service, scm); + throw std::runtime_error( + "Failed Set Service Description\n" + + GetErrorMessageA() + ); + } + CloseServiceHandles(Service, scm); + } + } +} + diff --git a/pool/shard007/C++/0095524_locator_test_main.cpp b/pool/shard007/C++/0095524_locator_test_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2621e010d90eb8b33eb34ce53c92d2f0ff434a2b --- /dev/null +++ b/pool/shard007/C++/0095524_locator_test_main.cpp @@ -0,0 +1,47 @@ +/* + * locator_test_main.cpp + * + * Created on: Sep 29, 2016 + * Author: zmij + */ + + +#include +#include + +#include "sparring/options.hpp" + +// Initialize the test suite +int +main( int argc, char* argv[] ) +try { + namespace po = boost::program_options; + using wire::test::sparring::options; + + ::testing::InitGoogleTest(&argc, argv); + + po::options_description desc("Test options"); + options& opts = options::instance(); + + desc.add_options() + ("help,h", "show options description") + ("sparring-partner,s", + po::value< std::string >(&opts.sparring_partner)->required(), + "Program to run for server counterpart (wire-locatord)") + ; + + po::variables_map vm; + po::store(po::parse_command_line(argc, argv, desc), vm); + + if (vm.count("help")) { + std::cout << desc << "\n"; + return 0; + } + + po::notify(vm); + + return RUN_ALL_TESTS(); +} catch (::std::exception const& e) { + ::std::cerr << e.what() << "\n"; + return 1; +} diff --git a/pool/shard007/C++/0095526_camera.cpp b/pool/shard007/C++/0095526_camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74814f68363fef8806e5997983068238b5b32344 --- /dev/null +++ b/pool/shard007/C++/0095526_camera.cpp @@ -0,0 +1,195 @@ +// camera.cpp +// +// Copyright 2012 Klaas Winter +// +// 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. + +#define GLM_FORCE_RADIANS + +#include +#include + +#include "dim/core/camera.hpp" + +using namespace std; +using namespace glm; + +namespace dim +{ + + Camera::Camera() + : + Camera(Camera::perspective, 1, 1) { } + + Camera::Camera(Camera::projection mode, float width, float height) + : + Camera(mode, width, height, vec3(0.0f), vec3(1.0f, 0.0f, 0.0f)) { } + + Camera::Camera(Camera::projection mode, float width, float height, vec3 coorFrom, vec3 coorTo) + : + d_coorFrom(coorFrom), + d_coorTo(coorTo), + d_height(height), + d_width(width), + d_fov(M_PI/3.0f), + d_zNear(0.5), + d_zFar(1000), + d_mode(mode) + { + setView(); + setProjection(); + } + + void Camera::setHeight(float height) + { + d_height = height; + d_changed = true; + } + + void Camera::setWidth(float width) + { + d_width = width; + d_changed = true; + } + + void Camera::setView() + { + vec2 dir = vec2(d_coorTo.x - d_coorFrom.x, d_coorTo.z - d_coorFrom.z); + vec2 line_dir1 = rotate(dir, -d_fov); + vec2 line_dir2 = rotate(dir, d_fov); + + A1 = line_dir1.y; + A2 = line_dir2.y; + B1 = -line_dir1.x; + B2 = -line_dir2.x; + D1 = -(A1 * d_coorFrom.x + B1 * d_coorFrom.z); + D2 = -(A2 * d_coorFrom.x + B2 * d_coorFrom.z); + + if(d_mode == Camera::perspective || d_mode == Camera::orthogonal) + { + d_view = lookAt(d_coorFrom, d_coorTo, vec3(0.0, 1.0, 0.0)); + } + else + { + d_view = mat4(1.0); + } + + d_changed = false; + } + + void Camera::setProjection() + { + if(d_mode == Camera::perspective) + { + if(d_height == 0) + d_height = 1; + + d_projection = glm::perspective(d_fov, d_width / d_height, d_zNear, d_zFar); + + if(d_height == 1) + d_height = 0; + } + else if(d_mode == Camera::orthogonal) + { + d_projection = ortho(-(d_width / 2), d_width / 2, -(d_height / 2), d_height / 2, d_zNear, d_zFar); + } + else + { + d_projection = ortho(0.0f, d_width, d_height, 0.0f); + } + } + + //void camera::setUp(vec3 up) + //{ + // d_up = up; + // d_changed = true; + //} + + float Camera::fov() const + { + return d_fov; + } + + float Camera::height() const + { + return d_height; + } + + float Camera::width() const + { + return d_width; + } + + mat4 const &Camera::viewMatrix() const + { + return d_view; + } + + mat4 const &Camera::projectionMatrix() const + { + return d_projection; + } + + void Camera::setCoorFrom(vec3 coorFrom) + { + d_coorFrom = coorFrom; + d_changed = true; + } + + void Camera::setCoorTo(vec3 coorTo) + { + d_coorTo = coorTo; + d_changed = true; + } + + void Camera::setCoorTo(float dir, float yDir) + { + d_coorTo = vec3(sin(dir) * cos(yDir), + sin(yDir), + cos(dir) * cos(yDir)); + d_coorTo += d_coorFrom; + d_changed = true; + } + + void Camera::setFOV(float fov) + { + d_fov = fov; + setProjection(); + } + + void Camera::setZrange(float zNear, float zFar) + { + d_zNear = zNear; + d_zFar = zFar; + setProjection(); + } + + // TODO: make this function const + void Camera::setAtShader(string const &viewMatrix, string const &projectionMatrix) const + { + if(d_changed == true) + const_cast(this)->setView(); + + Shader::set(viewMatrix, d_view); + Shader::set(projectionMatrix, d_projection); + } + + bool Camera::frustum(float ox, float oz) const + { + return A1 * ox + B1 * oz + D1 < 0 && A2 * ox + B2 * oz + D2 > 0; + } + +} diff --git a/pool/shard007/C++/0095527_Debug.cpp b/pool/shard007/C++/0095527_Debug.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d6871ad9255ba46ff918ee392c28b6824952616 --- /dev/null +++ b/pool/shard007/C++/0095527_Debug.cpp @@ -0,0 +1,53 @@ +/* + * Copyright © 2008 Silicondust USA Inc. . + */ + +#include "AppInclude.h" + +hdhomerun_debug_t *dbg = NULL; +unsigned long long DebugExpireTime = 0; +string DebugFilename = ""; + +void DebugInit(void) +{ + dbg = hdhomerun_debug_create(); + if (!dbg) { + return; + } + + DebugCheckState(); +} + +void DebugCheckState(void) +{ + +#ifdef __WINDOWS__ + char buf[1024]; + DWORD size = sizeof(buf); + + LSTATUS err = RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Silicondust\\HDHomeRun", "DebugFilename", RRF_RT_REG_SZ, NULL, (PVOID) buf, &size); + if (err != 0) { + buf[0] = '\0'; + } + + DebugFilename = buf; + + size = sizeof(DebugExpireTime); + err = RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Silicondust\\HDHomeRun", "DebugEnabled", RRF_RT_REG_QWORD, NULL, (PVOID) & DebugExpireTime, &size); + if (err != 0) { + DebugExpireTime = 0; + } +#endif + + if (DebugFilename.empty()) { + hdhomerun_debug_set_filename(dbg, NULL); + } else { + hdhomerun_debug_set_filename(dbg, DebugFilename.c_str()); + } + + if (DebugExpireTime > (unsigned long long)time(NULL)) { + hdhomerun_debug_enable(dbg); + } else { + hdhomerun_debug_disable(dbg); + } +} diff --git a/pool/shard007/C++/0095533_ecntgetsortprefs1_cstep.cpp b/pool/shard007/C++/0095533_ecntgetsortprefs1_cstep.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eedcac320875a5401d807cb552ae014650fe07c9 --- /dev/null +++ b/pool/shard007/C++/0095533_ecntgetsortprefs1_cstep.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +* Contact: http://www.qt-project.org/legal +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +#include "ecntgetsortprefs1_cstep.h" + + +//TO BE SAFE +IMPORT_C TInt StartDialogThread(); + +CECntGetSortPrefs1Step::CECntGetSortPrefs1Step() +/** Each test step initialises it's own name +*/ + { + // store the name of this test case + // this is the name that is used by the script file + //DEF iTestStepName = _L("CECntGetSortPrefs1Step"); + + //The server name and IPC number is obtained and all messages are checked Sync + SR_ServerName = _L("CNTSRV"); + SR_MESSAGE_TYPE = 2; + SR_MESSAGE_ID = 45; + SR_MESSAGE_MASK = 2147483648LL; + + //The iServer_Panic is a unique name from Server,but always truncated to KMaxExitCategoryName + + iServer_Panic = _L("CNTMODEL"); + + TCapability cap[] = {ECapability_None, ECapability_Limit}; + + TSecurityInfo info; + info.Set(RProcess()); + TBool result = EFalse; + + for (TInt i = 0; cap[i] != ECapability_Limit; i++) + { + + if (!(info.iCaps.HasCapability(cap[i]))) + { + result=ETrue; + + } + + } + + + iExpect_Rejection = result; + + iStepCap = 2147483648LL; + + //Get a unique thread name + ChildThread_SR.Format(_L("ChildThread_%S_%d"),&SR_ServerName,SR_MESSAGE_ID); + + } + +/* +Exec_SendReceive(): + This Fn is called by the Child Thread +1. Create a session with the server +2. Test an SendReceive call +3. Informs the main thread about the status of the call using + a. iSessionCreated, if the a connection is established + b. iResult_Server, holds the return value for connection + c. iResult_SR, the return value of SendReceive call +*/ +TInt CECntGetSortPrefs1Step::Exec_SendReceive() + { + iResult_Server = CreateSession(SR_ServerName,Version(),2); + + if (iResult_Server!=KErrNone) + { + + iResult_Server=StartServer(); + if (iResult_Server!=KErrNone) + return(iResult_Server); + + iResult_Server = CreateSession(SR_ServerName,TVersion(),2); + } + if(iResult_Server == 0) + { + iSessionCreated = ETrue; + if(SR_MESSAGE_ID >= 0) + iResult_SR = SendReceive(SR_MESSAGE_ID,TIpcArgs(0,0,0,0)); + } + + return iResult_Server; + } diff --git a/pool/shard007/C++/0095536_rpl_gtid_mutex_cond_array.cc b/pool/shard007/C++/0095536_rpl_gtid_mutex_cond_array.cc new file mode 100644 index 0000000000000000000000000000000000000000..3dcbac9d042c379e4e45968b52350aff8eace064 --- /dev/null +++ b/pool/shard007/C++/0095536_rpl_gtid_mutex_cond_array.cc @@ -0,0 +1,94 @@ +/* Copyright (c) 2012, Oracle and/or its affiliates. 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; version 2 of the + 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 + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + 02110-1301 USA */ + +#include "rpl_gtid.h" + +#include "my_sys.h" +#include "sql_class.h" + + +Mutex_cond_array::Mutex_cond_array(Checkable_rwlock *_global_lock) + : global_lock(_global_lock) +{ + DBUG_ENTER("Mutex_cond_array::Mutex_cond_array"); + my_init_dynamic_array(&array, sizeof(Mutex_cond *), 0, 8); + DBUG_VOID_RETURN; +} + + +Mutex_cond_array::~Mutex_cond_array() +{ + DBUG_ENTER("Mutex_cond_array::~Mutex_cond_array"); + // destructor should only be called when no other thread may access object + //global_lock->assert_no_lock(); + // need to hold lock before calling get_max_sidno + global_lock->rdlock(); + int max_index= get_max_index(); + for (int i= 0; i <= max_index; i++) + { + Mutex_cond *mutex_cond= get_mutex_cond(i); + if (mutex_cond) + { + mysql_mutex_destroy(&mutex_cond->mutex); + mysql_cond_destroy(&mutex_cond->cond); + free(mutex_cond); + } + } + delete_dynamic(&array); + global_lock->unlock(); + DBUG_VOID_RETURN; +} + + +void Mutex_cond_array::enter_cond(THD *thd, int n, PSI_stage_info *stage, + PSI_stage_info *old_stage) const +{ + DBUG_ENTER("Mutex_cond_array::enter_cond"); + Mutex_cond *mutex_cond= get_mutex_cond(n); + thd->ENTER_COND(&mutex_cond->cond, &mutex_cond->mutex, stage, old_stage); + DBUG_VOID_RETURN; +} + + +enum_return_status Mutex_cond_array::ensure_index(int n) +{ + DBUG_ENTER("Mutex_cond_array::ensure_index"); + global_lock->assert_some_wrlock(); + int max_index= get_max_index(); + if (n > max_index) + { + if (n > max_index) + { + if (allocate_dynamic(&array, n + 1)) + goto error; + for (int i= max_index + 1; i <= n; i++) + { + Mutex_cond *mutex_cond= (Mutex_cond *)my_malloc(sizeof(Mutex_cond), MYF(MY_WME)); + if (mutex_cond == NULL) + goto error; + mysql_mutex_init(key_gtid_ensure_index_mutex, &mutex_cond->mutex, NULL); + mysql_cond_init(key_gtid_ensure_index_cond, &mutex_cond->cond, NULL); + insert_dynamic(&array, &mutex_cond); + DBUG_ASSERT(&get_mutex_cond(i)->mutex == &mutex_cond->mutex); + } + } + } + RETURN_OK; +error: + BINLOG_ERROR(("Out of memory."), (ER_OUT_OF_RESOURCES, MYF(0))); + RETURN_REPORTED_ERROR; +} diff --git a/pool/shard007/C++/0095537_task.cpp b/pool/shard007/C++/0095537_task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b254d42f5405f5d644f4ec6eaf4f27917f6ac31 --- /dev/null +++ b/pool/shard007/C++/0095537_task.cpp @@ -0,0 +1,295 @@ +// ----------------------------------------------------------------------------- +// +// MIT License +// +// Copyright (c) 2016 Alberto Sola +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// ----------------------------------------------------------------------------- + +// ----------------------------------------------------------------------------- + +#include "task.hpp" + +// ----------------------------------------------------------------------------- + +Task::Task(){ + data = ""; + finished = false; + id = 0; + creation_date.set_current(); + tag = "General"; +} + +// ----------------------------------------------------------------------------- + +Task::Task( const std::string & new_data ){ + load_from_str(new_data); +} + +// ----------------------------------------------------------------------------- + +void Task::load_from_str( const std::string & task_data ){ + /* + Load task data from string. + + String format: field:value, + */ + std::map data; + std::map::const_iterator find; + bool add_field = true; + std::string field = ""; + std::string value = ""; + char next_char; + unsigned int data_size = task_data.size(); + + // Extract data + for( unsigned int i = 0; i < data_size; i++ ){ + + next_char = task_data[i]; + + if(next_char == ','){ + + data.insert(std::make_pair(field,value)); + field = ""; + value = ""; + add_field = true; + + } + else if(next_char == ':') + add_field = false; + else if(add_field) + field += next_char; + else + value += next_char; + + } + + data.insert(std::make_pair(field,value)); + + // ID + find = data.find("id"); + if(find != data.cend()) + set_id(std::stoi((*find).second)); + + // Task + find = data.find("task"); + if(find != data.cend()) + set_task((*find).second); + + // Finished + find = data.find("finished"); + if(find != data.cend()) + set_status((*find).second); + + // Tag + find = data.find("tag"); + if(find != data.cend()) + set_tag((*find).second); + + // Creation date + find = data.find("creation_date"); + if(find != data.cend()) + set_creation_date(Date((*find).second)); + + // Finish date + find = data.find("finish_date"); + if(find != data.cend()) + set_finish_date(Date((*find).second)); +} + +// ----------------------------------------------------------------------------- + +void Task::set_status(const std::string & status){ + /* + Set if the task is finished or not. + */ + if(status == "1") + finished = 1; + else + finished = 0; +} + +// ----------------------------------------------------------------------------- + +void Task::set_task(const std::string & task){ + /* + Set task. + */ + data = task; +} +// ----------------------------------------------------------------------------- + +const std::string & Task::get_task() const{ + /* + Return task. + */ + return data; +} + +// ----------------------------------------------------------------------------- + +std::string Task::to_str() const{ + /* + Turn the task into a string. + + String format: field:vlaue, + */ + const char separator = ','; + + char char_finished = (finished)? '1' : '0'; + std::string task_data; + + task_data.reserve(64); + + task_data += "task:"; + task_data += data; + task_data += separator; + task_data += "finished:"; + task_data += char_finished; + task_data += separator; + task_data += "creation_date:"; + task_data += creation_date.to_str(); + task_data += separator; + task_data += "finish_date:"; + task_data += finish_date.to_str(); + task_data += separator; + task_data += "id:"; + task_data += std::to_string(id); + task_data += separator; + task_data += "tag:"; + task_data += tag; + + return task_data; +} + +// ----------------------------------------------------------------------------- + +void Task::set_id(unsigned int new_id){ + /* + Set ID. + */ + id = new_id; +} + +// ----------------------------------------------------------------------------- + +unsigned int Task::get_id() const{ + /* + Return id. + */ + return id; +} + +// ----------------------------------------------------------------------------- + +bool Task::is_empty() const{ + /* + Check if the task is an empty task. + */ + return id == 0; +} + +// ----------------------------------------------------------------------------- + +bool Task::is_finished() const{ + /* + Return if the task is finished. + */ + return finished; +} + +// ----------------------------------------------------------------------------- + +bool Task::finish(){ + /* + Finish/Start the task. + */ + bool last_value = finished; + finished = !finished; + return last_value; +} + +// ----------------------------------------------------------------------------- + +bool Task::finish(bool status){ + /* + Finish/Start the task. + */ + bool last_value = finished; + finished = status; + return last_value; +} + +// ----------------------------------------------------------------------------- + +const Date & Task::get_creation_date() const{ + /* + Set the creation date. + */ + return creation_date; +} + +// ----------------------------------------------------------------------------- + +void Task::set_creation_date(const Date & date){ + /* + Set the creation date. + */ + creation_date = date; +} + +// ----------------------------------------------------------------------------- + +const Date & Task::get_finish_date() const{ + /* + Return the finish date. + */ + return finish_date; +} + +// ----------------------------------------------------------------------------- + +void Task::set_finish_date(const Date & date){ + /* + Set the finish date. + */ + finish_date = date; +} + +// ----------------------------------------------------------------------------- + +const std::string & Task::get_tag() const{ + /* + Return tag. + */ + return tag; +} + +// ----------------------------------------------------------------------------- + +void Task::set_tag(const std::string & new_tag){ + /* + Set tag. + */ + tag = new_tag; +} + +// ----------------------------------------------------------------------------- diff --git a/pool/shard007/C++/0095538_HelbingInitializer.cpp b/pool/shard007/C++/0095538_HelbingInitializer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5134e2fbcfe153ebe1f8c43a09d525c1538b9ed --- /dev/null +++ b/pool/shard007/C++/0095538_HelbingInitializer.cpp @@ -0,0 +1,139 @@ +/* + +License + +Menge +Copyright © and trademark ™ 2012-14 University of North Carolina at Chapel Hill. +All rights reserved. + +Permission to use, copy, modify, and distribute this software and its documentation +for educational, research, and non-profit purposes, without fee, and without a +written agreement is hereby granted, provided that the above copyright notice, +this paragraph, and the following four paragraphs appear in all copies. + +This software program and documentation are copyrighted by the University of North +Carolina at Chapel Hill. The software program and documentation are supplied "as is," +without any accompanying services from the University of North Carolina at Chapel +Hill or the authors. The University of North Carolina at Chapel Hill and the +authors do not warrant that the operation of the program will be uninterrupted +or error-free. The end-user understands that the program was developed for research +purposes and is advised not to rely exclusively on the program for any reason. + +IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS +BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS +DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE +AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY +DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY +OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND +THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS +TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + +Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu + +*/ + +#include "HelbingInitializer.h" +#include "HelbingAgent.h" +#include "MengeCore/Math/RandGenerator.h" +#include "MengeCore/Runtime/Logger.h" + +namespace Helbing { + +using Menge::Logger; +using Menge::logger; +using Menge::Agents::BaseAgent; +using Menge::Math::ConstFloatGenerator; + +//////////////////////////////////////////////////////////////// +// Implementation of Helbing::AgentInitializer +//////////////////////////////////////////////////////////////// + +// Default values +const float MASS = 80.f; ///< The agent's default mass. + +//////////////////////////////////////////////////////////////// + +AgentInitializer::AgentInitializer() : Menge::Agents::AgentInitializer() { + _mass = new ConstFloatGenerator(MASS); +} + +//////////////////////////////////////////////////////////////// + +AgentInitializer::AgentInitializer(const AgentInitializer& init) + : Menge::Agents::AgentInitializer(init) { + _mass = init._mass->copy(); +} + +//////////////////////////////////////////////////////////////// + +AgentInitializer::~AgentInitializer() { delete _mass; } + +//////////////////////////////////////////////////////////////// + +bool AgentInitializer::setProperties(BaseAgent* agent) { + Agent* a = dynamic_cast(agent); + if (a == 0x0) return false; + a->_mass = _mass->getValue(); + return Menge::Agents::AgentInitializer::setProperties(agent); +} + +//////////////////////////////////////////////////////////////// + +bool AgentInitializer::isRelevant(const ::std::string& tagName) { + return (tagName == "Helbing") || Menge::Agents::AgentInitializer::isRelevant(tagName); +} + +//////////////////////////////////////////////////////////////// + +AgentInitializer::ParseResult AgentInitializer::setFromXMLAttribute(const ::std::string& paramName, + const ::std::string& value) { + ParseResult result = IGNORED; + if (paramName == "mass") { + result = constFloatGenerator(_mass, value); + } + + if (result == FAILURE) { + logger << Logger::WARN_MSG << "Attribute \"" << paramName; + logger << "\" had an incorrectly formed value: \"" << value; + logger << "\". Using default value."; + result = ACCEPTED; + } else if (result == IGNORED) { + return Menge::Agents::AgentInitializer::setFromXMLAttribute(paramName, value); + } + return result; +} + +//////////////////////////////////////////////////////////////// + +AgentInitializer::ParseResult AgentInitializer::processProperty(::std::string propName, + TiXmlElement* node) { + ParseResult result = IGNORED; + if (propName == "mass") { + result = getFloatGenerator(_mass, node); + } + + if (result == FAILURE) { + logger << Logger::ERR_MSG << "Error extracting value distribution from Property "; + logger << propName << "."; + return result; + } else if (result == IGNORED) { + return Menge::Agents::AgentInitializer::processProperty(propName, node); + } + return result; +} + +//////////////////////////////////////////////////////////////// + +void AgentInitializer::setDefaults() { + if (_mass) delete _mass; + _mass = new ConstFloatGenerator(MASS); + Menge::Agents::AgentInitializer::setDefaults(); +} + +//////////////////////////////////////////////////////////////// + +} // namespace Helbing diff --git a/pool/shard007/C++/0095541_zipf.cpp b/pool/shard007/C++/0095541_zipf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53312a2ccec9e61deed9662f613b0aaab103c9bf --- /dev/null +++ b/pool/shard007/C++/0095541_zipf.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include + +#include "stdafx.h" + +#include + +#include + + + +#include "prng.h" +#include "zipf.h" + + + +ZipfianGenerator::ZipfianGenerator(int nItems, double order, unsigned long seed) : + _curr_number(0.0), _count(1), _order(order), + _discretized_cdf(nItems, 0.0), + prng(seed) +{} + +// Formula for calculating Zipfian CDF from Wikipedia +void ZipfianGenerator::Init(){ + if (_order == 0.0){ + // Shape is 0.0, using uniform distribution + return; + } + // using zipfian distribution + for (size_t i = 0; i < _discretized_cdf.size(); ++i){ + _discretized_cdf[i] = getNextGeneralizedHarmonicNumber(); + } + for (size_t i = 0; i < _discretized_cdf.size(); ++i){ + _discretized_cdf[i] /= _discretized_cdf[_discretized_cdf.size() - 1]; + } +} + +// Perform binary search to find the highest index less than a random (0.0, 1.0). +// This effective "inverts" the CDF, giving us the target distribution. +int ZipfianGenerator::GetIndex(){ + double p = (double)prng.next() / UINT64_MAX; + auto pos = std::lower_bound(_discretized_cdf.cbegin(), _discretized_cdf.cend(), p); + return static_cast(std::distance(_discretized_cdf.cbegin(), pos)); +} + +void ZipfianGenerator::print(){ + for (auto i = _discretized_cdf.cbegin(); i != _discretized_cdf.cend(); ++i){ + printf("%lld: %f\n", (long long) std::distance(_discretized_cdf.cbegin(), i), *i); + } +} + +#if 0 +int do_zipfian_test(){ + ZipfianGenerator zg(200000, 1); + zg.Init(); + std::unordered_map histogram; + { + for (auto i = 0; i < 1000000; ++i){ + int j = zg.GetIndex(); + if (histogram.find(j) != histogram.end()){ + histogram[j]++; + } else { + histogram[j] = 1; + } + } + } + for (auto i = 0; i < 100; ++i){ + printf("%d: %f\n", i, histogram[i]/double(1000000)); + } + return 0; +} + +int main(){ + do_zipfian_test(); + return 0; +} +#endif diff --git a/pool/shard007/C++/0095545_Ndberr.cpp b/pool/shard007/C++/0095545_Ndberr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9cac232f694d0926e97f197c589246cbb0e76ba --- /dev/null +++ b/pool/shard007/C++/0095545_Ndberr.cpp @@ -0,0 +1,104 @@ +/* + Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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; version 2 of the 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 + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "API.hpp" + +static void +update(const NdbError & _err){ + NdbError & error = (NdbError &) _err; + ndberror_struct ndberror = (ndberror_struct)error; + ndberror_update(&ndberror); + error = NdbError(ndberror); +} + +const +NdbError & +Ndb::getNdbError(int code){ + theError.code = code; + update(theError); + return theError; +} + +const +NdbError & +Ndb::getNdbError() const { + update(theError); + return theError; +} + +const +NdbError & +NdbDictionaryImpl::getNdbError() const { + update(m_error); + return m_error; +} + +const +NdbError & +NdbTransaction::getNdbError() const { + update(theError); + return theError; +} + +const +NdbError & +NdbOperation::getNdbError() const { + update(theError); + return theError; +} + +const +NdbError & +NdbBlob::getNdbError() const { + update(theError); + return theError; +} + +const +NdbError & +NdbEventOperationImpl::getNdbError() const { + update(m_error); + return m_error; +} + +const +NdbError & +NdbDictInterface::getNdbError() const { + update(m_error); + return m_error; +} + +const +NdbError & +NdbQueryBuilderImpl::getNdbError() const { + update(m_error); + return m_error; +} + +const +NdbError & +NdbQueryImpl::getNdbError() const { + update(m_error); + return m_error; +} + +const +NdbIndexStat::Error & +NdbIndexStatImpl::getNdbError() const { + update(m_error); + return m_error; +} diff --git a/pool/shard007/C++/0095546_arc_app_launcher.cc b/pool/shard007/C++/0095546_arc_app_launcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..e556345d96b2f024f03920ba1fbe406f53edd1e1 --- /dev/null +++ b/pool/shard007/C++/0095546_arc_app_launcher.cc @@ -0,0 +1,135 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/app_list/arc/arc_app_launcher.h" + +#include +#include + +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/apps/app_service/app_service_proxy_factory.h" +#include "chrome/browser/apps/app_service/launch_utils.h" +#include "chrome/browser/profiles/profile.h" +#include "ui/events/event_constants.h" + +ArcAppLauncher::ArcAppLauncher(content::BrowserContext* context, + const std::string& app_id, + apps::mojom::IntentPtr launch_intent, + bool deferred_launch_allowed, + int64_t display_id, + apps::mojom::LaunchSource launch_source) + : context_(context), + app_id_(app_id), + launch_intent_(std::move(launch_intent)), + deferred_launch_allowed_(deferred_launch_allowed), + display_id_(display_id), + launch_source_(launch_source) { + ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); + DCHECK(prefs); + + std::unique_ptr app_info = prefs->GetApp(app_id_); + if (!app_info || + !MaybeLaunchApp(app_id, *app_info, apps::Readiness::kUnknown)) + prefs->AddObserver(this); + + auto* profile = Profile::FromBrowserContext(context_); + DCHECK( + apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)); + Observe(&apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache()); +} + +ArcAppLauncher::~ArcAppLauncher() { + if (!app_launched_) { + ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); + if (prefs) + prefs->RemoveObserver(this); + VLOG(2) << "App " << app_id_ << "was not launched."; + } +} + +void ArcAppLauncher::OnAppRegistered( + const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info) { + MaybeLaunchApp(app_id, app_info, apps::Readiness::kUnknown); +} + +void ArcAppLauncher::OnAppStatesChanged( + const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info) { + MaybeLaunchApp(app_id, app_info, apps::Readiness::kUnknown); +} + +void ArcAppLauncher::OnAppUpdate(const apps::AppUpdate& update) { + if (update.AppId() != app_id_ || + update.Readiness() != apps::Readiness::kReady) { + return; + } + + ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); + DCHECK(prefs); + + const std::unique_ptr app_info = + prefs->GetApp(app_id_); + if (!app_info) + return; + + MaybeLaunchApp(app_id_, *app_info, apps::Readiness::kReady); +} + +void ArcAppLauncher::OnAppRegistryCacheWillBeDestroyed( + apps::AppRegistryCache* cache) { + Observe(nullptr); +} + +bool ArcAppLauncher::MaybeLaunchApp(const std::string& app_id, + const ArcAppListPrefs::AppInfo& app_info, + apps::Readiness readiness) { + if (app_launched_) + return true; + + if (app_id != app_id_ || (!app_info.ready && !deferred_launch_allowed_) || + app_info.suspended) { + return false; + } + + auto* profile = Profile::FromBrowserContext(context_); + DCHECK( + apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)); + auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile); + if (readiness == apps::Readiness::kUnknown) { + if (proxy->AppRegistryCache().GetAppType(app_id) == + apps::mojom::AppType::kUnknown) { + return false; + } + + auto readiness = apps::Readiness::kUnknown; + proxy->AppRegistryCache().ForOneApp( + app_id, [&readiness](const apps::AppUpdate& update) { + readiness = update.Readiness(); + }); + + if (readiness != apps::Readiness::kReady) + return false; + } else if (readiness != apps::Readiness::kReady) { + return false; + } + + ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); + DCHECK(prefs && prefs->GetApp(app_id_)); + prefs->RemoveObserver(this); + Observe(nullptr); + + if (launch_intent_) { + proxy->LaunchAppWithIntent(app_id_, ui::EF_NONE, std::move(launch_intent_), + launch_source_, + apps::MakeWindowInfo(display_id_)); + } else { + proxy->Launch(app_id_, ui::EF_NONE, launch_source_, + apps::MakeWindowInfo(display_id_)); + } + + app_launched_ = true; + return true; +} diff --git a/pool/shard007/C++/0095547_cmd_thread_pool.cpp b/pool/shard007/C++/0095547_cmd_thread_pool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43e2dd373df8986e84ffeb3f2ab559090268b8d8 --- /dev/null +++ b/pool/shard007/C++/0095547_cmd_thread_pool.cpp @@ -0,0 +1,238 @@ +/* Copyright 2012 K2Informatics GmbH, Root Laengenbold, Switzerland + * + * 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 "stdafx.h" + +#include "oci_marshal.h" + +#include "erl_interface.h" +#include "ei.h" + +#include "cmd_processors.h" + +#ifdef __WIN32__ +#include +#include +#else +#include "threadpool.h" +#define THREAD 10 +#define QUEUE 256 +#endif + +#include + +#ifdef __WIN32__ +static PTP_POOL pool = NULL; +static TP_CALLBACK_ENVIRON CallBackEnviron; +static PTP_CLEANUP_GROUP cleanupgroup = NULL; +static UINT rollback = 0; +#else +static threadpool_t *pTp = NULL; +#endif + +bool InitializeThreadPool(void) +{ + REMOTE_LOG("Port: Initializing Thread pool...\n"); + +#ifdef __WIN32__ + BOOL bRet = FALSE; + + InitializeThreadpoolEnvironment(&CallBackEnviron); + + // + // Create a custom, dedicated thread pool. + // + pool = CreateThreadpool(NULL); + + if (NULL == pool) { + _tprintf(_T("CreateThreadpool failed. LastError: %u\n"), GetLastError()); + goto main_cleanup; + } + + rollback = 1; // pool creation succeeded + + // + // The thread pool is made persistent simply by setting + // both the minimum and maximum threads to 1. + // + SetThreadpoolThreadMaximum(pool, 1); + + bRet = SetThreadpoolThreadMinimum(pool, 1); + + if (FALSE == bRet) { + _tprintf(_T("SetThreadpoolThreadMinimum failed. LastError: %u\n"), + GetLastError()); + goto main_cleanup; + } + + // + // Create a cleanup group for this thread pool. + // + cleanupgroup = CreateThreadpoolCleanupGroup(); + + if (NULL == cleanupgroup) { + _tprintf(_T("CreateThreadpoolCleanupGroup failed. LastError: %u\n"), GetLastError()); + goto main_cleanup; + } + + rollback = 2; // Cleanup group creation succeeded + + // + // Associate the callback environment with our thread pool. + // + SetThreadpoolCallbackPool(&CallBackEnviron, pool); + + // + // Associate the cleanup group with our thread pool. + // Objects created with the same callback environment + // as the cleanup group become members of the cleanup group. + // + SetThreadpoolCallbackCleanupGroup(&CallBackEnviron, cleanupgroup, NULL); + + return true; + +main_cleanup: + CloseThreadpool(pool); + pool = NULL; + return false; +#else + pTp = threadpool_create(THREAD, QUEUE, 0); + if(NULL != pTp) + return true; + return false; +#endif +} + +void CleanupThreadPool(void) +{ + REMOTE_LOG("Port: Cleanup Thread pool..."); + +#ifdef __WIN32__ + BOOL bRet = FALSE; + + // + // Wait for all callbacks to finish. + // CloseThreadpoolCleanupGroupMembers also releases objects + // that are members of the cleanup group, so it is not necessary + // to call close functions on individual objects + // after calling CloseThreadpoolCleanupGroupMembers. + // + CloseThreadpoolCleanupGroupMembers(cleanupgroup, FALSE, NULL); + + // + // Already cleaned up the work item with the + // CloseThreadpoolCleanupGroupMembers, so set rollback to 2. + // + rollback = 2; + goto main_cleanup; + +main_cleanup: + // + // Clean up any individual pieces manually + // Notice the fall-through structure of the switch. + // Clean up in reverse order. + // + + switch (rollback) { + case 3: + // Clean up the cleanup group members. + CloseThreadpoolCleanupGroupMembers(cleanupgroup,FALSE,NULL); + case 2: + // Clean up the cleanup group. + CloseThreadpoolCleanupGroup(cleanupgroup); + case 1: + // Clean up the pool. + CloseThreadpool(pool); + + default: + break; + } +#else + if(NULL != pTp) + threadpool_destroy(pTp, 0); +#endif +} + +// +// This is the thread pool work callback function. +// +static +#ifdef __WIN32__ +VOID CALLBACK +#else +void +#endif +ProcessCommandCb( +#ifdef __WIN32__ + PTP_CALLBACK_INSTANCE Instance, + PVOID arg, + PTP_WORK Work +#else + void *arg +#endif +) +{ + //REMOTE_LOG("Port: WorkThread processing command...\n"); +#ifdef __WIN32__ + // Instance, Parameter, and Work not used in this example. + UNREFERENCED_PARAMETER(Instance); + //UNREFERENCED_PARAMETER(Parameter); + UNREFERENCED_PARAMETER(Work); +#endif + + void * cmd_tuple = NULL; + + int indx = 0; + //cmd_tuple = erl_decode((unsigned char*)arg); + if (ei_decode_term((char*)arg, &indx, &cmd_tuple) < 0) { + // Term decoding failed + delete arg; + return; + } + + if(NULL != arg) delete arg; + exit_loop = cmd_processor(cmd_tuple); + + return; +} + +bool ProcessCommand(void * param) +{ + //REMOTE_LOG("Port: Delegating command processing to WorkThread..."); +#ifdef __WIN32__ + PTP_WORK work = NULL; + // + // Create work with the callback environment. + // + work = CreateThreadpoolWork(ProcessCommandCb, param, &CallBackEnviron); + + if (NULL == work) { + _tprintf(_T("CreateThreadpoolWork failed. LastError: %u\n"), + GetLastError()); + return false; + } + + rollback = 3; // Creation of work succeeded + + // + // Submit the work to the pool. Because this was a pre-allocated + // work item (using CreateThreadpoolWork), it is guaranteed to execute. + // + SubmitThreadpoolWork(work); +#else + threadpool_add(pTp, &ProcessCommandCb, param, 0); +#endif + + return true; +} diff --git a/pool/shard007/C++/0095551_test_shapes.cc b/pool/shard007/C++/0095551_test_shapes.cc new file mode 100644 index 0000000000000000000000000000000000000000..4ad85c4b510f88e9c87332382e320cda120744a1 --- /dev/null +++ b/pool/shard007/C++/0095551_test_shapes.cc @@ -0,0 +1,93 @@ +/* -*- mia-c++ -*- + * + * This file is part of MIA - a toolbox for medical image analysis + * Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny + * + * MIA 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 MIA; if not, see . + * + */ + +#include +#include +#include +using namespace mia; +using namespace basic_3dshape_creator; + +struct CShapeTestFixture { + void check(const C3DShape& shape, const C3DBounds& size, const bool *mask); + +}; + +void CShapeTestFixture::check(const C3DShape& shape, const C3DBounds& size, const bool *test_mask) +{ + auto mask = shape.get_mask(); + BOOST_CHECK_EQUAL(mask.get_size(), size); + auto im = mask.begin(); + auto em = mask.end(); + const bool *tm = test_mask; + int i = 0; + + while (im != em) { + BOOST_CHECK_EQUAL(*im, *tm); + ++im; + ++tm; + ++i; + } +} + +BOOST_FIXTURE_TEST_CASE( test_6n_shape, CShapeTestFixture ) +{ + auto shape = BOOST_TEST_create_from_plugin("6n"); + const bool test_mask [] = {0, 0, 0, /**/ 0, 1, 0, /**/ 0, 0, 0, + 0, 1, 0, /**/ 1, 1, 1, /**/ 0, 1, 0, + 0, 0, 0, /**/ 0, 1, 0, /**/ 0, 0, 0 + }; + check(*shape, C3DBounds(3, 3, 3), test_mask); +} + +BOOST_FIXTURE_TEST_CASE( test_18n_shape, CShapeTestFixture ) +{ + auto shape = BOOST_TEST_create_from_plugin("18n"); + const bool test_mask [] = {0, 1, 0, /**/ 1, 1, 1, /**/ 0, 1, 0, + 1, 1, 1, /**/ 1, 1, 1, /**/ 1, 1, 1, + 0, 1, 0, /**/ 1, 1, 1, /**/ 0, 1, 0 + }; + check(*shape, C3DBounds(3, 3, 3), test_mask); +} + +BOOST_FIXTURE_TEST_CASE( test_27n_shape, CShapeTestFixture ) +{ + auto shape = BOOST_TEST_create_from_plugin("26n"); + const bool test_mask [] = {1, 1, 1, /**/ 1, 1, 1, /**/ 1, 1, 1, + 1, 1, 1, /**/ 1, 1, 1, /**/ 1, 1, 1, + 1, 1, 1, /**/ 1, 1, 1, /**/ 1, 1, 1 + }; + check(*shape, C3DBounds(3, 3, 3), test_mask); +} + +BOOST_FIXTURE_TEST_CASE( test_sphere_2_shape, CShapeTestFixture ) +{ + auto shape = BOOST_TEST_create_from_plugin("sphere:r=2"); + const bool test_mask [] = {0, 0, 0, 0, 0, /**/ 0, 0, 0, 0, 0, /**/ 0, 0, 1, 0, 0, /**/ 0, 0, 0, 0, 0, /**/ 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, /**/ 0, 1, 1, 1, 0, /**/ 1, 1, 1, 1, 1, /**/ 0, 1, 1, 1, 0, /**/ 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 1, 1, 1, 0, /**/ 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, /**/ 0, 0, 0, 0, 0, /**/ 0, 0, 1, 0, 0, /**/ 0, 0, 0, 0, 0, /**/ 0, 0, 0, 0, 0 + }; + check(*shape, C3DBounds(5, 5, 5), test_mask); +} + + + + diff --git a/pool/shard007/C++/0095552_texttool.cpp b/pool/shard007/C++/0095552_texttool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa9c14777cb4483b5f8545848a07376c2c5544e8 --- /dev/null +++ b/pool/shard007/C++/0095552_texttool.cpp @@ -0,0 +1,69 @@ +#include "texttool.h" +#include "paperview.h" + +TextTool::TextTool() +{ + m_paper = nullptr; + selectedItem = nullptr; + m_textBox = nullptr; +} + +TextTool::~TextTool() +{ +} + +void TextTool::keyPressEvent(QKeyEvent* event) +{ + if(m_textBox) m_textBox->keyPressEvent(event); +} + +void TextTool::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + if(event->button() != Qt::LeftButton) + return; + + handleMousePressWhileEditingText(event); + selectedItem = m_paper->addSimpleText(""); + selectedItem->setPos(event->scenePos()); + selectedItem->setFlag(QGraphicsItem::ItemIsMovable); + m_textBox = std::unique_ptr( new TextBox(m_paper, selectedItem) ); +} + +void TextTool::mouseMoveEvent(QGraphicsSceneMouseEvent *) +{ + +} + +void TextTool::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + m_paper->graphicsSceneReleaseEvent(event); +} + +void TextTool::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + m_paper->graphicsSceneDoubleClickEvent(event); +} + +void TextTool::deselect() +{ + if(selectedItem) + m_paper->onNewItemAdded(selectedItem); + + m_paper = nullptr; + selectedItem = nullptr; + m_textBox = nullptr; +} + +void TextTool::handleMousePressWhileEditingText(QGraphicsSceneMouseEvent *event) +{ + if (! m_textBox) + return; + + if (m_textBox && m_textBox->amIClicked(event)) + return; + + if(selectedItem) + m_paper->onNewItemAdded(selectedItem); + + m_textBox = nullptr; +} diff --git a/pool/shard007/C++/0095555_pthread6.cc b/pool/shard007/C++/0095555_pthread6.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac28f66bfc1bd511c43009223f04b6af2ee51b9a --- /dev/null +++ b/pool/shard007/C++/0095555_pthread6.cc @@ -0,0 +1,86 @@ +// 2002-01-23 Loren J. Rittle +// Adpated from libstdc++/5444 submitted by markus.breuer@materna.de +// +// Copyright (C) 2002-2017 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 +// . + +// { dg-do run } +// { dg-options "-pthread" } +// { dg-require-effective-target pthread } + +#include +#include +#include +#include + +const int max_thread_count = 8; +const int loops = 100000; + +const char* my_default = "Hallo Welt!"; + +const std::size_t upper_limit = 2500; +const std::size_t lower_limit = 1000; + +typedef char charT; + +typedef std::string String; + +typedef String MyType; + +void* +thread_main (void*) +{ + typedef std::map Map; + typedef Map::value_type Value_Pair; + Map myMap; + + for (int loop = 0; loop < loops; loop++) + { + String& str = myMap[loop]; + str.append (my_default); + myMap.insert (Value_Pair (loop, str)); + + if (myMap.size () > upper_limit) + { + while (myMap.size () > lower_limit) + { + Map::iterator it = myMap.begin (); + myMap.erase (it); + } + } + } + + return 0; +} + +int +main (void) +{ + pthread_t tid[max_thread_count]; + +#if defined(__sun) && defined(__svr4__) && _XOPEN_VERSION >= 500 + pthread_setconcurrency (max_thread_count); +#endif + + for (int i = 0; i < max_thread_count; i++) + pthread_create (&tid[i], 0, thread_main, 0); + + for (int i = 0; i < max_thread_count; i++) + pthread_join (tid[i], 0); + + return 0; +} diff --git a/pool/shard007/C++/0095558_image.cpp b/pool/shard007/C++/0095558_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d632954687f7d4912212fa05d48e533ca6c29ae --- /dev/null +++ b/pool/shard007/C++/0095558_image.cpp @@ -0,0 +1,85 @@ +#include "EflCpp/image.h" + +#include "EflCpp/assert.h" +#include "EflCpp/bimap.h" + +#include + +#include "EflCpp/elementary_inc.h" + +namespace EflCpp +{ + +namespace +{ + +static const auto OrientationBimap = makeUnorderedBimap({ + {Image::Orientation::Default, ELM_IMAGE_ORIENT_NONE}, + {Image::Orientation::Rotate90, ELM_IMAGE_ROTATE_90}, + {Image::Orientation::Rotate180, ELM_IMAGE_ROTATE_180}, + {Image::Orientation::Rotate270, ELM_IMAGE_ROTATE_270}, + {Image::Orientation::FlipHorizontal, ELM_IMAGE_FLIP_HORIZONTAL}, + {Image::Orientation::FlipVertical, ELM_IMAGE_FLIP_VERTICAL}, + {Image::Orientation::FlipTranspose, ELM_IMAGE_FLIP_TRANSPOSE}, + {Image::Orientation::FlipTransverse, ELM_IMAGE_FLIP_TRANSVERSE}, +}); +} + +Image::Image(ElmObj& parent, const char* const objId) + : ElmObj(objId, &parent, &elm_image_add) +{ + EFLCPP_LOG_OBJECT_METHOD; +} + +Image::~Image() +{ + EFLCPP_LOG_OBJECT_METHOD; +} + +Image::Image(ElmObj& parent, const DerivedClassFactory factory, const char* const objId) + : ElmObj(objId, &parent, factory) +{ +} + +CoordSize Image::getImageSize() const +{ + int width, height; + elm_image_object_size_get(getHandle(), &width, &height); + EFLCPP_ASSERT(width); + EFLCPP_ASSERT(height); + + return {width, height}; +} + +void Image::setFile(const boost::filesystem::path& path) +{ + if (!boost::filesystem::exists(path)) + { + EFLCPP_FAIL_WITH_MESSAGE(std::string("Failed to load image: ") + path.string()); + } + + auto res = elm_image_file_set(getHandle(), path.string().c_str(), nullptr); + EFLCPP_ASSERT(res); +} + +void Image::setOrient(const Orientation orientation) +{ + elm_image_orient_set(getHandle(), getBimapValueByKey(OrientationBimap, orientation)); +} + +Image::Orientation Image::getOrient() const +{ + return getBimapKeyByValue(OrientationBimap, elm_image_orient_get(getHandle())); +} + +void Image::setFixedAspect(const bool fixed) +{ + elm_image_aspect_fixed_set(getHandle(), fixed); +} + +void Image::setFillOutside(const bool enable) +{ + elm_image_fill_outside_set(getHandle(), enable); +} + +} // namespace EflCpp diff --git a/pool/shard007/C++/0095559_EffekseerSoundXAudio2.SoundPlayer.cpp b/pool/shard007/C++/0095559_EffekseerSoundXAudio2.SoundPlayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..723cc636014f49d3ac26082b87b64ec1b7ac3b1b --- /dev/null +++ b/pool/shard007/C++/0095559_EffekseerSoundXAudio2.SoundPlayer.cpp @@ -0,0 +1,121 @@ + +//---------------------------------------------------------------------------------- +// Include +//---------------------------------------------------------------------------------- +#include "EffekseerSoundXAudio2.SoundImplemented.h" +#include "EffekseerSoundXAudio2.SoundVoice.h" +#include "EffekseerSoundXAudio2.SoundPlayer.h" + +//----------------------------------------------------------------------------------- +// +//----------------------------------------------------------------------------------- +namespace EffekseerSound +{ +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +SoundPlayer::SoundPlayer( SoundImplemented* sound ) + : m_sound ( sound ) +{ +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +SoundPlayer::~SoundPlayer() +{ +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +::Effekseer::SoundHandle SoundPlayer::Play( ::Effekseer::SoundTag tag, + const ::Effekseer::SoundPlayer::InstanceParameter& parameter ) +{ + if (m_sound->GetMute()) { + return NULL; + } + SoundData* soundData = (SoundData*)parameter.Data; + if (soundData) { + SoundVoice* voice = m_sound->GetVoice(soundData->channels); + if (voice) { + voice->Play(tag, parameter); + return (::Effekseer::SoundHandle)voice; + } + } + return NULL; +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +void SoundPlayer::Stop( ::Effekseer::SoundHandle handle, ::Effekseer::SoundTag tag ) +{ + SoundVoice* voice = (SoundVoice*)handle; + if (tag == voice->GetTag()) { + voice->Stop(); + } +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +void SoundPlayer::Pause( ::Effekseer::SoundHandle handle, ::Effekseer::SoundTag tag, bool pause ) +{ + SoundVoice* voice = (SoundVoice*)handle; + if (tag == voice->GetTag()) { + voice->Pause(pause); + } +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +bool SoundPlayer::CheckPlaying( ::Effekseer::SoundHandle handle, ::Effekseer::SoundTag tag ) +{ + SoundVoice* voice = (SoundVoice*)handle; + if (tag == voice->GetTag()) { + return voice->CheckPlaying(); + } + return false; +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +void SoundPlayer::StopTag( ::Effekseer::SoundTag tag ) +{ + m_sound->StopTag(tag); +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +void SoundPlayer::PauseTag( ::Effekseer::SoundTag tag, bool pause ) +{ + m_sound->PauseTag(tag, pause); +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +bool SoundPlayer::CheckPlayingTag( ::Effekseer::SoundTag tag ) +{ + return m_sound->CheckPlayingTag(tag); +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +void SoundPlayer::StopAll() +{ + m_sound->StopAllVoices(); +} + +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- +} +//---------------------------------------------------------------------------------- +// +//---------------------------------------------------------------------------------- diff --git a/pool/shard007/C++/0095560_Game.cpp b/pool/shard007/C++/0095560_Game.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d52fc3c96d0ce207916dcd37a6ab4072c843127a --- /dev/null +++ b/pool/shard007/C++/0095560_Game.cpp @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#include "pch.h" +#include "Game.h" +#include "Common\DirectXHelper.h" +#include "Utils\PerformanceCounters.h" +#include "httpClient\httpClient.h" +#include "AsyncIntegration.h" + +using namespace Sample; +using namespace Windows::Foundation; +using namespace Windows::System::Threading; +using namespace Concurrency; + +#define ACHIEVEMENT_ID "1" +#define ACHIEVEMENT_PROGRESS 10 +#define SKIP_ITEMS 0 +#define MAX_ITEMS 5 + +Game* g_sampleInstance = nullptr; +std::mutex Game::m_displayEventQueueLock; +// Loads and initializes application assets when the application is loaded. +Game::Game(const std::shared_ptr& deviceResources) : + m_deviceResources(deviceResources), + bInitialized(false) +{ + g_sampleInstance = this; + + // Register to be notified if the Device is lost or recreated + m_deviceResources->RegisterDeviceNotify(this); + m_sceneRenderer = std::unique_ptr(new Renderer(m_deviceResources)); + + InitializeXboxLive(); +} + +void Game::RegisterInputKeys() +{ + m_input->RegisterKey(Windows::System::VirtualKey::S, ButtonPress::SignIn); + m_input->RegisterKey(Windows::System::VirtualKey::G, ButtonPress::GetAchievementsForTitle); + m_input->RegisterKey(Windows::System::VirtualKey::N, ButtonPress::AchievementResultsGetNext); + m_input->RegisterKey(Windows::System::VirtualKey::A, ButtonPress::GetAchievement); + m_input->RegisterKey(Windows::System::VirtualKey::U, ButtonPress::UpdateAchievement); +} + +Game::~Game() +{ + // Deregister device notification + m_deviceResources->RegisterDeviceNotify(nullptr); + + CleanupXboxLive(); +} + +// Updates application state when the window size changes (e.g. device orientation change) +void Game::CreateWindowSizeDependentResources() +{ + m_sceneRenderer->CreateWindowSizeDependentResources(); +} + +// Updates the application state once per frame. +void Game::Update() +{ + if (!bInitialized) + { + return; + } + + // Update scene objects. + m_timer.Tick([&]() + { + m_input->Update(); + + OnGameUpdate(); + + m_sceneRenderer->Update(m_timer); + + // Since the KeyUp event could take a few frames to trigger, + // clear the keys to avoid running the scenarios multiple times. + m_input->ClearKeyHash(); + }); +} + +void Game::OnProtocolActivation(Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ args) +{ + m_protocolActivatedEventArgs = args; + + // the app has not initialized yet, it'll process the protocol after initialization + if (g_sampleInstance == nullptr || !bInitialized) + { + return; + } +} + +void Game::OnMainMenu() +{ +} + +void Game::OnGameUpdate() +{ + // Call one of the DrainAsyncCompletionQueue* helper functions + // For example: + // DrainAsyncCompletionQueue(m_queue, 5); + // DrainAsyncCompletionQueueUntilEmpty(m_queue); + double timeoutMilliseconds = 0.5f; + DrainAsyncCompletionQueueWithTimeout(m_queue, timeoutMilliseconds); + + if (m_input != nullptr) + { + if (m_input->IsKeyDown(ButtonPress::SignIn)) + { + SignIn(); + } + + if (m_input->IsKeyDown(ButtonPress::GetAchievementsForTitle)) + { + GetAchievementsForTitle(SKIP_ITEMS, MAX_ITEMS); + } + + if (m_input->IsKeyDown(ButtonPress::AchievementResultsGetNext)) + { + AchievementResultsGetNext(m_achievementsResult, MAX_ITEMS); + } + + if (m_input->IsKeyDown(ButtonPress::GetAchievement)) + { + GetAchievement(ACHIEVEMENT_ID); + } + + if (m_input->IsKeyDown(ButtonPress::UpdateAchievement)) + { + UpdateAchievement(ACHIEVEMENT_ID, ACHIEVEMENT_PROGRESS); + } + } +} + +std::vector +string_split( + _In_ const std::wstring& string, + _In_ std::wstring::value_type seperator + ) +{ + std::vector vSubStrings; + + if (!string.empty()) + { + size_t posStart = 0, posFound = 0; + while (posFound != std::wstring::npos && posStart < string.length()) + { + posFound = string.find(seperator, posStart); + if (posFound != std::wstring::npos) + { + if (posFound != posStart) + { + // this substring is not empty + vSubStrings.push_back(string.substr(posStart, posFound - posStart)); + } + posStart = posFound + 1; + } + else + { + vSubStrings.push_back(string.substr(posStart)); + } + } + } + + return vSubStrings; +} + +void replace_all(std::string& str, const std::string& from, const std::string& to) +{ + size_t start_pos = 0; + while ((start_pos = str.find(from, start_pos)) != std::string::npos) + { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); + } +} + +void Game::Init(Windows::UI::Core::CoreWindow^ window) +{ + bInitialized = true; + m_input = ref new Input(); + m_gameData.reset(new GameData()); + m_displayEventQueue = std::vector< std::wstring >(); + m_previousDisplayQueueSize = 0; + + m_gameData->SetViewDebugOutputOffsetX(1000); + m_gameData->SetViewCurrentCountersOffsetY(0); + m_gameData->SetViewGameDataOffsetX(0); + m_gameData->SetViewSelectedIndex(0); + m_gameData->SetViewDebug(false); + m_gameData->SetDisplayString(0, L""); + + RegisterInputKeys(); + + window->KeyDown += ref new TypedEventHandler(m_input, &Input::OnKeyDown); + window->KeyUp += ref new TypedEventHandler(m_input, &Input::OnKeyUp); + + std::weak_ptr thisWeakPtr = shared_from_this(); + XblUserAddSignOutCompletedHandler(Game::HandleSignout); + + SignInSilently(); +} + +// Renders the current frame according to the current application state. +// Returns true if the frame was rendered and is ready to be displayed. +bool Game::Render() +{ + // Don't try to render anything before the first Update. + if (m_timer.GetFrameCount() == 0) + { + return false; + } + + auto context = m_deviceResources->GetD3DDeviceContext(); + + // Reset the viewport to target the whole screen. + auto viewport = m_deviceResources->GetScreenViewport(); + context->RSSetViewports(1, &viewport); + + // Reset render targets to the screen. + ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() }; + context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView()); + + // Clear the back buffer and depth stencil view. + context->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::CornflowerBlue); + context->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); + + // Render the scene objects. + m_sceneRenderer->Render(); + + return true; +} + +// Notifies renderers that device resources need to be released. +void Game::OnDeviceLost() +{ + m_sceneRenderer->ReleaseDeviceDependentResources(); +} + +// Notifies renderers that device resources may now be recreated. +void Game::OnDeviceRestored() +{ + m_sceneRenderer->CreateDeviceDependentResources(); + CreateWindowSizeDependentResources(); +} + +void Game::Log(std::wstring log) +{ + std::lock_guard guard(m_displayEventQueueLock); + m_displayEventQueue.push_back(log); + if (m_displayEventQueue.size() > 15) + { + m_displayEventQueue.erase(m_displayEventQueue.begin()); + } +} + +void Game::Log(std::string log) +{ + Log(utility::conversions::to_utf16string(log)); +} \ No newline at end of file diff --git a/pool/shard007/C++/0095562_Adafruit_TLC5947.cpp b/pool/shard007/C++/0095562_Adafruit_TLC5947.cpp new file mode 100644 index 0000000000000000000000000000000000000000..543590f5a3616612197adb2b7ac081fc379032cb --- /dev/null +++ b/pool/shard007/C++/0095562_Adafruit_TLC5947.cpp @@ -0,0 +1,83 @@ +/*************************************************** + This is a library for our Adafruit 24-channel PWM/LED driver + + Pick one up today in the adafruit shop! + ------> http://www.adafruit.com/products/1429 + + These drivers uses SPI to communicate, 3 pins are required to + interface: Data, Clock and Latch. The boards are chainable + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Written by Limor Fried/Ladyada for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ****************************************************/ +//Use hardwired pins in order to use fast digital write +#define LED_DATA 4 +#define LED_CLOCK 5 +#define LED_LATCH 6 + + +#include "Adafruit_TLC5947.h" + +Adafruit_TLC5947::Adafruit_TLC5947(uint8_t n, uint8_t c, uint8_t d, uint8_t l) { + numdrivers = n; + _clk = c; + _dat = d; + _lat = l; + + pwmbuffer = (uint16_t *)calloc(2, 24 * n); +} + +void Adafruit_TLC5947::write(void) { + digitalWriteFast(LED_LATCH, LOW); + // 24 channels per TLC5974 + for (int8_t c = 24 * numdrivers - 1; c >= 0 ; c--) { + // 12 bits per channel, send MSB first + for (int8_t b = 11; b >= 0; b--) { + digitalWriteFast(LED_CLOCK, LOW); + + if (pwmbuffer[c] & (1 << b)) { + digitalWriteFast(LED_DATA, HIGH); + } + else { + digitalWriteFast(LED_DATA, LOW); + } + digitalWriteFast(LED_CLOCK, HIGH); + } + } + digitalWriteFast(LED_CLOCK, LOW); + + digitalWriteFast(LED_LATCH, HIGH); + digitalWriteFast(LED_LATCH, LOW); +} + + + +void Adafruit_TLC5947::setPWM(uint8_t chan, uint16_t pwm) { + if (pwm > 4095) pwm = 4095; + if (chan > 24 * numdrivers) return; + pwmbuffer[chan] = pwm; +} + + +void Adafruit_TLC5947::setLED(uint8_t lednum, uint16_t r, uint16_t g, uint16_t b) { + setPWM(lednum * 3, r); + setPWM(lednum * 3 + 1, g); + setPWM(lednum * 3 + 2, b); +} + + +boolean Adafruit_TLC5947::begin() { + if (!pwmbuffer) return false; + + pinModeFast(LED_DATA, OUTPUT); + pinModeFast(LED_CLOCK, OUTPUT); + pinModeFast(LED_LATCH, OUTPUT); + + digitalWriteFast(LED_LATCH, LOW); + + return true; +} diff --git a/pool/shard007/C++/0095566_ie_imp_GOChart.cpp b/pool/shard007/C++/0095566_ie_imp_GOChart.cpp new file mode 100644 index 0000000000000000000000000000000000000000..208d9c8badc768123da48f9b878cbe3daeaac5d1 --- /dev/null +++ b/pool/shard007/C++/0095566_ie_imp_GOChart.cpp @@ -0,0 +1,211 @@ +/* -*- mode: C++; tab-width: 4; c-basic-offset: 4; -*- */ + +/* AbiWord + * Copyright (C) 1998 AbiSource, Inc. + * Copyright (C) 2003 Tomas Frydrych + * Copyright (C) 2004 Martin Sevior + * + * 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 "ut_types.h" +#include "ut_assert.h" +#include "ut_debugmsg.h" +#include "ut_string.h" +#include "ut_iconv.h" +#include "ie_imp_GOChart.h" +#include "pd_Document.h" + +#include "xap_EncodingManager.h" + + +#include "ap_Dialog_Id.h" +#include "xap_DialogFactory.h" +#include "xap_Dlg_Encoding.h" +#include "ap_Prefs.h" +#include "ie_imp_Text.h" +#include "xap_Frame.h" +#include "xap_UnixFrameImpl.h" +#include "fv_View.h" + +/*****************************************************************/ +/*****************************************************************/ + +IE_Imp_Object_Sniffer::IE_Imp_Object_Sniffer () + : IE_ImpSniffer(IE_IMPEXPNAME_GOCHART, true) +{ + // +} + +// supported suffixes +static IE_SuffixConfidence IE_Imp_Object_Sniffer__SuffixConfidence[] = { + { "xml", UT_CONFIDENCE_GOOD }, + { "", UT_CONFIDENCE_ZILCH } +}; + +const IE_SuffixConfidence * IE_Imp_Object_Sniffer::getSuffixConfidence () +{ + return IE_Imp_Object_Sniffer__SuffixConfidence; +} + +// supported mimetypes +static IE_MimeConfidence IE_Imp_Object_Sniffer__MimeConfidence[] = { + { IE_MIME_MATCH_FULL, "application/x-goffice-graph", UT_CONFIDENCE_PERFECT }, + { IE_MIME_MATCH_FULL, "application/xml", UT_CONFIDENCE_GOOD }, + { IE_MIME_MATCH_BOGUS, "", UT_CONFIDENCE_ZILCH } +}; + +const IE_MimeConfidence * IE_Imp_Object_Sniffer::getMimeConfidence () +{ + return IE_Imp_Object_Sniffer__MimeConfidence; +} + +/*! + Check if buffer contains data meant for this importer. + + We don't attmpt to recognize since other filetypes (HTML) can + use the same encodings a text file can. + We also don't want to steal recognition when user wants to use + the Encoded Text importer. + */ +UT_Confidence_t IE_Imp_Object_Sniffer::recognizeContents(const char * szBuf, + G_GNUC_UNUSED UT_uint32 iNumbytes) +{ + const char * magic1 = ""; + + xxx_UT_DEBUGMSG(("magic1 = %s \n",magic1)); + xxx_UT_DEBUGMSG(("magic2 = %s \n",magic2)); + if((strstr(szBuf,magic1) != NULL) && (strstr(szBuf,magic2) != NULL)) + return UT_CONFIDENCE_PERFECT; + return UT_CONFIDENCE_ZILCH; + + +} + +UT_Error IE_Imp_Object_Sniffer::constructImporter(PD_Document * pDocument, + IE_Imp ** ppie) +{ + IE_Imp_Object * p = new IE_Imp_Object(pDocument); + *ppie = p; + return UT_OK; +} + +bool IE_Imp_Object_Sniffer::getDlgLabels(G_GNUC_UNUSED const char ** pszDesc, + G_GNUC_UNUSED const char ** pszSuffixList, + G_GNUC_UNUSED IEFileType * ft) +{ +/* *pszDesc = "GNOME Office Chart (.xml)"; + *pszSuffixList = "*.xml"; + *ft = getFileType(); */ + return false; +} + +/*****************************************************************/ +/*****************************************************************/ + +#define X_CleanupIfError(error,exp) do { if (((error)=(exp)) != UT_OK) goto Cleanup; } while (0) + +/* + Import Object data from a plain text file + \param szFilename Name of file to import + Simply fills a UT_byteBuf with the contents of the Object +*/ +UT_Error IE_Imp_Object::_loadFile(GsfInput * fp) +{ + ImportStreamFile * pStream = new ImportStreamFile(fp); + UT_Error error; + + + pStream->init(NULL); + X_CleanupIfError(error,_parseStream(pStream)); + error = UT_OK; + +Cleanup: + delete pStream; + return error; +} + +#undef X_CleanupIfError + +/*****************************************************************/ +/*****************************************************************/ + +/* + Construct text importer + \param pDocument Document to import Object into + + Uses current document's encoding if it is set +*/ +IE_Imp_Object::IE_Imp_Object(PD_Document * pDocument) + : IE_Imp(pDocument),m_pByteBuf(NULL) +{ + m_pByteBuf = new UT_ByteBuf; + +} + +IE_Imp_Object::~IE_Imp_Object(void) +{ + DELETEP(m_pByteBuf); +} + +/*****************************************************************/ + +#define X_ReturnIfFail(exp,error) do { bool b = (exp); if (!b) return (error); } while (0) +#define X_ReturnNoMemIfError(exp) X_ReturnIfFail(exp,UT_IE_NOMEMORY) + + +/*! + Parse stream contents into the document + \param stream Stream to import from + + This code is used for both files and the clipboard + */ +UT_Error IE_Imp_Object::_parseStream(ImportStream * pStream) +{ + UT_return_val_if_fail(pStream, UT_ERROR); + XAP_Frame *pFrame = XAP_App::getApp()->getLastFocussedFrame(); + FV_View* pView = static_cast(pFrame->getCurrentView()); + + UT_UCSChar c; + unsigned char uc; + while (pStream->getChar(c)) + { + uc = static_cast(c); + m_pByteBuf->append(&uc,1); + } + const char* mimetypeGOChart = "application/x-goffice-graph"; + const char * szProps="embed-type: GOChart"; + PT_DocPosition pos = pView->getPoint(); + pView->cmdInsertEmbed(m_pByteBuf,pView->getPoint(),mimetypeGOChart,szProps); + pView->cmdSelect(pos,pos+1); + + return UT_OK; +} + +bool IE_Imp_Object::pasteFromBuffer(PD_DocumentRange * pDocRange, + const unsigned char * pData, UT_uint32 lenData, + const char * /* encoding */) +{ + UT_return_val_if_fail(getDoc() == pDocRange->m_pDoc,false); + UT_return_val_if_fail(pDocRange->m_pos1 == pDocRange->m_pos2,false); + + ImportStreamClipboard stream(pData, lenData); + setClipboard (pDocRange->m_pos1); + stream.init(NULL); + _parseStream(&stream); + return true; +} diff --git a/pool/shard007/C++/0095567_IO_SpecularHighlights.cpp b/pool/shard007/C++/0095567_IO_SpecularHighlights.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d5ce3c5f3296679ec2df284ad6ad3e22189b156 --- /dev/null +++ b/pool/shard007/C++/0095567_IO_SpecularHighlights.cpp @@ -0,0 +1,76 @@ +#include +#include + +#include +#include +#include + +bool SpecularHighlights_readLocalData(osg::Object &obj, osgDB::Input &fr); +bool SpecularHighlights_writeLocalData(const osg::Object &obj, osgDB::Output &fw); + +REGISTER_DOTOSGWRAPPER(SpecularHighlights_Proxy) +( + new osgFX::SpecularHighlights, + "osgFX::SpecularHighlights", + "Object Node Group osgFX::Effect osgFX::SpecularHighlights", + SpecularHighlights_readLocalData, + SpecularHighlights_writeLocalData +); + +bool SpecularHighlights_readLocalData(osg::Object &obj, osgDB::Input &fr) +{ + osgFX::SpecularHighlights &myobj = static_cast(obj); + bool itAdvanced = false; + + if (fr[0].matchWord("lightNumber")) { + int n; + if (fr[1].getInt(n)) { + myobj.setLightNumber(n); + fr += 2; + itAdvanced = true; + } + } + + if (fr[0].matchWord("textureUnit")) { + int n; + if (fr[1].getInt(n)) { + myobj.setTextureUnit(n); + fr += 2; + itAdvanced = true; + } + } + + if (fr[0].matchWord("specularColor")) { + osg::Vec4 w; + if (fr[1].getFloat(w.x()) && fr[2].getFloat(w.y()) && + fr[3].getFloat(w.z()) && fr[4].getFloat(w.w())) { + myobj.setSpecularColor(w); + fr += 5; + itAdvanced = true; + } + } + + if (fr[0].matchWord("specularExponent")) { + float f; + if (fr[1].getFloat(f)) { + myobj.setSpecularExponent(f); + fr += 2; + itAdvanced = true; + } + } + + + return itAdvanced; +} + +bool SpecularHighlights_writeLocalData(const osg::Object &obj, osgDB::Output &fw) +{ + const osgFX::SpecularHighlights &myobj = static_cast(obj); + + fw.indent() << "lightNumber " << myobj.getLightNumber() << "\n"; + fw.indent() << "textureUnit " << myobj.getTextureUnit() << "\n"; + fw.indent() << "specularColor " << myobj.getSpecularColor() << "\n"; + fw.indent() << "specularExponent " << myobj.getSpecularExponent() << "\n"; + + return true; +} diff --git a/pool/shard007/C++/0095568_ServiceWin32.cpp b/pool/shard007/C++/0095568_ServiceWin32.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58725759329d69a10c0c0e8e8e85de7f55a2e134 --- /dev/null +++ b/pool/shard007/C++/0095568_ServiceWin32.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (C) 2013-2015 DeathCore + * Copyright (C) 2005-2009 MaNGOS + * + * 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, see . + */ + +#ifdef _WIN32 + +#include "Common.h" +#include "Log.h" +#include +#include +#include + +// stupid ACE define +#ifdef main +#undef main +#endif //main + +#if !defined(WINADVAPI) +#if !defined(_ADVAPI32_) +#define WINADVAPI DECLSPEC_IMPORT +#else +#define WINADVAPI +#endif +#endif + +extern int main(int argc, char ** argv); +extern char serviceLongName[]; +extern char serviceName[]; +extern char serviceDescription[]; + +extern int m_ServiceStatus; + +SERVICE_STATUS serviceStatus; + +SERVICE_STATUS_HANDLE serviceStatusHandle = 0; + +typedef WINADVAPI BOOL (WINAPI *CSD_T)(SC_HANDLE, DWORD, LPCVOID); + +bool WinServiceInstall() +{ + SC_HANDLE serviceControlManager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); + + if (serviceControlManager) + { + char path[_MAX_PATH + 10]; + if (GetModuleFileName( 0, path, sizeof(path)/sizeof(path[0]) ) > 0) + { + SC_HANDLE service; + std::strcat(path, " --service"); + service = CreateService(serviceControlManager, + serviceName, // name of service + serviceLongName, // service name to display + SERVICE_ALL_ACCESS, // desired access + // service type + SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, + SERVICE_AUTO_START, // start type + SERVICE_ERROR_IGNORE, // error control type + path, // service's binary + 0, // no load ordering group + 0, // no tag identifier + 0, // no dependencies + 0, // LocalSystem account + 0); // no password + if (service) + { + HMODULE advapi32 = GetModuleHandle("ADVAPI32.DLL"); + if (!advapi32) + { + CloseServiceHandle(service); + CloseServiceHandle(serviceControlManager); + return false; + } + + CSD_T ChangeService_Config2 = (CSD_T) GetProcAddress(advapi32, "ChangeServiceConfig2A"); + if (!ChangeService_Config2) + { + CloseServiceHandle(service); + CloseServiceHandle(serviceControlManager); + return false; + } + + SERVICE_DESCRIPTION sdBuf; + sdBuf.lpDescription = serviceDescription; + ChangeService_Config2( + service, // handle to service + SERVICE_CONFIG_DESCRIPTION, // change: description + &sdBuf); // new data + + SC_ACTION _action[1]; + _action[0].Type = SC_ACTION_RESTART; + _action[0].Delay = 10000; + SERVICE_FAILURE_ACTIONS sfa; + ZeroMemory(&sfa, sizeof(SERVICE_FAILURE_ACTIONS)); + sfa.lpsaActions = _action; + sfa.cActions = 1; + sfa.dwResetPeriod =INFINITE; + ChangeService_Config2( + service, // handle to service + SERVICE_CONFIG_FAILURE_ACTIONS, // information level + &sfa); // new data + + CloseServiceHandle(service); + + } + } + CloseServiceHandle(serviceControlManager); + } + return true; +} + +bool WinServiceUninstall() +{ + SC_HANDLE serviceControlManager = OpenSCManager(0, 0, SC_MANAGER_CONNECT); + + if (serviceControlManager) + { + SC_HANDLE service = OpenService(serviceControlManager, + serviceName, SERVICE_QUERY_STATUS | DELETE); + if (service) + { + SERVICE_STATUS serviceStatus2; + if (QueryServiceStatus(service, &serviceStatus2)) + { + if (serviceStatus2.dwCurrentState == SERVICE_STOPPED) + DeleteService(service); + } + CloseServiceHandle(service); + } + + CloseServiceHandle(serviceControlManager); + } + return true; +} + +void WINAPI ServiceControlHandler(DWORD controlCode) +{ + switch (controlCode) + { + case SERVICE_CONTROL_INTERROGATE: + break; + + case SERVICE_CONTROL_SHUTDOWN: + case SERVICE_CONTROL_STOP: + serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + + m_ServiceStatus = 0; + return; + + case SERVICE_CONTROL_PAUSE: + m_ServiceStatus = 2; + serviceStatus.dwCurrentState = SERVICE_PAUSED; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + break; + + case SERVICE_CONTROL_CONTINUE: + serviceStatus.dwCurrentState = SERVICE_RUNNING; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + m_ServiceStatus = 1; + break; + + default: + if ( controlCode >= 128 && controlCode <= 255 ) + // user defined control code + break; + else + // unrecognized control code + break; + } + + SetServiceStatus(serviceStatusHandle, &serviceStatus); +} + +void WINAPI ServiceMain(DWORD argc, char *argv[]) +{ + // initialise service status + serviceStatus.dwServiceType = SERVICE_WIN32; + serviceStatus.dwCurrentState = SERVICE_START_PENDING; + serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; + serviceStatus.dwWin32ExitCode = NO_ERROR; + serviceStatus.dwServiceSpecificExitCode = NO_ERROR; + serviceStatus.dwCheckPoint = 0; + serviceStatus.dwWaitHint = 0; + + serviceStatusHandle = RegisterServiceCtrlHandler(serviceName, ServiceControlHandler); + + if ( serviceStatusHandle ) + { + char path[_MAX_PATH + 1]; + unsigned int i, last_slash = 0; + + GetModuleFileName(0, path, sizeof(path)/sizeof(path[0])); + + for (i = 0; i < std::strlen(path); i++) + { + if (path[i] == '\\') last_slash = i; + } + + path[last_slash] = 0; + + // service is starting + serviceStatus.dwCurrentState = SERVICE_START_PENDING; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + + // do initialisation here + SetCurrentDirectory(path); + + // running + serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); + serviceStatus.dwCurrentState = SERVICE_RUNNING; + SetServiceStatus( serviceStatusHandle, &serviceStatus ); + + //////////////////////// + // service main cycle // + //////////////////////// + + m_ServiceStatus = 1; + argc = 1; + main(argc, argv); + + // service was stopped + serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + + // do cleanup here + + // service is now stopped + serviceStatus.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); + serviceStatus.dwCurrentState = SERVICE_STOPPED; + SetServiceStatus(serviceStatusHandle, &serviceStatus); + } +} + +bool WinServiceRun() +{ + SERVICE_TABLE_ENTRY serviceTable[] = + { + { serviceName, ServiceMain }, + { 0, 0 } + }; + + if (!StartServiceCtrlDispatcher(serviceTable)) + { + sLog->outError(LOG_FILTER_WORLDSERVER, "StartService Failed. Error [%u]", ::GetLastError()); + return false; + } + return true; +} +#endif + diff --git a/pool/shard007/C++/0095570_TextSeriesProperty.cpp b/pool/shard007/C++/0095570_TextSeriesProperty.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57608da0287c6b52d28185d6e248e19f2a9acefc --- /dev/null +++ b/pool/shard007/C++/0095570_TextSeriesProperty.cpp @@ -0,0 +1,120 @@ +// TextSeriesProperty.cpp : implementation file +// + +#include "stdafx.h" +#include "DebugPlotViewer.h" +#include "TextSeriesProperty.h" +#include "SeriesText.h" + +// TextSeriesProperty + +IMPLEMENT_DYNAMIC(TextSeriesProperty, BaseProperty) + +TextSeriesProperty::TextSeriesProperty() +{ + +} + +TextSeriesProperty::~TextSeriesProperty() +{ +} + + +BEGIN_MESSAGE_MAP(TextSeriesProperty, BaseProperty) + ON_WM_CREATE() +END_MESSAGE_MAP() + + + +// TextSeriesProperty message handlers + + + + +int TextSeriesProperty::OnCreate(LPCREATESTRUCT lpCreateStruct) +{ + if (BaseProperty::OnCreate(lpCreateStruct) == -1) + return -1; + + // TODO: Add your specialized creation code here + TextSeriesProp * seriesProp = (TextSeriesProp *)this->target; + + ASSERT(seriesProp != 0); + + CMFCPropertyGridProperty * pProp; + + pProp = new CMFCPropertyGridProperty(_T("Type"), _T("Text Channel")); + + pProp->Enable(FALSE); + this->AddProperty(pProp); + + pProp = new CMFCPropertyGridProperty(_T("Name"), seriesProp->name); + pProp->Enable(FALSE); + this->AddProperty(pProp); + + //pProp = new CMFCPropertyGridProperty( _T("Frame Count"), (_variant_t) seriesProp->frameCount, _T("Number of frames per screen")); + //this->AddProperty(pProp); + + CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("Color"), seriesProp->color, NULL); + pColorProp->EnableOtherButton(_T("Other...")); + pColorProp->EnableAutomaticButton(_T("Default"), ::GetSysColor(COLOR_3DFACE)); + this->AddProperty(pColorProp); + + //if (!seriesProp->isLog) + //{ + // CString strMode; + // if (seriesProp->replaceMode) + // strMode.SetString(L"Replace"); + // else + // strMode.SetString(L"Append"); + + // pProp = new CMFCPropertyGridProperty(_T("Display Mode"), strMode.GetBuffer()); + // pProp->AddOption(_T("Replace")); + // pProp->AddOption(_T("Append")); + // pProp->AllowEdit(FALSE); + // this->AddProperty(pProp); + //} + + return 0; +} + + +void TextSeriesProperty::OnPropertyChanged(CMFCPropertyGridProperty* pProp) const +{ + // TODO: Add your specialized code here and/or call the base class + TextSeriesProp * seriesProp = (TextSeriesProp *)this->target; + + if (wcscmp(pProp->GetName(), L"Color") == 0) + { + COLORREF color = ((CMFCPropertyGridColorProperty *)pProp)->GetColor(); + seriesProp->color = color; + //seriesProp->colorIsSet = true; + } + //else if (wcscmp(pProp->GetName(), L"Display Mode") == 0) + //{ + // _variant_t value = pProp->GetValue(); + // if (wcscmp(value.bstrVal, L"Replace") == 0) + // { + // seriesProp->replaceMode = true; + // } + // else + // { + // seriesProp->replaceMode = false; + // } + // //if (seriesProp->smSeriesInfo) + // //{ + // // SharedSeriesInfo * sharedSeriesInfo = + // // (SharedSeriesInfo *)seriesProp->smSeriesInfo->GetAddress(); + // // sharedSeriesInfo->replace = seriesProp->replaceMode; + // //} + //} + else + { + ASSERT(false); // impossible + } + + + seriesProp->ForceUpdateGraph(); + + return BaseProperty::OnPropertyChanged(pProp); +} diff --git a/pool/shard007/C++/0095573_app_remoting_test_driver.cc b/pool/shard007/C++/0095573_app_remoting_test_driver.cc new file mode 100644 index 0000000000000000000000000000000000000000..57f2947017bc22435c7f517d3f87af1965893129 --- /dev/null +++ b/pool/shard007/C++/0095573_app_remoting_test_driver.cc @@ -0,0 +1,232 @@ +// 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 "base/bind.h" +#include "base/command_line.h" +#include "base/logging.h" +#include "base/strings/stringprintf.h" +#include "base/test/launcher/unit_test_launcher.h" +#include "base/test/test_suite.h" +#include "base/test/test_switches.h" +#include "google_apis/google_api_keys.h" +#include "net/base/escape.h" +#include "remoting/test/app_remoting_test_driver_environment.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace switches { +const char kAuthCodeSwitchName[] = "authcode"; +const char kHelpSwitchName[] = "help"; +const char kLoggingLevelSwitchName[] = "verbosity"; +const char kServiceEnvironmentSwitchName[] = "environment"; +const char kShowHostAvailabilitySwitchName[] = "show-host-availability"; +const char kSingleProcessTestsSwitchName[] = "single-process-tests"; +const char kUserNameSwitchName[] = "username"; +} + +namespace { + +// Requested permissions needed for App Remoting tests. The spaces in between +// scope fragments are necessary and will be escaped properly before use. +const char kAppRemotingAuthScopeValues[] = + "https://www.googleapis.com/auth/appremoting.runapplication" + " https://www.googleapis.com/auth/googletalk" + " https://www.googleapis.com/auth/userinfo.email" + " https://docs.google.com/feeds" + " https://www.googleapis.com/auth/drive"; + +std::string GetAuthorizationCodeUri() { + // Replace space characters with a '+' sign when formatting. + bool use_plus = true; + return base::StringPrintf( + "https://accounts.google.com/o/oauth2/auth" + "?scope=%s" + "&redirect_uri=https://chromoting-oauth.talkgadget.google.com/" + "talkgadget/oauth/chrome-remote-desktop/dev" + "&response_type=code" + "&client_id=%s" + "&access_type=offline" + "&approval_prompt=force", + net::EscapeUrlEncodedData(kAppRemotingAuthScopeValues, use_plus).c_str(), + net::EscapeUrlEncodedData( + google_apis::GetOAuth2ClientID(google_apis::CLIENT_REMOTING), + use_plus).c_str()); +} + +void PrintUsage() { + printf("\n**************************************\n"); + printf("*** App Remoting Test Driver Usage ***\n"); + printf("**************************************\n"); + + printf("\nUsage:\n"); + printf(" ar_test_driver --username= [options]\n"); + printf("\nRequired Parameters:\n"); + printf(" %s: Specifies which account to use when running tests\n", + switches::kUserNameSwitchName); + printf("\nOptional Parameters:\n"); + printf(" %s: Exchanged for a refresh and access token for authentication\n", + switches::kAuthCodeSwitchName); + printf(" %s: Displays additional usage information\n", + switches::kHelpSwitchName); + printf(" %s: Specifies the service api to use (dev|test) [default: dev]\n", + switches::kServiceEnvironmentSwitchName); + printf( + " %s: Retrieves and displays the connection status for all known " + "hosts, no tests will be run\n", + switches::kShowHostAvailabilitySwitchName); + printf( + " %s: Specifies the optional logging level of the tool (0-3)." + " [default: off]\n", + switches::kLoggingLevelSwitchName); +} + +void PrintAuthCodeInfo() { + printf("\n*******************************\n"); + printf("*** Auth Code Example Usage ***\n"); + printf("*******************************\n\n"); + + printf("If this is the first time you are running the tool,\n"); + printf("you will need to provide an authorization code.\n"); + printf("This code will be exchanged for a long term refresh token which\n"); + printf("will be stored locally and used to acquire a short lived access\n"); + printf("token to connect to the remoting service apis and establish a\n"); + printf("remote host connection.\n\n"); + + printf("Note: You may need to repeat this step if the stored refresh token"); + printf("\n has been revoked or expired.\n"); + printf(" Passing in the same auth code twice will result in an error\n"); + + printf( + "\nFollow these steps to produce an auth code:\n" + " - Open the Authorization URL link shown below in your browser\n" + " - Approve the requested permissions for the tool\n" + " - Copy the 'code' value in the redirected URL\n" + " - Run the tool and pass in copied auth code as a parameter\n"); + + printf("\nAuthorization URL:\n"); + printf("%s\n", GetAuthorizationCodeUri().c_str()); + + printf("\nRedirected URL Example:\n"); + printf( + "https://chromoting-oauth.talkgadget.google.com/talkgadget/oauth/" + "chrome-remote-desktop/dev?code=4/AKtf...\n"); + + printf("\nTool usage example with the newly created auth code:\n"); + printf("ar_test_driver --%s=example@gmail.com --%s=4/AKtf...\n\n", + switches::kUserNameSwitchName, switches::kAuthCodeSwitchName); +} + +} // namespace + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + TestSuite test_suite(argc, argv); + + // The pointer returned here refers to a singleton, since we don't own the + // lifetime of the object, don't wrap in a scoped_ptr construct or release it. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + DCHECK(command_line); + + // We do not want to retry failures as a failed test should signify an error + // to be investigated. + command_line->AppendSwitchASCII(switches::kTestLauncherRetryLimit, "0"); + + // We do not want to run the tests in parallel and we do not want to retry + // failures. The reason for running in a single process is that some tests + // may share the same remoting host and they cannot be run concurrently, also + // the test output gets spammed with test launcher messages which reduces the + // readability of the results. + command_line->AppendSwitch(switches::kSingleProcessTestsSwitchName); + + // If the user passed in the help flag, then show the help info for this tool + // and 'run' the tests which will print the gtest specific help and then exit. + // NOTE: We do this check after updating the switches as otherwise the gtest + // help is written in parallel with our text and can appear interleaved. + if (command_line->HasSwitch(switches::kHelpSwitchName)) { + PrintUsage(); + PrintAuthCodeInfo(); + return base::LaunchUnitTestsSerially( + argc, argv, + base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); + } + + // Verify we received the required input from the command line. + if (!command_line->HasSwitch(switches::kUserNameSwitchName)) { + LOG(ERROR) << "No user name passed in, can't authenticate without that!"; + PrintUsage(); + return -1; + } + + std::string user_name; + user_name = command_line->GetSwitchValueASCII(switches::kUserNameSwitchName); + DVLOG(1) << "Running tests as: " << user_name; + + std::string auth_code; + // Check to see if the user passed in a one time use auth_code for + // refreshing their credentials. + auth_code = command_line->GetSwitchValueASCII(switches::kAuthCodeSwitchName); + + // If the user passed in a service environment, use it, otherwise set a + // default value. + remoting::test::ServiceEnvironment service_environment; + std::string service_environment_switch = command_line->GetSwitchValueASCII( + switches::kServiceEnvironmentSwitchName); + if (service_environment_switch.empty() || + service_environment_switch == "dev") { + service_environment = + remoting::test::ServiceEnvironment::kDeveloperEnvironment; + } else if (service_environment_switch == "test") { + service_environment = + remoting::test::ServiceEnvironment::kTestingEnvironment; + } else { + LOG(ERROR) << "Invalid " << switches::kServiceEnvironmentSwitchName + << " argument passed in."; + PrintUsage(); + return -1; + } + + // Update the logging verbosity level is user specified one. + std::string verbosity_level; + verbosity_level = + command_line->GetSwitchValueASCII(switches::kLoggingLevelSwitchName); + if (!verbosity_level.empty()) { + // Turn on logging for the test_driver and remoting components. + // This switch is parsed during logging::InitLogging. + command_line->AppendSwitchASCII("vmodule", + "*/remoting/*=" + verbosity_level); + logging::LoggingSettings logging_settings; + logging::InitLogging(logging_settings); + } + + // Create and register our global test data object. It will handle + // retrieving an access token for the user and spinning up VMs. + // The GTest framework will own the lifetime of this object once + // it is registered below. + scoped_ptr shared_data; + + shared_data.reset(new remoting::test::AppRemotingTestDriverEnvironment( + user_name, service_environment)); + + if (!shared_data->Initialize(auth_code)) { + // If we failed to initialize our shared data object, then bail. + return -1; + } + + if (command_line->HasSwitch(switches::kShowHostAvailabilitySwitchName)) { + // When this flag is specified, we will retrieve connection information + // for all known applications and report the status. No tests will be run. + shared_data->ShowHostAvailability(); + return 0; + } + + // Since we've successfully set up our shared_data object, we'll assign the + // value to our global* and transfer ownership to the framework. + remoting::test::AppRemotingSharedData = shared_data.release(); + testing::AddGlobalTestEnvironment(remoting::test::AppRemotingSharedData); + + // Because many tests may access the same remoting host(s), we need to run + // the tests sequentially so they do not interfere with each other. + return base::LaunchUnitTestsSerially( + argc, argv, + base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); +} diff --git a/pool/shard007/C++/0095578_start_u8_process.cpp b/pool/shard007/C++/0095578_start_u8_process.cpp new file mode 100644 index 0000000000000000000000000000000000000000..636e0b72e5dd80ef0b5911a3c8ef80694fb75f74 --- /dev/null +++ b/pool/shard007/C++/0095578_start_u8_process.cpp @@ -0,0 +1,124 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "ultima/ultima8/games/start_u8_process.h" +#include "ultima/ultima8/games/game.h" +#include "ultima/ultima8/world/loop_script.h" +#include "ultima/ultima8/usecode/uc_list.h" +#include "ultima/ultima8/world/current_map.h" +#include "ultima/ultima8/world/egg.h" +#include "ultima/ultima8/world/camera_process.h" +#include "ultima/ultima8/world/world.h" +#include "ultima/ultima8/ultima8.h" +#include "ultima/ultima8/kernel/kernel.h" +#include "ultima/ultima8/gumps/menu_gump.h" +#include "ultima/ultima8/world/get_object.h" +#include "ultima/ultima8/graphics/palette_fader_process.h" + +namespace Ultima { +namespace Ultima8 { + +// p_dynamic_cast stuff +DEFINE_RUNTIME_CLASSTYPE_CODE(StartU8Process) + +StartU8Process::StartU8Process(int saveSlot) : Process(), + _init(false), _saveSlot(saveSlot), _skipStart(saveSlot >= 0) { +} + + +void StartU8Process::run() { + if (!_skipStart && !_init) { + _init = true; + ProcId moviepid = Game::get_instance()->playIntroMovie(false); + Process *movieproc = Kernel::get_instance()->getProcess(moviepid); + if (movieproc) { + waitFor(movieproc); + return; + } + } + + // Try to load the save game, if succeeded this pointer will no longer be valid + if (_saveSlot >= 0 &&Ultima8Engine::get_instance()->loadGameState(_saveSlot).getCode() == Common::kNoError) { + PaletteFaderProcess::I_fadeFromBlack(0, 0); + return; + } + + CurrentMap *currentmap = World::get_instance()->getCurrentMap(); + UCList uclist(2); + + if (!_skipStart) { + LOOPSCRIPT(script, LS_AND(LS_SHAPE_EQUAL1(73), LS_Q_EQUAL(36))); + currentmap->areaSearch(&uclist, script, sizeof(script), + 0, 256, false, 16188, 7500); + if (uclist.getSize() < 1) { + perr << "Unable to find FIRST egg!" << Std::endl; + return; + } + + uint16 objid = uclist.getuint16(0); + Egg *egg = dynamic_cast(getObject(objid)); + int32 ix, iy, iz; + egg->getLocation(ix, iy, iz); + // Center on egg + CameraProcess::SetCameraProcess(new CameraProcess(ix, iy, iz)); + egg->hatch(); + } + + // Music Egg + // Item 2145 (class Item, shape 562, 0, (11551,2079,48) q:52, m:0, n:0, f:2000, ef:2) + uclist.free(); + LOOPSCRIPT(musicscript, LS_SHAPE_EQUAL1(562)); + currentmap->areaSearch(&uclist, musicscript, sizeof(musicscript), + 0, 256, false, 11551, 2079); + + if (uclist.getSize() < 1) { + perr << "Unable to find MUSIC egg!" << Std::endl; + } else { + ObjId objid = uclist.getuint16(0); + Item *musicEgg = getItem(objid); + musicEgg->callUsecodeEvent_cachein(); + } + + if (!_skipStart) + MenuGump::inputName(); + else + Ultima8Engine::get_instance()->setAvatarInStasis(false); + + + terminate(); +} + +void StartU8Process::saveData(Common::WriteStream *ws) { + CANT_HAPPEN(); + + Process::saveData(ws); +} + +bool StartU8Process::loadData(Common::ReadStream *rs, uint32 version) { + if (!Process::loadData(rs, version)) return false; + + return true; +} + +} // End of namespace Ultima8 +} // End of namespace Ultima diff --git a/pool/shard007/C++/0095582_MatchMaker.cpp b/pool/shard007/C++/0095582_MatchMaker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5908233d7800760b7e323ab0015e4d5e0993df46 --- /dev/null +++ b/pool/shard007/C++/0095582_MatchMaker.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include + +using namespace std; + +struct member { + string name; + int sf; + bool gend, want; + member() { + sf = 0; + } +}; +bool operator<(const member &a, const member &b) { + return a.sf < b.sf; +} + +class MatchMaker { + public: + vector getBestMatches(vector memb, string who, int sf) { + vector match; + int a[50][10]; + int x; + int n; + + for (int i=0; i<(int)memb.size(); ++i) { + istringstream is(memb[i]); + string t; + is >> match[i].name; + if (match[i].name == who) + x = i; + is >> t; + match[i].gend = t[0]=='M'; + is >> t; + match[i].want = t[0]=='M'; + for (n=0; is >> t; ++n) + a[i][n] = t[0]; + } + vector sol; + for (int i=0; i<(int)memb.size(); ++i) + if (i!=x) { + int cnt = 0; + for (int j=0; j= sf) { + match[i].sf = cnt; + sol.push_back(match[i]); + } + } + stable_sort(sol.begin(), sol.end()); + vector ret; + for (int i=0; i<(int)sol.size(); ++i) + ret.push_back(sol[i].name); + return ret; + } + + + + + + + + + // *** WARNING *** No test cases defined for this problem +}; + +// BEGIN CUT HERE +int main() + { + MatchMaker ___test; + ___test.run_test(-1); + } +// END CUT HERE diff --git a/pool/shard007/C++/0095588_prerender_resource_throttle.cc b/pool/shard007/C++/0095588_prerender_resource_throttle.cc new file mode 100644 index 0000000000000000000000000000000000000000..5636de8c0bea8b245baa28d7afa752f48e1fb33d --- /dev/null +++ b/pool/shard007/C++/0095588_prerender_resource_throttle.cc @@ -0,0 +1,165 @@ +// 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 "chrome/browser/prerender/prerender_resource_throttle.h" + +#include "chrome/browser/prerender/prerender_final_status.h" +#include "chrome/browser/prerender/prerender_manager.h" +#include "chrome/browser/prerender/prerender_util.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/resource_controller.h" +#include "content/public/browser/resource_request_info.h" +#include "content/public/browser/web_contents.h" +#include "net/url_request/url_request.h" + +namespace prerender { + +namespace { +static const char kFollowOnlyWhenPrerenderShown[] = + "follow-only-when-prerender-shown"; + +PrerenderContents* g_prerender_contents_for_testing; +} + +void PrerenderResourceThrottle::OverridePrerenderContentsForTesting( + PrerenderContents* contents) { + g_prerender_contents_for_testing = contents; +} + +PrerenderResourceThrottle::PrerenderResourceThrottle(net::URLRequest* request) + : request_(request) { +} + +void PrerenderResourceThrottle::WillStartRequest(bool* defer) { + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request_); + *defer = true; + content::BrowserThread::PostTask( + content::BrowserThread::UI, + FROM_HERE, + base::Bind(&PrerenderResourceThrottle::WillStartRequestOnUI, + AsWeakPtr(), request_->method(), info->GetResourceType(), + info->GetChildID(), info->GetRenderFrameID(), + request_->url())); +} + +void PrerenderResourceThrottle::WillRedirectRequest(const GURL& new_url, + bool* defer) { + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request_); + *defer = true; + std::string header; + request_->GetResponseHeaderByName(kFollowOnlyWhenPrerenderShown, &header); + + content::BrowserThread::PostTask( + content::BrowserThread::UI, + FROM_HERE, + base::Bind(&PrerenderResourceThrottle::WillRedirectRequestOnUI, + AsWeakPtr(), header, info->GetResourceType(), info->IsAsync(), + info->GetChildID(), info->GetRenderFrameID(), new_url)); +} + +const char* PrerenderResourceThrottle::GetNameForLogging() const { + return "PrerenderResourceThrottle"; +} + +void PrerenderResourceThrottle::Resume() { + controller()->Resume(); +} + +void PrerenderResourceThrottle::Cancel() { + controller()->Cancel(); +} + +void PrerenderResourceThrottle::WillStartRequestOnUI( + const base::WeakPtr& throttle, + const std::string& method, + ResourceType::Type resource_type, + int render_process_id, + int render_frame_id, + const GURL& url) { + bool cancel = false; + PrerenderContents* prerender_contents = + PrerenderContentsFromRenderFrame(render_process_id, render_frame_id); + if (prerender_contents) { + // Abort any prerenders that spawn requests that use unsupported HTTP + // methods or schemes. + if (!PrerenderManager::IsValidHttpMethod(method)) { + prerender_contents->Destroy(FINAL_STATUS_INVALID_HTTP_METHOD); + cancel = true; + } else if (!PrerenderManager::DoesSubresourceURLHaveValidScheme(url)) { + prerender_contents->Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME); + ReportUnsupportedPrerenderScheme(url); + cancel = true; +#if defined(OS_ANDROID) + } else if (resource_type == ResourceType::FAVICON) { + // Delay icon fetching until the contents are getting swapped in + // to conserve network usage in mobile devices. + prerender_contents->AddResourceThrottle(throttle); + return; +#endif + } + } + + content::BrowserThread::PostTask( + content::BrowserThread::IO, + FROM_HERE, + base::Bind(cancel ? &PrerenderResourceThrottle::Cancel : + &PrerenderResourceThrottle::Resume, throttle)); +} + +void PrerenderResourceThrottle::WillRedirectRequestOnUI( + const base::WeakPtr& throttle, + const std::string& follow_only_when_prerender_shown_header, + ResourceType::Type resource_type, + bool async, + int render_process_id, + int render_frame_id, + const GURL& new_url) { + bool cancel = false; + PrerenderContents* prerender_contents = + PrerenderContentsFromRenderFrame(render_process_id, render_frame_id); + if (prerender_contents) { + // Abort any prerenders with requests which redirect to invalid schemes. + if (!PrerenderManager::DoesURLHaveValidScheme(new_url)) { + prerender_contents->Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME); + ReportUnsupportedPrerenderScheme(new_url); + cancel = true; + } else if (follow_only_when_prerender_shown_header == "1" && + resource_type != ResourceType::MAIN_FRAME) { + // Only defer redirects with the Follow-Only-When-Prerender-Shown + // header. Do not defer redirects on main frame loads. + if (!async) { + // Cancel on deferred synchronous requests. Those will + // indefinitely hang up a renderer process. + prerender_contents->Destroy(FINAL_STATUS_BAD_DEFERRED_REDIRECT); + cancel = true; + } else { + // Defer the redirect until the prerender is used or canceled. + prerender_contents->AddResourceThrottle(throttle); + return; + } + } + } + + content::BrowserThread::PostTask( + content::BrowserThread::IO, + FROM_HERE, + base::Bind(cancel ? &PrerenderResourceThrottle::Cancel : + &PrerenderResourceThrottle::Resume, throttle)); +} + +PrerenderContents* PrerenderResourceThrottle::PrerenderContentsFromRenderFrame( + int render_process_id, int render_frame_id) { + if (g_prerender_contents_for_testing) + return g_prerender_contents_for_testing; + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + render_process_id, render_frame_id); + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + return PrerenderContents::FromWebContents(web_contents); +} + +} // namespace prerender diff --git a/pool/shard007/C++/0095589_1.cc b/pool/shard007/C++/0095589_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..83edbe11a8ce30e926ac96d946c8b65de146efb9 --- /dev/null +++ b/pool/shard007/C++/0095589_1.cc @@ -0,0 +1,54 @@ +// { dg-options "-std=gnu++0x" } +// { dg-require-string-conversions "" } + +// Copyright (C) 2011 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 Pred 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++/47773 +void test01() +{ + bool test __attribute__((unused)) = true; + + typedef __gnu_cxx::__wvstring vstring_t; + typedef std::unordered_map map_t; + + map_t mymap; + + mymap.insert(std::make_pair(L"hello", 10)); + mymap.insert(std::make_pair(L"hi", 20)); + + VERIFY( mymap.size() == 2 ); + + map_t::const_iterator imap1 = mymap.begin(); + map_t::const_iterator imap2 = mymap.begin(); + ++imap2; + + VERIFY( ((imap1->first == L"hello" && imap1->second == 10 + && imap2->first == L"hi" && imap2->second == 20) + || (imap1->first == L"hi" && imap1->second == 20 + && imap2->first == L"hello" && imap2->second == 10)) ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0095592_view_axis.cpp b/pool/shard007/C++/0095592_view_axis.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5145cd2077db309434d00ef1c937454c3b0d2a60 --- /dev/null +++ b/pool/shard007/C++/0095592_view_axis.cpp @@ -0,0 +1,40 @@ +// This file is part of libigl, a simple c++ geometry processing library. +// +// Copyright (C) 2013 Alec Jacobson +// +// This Source Code Form is subject to the terms of the Mozilla Public License +// v. 2.0. If a copy of the MPL was not distributed with this file, You can +// obtain one at http://mozilla.org/MPL/2.0/. +#include "view_axis.h" +#include "gl.h" + +IGL_INLINE void igl::opengl2::view_axis(double * x, double * y, double * z) +{ + double mv[16]; + glGetDoublev(GL_MODELVIEW_MATRIX, mv); + igl::opengl2::view_axis(mv,x,y,z); +} + +IGL_INLINE void igl::opengl2::view_axis(const double * mv, double * x, double * y, double * z) +{ + *x = -mv[0*4+2]; + *y = -mv[1*4+2]; + *z = -mv[2*4+2]; +} + +template +IGL_INLINE void igl::opengl2::view_axis(Eigen::PlainObjectBase & V) +{ + double x,y,z; + view_axis(&x,&y,&z); + V(0) = x; + V(1) = y; + V(2) = z; +} + +#ifdef IGL_STATIC_LIBRARY +// Explicit template instantiation +// generated by autoexplicit.sh +template void igl::opengl2::view_axis >(Eigen::PlainObjectBase >&); +template void igl::opengl2::view_axis >(Eigen::PlainObjectBase >&); +#endif diff --git a/pool/shard007/C++/0095603_SonyArw1Decompressor.cpp b/pool/shard007/C++/0095603_SonyArw1Decompressor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b711796dd15a6d518473e6a97dc42548f5a4a07 --- /dev/null +++ b/pool/shard007/C++/0095603_SonyArw1Decompressor.cpp @@ -0,0 +1,56 @@ +/* + RawSpeed - RAW file decoder. + + Copyright (C) 2017 Roman Lebedev + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "decompressors/SonyArw1Decompressor.h" // for SonyArw1Decompre... +#include "common/RawImage.h" // for RawImage +#include "common/RawspeedException.h" // for RawspeedException +#include "fuzz/Common.h" // for CreateRawImage +#include "io/Buffer.h" // for Buffer, DataBuffer +#include "io/ByteStream.h" // for ByteStream +#include "io/Endianness.h" // for Endianness, Endianness:: +#include // for assert +#include // for uint8_t +#include // for size_t + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size); + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { + assert(Data); + + try { + const rawspeed::Buffer b(Data, Size); + const rawspeed::DataBuffer db(b, rawspeed::Endianness::little); + rawspeed::ByteStream bs(db); + + rawspeed::RawImage mRaw(CreateRawImage(&bs)); + + rawspeed::SonyArw1Decompressor a(mRaw); + + mRaw->createData(); + + a.decompress(bs.getStream(bs.getRemainSize())); + + mRaw->checkMemIsInitialized(); + } catch (rawspeed::RawspeedException&) { + // Exceptions are good, crashes are bad. + } + + return 0; +} diff --git a/pool/shard007/C++/0095604_BitSparseDecoder.cpp b/pool/shard007/C++/0095604_BitSparseDecoder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..149928b479fbd8fc9fe3abf8bc4c0bc045d1ef9e --- /dev/null +++ b/pool/shard007/C++/0095604_BitSparseDecoder.cpp @@ -0,0 +1,247 @@ +/* Copyright (c) 2005, Regents of Massachusetts Institute of Technology, + * Brandeis University, Brown University, and University of Massachusetts + * Boston. 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 Massachusetts Institute of Technology, + * Brandeis University, Brown University, or University of + * Massachusetts Boston nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "BitSparseDecoder.h" + +BitSparseDecoder::BitSparseDecoder(bool valSorted_, unsigned short type_, int fieldSize_) : Decoder() { + if (type_ == ValPos::STRINGTYPE) { + outPair = new StringValPos(0,fieldSize_); + outBlock=new SparseBlock(valSorted_, true, true, outPair); + delete outPair; + } + else + outBlock=new SparseBlock(valSorted_, true, true, type_); + outPosBlock=new PosType2Block(); + posBlockBaseBlock = new Type2Block(valSorted_); + outPosBlock->setBlock(posBlockBaseBlock); + outPair=outBlock->vp; + fieldSize = fieldSize_; + reader.setStringSize(fieldSize_); + t2header=NULL; + currIter=NULL; +} +BitSparseDecoder::BitSparseDecoder(byte* buffer_, bool valSorted_, unsigned short type_, int fieldSize_) : Decoder(buffer_) { + if (type_ == ValPos::STRINGTYPE) { + outPair = new StringValPos(0,fieldSize_); + outBlock=new SparseBlock(valSorted_, true, true, outPair); + delete outPair; + } + else + outBlock=new SparseBlock(valSorted_, true, true, type_); + outPosBlock=new PosType2Block(); + posBlockBaseBlock = new Type2Block(valSorted_); + outPosBlock->setBlock(posBlockBaseBlock); + currIter=NULL; + fieldSize = fieldSize_; + reader.setStringSize(fieldSize_); + setBuffer(buffer_); + outPair=outBlock->vp; +} +BitSparseDecoder::BitSparseDecoder(BitSparseDecoder& decoder_) : Decoder(decoder_) { + reader=decoder_.reader; + numValsPtr=decoder_.numValsPtr; + startPosPtr=decoder_.startPosPtr; + endPosPtr=decoder_.endPosPtr; + fieldSize = decoder_.fieldSize; + outBlock=new SparseBlock(*decoder_.outBlock); + outPosBlock=new PosType2Block(*decoder_.outPosBlock); + posBlockBaseBlock = new Type2Block(*decoder_.posBlockBaseBlock); + outPosBlock->setBlock(posBlockBaseBlock); + outPair=outBlock->vp; + currIter=NULL; + setBuffer(decoder_.buffer); +} + +BitSparseDecoder::~BitSparseDecoder() +{ + delete outBlock; + delete outPosBlock; + delete posBlockBaseBlock; + delete currIter; +} + +void BitSparseDecoder::setBuffer(byte* buffer_) { + Decoder::setBuffer(buffer_); + if (buffer==NULL) throw new CodingException("IntDecoder: Error, buffer passed in is NULL"); + numValsPtr=(unsigned int*) buffer_; + startPosPtr=(unsigned int*) (buffer_+sizeof(int)); + endPosPtr=(unsigned int*) (buffer_+2*sizeof(int)); + currPos=*startPosPtr; + Log::writeToLog("IntDecoder", 1, "setBuffer(): buffer has numVals=", *numValsPtr); + Log::writeToLog("IntDecoder", 1, "setBuffer(): buffer has startPos=", *startPosPtr); + t2header = ((Type2Header*) (buffer_ + ((3*sizeof(int)) + ((*numValsPtr) * fieldSize)))); + + posBlockBaseBlock->setBufferWithHeader(buffer_ + ((3*sizeof(int)) + ((*numValsPtr) * fieldSize))); + delete currIter; + currIter = outPosBlock->getIterator(); + reader.setBuffer(buffer_+3*sizeof(int), 8*fieldSize*(*numValsPtr)); +} + +int BitSparseDecoder::getValueSize(){ + return 8*fieldSize; +} + +int BitSparseDecoder::getPageLengthBits() { + //Log::writeToLog("BitSparseDecoder", 0, "getPageLength returning leng=", 8*(2+((unsigned int) *numIntsPtr))*sizeof(int)); + return 8*( + 3*sizeof(int) + + (*numValsPtr)*fieldSize + + sizeof(Type2Header) + + (t2header->numValues)*sizeof(int)); +} + +bool BitSparseDecoder::hasNextBlock() { + if (!initialized) return false; + //return (currPos-*startPosPtr<*numIntsPtr); + return (currPos<=*endPosPtr); //might need to fix later if getNextBlockSingle is implemented +} + +Block* BitSparseDecoder::getNextBlock() { + if (!initialized) return NULL; + //int value; + int numVals; + byte* buffer; + //int* buffer2; + //int* valbuffer; + //int* posbuffer; + if (!(buffer=reader.getBuffer(numVals))) return NULL; + //valbuffer = new int[numInts/2]; + //posbuffer = new int[numInts/2]; + //int index = 0; + //for (int i = 0; i < numInts; i+=2) { + // valbuffer[index] = buffer2[i]; + // posbuffer[index] = buffer2[i+1]; + // index++; + //} + /* outPair->value=value; + outPair->position=currPos; + outBlock->currPos=-1;*/ + // outBlock->setValue(value, currPos); + outBlock->setBuffer(currPos, *endPosPtr, numVals, buffer); + //outPosBlock->setBuffer(buffer2+(*numIntsPtr), (numInts-*numIntsPtr)); + outBlock->setPosBlock(currIter); + currPos=(*endPosPtr)+1; + // Log::writeToLog("BitSparseDecoder", 0, "getNext returning pair value", value); + return outBlock; + +} + +Block* BitSparseDecoder::getNextBlockSingle() { + throw new UnimplementedException("Not done yet."); + /* + if (!initialized) return NULL; + int* value = new int[2]; + if (!(reader.readInt(value[0]))) return NULL; + assert(reader.readInt(value[1])); + //outPair->value=value; + //outPair->position=currPos; + //outBlock->currPos=-1; + outBlock->setBuffer(value[1], 1, (byte*)value); + // outBlock->setValue(value, currPos); + currPos++; + delete[] value; + // Log::writeToLog("BitSparseDecoder", 0, "getNext returning pair value", value);*/ + return outBlock; + +} +Block* BitSparseDecoder::peekNextBlock() { + throw new UnimplementedException("Not done yet."); + /* + if (!initialized) return NULL; + int* value = new int[2]; + int oldPos=reader.getCurrentIntPos(); + if (!reader.readInt(value[0])) return NULL; + assert(reader.readInt(value[1])); + reader.skipToIntPos(oldPos); + outPair->value=value; + outPair->position=currPos; + outBlock->currPos=-1; + */ + return outBlock; +} +bool BitSparseDecoder::skipToPos(unsigned int blockPos_) { + if (blockPos_> (*endPosPtr - *startPosPtr)) return false;//NULL; + //could probably do binary search but I won't bother for now (unlikely to be performance bottleneck) + + assert(initialized); + bool x; + int size = outPosBlock->getSize(); + delete currIter; + currIter = outPosBlock->getIterator(*startPosPtr + blockPos_, *endPosPtr); + x = reader.skipToStringPos(size-currIter->getSize()); + assert(x); + return true; +} + +bool BitSparseDecoder::skipToBlockOnValue(int value_) { + throw new UnimplementedException("Not done yet."); + /* Log::writeToLog("BitSparseDecoder", 0, "skipToBlockOnValue() called, val", value_); + // currently scan down, however can do binary search when sorted in future + reader.resetPos(); + int value; + while (reader.readInt(value)) { + currPos++; + //int value=((MultiBlock*) peekNextBlock())->getValue(); + if (value!=value_) { + if (outBlock->isValueSorted()) { + if (value>value_) { + Log::writeToLog("BitSparseDecoder", 0, "Did not find value, returning false, val", value_); + return false; + } + //getNextBlock(); + } + //else { + //getNextBlock(); + //} + } + else { + Log::writeToLog("BitSparseDecoder", 0, "skipToBlockOnValue() found value", value_); + skipToPos(currPos-*startPosPtr -1); + return true; + } + } + Log::writeToLog("BitSparseDecoder", 0, "Did not find value, returning false, val", value_); + return false;*/ +} + + +ValPos* BitSparseDecoder::getStartVal() { + throw new UnimplementedException("Not done yet."); +} +unsigned int BitSparseDecoder::getStartPos() { + return *startPosPtr; +} +ValPos* BitSparseDecoder::getEndVal() { + throw new UnimplementedException("Not done yet."); +} +unsigned int BitSparseDecoder::getEndPos() { + return (*endPosPtr); +} diff --git a/pool/shard007/C++/0095609_target_visualizer_display.cpp b/pool/shard007/C++/0095609_target_visualizer_display.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9d178e9260df35e221f64b7064c4154d57b91f5 --- /dev/null +++ b/pool/shard007/C++/0095609_target_visualizer_display.cpp @@ -0,0 +1,218 @@ +// -*- mode: c++; -*- +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2014, JSK Lab + * 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/o2r other materials provided + * with the distribution. + * * Neither the name of the JSK Lab nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *********************************************************************/ +#include +#include +#include +#include +#include +#include "target_visualizer_display.h" +#include + +namespace jsk_rviz_plugins +{ + const float arrow_animation_duration = 1.0; + const double minimum_font_size = 0.2; + + TargetVisualizerDisplay::TargetVisualizerDisplay(): + message_recieved_(false) + { + target_name_property_ = new rviz::StringProperty( + "target name", "target", + "name of the target", + this, SLOT(updateTargetName()) + ); + radius_property_ = new rviz::FloatProperty( + "radius", 1.0, + "radius of the target mark", + this, SLOT(updateRadius())); + radius_property_->setMin(0.0); + alpha_property_ = new rviz::FloatProperty( + "alpha", 0.8, + "0 is fully transparent, 1.0 is fully opaque.", + this, SLOT(updateAlpha())); + alpha_property_->setMin(0.0); + alpha_property_->setMax(1.0); + color_property_ = new rviz::ColorProperty( + "color", QColor(25, 255, 240), + "color of the target", + this, SLOT(updateColor())); + shape_type_property_ = new rviz::EnumProperty( + "type", "Simple Circle", + "Shape to display the pose as", + this, SLOT(updateShapeType())); + shape_type_property_->addOption("Simple Circle", SimpleCircle); + shape_type_property_->addOption("Decoreted Circle", GISCircle); + } + + TargetVisualizerDisplay::~TargetVisualizerDisplay() + { + delete target_name_property_; + delete alpha_property_; + delete color_property_; + delete radius_property_; + } + + void TargetVisualizerDisplay::onEnable() + { + subscribe(); + visualizer_->setEnable(false); // keep false, it will be true + // in side of processMessae callback. + } + + void TargetVisualizerDisplay::processMessage( + const geometry_msgs::PoseStamped::ConstPtr& msg) + { + boost::mutex::scoped_lock lock(mutex_); + message_recieved_ = true; + visualizer_->setEnable(isEnabled()); + if (!isEnabled()) { + return; + } + Ogre::Quaternion orientation; + Ogre::Vector3 position; + if(!context_->getFrameManager()->transform(msg->header, + msg->pose, + position, orientation)) + { + ROS_DEBUG( "Error transforming from frame '%s' to frame '%s'", + msg->header.frame_id.c_str(), qPrintable( fixed_frame_ )); + return; + } + visualizer_->setPosition(position); + } + + + void TargetVisualizerDisplay::update(float wall_dt, float ros_dt) + { + if (!message_recieved_) { + return; + } + visualizer_->setOrientation(context_); + visualizer_->update(wall_dt, ros_dt); + } + + void TargetVisualizerDisplay::onInitialize() + { + MFDClass::onInitialize(); + scene_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode(); + + updateRadius(); + updateShapeType(); + // updateTargetName(); + // updateColor(); + // updateAlpha(); + } + + void TargetVisualizerDisplay::reset() + { + MFDClass::reset(); + message_recieved_ = false; + if (visualizer_) { + visualizer_->setEnable(false); + } + } + + void TargetVisualizerDisplay::updateTargetName() + { + boost::mutex::scoped_lock lock(mutex_); + target_name_ = target_name_property_->getStdString(); + if (visualizer_) { + visualizer_->setText(target_name_); + } + } + + void TargetVisualizerDisplay::updateRadius() + { + boost::mutex::scoped_lock lock(mutex_); + radius_ = radius_property_->getFloat(); + if (visualizer_) { + visualizer_->setSize(radius_); + } + } + + void TargetVisualizerDisplay::updateAlpha() + { + boost::mutex::scoped_lock lock(mutex_); + alpha_ = alpha_property_->getFloat(); + if (visualizer_) { + visualizer_->setAlpha(alpha_); + } + } + + void TargetVisualizerDisplay::updateColor() + { + boost::mutex::scoped_lock lock(mutex_); + color_ = color_property_->getColor(); + if (visualizer_) { + visualizer_->setColor(color_); + } + } + + void TargetVisualizerDisplay::updateShapeType() + { + if (current_type_ != shape_type_property_->getOptionInt()) { + { + boost::mutex::scoped_lock lock(mutex_); + if (shape_type_property_->getOptionInt() == SimpleCircle) { + current_type_ = SimpleCircle; + // simple circle + visualizer_.reset(new SimpleCircleFacingVisualizer( + scene_manager_, + scene_node_, + context_, + radius_)); + } + else { + current_type_ = GISCircle; + // GIS + GISCircleVisualizer* v = new GISCircleVisualizer( + scene_manager_, + scene_node_, + radius_); + v->setAnonymous(false); + visualizer_.reset(v); + + } + } + updateTargetName(); + updateColor(); + updateAlpha(); + } + } +} + +#include +PLUGINLIB_EXPORT_CLASS( jsk_rviz_plugins::TargetVisualizerDisplay, rviz::Display ) + diff --git a/pool/shard007/C++/0095613_network_ui_data.cc b/pool/shard007/C++/0095613_network_ui_data.cc new file mode 100644 index 0000000000000000000000000000000000000000..a80ee3ecd5a47580fe5c09a490ebdd1fd7c2bffa --- /dev/null +++ b/pool/shard007/C++/0095613_network_ui_data.cc @@ -0,0 +1,233 @@ +// 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 "chromeos/network/network_ui_data.h" + +#include "base/logging.h" +#include "base/values.h" +#include "chromeos/network/onc/onc_signature.h" + +namespace chromeos { + +// Top-level UI data dictionary keys. +const char NetworkUIData::kKeyONCSource[] = "onc_source"; +const char NetworkUIData::kKeyCertificatePattern[] = "certificate_pattern"; +const char NetworkUIData::kKeyCertificateType[] = "certificate_type"; +const char NetworkUIData::kKeyUserSettings[] = "user_settings"; + +namespace { + +template +struct StringEnumEntry { + const char* string; + Enum enum_value; +}; + +const StringEnumEntry kONCSourceTable[] = { + { "user_import", onc::ONC_SOURCE_USER_IMPORT }, + { "device_policy", onc::ONC_SOURCE_DEVICE_POLICY }, + { "user_policy", onc::ONC_SOURCE_USER_POLICY } +}; + +const StringEnumEntry kClientCertTable[] = { + { "none", CLIENT_CERT_TYPE_NONE }, + { "pattern", CLIENT_CERT_TYPE_PATTERN }, + { "ref", CLIENT_CERT_TYPE_REF } +}; + +// Converts |enum_value| to the corresponding string according to |table|. If no +// enum value of the table matches (which can only occur if incorrect casting +// was used to obtain |enum_value|), returns an empty string instead. +template +std::string EnumToString(const StringEnumEntry(& table)[N], + Enum enum_value) { + for (int i = 0; i < N; ++i) { + if (table[i].enum_value == enum_value) + return table[i].string; + } + return std::string(); +} + +// Converts |str| to the corresponding enum value according to |table|. If no +// string of the table matches, returns |fallback| instead. +template +Enum StringToEnum(const StringEnumEntry(& table)[N], + const std::string& str, + Enum fallback) { + for (int i = 0; i < N; ++i) { + if (table[i].string == str) + return table[i].enum_value; + } + return fallback; +} + +} // namespace + +NetworkUIData::NetworkUIData() + : onc_source_(onc::ONC_SOURCE_NONE), + certificate_type_(CLIENT_CERT_TYPE_NONE) { +} + +NetworkUIData::NetworkUIData(const NetworkUIData& other) { + *this = other; +} + +NetworkUIData& NetworkUIData::operator=(const NetworkUIData& other) { + certificate_pattern_ = other.certificate_pattern_; + onc_source_ = other.onc_source_; + certificate_type_ = other.certificate_type_; + if (other.user_settings_) + user_settings_.reset(other.user_settings_->DeepCopy()); + policy_guid_ = other.policy_guid_; + return *this; +} + +NetworkUIData::NetworkUIData(const DictionaryValue& dict) { + std::string source; + dict.GetString(kKeyONCSource, &source); + onc_source_ = StringToEnum(kONCSourceTable, source, onc::ONC_SOURCE_NONE); + + std::string type_string; + dict.GetString(kKeyCertificateType, &type_string); + certificate_type_ = + StringToEnum(kClientCertTable, type_string, CLIENT_CERT_TYPE_NONE); + + if (certificate_type_ == CLIENT_CERT_TYPE_PATTERN) { + const DictionaryValue* cert_dict = NULL; + dict.GetDictionary(kKeyCertificatePattern, &cert_dict); + if (cert_dict) + certificate_pattern_.CopyFromDictionary(*cert_dict); + if (certificate_pattern_.Empty()) { + LOG(ERROR) << "Couldn't parse a valid certificate pattern."; + certificate_type_ = CLIENT_CERT_TYPE_NONE; + } + } + + const DictionaryValue* user_settings = NULL; + if (dict.GetDictionary(kKeyUserSettings, &user_settings)) + user_settings_.reset(user_settings->DeepCopy()); +} + +NetworkUIData::~NetworkUIData() { +} + +void NetworkUIData::FillDictionary(base::DictionaryValue* dict) const { + dict->Clear(); + + std::string source_string = EnumToString(kONCSourceTable, onc_source_); + if (!source_string.empty()) + dict->SetString(kKeyONCSource, source_string); + + if (certificate_type_ != CLIENT_CERT_TYPE_NONE) { + std::string type_string = EnumToString(kClientCertTable, certificate_type_); + dict->SetString(kKeyCertificateType, type_string); + + if (certificate_type_ == CLIENT_CERT_TYPE_PATTERN && + !certificate_pattern_.Empty()) { + dict->Set(kKeyCertificatePattern, + certificate_pattern_.CreateAsDictionary()); + } + } + if (user_settings_) + dict->SetWithoutPathExpansion(kKeyUserSettings, + user_settings_->DeepCopy()); +} + +namespace { + +void TranslateClientCertType(const std::string& client_cert_type, + NetworkUIData* ui_data) { + using namespace onc::certificate; + ClientCertType type; + if (client_cert_type == kNone) { + type = CLIENT_CERT_TYPE_NONE; + } else if (client_cert_type == kRef) { + type = CLIENT_CERT_TYPE_REF; + } else if (client_cert_type == kPattern) { + type = CLIENT_CERT_TYPE_PATTERN; + } else { + type = CLIENT_CERT_TYPE_NONE; + NOTREACHED(); + } + + ui_data->set_certificate_type(type); +} + +void TranslateCertificatePattern(const base::DictionaryValue& onc_object, + NetworkUIData* ui_data) { + CertificatePattern pattern; + bool success = pattern.CopyFromDictionary(onc_object); + DCHECK(success); + ui_data->set_certificate_pattern(pattern); +} + +void TranslateEAP(const base::DictionaryValue& eap, + NetworkUIData* ui_data) { + std::string client_cert_type; + if (eap.GetStringWithoutPathExpansion(onc::eap::kClientCertType, + &client_cert_type)) { + TranslateClientCertType(client_cert_type, ui_data); + } +} + +void TranslateIPsec(const base::DictionaryValue& ipsec, + NetworkUIData* ui_data) { + std::string client_cert_type; + if (ipsec.GetStringWithoutPathExpansion(onc::vpn::kClientCertType, + &client_cert_type)) { + TranslateClientCertType(client_cert_type, ui_data); + } +} + +void TranslateOpenVPN(const base::DictionaryValue& openvpn, + NetworkUIData* ui_data) { + std::string client_cert_type; + if (openvpn.GetStringWithoutPathExpansion(onc::vpn::kClientCertType, + &client_cert_type)) { + TranslateClientCertType(client_cert_type, ui_data); + } +} + +void TranslateONCHierarchy(const onc::OncValueSignature& signature, + const base::DictionaryValue& onc_object, + NetworkUIData* ui_data) { + if (&signature == &onc::kCertificatePatternSignature) + TranslateCertificatePattern(onc_object, ui_data); + else if (&signature == &onc::kEAPSignature) + TranslateEAP(onc_object, ui_data); + else if (&signature == &onc::kIPsecSignature) + TranslateIPsec(onc_object, ui_data); + else if (&signature == &onc::kOpenVPNSignature) + TranslateOpenVPN(onc_object, ui_data); + + // Recurse into nested objects. + for (base::DictionaryValue::Iterator it(onc_object); !it.IsAtEnd(); + it.Advance()) { + const base::DictionaryValue* inner_object; + if (!it.value().GetAsDictionary(&inner_object)) + continue; + + const onc::OncFieldSignature* field_signature = + GetFieldSignature(signature, it.key()); + + TranslateONCHierarchy(*field_signature->value_signature, *inner_object, + ui_data); + } +} + +} // namespace + +scoped_ptr CreateUIDataFromONC( + onc::ONCSource onc_source, + const base::DictionaryValue& onc_network) { + scoped_ptr ui_data(new NetworkUIData()); + TranslateONCHierarchy(onc::kNetworkConfigurationSignature, onc_network, + ui_data.get()); + + ui_data->set_onc_source(onc_source); + + return ui_data.Pass(); +} + +} // namespace chromeos diff --git a/pool/shard007/C++/0095614_AnimatedGraphics.cpp b/pool/shard007/C++/0095614_AnimatedGraphics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..823e259b9dc6478648d98084ed8441ab6f587937 --- /dev/null +++ b/pool/shard007/C++/0095614_AnimatedGraphics.cpp @@ -0,0 +1,173 @@ +/** +@file AnimatedGraphics.cpp + +Contiene la implementación del componente que controla la representación +gráfica de una entidad estática. + +@see Logic::CAnimatedGraphics +@see Logic::IComponent + +@author David Llansó +@date Agosto, 2010 + +@refactor Alberto Martínez Villarán +@date Marzo, 2015 +*/ + +#include "AnimatedGraphics.h" + +#include "Logic/Entity/Entity.h" +#include "Logic/Entity/Components/WaitAnimations.h" +#include "Logic/Maps/Map.h" +#include "Map/MapEntity.h" + +#include "Graphics/Scene.h" + +#include "LUA\ScriptManager.h" + +namespace Logic +{ + IMP_FACTORY(CAnimatedGraphics); + + //--------------------------------------------------------- + + Graphics::CEntity* CAnimatedGraphics::createGraphicsEntity(const Map::CEntity *entityInfo) + { + if(entityInfo->hasAttribute("animation_config")) + { + _animationConfig = entityInfo->getStringAttribute("animation_config"); + } + + _animatedGraphicsEntity = new Graphics::CAnimatedEntity(_entity->getName(),_model, _animationConfig); + _animatedGraphicsEntity->setNeedNode(_needNode); + /*if(!_scene->addEntity(_animatedGraphicsEntity)) + return 0;*/ + + _animatedGraphicsEntity->setTransform(_entity->getTransform()); + + if(entityInfo->hasAttribute("defaultAnimation")) + { + _defaultAnimation = entityInfo->getStringAttribute("defaultAnimation"); + } + + _speed = 1.0f; + if(entityInfo->hasAttribute("defaultSpeedAnimation")) + { + _speed = entityInfo->getFloatAttribute("defaultSpeedAnimation"); + } + + + return _animatedGraphicsEntity; + + } // createGraphicsEntity + + //--------------------------------------------------------- + + bool CAnimatedGraphics::accept(const std::shared_ptr &message) + { + return CGraphics::accept(message) || + /*message->getType() == "SET_ANIMATION" ||*/ + message->getType() == "STOP_ANIMATION" || + message->getType() == "SET_ANIM_SPEED_MULT"; + + } // accept + + //--------------------------------------------------------- + + bool CAnimatedGraphics::activate() + { + if(!CGraphics::activate()) + { + return false; + } + + _multSpeed = 1; + //Las animaciones estarán por defecto en la categoría o conjunto de animación "default" + _animatedGraphicsEntity->setAnimation(_defaultAnimation, "default", true, false, 0.0f, _speed); + + _actualAnimation = _defaultAnimation; + //Nos registramos como observadores de la animación por defecto + //_animatedGraphicsEntity->setObserver(this, _defaultAnimation); + + ///seteamos el modo de blend + _animatedGraphicsEntity->setAnimationBlendMode(Graphics::BlendMode::CUMULATIVE); + + return true; + } + void CAnimatedGraphics::deactivate() + { + + //Eliminamos esta entidad de la escena grafica + if(_animatedGraphicsEntity) + { + //Primero la hacemos invisible + _animatedGraphicsEntity->setVisible(false); + _animatedGraphicsEntity->stopAllAnimations(); + _scene->removeEntity(_animatedGraphicsEntity); + } + _scene = 0; + } + //--------------------------------------------------------- + + void CAnimatedGraphics::process(const std::shared_ptr &message) + { + CGraphics::process(message); + + /*if(message->getType().compare("SET_ANIMATION") == 0) + { + // Paramos todas las animaciones antes de poner una nueva. + // Un control más sofisticado debería permitir interpolación + // de animaciones. Galeon no lo plantea. + //_animatedGraphicsEntity->stopAllAnimations(); + SET_ANIMATION *msg = dynamic_cast(message.get()); + std::string animName = msg->getAnimation(); + std::string animSet = msg->getAnimationSet(); + bool loop = msg->getLoop(); + bool restart = msg->getRestartFlag(); + float duration = msg->getDuration(); + float speed = msg->getSpeed(); + + //Como ha recibido un mensaje para cambiar la animación reseteamos el tiempo en el qspecialAttackOrderue permanece + //sin hacer nada + LUA::CScriptManager::GetPtrSingleton()->executeProcedure("GameMgr", "resetTemp"); + + _animatedGraphicsEntity->setAnimation(animName, animSet, loop, restart, duration, speed); + } + else*/ if (message->getType().compare("STOP_ANIMATION") == 0) + { + STOP_ANIMATION *msg = dynamic_cast(message.get()); + std::string animName = msg->getAnimation(); + std::string animSet = msg->getAnimationSet(); + _animatedGraphicsEntity->stopAnimation(animName, animSet); + } + + else if (message->getType().compare("SET_ANIM_SPEED_MULT") == 0) + { + _multSpeed = dynamic_cast(message.get())->getFloat(); + } + + } // process + + //--------------------------------------------------------- + + void CAnimatedGraphics::animationFinished(const std::string &animation) + { + // Si acaba una animación y tenemos una por defecto la ponemos + //_animatedGraphicsEntity->stopAllAnimations(); + //_animatedGraphicsEntity->setAnimation(_defaultAnimation,true, false); + //BaseSubsystems::Log::Debug("CAnimatedGraphics->animationFinished - "+animation); + } + + void CAnimatedGraphics::setAnimation(const std::string &animation, const std::string &animSet, bool loop, bool restart, float duration, float speed, bool saveAnim) + { + if (saveAnim) + _actualAnimation = animation; + + _animatedGraphicsEntity->setAnimation(animation, animSet, loop, restart, duration, speed * _multSpeed); + } + + + + +} // namespace Logic + diff --git a/pool/shard007/C++/0095616_CCConfiguration.cpp b/pool/shard007/C++/0095616_CCConfiguration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e43302dda634ce3ea623d33b8b3ccc4823772ee --- /dev/null +++ b/pool/shard007/C++/0095616_CCConfiguration.cpp @@ -0,0 +1,318 @@ +/**************************************************************************** +Copyright (c) 2010 Ricardo Quesada +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2013-2014 Chukong Technologies Inc. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "base/CCConfiguration.h" +#include "platform/CCFileUtils.h" + +NS_CC_BEGIN + +extern const char* cocos2dVersion(); + +Configuration* Configuration::s_sharedConfiguration = nullptr; + +Configuration::Configuration() +: _maxTextureSize(0) +, _maxModelviewStackDepth(0) +, _supportsPVRTC(false) +, _supportsETC1(false) +, _supportsS3TC(false) +, _supportsATITC(false) +, _supportsNPOT(false) +, _supportsBGRA8888(false) +, _supportsDiscardFramebuffer(false) +, _supportsShareableVAO(false) +, _maxSamplesAllowed(0) +, _maxTextureUnits(0) +, _glExtensions(nullptr) +{ +} + +bool Configuration::init() +{ + _valueDict["cocos2d.x.version"] = Value(cocos2dVersion()); + + +#if CC_ENABLE_PROFILERS + _valueDict["cocos2d.x.compiled_with_profiler"] = Value(true); +#else + _valueDict["cocos2d.x.compiled_with_profiler"] = Value(false); +#endif + +#if CC_ENABLE_GL_STATE_CACHE == 0 + _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(false); +#else + _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true); +#endif + +#if COCOS2D_DEBUG + _valueDict["cocos2d.x.build_type"] = Value("DEBUG"); +#else + _valueDict["cocos2d.x.build_type"] = Value("RELEASE"); +#endif + + return true; +} + +Configuration::~Configuration() +{ +} + +std::string Configuration::getInfo() const +{ + // And Dump some warnings as well +#if CC_ENABLE_PROFILERS + CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)\n"); +#endif + +#if CC_ENABLE_GL_STATE_CACHE == 0 + CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)\n"); +#endif + + // Dump + Value forDump = Value(_valueDict); + return forDump.getDescription(); +} + +void Configuration::gatherGPUInfo() +{ + _valueDict["gl.vendor"] = Value((const char*)glGetString(GL_VENDOR)); + _valueDict["gl.renderer"] = Value((const char*)glGetString(GL_RENDERER)); + _valueDict["gl.version"] = Value((const char*)glGetString(GL_VERSION)); + + _glExtensions = (char *)glGetString(GL_EXTENSIONS); + + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &_maxTextureSize); + _valueDict["gl.max_texture_size"] = Value((int)_maxTextureSize); + + glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &_maxTextureUnits); + _valueDict["gl.max_texture_units"] = Value((int)_maxTextureUnits); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + glGetIntegerv(GL_MAX_SAMPLES_APPLE, &_maxSamplesAllowed); + _valueDict["gl.max_samples_allowed"] = Value((int)_maxSamplesAllowed); +#endif + + _supportsETC1 = checkForGLExtension("GL_OES_compressed_ETC1_RGB8_texture"); + _valueDict["gl.supports_ETC1"] = Value(_supportsETC1); + + _supportsS3TC = checkForGLExtension("GL_EXT_texture_compression_s3tc"); + _valueDict["gl.supports_S3TC"] = Value(_supportsS3TC); + + _supportsATITC = checkForGLExtension("GL_AMD_compressed_ATC_texture"); + _valueDict["gl.supports_ATITC"] = Value(_supportsATITC); + + _supportsPVRTC = checkForGLExtension("GL_IMG_texture_compression_pvrtc"); + _valueDict["gl.supports_PVRTC"] = Value(_supportsPVRTC); + + _supportsNPOT = true; + _valueDict["gl.supports_NPOT"] = Value(_supportsNPOT); + + _supportsBGRA8888 = checkForGLExtension("GL_IMG_texture_format_BGRA888"); + _valueDict["gl.supports_BGRA8888"] = Value(_supportsBGRA8888); + + _supportsDiscardFramebuffer = checkForGLExtension("GL_EXT_discard_framebuffer"); + _valueDict["gl.supports_discard_framebuffer"] = Value(_supportsDiscardFramebuffer); + + _supportsShareableVAO = checkForGLExtension("vertex_array_object"); + _valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO); + + CHECK_GL_ERROR_DEBUG(); +} + +Configuration* Configuration::getInstance() +{ + if (! s_sharedConfiguration) + { + s_sharedConfiguration = new (std::nothrow) Configuration(); + s_sharedConfiguration->init(); + } + + return s_sharedConfiguration; +} + +void Configuration::destroyInstance() +{ + CC_SAFE_RELEASE_NULL(s_sharedConfiguration); +} + +// FIXME: deprecated +Configuration* Configuration::sharedConfiguration() +{ + return Configuration::getInstance(); +} + +// FIXME: deprecated +void Configuration::purgeConfiguration() +{ + Configuration::destroyInstance(); +} + + +bool Configuration::checkForGLExtension(const std::string &searchName) const +{ + return (_glExtensions && strstr(_glExtensions, searchName.c_str() ) ) ? true : false; +} + +// +// getters for specific variables. +// Mantained for backward compatiblity reasons only. +// +int Configuration::getMaxTextureSize() const +{ + return _maxTextureSize; +} + +int Configuration::getMaxModelviewStackDepth() const +{ + return _maxModelviewStackDepth; +} + +int Configuration::getMaxTextureUnits() const +{ + return _maxTextureUnits; +} + +bool Configuration::supportsNPOT() const +{ + return _supportsNPOT; +} + +bool Configuration::supportsPVRTC() const +{ + return _supportsPVRTC; +} + +bool Configuration::supportsETC() const +{ + //GL_ETC1_RGB8_OES is not defined in old opengl version +#ifdef GL_ETC1_RGB8_OES + return _supportsETC1; +#else + return false; +#endif +} + +bool Configuration::supportsS3TC() const +{ + return _supportsS3TC; +} + +bool Configuration::supportsATITC() const +{ + return _supportsATITC; +} + +bool Configuration::supportsBGRA8888() const +{ + return _supportsBGRA8888; +} + +bool Configuration::supportsDiscardFramebuffer() const +{ + return _supportsDiscardFramebuffer; +} + +bool Configuration::supportsShareableVAO() const +{ +#if CC_TEXTURE_ATLAS_USE_VAO + return _supportsShareableVAO; +#else + return false; +#endif +} + +// +// generic getters for properties +// +const Value& Configuration::getValue(const std::string& key, const Value& defaultValue) const +{ + auto iter = _valueDict.find(key); + if (iter != _valueDict.cend()) + return _valueDict.at(key); + return defaultValue; +} + +void Configuration::setValue(const std::string& key, const Value& value) +{ + _valueDict[key] = value; +} + + +// +// load file +// +void Configuration::loadConfigFile(const std::string& filename) +{ + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); + CCASSERT(!dict.empty(), "cannot create dictionary"); + + // search for metadata + bool validMetadata = false; + auto metadataIter = dict.find("metadata"); + if (metadataIter != dict.cend() && metadataIter->second.getType() == Value::Type::MAP) + { + + const auto& metadata = metadataIter->second.asValueMap(); + auto formatIter = metadata.find("format"); + + if (formatIter != metadata.cend()) + { + int format = formatIter->second.asInt(); + + // Support format: 1 + if (format == 1) + { + validMetadata = true; + } + } + } + + if (! validMetadata) + { + CCLOG("Invalid config format for file: %s", filename.c_str()); + return; + } + + auto dataIter = dict.find("data"); + if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) + { + CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); + return; + } + + // Add all keys in the existing dictionary + + const auto& dataMap = dataIter->second.asValueMap(); + for (auto dataMapIter = dataMap.cbegin(); dataMapIter != dataMap.cend(); ++dataMapIter) + { + if (_valueDict.find(dataMapIter->first) == _valueDict.cend()) + _valueDict[dataMapIter->first] = dataMapIter->second; + else + CCLOG("Key already present. Ignoring '%s'",dataMapIter->first.c_str()); + } +} + +NS_CC_END diff --git a/pool/shard007/C++/0095617_VertexLayout.cc b/pool/shard007/C++/0095617_VertexLayout.cc new file mode 100644 index 0000000000000000000000000000000000000000..dca4e7cc166a43badae2a57bac517a15b3d367b8 --- /dev/null +++ b/pool/shard007/C++/0095617_VertexLayout.cc @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2007, Radon Labs GmbH +Copyright (c) 2011-2013,WebJet Business Division,CYOU + +http://www.genesis-3d.com.cn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "stdneb.h" +#include "core/types.h" +#include "VertexLayout.h" +#include "util/array.h" +namespace RenderBase +{ + __ImplementClass(VertexLayout, 'VXLB', Core::RefCounted); + + + using namespace Util; + //------------------------------------------------------------------------------ + /** + */ + VertexLayout::VertexLayout() : + vertexByteSize(0) + { + // empty + } + + //------------------------------------------------------------------------------ + /** + */ + VertexLayout::~VertexLayout() + { + if (this->IsValid()) + { + Discard(); + } + n_assert(!this->IsValid()); + } + + void VertexLayout::CopyFrom(const VertexLayout* vl) + { + components = vl->components; + vertexByteSize = vl->vertexByteSize; + } + + //------------------------------------------------------------------------------ + /** + */ + String + VertexLayout::BuildSignature(const Array& comps) + { + n_assert(comps.Size() > 0); + String sig; + IndexT i; + for (i = 0; i < comps.Size(); i++) + { + sig.Append(comps[i].GetSignature()); + } + return sig; + } + + //------------------------------------------------------------------------------ + /** + */ + void + VertexLayout::Setup(const Array& comps) + { + n_assert(comps.Size() > 0); + n_assert(!this->IsValid()); + n_assert(0 == this->vertexByteSize); + this->components = comps; + this->vertexByteSize = VertexComponent::BuildComponentsOffsetAndSize(this->components); + } + + //------------------------------------------------------------------------------ + /** + */ + void + VertexLayout::Discard() + { + if(this->IsValid()) + { + this->components.Clear(); + this->vertexByteSize = 0; + } + } + + //------------------------------------------------------------------------------ + /** + */ + IndexT + VertexLayout::FindComponent(VertexComponent::SemanticName semName, IndexT semIndex) const + { + IndexT i; + for (i = 0; i < this->components.Size(); i++) + { + const VertexComponent& cur = this->components[i]; + if ((cur.GetSemanticName() == semName) && (cur.GetSemanticIndex() == semIndex)) + { + return i; + } + } + // fallthrough: not found + return InvalidIndex; + } + + +} \ No newline at end of file diff --git a/pool/shard007/C++/0095620_grid_tools_03.cc b/pool/shard007/C++/0095620_grid_tools_03.cc new file mode 100644 index 0000000000000000000000000000000000000000..eb98a50c2bfe4265959dc1be65e70eab1c031dff --- /dev/null +++ b/pool/shard007/C++/0095620_grid_tools_03.cc @@ -0,0 +1,97 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2001 - 2013 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. +// +// --------------------------------------------------------------------- + + +// check GridTools::volume + + +#include "../tests.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +std::ofstream logfile("output"); + + + +template +void test1 () +{ + // test 1: hypercube + if (true) + { + Triangulation tria; + GridGenerator::hyper_cube(tria); + + for (unsigned int i=0; i<2; ++i) + { + tria.refine_global(2); + deallog << dim << "d, " + << "hypercube volume, " + << i*2 + << " refinements: " + << GridTools::volume (tria) + << std::endl; + }; + }; + + // test 2: hyperball + if (dim >= 2) + { + Triangulation tria; + GridGenerator::hyper_ball(tria, Point(), 1); + + static const HyperBallBoundary boundary; + tria.set_boundary (0, boundary); + + for (unsigned int i=0; i<4; ++i) + { + tria.refine_global(1); + deallog << dim << "d, " + << "hyperball volume, " + << i + << " refinements: " + << GridTools::volume (tria) + << std::endl; + } + deallog << "exact value=" + << (dim==2 ? numbers::PI : + 4./3.*numbers::PI) + << std::endl; + } +} + + +int main () +{ + deallog << std::setprecision(4); + logfile << std::setprecision(4); + deallog.attach(logfile); + deallog.depth_console(0); + deallog.threshold_double(1.e-10); + + test1<1> (); + test1<2> (); + test1<3> (); + + return 0; +} + diff --git a/pool/shard007/C++/0095621_FontImporterStage.cpp b/pool/shard007/C++/0095621_FontImporterStage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15ce12e798d97406f23835dafd1a9069ba405580 --- /dev/null +++ b/pool/shard007/C++/0095621_FontImporterStage.cpp @@ -0,0 +1,48 @@ + +#include + +#include + +#include +#include + + +namespace gloperate_text +{ + + +FontImporterStage::FontImporterStage() +: AbstractStage("FontImporterStage") +{ + addInput("resourceManager", resourceManager); + addInput("fontFilePath", fontFilePath); + + addOutput("font", font); +} + +FontImporterStage::~FontImporterStage() +{ +} + +void FontImporterStage::initialize() +{ + m_importer.reset(new gloperate_text::FontLoader(*resourceManager.data())); +} + +void FontImporterStage::process() +{ + FontFace * newFont = m_importer->load(fontFilePath.data().toString()); + + if (newFont == nullptr) + { + return; + } + + m_font = newFont; + font.data() = m_font; + + invalidateOutputs(); +} + + +} // namespace gloperate_text diff --git a/pool/shard007/C++/0095622_backend_manager.cpp b/pool/shard007/C++/0095622_backend_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa6ae7ca815589c113594a7d09344236bcf5250d --- /dev/null +++ b/pool/shard007/C++/0095622_backend_manager.cpp @@ -0,0 +1,549 @@ +//===----------------------------------------------------------------------===// +// +// Peloton +// +// backend_manager.cpp +// +// Identification: src/storage/backend_manager.cpp +// +// Copyright (c) 2015-16, Carnegie Mellon University Database Group +// +//===----------------------------------------------------------------------===// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "common/exception.h" +#include "common/logger.h" +#include "common/macros.h" +#include "common/internal_types.h" +// #include "logging/logging_util.h" +#include "storage/backend_manager.h" + +//===--------------------------------------------------------------------===// +// GUC Variables +//===--------------------------------------------------------------------===// + +// // Logging mode +// extern peloton::LoggingType peloton_logging_mode; + +// // Flush mode (for NVM WBL) +// extern int peloton_flush_mode; + +// // PCOMMIT latency (for NVM WBL) +// extern int peloton_pcommit_latency; + +// PMEM file size +size_t peloton_data_file_size = 0; + +namespace peloton { +namespace storage { + +//===--------------------------------------------------------------------===// +// INSTRUCTIONS +//===--------------------------------------------------------------------===// + +// Source : https://github.com/pmem/nvml/blob/master/src/libpmem/pmem.c + +// 64B cache line size +#define FLUSH_ALIGN ((uintptr_t)64) + +#define EAX_IDX 0 +#define EBX_IDX 1 +#define ECX_IDX 2 +#define EDX_IDX 3 + +#ifndef bit_CLFLUSH +#define bit_CLFLUSH (1 << 23) +#endif + +#ifndef bit_PCOMMIT +#define bit_PCOMMIT (1 << 22) +#endif + +#ifndef bit_CLFLUSHOPT +#define bit_CLFLUSHOPT (1 << 23) +#endif + +#ifndef bit_CLWB +#define bit_CLWB (1 << 24) +#endif + +/* + * The x86 memory instructions are new enough that the compiler + * intrinsic functions are not always available. The intrinsic + * functions are defined here in terms of asm statements for now. + */ +#define _mm_clflushopt(addr) \ + asm volatile(".byte 0x66; clflush %0" : "+m"(*(volatile char *)addr)); +#define _mm_clwb(addr) \ + asm volatile(".byte 0x66; xsaveopt %0" : "+m"(*(volatile char *)addr)); +#define _mm_pcommit() asm volatile(".byte 0x66, 0x0f, 0xae, 0xf8"); + +//===--------------------------------------------------------------------===// +// CPU CHECK +//===--------------------------------------------------------------------===// + +static inline void cpuid(unsigned func, unsigned subfunc, unsigned cpuinfo[4]) { + __cpuid_count(func, subfunc, cpuinfo[EAX_IDX], cpuinfo[EBX_IDX], + cpuinfo[ECX_IDX], cpuinfo[EDX_IDX]); +} + +/* + * is_cpu_genuine_intel -- checks for genuine Intel CPU + */ +int is_cpu_genuine_intel(void) { + unsigned cpuinfo[4] = {0}; + + union { + char name[0x20]; + unsigned cpuinfo[3]; + } vendor; + + PL_MEMSET(&vendor, 0, sizeof(vendor)); + + cpuid(0x0, 0x0, cpuinfo); + + vendor.cpuinfo[0] = cpuinfo[EBX_IDX]; + vendor.cpuinfo[1] = cpuinfo[EDX_IDX]; + vendor.cpuinfo[2] = cpuinfo[ECX_IDX]; + + return (strncmp(vendor.name, "GenuineIntel", sizeof(vendor.name))) == 0; +} + +//===--------------------------------------------------------------------===// +// INSTRUCTION CHECKS +//===--------------------------------------------------------------------===// + +/* + * is_cpu_clflush_present -- checks if CLFLUSH instruction is supported + */ +int is_cpu_clflush_present(void) { + unsigned cpuinfo[4] = {0}; + + cpuid(0x1, 0x0, cpuinfo); + + int ret = (cpuinfo[EDX_IDX] & bit_CLFLUSH) != 0; + + return ret; +} + +/* + * is_cpu_clwb_present -- checks if CLWB instruction is supported + */ +int is_cpu_clwb_present(void) { + unsigned cpuinfo[4] = {0}; + + if (!is_cpu_genuine_intel()) return 0; + + cpuid(0x7, 0x0, cpuinfo); + + int ret = (cpuinfo[EBX_IDX] & bit_CLWB) != 0; + + return ret; +} + +/* + * is_cpu_pcommit_present -- checks if PCOMMIT instruction is supported + */ +int is_cpu_pcommit_present(void) { + unsigned cpuinfo[4] = {0}; + + if (!is_cpu_genuine_intel()) return 0; + + cpuid(0x7, 0x0, cpuinfo); + + int ret = (cpuinfo[EBX_IDX] & bit_PCOMMIT) != 0; + + return ret; +} + +//===--------------------------------------------------------------------===// +// FLUSH FUNCTIONS +//===--------------------------------------------------------------------===// + +/* + * flush_clflush -- (internal) flush the CPU cache, using clflush + */ +static inline void flush_clflush(const void *addr, size_t len) { + uintptr_t uptr; + + // Loop through cache-line-size (typically 64B) aligned chunks + // covering the given range. + for (uptr = (uintptr_t)addr & ~(FLUSH_ALIGN - 1); + uptr < (uintptr_t)addr + len; uptr += FLUSH_ALIGN) + _mm_clflush((char *)uptr); +} + +// // flush_clwb -- (internal) flush the CPU cache, using clwb +// static inline void flush_clwb(const void *addr, size_t len) { +// uintptr_t uptr; + +// // Loop through cache-line-size (typically 64B) aligned chunks +// // covering the given range. +// for (uptr = (uintptr_t)addr & ~(FLUSH_ALIGN - 1); +// uptr < (uintptr_t)addr + len; uptr += FLUSH_ALIGN) { +// _mm_clwb((char *)uptr); +// } +// } + +/* + * pmem_flush() calls through Func_flush to do the work. Although + * initialized to flush_clflush(), once the existence of the clflushopt + * feature is confirmed by pmem_init() at library initialization time, + * Func_flush is set to flush_clflushopt(). That's the most common case + * on modern hardware that supports persistent memory. + */ +static void (*Func_flush)(const void *, size_t) = flush_clflush; + +// //===--------------------------------------------------------------------===// +// // PREDRAIN FUNCTIONS +// //===--------------------------------------------------------------------===// + +/* + * predrain_fence_empty -- (internal) issue the pre-drain fence instruction + */ +static void predrain_fence_empty(void) { + /* nothing to do (because CLFLUSH did it for us) */ +} + +// /* +// * predrain_fence_sfence -- (internal) issue the pre-drain fence instruction +// */ +// static void predrain_fence_sfence(void) { +// _mm_sfence(); /* ensure CLWB or CLFLUSHOPT completes before PCOMMIT */ +// } + +// * pmem_drain() calls through Func_predrain_fence to do the fence. Although +// * initialized to predrain_fence_empty(), once the existence of the CLWB or +// * CLFLUSHOPT feature is confirmed by pmem_init() at library initialization +// * time, Func_predrain_fence is set to predrain_fence_sfence(). That's the +// * most common case on modern hardware that supports persistent memory. + +static void (*Func_predrain_fence)(void) = predrain_fence_empty; + +// //===--------------------------------------------------------------------===// +// // DRAIN FUNCTIONS +// //===--------------------------------------------------------------------===// + +/* + * drain_no_pcommit -- (internal) wait for PM stores to drain, empty version + */ +static void drain_no_pcommit(void) { + Func_predrain_fence(); + + /* caller assumed responsibility for the rest */ +} + +// // PCOMMIT helpers + +// #define CPU_FREQ_MHZ (2593) + +// static inline unsigned long read_tsc(void) { +// unsigned long var; +// unsigned int hi, lo; + +// asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); +// var = ((unsigned long long int)hi << 32) | lo; + +// return var; +// } + +// static inline void cpu_pause() { __asm__ volatile("pause" ::: "memory"); } + +// static inline void pcommit(unsigned long lat) { +// // Special case +// if (lat == 0) return; + +// unsigned long etsc = read_tsc() + (unsigned long)(lat * CPU_FREQ_MHZ / +// 1000); +// while (read_tsc() < etsc) { +// cpu_pause(); +// } +// } + +// /* +// * drain_pcommit -- (internal) wait for PM stores to drain, pcommit version +// */ +// static void drain_pcommit(void) { +// Func_predrain_fence(); + +// // pause if needed +// pcommit(peloton_pcommit_latency); + +// // by default, this is zero +// if (peloton_pcommit_latency == 0) { +// _mm_pcommit(); +// _mm_sfence(); +// } +// } + +/* + * pmem_drain() calls through Func_drain to do the work. Although + * initialized to drain_no_pcommit(), once the existence of the pcommit + * feature is confirmed by pmem_init() at library initialization time, + * Func_drain is set to drain_pcommit(). That's the most common case + * on modern hardware that supports persistent memory. + */ +static void (*Func_drain)(void) = drain_no_pcommit; + +//===--------------------------------------------------------------------===// +// STORAGE MANAGER +//===--------------------------------------------------------------------===// + +#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) // 512 MB +#define DATA_FILE_NAME "peloton.pmem" + +// global singleton +BackendManager &BackendManager::GetInstance(void) { + static BackendManager backend_manager; + return backend_manager; +} + +BackendManager::BackendManager() + : data_file_address(nullptr), data_file_len(0), data_file_offset(0) { + // // Check if we need a data pool + // if (logging::LoggingUtil::IsBasedOnWriteAheadLogging(peloton_logging_mode) + // == + // true || + // peloton_logging_mode == LoggingType::INVALID) { + // return; + // } + + // // Check for instruction availability and flush mode + // // (1 -- clflush or 2 -- clwb) + // if (is_cpu_clwb_present() && peloton_flush_mode == 2) { + // LOG_TRACE("Found clwb \n"); + // Func_flush = flush_clwb; + // Func_predrain_fence = predrain_fence_sfence; + // } + + // if (is_cpu_pcommit_present()) { + // LOG_TRACE("Found pcommit \n"); + // Func_drain = drain_pcommit; + // } + + // // Rest of this stuff is needed only for Write Behind Logging + // int data_fd; + // std::string data_file_name; + // struct stat data_stat; + + // // Initialize file size + // if (peloton_data_file_size != 0) + // data_file_len = peloton_data_file_size * 1024 * 1024; // MB + // else + // data_file_len = DATA_FILE_LEN; + + // // Check for relevant file system + // bool found_file_system = false; + + // switch (peloton_logging_mode) { + // // Check for NVM FS for data + // case LoggingType::NVM_WBL: { + // int status = stat(NVM_DIR, &data_stat); + // if (status == 0 && S_ISDIR(data_stat.st_mode)) { + // data_file_name = std::string(NVM_DIR) + std::string(DATA_FILE_NAME); + // found_file_system = true; + // } + + // } break; + + // // Check for SSD FS for data + // case LoggingType::SSD_WBL: { + // int status = stat(SSD_DIR, &data_stat); + // if (status == 0 && S_ISDIR(data_stat.st_mode)) { + // data_file_name = std::string(SSD_DIR) + std::string(DATA_FILE_NAME); + // found_file_system = true; + // } + + // } break; + + // // Check for HDD FS + // case LoggingType::HDD_WBL: { + // int status = stat(HDD_DIR, &data_stat); + // if (status == 0 && S_ISDIR(data_stat.st_mode)) { + // data_file_name = std::string(HDD_DIR) + std::string(DATA_FILE_NAME); + // found_file_system = true; + // } + + // } break; + + // default: + // break; + // } + + // // Fallback to tmp directory if needed + // if (found_file_system == false) { + // int status = stat(TMP_DIR, &data_stat); + // if (status == 0 && S_ISDIR(data_stat.st_mode)) { + // data_file_name = std::string(TMP_DIR) + std::string(DATA_FILE_NAME); + // } else { + // throw Exception("Could not find temp directory : " + + // std::string(TMP_DIR)); + // } + // } + + // LOG_TRACE("DATA DIR :: %s ", data_file_name.c_str()); + + // // Create a data file + // if ((data_fd = open( + // data_file_name.c_str(), O_CREAT | O_TRUNC | O_RDWR, + // S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) { + // perror(data_file_name.c_str()); + // exit(EXIT_FAILURE); + // } + + // // Allocate the data file + // if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) { + // perror("posix_fallocate"); + // exit(EXIT_FAILURE); + // } + + // // map the data file in memory + // if ((data_file_address = mmap(NULL, data_file_len, PROT_READ | PROT_WRITE, + // MAP_SHARED, data_fd, 0)) == MAP_FAILED) { + // perror("mmap"); + // exit(EXIT_FAILURE); + // } + + // // close the pmem file -- it will remain mapped + // close(data_fd); +} + +BackendManager::~BackendManager() { + LOG_TRACE("Allocation count : %ld \n", allocation_count); + + // // Check if we need a PMEM pool + // if (peloton_logging_mode != LoggingType::NVM_WBL) return; + + // // sync and unmap the data file + // if (data_file_address != nullptr) { + // // sync the mmap'ed file to SSD or HDD + // int status = msync(data_file_address, data_file_len, MS_SYNC); + // if (status != 0) { + // perror("msync"); + // exit(EXIT_FAILURE); + // } + + // if (munmap(data_file_address, data_file_len)) { + // perror("munmap"); + // exit(EXIT_FAILURE); + // } + // } +} + +void *BackendManager::Allocate(BackendType type, size_t size) { + // Update allocation count + allocation_count++; + + switch (type) { + case BackendType::MM: + case BackendType::NVM: { + return ::operator new(size); + } break; + + case BackendType::SSD: + case BackendType::HDD: { + { + size_t cache_data_file_offset = 0; + + // Lock the file + data_file_spinlock.Lock(); + + // Check if within bounds + if (data_file_offset < data_file_len) { + cache_data_file_offset = data_file_offset; + + // Offset by the requested size + data_file_offset += size; + + // Unlock the file + data_file_spinlock.Unlock(); + + void *address = reinterpret_cast(data_file_address) + + cache_data_file_offset; + return address; + } + + data_file_spinlock.Unlock(); + throw Exception("no more memory available: offset : " + + std::to_string(data_file_offset) + " length : " + + std::to_string(data_file_len)); + + return nullptr; + } + } break; + + case BackendType::INVALID: + default: { + throw Exception("invalid backend: " + std::to_string(data_file_len)); + return nullptr; + } + } +} + +void BackendManager::Release(BackendType type, void *address) { + switch (type) { + case BackendType::MM: + case BackendType::NVM: { + ::operator delete(address); + } break; + + case BackendType::SSD: + case BackendType::HDD: { + // Nothing to do here + } break; + + case BackendType::INVALID: + default: { + // Nothing to do here + break; + } + } +} + +void BackendManager::Sync(BackendType type, void *address, size_t length) { + switch (type) { + case BackendType::MM: { + // Nothing to do here + } break; + + case BackendType::NVM: { + // flush writes to NVM + Func_flush(address, length); + Func_drain(); + clflush_count++; + } break; + + case BackendType::SSD: + case BackendType::HDD: { + // sync the mmap'ed file to SSD or HDD + int status = msync(data_file_address, data_file_len, MS_SYNC); + if (status != 0) { + perror("msync"); + exit(EXIT_FAILURE); + } + + msync_count++; + } break; + + case BackendType::INVALID: + default: { + // Nothing to do here + } break; + } +} + +} // namespace storage +} // namespace peloton diff --git a/pool/shard007/C++/0095624_InlineReductions.cpp b/pool/shard007/C++/0095624_InlineReductions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b33e9b352793b0d474973333b70444e951f54486 --- /dev/null +++ b/pool/shard007/C++/0095624_InlineReductions.cpp @@ -0,0 +1,225 @@ +#include "InlineReductions.h" +#include "Func.h" +#include "Scope.h" +#include "IROperator.h" +#include "IRMutator.h" +#include "Debug.h" +#include "CSE.h" + +namespace Halide { + +using std::string; +using std::vector; +using std::ostringstream; + +namespace Internal { + +class FindFreeVars : public IRMutator2 { +public: + vector free_vars; + vector call_args; + RDom rdom; + + FindFreeVars(RDom r, const string &n) : + rdom(r), explicit_rdom(r.defined()), name(n) { + } + +private: + bool explicit_rdom; + const string &name; + + Scope<> internal; + + using IRMutator2::visit; + + Expr visit(const Let *op) override { + Expr value = mutate(op->value); + internal.push(op->name); + Expr body = mutate(op->body); + internal.pop(op->name); + if (value.same_as(op->value) && + body.same_as(op->body)) { + return op; + } else { + return Let::make(op->name, value, body); + } + } + + Expr visit(const Variable *v) override { + string var_name = v->name; + Expr expr = v; + + if (internal.contains(var_name)) { + // Don't capture internally defined vars + return expr; + } + + if (v->reduction_domain.defined()) { + if (explicit_rdom) { + if (v->reduction_domain.same_as(rdom.domain())) { + // This variable belongs to the explicit reduction domain, so + // skip it. + return expr; + } else { + // This should be converted to a pure variable and + // added to the free vars list. + var_name = unique_name('v'); + expr = Variable::make(v->type, var_name); + } + } else { + if (!rdom.defined()) { + // We're looking for a reduction domain, and this variable + // has one. Capture it. + rdom = RDom(v->reduction_domain); + return expr; + } else if (!rdom.domain().same_as(v->reduction_domain)) { + // We were looking for a reduction domain, and already + // found one. This one is different! + user_error << "Inline reduction \"" << name + << "\" refers to reduction variables from multiple reduction domains: " + << v->name << ", " << rdom.x.name() << "\n"; + } else { + // Recapturing an already-known reduction domain + return expr; + } + } + } + + if (v->param.defined()) { + // Skip parameters + return expr; + } + + for (size_t i = 0; i < free_vars.size(); i++) { + if (var_name == free_vars[i].name()) { + return expr; + } + } + + free_vars.push_back(Var(var_name)); + call_args.push_back(v); + return expr; + } +}; +} + +Expr sum(Expr e, const std::string &name) { + return sum(RDom(), e, name); +} + +Expr sum(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + user_assert(v.rdom.defined()) << "Expression passed to sum must reference a reduction domain"; + + Func f(name); + f(v.free_vars) += e; + return f(v.call_args); +} + +Expr product(Expr e, const std::string &name) { + return product(RDom(), e, name); +} + +Expr product(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + user_assert(v.rdom.defined()) << "Expression passed to product must reference a reduction domain"; + + Func f(name); + f(v.free_vars) *= e; + return f(v.call_args); +} + +Expr maximum(Expr e, const std::string &name) { + return maximum(RDom(), e, name); +} + +Expr maximum(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + user_assert(v.rdom.defined()) << "Expression passed to maximum must reference a reduction domain"; + + Func f(name); + f(v.free_vars) = e.type().min(); + f(v.free_vars) = max(f(v.free_vars), e); + return f(v.call_args); +} + +Expr minimum(Expr e, const std::string &name) { + return minimum(RDom(), e, name); +} + +Expr minimum(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + user_assert(v.rdom.defined()) << "Expression passed to minimum must reference a reduction domain"; + + Func f(name); + f(v.free_vars) = e.type().max(); + f(v.free_vars) = min(f(v.free_vars), e); + return f(v.call_args); +} + +Tuple argmax(Expr e, const std::string &name) { + return argmax(RDom(), e, name); +} + +Tuple argmax(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + Func f(name); + + user_assert(v.rdom.defined()) << "Expression passed to argmax must reference a reduction domain"; + + Tuple initial_tup(vector(v.rdom.dimensions()+1)); + Tuple update_tup(vector(v.rdom.dimensions()+1)); + for (int i = 0; i < v.rdom.dimensions(); i++) { + initial_tup[i] = 0; + update_tup[i] = v.rdom[i]; + } + int value_index = (int)initial_tup.size()-1; + initial_tup[value_index] = e.type().min(); + update_tup[value_index] = e; + + f(v.free_vars) = initial_tup; + Expr better = e > f(v.free_vars)[value_index]; + Tuple update = tuple_select(better, update_tup, f(v.free_vars)); + f(v.free_vars) = update; + return f(v.call_args); +} + +Tuple argmin(Expr e, const std::string &name) { + return argmin(RDom(), e, name); +} + +Tuple argmin(RDom r, Expr e, const std::string &name) { + Internal::FindFreeVars v(r, name); + e = v.mutate(common_subexpression_elimination(e)); + + Func f(name); + + user_assert(v.rdom.defined()) << "Expression passed to argmin must reference a reduction domain"; + + Tuple initial_tup(vector(v.rdom.dimensions()+1)); + Tuple update_tup(vector(v.rdom.dimensions()+1)); + for (int i = 0; i < v.rdom.dimensions(); i++) { + initial_tup[i] = 0; + update_tup[i] = v.rdom[i]; + } + int value_index = (int)initial_tup.size()-1; + initial_tup[value_index] = e.type().max(); + update_tup[value_index] = e; + + f(v.free_vars) = initial_tup; + Expr better = e < f(v.free_vars)[value_index]; + f(v.free_vars) = tuple_select(better, update_tup, f(v.free_vars)); + return f(v.call_args); +} + +} diff --git a/pool/shard007/C++/0095626_Engine.cpp b/pool/shard007/C++/0095626_Engine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..867260c2279d06ea5dd583c05dd3c286f05bd418 --- /dev/null +++ b/pool/shard007/C++/0095626_Engine.cpp @@ -0,0 +1,170 @@ +/* + * Engine.cpp - implementation of LMMS' engine-system + * + * Copyright (c) 2006-2014 Tobias Doerffel + * + * This file is part of LMMS - https://lmms.io + * + * 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 (see COPYING); if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA. + * + */ + + +#include "Engine.h" +#include "BBTrackContainer.h" +#include "ConfigManager.h" +#include "FxMixer.h" +#include "Ladspa2LMMS.h" +#include "Lv2Manager.h" +#include "Mixer.h" +#include "Plugin.h" +#include "PresetPreviewPlayHandle.h" +#include "ProjectJournal.h" +#include "Song.h" +#include "BandLimitedWave.h" +#include "Oscillator.h" + +float LmmsCore::s_framesPerTick; +Mixer* LmmsCore::s_mixer = NULL; +FxMixer * LmmsCore::s_fxMixer = NULL; +BBTrackContainer * LmmsCore::s_bbTrackContainer = NULL; +Song * LmmsCore::s_song = NULL; +ProjectJournal * LmmsCore::s_projectJournal = NULL; +#ifdef LMMS_HAVE_LV2 +Lv2Manager * LmmsCore::s_lv2Manager = nullptr; +#endif +Ladspa2LMMS * LmmsCore::s_ladspaManager = NULL; +void* LmmsCore::s_dndPluginKey = nullptr; + + + + +void LmmsCore::init( bool renderOnly ) +{ + LmmsCore *engine = inst(); + + emit engine->initProgress(tr("Generating wavetables")); + // generate (load from file) bandlimited wavetables + BandLimitedWave::generateWaves(); + //initilize oscillators + Oscillator::waveTableInit(); + + emit engine->initProgress(tr("Initializing data structures")); + s_projectJournal = new ProjectJournal; + s_mixer = new Mixer( renderOnly ); + s_song = new Song; + s_fxMixer = new FxMixer; + s_bbTrackContainer = new BBTrackContainer; + +#ifdef LMMS_HAVE_LV2 + s_lv2Manager = new Lv2Manager; + s_lv2Manager->initPlugins(); +#endif + s_ladspaManager = new Ladspa2LMMS; + + s_projectJournal->setJournalling( true ); + + emit engine->initProgress(tr("Opening audio and midi devices")); + s_mixer->initDevices(); + + PresetPreviewPlayHandle::init(); + + emit engine->initProgress(tr("Launching mixer threads")); + s_mixer->startProcessing(); +} + + + + +void LmmsCore::destroy() +{ + s_projectJournal->stopAllJournalling(); + s_mixer->stopProcessing(); + + PresetPreviewPlayHandle::cleanup(); + + s_song->clearProject(); + + deleteHelper( &s_bbTrackContainer ); + + deleteHelper( &s_fxMixer ); + deleteHelper( &s_mixer ); + +#ifdef LMMS_HAVE_LV2 + deleteHelper( &s_lv2Manager ); +#endif + deleteHelper( &s_ladspaManager ); + + //delete ConfigManager::inst(); + deleteHelper( &s_projectJournal ); + + deleteHelper( &s_song ); + + delete ConfigManager::inst(); + + // The oscillator FFT plans remain throughout the application lifecycle + // due to being expensive to create, and being used whenever a userwave form is changed + Oscillator::destroyFFTPlans(); +} + + + + +bool LmmsCore::ignorePluginBlacklist() +{ + const char* envVar = getenv("LMMS_IGNORE_BLACKLIST"); + return (envVar && *envVar); +} + + + + +float LmmsCore::framesPerTick(sample_rate_t sampleRate) +{ + return sampleRate * 60.0f * 4 / + DefaultTicksPerBar / s_song->getTempo(); +} + + + + +void LmmsCore::updateFramesPerTick() +{ + s_framesPerTick = s_mixer->processingSampleRate() * 60.0f * 4 / + DefaultTicksPerBar / s_song->getTempo(); +} + + + + +void LmmsCore::setDndPluginKey(void *newKey) +{ + Q_ASSERT(static_cast(newKey)); + s_dndPluginKey = newKey; +} + + + + +void *LmmsCore::pickDndPluginKey() +{ + return s_dndPluginKey; +} + + + + +LmmsCore * LmmsCore::s_instanceOfMe = NULL; diff --git a/pool/shard007/C++/0095627_usModuleContext.cpp b/pool/shard007/C++/0095627_usModuleContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f4aa9c2b623c411a2dc38f028bff717d073ce23 --- /dev/null +++ b/pool/shard007/C++/0095627_usModuleContext.cpp @@ -0,0 +1,196 @@ +/*============================================================================= + + Library: CppMicroServices + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + 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 "usModuleContext.h" + +#include "usModuleRegistry.h" +#include "usModulePrivate.h" +#include "usModuleSettings.h" +#include "usCoreModuleContext_p.h" +#include "usServiceRegistry_p.h" +#include "usServiceReferenceBasePrivate.h" + +#include + +US_BEGIN_NAMESPACE + +class ModuleContextPrivate { + +public: + + ModuleContextPrivate(ModulePrivate* module) + : module(module) + {} + + ModulePrivate* module; +}; + + +ModuleContext::ModuleContext(ModulePrivate* module) + : d(new ModuleContextPrivate(module)) +{} + +ModuleContext::~ModuleContext() +{ + delete d; +} + +Module* ModuleContext::GetModule() const +{ + return d->module->q; +} + +Module* ModuleContext::GetModule(long id) const +{ + return d->module->coreCtx->moduleHooks.FilterModule(this, ModuleRegistry::GetModule(id)); +} + +Module* ModuleContext::GetModule(const std::string& name) +{ + return ModuleRegistry::GetModule(name); +} + +std::vector ModuleContext::GetModules() const +{ + std::vector modules = ModuleRegistry::GetModules(); + d->module->coreCtx->moduleHooks.FilterModules(this, modules); + return modules; +} + +ServiceRegistrationU ModuleContext::RegisterService(const InterfaceMap& service, + const ServiceProperties& properties) +{ + return d->module->coreCtx->services.RegisterService(d->module, service, properties); +} + +std::vector ModuleContext::GetServiceReferences(const std::string& clazz, + const std::string& filter) +{ + std::vector result; + std::vector refs; + d->module->coreCtx->services.Get(clazz, filter, d->module, refs); + for (std::vector::const_iterator iter = refs.begin(); + iter != refs.end(); ++iter) + { + result.push_back(ServiceReferenceU(*iter)); + } + return result; +} + +ServiceReferenceU ModuleContext::GetServiceReference(const std::string& clazz) +{ + return d->module->coreCtx->services.Get(d->module, clazz); +} + +void* ModuleContext::GetService(const ServiceReferenceBase& reference) +{ + if (!reference) + { + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); + } + return reference.d->GetService(d->module->q); +} + +InterfaceMap ModuleContext::GetService(const ServiceReferenceU& reference) +{ + if (!reference) + { + throw std::invalid_argument("Default constructed ServiceReference is not a valid input to GetService()"); + } + return reference.d->GetServiceInterfaceMap(d->module->q); +} + +bool ModuleContext::UngetService(const ServiceReferenceBase& reference) +{ + ServiceReferenceBase ref = reference; + return ref.d->UngetService(d->module->q, true); +} + +void ModuleContext::AddServiceListener(const ServiceListener& delegate, + const std::string& filter) +{ + d->module->coreCtx->listeners.AddServiceListener(this, delegate, NULL, filter); +} + +void ModuleContext::RemoveServiceListener(const ServiceListener& delegate) +{ + d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, NULL); +} + +void ModuleContext::AddModuleListener(const ModuleListener& delegate) +{ + d->module->coreCtx->listeners.AddModuleListener(this, delegate, NULL); +} + +void ModuleContext::RemoveModuleListener(const ModuleListener& delegate) +{ + d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, NULL); +} + +void ModuleContext::AddServiceListener(const ServiceListener& delegate, void* data, + const std::string &filter) +{ + d->module->coreCtx->listeners.AddServiceListener(this, delegate, data, filter); +} + +void ModuleContext::RemoveServiceListener(const ServiceListener& delegate, void* data) +{ + d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, data); +} + +void ModuleContext::AddModuleListener(const ModuleListener& delegate, void* data) +{ + d->module->coreCtx->listeners.AddModuleListener(this, delegate, data); +} + +void ModuleContext::RemoveModuleListener(const ModuleListener& delegate, void* data) +{ + d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, data); +} + +std::string ModuleContext::GetDataFile(const std::string &filename) const +{ + // compute the module storage path +#ifdef US_PLATFORM_WINDOWS + static const char separator = '\\'; +#else + static const char separator = '/'; +#endif + + std::string baseStoragePath = ModuleSettings::GetStoragePath(); + if (baseStoragePath.empty()) return std::string(); + if (baseStoragePath != d->module->baseStoragePath) + { + d->module->baseStoragePath = baseStoragePath; + d->module->storagePath.clear(); + } + + if (d->module->storagePath.empty()) + { + char buf[50]; + sprintf(buf, "%ld", d->module->info.id); + d->module->storagePath = baseStoragePath + separator + buf + "_" + d->module->info.name + separator; + } + return d->module->storagePath + filename; +} + + +US_END_NAMESPACE diff --git a/pool/shard007/C++/0095628_rpcnet.cpp b/pool/shard007/C++/0095628_rpcnet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e03515c8c98a9f959a8a8cd36cbe867319851545 --- /dev/null +++ b/pool/shard007/C++/0095628_rpcnet.cpp @@ -0,0 +1,151 @@ +// Copyright (c) 2009-2012 Bitcoin Developers +// Copyright (c) 2014-2018 Stealth R&D LLC +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "net.h" +#include "bitcoinrpc.h" +#include "alert.h" +#include "wallet.h" +#include "db.h" +#include "walletdb.h" + +using namespace json_spirit; +using namespace std; + +Value getconnectioncount(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "getconnectioncount\n" + "Returns the number of connections to other nodes."); + + LOCK(cs_vNodes); + return (int)vNodes.size(); +} + +Value getadjustedtime(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "getadjustedtime\n" + "Returns the Stealth network adjusted time."); + + return (boost::int64_t)GetAdjustedTime(); +} + +static void CopyNodeStats(std::vector& vstats) +{ + vstats.clear(); + + LOCK(cs_vNodes); + vstats.reserve(vNodes.size()); + BOOST_FOREACH(CNode* pnode, vNodes) { + CNodeStats stats; + pnode->copyStats(stats); + vstats.push_back(stats); + } +} + +Value getpeerinfo(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "getpeerinfo\n" + "Returns data about each connected network node."); + + vector vstats; + CopyNodeStats(vstats); + + Array ret; + + BOOST_FOREACH(const CNodeStats& stats, vstats) { + Object obj; + + obj.push_back(Pair("addr", stats.addrName)); + obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices))); + obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); + obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); + obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); + obj.push_back(Pair("version", stats.nVersion)); + // Use the sanitized form of subver here, to avoid tricksy remote peers from + // corrupting or modifiying the JSON output by putting special characters in + // their ver message. + obj.push_back(Pair("subver", stats.cleanSubVer)); + obj.push_back(Pair("inbound", stats.fInbound)); + obj.push_back(Pair("releasetime", (boost::int64_t)stats.nReleaseTime)); + obj.push_back(Pair("startingheight", stats.nStartingHeight)); + obj.push_back(Pair("banscore", stats.nMisbehavior)); + + ret.push_back(obj); + } + + return ret; +} + +extern CCriticalSection cs_mapAlerts; +extern map mapAlerts; + +// ppcoin: send alert. +// There is a known deadlock situation with ThreadMessageHandler +// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages() +// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage() +Value sendalert(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 6) + throw runtime_error( + "sendalert [cancelupto]\n" + " is the alert text message\n" + " is hex string of alert master private key\n" + " is the minimum applicable internal client version\n" + " is the maximum applicable internal client version\n" + " is integer priority number\n" + " is the alert id (id=0 canels *all* alerts except id=1 alerts)\n" + "[cancelupto] cancels all alert id's up to this number\n" + "Returns true or false."); + + CAlert alert; + CKey key; + + alert.strStatusBar = params[0].get_str(); + alert.nMinVer = atoi(params[2].get_str()); + alert.nMaxVer = atoi(params[3].get_str()); + alert.nPriority = atoi(params[4].get_str()); + alert.nID = atoi(params[5].get_str()); + if (params.size() > 6) + alert.nCancel = atoi(params[6].get_str()); + alert.nVersion = PROTOCOL_VERSION; + alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60; + alert.nExpiration = GetAdjustedTime() + 365*24*60*60; + + CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); + sMsg << (CUnsignedAlert)alert; + alert.vchMsg = vector(sMsg.begin(), sMsg.end()); + + printf("sendalert 1\n"); + vector vchPrivKey = ParseHex(params[1].get_str()); + key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash + if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) + throw runtime_error( + "Unable to sign alert, check private key?\n"); + if(!alert.ProcessAlert()) + throw runtime_error( + "Failed to process alert.\n"); + // Relay alert + { + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + alert.RelayTo(pnode); + } + + Object result; + result.push_back(Pair("strStatusBar", alert.strStatusBar)); + result.push_back(Pair("nVersion", alert.nVersion)); + result.push_back(Pair("nMinVer", alert.nMinVer)); + result.push_back(Pair("nMaxVer", alert.nMaxVer)); + result.push_back(Pair("nPriority", alert.nPriority)); + result.push_back(Pair("nID", alert.nID)); + if (alert.nCancel > 0) + result.push_back(Pair("nCancel", alert.nCancel)); + return result; +} diff --git a/pool/shard007/C++/0095629_utility.cpp b/pool/shard007/C++/0095629_utility.cpp new file mode 100644 index 0000000000000000000000000000000000000000..933833b24ebb76833764a12acb60c61ae9145d06 --- /dev/null +++ b/pool/shard007/C++/0095629_utility.cpp @@ -0,0 +1,42 @@ +//***************************************************************************** +// +// utility.cpp: Utility Implementation file +// +//***************************************************************************** +#include "utility.h" +#include "GeomBase.h" + +// ****************************************************************** +// ¼ÆËãÁ¿ÏòÁ¿µÄ¼Ð½Ç +// vec1 * vec2 +// cos¦È = ------------- +// |vec1|*|vec2| +// ****************************************************************** +double AngleBetween(const TVector3D& vec1, const TVector3D& vec2) +{ + if (IsParallel(vec1, vec2)) // ÅжÏÁ½ÏòÁ¿ÊÇ·ñƽÐÐ + {// Á½ÏòÁ¿Æ½ÐÐ, ·µ»Ø¼Ð½ÇΪ0 + return 0.0; + } + else + { + return acos(vec1*(vec2.GetNormal()) / vec1.Norm()); + } + +} +// ÅжÏÁ½ÏòÁ¿ÊÇ·ñƽÐÐ +bool IsParallel(const TVector3D& vec1, const TVector3D& vec2) +{ + return IS_ZERO((vec1^vec2).Norm2()); +} +// ¼ÆËãÁ½ÏòÁ¿²îµÄÄ£ +double DistOf(const TPoint3D& lpt, const TPoint3D& rpt) +{ + TVector3D vec = rpt - lpt; + return vec.Norm(); +} +// ÅжÏÁ½ÏòÁ¿ÊÇ·ñ´¹Ö± +bool IsOrthogonal(const TVector3D& vec1, const TVector3D& vec2) +{ + return IS_ZERO(vec1*vec2); +} \ No newline at end of file diff --git a/pool/shard007/C++/0095631_CreatureAI.cpp b/pool/shard007/C++/0095631_CreatureAI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b590a3132d5b5632384b0cfd1af03d7f632652f --- /dev/null +++ b/pool/shard007/C++/0095631_CreatureAI.cpp @@ -0,0 +1,235 @@ +/** + * This code is part of MaNGOS. Contributor & Copyright details are in AUTHORS/THANKS. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "CreatureAI.h" +#include "Creature.h" +#include "DBCStores.h" +#include "Spell.h" +#include "GridNotifiers.h" +#include "GridNotifiersImpl.h" +#include "CellImpl.h" + +CreatureAI::~CreatureAI() +{ +} + +void CreatureAI::AttackedBy(Unit* attacker) +{ + if (!m_creature->getVictim()) + AttackStart(attacker); +} + +CanCastResult CreatureAI::CanCastSpell(Unit* pTarget, const SpellEntry* pSpell, bool isTriggered) +{ + // If not triggered, we check + if (!isTriggered) + { + // State does not allow + if (m_creature->hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL)) + return CAST_FAIL_STATE; + + if (pSpell->GetPreventionType() == SPELL_PREVENTION_TYPE_SILENCE && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED)) + return CAST_FAIL_STATE; + + if (pSpell->GetPreventionType() == SPELL_PREVENTION_TYPE_PACIFY && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED)) + return CAST_FAIL_STATE; + + // Check for power (also done by Spell::CheckCast()) + if (m_creature->GetPower((Powers)pSpell->powerType) < Spell::CalculatePowerCost(pSpell, m_creature)) + return CAST_FAIL_POWER; + } + + if (const SpellRangeEntry* pSpellRange = sSpellRangeStore.LookupEntry(pSpell->rangeIndex)) + { + if (pTarget != m_creature) + { + // pTarget is out of range of this spell (also done by Spell::CheckCast()) + float fDistance = m_creature->GetCombatDistance(pTarget, pSpell->rangeIndex == SPELL_RANGE_IDX_COMBAT); + + if (fDistance > (m_creature->IsHostileTo(pTarget) ? pSpellRange->maxRange : pSpellRange->maxRangeFriendly)) + return CAST_FAIL_TOO_FAR; + + float fMinRange = m_creature->IsHostileTo(pTarget) ? pSpellRange->minRange : pSpellRange->minRangeFriendly; + + if (fMinRange && fDistance < fMinRange) + return CAST_FAIL_TOO_CLOSE; + } + + return CAST_OK; + } + else + return CAST_FAIL_OTHER; +} + +CanCastResult CreatureAI::DoCastSpellIfCan(Unit* pTarget, uint32 uiSpell, uint32 uiCastFlags, ObjectGuid uiOriginalCasterGUID) +{ + Unit* pCaster = m_creature; + + if (uiCastFlags & CAST_FORCE_TARGET_SELF) + pCaster = pTarget; + + // Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered + if (!pCaster->IsNonMeleeSpellCasted(false) || (uiCastFlags & (CAST_TRIGGERED | CAST_INTERRUPT_PREVIOUS))) + { + if (const SpellEntry* pSpell = sSpellStore.LookupEntry(uiSpell)) + { + // If cast flag CAST_AURA_NOT_PRESENT is active, check if target already has aura on them + if (uiCastFlags & CAST_AURA_NOT_PRESENT) + { + if (pTarget->HasAura(uiSpell)) + return CAST_FAIL_TARGET_AURA; + } + + // Check if cannot cast spell + if (!(uiCastFlags & (CAST_FORCE_TARGET_SELF | CAST_FORCE_CAST))) + { + CanCastResult castResult = CanCastSpell(pTarget, pSpell, uiCastFlags & CAST_TRIGGERED); + + if (castResult != CAST_OK) + return castResult; + } + + // Interrupt any previous spell + if (uiCastFlags & CAST_INTERRUPT_PREVIOUS && pCaster->IsNonMeleeSpellCasted(false)) + pCaster->InterruptNonMeleeSpells(false); + + pCaster->CastSpell(pTarget, pSpell, uiCastFlags & CAST_TRIGGERED, NULL, NULL, uiOriginalCasterGUID); + return CAST_OK; + } + else + { + sLog.outErrorDb("DoCastSpellIfCan by creature entry %u attempt to cast spell %u but spell does not exist.", m_creature->GetEntry(), uiSpell); + return CAST_FAIL_OTHER; + } + } + else + return CAST_FAIL_IS_CASTING; +} + +bool CreatureAI::DoMeleeAttackIfReady() +{ + return m_creature->UpdateMeleeAttackingState(); +} + +void CreatureAI::SetCombatMovement(bool enable, bool stopOrStartMovement /*=false*/) +{ + m_isCombatMovement = enable; + + if (enable) + m_creature->clearUnitState(UNIT_STAT_NO_COMBAT_MOVEMENT); + else + m_creature->addUnitState(UNIT_STAT_NO_COMBAT_MOVEMENT); + + if (stopOrStartMovement && m_creature->getVictim()) // Only change current movement while in combat + { + if (enable) + m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), m_attackDistance, m_attackAngle); + else if (!enable && m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) + m_creature->StopMoving(); + } +} + +void CreatureAI::HandleMovementOnAttackStart(Unit* victim) +{ + if (m_isCombatMovement) + m_creature->GetMotionMaster()->MoveChase(victim, m_attackDistance, m_attackAngle); + // TODO - adapt this to only stop OOC-MMGens when MotionMaster rewrite is finished + else if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE || m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == RANDOM_MOTION_TYPE) + { + m_creature->GetMotionMaster()->MoveIdle(); + m_creature->StopMoving(); + } +} + +// //////////////////////////////////////////////////////////////////////////////////////////////// +// Event system +// //////////////////////////////////////////////////////////////////////////////////////////////// + +class AiDelayEventAround : public BasicEvent +{ + public: + AiDelayEventAround(AIEventType eventType, ObjectGuid invokerGuid, Creature& owner, std::list const& receivers, uint32 miscValue) : + BasicEvent(), + m_eventType(eventType), + m_invokerGuid(invokerGuid), + m_owner(owner), + m_miscValue(miscValue) + { + // Pushing guids because in delay can happen some creature gets despawned => invalid pointer + m_receiverGuids.reserve(receivers.size()); + for (std::list::const_iterator itr = receivers.begin(); itr != receivers.end(); ++itr) + m_receiverGuids.push_back((*itr)->GetObjectGuid()); + } + + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override + { + Unit* pInvoker = m_owner.GetMap()->GetUnit(m_invokerGuid); + + for (GuidVector::const_reverse_iterator itr = m_receiverGuids.rbegin(); itr != m_receiverGuids.rend(); ++itr) + { + if (Creature* pReceiver = m_owner.GetMap()->GetAnyTypeCreature(*itr)) + { + pReceiver->AI()->ReceiveAIEvent(m_eventType, &m_owner, pInvoker, m_miscValue); + // Special case for type 0 (call-assistance) + if (m_eventType == AI_EVENT_CALL_ASSISTANCE && pInvoker && pReceiver->CanAssistTo(&m_owner, pInvoker)) + { + pReceiver->SetNoCallAssistance(true); + pReceiver->AI()->AttackStart(pInvoker); + } + } + } + m_receiverGuids.clear(); + + return true; + } + + private: + AiDelayEventAround(); + + ObjectGuid m_invokerGuid; + GuidVector m_receiverGuids; + Creature& m_owner; + + AIEventType m_eventType; + uint32 m_miscValue; +}; + +void CreatureAI::SendAIEventAround(AIEventType eventType, Unit* pInvoker, uint32 uiDelay, float fRadius, uint32 miscValue /*=0*/) const +{ + if (fRadius > 0) + { + std::list receiverList; + + // Use this check here to collect only assitable creatures in case of CALL_ASSISTANCE, else be less strict + MaNGOS::AnyAssistCreatureInRangeCheck u_check(m_creature, eventType == AI_EVENT_CALL_ASSISTANCE ? pInvoker : NULL, fRadius); + MaNGOS::CreatureListSearcher searcher(receiverList, u_check); + Cell::VisitGridObjects(m_creature, searcher, fRadius); + + if (!receiverList.empty()) + { + AiDelayEventAround* e = new AiDelayEventAround(eventType, pInvoker ? pInvoker->GetObjectGuid() : ObjectGuid(), *m_creature, receiverList, miscValue); + m_creature->m_Events.AddEvent(e, m_creature->m_Events.CalculateTime(uiDelay)); + } + } +} + +void CreatureAI::SendAIEvent(AIEventType eventType, Unit* pInvoker, Creature* pReceiver, uint32 miscValue /*=0*/) const +{ + MANGOS_ASSERT(pReceiver); + pReceiver->AI()->ReceiveAIEvent(eventType, m_creature, pInvoker, miscValue); +} diff --git a/pool/shard007/C++/0095636_1.cc b/pool/shard007/C++/0095636_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a98df6072add4dd143659a2082329b4971699e5 --- /dev/null +++ b/pool/shard007/C++/0095636_1.cc @@ -0,0 +1,65 @@ +// Copyright (C) 2005 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 2, 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 COPYING. If not, write to the Free +// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, +// USA. + +// 25.1.6 count_if + +#include +#include +#include + +using __gnu_test::test_container; +using __gnu_test::input_iterator_wrapper; + +typedef test_container Container; +int array[] = {0, 0, 0, 1, 0, 1}; + +bool +predicate(const int& i) +{ return i == 1; } + +void +test1() +{ + Container con(array, array); + VERIFY(std::count_if(con.begin(), con.end(), + predicate) == 0); +} + +void +test2() +{ + Container con(array, array + 1); + VERIFY(std::count_if(con.begin(), con.end(), + predicate) == 0); +} + +void +test3() +{ + Container con(array, array + 6); + VERIFY(std::count_if(con.begin(), con.end(), + predicate) == 2); +} + +int +main() +{ + test1(); + test2(); + test3(); +} diff --git a/pool/shard007/C++/0095641_double.cpp b/pool/shard007/C++/0095641_double.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81f236ca881f8fd339e2d273172c0bd93bef2b00 --- /dev/null +++ b/pool/shard007/C++/0095641_double.cpp @@ -0,0 +1,105 @@ +// spreadsort double sorting example. +// +// Copyright Steven Ross 2009-2014. +// +// 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) + +// See http://www.boost.org/libs/sort for library home page. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace boost::sort::spreadsort; + +#define DATA_TYPE double +#define CAST_TYPE boost::int64_t + +//Pass in an argument to test std::sort +//Note that this converts NaNs and -0.0 to 0.0, so that sorting results are +//identical every time +int main(int argc, const char ** argv) { + size_t uCount,uSize=sizeof(DATA_TYPE); + bool stdSort = false; + unsigned loopCount = 1; + for (int u = 1; u < argc; ++u) { + if (std::string(argv[u]) == "-std") + stdSort = true; + else + loopCount = atoi(argv[u]); + } + std::ifstream input("input.txt", std::ios_base::in | std::ios_base::binary); + if (input.fail()) { + printf("input.txt could not be opened\n"); + return 1; + } + double total = 0.0; + std::vector array; + input.seekg (0, std::ios_base::end); + size_t length = input.tellg(); + uCount = length/uSize; + //Using this to support compilers that don't support 64-bit constants + CAST_TYPE exponent_mask = 0x7ff00000; + exponent_mask <<= 32; + CAST_TYPE top_exponent_bit = 0x40000000; + top_exponent_bit <<= 32; + //Run multiple loops, if requested + for (unsigned u = 0; u < loopCount; ++u) { + input.seekg (0, std::ios_base::beg); + //Conversion to a vector + array.resize(uCount); + unsigned v = 0; + while (input.good() && v < uCount) { + input.read(reinterpret_cast(&(array[v])), uSize ); + //Checking for denormalized numbers + if (!(float_mem_cast(array[v]) & exponent_mask)) { + //Make the top exponent bit high + CAST_TYPE temp = top_exponent_bit | + float_mem_cast(array[v]); + memcpy(&(array[v]), &temp, sizeof(DATA_TYPE)); + } + //Testcase doesn't sort NaNs; they just cause confusion + if (!(array[v] < 0.0) && !(0.0 < array[v])) + array[v] = 0.0; + ++v; + } + clock_t start, end; + double elapsed; + start = clock(); + if (stdSort) + //std::sort(&(array[0]), &(array[0]) + uCount); + std::sort(array.begin(), array.end()); + else + //float_sort(&(array[0]), &(array[0]) + uCount); + float_sort(array.begin(), array.end()); + end = clock(); + elapsed = static_cast(end - start) ; + std::ofstream ofile; + if (stdSort) + ofile.open("standard_sort_out.txt", std::ios_base::out | + std::ios_base::binary | std::ios_base::trunc); + else + ofile.open("boost_sort_out.txt", std::ios_base::out | + std::ios_base::binary | std::ios_base::trunc); + if (ofile.good()) { + for (unsigned v = 0; v < array.size(); ++v) { + ofile.write(reinterpret_cast(&(array[v])), sizeof(array[v]) ); + } + ofile.close(); + } + total += elapsed; + array.clear(); + } + if (stdSort) + printf("std::sort elapsed time %f\n", total / CLOCKS_PER_SEC); + else + printf("spreadsort elapsed time %f\n", total / CLOCKS_PER_SEC); + return 0; +} diff --git a/pool/shard007/C++/0095642_HitTestingTransformState.cpp b/pool/shard007/C++/0095642_HitTestingTransformState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b8e06785e319d053bd20ff1306fd770dc09a7bb --- /dev/null +++ b/pool/shard007/C++/0095642_HitTestingTransformState.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "core/layout/HitTestingTransformState.h" + +#include "platform/geometry/LayoutRect.h" +#include "wtf/PassOwnPtr.h" + +namespace blink { + +void HitTestingTransformState::translate(int x, int y, TransformAccumulation accumulate) +{ + m_accumulatedTransform.translate(x, y); + if (accumulate == FlattenTransform) + flattenWithTransform(m_accumulatedTransform); + + m_accumulatingTransform = accumulate == AccumulateTransform; +} + +void HitTestingTransformState::applyTransform(const TransformationMatrix& transformFromContainer, TransformAccumulation accumulate) +{ + m_accumulatedTransform.multiply(transformFromContainer); + if (accumulate == FlattenTransform) + flattenWithTransform(m_accumulatedTransform); + + m_accumulatingTransform = accumulate == AccumulateTransform; +} + +void HitTestingTransformState::flatten() +{ + flattenWithTransform(m_accumulatedTransform); +} + +void HitTestingTransformState::flattenWithTransform(const TransformationMatrix& t) +{ + TransformationMatrix inverseTransform = t.inverse(); + m_lastPlanarPoint = inverseTransform.projectPoint(m_lastPlanarPoint); + m_lastPlanarQuad = inverseTransform.projectQuad(m_lastPlanarQuad); + m_lastPlanarArea = inverseTransform.projectQuad(m_lastPlanarArea); + + m_accumulatedTransform.makeIdentity(); + m_accumulatingTransform = false; +} + +FloatPoint HitTestingTransformState::mappedPoint() const +{ + return m_accumulatedTransform.inverse().projectPoint(m_lastPlanarPoint); +} + +FloatQuad HitTestingTransformState::mappedQuad() const +{ + return m_accumulatedTransform.inverse().projectQuad(m_lastPlanarQuad); +} + +FloatQuad HitTestingTransformState::mappedArea() const +{ + return m_accumulatedTransform.inverse().projectQuad(m_lastPlanarArea); +} + +LayoutRect HitTestingTransformState::boundsOfMappedArea() const +{ + return m_accumulatedTransform.inverse().clampedBoundsOfProjectedQuad(m_lastPlanarArea); +} + +} // namespace blink diff --git a/pool/shard007/C++/0095647_decoder_tester.cc b/pool/shard007/C++/0095647_decoder_tester.cc new file mode 100644 index 0000000000000000000000000000000000000000..29aa5be1a8a17c1cba391c24b4008bc3a096665d --- /dev/null +++ b/pool/shard007/C++/0095647_decoder_tester.cc @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2012 The Native Client Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +/* + * Tests the decoder. + */ + +#ifndef NACL_TRUSTED_BUT_NOT_TCB +#error This file is not meant for use in the TCB +#endif + +#include "native_client/src/trusted/validator_arm/decoder_tester.h" + +#include +#include "gtest/gtest.h" + +using nacl_arm_dec::kArm32InstSize; +using nacl_arm_dec::Instruction; +using nacl_arm_dec::MAY_BE_SAFE; + +namespace nacl_arm_test { + +DecoderTester::DecoderTester() +{} + +bool DecoderTester::PassesParsePreconditions( + nacl_arm_dec::Instruction inst, + const NamedClassDecoder& decoder) { + UNREFERENCED_PARAMETER(inst); + UNREFERENCED_PARAMETER(decoder); + return true; +} + +bool DecoderTester::ApplySanityChecks(Instruction inst, + const NamedClassDecoder& decoder) { + // Only allow different decoders if the expected decoder is expected to be + // able to apply safety. + bool test = (&decoder == &ExpectedDecoder()); + if (!test) { + if (nacl_arm_dec::DECODER_ERROR != ExpectedDecoder().safety(inst)) { + EXPECT_EQ(nacl_arm_dec::DECODER_ERROR, ExpectedDecoder().safety(inst)) + << "Expected " << ExpectedDecoder().name() << " but found " + << decoder.name() << " for " << InstContents(); + } + } + // Only allow additional sanity checks if the found decoder is the + // expected decoder. + return test; +} + +void DecoderTester::TestAtIndex(int index) { + while (true) { + // First see if we have completed generating test. + if (index < 0) { + ProcessMatch(); + return; + } + + // If reached, more pattern to process. + char selector = Pattern(index); + + if (selector == '0') { + SetBit(index, false); + --index; + continue; + } + + if (selector == '1') { + SetBit(index, true); + --index; + continue; + } + + if (islower(selector)) { + // Find the length of the run of the same character (selector) in + // the pattern. Then, test all combinations of zero and one for the + // run length. + int length = 1; + while (Pattern(index - length) == selector) ++length; + TestAtIndexExpandAll(index, length); + return; + } + + if (isupper(selector)) { + // Find length of selector, then expand. + int length = 1; + while (Pattern(index - length) == selector) ++length; + if (length <= 4) { + TestAtIndexExpandAll(index, length); + } else { + TestAtIndexExpandFill4(index, length, true); + TestAtIndexExpandFill4(index, length, false); + } + return; + } + GTEST_FAIL() << "Don't understand pattern character '" << selector << "'"; + } +} + +void DecoderTester::TestAtIndexExpandAll(int index, int length) { + if (length == 32) { + // To be safe about overflow conditions, we use the recursive solution here. + // Try setting index bit to false and continue testing. + SetBit(index, false); + TestAtIndexExpandAll(index-1, length-1); + + // Try setting index bit to true and continue testing. + SetBit(index, true); + TestAtIndexExpandAll(index-1, length-1); + } else if (length == 0) { + TestAtIndex(index); + } else { + // Use an (hopefully faster) iterative solution. + uint32_t i; + for (i = 0; i <= (((uint32_t) 1) << length) - 1; ++i) { + SetBitRange(index - (length - 1), length, i); + TestAtIndex(index - length); + } + } +} + +void DecoderTester::FillBitRange(int index, int length, bool value) { + if (length == 0) + return; + uint32_t val = (value ? 1 : 0); + uint32_t bits = (val << length) - val; + SetBitRange(index - (length - 1), length, bits); +} + +void DecoderTester::TestAtIndexExpandFill(int index, int length, bool value) { + FillBitRange(index, length, value); + TestAtIndex(index - length); +} + +void DecoderTester::TestAtIndexExpandFillAll( + int index, int stride, int length, bool value) { + ASSERT_LT(stride, 32) << "TestAtIndexExpandFillAll - illegal stride"; + if (stride == 0) { + TestAtIndexExpandFill(index, length, value); + return; + } else { + uint32_t i; + for (i = 0; i <= (((uint32_t) 1) << stride) - 1; ++i) { + SetBitRange(index - (stride - 1), stride, i); + TestAtIndexExpandFill(index - stride, length - stride, value); + } + } +} + +void DecoderTester::TestAtIndexExpandFill4(int index, int length, bool value) { + int stride = 4; + ASSERT_GT(length, stride); + int window = length - stride; + for (int i = 0; i <= window; ++i) { + FillBitRange(index, i, value); + TestAtIndexExpandFillAll(index - i, stride, length - i, value); + } +} + +Arm32DecoderTester::Arm32DecoderTester( + const NamedClassDecoder& expected_decoder) + : DecoderTester(), + expected_decoder_(expected_decoder), + pattern_(""), + state_(), + inst_((uint32_t) 0xFFFFFFFF) { +} + +void Arm32DecoderTester::Test(const char* pattern) { + pattern_ = pattern; + ASSERT_EQ(static_cast(kArm32InstSize), + static_cast(strlen(pattern_))) + << "Arm32 pattern length incorrect: " << pattern_; + TestAtIndex(kArm32InstSize-1); +} + +const NamedClassDecoder& Arm32DecoderTester::ExpectedDecoder() const { + return expected_decoder_; +} + +static inline char BoolToChar(bool value) { + return '0' + (uint8_t) value; +} + +const char* Arm32DecoderTester::InstContents() const { + static char buffer[kArm32InstSize + 1]; + for (int i = 1; i <= kArm32InstSize; ++i) { + buffer[kArm32InstSize - i] = BoolToChar(inst_.Bit(i - 1)); + } + buffer[kArm32InstSize] = '\0'; + return buffer; +} + +char Arm32DecoderTester::Pattern(int index) const { + return pattern_[kArm32InstSize - (index + 1)]; +} + +void Arm32DecoderTester::InjectInstruction(nacl_arm_dec::Instruction inst) { + inst_.Copy(inst); +} + +const NamedClassDecoder& Arm32DecoderTester::GetInstDecoder() const { + return state_.decode_named(inst_); +} + +void Arm32DecoderTester::ProcessMatch() { + // Completed pattern, decode and test resulting state. + const NamedClassDecoder& decoder = GetInstDecoder(); + if (!PassesParsePreconditions(inst_, decoder)) + return; + if (MAY_BE_SAFE == decoder.safety(inst_)) + ApplySanityChecks(inst_, decoder); +} + +void Arm32DecoderTester::SetBit(int index, bool value) { + ASSERT_LT(index, kArm32InstSize) + << "Arm32DecoderTester::SetBit(" << index << ", " << value << ")"; + ASSERT_GE(index , 0) + << "Arm32DecoderTester::SetBit(" << index << ", " << value << ")"; + inst_.SetBit(index, value); +} + +void Arm32DecoderTester::SetBitRange(int index, int length, uint32_t value) { + ASSERT_LE(index + length, kArm32InstSize) + << "Arm32DecoderTester::SetBitRange(" << index << ", " << length + << ", " << value << ")"; + ASSERT_GE(index, 0) + << "Arm32DecoderTester::SetBitRange(" << index << ", " << length + << ", " << value << ")"; + inst_.SetBits(index + (length - 1), index, value); +} + +} // namespace nacl_arm_test diff --git a/pool/shard007/C++/0095653_OnLoad.cpp b/pool/shard007/C++/0095653_OnLoad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6cbef092de08ab973c83fc4ca0c4031441bde7b --- /dev/null +++ b/pool/shard007/C++/0095653_OnLoad.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include <../instrumentation/HermesMemoryDumper.h> +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace facebook { +namespace react { + +static ::hermes::vm::RuntimeConfig makeRuntimeConfig( + jlong heapSizeMB, + bool es6Proxy) { + namespace vm = ::hermes::vm; + auto gcConfigBuilder = + vm::GCConfig::Builder() + .withName("RN") + // For the next two arguments: avoid GC before TTI by initializing the + // runtime to allocate directly in the old generation, but revert to + // normal operation when we reach the (first) TTI point. + .withAllocInYoung(false) + .withRevertToYGAtTTI(true); + + if (heapSizeMB > 0) { + gcConfigBuilder.withMaxHeapSize(heapSizeMB << 20); + } + + return vm::RuntimeConfig::Builder() + .withGCConfig(gcConfigBuilder.build()) + .withES6Proxy(es6Proxy) + .build(); +} + +static void installBindings(jsi::Runtime &runtime) { + react::Logger androidLogger = + static_cast( + &reactAndroidLoggingHook); + react::bindNativeLogger(runtime, androidLogger); + + react::PerformanceNow androidNativePerformanceNow = + static_cast(&reactAndroidNativePerformanceNowHook); + react::bindNativePerformanceNow(runtime, androidNativePerformanceNow); +} + +class HermesExecutorHolder + : public jni::HybridClass { + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/hermes/reactexecutor/HermesExecutor;"; + + static jni::local_ref initHybridDefaultConfig( + jni::alias_ref) { + JReactMarker::setLogPerfMarkerIfNeeded(); + + return makeCxxInstance( + std::make_unique(installBindings)); + } + + static jni::local_ref + initHybrid(jni::alias_ref, jlong heapSizeMB, bool es6Proxy) { + JReactMarker::setLogPerfMarkerIfNeeded(); + auto runtimeConfig = makeRuntimeConfig(heapSizeMB, es6Proxy); + return makeCxxInstance(std::make_unique( + installBindings, JSIExecutor::defaultTimeoutInvoker, runtimeConfig)); + } + + static bool canLoadFile(jni::alias_ref, const std::string &path) { + return true; + } + + static void registerNatives() { + registerHybrid( + {makeNativeMethod("initHybrid", HermesExecutorHolder::initHybrid), + makeNativeMethod( + "initHybridDefaultConfig", + HermesExecutorHolder::initHybridDefaultConfig), + makeNativeMethod("canLoadFile", HermesExecutorHolder::canLoadFile)}); + } + + private: + friend HybridBase; + using HybridBase::HybridBase; +}; + +} // namespace react +} // namespace facebook + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { + return facebook::jni::initialize( + vm, [] { facebook::react::HermesExecutorHolder::registerNatives(); }); +} diff --git a/pool/shard007/C++/0095658_trie.cpp b/pool/shard007/C++/0095658_trie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2c1ccda3fc837d6a10277bbce1494a8297e7440 --- /dev/null +++ b/pool/shard007/C++/0095658_trie.cpp @@ -0,0 +1,132 @@ +#include +#include +#include + +using namespace std; + +const int num_chars = 26; + +class Trie +{ +public: + Trie(); + Trie(Trie& tr); + virtual ~Trie(); + int trie_search(const char* word,char* entry) const; + int insert(const char* word,const char* entry); + int remove(const char* word,char* entry); +protected: + struct Trie_node + { + char* data; //若不为空,表示从root到此结点构成一个单词 + Trie_node* branch[num_chars]; //分支 + Trie_node(); //构造函数 + }; + + Trie_node* root; //根结点(指针) +}; + +Trie::Trie_node::Trie_node() +{ + data = NULL; + for(int i = 0; i < num_chars; ++i) + { + branch[i] = NULL; + } +} + +Trie::Trie():root(NULL) +{ + +} + +Trie::~Trie() +{ + +} + + +int Trie::insert(const char* word,const char* entry) +{ + int result = 1,position = 0; + if(root == NULL) + root = new Trie_node; //初始插入,根节点为空 + char char_code; + Trie_node *location = root; //从根节点开始 + while(location != NULL && *word != 0) + { + if(*word >= 'A' && *word <= 'Z') + char_code = *word - 'A'; + else if(*word >= 'a' && *word <= 'z') + char_code = *word - 'a'; + else + return 0; // 不合法的单词 + + // 不存在此分支 + if(location->branch[char_code] == NULL) + location->branch[char_code] = new Trie_node; // 创建空分支 + //转入分支 + location = location->branch[char_code]; + position++; + word++; + } + if(location->data != NULL) + result = 0; //欲插入的单词已经存在 + else + { + //插入数据 + location->data = new char[strlen(entry) + 1]; //分配内存 + strcpy(location->data,entry); //给data赋值表明单词存在 + } + return result; +} + +int Trie::trie_search(const char* word,char* entry) const +{ + int position = 0; //层数 + char char_code; + Trie_node *location = root; //从根结点开始 + while(location != NULL && *word != 0) + { + if(*word >= 'A' && *word <= 'Z') + char_code = *word - 'A'; + else if(*word >= 'a' && *word <= 'z') + char_code = *word - 'a'; + else + return 0; + location = location->branch[char_code]; + position++; + word++; + } + + // 找到,获取数据,成功返回 + if(location != NULL && location->data != NULL) + { + strcpy(entry,location->data); + return 1; + } + else + return 0; // 不合法的单词 +} + +int main() +{ + Trie t; + char entry[100]; + t.insert("a","DET"); + t.insert("abacus","NOUN"); + t.insert("abalone","NOUN"); + t.insert("abandon","VERB"); + t.insert("abate","VERB"); + t.insert("this","PRON"); + + if(t.trie_search("this",entry)) + cout<<"'this' was found. pos: "< +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + vector preorderTraversal(TreeNode *root) { + vector result; + + TreeNode *right_most; + while(root) { + if(root->left) { + right_most = root->left; + while(right_most->right && right_most->right != root) { + right_most = right_most->right; + } + if(right_most->right == NULL) { + right_most->right = root; + result.push_back(root->val); + root = root->left; + } + else { + right_most->right = NULL; + root = root->right; + } + } + else { + result.push_back(root->val); + root = root->right; + } + } + + return result; + } +}; +int main() { + Solution s; + TreeNode *root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector result = s.preorderTraversal(root); + for(int i = 0; i < result.size(); i ++) + cout << result[i] << "\t"; + cout << endl; +} diff --git a/pool/shard007/C++/0095665_daytime_server.cpp b/pool/shard007/C++/0095665_daytime_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7c4141effc52946f75347f62915a78bd58bf0cc --- /dev/null +++ b/pool/shard007/C++/0095665_daytime_server.cpp @@ -0,0 +1,51 @@ +// +// daytime_server.cpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2016 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) +// + +#include +#include +#include +#include + +using boost::asio::ip::tcp; + +std::string make_daytime_string() +{ + using namespace std; // For time_t, time and ctime; + time_t now = time(0); + return ctime(&now); +} + +int main() +{ + try + { + boost::asio::io_service io_service; + + tcp::endpoint endpoint(tcp::v4(), 13); + tcp::acceptor acceptor(io_service, endpoint); + + for (;;) + { + tcp::iostream stream; + boost::system::error_code ec; + acceptor.accept(*stream.rdbuf(), ec); + if (!ec) + { + stream << make_daytime_string(); + } + } + } + catch (std::exception& e) + { + std::cerr << e.what() << std::endl; + } + + return 0; +} diff --git a/pool/shard007/C++/0095668_seqc.cpp b/pool/shard007/C++/0095668_seqc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b483af17e309ae6b54a7523ac7a319aa39fa70e --- /dev/null +++ b/pool/shard007/C++/0095668_seqc.cpp @@ -0,0 +1,202 @@ +// ========================================================================== +// seqc +// ========================================================================== +// Copyright (c) 2006-2012, Knut Reinert, FU Berlin +// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. +// +// ========================================================================== +// Author: Daniel Kersting <@fu-berlin.de> +// Author: Antje Oldenburg +// ========================================================================== + +#include +#include + +#include +#include +#include +#include +#include + + +#include + +#include "seqc.h" +#include "read_stats.h" +#include "output.h" + +using namespace seqan; +using std::cout; +using std::endl; +using std::ostream; + +void AppOptions::out(ostream & os){ + os << "active configuration" << endl + << "========================================"<< endl + << "VERBOSITY\t" << verbosity << endl + << "inputFile\t" << inputFile << endl + << "max-reads\t" << maxReads << endl; +} + +// -------------------------------------------------------------------------- +// Function parseCommandLine() +// -------------------------------------------------------------------------- + +seqan::ArgumentParser::ParseResult +parseCommandLine(AppOptions & options, int argc, char const ** argv) +{ + // Setup ArgumentParser. + seqan::ArgumentParser parser("seqc"); + // Set short description, version, and date. + setShortDescription(parser, "Quality Control app for NGS reads - implemented using seqan lib."); + setVersion(parser, "0.1"); + setDate(parser, "May 2013"); + + // Define usage line and long description. + addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fITEXT\\fP\""); + addDescription(parser, "This is the application description."); + + // We require one argument. + addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "inputFile")); + + addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); + addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); + addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); + + // custom options + addOption(parser, seqan::ArgParseOption( + "r","max-reads", + "Maximum number of records to analyse. Report on what we found so far, as if the input ended after given number of reads", + seqan::ArgParseArgument::INTEGER, "INT")); + + addOption(parser, seqan::ArgParseOption( + "o", "outdir", + "name of directory that will be created to contain gathered report data, defaults to _out", + seqan::ArgParseArgument::STRING, "STRING" + )); +// setDefaultValue(parser,"outdir",); + // Add Examples Section. + addTextSection(parser, "Examples"); + addListItem(parser, "\\fBseqc\\fP \\fB-v\\fP \\fItext\\fP", + "Call with \\fITEXT\\fP set to \"text\" with verbose output."); + + // Parse command line. + seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); + + // Only extract options if the program will continue after parseCommandLine() + if (res != seqan::ArgumentParser::PARSE_OK) + return res; + + // Extract option values. + if (isSet(parser, "quiet")) + options.verbosity = 0; + if (isSet(parser, "verbose")) + options.verbosity = 2; + if (isSet(parser, "very-verbose")) + options.verbosity = 3; + + + seqan::getArgumentValue(options.inputFile, parser, 0); + seqan::getOptionValue(options.maxReads,parser, "max-reads"); + + seqan::getOptionValue(options.outdir,parser, "outdir"); + + + return seqan::ArgumentParser::PARSE_OK; +} + + + +// -------------------------------------------------------------------------- +// Function main() +// -------------------------------------------------------------------------- +// Program entry point. + +int main(int argc, char const ** argv) +{ + // Parse the command line. + seqan::ArgumentParser parser; + AppOptions options; + seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv); + + // If there was an error parsing or built-in argument parser functionality + // was triggered then we exit the program. The return code is 1 if there + // were errors and 0 if there were none. + if (res != seqan::ArgumentParser::PARSE_OK) + return res == seqan::ArgumentParser::PARSE_ERROR; + + // Print the command line arguments back to the user. + if (options.verbosity > 0) + options.out(cout); + + + // start reading the input stream + seqan::CharString id; + seqan::Dna5String seq; + seqan::CharString qual; + + seqan::SequenceStream seqStreamIn(seqan::toCString(options.inputFile)); + + if (!isGood(seqStreamIn)) + { + std::cerr << "ERROR: Could not open the file.\n"; + return 1; + } + + + /* + * Initialize the data structure for stats + * + */ + + ReadStats readStats(1); + + unsigned noReads = 0; + int writeResult = 0; + while((noReads < options.maxReads) && !atEnd(seqStreamIn)) + { + ++noReads; + if (readRecord(id, seq, qual, seqStreamIn) == 0){ + readStats.collectReadStats(id, seq, qual); + readStats.dupCheck(seq); + } else { + std::cerr << "WARN: Bad Sequence in record [#" << noReads << "] " << id << std::endl; + } + } + + + readStats.jobParams["Filename"] = seqan::toCString(options.inputFile); + readStats.jobParams["File type"] = "Conventional base calls"; + readStats.jobParams["Encoding"] = "Sanger / Illumina 1.9"; + + TSVWriter writer; + + writer.writeAll(readStats, options.outdir); + + std::cout << "no of reads analyzed: " << noReads << std::endl; + return 0; +} diff --git a/pool/shard007/C++/0095669_project.cpp b/pool/shard007/C++/0095669_project.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c70ee1d89285687f5f3560e73b1fd267298e370b --- /dev/null +++ b/pool/shard007/C++/0095669_project.cpp @@ -0,0 +1,152 @@ +#include "project.h" +#include "luainterface.h" +#include "groundingsystem.h" +#include "groundingsystemreport.h" +#include +#include +#include +#include +#include +#include +#include + +Project *g_project = nullptr; + +Project::Project() +{ + QDir prev = QCoreApplication::applicationDirPath(); + prev.cd(".."); + QSettings *settings = new QSettings(prev.path() + "/input.ftl", QSettings::IniFormat); + + load(settings); + + g_database = new Database(); + g_database->load(settings); + + QString error; + if(!calculate(error)) + qDebug() << "Error:" << error; + + +// if(!QDir("assets").exists()) { +// QDir prev = QDir::current(); +// prev.cd(".."); +// QDir::setCurrent(prev.path()); +// if(!QDir("assets").exists()) +// qDebug() << "Could not find assets"; +// } + +// g_lua.initialize(); +// error = g_lua.executeFile("assets/lua/init.lua").c_str(); +// if(!error.isEmpty()) +// qDebug() << error; + + if(error.isEmpty()) { + QDir dir; + dir.remove(prev.path() + "/results.ftl"); + generateReport(prev.path() + "/results.ftl"); + } +} + +void Project::load(QSettings *settings) +{ + settings->beginGroup("Project"); + m_transmitterId = settings->value("transmitterId").toUInt(); + m_designerId = settings->value("designerId", 1).toUInt(); + m_epcId = settings->value("epcId").toUInt(); + m_type = (ProjectType) settings->value("type").toInt(); + m_reference = settings->value("reference").toString(); + m_auctionNumber = settings->value("auctionNumber").toString(); + m_lotNumber = settings->value("lotNumber").toString(); + m_title = settings->value("title").toString(); + m_description = settings->value("description").toString(); + m_date = settings->value("date").toString(); + settings->endGroup(); +} + +bool Project::calculate(QString& error) +{ + for(GroundingSystemPtr gs : g_database->getGroundingSystems()) { + if(!gs->calculateResistance(gs, error)) + return false; + + gs->calculateSurfaceVoltage(gs); + } + + return true; +} + +void Project::generateReport(const QString &fileName) +{ + GroundingSystemReport *gsReport = new GroundingSystemReport(); + gsReport->generateResources(); + + QFile file(fileName); + file.open(QIODevice::WriteOnly | QIODevice::Text); + QTextStream out(&file); + for(int i = 0; i < g_database->getGroundingSystems().size(); i++) { + GroundingSystemPtr gs = g_database->getGroundingSystems()[i]; + QString gsArray = "GroundingSystems." + QString::number(i+1) + "."; + out << gsArray << "id = " << gs->getId() << "\n"; + out << gsArray << "name = " << gs->getName() << "\n"; + out << gsArray << "resistance = " << gs->getResistance() << "\n"; + out << gsArray << "injectedCurrent = " << gs->getInjectedCurrent() << "\n"; + out << gsArray << "voltage = " << gs->getResistance() * gs->getInjectedCurrent() << "\n"; + + for(int j = 0; j < gs->getSurfaceVoltagePoints().size(); j++) { + const Vector3Dd& point = gs->getSurfaceVoltagePoints()[j]; + QString pointsArray = gsArray + "Points." + QString::number(j+1) + "."; + out << pointsArray << "x = " << point.x() << "\n"; + out << pointsArray << "y = " << point.y() << "\n"; + out << pointsArray << "surfaceVoltage = " << gs->calculateSurfaceVoltage(point) << "\n"; + } + + for(int j = 0; j < gs->getSurfaceVoltageProfiles().size(); j++) { + SurfaceVoltageProfile profile = gs->getSurfaceVoltageProfiles()[j]; + QString profileArray = gsArray + "Profiles." + QString::number(j+1) + "."; + out << profileArray << "touch = " << profile.touch << "\n"; + out << profileArray << "touchX = " << profile.maxTouchVoltagePos.x() << "\n"; + out << profileArray << "touchY = " << profile.maxTouchVoltagePos.y() << "\n"; + out << profileArray << "maxTouchVoltage = " << profile.maxTouchVoltage << "\n"; + out << profileArray << "step = " << profile.step << "\n"; + out << profileArray << "stepX0 = " << profile.maxStepVoltagePos1.x() << "\n"; + out << profileArray << "stepY0 = " << profile.maxStepVoltagePos1.y() << "\n"; + out << profileArray << "stepX1 = " << profile.maxStepVoltagePos2.x() << "\n"; + out << profileArray << "stepY1 = " << profile.maxStepVoltagePos2.y() << "\n"; + out << profileArray << "maxStepVoltage = " << profile.maxStepVoltage << "\n"; + out << profileArray << "precision = " << profile.precision << "\n"; + + double x1 = profile.pi.distanceTo(profile.pf); + double precision = profile.precision; + Vector3Dd dir = (profile.pf - profile.pi).normalized(); + + int pointIndex = 0; + for(double x = 0; x < x1; x+=precision) { + QString profilePointsArray = profileArray + "Points." + QString::number(pointIndex++) + "."; + Vector3Dd point = profile.pi + (dir * x); + out << profilePointsArray << "x = " << point.x() << "\n"; + out << profilePointsArray << "y = " << point.y() << "\n"; + out << profilePointsArray << "voltage = " << gs->calculateSurfaceVoltage(point) << "\n"; + } + + QVector weights = {50, 70}; + for(int j = 0; j < weights.size(); j++) { + QString limitsArray = gsArray + "Limits." + QString::number(j+1) + "."; + double weight = weights[j]; + out << limitsArray << "weight = " << weight << "\n"; + int faultClearCount = 1; + for(double faultTime = 0.5; faultTime <= 3; faultTime += 0.5) { + QString faultTimesArray = limitsArray + "FaultTimes." + QString::number(faultClearCount++) + "."; + double touchPotential = gs->calculateTouchPotentialLimit2013(faultTime, weight); + double stepPotential = gs->calculateStepPotentialLimit2013(faultTime, weight); + out << faultTimesArray << "faultTime = " << faultTime << "\n"; + out << faultTimesArray << "touchPotential = " << touchPotential << "\n"; + out << faultTimesArray << "stepPotential = " << stepPotential << "\n"; + } + } + + } + } + + file.close(); +} diff --git a/pool/shard007/C++/0095673_Gripper.cc b/pool/shard007/C++/0095673_Gripper.cc new file mode 100644 index 0000000000000000000000000000000000000000..877cf60719558bd7fa30114e9a384a49c9636ed0 --- /dev/null +++ b/pool/shard007/C++/0095673_Gripper.cc @@ -0,0 +1,235 @@ +/* + * Copyright 2012 Open Source Robotics 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 "common/Events.hh" + +#include "physics/World.hh" +#include "physics/Joint.hh" +#include "physics/Link.hh" +#include "physics/Collision.hh" +#include "physics/Contact.hh" +#include "physics/Model.hh" +#include "physics/PhysicsEngine.hh" +#include "physics/Gripper.hh" + +using namespace gazebo; +using namespace physics; + +///////////////////////////////////////////////// +Gripper::Gripper(ModelPtr _model) +{ + this->model = _model; + this->world = this->model->GetWorld(); + this->physics = this->world->GetPhysicsEngine(); + + this->diffs.resize(10); + this->diffIndex = 0; + this->ResetDiffs(); + + this->attached = false; + + this->updateRate = common::Time(0, common::Time::SecToNano(0.75)); +} + +///////////////////////////////////////////////// +Gripper::~Gripper() +{ + this->model.reset(); + this->physics.reset(); + this->world.reset(); + this->connections.clear(); +} + +///////////////////////////////////////////////// +void Gripper::Load(sdf::ElementPtr _sdf) +{ + this->fixedJoint = this->physics->CreateJoint("revolute", this->model); + + sdf::ElementPtr grasp_check = _sdf->GetElement("grasp_check"); + this->min_contact_count = grasp_check->GetValueUInt("min_contact_count"); + this->attachSteps = grasp_check->GetValueInt("attach_steps"); + this->detachSteps = grasp_check->GetValueInt("detach_steps"); + + sdf::ElementPtr palmLinkElem = _sdf->GetElement("palm_link"); + this->palmLink = this->model->GetLink(palmLinkElem->GetValueString()); + if (!this->palmLink) + gzerr << "palm link [" << palmLinkElem->GetValueString() + << "] not found!\n"; + + sdf::ElementPtr gripperLinkElem = _sdf->GetElement("gripper_link"); + + + while (gripperLinkElem) + { + physics::LinkPtr gripperLink + = this->model->GetLink(gripperLinkElem->GetValueString()); + for (unsigned int j = 0; j < gripperLink->GetChildCount(); ++j) + { + physics::CollisionPtr collision = gripperLink->GetCollision(j); + std::map::iterator collIter + = this->collisions.find(collision->GetScopedName()); + if (collIter != this->collisions.end()) + continue; + collision->SetContactsEnabled(true); + + this->collisions[collision->GetScopedName()] = collision; + } + gripperLinkElem = gripperLinkElem->GetNextElement("gripper_link"); + } + + this->connections.push_back(event::Events::ConnectWorldUpdateEnd( + boost::bind(&Gripper::OnUpdate, this))); +} + +///////////////////////////////////////////////// +void Gripper::Init() +{ + this->prevUpdateTime = common::Time::GetWallTime(); + this->zeroCount = 0; + this->posCount = 0; + this->attached = false; +} + +///////////////////////////////////////////////// +void Gripper::OnUpdate() +{ + if (common::Time::GetWallTime() - this->prevUpdateTime < this->updateRate) + return; + + // @todo: should package the decision into a function + if (this->contacts.size() >= this->min_contact_count) + { + this->posCount++; + this->zeroCount = 0; + } + else + { + this->zeroCount++; + this->posCount = std::max(0, this->posCount-1); + } + + if (this->posCount > this->attachSteps && !this->attached) + this->HandleAttach(); + else if (this->zeroCount > this->detachSteps && this->attached) + this->HandleDetach(); + + this->contacts.clear(); + this->prevUpdateTime = common::Time::GetWallTime(); +} + +///////////////////////////////////////////////// +void Gripper::HandleAttach() +{ + if (!this->palmLink) + { + gzwarn << "palm link not found, not enforcing grasp hack!\n"; + return; + } + + std::map cc; + std::map contactCounts; + std::map::iterator iter; + + for (unsigned int i = 0; i < this->contacts.size(); ++i) + { + std::string name1 = this->contacts[i].collision1; + std::string name2 = this->contacts[i].collision2; + + if (this->collisions.find(name1) == this->collisions.end()) + { + cc[name1] = boost::dynamic_pointer_cast( + this->world->GetEntity(this->contacts[i].collision1)); + contactCounts[name1] += 1; + } + if (this->collisions.find(name2) == this->collisions.end()) + { + cc[name2] = boost::dynamic_pointer_cast( + this->world->GetEntity(this->contacts[i].collision2)); + contactCounts[name2] += 1; + } + } + + iter = contactCounts.begin(); + while (iter != contactCounts.end()) + { + if (iter->second < 2) + contactCounts.erase(iter++); + else + { + if (!this->attached && cc[iter->first]) + { + math::Pose diff = cc[iter->first]->GetLink()->GetWorldPose() - + this->palmLink->GetWorldPose(); + + double dd = (diff - this->prevDiff).pos.GetSquaredLength(); + + this->prevDiff = diff; + + this->diffs[this->diffIndex] = dd; + double var = math::variance(this->diffs); + double max = math::max(this->diffs); + + if (var < 1e-5 && max < 1e-5) + { + this->attached = true; + + this->fixedJoint->Load(this->palmLink, + cc[iter->first]->GetLink(), math::Pose()); + this->fixedJoint->Init(); + this->fixedJoint->SetHighStop(0, 0); + this->fixedJoint->SetLowStop(0, 0); + } + + this->diffIndex = (this->diffIndex+1) % 10; + } + ++iter; + } + } +} + +///////////////////////////////////////////////// +void Gripper::HandleDetach() +{ + this->attached = false; + this->fixedJoint->Detach(); +} + +///////////////////////////////////////////////// +void Gripper::OnContact(const std::string &/*_collisionName*/, + const physics::Contact &_contact) +{ + CollisionPtr collision1 = boost::dynamic_pointer_cast( + this->world->GetEntity(_contact.collision1)); + + CollisionPtr collision2 = boost::dynamic_pointer_cast( + this->world->GetEntity(_contact.collision1)); + + if ((collision1 && collision1->IsStatic()) || + (collision2 && collision2->IsStatic())) + { + return; + } + + this->contacts.push_back(_contact); +} + +///////////////////////////////////////////////// +void Gripper::ResetDiffs() +{ + for (unsigned int i = 0; i < 10; ++i) + this->diffs[i] = GZ_DBL_MAX; +} diff --git a/pool/shard007/C++/0095678_CWE36_Absolute_Path_Traversal__char_connect_socket_open_17.cpp b/pool/shard007/C++/0095678_CWE36_Absolute_Path_Traversal__char_connect_socket_open_17.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d587f8f96b173a1ff37f1a994596bcbabe88cb3 --- /dev/null +++ b/pool/shard007/C++/0095678_CWE36_Absolute_Path_Traversal__char_connect_socket_open_17.cpp @@ -0,0 +1,211 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE36_Absolute_Path_Traversal__char_connect_socket_open_17.cpp +Label Definition File: CWE36_Absolute_Path_Traversal.label.xml +Template File: sources-sink-17.tmpl.cpp +*/ +/* + * @description + * CWE: 36 Absolute Path Traversal + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Full path and file name + * Sink: open + * BadSink : Open the file named in data using open() + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" + +#ifdef _WIN32 +#define OPEN _open +#define CLOSE _close +#else +#define OPEN open +#define CLOSE close +#endif + +namespace CWE36_Absolute_Path_Traversal__char_connect_socket_open_17 +{ + +#ifndef OMITBAD + +void bad() +{ + int i; + char * data; + char dataBuffer[FILENAME_MAX] = ""; + data = dataBuffer; + for(i = 0; i < 1; i++) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + { + int fileDesc; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + if (fileDesc != -1) + { + CLOSE(fileDesc); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource in the for statement */ +static void goodG2B() +{ + int h; + char * data; + char dataBuffer[FILENAME_MAX] = ""; + data = dataBuffer; + for(h = 0; h < 1; h++) + { +#ifdef _WIN32 + /* FIX: Use a fixed, full path and file name */ + strcat(data, "c:\\temp\\file.txt"); +#else + /* FIX: Use a fixed, full path and file name */ + strcat(data, "/tmp/file.txt"); +#endif + } + { + int fileDesc; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + if (fileDesc != -1) + { + CLOSE(fileDesc); + } + } +} + +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 CWE36_Absolute_Path_Traversal__char_connect_socket_open_17; /* 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/shard007/C++/0095680_example_escort.cpp b/pool/shard007/C++/0095680_example_escort.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21c8c916f085af0db30a0d37b66640b9725b84d6 --- /dev/null +++ b/pool/shard007/C++/0095680_example_escort.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2011 SingularityCore + * Copyright (C) 2008-2011 TrinityCore + * Copyright (C) 2006-2009 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 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, see . + */ + +/* ScriptData +SDName: Example_Escort +SD%Complete: 100 +SDComment: Script used for testing escortAI +SDCategory: Script Examples +EndScriptData */ + +#include "ScriptPCH.h" +#include "ScriptedEscortAI.h" + +enum eEnums +{ + NPC_FELBOAR = 21878, + + SPELL_DEATH_COIL = 33130, + SPELL_ELIXIR_OF_FORTITUDE = 3593, + SPELL_BLUE_FIREWORK = 11540, + + SAY_AGGRO1 = -1999910, + SAY_AGGRO2 = -1999911, + SAY_WP_1 = -1999912, + SAY_WP_2 = -1999913, + SAY_WP_3 = -1999914, + SAY_WP_4 = -1999915, + SAY_DEATH_1 = -1999916, + SAY_DEATH_2 = -1999917, + SAY_DEATH_3 = -1999918, + SAY_SPELL = -1999919, + SAY_RAND_1 = -1999920, + SAY_RAND_2 = -1999921 +}; + +#define GOSSIP_ITEM_1 "Click to Test Escort(Attack, Run)" +#define GOSSIP_ITEM_2 "Click to Test Escort(NoAttack, Walk)" +#define GOSSIP_ITEM_3 "Click to Test Escort(NoAttack, Run)" + +class example_escort : public CreatureScript +{ + public: + + example_escort() + : CreatureScript("example_escort") + { + } + + struct example_escortAI : public npc_escortAI + { + // CreatureAI functions + example_escortAI(Creature* creature) : npc_escortAI(creature) { } + + uint32 m_uiDeathCoilTimer; + uint32 m_uiChatTimer; + + void JustSummoned(Creature* summoned) + { + summoned->AI()->AttackStart(me); + } + + // Pure Virtual Functions (Have to be implemented) + void WaypointReached(uint32 uiWP) + { + switch (uiWP) + { + case 1: + DoScriptText(SAY_WP_1, me); + break; + case 3: + DoScriptText(SAY_WP_2, me); + me->SummonCreature(NPC_FELBOAR, me->GetPositionX()+5.0f, me->GetPositionY()+7.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 3000); + break; + case 4: + if (Player* player = GetPlayerForEscort()) + { + //pTmpPlayer is the target of the text + DoScriptText(SAY_WP_3, me, player); + //pTmpPlayer is the source of the text + DoScriptText(SAY_WP_4, player); + } + break; + } + } + + void EnterCombat(Unit* /*who*/) + { + if (HasEscortState(STATE_ESCORT_ESCORTING)) + { + if (Player* player = GetPlayerForEscort()) + DoScriptText(SAY_AGGRO1, me, player); + } + else + DoScriptText(SAY_AGGRO2, me); + } + + void Reset() + { + m_uiDeathCoilTimer = 4000; + m_uiChatTimer = 4000; + } + + void JustDied(Unit* killer) + { + if (HasEscortState(STATE_ESCORT_ESCORTING)) + { + if (Player* player = GetPlayerForEscort()) + { + // not a likely case, code here for the sake of example + if (killer == me) + { + DoScriptText(SAY_DEATH_1, me, player); + } + else + DoScriptText(SAY_DEATH_2, me, player); + } + } + else + DoScriptText(SAY_DEATH_3, me); + } + + void UpdateAI(const uint32 uiDiff) + { + //Must update npc_escortAI + npc_escortAI::UpdateAI(uiDiff); + + //Combat check + if (me->getVictim()) + { + if (m_uiDeathCoilTimer <= uiDiff) + { + DoScriptText(SAY_SPELL, me); + DoCast(me->getVictim(), SPELL_DEATH_COIL, false); + m_uiDeathCoilTimer = 4000; + } + else + m_uiDeathCoilTimer -= uiDiff; + } + else + { + //Out of combat but being escorted + if (HasEscortState(STATE_ESCORT_ESCORTING)) + { + if (m_uiChatTimer <= uiDiff) + { + if (me->HasAura(SPELL_ELIXIR_OF_FORTITUDE, 0)) + { + DoScriptText(SAY_RAND_1, me); + DoCast(me, SPELL_BLUE_FIREWORK, false); + } + else + { + DoScriptText(SAY_RAND_2, me); + DoCast(me, SPELL_ELIXIR_OF_FORTITUDE, false); + } + + m_uiChatTimer = 12000; + } + else + m_uiChatTimer -= uiDiff; + } + } + } + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new example_escortAI(creature); + } + + bool OnGossipHello(Player* player, Creature* creature) + { + player->TalkedToCreature(creature->GetEntry(), creature->GetGUID()); + player->PrepareGossipMenu(creature, 0); + + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); + + player->SendPreparedGossip(creature); + + return true; + } + + bool OnGossipSelect(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction) + { + player->PlayerTalkClass->ClearMenus(); + npc_escortAI* pEscortAI = CAST_AI(example_escort::example_escortAI, creature->AI()); + + switch(uiAction) + { + case GOSSIP_ACTION_INFO_DEF+1: + player->CLOSE_GOSSIP_MENU(); + + if (pEscortAI) + pEscortAI->Start(true, true, player->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+2: + player->CLOSE_GOSSIP_MENU(); + + if (pEscortAI) + pEscortAI->Start(false, false, player->GetGUID()); + break; + case GOSSIP_ACTION_INFO_DEF+3: + player->CLOSE_GOSSIP_MENU(); + + if (pEscortAI) + pEscortAI->Start(false, true, player->GetGUID()); + break; + default: + return false; // nothing defined -> trinity core handling + } + + return true; // no default handling -> prevent trinity core handling + } +}; + +void AddSC_example_escort() +{ + new example_escort(); +} diff --git a/pool/shard007/C++/0095681_callj.cpp b/pool/shard007/C++/0095681_callj.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df19e1d653654c41455ed5ad023ffed399fca7bb --- /dev/null +++ b/pool/shard007/C++/0095681_callj.cpp @@ -0,0 +1,52 @@ +#include +#include + +#ifdef _WIN32 +#define PATH_SEPARATOR ';' +#else +#define PATH_SEPARATOR ':' +#endif + +int main() +{ + JavaVMOption options[1]; + JNIEnv *env; + JavaVM *jvm; + JavaVMInitArgs vm_args; + long status; + jclass cls; + jmethodID mid; + jint square; + jboolean jnot; + + options[0].optionString = "-Djava.class.path=."; + memset(&vm_args, 0, sizeof(vm_args)); + vm_args.version = JNI_VERSION_1_2; + vm_args.nOptions = 1; + vm_args.options = options; + status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); + + if (status != JNI_ERR) + { + cls = env->FindClass("Sample2"); + if(cls !=0) + { mid = env->GetStaticMethodID(cls, "intMethod", "(I)I"); + if(mid !=0) + { square = env->CallStaticIntMethod(cls, mid, 5); + printf("Result of intMethod: %d\n", square); + } + + mid = env->GetStaticMethodID(cls, "booleanMethod", "(Z)Z"); + if(mid !=0) + { jnot = env->CallStaticBooleanMethod(cls, mid, 1); + printf("Result of booleanMethod: %d\n", jnot); + } + } + + jvm->DestroyJavaVM(); + return 0; + } + else + return -1; +} + diff --git a/pool/shard007/C++/0095684_rpc_address.cpp b/pool/shard007/C++/0095684_rpc_address.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8022ecf8e76f1fa54f3876c3535add349764fb2e --- /dev/null +++ b/pool/shard007/C++/0095684_rpc_address.cpp @@ -0,0 +1,217 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Microsoft Corporation + * + * -=- Robust Distributed System Nucleus (rDSN) -=- + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include + +namespace dsn { + +const rpc_address rpc_address::s_invalid_address; + +/*static*/ +uint32_t rpc_address::ipv4_from_host(const char *name) +{ + sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + + addr.sin_family = AF_INET; + if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1)) { + hostent *hp = ::gethostbyname(name); + int err = h_errno; + + if (hp == nullptr) { + derror("gethostbyname failed, name = %s, err = %d.", name, err); + return 0; + } else { + memcpy((void *)&(addr.sin_addr.s_addr), (const void *)hp->h_addr, (size_t)hp->h_length); + } + } + + // converts from network byte order to host byte order + return (uint32_t)ntohl(addr.sin_addr.s_addr); +} + +/*static*/ +bool rpc_address::is_site_local_address(uint32_t ip_net) +{ + uint32_t iphost = ntohl(ip_net); + return (iphost >= 0x0A000000 && iphost <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255 + (iphost >= 0xAC100000 && iphost <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255 + (iphost >= 0xC0A80000 && iphost <= 0xC0A8FFFF) || // 192.168.0.0-192.168.255.255 + false; +} + +/*static*/ +bool rpc_address::is_docker_netcard(const char *netcard_interface, uint32_t ip_net) +{ + if (dsn::string_view(netcard_interface).find("docker") != dsn::string_view::npos) + return true; + uint32_t iphost = ntohl(ip_net); + return iphost == 0xAC112A01; // 172.17.42.1 +} + +/*static*/ +uint32_t rpc_address::ipv4_from_network_interface(const char *network_interface) +{ + uint32_t ret = 0; + + struct ifaddrs *ifa = nullptr; + if (getifaddrs(&ifa) == 0) { + struct ifaddrs *i = ifa; + while (i != nullptr) { + if (i->ifa_name != nullptr && i->ifa_addr != nullptr && + i->ifa_addr->sa_family == AF_INET) { + uint32_t ip_val = ((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr; + if (strcmp(i->ifa_name, network_interface) == 0 || + (network_interface[0] == '\0' && !is_docker_netcard(i->ifa_name, ip_val) && + is_site_local_address(ip_val))) { + ret = (uint32_t)ntohl(ip_val); + break; + } else { + ddebug("skip interface(%s), address(%08X)", i->ifa_name, ip_val); + } + } + i = i->ifa_next; + } + + if (i == nullptr) { + derror("get local ip from network interfaces failed, network_interface = %s", + network_interface); + } else { + ddebug("get ip address from network interface(%s), addr(%08X), input interface(%s)", + i->ifa_name, + ret, + network_interface); + } + + if (ifa != nullptr) { + // remember to free it + freeifaddrs(ifa); + } + } + + return ret; +} + +rpc_address::~rpc_address() { set_invalid(); } + +rpc_address::rpc_address(const rpc_address &another) { *this = another; } + +rpc_address &rpc_address::operator=(const rpc_address &another) +{ + if (this == &another) { + // avoid memory leak + return *this; + } + set_invalid(); + _addr = another._addr; + switch (another.type()) { + case HOST_TYPE_GROUP: + group_address()->add_ref(); + break; + default: + break; + } + return *this; +} + +void rpc_address::assign_group(const char *name) +{ + set_invalid(); + _addr.group.type = HOST_TYPE_GROUP; + dsn::rpc_group_address *addr = new dsn::rpc_group_address(name); + // take the lifetime of rpc_uri_address, release_ref when change value or call destructor + addr->add_ref(); + _addr.group.group = (uint64_t)addr; +} + +void rpc_address::set_invalid() +{ + switch (type()) { + case HOST_TYPE_GROUP: + group_address()->release_ref(); + break; + default: + break; + } + _addr.value = 0; +} + +static __thread fixed_size_buffer_pool<8, 256> bf; + +const char *rpc_address::ipv4_str() const +{ + char *p = bf.next(); + auto sz = bf.get_chunk_size(); + struct in_addr net_addr; + + if (_addr.v4.type == HOST_TYPE_IPV4) { + net_addr.s_addr = htonl(ip()); + inet_ntop(AF_INET, &net_addr, p, sz); + } else { + p = (char *)"invalid_ipv4"; + } + return p; +} + +const char *rpc_address::to_string() const +{ + char *p = bf.next(); + auto sz = bf.get_chunk_size(); + struct in_addr net_addr; + int ip_len; + + switch (_addr.v4.type) { + case HOST_TYPE_IPV4: + net_addr.s_addr = htonl(ip()); + inet_ntop(AF_INET, &net_addr, p, sz); + ip_len = strlen(p); + snprintf_p(p + ip_len, sz - ip_len, ":%hu", port()); + break; + case HOST_TYPE_GROUP: + p = (char *)group_address()->name(); + break; + default: + p = (char *)"invalid address"; + break; + } + + return (const char *)p; +} +} // namespace dsn diff --git a/pool/shard007/C++/0095686_weak_machine.cpp b/pool/shard007/C++/0095686_weak_machine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..812704b185120733c8015c77eadc69d55e1f8e1d --- /dev/null +++ b/pool/shard007/C++/0095686_weak_machine.cpp @@ -0,0 +1,76 @@ + +#include "main.h" +#include +#include + +static std::map machineFactory; + +bool registerMachineType(size_t type_hash, CreateFunction creator_function){ + if (machineFactory.find(type_hash) != machineFactory.end()){ + PyErr_Format(PyExc_TypeError, "The given machine hash %zu already has been registered.", type_hash); + return false; + } + machineFactory[type_hash] = creator_function; + return true; +} + +PyObject* createMachine(boost::shared_ptr machine){ + size_t type_hash = boost::typeindex::type_id_runtime(*machine).hash_code(); + if (machineFactory.find(type_hash) == machineFactory.end()){ + PyErr_Format(PyExc_TypeError, "The given machine hash %zu has not been registered.", type_hash); + return NULL; + } + return machineFactory[type_hash](machine); +} + +static PyObject* weakMachineCreate(boost::shared_ptr machine){ + PyObject* o = WeakMachineType.tp_alloc(&WeakMachineType,0); + reinterpret_cast(o)->base = machine; + return o; +} + +int weakMachineCheck(PyObject* o){ + if (!o) return 0; + return PyObject_IsInstance(o, reinterpret_cast(&WeakMachineType)); +} + +int weakMachineConverter(PyObject* o, WeakMachineObject** a) { + if (!weakMachineCheck(o)) return 0; + Py_INCREF(o); + (*a) = reinterpret_cast(o); + return 1; +} + + +static auto weakMachine_doc = bob::extension::ClassDoc( + "WeakMachine", + "Pure virtual base class for weak machines" +); + +// Define Weak Machine type here to avoid needing another cpp file +PyTypeObject WeakMachineType = { + PyVarObject_HEAD_INIT(0,0) + 0 +}; + +bool init_WeakMachine(PyObject* module){ + // The weak machine is quite simple since it is pure virtual + WeakMachineType.tp_name = weakMachine_doc.name(); + WeakMachineType.tp_basicsize = sizeof(WeakMachineObject); + WeakMachineType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; + WeakMachineType.tp_doc = weakMachine_doc.doc(); + + // register creator function + // register machine + if (!registerMachineType(boost::typeindex::type_id().hash_code(), &weakMachineCreate)) + return false; + + // check that everyting is fine + if (PyType_Ready(&WeakMachineType) < 0) + return false; + + // add the type to the module + Py_INCREF(&WeakMachineType); + return PyModule_AddObject(module, weakMachine_doc.name(), (PyObject*)&WeakMachineType) >= 0; +} + diff --git a/pool/shard007/C++/0095689_main.cpp b/pool/shard007/C++/0095689_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4de1574c240f599e6d887da3e9c692b4627322f5 --- /dev/null +++ b/pool/shard007/C++/0095689_main.cpp @@ -0,0 +1,64 @@ +#include +#include +#include + +uint32_t colors[] = { + 0xff0000, + 0xeeb422, + 0xeeee00, + 0x76ee00, + 0x40e0d0, + 0x1e90ff, + 0x4b0082, +}; + +void print(Float f) { + printf("%d.%04x\n", (uint32_t)f.value >> 16, (uint32_t)f.value & 0xffff); +} + +void plot(Float(*f)(Float)) { + static int col = 0; + + int N = _screen.height; + + Float n = Float(N << 16); + + for (int i = 0; i < N; i ++) { + Float x = Float(i << 16) / n; + Float y = f(x) * n; + int iy = (int16_t)((uint32_t)y.value >> 16); + + if (iy >= -N && iy <= N) { + iy = (iy + N) / 2; + if (iy == N) iy --; + _draw_p(i + (_screen.width - _screen.height) / 2, N - iy, colors[col]); + } + } + + _draw_sync(); + col = (col + 1) % 7; +} + +int main() { + _ioe_init(); + // plot functions: x in [0, 1], y in [-1, 1] + + // y = 2(x-1/2) + plot( [](Float x) { return Float(2.0) * (x - Float(0.5)) ; } ); + // y = 0.1 / x + plot( [](Float x) { return Float(0.1) / x; } ); + // y = 2 * x^2 - 1 + plot( [](Float x) { return Float(2.0) * x * x - Float(1.0); } ); + // y = sqrt(x) + plot( [](Float x) { return (Float(2.0) * x.sqrt()) - 1.0; } ); + // y = sin(x * 2pi) + plot( [](Float x) { Float x1 = x * Float(3.1415 * 2); return x1.sin(); } ); + // y = cos(x * 2pi) + plot( [](Float x) { Float x1 = x * Float(3.1415 * 2); return x1.cos(); } ); + // y = asin(x) / (pi/2) + plot( [](Float x) { Float x1 = x; return x1.asin() / Float(3.1415 / 2); } ); + + while (1); + + return 0; +} diff --git a/pool/shard007/C++/0095692_touch_log_source.cc b/pool/shard007/C++/0095692_touch_log_source.cc new file mode 100644 index 0000000000000000000000000000000000000000..59e000db60bde14eda270cadb1ac2e20f948c3fa --- /dev/null +++ b/pool/shard007/C++/0095692_touch_log_source.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/system_logs/touch_log_source.h" + +#include "ash/touch/touch_hud_debug.h" +#include "base/bind.h" +#include "base/command_line.h" +#include "base/json/json_string_value_serializer.h" +#include "base/process/launch.h" +#include "chrome/browser/feedback/feedback_util.h" +#include "content/public/browser/browser_thread.h" + +using content::BrowserThread; + +namespace { + +const char kHUDLogDataKey[] = "hud_log"; + +void GetTouchLogs(chromeos::SystemLogsResponse* response) { + scoped_ptr dictionary = + ash::internal::TouchHudDebug::GetAllAsDictionary(); + if (!dictionary->empty()) { + std::string touch_log; + JSONStringValueSerializer json(&touch_log); + json.set_pretty_print(true); + if (json.Serialize(*dictionary) && !touch_log.empty()) + (*response)[kHUDLogDataKey] = touch_log; + } + + std::vector > commands; + CommandLine command = + CommandLine(base::FilePath("/opt/google/touchpad/tpcontrol")); + command.AppendArg("status"); + commands.push_back(std::make_pair("hack-33025-touchpad", command)); + + command = + CommandLine(base::FilePath("/opt/google/touchpad/generate_userfeedback")); + commands.push_back(std::make_pair("hack-33025-touchpad_activity", command)); + + command = CommandLine( + base::FilePath("/opt/google/touchscreen/touchscreen_feedback")); + commands.push_back( + std::make_pair("hack-33025-touchscreen_activity", command)); + + for (size_t i = 0; i < commands.size(); ++i) { + std::string output; + base::GetAppOutput(commands[i].second, &output); + (*response)[commands[i].first] = output; + } +} + +} // namespace + +namespace chromeos { + +TouchLogSource::TouchLogSource() { +} + +TouchLogSource::~TouchLogSource() { +} + +void TouchLogSource::Fetch(const SysLogsSourceCallback& callback) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK(!callback.is_null()); + + SystemLogsResponse* response = new SystemLogsResponse; + BrowserThread::PostBlockingPoolTaskAndReply( + FROM_HERE, + base::Bind(&GetTouchLogs, response), + base::Bind(callback, base::Owned(response))); +} + +} // namespace chromeos diff --git a/pool/shard007/C++/0095700_033_Search_in_Rotated_Sorted_Array.cpp b/pool/shard007/C++/0095700_033_Search_in_Rotated_Sorted_Array.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbfd7ab98d7d9f64a537023bf42487def8bc667c --- /dev/null +++ b/pool/shard007/C++/0095700_033_Search_in_Rotated_Sorted_Array.cpp @@ -0,0 +1,52 @@ +class Solution { +private: + int search_sorted(vector& nums, int target, int left, int right){ + int m; + while(left < right){ + m = left + (right - left) / 2; + + if (nums[m] < target){ + left = m + 1; + } + else{ + right = m; + } + } + + return (nums[right] == target) ? right : -1; + } + + +public: + int search(vector& nums, int target) { + if (nums.size() == 0){ + return -1; + } + + if (nums[0] < nums[nums.size() - 1]){ + return search_sorted(nums, target, 0, nums.size() - 1); + } + else{ + + int l = 0, r = nums.size() - 1, m; + while(l < r){ + m = l + (r - l) / 2; + if (nums[0] <= nums[m]){ + l = m + 1; + } + else{ + r = m; + } + } + + if (nums[0] <= target){ + return search_sorted(nums, target, 0, max(0, r - 1)); + } + else{ + return search_sorted(nums, target, r, nums.size() - 1); + } + + } + + } +}; \ No newline at end of file diff --git a/pool/shard007/C++/0095702_DevicesWithParameters.cpp b/pool/shard007/C++/0095702_DevicesWithParameters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39511fe74f86a5ca90b3fe719ece421a45db1875 --- /dev/null +++ b/pool/shard007/C++/0095702_DevicesWithParameters.cpp @@ -0,0 +1,145 @@ +/** @file + @brief Implementation + + @date 2014 + + @author + Sensics, Inc. + +*/ + +// Copyright 2014 Sensics, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Internal Includes +#include "DevicesWithParameters.h" +#include "GetSerialPortState.h" +#include +#ifdef OSVR_HAVE_USBSERIALENUM +#include +#endif +#include +#include "com_osvr_Multiserver_YEI_3Space_Sensor_json.h" + +// Library/third-party includes +#include +#include + +#include + +// Standard includes +#include +#include +#include +#include +#include + +namespace { +/// @brief Manage an array of dynamically allocated c-strings, terminated with a +/// null entry. +class CStringArray : boost::noncopyable { + public: + typedef std::unique_ptr UniqueCharArray; + void push_back(std::string const &str) { + // Remove null terminator from array + if (m_arrayHasNullTerminator()) { + m_data.pop_back(); + } + { + const size_t stringLength = str.size() + 1; + UniqueCharArray copy(new char[stringLength]); + memcpy(copy.get(), str.c_str(), stringLength); + m_dataOwnership.push_back(std::move(copy)); + } + m_data.push_back(m_dataOwnership.back().get()); + } + const char **get_array() { + // Ensure null terminator on array + if (!m_arrayHasNullTerminator()) { + m_data.push_back(nullptr); + } + return m_data.data(); + } + + private: + bool m_arrayHasNullTerminator() const { + return !m_data.empty() && nullptr == m_data.back(); + } + std::vector m_data; + std::vector m_dataOwnership; +}; +} // namespace + +static void createYEIImpl(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, + Json::Value const &root, std::string port) { + if (port.empty()) { + throw std::runtime_error( + "Could not create a YEI device: no port specified!."); + } + port = normalizeAndVerifySerialPort(port); + + bool calibrate_gyros_on_setup = + root.get("calibrateGyrosOnSetup", false).asBool(); + bool tare_on_setup = root.get("tareOnSetup", false).asBool(); + double frames_per_second = root.get("framesPerSecond", 250).asFloat(); + + Json::Value commands = root.get("resetCommands", Json::arrayValue); + CStringArray reset_commands; + + if (commands.empty()) { + // Enable Q-COMP filtering by default + reset_commands.push_back("123,2"); + } else { + for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) { + reset_commands.push_back(commands[i].asString()); + } + } + + osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); + + reg.registerDevice(new vrpn_YEI_3Space_Sensor( + reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(), + reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup, + tare_on_setup, frames_per_second, 0, 0, 1, 0, + reset_commands.get_array())); + reg.setDeviceDescriptor( + osvr::util::makeString(com_osvr_Multiserver_YEI_3Space_Sensor_json)); +} + +void createYEI(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, + const char *params) { + Json::Reader reader; + Json::Value root; + if (!reader.parse(params, root)) { + throw std::runtime_error("Could not parse configuration: " + + reader.getFormattedErrorMessages()); + } + auto port = root.get("port", "").asString(); +#ifdef OSVR_HAVE_USBSERIALENUM + // Have usb serial enum: specifying a port means you just want that one, + // not specifying means you want it to auto-configure all. + if (!port.empty()) { + createYEIImpl(data, ctx, root, port); + } else { + static const uint16_t vID = 0x9AC; + static const uint16_t pID = 0x3F2; + for (auto dev : osvr::usbserial::Enumerator(vID, pID)) { + createYEIImpl(data, ctx, root, dev->getPort()); + } + } +#else // !OSVR_HAVE_USBSERIALENUM + // No usb serial enum: must unconditionally specify a port. + createYEIImpl(data, ctx, root, port); +#endif // OSVR_HAVE_USBSERIALENUM +} diff --git a/pool/shard007/C++/0095705_topology_1e_builder.cc b/pool/shard007/C++/0095705_topology_1e_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..e7b498ebd7d56c3eb456ce422a4378fe933ec479 --- /dev/null +++ b/pool/shard007/C++/0095705_topology_1e_builder.cc @@ -0,0 +1,58 @@ +/** \file falaise/snemo/datamodels/topology_1e_builder.cc + */ + +// Ourselves: +#include +#include +#include +#include +#include +#include + +namespace snemo { + + namespace reconstruction { + + // Registration instantiation macro : + FL_SNEMO_RECONSTRUCTION_TOPOLOGY_BUILDER_REGISTRATION_IMPLEMENT(topology_1e_builder, + "snemo::reconstruction::topology_1e_builder") + + snemo::datamodel::base_topology_pattern::handle_type topology_1e_builder::create_pattern() + { + snemo::datamodel::base_topology_pattern::handle_type h(new snemo::datamodel::topology_1e_pattern); + return h; + } + + void topology_1e_builder::make_measurements(snemo::datamodel::base_topology_pattern & pattern_) + { + const std::string e1_label = "e1"; + DT_THROW_IF(! pattern_.has_particle_track(e1_label), std::logic_error, + "No particle with label '" << e1_label << "' has been stored !"); + auto e1 = pattern_.get_particle_track(e1_label); + + auto meas = pattern_.get_measurement_dictionary(); + auto& drivers = base_topology_builder::get_measurement_drivers(); + + if (drivers.AMD) { + double electronAngle = drivers.AMD->process(e1); + meas["angle_" + e1_label].reset(new snemo::datamodel::angle_measurement(electronAngle)); + } + + { + snemo::datamodel::energy_measurement * ptr_energy = new snemo::datamodel::energy_measurement; + meas["energy_" + e1_label].reset(ptr_energy); + if (drivers.EMD) drivers.EMD->process(e1, *ptr_energy); + } + } + + } // end of namespace reconstruction + +} // end of namespace snemo + +/* +** Local Variables: -- +** mode: c++ -- +** c-file-style: "gnu" -- +** tab-width: 2 -- +** End: -- +*/ diff --git a/pool/shard007/C++/0095708_HeightField.cpp b/pool/shard007/C++/0095708_HeightField.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd21fb53f771b3aac409d1564d81c7d82dbca68c --- /dev/null +++ b/pool/shard007/C++/0095708_HeightField.cpp @@ -0,0 +1,73 @@ +#include "HaxeAPI.h" + +// DECL: static HeightField* create(unsigned int rows, unsigned int columns); +value hx_HeightField_static_create(value rows, value columns) +{ + unsigned int _rows = ValueToUint(rows); + unsigned int _columns = ValueToUint(columns); + return ReferenceToValue(HeightField::create(_rows, _columns)); +} +DEFINE_PRIM(hx_HeightField_static_create, 2); + +// DECL: static HeightField* createFromImage(const char* path, float heightMin = 0, float heightMax = 1); +value hx_HeightField_static_createFromImage(value path, value heightMin, value heightMax) +{ + const char *_path = ValueToString(path); + float _heightMin = ValueToFloat(heightMin); + float _heightMax = ValueToFloat(heightMax); + return ReferenceToValue(HeightField::createFromImage(_path, _heightMin, _heightMax)); +} +DEFINE_PRIM(hx_HeightField_static_createFromImage, 3); + +// DECL: static HeightField* createFromRAW(const char* path, unsigned int width, unsigned int height, float heightMin = 0, float heightMax = 1); +value hx_HeightField_static_createFromRAW(value path, value width, value height, value heightMin, value heightMax) +{ + const char *_path = ValueToString(path); + unsigned int _width = ValueToUint(width); + unsigned int _height = ValueToUint(height); + float _heightMin = ValueToFloat(heightMin); + float _heightMax = ValueToFloat(heightMax); + return ReferenceToValue(HeightField::createFromRAW(_path, _width, _height, _heightMin, _heightMax)); +} +DEFINE_PRIM(hx_HeightField_static_createFromRAW, 5); + +// DECL: float* getArray() const; +value hx_HeightField_getArray(value thisObj) +{ + HeightField *_thisObj; + ValueToObject(thisObj, _thisObj); + return ArrayToValue(_thisObj->getArray()); +} +DEFINE_PRIM(hx_HeightField_getArray, 1); + +// DECL: unsigned int getColumnCount() const; +value hx_HeightField_getColumnCount(value thisObj) +{ + HeightField *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_int(_thisObj->getColumnCount()); +} +DEFINE_PRIM(hx_HeightField_getColumnCount, 1); + +// DECL: float getHeight(float column, float row) const; +value hx_HeightField_getHeight(value thisObj, value column, value row) +{ + HeightField *_thisObj; + float _column = ValueToFloat(column); + float _row = ValueToFloat(row); + ValueToObject(thisObj, _thisObj); + return alloc_float(_thisObj->getHeight(_column, _row)); +} +DEFINE_PRIM(hx_HeightField_getHeight, 3); + +// DECL: unsigned int getRowCount() const; +value hx_HeightField_getRowCount(value thisObj) +{ + HeightField *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_int(_thisObj->getRowCount()); +} +DEFINE_PRIM(hx_HeightField_getRowCount, 1); + +// END +// diff --git a/pool/shard007/C++/0095709_ros_main.cpp b/pool/shard007/C++/0095709_ros_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d7879ad3a34e1812aa2646e1e351ea9b38e1d1a --- /dev/null +++ b/pool/shard007/C++/0095709_ros_main.cpp @@ -0,0 +1,159 @@ +/* includes of RTOS */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "semphr.h" +extern "C" +{ + +#include "ros.h" +#include "rcl.h" +#include +} + +#include "Node.h" +#include "Subscriber.h" +#include "Publisher.h" + +#include +#include + +#include "wiring.h" + +extern "C" +void InitNodesTask(void* params) +{ + unsigned int num_nodes = sizeof(nodes)/sizeof(node_decriptor); + for (unsigned int i=0; i< num_nodes; i++) + { +#ifdef DEADLINE_SCHEDULING + xDeadlineTaskCreate(nodes[i].function, (const signed char*)nodes[i].name, configMINIMAL_STACK_SIZE*4, NULL, nodes[i].deadline, NULL); +#else + xTaskCreate(nodes[i].function, (const signed char*)nodes[i].name, configMINIMAL_STACK_SIZE*4, NULL, tskIDLE_PRIORITY + 4UL , NULL); +#endif + } + + vTaskDelete(NULL); +} + +extern "C" void* os_malloc(unsigned int); +void* operator new(unsigned int sz) { + return os_malloc(sz); +} +void *operator new[](unsigned int sz) +{ + // TODO: is this correct? + return os_malloc(sz); +} +void operator delete(void* ptr) +{ + // Do nothing, since once allocated memory cannot be freed! +} + +void operator delete[](void *ptr) +{ + // Do nothing, since once allocated memory cannot be freed! +} + + +#define TSK_workload_PRIO ( tskIDLE_PRIORITY + 1UL ) +#define TSK_monitor_PRIO ( tskIDLE_PRIORITY + 5UL ) +#define TSK_monitor_PERIOD ( ( portTickType ) 5000 / portTICK_RATE_MS ) +#define PRINT_LOAD true +#define TSK_Monitor_STACK_SIZE 200 +long int load_counter; +extern "C" void workload( void *pvParameters ) +{ + ( void ) pvParameters; + load_counter = 0; + for( ;; ) + { + taskENTER_CRITICAL(); + load_counter++; + taskEXIT_CRITICAL(); + /*if (load_counter % 100000000 == 0) + { + //os_printf("Counter = %d\r\n", load_counter); + vTaskDelay(1); + }*/ + } +} + +#define MAX_LOAD_COUNTER 25087398.0 +//#define MAX_LOAD_COUNTER 64511682.0 + +#include "math.h" +extern "C" +void Monitor( void *pvParameters ) +{ + long int newCounter = 0; + long int oldCounter = 0; + long int Delta; + portTickType xTimeToWait = TSK_monitor_PERIOD; + portTickType xLastExecutionTime; + int processor_workload; + ( void ) pvParameters; + + xLastExecutionTime = xTaskGetTickCount(); + // create workload task + xTaskCreate( workload, ( signed portCHAR * ) "wload", configMINIMAL_STACK_SIZE, NULL, TSK_workload_PRIO, NULL ); + for( ;; ) + { + // resume for 5 sec + vTaskDelayUntil( &xLastExecutionTime, xTimeToWait ); + taskENTER_CRITICAL(); + newCounter = load_counter; + taskEXIT_CRITICAL(); + Delta = newCounter - oldCounter; + if( Delta < 0 ) + { + Delta = newCounter - oldCounter + + pow(2,32); + } + oldCounter = newCounter; + processor_workload = ( (int) ((1-Delta/(MAX_LOAD_COUNTER))*100.0)); + + if (PRINT_LOAD) + { + os_printf("Counter = %d Delta = %d, workload during last 5 sec = %d percent \r\n", load_counter, Delta, processor_workload); + } + } +} + +#define HIGHLOAD_COUNTER 200000 +#define HIGHLOAD_PERIOD 50000 + + +extern "C" +void highLoadTask( void *pvParameters ) +{ + for(;;) + for (uint32_t i=0; iisDisabled() ? "Disabled" : "Enabled"); + // peform the rendering operation. + imagery->render(*d_window); + } + + Rect FalagardItemListbox::getItemRenderArea(void) const + { + ItemListbox* lb = static_cast(d_window); + // get WidgetLookFeel for the assigned look. + const WidgetLookFeel& wlf = getLookNFeel(); + bool v_visible = lb->getVertScrollbar()->isVisible(true); + bool h_visible = lb->getHorzScrollbar()->isVisible(true); + + // if either of the scrollbars are visible, we might want to use another text rendering area + if (v_visible || h_visible) + { + String area_name("ItemRenderArea"); + + if (h_visible) + { + area_name.push_back('H'); + } + if (v_visible) + { + area_name.push_back('V'); + } + area_name += "Scroll"; + + if (wlf.isNamedAreaDefined(area_name)) + { + return wlf.getNamedArea(area_name).getArea().getPixelRect(*lb); + } + } + + // default to plain ItemRenderArea + return wlf.getNamedArea("ItemRenderArea").getArea().getPixelRect(*lb); + } + + void FalagardItemListbox::onLookNFeelAssigned() + { + d_widgetLookAssigned = true; + } + + void FalagardItemListbox::onLookNFeelUnassigned() + { + d_widgetLookAssigned = false; + } + + Rect FalagardItemListbox::getUnclippedInnerRect() const + { + if (!d_widgetLookAssigned) + return d_window->getUnclippedOuterRect(); + + const Rect lr(getItemRenderArea()); + return CoordConverter::windowToScreen(*d_window, lr); + } + +} // End of CEGUI namespace section diff --git a/pool/shard007/C++/0095711_passive_aggressive.cpp b/pool/shard007/C++/0095711_passive_aggressive.cpp new file mode 100644 index 0000000000000000000000000000000000000000..837dae586bc286ec000f15a1d6873aa15ced6f81 --- /dev/null +++ b/pool/shard007/C++/0095711_passive_aggressive.cpp @@ -0,0 +1,53 @@ +// Jubatus: Online machine learning framework for distributed environment +// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License version 2.1 as published by the Free Software Foundation. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +#include "passive_aggressive.hpp" + +#include + +using std::string; + +namespace jubatus { +namespace core { +namespace classifier { + +passive_aggressive::passive_aggressive(storage_ptr storage) + : classifier_base(storage) { +} + +void passive_aggressive::train(const common::sfv_t& sfv, const string& label) { + string incorrect_label; + float margin = calc_margin(sfv, label, incorrect_label); + float loss = 1.f + margin; + if (loss < 0.f) { + return; + } + float sfv_norm = squared_norm(sfv); + if (sfv_norm == 0.f) { + storage_->register_label(label); + return; + } + update_weight(sfv, loss / (2 * sfv_norm), label, incorrect_label); + touch(label); +} + +string passive_aggressive::name() const { + return string("passive_aggressive"); +} + +} // namespace classifier +} // namespace core +} // namespace jubatus diff --git a/pool/shard007/C++/0095713_MeritSeqCBCSignals.cc b/pool/shard007/C++/0095713_MeritSeqCBCSignals.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b18dfa9a040b7155e79f1a6a4b3503957b00a27 --- /dev/null +++ b/pool/shard007/C++/0095713_MeritSeqCBCSignals.cc @@ -0,0 +1,150 @@ +// Copyright (c) 2012 David Munger, Pierre L'Ecuyer, Université de Montréal. +// +// This file is part of Lattice Builder. +// +// Lattice Builder 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. +// +// Lattice Builder 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 Lattice Builder. If not, see . + +#include "latbuilder/WeightedFigureOfMerit.h" +#include "latcommon/ProductWeights.h" +#include "latcommon/CoordinateSets.h" +#include "latbuilder/ProjDepMerit/Spectral.h" +#include "latcommon/NormaBestLat.h" +#include "latbuilder/Accumulator.h" +#include "latbuilder/Storage.h" +#include "latbuilder/Functor/binary.h" + +#include "latbuilder/MeritFilterList.h" +#include "latbuilder/MeritSeq/CBC.h" +#include "latbuilder/GenSeq/CoprimeIntegers.h" +#include "latbuilder/GenSeq/Creator.h" +#include "latbuilder/Functor/MinElement.h" + +#include "latbuilder/TextStream.h" + +#include +#include + +using namespace LatBuilder; +using TextStream::operator<<; + +template +std::unique_ptr unique(ARGS&&... args) +{ return std::unique_ptr(new T(std::forward(args)...)); } + +//! [Observer] +class Observer { +public: + typedef LatBuilder::LatDef LatDef; + + Observer() { reset(); } + + // initializes the best observed merit value to infinity + void reset() { m_bestMerit = std::numeric_limits::infinity(); } + + //! [onProgress] + bool onProgress(Real merit) const + { return merit <= m_bestMerit; } + //! [onProgress] + + //! [onAbort] + void onAbort(const LatDef& lat) const + { std::cout << "rejected " << lat << std::endl; } + //! [onAbort] + + //! [onMinUpdated] + void onMinUpdated(const Real& bestMerit) + { m_bestMerit = bestMerit; } + //! [onMinUpdated] + +private: + Real m_bestMerit; +}; +//! [Observer] + +template +void test(const Storage& storage, Dimension dimension) +{ + //! [figure] + auto weights = unique(); + weights->setDefaultWeight(0.7); + + typedef ProjDepMerit::Spectral ProjDep; + WeightedFigureOfMerit figure(2, std::move(weights)); + std::cout << "figure of merit: " << figure << std::endl; + //! [figure] + + typedef GenSeq::CoprimeIntegers Coprime; + auto genSeq = GenSeq::Creator::create(storage.sizeParam()); + auto genSeq0 = GenSeq::Creator::create(SizeParam(2)); + + //! [cbc] + auto cbc = MeritSeq::cbc(storage, figure); + //! [cbc] + + //! [filters] + MeritFilterList filters; + //! [filters] + + //! [connect] + Observer obs; + cbc.evaluator().onProgress().connect(boost::bind(&Observer::onProgress, &obs, _1)); + cbc.evaluator().onAbort().connect(boost::bind(&Observer::onAbort, &obs, _1)); + //! [connect] + + //! [minElement] + Functor::MinElement minElement; + minElement.onMinUpdated().connect(boost::bind(&Observer::onMinUpdated, &obs, _1)); + //! [minElement] + + //! [CBC loop] + while (cbc.baseLat().dimension() < dimension) { + + Dimension baseDim = cbc.baseLat().dimension(); + + std::cout << "CBC search for dimension: " << (baseDim + 1) << std::endl; + std::cout << " base lattice: " << cbc.baseLat() << std::endl; + std::cout << " base merit value: " << cbc.baseMerit() << std::endl; + std::cout << " new projections: " << cbc.projections() << std::endl; + + //! [meritSeq] + auto meritSeq = cbc.meritSeq(baseDim == 0 ? genSeq0 : genSeq); + //! [meritSeq] + + //! [filteredSeq] + auto filteredSeq = filters.apply(meritSeq); + //! [filteredSeq] + + //! [minElement call] + obs.reset(); + auto best = minElement(filteredSeq.begin(), filteredSeq.end()); + //! [minElement call] + //! [select] + cbc.select(best.base()); + //! [select] + + std::cout << "BEST LATTICE: " << cbc.baseLat() << " with merit value " << *best << std::endl; + } + //! [CBC loop] +} + +int main() +{ + Dimension dim = 3; + + //! [storage] + test(Storage(256), dim); + //! [storage] + + return 0; +} diff --git a/pool/shard007/C++/0095714_quick_items_manager.cpp b/pool/shard007/C++/0095714_quick_items_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8052838add98a31238db98f7b8f560982f020d77 --- /dev/null +++ b/pool/shard007/C++/0095714_quick_items_manager.cpp @@ -0,0 +1,29 @@ + +#include "quick_items_manager.h" +#include "connection_item.h" + +namespace wgt +{ +QuickItemsManager& QuickItemsManager::Instance() +{ + static QuickItemsManager mng; + return mng; +} + +void QuickItemsManager::RegisterObject(ConnectionItem* item) +{ + items.emplace(item->GetUID(), item); +} + +void QuickItemsManager::UnregisterObject(ConnectionItem* item) +{ + items.erase(item->GetUID()); +} + +void QuickItemsManager::RepaintItem(size_t uid) +{ + auto iter = items.find(uid); + if (iter != items.end()) + iter->second->update(); +} +} // end namespace wgt diff --git a/pool/shard007/C++/0095715_pub_test.cpp b/pool/shard007/C++/0095715_pub_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a652df788c2a0bb9a58f66910651fa5ce4c8b5a7 --- /dev/null +++ b/pool/shard007/C++/0095715_pub_test.cpp @@ -0,0 +1,51 @@ +/* +* Copyright (C) 2015 Dato, Inc. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 3 of the +* License, or (at your option) any later version. +* +* 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 Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see . +*/ +#include +#include +#include +#include +#include +#include +using namespace libfault; + +int main(int argc, char** argv) { + if (argc != 2) { + std::cout << "Usage: pub_test [listen_addr] \n"; + return 0; + } + std::string listen_addr = argv[1]; + void* zmq_ctx = zmq_ctx_new(); + zmq_ctx_set(zmq_ctx, ZMQ_IO_THREADS, 4); + publish_socket pubsock(zmq_ctx, + NULL, + listen_addr); + std::cout << "Publish server running. Empty message to quit\n"; + while(1) { + std::string msg; + std::cout << "Message to Publish: "; + std::getline(std::cin, msg); + if (msg.size() == 0) break; + else { + zmq_msg_vector v; + zmq_msg_t* zmsg = v.insert_back(); + zmq_msg_init_size(zmsg, msg.size()); + memcpy(zmq_msg_data(zmsg), msg.c_str(), msg.length()); + pubsock.send(v); + } + } + pubsock.close(); +} diff --git a/pool/shard007/C++/0095720_PartiallyInlineLibCalls.cpp b/pool/shard007/C++/0095720_PartiallyInlineLibCalls.cpp new file mode 100644 index 0000000000000000000000000000000000000000..039123218544f72be06cb38651936c2e6734f014 --- /dev/null +++ b/pool/shard007/C++/0095720_PartiallyInlineLibCalls.cpp @@ -0,0 +1,185 @@ +//===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This pass tries to partially inline the fast path of well-known library +// functions, such as using square-root instructions for cases where sqrt() +// does not need to set errno. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h" +#include "llvm/Analysis/TargetLibraryInfo.h" +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/Support/DebugCounter.h" +#include "llvm/Transforms/Scalar.h" +#include "llvm/Transforms/Utils/BasicBlockUtils.h" + +using namespace llvm; + +#define DEBUG_TYPE "partially-inline-libcalls" + +DEBUG_COUNTER(PILCounter, "partially-inline-libcalls-transform", + "Controls transformations in partially-inline-libcalls"); + +static bool optimizeSQRT(CallInst *Call, Function *CalledFunc, + BasicBlock &CurrBB, Function::iterator &BB, + const TargetTransformInfo *TTI) { + // There is no need to change the IR, since backend will emit sqrt + // instruction if the call has already been marked read-only. + if (Call->onlyReadsMemory()) + return false; + + if (!DebugCounter::shouldExecute(PILCounter)) + return false; + + // Do the following transformation: + // + // (before) + // dst = sqrt(src) + // + // (after) + // v0 = sqrt_noreadmem(src) # native sqrt instruction. + // [if (v0 is a NaN) || if (src < 0)] + // v1 = sqrt(src) # library call. + // dst = phi(v0, v1) + // + + // Move all instructions following Call to newly created block JoinBB. + // Create phi and replace all uses. + BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode()); + IRBuilder<> Builder(JoinBB, JoinBB->begin()); + Type *Ty = Call->getType(); + PHINode *Phi = Builder.CreatePHI(Ty, 2); + Call->replaceAllUsesWith(Phi); + + // Create basic block LibCallBB and insert a call to library function sqrt. + BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt", + CurrBB.getParent(), JoinBB); + Builder.SetInsertPoint(LibCallBB); + Instruction *LibCall = Call->clone(); + Builder.Insert(LibCall); + Builder.CreateBr(JoinBB); + + // Add attribute "readnone" so that backend can use a native sqrt instruction + // for this call. Insert a FP compare instruction and a conditional branch + // at the end of CurrBB. + Call->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone); + CurrBB.getTerminator()->eraseFromParent(); + Builder.SetInsertPoint(&CurrBB); + Value *FCmp = TTI->isFCmpOrdCheaperThanFCmpZero(Ty) + ? Builder.CreateFCmpORD(Call, Call) + : Builder.CreateFCmpOGE(Call->getOperand(0), + ConstantFP::get(Ty, 0.0)); + Builder.CreateCondBr(FCmp, JoinBB, LibCallBB); + + // Add phi operands. + Phi->addIncoming(Call, &CurrBB); + Phi->addIncoming(LibCall, LibCallBB); + + BB = JoinBB->getIterator(); + return true; +} + +static bool runPartiallyInlineLibCalls(Function &F, TargetLibraryInfo *TLI, + const TargetTransformInfo *TTI) { + bool Changed = false; + + Function::iterator CurrBB; + for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) { + CurrBB = BB++; + + for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end(); + II != IE; ++II) { + CallInst *Call = dyn_cast(&*II); + Function *CalledFunc; + + if (!Call || !(CalledFunc = Call->getCalledFunction())) + continue; + + if (Call->isNoBuiltin()) + continue; + + // Skip if function either has local linkage or is not a known library + // function. + LibFunc LF; + if (CalledFunc->hasLocalLinkage() || + !TLI->getLibFunc(*CalledFunc, LF) || !TLI->has(LF)) + continue; + + switch (LF) { + case LibFunc_sqrtf: + case LibFunc_sqrt: + if (TTI->haveFastSqrt(Call->getType()) && + optimizeSQRT(Call, CalledFunc, *CurrBB, BB, TTI)) + break; + continue; + default: + continue; + } + + Changed = true; + break; + } + } + + return Changed; +} + +PreservedAnalyses +PartiallyInlineLibCallsPass::run(Function &F, FunctionAnalysisManager &AM) { + auto &TLI = AM.getResult(F); + auto &TTI = AM.getResult(F); + if (!runPartiallyInlineLibCalls(F, &TLI, &TTI)) + return PreservedAnalyses::all(); + return PreservedAnalyses::none(); +} + +namespace { +class PartiallyInlineLibCallsLegacyPass : public FunctionPass { +public: + static char ID; + + PartiallyInlineLibCallsLegacyPass() : FunctionPass(ID) { + initializePartiallyInlineLibCallsLegacyPassPass( + *PassRegistry::getPassRegistry()); + } + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired(); + AU.addRequired(); + FunctionPass::getAnalysisUsage(AU); + } + + bool runOnFunction(Function &F) override { + if (skipFunction(F)) + return false; + + TargetLibraryInfo *TLI = + &getAnalysis().getTLI(); + const TargetTransformInfo *TTI = + &getAnalysis().getTTI(F); + return runPartiallyInlineLibCalls(F, TLI, TTI); + } +}; +} + +char PartiallyInlineLibCallsLegacyPass::ID = 0; +INITIALIZE_PASS_BEGIN(PartiallyInlineLibCallsLegacyPass, + "partially-inline-libcalls", + "Partially inline calls to library functions", false, + false) +INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) +INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) +INITIALIZE_PASS_END(PartiallyInlineLibCallsLegacyPass, + "partially-inline-libcalls", + "Partially inline calls to library functions", false, false) + +FunctionPass *llvm::createPartiallyInlineLibCallsPass() { + return new PartiallyInlineLibCallsLegacyPass(); +} diff --git a/pool/shard007/C++/0095722_aw_cookie_store_wrapper_unittest.cc b/pool/shard007/C++/0095722_aw_cookie_store_wrapper_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..a4bbd287b94889678fe2510f43091c13f295670e --- /dev/null +++ b/pool/shard007/C++/0095722_aw_cookie_store_wrapper_unittest.cc @@ -0,0 +1,49 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "android_webview/browser/net/aw_cookie_store_wrapper.h" + +#include + +#include "net/cookies/cookie_store.h" +#include "net/cookies/cookie_store_test_callbacks.h" +#include "net/cookies/cookie_store_unittest.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace android_webview { + +struct AwCookieStoreWrapperTestTraits { + static std::unique_ptr Create() { + std::unique_ptr cookie_store(new AwCookieStoreWrapper()); + + // Android Webview can run multiple tests without restarting the binary, + // so have to delete any cookies the global store may have from an earlier + // test. + net::ResultSavingCookieCallback callback; + cookie_store->DeleteAllAsync( + base::Bind(&net::ResultSavingCookieCallback::Run, + base::Unretained(&callback))); + callback.WaitUntilDone(); + + return cookie_store; + } + + static const bool supports_http_only = true; + static const bool supports_non_dotted_domains = true; + static const bool preserves_trailing_dots = true; + static const bool filters_schemes = true; + static const bool has_path_prefix_bug = false; + static const int creation_time_granularity_in_ms = 0; + static const bool enforce_strict_secure = false; +}; + +} // namespace android_webview + +// Run the standard cookie tests with AwCookieStoreWrapper. Macro must be in +// net namespace. +namespace net { +INSTANTIATE_TYPED_TEST_CASE_P(AwCookieStoreWrapper, + CookieStoreTest, + android_webview::AwCookieStoreWrapperTestTraits); +} // namespace net diff --git a/pool/shard007/C++/0095727_fake_host_backend_delegate.cc b/pool/shard007/C++/0095727_fake_host_backend_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3376a002c033f8b1d88ad8e863c1a8e4b9162d7 --- /dev/null +++ b/pool/shard007/C++/0095727_fake_host_backend_delegate.cc @@ -0,0 +1,88 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/services/multidevice_setup/fake_host_backend_delegate.h" + +#include "base/callback.h" + +namespace chromeos { + +namespace multidevice_setup { + +FakeHostBackendDelegate::FakeHostBackendDelegate() : HostBackendDelegate() {} + +FakeHostBackendDelegate::~FakeHostBackendDelegate() = default; + +void FakeHostBackendDelegate::NotifyHostChangedOnBackend( + const base::Optional& + host_device_on_backend) { + host_device_on_backend_ = host_device_on_backend; + + if (pending_host_request_ && *pending_host_request_ == host_device_on_backend) + pending_host_request_.reset(); + + HostBackendDelegate::NotifyHostChangedOnBackend(); +} + +void FakeHostBackendDelegate::NotifyBackendRequestFailed() { + // A request must be active in order for a back-end request to fail. + DCHECK(pending_host_request_); + + HostBackendDelegate::NotifyBackendRequestFailed(); +} + +void FakeHostBackendDelegate::AttemptToSetMultiDeviceHostOnBackend( + const base::Optional& host_device) { + ++num_attempt_to_set_calls_; + + if (host_device_on_backend_ == host_device) { + if (pending_host_request_) { + pending_host_request_.reset(); + NotifyPendingHostRequestChange(); + } + return; + } + + // If |pending_host_request_| was set and already referred to |host_device|, + // there is no need to notify observers. + if (pending_host_request_ && *pending_host_request_ == host_device) + return; + + pending_host_request_ = host_device; + NotifyPendingHostRequestChange(); +} + +bool FakeHostBackendDelegate::HasPendingHostRequest() { + return pending_host_request_ != base::nullopt; +} + +base::Optional +FakeHostBackendDelegate::GetPendingHostRequest() const { + return *pending_host_request_; +} + +base::Optional +FakeHostBackendDelegate::GetMultiDeviceHostFromBackend() const { + return host_device_on_backend_; +} + +FakeHostBackendDelegateObserver::FakeHostBackendDelegateObserver() = default; + +FakeHostBackendDelegateObserver::~FakeHostBackendDelegateObserver() = default; + +void FakeHostBackendDelegateObserver::OnHostChangedOnBackend() { + ++num_changes_on_backend_; +} + +void FakeHostBackendDelegateObserver::OnBackendRequestFailed() { + ++num_failed_backend_requests_; +} + +void FakeHostBackendDelegateObserver::OnPendingHostRequestChange() { + ++num_pending_host_request_changes_; +} + +} // namespace multidevice_setup + +} // namespace chromeos diff --git a/pool/shard007/C++/0095732_CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72a.cpp b/pool/shard007/C++/0095732_CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07085b90e0f83d56e84d5c94b350b17c6c7598f9 --- /dev/null +++ b/pool/shard007/C++/0095732_CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72a.cpp @@ -0,0 +1,125 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72a.cpp +Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml +Template File: sources-sinks-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 789 Uncontrolled Memory Allocation + * BadSource: rand Set data to result of rand(), which may be zero + * GoodSource: Small number greater than zero + * Sinks: + * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated + * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +#ifndef _WIN32 +#include +#endif + +using namespace std; + +namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector dataVector); + +void bad() +{ + size_t data; + vector dataVector; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Set data to a random value */ + data = rand(); + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + badSink(dataVector); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector dataVector); + +static void goodG2B() +{ + size_t data; + vector dataVector; + /* Initialize data */ + data = 0; + /* FIX: Use a relatively small number for memory allocation */ + data = 20; + /* Put data in a vector */ + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodG2BSink(dataVector); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(vector dataVector); + +static void goodB2G() +{ + size_t data; + vector dataVector; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Set data to a random value */ + data = rand(); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + dataVector.insert(dataVector.end(), 1, data); + goodB2GSink(dataVector); +} + +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 CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_72; /* 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/shard007/C++/0095734_Hammer.cpp b/pool/shard007/C++/0095734_Hammer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fc82f921aafd2ca65cfdd3b42677b06494f0bdb --- /dev/null +++ b/pool/shard007/C++/0095734_Hammer.cpp @@ -0,0 +1,78 @@ +#include "../common/FASTAReader.h" +#include "../common/FASTASequence.h" + +#include +using namespace std; + + +int HammingDistance(Nucleotide *a, Nucleotide *b, DNALength length) { + Nucleotide *aend = a + length; + int dist = 0; + int i; + if (length < 12) return 0; + for (i = 0 ; i < 6; i++) { + if (toupper(a[i]) != toupper(b[i])) { + dist++; + a[i] = tolower(a[i]); + } + if (toupper(a[length-i-1]) != toupper(b[length-i-1])) { + dist++; + a[length-i-1] = tolower(a[length-i-1]); + } + } + return dist; +} + +int main(int argc, char* argv[]) { + string refFileName, queryFileName; + int maxHammingDistance; + if (argc < 4) { + cout << "usage: hammer ref query maxHam " << endl; + exit(1); + } + refFileName = argv[1]; + queryFileName = argv[2]; + maxHammingDistance = atoi(argv[3]); + + FASTAReader reader; + reader.Initialize(refFileName); + FASTASequence ref, refRC; + reader.GetNext(ref); + ref.MakeRC(refRC); + + FASTAReader queryReader; + queryReader.Initialize(queryFileName); + FASTASequence query; + queryReader.GetNext(query); + DNALength p; + for(p=0; p < ref.length-query.length-1; p++ ){ + DNASequence subseq; + subseq.seq = &ref.seq[p]; + subseq.length = query.length; + // cout << "t "; subseq.PrintSeq(cout); + // cout << "q "; ((DNASequence*)&query)->PrintSeq(cout); + if (HammingDistance(&subseq.seq[0], &query.seq[0], query.length) < maxHammingDistance) { + cout << ">" << p << endl; + subseq.PrintSeq(cout); + } + int i; + for (i =0; i < query.length; i++) { + subseq.seq[i] = toupper(subseq.seq[i]); + } + } + + for(p=0; p < ref.length-query.length-1; p++ ){ + DNASequence subseq; + subseq.seq = &refRC.seq[p]; + subseq.length = query.length; + if (HammingDistance(&subseq.seq[0], &query.seq[0], query.length) < maxHammingDistance) { + cout << ">" << p << "rc" << endl; + subseq.PrintSeq(cout); + } + int i; + for (i =0; i < query.length; i++) { + subseq.seq[i] = toupper(subseq.seq[i]); + } + } + +} diff --git a/pool/shard007/C++/0095735_Doors.cc b/pool/shard007/C++/0095735_Doors.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee9046b99139d9652d55f9dd0f4dc76da5245db9 --- /dev/null +++ b/pool/shard007/C++/0095735_Doors.cc @@ -0,0 +1,193 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "CommonScreens.h" +#include "Doors.h" +#include "Image.h" +#include "Mark.h" +#include "Random.h" +#include "Screen.h" +#include "Shuffler.h" + +namespace stimulus { +namespace { + +const float kDefaultWinLossWidthCm = 1; // cm +const float kDoorsWidthCm = 10; // cm +const float kDoorsHeightCm = 7.5; // cm +const int kTotalTrials = 60; +const int kMaxRunLength = 3; +const char *kWinLossWidthSetting = "win_loss_width_cm"; + +// This screen doesn't have any interaction, it just serves as a point to +// compute the next result and check if the task is over. +class LoopScreen : public Screen { + public: + LoopScreen(Shuffler *shuffler) : shuffler_(shuffler) { + } + + void IsVisible() override { + if (shuffler_->IsDone()) { + shuffler_->ShuffleElements(); + SwitchToScreen(1); // Back to selection screen + } else { + SwitchToScreen(0); + } + } + + private: + Shuffler *shuffler_; +}; + +class ChooseDoorScreen : public Screen { + public: + ChooseDoorScreen() { + door_ = LoadImage(GetResourceDir() + "door.bmp"); + int door_source_width_px; + int door_source_height_px; + SDL_QueryTexture(door_, nullptr, nullptr, &door_source_width_px, + &door_source_height_px); + + int total_dest_width_px = HorzSizeToPixels(kDoorsWidthCm); + int door_dest_height_px = VertSizeToPixels(kDoorsHeightCm); + float door_scale = static_cast(door_dest_height_px) + / door_source_height_px; + int door_dest_width_px = door_scale * door_source_width_px; + + door1_rect_.x = (GetDisplayWidthPx() - total_dest_width_px) / 2; + door1_rect_.y = (GetDisplayHeightPx() - total_dest_width_px) / 2; + door1_rect_.w = door_dest_width_px; + door1_rect_.h = door_dest_height_px; + + door2_rect_.x = (GetDisplayWidthPx() + total_dest_width_px) / 2 + - door_dest_width_px; + door2_rect_.y = door1_rect_.y; + door2_rect_.w = door_dest_width_px; + door2_rect_.h = door_dest_height_px; + } + + void Render() override { + Blit(door_, door1_rect_); + Blit(door_, door2_rect_); + } + + void IsVisible() override { + SendMark(10, "Stimulus"); + } + + void MouseClicked(int button, int x, int y) override { + if (button == SDL_BUTTON_LEFT) { + SendMark(1, "Response"); + SwitchToScreen(0); + } else if (button == SDL_BUTTON_RIGHT) { + SendMark(3, "Response"); + SwitchToScreen(0); + } + } + + private: + SDL_Texture *door_; + SDL_Rect door1_rect_; + SDL_Rect door2_rect_; +}; + +class DoorsResultScreen : public Screen { + public: + DoorsResultScreen(Shuffler *shuffler, int win_loss_width_cm) + : shuffler_(shuffler) { + win_ = LoadImage(GetResourceDir() + "win.bmp"); + lose_ = LoadImage(GetResourceDir() + "lose.bmp"); + win_dest_rect_ = ComputeRectForPhysicalWidth(win_, win_loss_width_cm); + lose_dest_rect_ = ComputeRectForPhysicalWidth(lose_, win_loss_width_cm); + } + + void IsActive() override { + is_win_ = shuffler_->GetNextItem(); + } + + void Render() override { + if (is_win_) { + Blit(win_, win_dest_rect_); + } else { + Blit(lose_, lose_dest_rect_); + } + } + + void IsVisible() override { + if (is_win_) { + SendMark(7, "PositiveFeedback"); + } else { + SendMark(9, "NegativeFeedback"); + } + + SwitchToScreen(0, 2000); + } + + private: + bool is_win_; + Shuffler *shuffler_; + SDL_Texture *win_; + SDL_Texture *lose_; + SDL_Rect win_dest_rect_; + SDL_Rect lose_dest_rect_; +}; + +} // namespace + +Screen *InitDoors(Screen *main_screen, const Settings &settings) { + Shuffler *shuffler = new Shuffler(); + std::vector win_array; + for (int i = 0; i < kTotalTrials / 2; i++) { + win_array.push_back(true); + } + + shuffler->AddCategoryElements(win_array, kMaxRunLength); + + std::vector lose_array; + for (int i = 0; i < kTotalTrials / 2; i++) { + lose_array.push_back(false); + } + + shuffler->AddCategoryElements(lose_array, kMaxRunLength); + shuffler->ShuffleElements(); + + Screen *loop = new LoopScreen(shuffler); + Screen *instructions = new InstructionScreen( + "Click to start next round."); + Screen *fixation1 = new FixationScreen(1000, 1000); + Screen *choose_door = new ChooseDoorScreen(); + Screen *fixation2 = new FixationScreen(1000, 1000); + + int win_loss_width_cm = kDefaultWinLossWidthCm; + if (settings.HasKey(kWinLossWidthSetting)) { + win_loss_width_cm = settings.GetIntValue(kWinLossWidthSetting); + } + + Screen *doors_result = new DoorsResultScreen(shuffler, win_loss_width_cm); + Screen *fixation3 = new FixationScreen(1500, 1500); + + loop->AddSuccessor(instructions); + loop->AddSuccessor(main_screen); + instructions->AddSuccessor(fixation1); + fixation1->AddSuccessor(choose_door); + choose_door->AddSuccessor(fixation2); + fixation2->AddSuccessor(doors_result); + doors_result->AddSuccessor(fixation3); + doors_result->AddSuccessor(main_screen); + fixation3->AddSuccessor(loop); + + return loop; +} + +} // namespace stimulus diff --git a/pool/shard007/C++/0095737_scriptobjectrulegroup.cpp b/pool/shard007/C++/0095737_scriptobjectrulegroup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5932eda51043bb4605c64865632586af974e76b0 --- /dev/null +++ b/pool/shard007/C++/0095737_scriptobjectrulegroup.cpp @@ -0,0 +1,142 @@ +/* + DNT: a satirical post-apocalyptical RPG. + Copyright (C) DNTeam + + This file is part of DNT. + + DNT 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. + + DNT 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 DNT. If not, see . +*/ + +#include "scriptobjectrulegroup.h" +using namespace DNT; + +/************************************************************************** + * Constructor * + **************************************************************************/ +ScriptObjectRuleGroup::ScriptObjectRuleGroup(RuleGroupAvailableInfo* groupPtr) + :ScriptObject(TYPE_RULE_GROUP, groupPtr->getId()) +{ + ruleGroup = groupPtr; +} + +/************************************************************************** + * Destructor * + **************************************************************************/ +ScriptObjectRuleGroup::~ScriptObjectRuleGroup() +{ +} + +/************************************************************************** + * setPointer * + **************************************************************************/ +void ScriptObjectRuleGroup::setPointer(void* newPtr) +{ + mutex.lock(); + ruleGroup = static_cast(newPtr); + mutex.unlock(); +} + +/************************************************************************** + * isValid * + **************************************************************************/ +const bool ScriptObjectRuleGroup::isValid() +{ + mutex.lock(); + bool res = ruleGroup != NULL; + mutex.unlock(); + + return res; +} + +/************************************************************************** + * addTotal * + **************************************************************************/ +void ScriptObjectRuleGroup::addTotal(int val) +{ + mutex.lock(); + if(ruleGroup) + { + ruleGroup->add(val); + } + mutex.unlock(); +} + +/************************************************************************** + * setTotal * + **************************************************************************/ +void ScriptObjectRuleGroup::setTotal(int val) +{ + mutex.lock(); + if(ruleGroup) + { + ruleGroup->setTotal(val); + } + mutex.unlock(); +} + +/************************************************************************** + * getTotal * + **************************************************************************/ +int ScriptObjectRuleGroup::getTotal() +{ + int res = 0; + + mutex.lock(); + if(ruleGroup) + { + res = ruleGroup->getTotal(); + } + mutex.unlock(); + + return res; +} + +/************************************************************************** + * registerClass * + **************************************************************************/ +void ScriptObjectRuleGroup::registerClass(asIScriptEngine* asEngine) +{ + int r = asEngine->RegisterObjectType("RuleGroup", 0, asOBJ_REF); + assert(r >= 0); + r = asEngine->RegisterObjectBehaviour("RuleGroup", asBEHAVE_ADDREF, + "void f()", asMETHOD(ScriptObjectRuleGroup, addReference), + asCALL_THISCALL); + assert(r >= 0); + r = asEngine->RegisterObjectBehaviour("RuleGroup", asBEHAVE_RELEASE, + "void f()", asMETHOD(ScriptObjectRuleGroup, release), + asCALL_THISCALL); + assert(r >= 0); +} + +/************************************************************************** + * registerFunctions * + **************************************************************************/ +void ScriptObjectRuleGroup::registerFunctions(asIScriptEngine* asEngine) +{ + int r; + + r = asEngine->RegisterObjectMethod("RuleGroup", + "void addTotal(int val)", + asMETHOD(ScriptObjectRuleGroup, addTotal), asCALL_THISCALL); + assert(r >=0 ); + r = asEngine->RegisterObjectMethod("RuleGroup", + "void setTotal(int val)", + asMETHOD(ScriptObjectRuleGroup, setTotal), asCALL_THISCALL); + assert(r >=0 ); + r = asEngine->RegisterObjectMethod("RuleGroup", + "int getTotal()", + asMETHOD(ScriptObjectRuleGroup, getTotal), asCALL_THISCALL); + assert(r >=0 ); +} + diff --git a/pool/shard007/C++/0095741_SetConductivitiesToTetMeshAlgorithmTests.cc b/pool/shard007/C++/0095741_SetConductivitiesToTetMeshAlgorithmTests.cc new file mode 100644 index 0000000000000000000000000000000000000000..fd02ba2472144586850519b687ca6c8199be6c30 --- /dev/null +++ b/pool/shard007/C++/0095741_SetConductivitiesToTetMeshAlgorithmTests.cc @@ -0,0 +1,171 @@ +/* + For more information, please see: http://software.sci.utah.edu + + The MIT License + + Copyright (c) 2020 Scientific Computing and Imaging Institute, + University of Utah. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ + + +#include + +#include +#include +#include +#include +#include +#include +#include + + +using namespace SCIRun; +using namespace SCIRun::Core::Geometry; +using namespace SCIRun::Core::Algorithms::BrainStimulator; +using namespace SCIRun::TestUtils; +using namespace SCIRun::Core::Algorithms; + +namespace +{ + FieldHandle CreateTetMeshVectorOnElem() + { + return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_elem/vector/tet_vector_on_elem.fld"); + } + FieldHandle CreateTetMeshScalarSevenElem() + { + return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/tet_mesh_7elem.fld"); + } + FieldHandle CreateTetMeshScalarOnElem() + { + return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_elem/scalar/tet_scalar_on_elem.fld"); + } + FieldHandle CreateTetMeshScalarOnNode() + { + return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/scalar/tet_scalar_on_node.fld"); + } +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, TetMeshScalars) +{ + SetConductivitiesToMeshAlgorithm algo; + + double conductivities[] = {9.25, 25.1988, 18.99999, 3.5, 5.1988, 5.22, 22.2013}; + + algo.set(Parameters::Skin, conductivities[0]); + algo.set(Parameters::SoftBone, conductivities[1]); + algo.set(Parameters::HardBone, conductivities[2]); + algo.set(Parameters::CSF, conductivities[3]); + algo.set(Parameters::GM, conductivities[4]); + algo.set(Parameters::WM, conductivities[5]); + algo.set(Parameters::Electrode, conductivities[6]); + + auto input = CreateTetMeshScalarSevenElem(); + auto output = algo.run(input); + + VField* ivfield = input->vfield(); + VField* ovfield = output->vfield(); + int ival = 0; + double oval = 0; +; + for (VMesh::Elem::index_type i=0; i < ivfield->vmesh()->num_elems(); i++) + { + ivfield->get_value(ival, i); + ovfield->get_value(oval, i); + EXPECT_EQ(oval, conductivities[ival-1]); + } +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, TetMeshScalarSevenElem) +{ + SetConductivitiesToMeshAlgorithm algo; + + double conductivities[] = {9.25, 25.1988, 18.99999, 3.5, 5.1988, 5.22, 22.2013}; + + algo.set(Parameters::Skin, conductivities[0]); + algo.set(Parameters::SoftBone, conductivities[1]); + algo.set(Parameters::HardBone, conductivities[2]); + algo.set(Parameters::CSF, conductivities[3]); + algo.set(Parameters::GM, conductivities[4]); + algo.set(Parameters::WM, conductivities[5]); + algo.set(Parameters::Electrode, conductivities[6]); + + FieldHandle input = CreateTetMeshScalarSevenElem(); + FieldHandle output = algo.run(CreateTetMeshScalarSevenElem()); + + VField* ivfield = input->vfield(); + VField* ovfield = output->vfield(); + int ival = 0; + double oval = 0; + for (VMesh::Elem::index_type i=0; i < ivfield->vmesh()->num_elems(); i++) + { + ivfield->get_value(ival, i); + if (ival != 1 && ival != 2 && ival != 3 && ival != 4 && ival !=5 && ival !=6) + FAIL() << "field value outside of range obtained " << std::endl; + ovfield->get_value(oval, i); + EXPECT_EQ(oval, conductivities[ival-1]); + } +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, TetMeshScalarThreeElem) +{ + SetConductivitiesToMeshAlgorithm algo; + double conductivities[] = {9.25, 18.999, 123,456, 25.1988}; + + algo.set(Parameters::Skin, conductivities[0]); + algo.set(Parameters::SoftBone, conductivities[1]); + algo.set(Parameters::HardBone, conductivities[2]); + algo.set(Parameters::CSF, conductivities[4]); + + FieldHandle input = CreateTetMeshScalarOnElem(); + FieldHandle output = algo.run(CreateTetMeshScalarOnElem()); + + VField* ivfield = input->vfield(); + VField* ovfield = output->vfield(); + int ival = 0; + double oval = 0; + for (VMesh::Elem::index_type i=0; i < ivfield->vmesh()->num_elems(); i++) + { + ivfield->get_value(ival, i); + if (ival != 1 && ival != 2 && ival != 3) + FAIL() << "field value outside of range obtained " << std::endl; + ovfield->get_value(oval, i); + EXPECT_EQ(oval, conductivities[ival-1]); + } +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, TetMeshVector) +{ + SetConductivitiesToMeshAlgorithm algo; + EXPECT_THROW(algo.run(CreateTetMeshVectorOnElem()), AlgorithmInputException); +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, ThrowsForDataOnNode) +{ + SetConductivitiesToMeshAlgorithm algo; + EXPECT_THROW(algo.run(CreateTetMeshScalarOnNode()), AlgorithmInputException); +} + +TEST(SetConductivitiesToTetMeshAlgorithmTest, ThrowsForNullInput) +{ + SetConductivitiesToMeshAlgorithm algo; + FieldHandle nullField; + EXPECT_THROW(algo.run(nullField), AlgorithmInputException); +} diff --git a/pool/shard007/C++/0095747_PortableDevicePropVariantCollection.cpp b/pool/shard007/C++/0095747_PortableDevicePropVariantCollection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de3ad388c17bee33b8739cf95b584dd3f5016a02 --- /dev/null +++ b/pool/shard007/C++/0095747_PortableDevicePropVariantCollection.cpp @@ -0,0 +1,171 @@ +/* + * Copyright 2007 Pieter De Rycke + * + * This file is part of JMTP. + * + * JTMP 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 any later version. + * + * JMTP 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 LesserGeneral Public + * License along with JMTP. If not, see . + */ + +#include + +#include "jmtp.h" +#include "jmtp_PortableDevicePropVariantCollectionImplWin32.h" + +static inline IPortableDevicePropVariantCollection* GetPortableDevicePropVariantCollection + (JNIEnv* env, jobject obj) +{ + return (IPortableDevicePropVariantCollection*)GetComReferencePointer(env, obj, "pPropVariantCollection"); +} + +JNIEXPORT void JNICALL Java_jmtp_PortableDevicePropVariantCollectionImplWin32_add + (JNIEnv* env, jobject obj, jobject jobjPropVariant) +{ + //variabelen + HRESULT hr; + IPortableDevicePropVariantCollection* pPropVariantCollection; + PROPVARIANT pv; + + + //methode implementatie + if(jobjPropVariant != NULL) + { + pPropVariantCollection = GetPortableDevicePropVariantCollection(env, obj); + pv = ConvertJavaToPropVariant(env, jobjPropVariant); + hr = pPropVariantCollection->Add(&pv); + PropVariantClear(&pv); + + if(FAILED(hr)) + { + ThrowCOMException(env, L"Failed to add the element to the collection", hr); + return; + } + } + else + { + env->ThrowNew(env->FindClass("java/lang/NullPointerException"), + "propvariant isn't allowed to be null"); + } +} + +JNIEXPORT void JNICALL Java_jmtp_PortableDevicePropVariantCollectionImplWin32_clear + (JNIEnv* env, jobject obj) +{ + HRESULT hr; + IPortableDevicePropVariantCollection* pPropVariantCollection; + + pPropVariantCollection = GetPortableDevicePropVariantCollection(env, obj); + hr = pPropVariantCollection->Clear(); + if(FAILED(hr)) + { + ThrowCOMException(env, L"Failed to clear the collection", hr); + return; + } +} + +JNIEXPORT jlong JNICALL Java_jmtp_PortableDevicePropVariantCollectionImplWin32_count + (JNIEnv* env, jobject obj) +{ + HRESULT hr; + IPortableDevicePropVariantCollection* pPropVariantCollection; + DWORD dwCount; + + pPropVariantCollection = GetPortableDevicePropVariantCollection(env, obj); + hr = pPropVariantCollection->GetCount(&dwCount); + if(SUCCEEDED(hr)) + { + return (jlong)dwCount; + } + else + { + ThrowCOMException(env, L"Failed to count the collection", hr); + return -1; + } +} + +JNIEXPORT jobject JNICALL Java_jmtp_PortableDevicePropVariantCollectionImplWin32_getAt + (JNIEnv* env, jobject obj, jlong jlIndex) +{ + //variabelen + HRESULT hr; + IPortableDevicePropVariantCollection* pPropVariantCollection; + PROPVARIANT pv; + jobject jobjPropVariant; + DWORD dwCount; + + + //methode implementatie + pPropVariantCollection = GetPortableDevicePropVariantCollection(env, obj); + hr = pPropVariantCollection->GetCount(&dwCount); + if(SUCCEEDED(hr)) + { + if(jlIndex >= 0 && jlIndex < dwCount) + { + hr = pPropVariantCollection->GetAt((DWORD)jlIndex, &pv); + if(SUCCEEDED(hr)) + { + jobjPropVariant = ConvertPropVariantToJava(env, pv); + PropVariantClear(&pv); + return jobjPropVariant; + } + else + { + ThrowCOMException(env, L"Failed to retrieve the element from the collection", hr); + } + } + else + { + env->ThrowNew(env->FindClass("java/lang/IndexOutOfBoundsException"), "index out of range"); + } + } + else + { + ThrowCOMException(env, L"Failed to check the bounds of the collection", hr); + } + + return NULL; +} + +JNIEXPORT void JNICALL Java_jmtp_PortableDevicePropVariantCollectionImplWin32_removeAt + (JNIEnv* env, jobject obj, jlong jlIndex) +{ + //variabelen + HRESULT hr; + IPortableDevicePropVariantCollection* pPropVariantCollection; + DWORD dwCount; + + + //methode implementatie + pPropVariantCollection = GetPortableDevicePropVariantCollection(env, obj); + hr = pPropVariantCollection->GetCount(&dwCount); + if(SUCCEEDED(hr)) + { + if(jlIndex >= 0 && jlIndex < dwCount) + { + hr = pPropVariantCollection->RemoveAt((DWORD)jlIndex); + if(FAILED(hr)) + { + ThrowCOMException(env, L"Failed to remove the element from the collection", hr); + return; + } + } + else + { + env->ThrowNew(env->FindClass("java/lang/IndexOutOfBoundsException"), "index out of range"); + } + } + else + { + ThrowCOMException(env, L"Failed to check the bounds of the collection", hr); + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0095748_intc.cpp b/pool/shard007/C++/0095748_intc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3eac8e8d43df6ad4e3cad14f44685d28ed9bf84 --- /dev/null +++ b/pool/shard007/C++/0095748_intc.cpp @@ -0,0 +1,83 @@ +/* + SH4/mod/intc + + Implements the register interface of the sh4 interrupt controller. + For the actual implementation of interrupt caching/handling logic, look at sh4_interrupts.cpp + + -- +*/ + +#include "types.h" +#include "../sh4_interrupts.h" +#include "../sh4_mmr.h" + + +//Register writes need interrupt re-testing ! + +void write_INTC_IPRA(u32 addr, u32 data) +{ + if (INTC_IPRA.reg_data!=(u16)data) + { + INTC_IPRA.reg_data=(u16)data; + SIIDRebuild(); //we need to rebuild the table + } +} +void write_INTC_IPRB(u32 addr, u32 data) +{ + if (INTC_IPRB.reg_data!=(u16)data) + { + INTC_IPRB.reg_data=(u16)data; + SIIDRebuild(); //we need to rebuild the table + } +} +void write_INTC_IPRC(u32 addr, u32 data) +{ + if (INTC_IPRC.reg_data!=(u16)data) + { + INTC_IPRC.reg_data=(u16)data; + SIIDRebuild(); //we need to rebuild the table + } +} +static u32 read_INTC_IPRD(u32 addr) +{ + return 0; +} + +//Init/Res/Term +void intc_init() +{ + //INTC ICR 0xFFD00000 0x1FD00000 16 0x0000 0x0000 Held Held Pclk + sh4_rio_reg(INTC,INTC_ICR_addr,RIO_DATA,16); + + //INTC IPRA 0xFFD00004 0x1FD00004 16 0x0000 0x0000 Held Held Pclk + sh4_rio_reg(INTC,INTC_IPRA_addr,RIO_WF,16,0,&write_INTC_IPRA); + + //INTC IPRB 0xFFD00008 0x1FD00008 16 0x0000 0x0000 Held Held Pclk + sh4_rio_reg(INTC,INTC_IPRB_addr,RIO_WF,16,0,&write_INTC_IPRB); + + //INTC IPRC 0xFFD0000C 0x1FD0000C 16 0x0000 0x0000 Held Held Pclk + sh4_rio_reg(INTC,INTC_IPRC_addr,RIO_WF,16,0,&write_INTC_IPRC); + + //INTC IPRD 0xFFD00010 0x1FD00010 16 0xDA74 0xDA74 Held Held Pclk (SH7750S, SH7750R only) + sh4_rio_reg(INTC,INTC_IPRD_addr,RIO_RO_FUNC,16,&read_INTC_IPRD); + + interrupts_init(); +} + +void intc_reset() +{ + INTC_ICR.reg_data = 0x0; + INTC_IPRA.reg_data = 0x0; + INTC_IPRB.reg_data = 0x0; + INTC_IPRC.reg_data = 0x0; + + SIIDRebuild(); //rebuild the interrupts table + + interrupts_reset(); +} + +void intc_term() +{ + interrupts_term(); +} + diff --git a/pool/shard007/C++/0095749_main.cpp b/pool/shard007/C++/0095749_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5d57d5e08f1045fd9bad8d79aeb70b7343cdfae --- /dev/null +++ b/pool/shard007/C++/0095749_main.cpp @@ -0,0 +1,201 @@ +#include "polytope/stability_margin.h" + +#include "cdd/cddmp.h" +#include "cdd/setoper.h" +#include "cdd/cddtypes.h" +#include "cdd/cdd.h" + +#include +#include + +using namespace polytope; + +// defining timer +#ifdef WIN32 +#include +double get_time() +{ + LARGE_INTEGER t, f; + QueryPerformanceCounter(&t); + QueryPerformanceFrequency(&f); + return (double)t.QuadPart/(double)f.QuadPart; +} + +#else +#include +#include + +double get_time() +{ + struct timeval t; + struct timezone tzp; + gettimeofday(&t, &tzp); + return (double)t.tv_sec + ((double)t.tv_usec*1e-6); +} +#endif + +double unifRand(value_type a, value_type b) +{ + return (b-a)*(rand() / value_type(RAND_MAX)) + a; +} + +double unifRand(value_type b) +{ + return (b)*(rand() / value_type(RAND_MAX)); +} + +typedef Eigen::AngleAxis angle_axis_t; + +struct Problem +{ + Problem() + :x(vector_t(2)) + ,y(vector_t(2)) + ,nu(vector_t(2)) + ,positions(vector_t(6)) + ,contacts(Eigen::Matrix ::Zero()) + {} + vector_t x; + vector_t y; + vector_t nu; + vector3_t xyz; + vector_t positions; + T_rotation_t contacts; +}; + +void timeGeneration() +{ + int nbProblems = 10000; + std::vector problems; + problems.resize(nbProblems); + for(int i=0; i < nbProblems; ++i) + { + Problem& p = problems[i]; + for(int cid =0; cid <2; ++cid) + { + p.x(cid) = unifRand(2, 2); + p.y(cid) = unifRand(2, 2); + p.nu(cid) = unifRand(0.1,1.); + //p.nu(cid) = 1; + p.xyz = vector3_t(unifRand(M_PI),unifRand(M_PI),unifRand(M_PI)); + Eigen::Matrix rot = //-Eigen::Matrix ::Identity(); + Eigen::Matrix ( + angle_axis_t(p.xyz[0], vector3_t::UnitX()) + * angle_axis_t(p.xyz[1], vector3_t::UnitY()) + * angle_axis_t(p.xyz[2], vector3_t::UnitZ())); + vector3_t translation; + for(int tid = 0; tid < 3; ++tid) + { + translation[tid] = 0; //unifRand(3.); + translation[tid] = unifRand(1,3.); + } + p.contacts.block<3,3>(cid*3,0) = rot; + p.positions.segment<3>(cid*3) = translation; + } + } + + double time = get_time(); + int saved(0); int failed(0); + int i = 0; + for(std::vector::iterator cit = problems.begin(); + cit != problems.end(); ++cit, ++i) + { + //std::auto_ptr cone (U_stance(cit->contacts.block<3,3>(0,0), cit->positions.head(3), cit->nu.head(1), cit->x.head(1), cit->y.head(1))); + std::auto_ptr cone (U_stance(cit->contacts, cit->positions, cit->nu, cit->x, cit->y)); + if(!cone.get()) + { + /*std::cout << "rot x y z \n" << cit->xyz * 180 / M_PI << std::endl; + std::cout << "positions " << cit->positions.head(3) << std::endl; + std::cout << "friction " << cit->nu.head(1) << std::endl; + cit->nu[0] = cit->nu[0] + 0.2;*/ + //const ProjectedCone* coneOffset = U_stance(cit->contacts.block<3,3>(0,0), cit->positions.head(3), cit->nu.head(1), cit->x.head(1), cit->y.head(1)); + cit->nu[0] = cit->nu[0] + 0.2; + const ProjectedCone* coneOffset = U_stance(cit->contacts, cit->positions, cit->nu, cit->x, cit->y); + if(coneOffset) + { + ++saved; + delete coneOffset; + } + else + { + ++failed; + } + //dd_debug = false; + //break; + } + } + time = get_time() - time; + std::cout << "average time to generate two contact problem (one projection): \n" + << time / (double)nbProblems << std::endl; + std::cout << "number of instable cones:" << (saved+failed) << std::endl; + std::cout << "percentage of instable cones:" << (double)(saved+failed) * 100 / (double)nbProblems << "%" << std::endl; + std::cout << "percentage of saved instable cones:" << (double)(saved) * 100 / (double)(saved+failed) << "%" << std::endl; +} + +int creationTest() +{ + int ret = 0; + vector_t x(2); x << 1, 1; + vector_t y(2); y << 1, 1; + vector_t nu(2); nu << 1, 0.5; + T_rotation_t contact = Eigen::Matrix ::Identity(); + T_rotation_t contacts = Eigen::Matrix ::Zero(); + contacts.block<3,3>(0,0) = contact; + contacts.block<3,3>(3,0) = contact; + vector_t position(6); position << 0,0,0,3,0,0; + // assert all vectors are different + matrix_t cone = V_all(x.head(1), y.head(1), nu.head(1)).transpose(); + std::cout << "cone \n" << cone.transpose() << std::endl; + /*for(int i = 0; i < 37; ++i) + { + for(int j = i+1; j < 32; ++j) + { + if((cone.block<1,6>(i,0) - cone.block<1,6>(j,0)).norm() + < 2 * std::numeric_limits::epsilon()) + { + std::cout << "found two equal vectors at col indexes " << i << " and " << j << std::endl; + std::cout << cone.block<1,6>(i,0) << "\n \n" << cone.block<1,6>(j,0) << std::endl; + ret = -1; + } + } + }*/ + + const ProjectedCone* c = U_stance(contacts,position, nu,x,y); + const ProjectedCone* c1 = U_stance(contacts.block<3,3>(0,0), position.head<3>(), + nu.head(1),x.head(1),y.head(1)); + const ProjectedCone* c2 = U_stance(contacts.block<3,3>(3,0), position.tail<3>(), + nu.tail(1),x.tail(1),y.tail(1)); + vector3_t gravity(0,0,-9.81); + value_type mass(40); + vector3_t goodP(0,0,3.); + vector3_t goodP2(1,0,0); + vector3_t badP(1.5,0,3.); // valid only in double support + + std::cout << "good position verified ? " << c1->IsValid(goodP2,gravity,mass) << std::endl; + std::cout << "good position verified ? " << c1->IsValid(goodP,gravity,mass) << std::endl; + std::cout << "bad position verified ? " << c1->IsValid(badP,gravity,mass) << std::endl; + std::cout << "bad position verified ? " << c2->IsValid(badP,gravity,mass) << std::endl; + std::cout << "good position verified ? " << c->IsValid(badP,gravity,mass) << std::endl; + delete c; + delete c1; + delete c2; + return ret; +} + +int main() +{ + srand ((unsigned int)(time(NULL))); + int ret = 0; + init_library(); + ret+= creationTest(); + timeGeneration(); + Eigen::Matrix nu, x, y; + nu << 2, 4; x << 3, 6; y << 5, 10; + + /*Eigen::Matrix nu, x, y; + nu << 1; x << 1; y << 1;*/ + + std::cout << V_all(nu,x,y) << std::endl; + release_library(); + return ret; +} diff --git a/pool/shard007/C++/0095757_SimpleGame.cpp b/pool/shard007/C++/0095757_SimpleGame.cpp new file mode 100644 index 0000000000000000000000000000000000000000..94a40c37c266aeeb7ada14c4b37e1344f1ff916b --- /dev/null +++ b/pool/shard007/C++/0095757_SimpleGame.cpp @@ -0,0 +1,110 @@ +/* +Copyright 2017 Lee Taek Hee (Korea Polytech University) + +This program is free software: you can redistribute it and/or modify +it under the terms of the What The Hell License. Do it plz. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY. +*/ + + +#include "stdafx.h" +#include +#include "Dependencies\glew.h" +#include "Dependencies\freeglut.h" + + +#include "Renderer.h" +#include "Object.h" +#include "ScenceMgr.h" + + +ScenceMgr* Scence = NULL; +DWORD starttime = 0; + +void RenderScene(void) +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClearColor(0.0f, 0.3f, 0.3f, 1.0f); + + DWORD nowtime = timeGetTime(); + DWORD elaspedtime = nowtime - starttime; + starttime = nowtime; + + Scence->RenderObject(); + Scence->Update_AllObject((float)elaspedtime); + + glutSwapBuffers(); + +} + + +void Idle(void) +{ + + RenderScene(); +} + +void MouseInput(int button, int state, int x, int y) +{ + + if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { + Scence->Clickmake(x, y); + } + RenderScene(); +} + +void KeyInput(unsigned char key, int x, int y) +{ + RenderScene(); +} + +void SpecialKeyInput(int key, int x, int y) +{ + RenderScene(); +} + + +int main(int argc, char **argv) +{ + + // Initialize GL things + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); + glutInitWindowPosition(0, 0); + glutInitWindowSize(500, 800); + glutCreateWindow("Game Software Engineering KPU"); + + + glewInit(); + + if (glewIsSupported("GL_VERSION_3_0")) + { + std::cout << " GLEW Version is 3.0\n "; + } + else + { + cout << "GLEW 3.0 not supported "<< endl; + } + + // Initialize Renderer + + + Scence = new ScenceMgr(500, 800); + + glutDisplayFunc(RenderScene); + glutIdleFunc(Idle); + glutKeyboardFunc(KeyInput); + glutMouseFunc(MouseInput); + glutSpecialFunc(SpecialKeyInput); + + starttime = timeGetTime(); + + glutMainLoop(); + + delete Scence; + + return 0; +} + diff --git a/pool/shard007/C++/0095758_cpptoolsreuse.cpp b/pool/shard007/C++/0095758_cpptoolsreuse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f64a31ffdba9520a66cff8cfa21162cce99ae3c3 --- /dev/null +++ b/pool/shard007/C++/0095758_cpptoolsreuse.cpp @@ -0,0 +1,230 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** 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://www.qt.io/licensing. For further information +** use the contact form at http://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 2.1 or version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv21 and +** LICENSE.LGPLv3 included in the packaging of this file. Please review the +** following information to ensure the GNU Lesser General Public License +** requirements will be met: https://www.gnu.org/licenses/lgpl.html and +** 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. +** +****************************************************************************/ + +#include "cpptoolsreuse.h" + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +using namespace CPlusPlus; + +namespace CppTools { + +static void moveCursorToStartOrEndOfIdentifier(QTextCursor *tc, + QTextCursor::MoveOperation op, + int posDiff = 0) +{ + QTextDocument *doc = tc->document(); + if (!doc) + return; + + QChar ch = doc->characterAt(tc->position() - posDiff); + while (isValidIdentifierChar(ch)) { + tc->movePosition(op); + ch = doc->characterAt(tc->position() - posDiff); + } +} + +void moveCursorToEndOfIdentifier(QTextCursor *tc) +{ + moveCursorToStartOrEndOfIdentifier(tc, QTextCursor::NextCharacter); +} + +void moveCursorToStartOfIdentifier(QTextCursor *tc) +{ + moveCursorToStartOrEndOfIdentifier(tc, QTextCursor::PreviousCharacter, 1); +} + +static bool isOwnershipRAIIName(const QString &name) +{ + static QSet knownNames; + if (knownNames.isEmpty()) { + // Qt + knownNames.insert(QLatin1String("QScopedPointer")); + knownNames.insert(QLatin1String("QScopedArrayPointer")); + knownNames.insert(QLatin1String("QMutexLocker")); + knownNames.insert(QLatin1String("QReadLocker")); + knownNames.insert(QLatin1String("QWriteLocker")); + // Standard C++ + knownNames.insert(QLatin1String("auto_ptr")); + knownNames.insert(QLatin1String("unique_ptr")); + // Boost + knownNames.insert(QLatin1String("scoped_ptr")); + knownNames.insert(QLatin1String("scoped_array")); + } + + return knownNames.contains(name); +} + +bool isOwnershipRAIIType(CPlusPlus::Symbol *symbol, const LookupContext &context) +{ + if (!symbol) + return false; + + // This is not a "real" comparison of types. What we do is to resolve the symbol + // in question and then try to match its name with already known ones. + if (symbol->isDeclaration()) { + Declaration *declaration = symbol->asDeclaration(); + const NamedType *namedType = declaration->type()->asNamedType(); + if (namedType) { + ClassOrNamespace *clazz = context.lookupType(namedType->name(), + declaration->enclosingScope()); + if (clazz && !clazz->symbols().isEmpty()) { + Overview overview; + Symbol *symbol = clazz->symbols().at(0); + return isOwnershipRAIIName(overview.prettyName(symbol->name())); + } + } + } + + return false; +} + +bool isValidAsciiIdentifierChar(const QChar &ch) +{ + return ch.isLetterOrNumber() || ch == QLatin1Char('_'); +} + +bool isValidFirstIdentifierChar(const QChar &ch) +{ + return ch.isLetter() || ch == QLatin1Char('_') || ch.isHighSurrogate() || ch.isLowSurrogate(); +} + +bool isValidIdentifierChar(const QChar &ch) +{ + return isValidFirstIdentifierChar(ch) || ch.isNumber(); +} + +bool isValidIdentifier(const QString &s) +{ + const int length = s.length(); + for (int i = 0; i < length; ++i) { + const QChar &c = s.at(i); + if (i == 0) { + if (!isValidFirstIdentifierChar(c)) + return false; + } else { + if (!isValidIdentifierChar(c)) + return false; + } + } + return true; +} + +bool isQtKeyword(const QStringRef &text) +{ + switch (text.length()) { + case 4: + switch (text.at(0).toLatin1()) { + case 'e': + if (text == QLatin1String("emit")) + return true; + break; + case 'S': + if (text == QLatin1String("SLOT")) + return true; + break; + } + break; + + case 5: + if (text.at(0) == QLatin1Char('s') && text == QLatin1String("slots")) + return true; + break; + + case 6: + if (text.at(0) == QLatin1Char('S') && text == QLatin1String("SIGNAL")) + return true; + break; + + case 7: + switch (text.at(0).toLatin1()) { + case 's': + if (text == QLatin1String("signals")) + return true; + break; + case 'f': + if (text == QLatin1String("foreach") || text == QLatin1String("forever")) + return true; + break; + } + break; + + default: + break; + } + return false; +} + +void switchHeaderSource() +{ + const Core::IDocument *currentDocument = Core::EditorManager::currentDocument(); + QTC_ASSERT(currentDocument, return); + const QString otherFile = correspondingHeaderOrSource(currentDocument->filePath().toString()); + if (!otherFile.isEmpty()) + Core::EditorManager::openEditor(otherFile); +} + +QString identifierUnderCursor(QTextCursor *cursor) +{ + cursor->movePosition(QTextCursor::StartOfWord); + cursor->movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor); + return cursor->selectedText(); +} + +const Macro *findCanonicalMacro(const QTextCursor &cursor, Document::Ptr document) +{ + QTC_ASSERT(document, return 0); + + int line, column; + TextEditor::Convenience::convertPosition(cursor.document(), cursor.position(), &line, &column); + + if (const Macro *macro = document->findMacroDefinitionAt(line)) { + QTextCursor macroCursor = cursor; + const QByteArray name = CppTools::identifierUnderCursor(¯oCursor).toUtf8(); + if (macro->name() == name) + return macro; + } else if (const Document::MacroUse *use = document->findMacroUseAt(cursor.position())) { + return &use->macro(); + } + + return 0; +} + +} // CppTools diff --git a/pool/shard007/C++/0095762_qvfbprotocol.cpp b/pool/shard007/C++/0095762_qvfbprotocol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b253f148757a84ec99c3cf71c7c8b9b33fe080c --- /dev/null +++ b/pool/shard007/C++/0095762_qvfbprotocol.cpp @@ -0,0 +1,195 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** 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, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qvfbprotocol.h" +#include "qvfbhdr.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_UNIX +#include +#endif + +#include "qvfbshmem.h" + +QT_BEGIN_NAMESPACE + +QVFbViewProtocol::QVFbViewProtocol(int display_id, QObject *parent) : + QObject(parent), mDisplayId(display_id) { } + +QVFbViewProtocol::~QVFbViewProtocol() {} + +void QVFbViewProtocol::flushChanges() {} + +void QVFbViewProtocol::sendKeyboardData(QString unicode, int keycode, + int modifiers, bool press, bool repeat) +{ + if (keyHandler()) + keyHandler()->sendKeyboardData(unicode, keycode, modifiers, press, repeat); +} + +void QVFbViewProtocol::sendMouseData(const QPoint &pos, int buttons, int wheel) +{ + if (mouseHandler()) + mouseHandler()->sendMouseData(pos, buttons, wheel); +} + +static int openPipe(const char *fileName) +{ + unlink(fileName); + + mkfifo(fileName, 0666); + int fd = ::open(fileName, O_RDWR | O_NDELAY); + return fd; +} + +QVFbKeyPipeProtocol::QVFbKeyPipeProtocol(int display_id) + : QVFbKeyProtocol(display_id) +{ + fileName = QT_VFB_KEYBOARD_PIPE(display_id); + fd = openPipe(fileName.toLocal8Bit().constData()); + + if (fd == -1) + qFatal("Cannot open keyboard pipe %s", fileName.toLocal8Bit().data()); +} + +QVFbKeyPipeProtocol::~QVFbKeyPipeProtocol() +{ + sendKeyboardData(0, 0, 0, true, false); // magic die key + ::close(fd); + unlink(fileName.toLocal8Bit().constData()); +} + +void QVFbKeyPipeProtocol::sendKeyboardData(QString unicode, int keycode, + int modifiers, bool press, bool repeat) +{ + QVFbKeyData kd; + kd.unicode = unicode[0].unicode(); + kd.keycode = keycode; + kd.modifiers = static_cast(modifiers); + kd.press = press; + kd.repeat = repeat; + write(fd, &kd, sizeof(QVFbKeyData)); +} + +QVFbMousePipe::QVFbMousePipe(int display_id) + : QVFbMouseProtocol(display_id) +{ + fileName = QT_VFB_MOUSE_PIPE(display_id); + fd = openPipe(fileName.toLocal8Bit().constData()); + + if (fd == -1) + qFatal("Cannot open mouse pipe %s", fileName.toLocal8Bit().data()); +} + +QVFbMousePipe::~QVFbMousePipe() +{ + ::close(fd); + unlink(fileName.toLocal8Bit().constData()); +} + + +void QVFbMousePipe::sendMouseData(const QPoint &pos, int buttons, int wheel) +{ + write(fd, &pos, sizeof(QPoint)); + write(fd, &buttons, sizeof(int)); + write(fd, &wheel, sizeof(int)); +} + +QVFbMouseLinuxTP::QVFbMouseLinuxTP(int display_id) + : QObject(), QVFbMousePipe(display_id), lastPos(-1,-1) +{ + /* the timer is needed because a real touch screen send data as long as + there is pressure. And the linux tp driver will filter, requiring + a minimum of 5 samples before it even registers a press. + */ + repeater = new QTimer(this); + connect(repeater, SIGNAL(timeout()), this, SLOT(repeatLastPress())); +} + +QVFbMouseLinuxTP::~QVFbMouseLinuxTP() +{ +} + + +void QVFbMouseLinuxTP::sendMouseData(const QPoint &pos, int buttons, int) +{ + if (buttons & Qt::LeftButton) { + // press + repeater->start(5); + writeToPipe(pos, 1); + lastPos = pos; + } else { + // release + if (lastPos == QPoint(-1,-1)) + return; /* only send one release */ + repeater->stop(); + writeToPipe(pos, 0); + lastPos = QPoint(-1,-1); + } +} + +void QVFbMouseLinuxTP::writeToPipe(const QPoint &pos, ushort pressure) +{ + ushort v; + write(fd, &pressure, sizeof(ushort)); + v = pos.x(); + write(fd, &v, sizeof(ushort)); + v = pos.y(); + write(fd, &v, sizeof(ushort)); + v = 1; // pad + write(fd, &v, sizeof(ushort)); +} + +void QVFbMouseLinuxTP::repeatLastPress() +{ + writeToPipe(lastPos, 1); +} + +QT_END_NAMESPACE diff --git a/pool/shard007/C++/0095770_testtimer.cpp b/pool/shard007/C++/0095770_testtimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d40347b894cf2ecca2fbf5ef47ae7143ca09ddb2 --- /dev/null +++ b/pool/shard007/C++/0095770_testtimer.cpp @@ -0,0 +1,45 @@ +/* + * Cppcheck - A tool for static C/C++ code analysis + * Copyright (C) 2007-2016 Cppcheck 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 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 "timer.h" +#include "testsuite.h" +#include + + +class TestTimer : public TestFixture { +public: + TestTimer() : TestFixture("TestTimer") { + } + +private: + + void run() { + TEST_CASE(result); + } + + void result() const { + TimerResultsData t1; + t1._clocks = ~(std::clock_t)0; + ASSERT(t1.seconds() > 100.0); + + t1._clocks = CLOCKS_PER_SEC * 5 / 2; + ASSERT(std::fabs(t1.seconds()-2.5) < 0.01); + } +}; + +REGISTER_TEST(TestTimer) diff --git a/pool/shard007/C++/0095771_logmacro.cc b/pool/shard007/C++/0095771_logmacro.cc new file mode 100644 index 0000000000000000000000000000000000000000..92ae5b680e75aad7fbb02b73e2927ddb0bd4b952 --- /dev/null +++ b/pool/shard007/C++/0095771_logmacro.cc @@ -0,0 +1,91 @@ +// Module: Log4CPLUS +// File: loggingmacros.cxx +// Created: 4/2010 +// Author: Vaclav Haisman +// +// +// Copyright 2010 Vaclav Haisman +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** @file + * This file implements support function for logmacro.h file. */ + +#include "dcmtk/oflog/internal/internal.h" +#include "dcmtk/oflog/logmacro.h" + + +namespace dcmtk { +namespace log4cplus { namespace detail { + + +//! Helper stream to get the defaults from. +static tostringstream const macros_oss_defaults; + +// Individual defaults. + +static STD_NAMESPACE ios_base::fmtflags const default_flags + = macros_oss_defaults.flags (); +static log4cplus::tchar const default_fill = macros_oss_defaults.fill (); +static STD_NAMESPACE streamsize const default_precision + = macros_oss_defaults.precision (); +static STD_NAMESPACE streamsize const default_width = macros_oss_defaults.width (); + +//! Clears string stream using defaults taken from macros_oss_defaults. +void +clear_tostringstream (tostringstream & os) +{ + os.clear (); + os.str (""); + os.setf (default_flags); + os.fill (default_fill); + os.precision (default_precision); + os.width (default_width); +#if defined (DCMTK_LOG4CPLUS_WORKING_LOCALE) + STD_NAMESPACE locale glocale = STD_NAMESPACE locale (); + if (os.getloc () != glocale) + os.imbue (glocale); +#endif // defined (DCMTK_LOG4CPLUS_WORKING_LOCALE) +} + + +log4cplus::tostringstream & +get_macro_body_oss () +{ + tostringstream & oss = internal::get_ptd ()->macros_oss; + clear_tostringstream (oss); + return oss; +} + + +log4cplus::helpers::snprintf_buf & +get_macro_body_snprintf_buf () +{ + return internal::get_ptd ()->snprintf_buf; +} + + +void +macro_forced_log (log4cplus::Logger const & logger, + log4cplus::LogLevel log_level, log4cplus::tstring const & msg, + char const * filename, int line, char const * func) +{ + log4cplus::spi::InternalLoggingEvent & ev = internal::get_ptd ()->forced_log_ev; + ev.setLoggingEvent (logger.getName (), log_level, msg, filename, line); + ev.setFunction (func ? func : ""); + logger.forcedLog (ev); +} + + +} } // namespace log4cplus { namespace detail { +} // end namespace dcmtk diff --git a/pool/shard007/C++/0095781_Time.cpp b/pool/shard007/C++/0095781_Time.cpp new file mode 100644 index 0000000000000000000000000000000000000000..624932991be639339e9556b53c6da9f189bc7636 --- /dev/null +++ b/pool/shard007/C++/0095781_Time.cpp @@ -0,0 +1,126 @@ +// Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) +// 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. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include +#include +#include + +namespace w32 { + + Time Time::now () + { + ::SYSTEMTIME time; + ::GetSystemTime(&time); + return (Time(time)); + } + + Time::Time () + { + ::ZeroMemory(&myData,sizeof(myData)); + } + + Time::Time ( const Data& value ) + : myData(value) + { + } + + Time::Time ( const ::FILETIME& value ) + { + const ::BOOL result = ::FileTimeToSystemTime(&value,&myData); + if ( result == FALSE ) { + UNCHECKED_WIN32C_ERROR(FileTimeToSystemTime,::GetLastError()); + } + } + + Time::Data& Time::data () + { + return (myData); + } + + const Time::Data& Time::data () const + { + return (myData); + } + + word Time::year () const + { + return (myData.wYear); + } + + word Time::month () const + { + return (myData.wMonth); + } + + word Time::day () const + { + return (myData.wDay); + } + + word Time::hour () const + { + return (myData.wHour); + } + + word Time::minute () const + { + return (myData.wMinute); + } + + word Time::second () const + { + return (myData.wSecond); + } + + word Time::millisecond () const + { + return (myData.wMilliseconds); + } + + Time& Time::operator+= ( const Delta& delta ) + { + // Convert to file time. + ::FILETIME time; ::SystemTimeToFileTime(&myData, &time); + + // Perform computation in number of ticks. + ::ULARGE_INTEGER result = + { time.dwLowDateTime, time.dwHighDateTime }; + result.QuadPart += delta.ticks(); + time.dwLowDateTime = result.LowPart; + time.dwHighDateTime = result.HighPart; + + // Convert back to system time. + ::FileTimeToSystemTime(&time, &myData); + + return (*this); + } + + Time operator+ ( const Time& time, const Delta& delta ) + { + Time result = time; result += delta; return (result); + } + +} diff --git a/pool/shard007/C++/0095786_TestDataListener.cpp b/pool/shard007/C++/0095786_TestDataListener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7eb76a0a2e591a48254733d5449f1a9310d399f --- /dev/null +++ b/pool/shard007/C++/0095786_TestDataListener.cpp @@ -0,0 +1,141 @@ +#include "TestDataListener.h" +#include "MantidAPI/Axis.h" +#include "MantidAPI/LiveListenerFactory.h" +#include "MantidAPI/WorkspaceFactory.h" +#include "MantidDataObjects/EventWorkspace.h" +#include "MantidGeometry/Instrument.h" +#include "MantidKernel/ConfigService.h" +#include "MantidKernel/MersenneTwister.h" +#include "MantidTestHelpers/ComponentCreationHelper.h" + +using namespace Mantid::API; +using namespace Mantid::DataObjects; +using namespace Mantid::Geometry; +using Mantid::Kernel::ConfigService; + +namespace Mantid { +namespace LiveData { +DECLARE_LISTENER(TestDataListener) + +/// Constructor +TestDataListener::TestDataListener() + : LiveListener(), m_buffer(), + m_rand(new Kernel::MersenneTwister( + Kernel::DateAndTime::getCurrentTime().totalNanoseconds(), 40000, + 60000)), + m_changeStatusAfter(0), m_newStatus(ILiveListener::EndRun) { + // Set up the first workspace buffer + this->createEmptyWorkspace(); + + m_dataReset = false; + m_timesCalled = 0; + if (!ConfigService::Instance().getValue("testdatalistener.reset_after", + m_resetAfter)) + m_resetAfter = 0; + if (!ConfigService::Instance().getValue( + "testdatalistener.m_changeStatusAfter", m_changeStatusAfter)) + m_changeStatusAfter = 0; + int temp = 0; + if (!ConfigService::Instance().getValue("testdatalistener.m_newStatus", + temp)) { + if (temp == 0) + m_newStatus = ILiveListener::NoRun; + if (temp == 1) + m_newStatus = ILiveListener::BeginRun; + if (temp == 2) + m_newStatus = ILiveListener::Running; + if (temp == 4) + m_newStatus = ILiveListener::EndRun; + } +} + +/// Destructor +TestDataListener::~TestDataListener() { delete m_rand; } + +bool TestDataListener::connect(const Poco::Net::SocketAddress &) { + // Do nothing for now. Later, put in stuff to help test failure modes. + return true; +} + +bool TestDataListener::isConnected() { + // For the time being at least + return true; +} + +bool TestDataListener::dataReset() { + // No support for reset signal + return false; +} + +ILiveListener::RunStatus TestDataListener::runStatus() { + // For testing + if (m_changeStatusAfter > 0 && m_timesCalled == m_changeStatusAfter) { + return m_newStatus; + } else + // In a run by default + return Running; +} + +int TestDataListener::runNumber() const { return 999; } + +void TestDataListener::start( + Kernel::DateAndTime /*startTime*/) // Ignore the start time +{} + +/** Create the default empty event workspace */ +void TestDataListener::createEmptyWorkspace() { + // Create a new, empty workspace of the same dimensions and assign to the + // buffer variable + m_buffer = boost::dynamic_pointer_cast( + WorkspaceFactory::Instance().create("EventWorkspace", 2, 2, 1)); + // Give detector IDs + for (size_t i = 0; i < m_buffer->getNumberHistograms(); i++) + m_buffer->getSpectrum(i).setDetectorID(detid_t(i)); + // Create in TOF units + m_buffer->getAxis(0)->setUnit("TOF"); + // Load a fake instrument + Instrument_sptr inst = + ComponentCreationHelper::createTestInstrumentRectangular2(1, 10, 0.1); + m_buffer->setInstrument(inst); + // Set a run number + m_buffer->mutableRun().addProperty("run_number", std::string("999")); + // Add a monitor workspace + auto monitorWS = + WorkspaceFactory::Instance().create("EventWorkspace", 1, 2, 1); + WorkspaceFactory::Instance().initializeFromParent(*m_buffer, *monitorWS, + true); + monitorWS->dataX(0)[0] = 40000; + monitorWS->dataX(0)[1] = 60000; + m_buffer->setMonitorWorkspace(monitorWS); +} + +boost::shared_ptr TestDataListener::extractData() { + m_dataReset = false; + // Add a small number of uniformly distributed events to each event list. + using namespace DataObjects; + EventList &el1 = m_buffer->getSpectrum(0); + EventList &el2 = m_buffer->getSpectrum(1); + for (int i = 0; i < 100; ++i) { + el1.addEventQuickly(TofEvent(m_rand->nextValue())); + el2.addEventQuickly(TofEvent(m_rand->nextValue())); + } + auto mon_buffer = + boost::dynamic_pointer_cast(m_buffer->monitorWorkspace()); + mon_buffer->getSpectrum(0).addEventQuickly(TofEvent(m_rand->nextValue())); + + // Copy the workspace pointer to a temporary variable + EventWorkspace_sptr extracted = m_buffer; + this->createEmptyWorkspace(); + + m_timesCalled++; + + if (m_resetAfter > 0 && m_timesCalled >= m_resetAfter) { + m_dataReset = true; + m_timesCalled = 0; + } + + return extracted; +} + +} // namespace LiveData +} // namespace Mantid diff --git a/pool/shard007/C++/0095788_Or1ksimJtagSC.cpp b/pool/shard007/C++/0095788_Or1ksimJtagSC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8973810742c33ff17dea7099559e83509c16a47b --- /dev/null +++ b/pool/shard007/C++/0095788_Or1ksimJtagSC.cpp @@ -0,0 +1,182 @@ +// Wrapper for Or1ksim with interrupts and JTAG module implementation + +// Copyright (C) 2008, 2010 Embecosm Limited + +// Contributor Jeremy Bennett + +// This file is part of the example programs for "Building a Loosely Timed SoC +// Model with OSCI TLM 2.0" + +// 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 . +// ---------------------------------------------------------------------------- + +// ---------------------------------------------------------------------------- +// This code is commented throughout for use with Doxygen. +// ---------------------------------------------------------------------------- + +#include "Or1ksimJtagSC.h" + + +using sc_core::SC_SEC; +using sc_core::sc_module_name; +using sc_core::sc_time; + +using std::cerr; +using std::endl; + + +// ---------------------------------------------------------------------------- +//! Custom constructor for the Or1ksimJtagSC SystemC module + +//! Although there is a new thread of control to handle JTAG, it is not +//! declared here. Since we are (for JTAG) a TLM target, it will be the thread +//! of the initiator socket. + +//! The JTAG interface is implemented as an 8-bit wide TLM target port with an +//! extension to specify the number of bits. + +//! We must initialize the Mutex to be unlocked. + +//! @param name SystemC module name +//! @param configFile Config file for the underlying ISS +//! @param imageFile Binary image to run on the ISS +// ---------------------------------------------------------------------------- +Or1ksimJtagSC::Or1ksimJtagSC (sc_module_name name, + const char *configFile, + const char *imageFile) : + Or1ksimIntrSC (name, configFile, imageFile) +{ + // Bind the handler to the JTAG target port. + jtag.register_b_transport( this, &Or1ksimJtagSC::jtagHandler ); + + // Unlock the Mutex + or1ksimMutex.unlock (); + +} /* Or1ksimJtagSC() */ + + +// ---------------------------------------------------------------------------- +//! The SystemC thread running the underlying ISS + +//! This version uses temporal decoupling and is based on the version in the +//! base class, Or1ksimDecoupSC::run (). + +//! This version adds a mutex to lock access to the underlying ISS. The JTAG +//! thread may not simultaneously access this. +// ---------------------------------------------------------------------------- +void +Or1ksimJtagSC::run () +{ + while( true ) { + // Compute how much time left in this quantum + sc_time timeLeft = + tgq->compute_local_quantum () - issQk.get_local_time (); + + // Reset the ISS time point. + or1ksim_set_time_point (); + + // Run for (up to) the remainder of this quantum. Surround the call by a + // mutex lock. + or1ksimMutex.lock (); + (void)or1ksim_run (timeLeft.to_seconds ()); + or1ksimMutex.unlock (); + + // Increment local time by the amount consumed. + issQk.inc (sc_time (or1ksim_get_time_period(), SC_SEC)); + + // If we halted before the end of the ISS period, that is presumably + // because we have stalled. In which case we should immediately sync to + // allow a potential JTAG thread to run. Otherwise we should only sync if + // we have reached the end of the quantum. Except that must be the + // case. So we don't need to call need_sync (), we can just sync here. + issQk.sync (); + } + +} // Or1ksimSC () + + +//----------------------------------------------------------------------------- +//! Handler for a new JTAG transaction + +//! The extension is ignorable, for greatest interoperability. If it is not +//! present, then the data length multiplied by 8 is used as the bit length +//! and the address is used to indicate the transaction required as follows: +//! - 0: Shift through IR +//! - 1: Shift through DR +//! - any other value: Reset + +//! @param[in,out] payload The generic payload (with mandatory JTAG extensions) +//! @param[in,out] delay The incoming delay and on return the total delay +//! for this thread. +//----------------------------------------------------------------------------- +void +Or1ksimJtagSC::jtagHandler( tlm::tlm_generic_payload &payload, + sc_core::sc_time &delay ) +{ + // Retrieve the extension. + JtagExtensionSC *ext; + payload.get_extension (ext); + + // Check if the extension exists. Set up the access type and bit size as + // appropriate. + JtagExtensionSC::AccessType type; + int bitSize; + + if (NULL == ext) + { + unsigned int addr = (unsigned int) payload.get_address (); + + type = (ADDR_SHIFT_IR == addr) ? JtagExtensionSC::SHIFT_IR : + (ADDR_SHIFT_DR == addr) ? JtagExtensionSC::SHIFT_DR : + JtagExtensionSC::RESET ; + bitSize = 8 * (int) payload.get_data_length (); + } + else + { + type = ext->getType (); + bitSize = ext->getBitSize (); + } + + // Behavior depends on the type + switch (type) + { + case JtagExtensionSC::RESET: + or1ksimMutex.lock (); + delay += sc_time (or1ksim_jtag_reset (), SC_SEC); + or1ksimMutex.unlock (); + payload.set_response_status (tlm::TLM_OK_RESPONSE); + return; + + case JtagExtensionSC::SHIFT_IR: + or1ksimMutex.lock (); + delay += sc_time (or1ksim_jtag_shift_ir (payload.get_data_ptr (), + bitSize), SC_SEC); + or1ksimMutex.unlock (); + payload.set_response_status (tlm::TLM_OK_RESPONSE); + return; + + case JtagExtensionSC::SHIFT_DR: + or1ksimMutex.lock (); + delay += sc_time (or1ksim_jtag_shift_dr (payload.get_data_ptr (), + bitSize), SC_SEC); + or1ksimMutex.unlock (); + payload.set_response_status (tlm::TLM_OK_RESPONSE); + return; + + default: + cerr << "ERROR: Unrecognized JTAG transaction type." << endl; + payload.set_response_status (tlm::TLM_GENERIC_ERROR_RESPONSE); + return; + } +} /* jtagHandler () */ diff --git a/pool/shard007/C++/0095792_instance_unittest.cc b/pool/shard007/C++/0095792_instance_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..31ac8b57f0fa967ca636edd520c38111d13c6a2b --- /dev/null +++ b/pool/shard007/C++/0095792_instance_unittest.cc @@ -0,0 +1,59 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +#include "../src/configuration.h" +#include "../src/environment.h" +#include "../src/instance.h" +#include "../src/resource.h" +#include "../src/updater.h" +#include "gtest/gtest.h" + +namespace google { +namespace { + +TEST(InstanceTest, GetInstanceMonitoredResource) { + Configuration config(std::istringstream( + "InstanceResourceType: gce_instance\n" + "InstanceId: 1234567891011\n" + "InstanceZone: us-east1-b\n" + )); + Environment env(config); + EXPECT_EQ(MonitoredResource("gce_instance", { + {"instance_id", "1234567891011"}, + {"zone", "us-east1-b"} + }), InstanceReader::InstanceResource(env)); +} + +TEST(InstanceTest, GetInstanceMetatadataQuery) { + Configuration config(std::istringstream( + "InstanceResourceType: gce_instance\n" + "InstanceId: 1234567891011\n" + "InstanceZone: us-east1-b\n" + )); + InstanceReader reader(config); + const auto result = reader.MetadataQuery(); + EXPECT_EQ(1, result.size()); + const MetadataUpdater::ResourceMetadata& rm = result[0]; + EXPECT_EQ(MonitoredResource("gce_instance", { + {"instance_id", "1234567891011"}, + {"zone", "us-east1-b"} + }), rm.resource()); + EXPECT_EQ(std::vector({"", "1234567891011"}), rm.ids()); + EXPECT_TRUE(rm.metadata().ignore); +} + +} // namespace +} // google diff --git a/pool/shard007/C++/0095793_CConfigViewer.cpp b/pool/shard007/C++/0095793_CConfigViewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4e9ae90da3db35becd09f9a792d8a0a5821f41a --- /dev/null +++ b/pool/shard007/C++/0095793_CConfigViewer.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2013 Matus Fedorko + * + * This file is part of Holoren. + * + * Holoren 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. + * + * Holoren 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 Holoren. If not, see . + */ + +/** + */ + +#include "CConfigViewer.h" + +#include +#include +#include + + + +/** + */ +CConfigViewer::CConfigViewer(const QString & cfg_dir, QWidget *parent) + : QDockWidget(parent), + m_cfg_list(0), + m_cfg_dir(cfg_dir) +{ + m_cfg_list = new QListWidget; + + m_cfg_list->setSelectionMode(QAbstractItemView::SingleSelection); + + refresh(); + + setWidget(m_cfg_list); +} + + +/** + */ +QString CConfigViewer::getSelectedConfigDir(void) const +{ + QListWidgetItem *item = m_cfg_list->currentItem(); + if (item == NULL) + { + return QString(); + } + + return item->data(Qt::UserRole).toString(); +} + + +/** + */ +void CConfigViewer::refresh(void) +{ + m_cfg_list->clear(); + + if (m_cfg_dir.isEmpty()) + { + return; + } + + QDirIterator cfg_dir_it(m_cfg_dir, QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); + + while (cfg_dir_it.hasNext()) + { + cfg_dir_it.next(); // this has to be called first (for some weird reason) + + QListWidgetItem *item = new QListWidgetItem; + + item->setData(Qt::UserRole, cfg_dir_it.filePath()); + item->setText(cfg_dir_it.fileName()); + + qDebug() << "full path:" << cfg_dir_it.filePath(); + qDebug() << "file name:" << cfg_dir_it.fileName(); + + m_cfg_list->addItem(item); + } + + return; +} diff --git a/pool/shard007/C++/0095807_D3D10OutputDuplicator.cpp b/pool/shard007/C++/0095807_D3D10OutputDuplicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3553a2eb996e7e4cd3e31521b0a4a10929a19e18 --- /dev/null +++ b/pool/shard007/C++/0095807_D3D10OutputDuplicator.cpp @@ -0,0 +1,153 @@ +/******************************************************************************** + Copyright (C) 2012 Hugh Bailey + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. +********************************************************************************/ + + +#include "Main.h" + + +#define DXGI_ERROR_ACCESS_LOST _HRESULT_TYPEDEF_(0x887A0026L) +#define DXGI_ERROR_WAIT_TIMEOUT _HRESULT_TYPEDEF_(0x887A0027L) + + + +bool D3D10OutputDuplicator::Init(UINT output) +{ + HRESULT hRes; + + bool bSuccess = false; + + IDXGIDevice *device; + if(SUCCEEDED(hRes = GetD3D()->QueryInterface(__uuidof(IDXGIDevice), (void**)&device))) + { + IDXGIAdapter *adapter; + if(SUCCEEDED(hRes = device->GetAdapter(&adapter))) + { + IDXGIOutput *outputInterface; + if(SUCCEEDED(hRes = adapter->EnumOutputs(output, &outputInterface))) + { + IDXGIOutput1 *output1; + + if(SUCCEEDED(hRes = outputInterface->QueryInterface(__uuidof(IDXGIOutput1), (void**)&output1))) + { + if(SUCCEEDED(hRes = output1->DuplicateOutput(GetD3D(), &duplicator))) + bSuccess = true; + /*else + AppWarning(TEXT("D3D10OutputDuplicator::Init: output1->DuplicateOutput failed, result = %u"), (UINT)hRes);*/ + + output1->Release(); + } + /*else + AppWarning(TEXT("D3D10OutputDuplicator::Init: outputInterface->QueryInterface failed, result = %u"), (UINT)hRes);*/ + + outputInterface->Release(); + } + /*else + AppWarning(TEXT("D3D10OutputDuplicator::Init: adapter->EnumOutputs failed, result = %u"), (UINT)hRes);*/ + + adapter->Release(); + } + /*else + AppWarning(TEXT("D3D10OutputDuplicator::Init: device->GetAdapter failed, result = %u"), (UINT)hRes);*/ + + device->Release(); + } + /*else + AppWarning(TEXT("D3D10OutputDuplicator::Init: GetD3D()->QueryInterface failed, result = %u"), (UINT)hRes);*/ + + return bSuccess; +} + +D3D10OutputDuplicator::~D3D10OutputDuplicator() +{ + SafeRelease(duplicator); + delete copyTex; +} + +DuplicatorInfo D3D10OutputDuplicator::AquireNextFrame(UINT timeout) +{ + if(!duplicator) + { + AppWarning(TEXT("D3D10OutputDuplicator::AquireNextFrame: Well, apparently there's no duplicator.")); + return DuplicatorInfo_Error; + } + + //------------------------------------------ + + DXGI_OUTDUPL_FRAME_INFO frameInfo; + IDXGIResource *tempResource = NULL; + + HRESULT hRes = duplicator->AcquireNextFrame(timeout, &frameInfo, &tempResource); + if(hRes == DXGI_ERROR_ACCESS_LOST) + return DuplicatorInfo_Lost; + else if(hRes == DXGI_ERROR_WAIT_TIMEOUT) + return DuplicatorInfo_Timeout; + else if(FAILED(hRes)) + return DuplicatorInfo_Error; + + //------------------------------------------ + + ID3D10Texture2D *texVal; + if(FAILED(hRes = tempResource->QueryInterface(__uuidof(ID3D10Texture2D), (void**)&texVal))) + { + SafeRelease(tempResource); + AppWarning(TEXT("D3D10OutputDuplicator::AquireNextFrame: could not query interface, result = 0x%08lX"), hRes); + return DuplicatorInfo_Error; + } + + tempResource->Release(); + + //------------------------------------------ + + D3D10_TEXTURE2D_DESC texDesc; + texVal->GetDesc(&texDesc); + + if(!copyTex || copyTex->Width() != texDesc.Width || copyTex->Height() != texDesc.Height) + { + delete copyTex; + copyTex = CreateTexture(texDesc.Width, texDesc.Height, ConvertGIBackBufferFormat(texDesc.Format), NULL, FALSE, TRUE); + } + + //------------------------------------------ + + if(copyTex && texVal) + { + D3D10Texture *d3dCopyTex = (D3D10Texture*)copyTex; + GetD3D()->CopyResource(d3dCopyTex->texture, texVal); + } + + SafeRelease(texVal); + duplicator->ReleaseFrame(); + + return DuplicatorInfo_Acquired; +} + +Texture* D3D10OutputDuplicator::GetCopyTexture() +{ + return copyTex; +} + +Texture* D3D10OutputDuplicator::GetCursorTex(POINT* pos) +{ + if(pos) + mcpy(pos, &cursorPos, sizeof(POINT)); + + if(bCursorVis) + return cursorTex; + + return NULL; +} diff --git a/pool/shard007/C++/0095810_SectionMemoryManager.cpp b/pool/shard007/C++/0095810_SectionMemoryManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07c4986ed8449623aad2d54d88f621bfa86861fe --- /dev/null +++ b/pool/shard007/C++/0095810_SectionMemoryManager.cpp @@ -0,0 +1,265 @@ +//===- SectionMemoryManager.cpp - Memory manager for MCJIT/RtDyld *- C++ -*-==// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the section-based memory manager used by the MCJIT +// execution engine and RuntimeDyld +// +//===----------------------------------------------------------------------===// + +#include "llvm/ExecutionEngine/SectionMemoryManager.h" +#include "llvm/Config/config.h" +#include "llvm/Support/MathExtras.h" +#include "llvm/Support/Process.h" + +namespace llvm { + +uint8_t *SectionMemoryManager::allocateDataSection(uintptr_t Size, + unsigned Alignment, + unsigned SectionID, + StringRef SectionName, + bool IsReadOnly) { + if (IsReadOnly) + return allocateSection(SectionMemoryManager::AllocationPurpose::ROData, + Size, Alignment); + return allocateSection(SectionMemoryManager::AllocationPurpose::RWData, Size, + Alignment); +} + +uint8_t *SectionMemoryManager::allocateCodeSection(uintptr_t Size, + unsigned Alignment, + unsigned SectionID, + StringRef SectionName) { + return allocateSection(SectionMemoryManager::AllocationPurpose::Code, Size, + Alignment); +} + +uint8_t *SectionMemoryManager::allocateSection( + SectionMemoryManager::AllocationPurpose Purpose, uintptr_t Size, + unsigned Alignment) { + if (!Alignment) + Alignment = 16; + + assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two."); + + uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1) / Alignment + 1); + uintptr_t Addr = 0; + + MemoryGroup &MemGroup = [&]() -> MemoryGroup & { + switch (Purpose) { + case AllocationPurpose::Code: + return CodeMem; + case AllocationPurpose::ROData: + return RODataMem; + case AllocationPurpose::RWData: + return RWDataMem; + } + llvm_unreachable("Unknown SectionMemoryManager::AllocationPurpose"); + }(); + + // Look in the list of free memory regions and use a block there if one + // is available. + for (FreeMemBlock &FreeMB : MemGroup.FreeMem) { + if (FreeMB.Free.allocatedSize() >= RequiredSize) { + Addr = (uintptr_t)FreeMB.Free.base(); + uintptr_t EndOfBlock = Addr + FreeMB.Free.allocatedSize(); + // Align the address. + Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); + + if (FreeMB.PendingPrefixIndex == (unsigned)-1) { + // The part of the block we're giving out to the user is now pending + MemGroup.PendingMem.push_back(sys::MemoryBlock((void *)Addr, Size)); + + // Remember this pending block, such that future allocations can just + // modify it rather than creating a new one + FreeMB.PendingPrefixIndex = MemGroup.PendingMem.size() - 1; + } else { + sys::MemoryBlock &PendingMB = + MemGroup.PendingMem[FreeMB.PendingPrefixIndex]; + PendingMB = sys::MemoryBlock(PendingMB.base(), + Addr + Size - (uintptr_t)PendingMB.base()); + } + + // Remember how much free space is now left in this block + FreeMB.Free = + sys::MemoryBlock((void *)(Addr + Size), EndOfBlock - Addr - Size); + return (uint8_t *)Addr; + } + } + + // No pre-allocated free block was large enough. Allocate a new memory region. + // Note that all sections get allocated as read-write. The permissions will + // be updated later based on memory group. + // + // FIXME: It would be useful to define a default allocation size (or add + // it as a constructor parameter) to minimize the number of allocations. + // + // FIXME: Initialize the Near member for each memory group to avoid + // interleaving. + std::error_code ec; + sys::MemoryBlock MB = MMapper.allocateMappedMemory( + Purpose, RequiredSize, &MemGroup.Near, + sys::Memory::MF_READ | sys::Memory::MF_WRITE, ec); + if (ec) { + // FIXME: Add error propagation to the interface. + return nullptr; + } + + // Save this address as the basis for our next request + MemGroup.Near = MB; + + // Remember that we allocated this memory + MemGroup.AllocatedMem.push_back(MB); + Addr = (uintptr_t)MB.base(); + uintptr_t EndOfBlock = Addr + MB.allocatedSize(); + + // Align the address. + Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); + + // The part of the block we're giving out to the user is now pending + MemGroup.PendingMem.push_back(sys::MemoryBlock((void *)Addr, Size)); + + // The allocateMappedMemory may allocate much more memory than we need. In + // this case, we store the unused memory as a free memory block. + unsigned FreeSize = EndOfBlock - Addr - Size; + if (FreeSize > 16) { + FreeMemBlock FreeMB; + FreeMB.Free = sys::MemoryBlock((void *)(Addr + Size), FreeSize); + FreeMB.PendingPrefixIndex = (unsigned)-1; + MemGroup.FreeMem.push_back(FreeMB); + } + + // Return aligned address + return (uint8_t *)Addr; +} + +bool SectionMemoryManager::finalizeMemory(std::string *ErrMsg) { + // FIXME: Should in-progress permissions be reverted if an error occurs? + std::error_code ec; + + // Make code memory executable. + ec = applyMemoryGroupPermissions(CodeMem, + sys::Memory::MF_READ | sys::Memory::MF_EXEC); + if (ec) { + if (ErrMsg) { + *ErrMsg = ec.message(); + } + return true; + } + + // Make read-only data memory read-only. + ec = applyMemoryGroupPermissions(RODataMem, + sys::Memory::MF_READ | sys::Memory::MF_EXEC); + if (ec) { + if (ErrMsg) { + *ErrMsg = ec.message(); + } + return true; + } + + // Read-write data memory already has the correct permissions + + // Some platforms with separate data cache and instruction cache require + // explicit cache flush, otherwise JIT code manipulations (like resolved + // relocations) will get to the data cache but not to the instruction cache. + invalidateInstructionCache(); + + return false; +} + +static sys::MemoryBlock trimBlockToPageSize(sys::MemoryBlock M) { + static const size_t PageSize = sys::Process::getPageSizeEstimate(); + + size_t StartOverlap = + (PageSize - ((uintptr_t)M.base() % PageSize)) % PageSize; + + size_t TrimmedSize = M.allocatedSize(); + TrimmedSize -= StartOverlap; + TrimmedSize -= TrimmedSize % PageSize; + + sys::MemoryBlock Trimmed((void *)((uintptr_t)M.base() + StartOverlap), + TrimmedSize); + + assert(((uintptr_t)Trimmed.base() % PageSize) == 0); + assert((Trimmed.allocatedSize() % PageSize) == 0); + assert(M.base() <= Trimmed.base() && + Trimmed.allocatedSize() <= M.allocatedSize()); + + return Trimmed; +} + +std::error_code +SectionMemoryManager::applyMemoryGroupPermissions(MemoryGroup &MemGroup, + unsigned Permissions) { + for (sys::MemoryBlock &MB : MemGroup.PendingMem) + if (std::error_code EC = MMapper.protectMappedMemory(MB, Permissions)) + return EC; + + MemGroup.PendingMem.clear(); + + // Now go through free blocks and trim any of them that don't span the entire + // page because one of the pending blocks may have overlapped it. + for (FreeMemBlock &FreeMB : MemGroup.FreeMem) { + FreeMB.Free = trimBlockToPageSize(FreeMB.Free); + // We cleared the PendingMem list, so all these pointers are now invalid + FreeMB.PendingPrefixIndex = (unsigned)-1; + } + + // Remove all blocks which are now empty + MemGroup.FreeMem.erase(remove_if(MemGroup.FreeMem, + [](FreeMemBlock &FreeMB) { + return FreeMB.Free.allocatedSize() == 0; + }), + MemGroup.FreeMem.end()); + + return std::error_code(); +} + +void SectionMemoryManager::invalidateInstructionCache() { + for (sys::MemoryBlock &Block : CodeMem.PendingMem) + sys::Memory::InvalidateInstructionCache(Block.base(), + Block.allocatedSize()); +} + +SectionMemoryManager::~SectionMemoryManager() { + for (MemoryGroup *Group : {&CodeMem, &RWDataMem, &RODataMem}) { + for (sys::MemoryBlock &Block : Group->AllocatedMem) + MMapper.releaseMappedMemory(Block); + } +} + +SectionMemoryManager::MemoryMapper::~MemoryMapper() {} + +void SectionMemoryManager::anchor() {} + +namespace { +// Trivial implementation of SectionMemoryManager::MemoryMapper that just calls +// into sys::Memory. +class DefaultMMapper final : public SectionMemoryManager::MemoryMapper { +public: + sys::MemoryBlock + allocateMappedMemory(SectionMemoryManager::AllocationPurpose Purpose, + size_t NumBytes, const sys::MemoryBlock *const NearBlock, + unsigned Flags, std::error_code &EC) override { + return sys::Memory::allocateMappedMemory(NumBytes, NearBlock, Flags, EC); + } + + std::error_code protectMappedMemory(const sys::MemoryBlock &Block, + unsigned Flags) override { + return sys::Memory::protectMappedMemory(Block, Flags); + } + + std::error_code releaseMappedMemory(sys::MemoryBlock &M) override { + return sys::Memory::releaseMappedMemory(M); + } +}; +} // namespace + +SectionMemoryManager::SectionMemoryManager(MemoryMapper *MM) + : DefMMapper(MM ? nullptr : new DefaultMMapper), MMapper(MM ? *MM : *DefMMapper) {} + +} // namespace llvm diff --git a/pool/shard007/C++/0095812_TP_Reactor_Logging_Server.cpp b/pool/shard007/C++/0095812_TP_Reactor_Logging_Server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c23238a56d4317d4ce842ba8aa7ce6b317e03255 --- /dev/null +++ b/pool/shard007/C++/0095812_TP_Reactor_Logging_Server.cpp @@ -0,0 +1,114 @@ +/* +** Copyright 2002 Addison Wesley. All Rights Reserved. +*/ + +// FUZZ: disable check_for_streams_include +#include "ace/streams.h" + +#include "ace/Auto_Ptr.h" +#include "ace/Reactor.h" +#include "ace/TP_Reactor.h" +#include "ace/Thread_Manager.h" + +#if defined (ACE_WIN32) && (!defined (ACE_HAS_STANDARD_CPP_LIBRARY) || \ + (ACE_HAS_STANDARD_CPP_LIBRARY == 0) || \ + defined (ACE_USES_OLD_IOSTREAMS)) +# include +#else +# include +#endif + +#include "Reactor_Logging_Server_T.h" +#include "Logging_Acceptor_Ex.h" + +typedef Reactor_Logging_Server + Server_Logging_Daemon; + + +class Quit_Handler : public ACE_Event_Handler { +public: + Quit_Handler (ACE_Reactor *r) : ACE_Event_Handler (r) {} + + virtual int handle_exception (ACE_HANDLE) { + reactor ()->end_reactor_event_loop (); + return -1; // Trigger call to handle_close() method. + } + + virtual int handle_close (ACE_HANDLE, ACE_Reactor_Mask) + { delete this; return 0; } + +protected: + + // Protected destructor ensures dynamic allocation. + virtual ~Quit_Handler () {} +}; + + +static ACE_THR_FUNC_RETURN event_loop (void *arg) { + ACE_Reactor *reactor = static_cast (arg); + + reactor->owner (ACE_OS::thr_self ()); + reactor->run_reactor_event_loop (); + return 0; +} + + +static ACE_THR_FUNC_RETURN controller (void *arg) { + ACE_Reactor *reactor = static_cast (arg); + + Quit_Handler *quit_handler = 0; + ACE_NEW_RETURN (quit_handler, Quit_Handler (reactor), 0); + +#if defined (ACE_WIN32) && (!defined (ACE_HAS_STANDARD_CPP_LIBRARY) || \ + (ACE_HAS_STANDARD_CPP_LIBRARY == 0) || \ + defined (ACE_USES_OLD_IOSTREAMS)) + for (;;) { + char user_input[80]; + ACE_OS::fgets (user_input, sizeof (user_input), stdin); + if (ACE_OS::strcmp (user_input, "quit") == 0) { + reactor->notify (quit_handler); + break; + } + } +#else + for (;;) { +#if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB == 0) + string user_input; + getline (cin, user_input, '\n'); +#else + std::string user_input; + std::getline (cin, user_input, '\n'); +#endif + if (user_input == "quit") { + reactor->notify (quit_handler); + break; + } + } +#endif + + return 0; +} + + +int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) +{ + const size_t N_THREADS = 4; + ACE_TP_Reactor tp_reactor; + ACE_Reactor reactor (&tp_reactor); + auto_ptr delete_instance + (ACE_Reactor::instance (&reactor)); + + Server_Logging_Daemon *server; + // Ignore argv[0]... + --argc; ++argv; + ACE_NEW_RETURN (server, + Server_Logging_Daemon (argc, argv, + ACE_Reactor::instance ()), + 1); + ACE_Thread_Manager::instance ()->spawn_n + (N_THREADS, event_loop, ACE_Reactor::instance ()); + ACE_Thread_Manager::instance ()->spawn + (controller, ACE_Reactor::instance ()); + return ACE_Thread_Manager::instance ()->wait (); +} + diff --git a/pool/shard007/C++/0095817_chain.cpp b/pool/shard007/C++/0095817_chain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc03255f8d349746f572ba514d80de3d64cafc01 --- /dev/null +++ b/pool/shard007/C++/0095817_chain.cpp @@ -0,0 +1,152 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2016 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 "chain.h" +#include "consensus/params.h" + +/** + * CChain implementation + */ +void CChain::SetTip(CBlockIndex *pindex) { + if (pindex == NULL) { + vChain.clear(); + return; + } + vChain.resize(pindex->nHeight + 1); + while (pindex && vChain[pindex->nHeight] != pindex) { + vChain[pindex->nHeight] = pindex; + pindex = pindex->pprev; + } +} + +CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { + int nStep = 1; + std::vector vHave; + vHave.reserve(32); + + if (!pindex) + pindex = Tip(); + while (pindex) { + vHave.push_back(pindex->GetBlockHash()); + // Stop when we have added the genesis block. + if (pindex->nHeight == 0) + break; + // Exponentially larger steps back, plus the genesis block. + int nHeight = std::max(pindex->nHeight - nStep, 0); + if (Contains(pindex)) { + // Use O(1) CChain index if possible. + pindex = (*this)[nHeight]; + } else { + // Otherwise, use O(log n) skiplist. + pindex = pindex->GetAncestor(nHeight); + } + if (vHave.size() > 10) + nStep *= 2; + } + + return CBlockLocator(vHave); +} + +const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { + if (pindex == NULL) { + return NULL; + } + if (pindex->nHeight > Height()) + pindex = pindex->GetAncestor(Height()); + while (pindex && !Contains(pindex)) + pindex = pindex->pprev; + return pindex; +} + +CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const +{ + std::vector::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, + [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); + return (lower == vChain.end() ? NULL : *lower); +} + +/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ +int static inline InvertLowestOne(int n) { return n & (n - 1); } + +/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ +int static inline GetSkipHeight(int height) { + if (height < 2) + return 0; + + // Determine which height to jump back to. Any number strictly lower than height is acceptable, + // but the following expression seems to perform well in simulations (max 110 steps to go back + // up to 2**18 blocks). + return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); +} + +CBlockIndex* CBlockIndex::GetAncestor(int height) +{ + if (height > nHeight || height < 0) + return NULL; + + CBlockIndex* pindexWalk = this; + int heightWalk = nHeight; + while (heightWalk > height) { + int heightSkip = GetSkipHeight(heightWalk); + int heightSkipPrev = GetSkipHeight(heightWalk - 1); + if (pindexWalk->pskip != NULL && + (heightSkip == height || + (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && + heightSkipPrev >= height)))) { + // Only follow pskip if pprev->pskip isn't better than pskip->pprev. + pindexWalk = pindexWalk->pskip; + heightWalk = heightSkip; + } else { + assert(pindexWalk->pprev); + pindexWalk = pindexWalk->pprev; + heightWalk--; + } + } + return pindexWalk; +} + +const CBlockIndex* CBlockIndex::GetAncestor(int height) const +{ + return const_cast(this)->GetAncestor(height); +} + +void CBlockIndex::BuildSkip() +{ + if (pprev) + pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); +} + +arith_uint256 GetBlockProof(const CBlockIndex& block) +{ + arith_uint256 bnTarget; + bool fNegative; + bool fOverflow; + bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); + if (fNegative || fOverflow || bnTarget == 0) + return 0; + // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 + // as it's too large for a arith_uint256. However, as 2**256 is at least as large + // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, + // or ~bnTarget / (nTarget+1) + 1. + return (~bnTarget / (bnTarget + 1)) + 1; +} + +int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) +{ + arith_uint256 r; + int sign = 1; + if (to.nChainWork > from.nChainWork) { + r = to.nChainWork - from.nChainWork; + } else { + r = from.nChainWork - to.nChainWork; + sign = -1; + } + r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); + if (r.bits() > 63) { + return sign * std::numeric_limits::max(); + } + return sign * r.GetLow64(); +} + diff --git a/pool/shard007/C++/0095827_ossimPlanetGeocoder.cpp b/pool/shard007/C++/0095827_ossimPlanetGeocoder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f11c7030bb02131a2e82b74fddae78dfc7ab830d --- /dev/null +++ b/pool/shard007/C++/0095827_ossimPlanetGeocoder.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +static std::istream& geocoderskipws(std::istream& in) +{ + int c = in.peek(); + while((c == ' ') || + (c == '\t') || + (c == '\n')|| + (c == '\r')) + { + in.ignore(1); + c = in.peek(); + } + + return in; +} +ossimPlanetGoecoder::ossimPlanetGeocoderLocation::ossimPlanetGeocoderLocation() +{ + theMetaInformation = new ossimXmlNode; + theMetaInformation->setTag("kml"); + theNameNode = new ossimXmlNode; + theNameNode->setTag("name"); + theMetaInformation->addChildNode(theNameNode.get()); + thePlacemarkNode = new ossimXmlNode; + thePlacemarkNode->setTag("Placemark"); + theMetaInformation->addChildNode(thePlacemarkNode.get()); + theAddressNode = new ossimXmlNode; + theAddressNode->setTag("Address"); + thePointNode = new ossimXmlNode; + theCoordinatesNode = new ossimXmlNode; + theCoordinatesNode->setText("0.0, 0.0, 0.0"); + thePointNode->addChildNode(theCoordinatesNode.get()); + + theMetaInformation->addChildNode(theNameNode.get()); + theMetaInformation->addChildNode(thePlacemarkNode.get()); + theMetaInformation->addChildNode(theAddressNode.get()); + theMetaInformation->addChildNode(thePointNode.get()); +} + +void ossimPlanetGoecoder::ossimPlanetGeocoderLocation::setLocation(const ossimGpt& location) +{ + theCoordinatesNode->setText(ossimString::toString(location.latd())+ "," + + ossimString::toString(location.lond())+ ", 0.0"); + +} + +ossimGpt ossimPlanetGoecoder::ossimPlanetGeocoderLocation::getLocation()const +{ + ossimGpt result; + std::istringstream in(theCoordinatesNode->getText()); + + char c; + double lat, lon; + + in >> lat >> geocoderskipws >> c >> geocoderskipws >>lon; + result.latd(lat); + result.lond(lon); + + return result; +} + +void ossimPlanetGoecoder::ossimPlanetGeocoderLocation::setName(const ossimString& name) +{ + theNameNode->setText(name); +} + +ossimString ossimPlanetGoecoder::ossimPlanetGeocoderLocation::getName()const +{ + return theNameNode->getText(); +} + +ossimString ossimPlanetGoecoder::ossimPlanetGeocoderLocation::getAddress()const +{ + return theAddressNode->getText(); +} + +void ossimPlanetGoecoder::ossimPlanetGeocoderLocation::setAddress(const ossimString& address) +{ + theAddressNode->setText(address); +} diff --git a/pool/shard007/C++/0095830_fonts.cpp b/pool/shard007/C++/0095830_fonts.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1620f617893486e40f311abe20dd232614bc987d --- /dev/null +++ b/pool/shard007/C++/0095830_fonts.cpp @@ -0,0 +1,19 @@ +#include "fonts.h" + +#include "settings.h" +#include "interfaces.h" + +HFont esp_font = 0; + +static HFont CreateFont( const char* fontName, int size, int flag ) { + HFont newFont = surface->CreateFont(); + surface->SetFontGlyphSet( newFont, fontName, size, 0, 0, 0, flag ); + return newFont; +} + +void Fonts::SetupFonts() +{ + esp_font = CreateFont(Settings::UI::Fonts::ESP::family, + Settings::UI::Fonts::ESP::size, + Settings::UI::Fonts::ESP::flags); +} diff --git a/pool/shard007/C++/0095833_pickle_fuzzer.cc b/pool/shard007/C++/0095833_pickle_fuzzer.cc new file mode 100644 index 0000000000000000000000000000000000000000..480c4b8a1d1e1dad02114827b546911b29a71f0d --- /dev/null +++ b/pool/shard007/C++/0095833_pickle_fuzzer.cc @@ -0,0 +1,125 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "base/ignore_result.h" +#include "base/pickle.h" + +namespace { +constexpr int kIterations = 16; +constexpr int kReadControlBytes = 32; +constexpr int kReadDataTypes = 17; +constexpr int kMaxReadLength = 1024; +constexpr int kMaxSkipBytes = 1024; +} // namespace + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (size < kReadControlBytes) { + return 0; + } + // Use the first kReadControlBytes bytes of the fuzzer input to control how + // the pickled data is read. + FuzzedDataProvider data_provider(data, kReadControlBytes); + data += kReadControlBytes; + size -= kReadControlBytes; + + base::Pickle pickle(reinterpret_cast(data), size); + base::PickleIterator iter(pickle); + for (int i = 0; i < kIterations; i++) { + uint8_t read_type = data_provider.ConsumeIntegral(); + switch (read_type % kReadDataTypes) { + case 0: { + bool result = 0; + ignore_result(iter.ReadBool(&result)); + break; + } + case 1: { + int result = 0; + ignore_result(iter.ReadInt(&result)); + break; + } + case 2: { + long result = 0; + ignore_result(iter.ReadLong(&result)); + break; + } + case 3: { + uint16_t result = 0; + ignore_result(iter.ReadUInt16(&result)); + break; + } + case 4: { + uint32_t result = 0; + ignore_result(iter.ReadUInt32(&result)); + break; + } + case 5: { + int64_t result = 0; + ignore_result(iter.ReadInt64(&result)); + break; + } + case 6: { + uint64_t result = 0; + ignore_result(iter.ReadUInt64(&result)); + break; + } + case 7: { + float result = 0; + ignore_result(iter.ReadFloat(&result)); + break; + } + case 8: { + double result = 0; + ignore_result(iter.ReadDouble(&result)); + break; + } + case 9: { + std::string result; + ignore_result(iter.ReadString(&result)); + break; + } + case 10: { + base::StringPiece result; + ignore_result(iter.ReadStringPiece(&result)); + break; + } + case 11: { + std::u16string result; + ignore_result(iter.ReadString16(&result)); + break; + } + case 12: { + base::StringPiece16 result; + ignore_result(iter.ReadStringPiece16(&result)); + break; + } + case 13: { + const char* data_result = nullptr; + int length_result = 0; + ignore_result(iter.ReadData(&data_result, &length_result)); + break; + } + case 14: { + const char* data_result = nullptr; + int read_length = + data_provider.ConsumeIntegralInRange(0, kMaxReadLength); + ignore_result(iter.ReadBytes(&data_result, read_length)); + break; + } + case 15: { + int result = 0; + ignore_result(iter.ReadLength(&result)); + break; + } + case 16: { + ignore_result(iter.SkipBytes( + data_provider.ConsumeIntegralInRange(0, kMaxSkipBytes))); + break; + } + } + } + + return 0; +} diff --git a/pool/shard007/C++/0095834_Cdirectshowcontrol.cpp b/pool/shard007/C++/0095834_Cdirectshowcontrol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a0f8f729f690f175212bcb790c707bee3e1650c --- /dev/null +++ b/pool/shard007/C++/0095834_Cdirectshowcontrol.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2002-2006 Milan Cutka + * + * 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 "stdafx.h" +#include "Cdirectshowcontrol.h" +#include "TvideoCodec.h" +#include "TaudioCodec.h" +#include "ffdshow_mediaguids.h" +#include "Tconfig.h" +#include "TffdshowPageDec.h" +#include "Tinfo.h" +#include "Ttranslate.h" +#include "TcompatibilityList.h" +#include "TglobalSettings.h" + +//=================================== TdirectshowControlPageDec ======================================= +void TdirectshowControlPageDec::init(void) +{ + static const int insts[] = {IDC_LBL_MULTIPLE_INSTANCES, IDC_CBX_MULTIPLE_INSTANCES, 0}; + enable((filterMode & IDFF_FILTERMODE_VFW) == 0, insts); + + merits.clear(); + static const int idmerits[] = {IDC_LBL_MERIT, IDC_TBR_MERIT, 0}; + isMerit = (filterMode & (IDFF_FILTERMODE_VFW | IDFF_FILTERMODE_ENC | IDFF_FILTERMODE_VIDEORAW | IDFF_FILTERMODE_AUDIORAW)) == 0; + if (isMerit) { + // Add 1 for DXVA filter + int offset = (filterMode & (IDFF_FILTERMODE_VIDEODXVA)) == 0 ? 0 : 1; + //merits.push_back(std::make_pair(MERIT_SW_COMPRESSOR /*0x100000*/,_("SW compressor"))); + //merits.push_back(std::make_pair(MERIT_HW_COMPRESSOR /*0x100050*/,_("HW compressor"))); + merits.push_back(std::make_pair(MERIT_DO_NOT_USE + offset /*0x200000*/, (const char_t*)_l("do not use"))); + merits.push_back(std::make_pair(MERIT_UNLIKELY + offset /*0x400000*/, (const char_t*)_l("unlikely"))); + merits.push_back(std::make_pair(MERIT_NORMAL + offset /*0x600000*/, (const char_t*)_l("normal"))); + merits.push_back(std::make_pair(MERIT_PREFERRED + offset /*0x800000*/, (const char_t*)_l("preferred"))); + merits.push_back(std::make_pair(cfgGet(IDFF_defaultMerit) + offset , (const char_t*)_l("ffdshow default"))); + merits.push_back(std::make_pair(0xffffff00 + offset , (const char_t*)_l("very high"))); + std::sort(merits.begin(), merits.end(), sortMerits); + tbrSetRange(IDC_TBR_MERIT, 0, (int)merits.size() - 1, 1); + enable(1, idmerits); + } else { + enable(0, idmerits); + } + + edLimitText(IDC_ED_BLACKLIST, MAX_COMPATIBILITYLIST_LENGTH); + edLimitText(IDC_ED_COMPATIBILITYLIST, MAX_COMPATIBILITYLIST_LENGTH); + addHint(IDC_ED_BLACKLIST, _l("List of applications for which ffdshow should not load, separated by semicolons")); + addHint(IDC_ED_COMPATIBILITYLIST, _l("List of applications which are compatible with ffdshow, separated by semicolons.")); + + blacklist2dlg(); +} + +void TdirectshowControlPageDec::cfg2dlg(void) +{ + setCheck(IDC_CHB_ADDTOROT, cfgGet(IDFF_addToROT)); + cbxSetDataCurSel(IDC_CBX_MULTIPLE_INSTANCES, cfgGet(IDFF_multipleInstances)); + if (isMerit) { + merit2dlg(); + } + blacklist2dlg(); +} + +bool TdirectshowControlPageDec::sortMerits(const Tmerit &m1, const Tmerit &m2) +{ + return m1.first < m2.first; +} + +void TdirectshowControlPageDec::merit2dlg(void) +{ + DWORD merit = 0; + deci->getMerit(&merit); + meritset = true; + for (int ii = 0; ii < 2; ii++, merit = cfgGet(IDFF_defaultMerit)) { + int i = 0; + for (Tmerits::const_iterator m = merits.begin(); m != merits.end(); m++, i++) + if (m->first == merit) { + tbrSet(IDC_TBR_MERIT, i); + setText(IDC_LBL_MERIT, _l("%s %s"), _(IDC_LBL_MERIT), _(IDC_LBL_MERIT, m->second)); + return; + } + } +} + +void TdirectshowControlPageDec::blacklist2dlg(void) +{ + int is = cfgGet(IDFF_isBlacklist); + setCheck(IDC_CHB_BLACKLIST, is); + const char_t *blacklist0 = cfgGetStr(IDFF_blacklist); + ffstring blacklistResult; + convertDelimit(blacklist0, _l(";"), blacklistResult, _l(";")); + SetDlgItemText(m_hwnd, IDC_ED_BLACKLIST, blacklistResult.c_str()); + enable(is, IDC_ED_BLACKLIST); + enable(is, IDC_BT_BLACKLIST); + + is = cfgGet(IDFF_isWhitelist); + setCheck(IDC_CHB_COMPATIBILITYLIST, is); + const char_t *complist0 = cfgGetStr(IDFF_whitelist); + ffstring complistResult; + convertDelimit(complist0, _l(";"), complistResult, _l(";")); + SetDlgItemText(m_hwnd, IDC_ED_COMPATIBILITYLIST, complistResult.c_str()); + setCheck(IDC_CHB_IS_COMPMGR, cfgGet(IDFF_isCompMgr)); + enable(is, IDC_ED_COMPATIBILITYLIST); + enable(is, IDC_BT_COMPATIBILITYLIST); + enable(is, IDC_CHB_IS_COMPMGR); +} + +void TdirectshowControlPageDec::applySettings(void) +{ + if (isMerit && meritset) { + deci->setMerit(merits[tbrGet(IDC_TBR_MERIT)].first); + } +} + +bool TdirectshowControlPageDec::strCaseCmp(const ffstring &s1, const ffstring &s2) +{ + return DwStrcasecmp(s1, s2) == -1; +} + +INT_PTR TdirectshowControlPageDec::msgProc(UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch (uMsg) { + case WM_HSCROLL: + switch (getId(HWND(lParam))) { + case IDC_TBR_MERIT: + setText(IDC_LBL_MERIT, _l("%s %s"), _(IDC_LBL_MERIT), _(IDC_LBL_MERIT, merits[tbrGet(IDC_TBR_MERIT)].second)); + parent->setChange(); + return TRUE; + } + break; + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDC_ED_BLACKLIST: + if (HIWORD(wParam) == EN_CHANGE && !isSetWindowText) { + comp_dlg2cfg(IDC_ED_BLACKLIST, IDFF_blacklist, _l(";")); + } + return TRUE; + case IDC_ED_COMPATIBILITYLIST: + if (HIWORD(wParam) == EN_CHANGE && !isSetWindowText) { + comp_dlg2cfg(IDC_ED_COMPATIBILITYLIST, IDFF_whitelist, _l(";")); + } + return TRUE; + } + break; + } + return TconfPageDec::msgProc(uMsg, wParam, lParam); +} +void TdirectshowControlPageDec::comp_dlg2cfg(int IDC_ED_target, int IDFF_target, const char_t *delimitResult) +{ + char_t complist0[MAX_COMPATIBILITYLIST_LENGTH]; + GetDlgItemText(m_hwnd, IDC_ED_target, complist0, MAX_COMPATIBILITYLIST_LENGTH); + ffstring complistResult; + convertDelimit(complist0, _l(";"), complistResult, delimitResult); + cfgSet(IDFF_target, complistResult.c_str()); +} + +void TdirectshowControlPageDec::convertDelimit(const char_t* instr, const char_t *inDelimit, ffstring &outstr, const char_t *outDelimit, const char_t *newFileName) +{ + strings complist; + strtok(instr, inDelimit, complist); + + std::list complistList; + complistList.insert(complistList.begin(), complist.begin(), complist.end()); + if (newFileName) { + complistList.push_back(newFileName); + } + complistList.sort(strCaseCmp); + + for (std::list::iterator i = complistList.begin(); i != complistList.end(); i++) { + outstr += *i + outDelimit; + } +} + +void TdirectshowControlPageDec::translate(void) +{ + TconfPageDec::translate(); + + int ii = cbxGetCurSel(IDC_CBX_MULTIPLE_INSTANCES); + cbxClear(IDC_CBX_MULTIPLE_INSTANCES); + for (int i = 0; multipleInstances[i].name; i++) { + cbxAdd(IDC_CBX_MULTIPLE_INSTANCES, _(IDC_CBX_MULTIPLE_INSTANCES, multipleInstances[i].name), multipleInstances[i].id); + } + cbxSetCurSel(IDC_CBX_MULTIPLE_INSTANCES, ii); +} + +void TdirectshowControlPageDec::onChbIsCompMgr(void) +{ + cfgSet(IDFF_isCompMgrChanged, 1); +} + +TdirectshowControlPageDec::TdirectshowControlPageDec(TffdshowPageDec *Iparent): TconfPageDec(Iparent, NULL, 0) +{ + helpURL = _l("http://ffdshow-tryout.sourceforge.net/wiki/video:directshow_control"); + dialogId = IDD_DIRECTSHOWCONTROL; + meritset = false; + static const TbindCheckbox chb[] = { + IDC_CHB_ADDTOROT, IDFF_addToROT, NULL, + IDC_CHB_BLACKLIST, IDFF_isBlacklist, &TdirectshowControlPageDec::blacklist2dlg, + IDC_CHB_COMPATIBILITYLIST, IDFF_isWhitelist, &TdirectshowControlPageDec::blacklist2dlg, + IDC_CHB_IS_COMPMGR, IDFF_isCompMgr, &TdirectshowControlPageDec::onChbIsCompMgr, + 0, NULL, NULL + }; + bindCheckboxes(chb); + static const TbindCombobox cbx[] = { + IDC_CBX_MULTIPLE_INSTANCES, IDFF_multipleInstances, BINDCBX_DATA, NULL, + 0 + }; + bindComboboxes(cbx); + static const TbindButton bt[] = { + IDC_BT_COMPATIBILITYLIST, &TdirectshowControlPageDec::onEditCompatibilitylist, + IDC_BT_BLACKLIST, &TdirectshowControlPageDec::onEditBlacklist, + 0, NULL + }; + bindButtons(bt); +} +TdirectshowControlPageDec::~TdirectshowControlPageDec() +{ +} +void TdirectshowControlPageDec::onEditCompatibilitylist(void) +{ + onEditCompI(IDFF_whitelist); +} +void TdirectshowControlPageDec::onEditBlacklist(void) +{ + onEditCompI(IDFF_blacklist); +} +void TdirectshowControlPageDec::onEditCompI(int IDFF_target) +{ + TcompatibilityList *dlg = new TcompatibilityList(deci, m_hwnd, 10, 10, IDFF_target); + if (dlg->show()) { + blacklist2dlg(); + parent->setChange(); + } + delete dlg; +} diff --git a/pool/shard007/C++/0095836_JobSummary.cpp b/pool/shard007/C++/0095836_JobSummary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee9f21b8a77faa2bd0dce0d0ccacf98e1e571a1e --- /dev/null +++ b/pool/shard007/C++/0095836_JobSummary.cpp @@ -0,0 +1,188 @@ +/* +* 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 + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace Amplify +{ +namespace Model +{ + +JobSummary::JobSummary() : + m_jobArnHasBeenSet(false), + m_jobIdHasBeenSet(false), + m_commitIdHasBeenSet(false), + m_commitMessageHasBeenSet(false), + m_commitTimeHasBeenSet(false), + m_startTimeHasBeenSet(false), + m_status(JobStatus::NOT_SET), + m_statusHasBeenSet(false), + m_endTimeHasBeenSet(false), + m_jobType(JobType::NOT_SET), + m_jobTypeHasBeenSet(false) +{ +} + +JobSummary::JobSummary(JsonView jsonValue) : + m_jobArnHasBeenSet(false), + m_jobIdHasBeenSet(false), + m_commitIdHasBeenSet(false), + m_commitMessageHasBeenSet(false), + m_commitTimeHasBeenSet(false), + m_startTimeHasBeenSet(false), + m_status(JobStatus::NOT_SET), + m_statusHasBeenSet(false), + m_endTimeHasBeenSet(false), + m_jobType(JobType::NOT_SET), + m_jobTypeHasBeenSet(false) +{ + *this = jsonValue; +} + +JobSummary& JobSummary::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("jobArn")) + { + m_jobArn = jsonValue.GetString("jobArn"); + + m_jobArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("jobId")) + { + m_jobId = jsonValue.GetString("jobId"); + + m_jobIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("commitId")) + { + m_commitId = jsonValue.GetString("commitId"); + + m_commitIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("commitMessage")) + { + m_commitMessage = jsonValue.GetString("commitMessage"); + + m_commitMessageHasBeenSet = true; + } + + if(jsonValue.ValueExists("commitTime")) + { + m_commitTime = jsonValue.GetDouble("commitTime"); + + m_commitTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("startTime")) + { + m_startTime = jsonValue.GetDouble("startTime"); + + m_startTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("status")) + { + m_status = JobStatusMapper::GetJobStatusForName(jsonValue.GetString("status")); + + m_statusHasBeenSet = true; + } + + if(jsonValue.ValueExists("endTime")) + { + m_endTime = jsonValue.GetDouble("endTime"); + + m_endTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("jobType")) + { + m_jobType = JobTypeMapper::GetJobTypeForName(jsonValue.GetString("jobType")); + + m_jobTypeHasBeenSet = true; + } + + return *this; +} + +JsonValue JobSummary::Jsonize() const +{ + JsonValue payload; + + if(m_jobArnHasBeenSet) + { + payload.WithString("jobArn", m_jobArn); + + } + + if(m_jobIdHasBeenSet) + { + payload.WithString("jobId", m_jobId); + + } + + if(m_commitIdHasBeenSet) + { + payload.WithString("commitId", m_commitId); + + } + + if(m_commitMessageHasBeenSet) + { + payload.WithString("commitMessage", m_commitMessage); + + } + + if(m_commitTimeHasBeenSet) + { + payload.WithDouble("commitTime", m_commitTime.SecondsWithMSPrecision()); + } + + if(m_startTimeHasBeenSet) + { + payload.WithDouble("startTime", m_startTime.SecondsWithMSPrecision()); + } + + if(m_statusHasBeenSet) + { + payload.WithString("status", JobStatusMapper::GetNameForJobStatus(m_status)); + } + + if(m_endTimeHasBeenSet) + { + payload.WithDouble("endTime", m_endTime.SecondsWithMSPrecision()); + } + + if(m_jobTypeHasBeenSet) + { + payload.WithString("jobType", JobTypeMapper::GetNameForJobType(m_jobType)); + } + + return payload; +} + +} // namespace Model +} // namespace Amplify +} // namespace Aws diff --git a/pool/shard007/C++/0095838_main.cpp b/pool/shard007/C++/0095838_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2dd34358edd27c201724a04018c5901f2c81cdb --- /dev/null +++ b/pool/shard007/C++/0095838_main.cpp @@ -0,0 +1,75 @@ +#include +#include "lexer.h" +#include "parser.h" +#include "FASMgen.h" +#include +#include + + +int main(int argc, char** argv) { + Error errHandler; + errHandler.currLine = 0; + Lexer lexer(&errHandler); + Parser parser(&lexer); + CodeGenerator *codeGen = new FASMGenerator(); + codeGen->getFunctionRetVal = + [&parser](const std::string &s) -> std::string { return parser.functionDefinitions[s]->GetType(); }; + + std::string filename; + std::vector compileArgs; + if (argc <= 1) + return 0; + std::string outputName = ""; + for (unsigned int i = 2; i < argc; i++) { + std::string targ = argv[i]; + if (targ.find("-o") != 0) + compileArgs.push_back(targ); + else + outputName = targ.substr(2, targ.size()); + } + filename = argv[1]; + //std::cout << "compile> "; // for debug purposes + //std::cin >> filename; + if (outputName == "") + outputName = filename; + + std::ifstream filehandle; + filename += ".cas"; + filehandle.open(filename); + std::string contents((std::istreambuf_iterator(filehandle)), std::istreambuf_iterator()); + unsigned int lines = std::count(contents.begin(), contents.end(), '\n'); + errHandler.files.push_back(new Error::file{ filename, lines+1 }); + filehandle.close(); + + lexer.SetCode(&contents); + lexer.NextToken(); + std::string imported = parser.GetImportedCode(); + imported += contents; + contents = imported; + lexer.FirstToken(); + + std::vector gens; + unsigned int errors; + std::cout << "Parsing.." << std::endl; + while (lexer.token != Lexer::TOK_EOF) { + errors = errHandler.errCounter; + CodeGen *gen = parser.Parse(); + if (!gen || errHandler.errCounter > errors) continue; + gens.push_back(gen); + } + std::cout << "Generating code.." << std::endl; + for (unsigned int i = 0; i < gens.size(); i++) + gens[i]->GenerateCode(codeGen, &errHandler); + + if (errHandler.errCounter <= 0) + codeGen->Compile(outputName,compileArgs); + else + std::cout << "Compile failed with " << errHandler.errCounter << " error(s)" << std::endl; + for (unsigned int i = 0; i < gens.size(); i++) + delete gens[i]; + delete codeGen; + + std::cout << "Done." << std::endl; + system("pause"); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0095839_eventloopthreadpool_test.cc b/pool/shard007/C++/0095839_eventloopthreadpool_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..2aa1cb66cd40b3e590ea36ebf64cfa2b509e80e8 --- /dev/null +++ b/pool/shard007/C++/0095839_eventloopthreadpool_test.cc @@ -0,0 +1,63 @@ +#include "EventLoopThreadPool.h" +#include "EventLoop.h" +#include "thread.h" +#include "logging.h" +#include + +using namespace calm; +using namespace calm::net; + +void print_id(EventLoop* p = NULL) +{ + LOG_INFO << "print_id func: threadId = " << getCurrentThreadId() << " loop = " << p; +} +void init(EventLoop* p) +{ + LOG_INFO << "init func: threadId = " << getCurrentThreadId() << " loop = " << p; +} + +int main_eventloopthreadpool() +{ + print_id(); + EventLoop loop; + + { + LOG_INFO << "single thread : " << &loop; + EventLoopThreadPool model(&loop); + model.setThreadNum(0); + model.start(init); + assert(model.getNextLoop() == &loop); + assert(model.getNextLoop() == &loop); + assert(model.getNextLoop() == &loop); + std::this_thread::sleep_for(std::chrono::seconds(5)); + } + + { + LOG_INFO<<"Another thread"; + EventLoopThreadPool model(&loop); + model.setThreadNum(1); + model.start(init); + EventLoop* nextLoop = model.getNextLoop(); + nextLoop->queueInLoop(std::bind(print_id, nextLoop)); + assert(nextLoop != &loop); + assert(nextLoop == model.getNextLoop()); + assert(nextLoop == model.getNextLoop()); + std::this_thread::sleep_for(std::chrono::seconds(3)); + } + + { + LOG_INFO << "Three threads"; + EventLoopThreadPool model(&loop); + model.setThreadNum(3); + model.start(init); + EventLoop* nextLoop = model.getNextLoop(); + nextLoop->runInLoop(std::bind(print_id, nextLoop)); + assert(nextLoop != &loop); + assert(nextLoop != model.getNextLoop()); + assert(nextLoop != model.getNextLoop()); + assert(nextLoop == model.getNextLoop()); + } + + //loop.loop(); + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0095840_testcrtfverticalcolumn.cpp b/pool/shard007/C++/0095840_testcrtfverticalcolumn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a89c8a3ac2738edb8773d28d742413679104448 --- /dev/null +++ b/pool/shard007/C++/0095840_testcrtfverticalcolumn.cpp @@ -0,0 +1,60 @@ +/*************************************************************************** + * Copyright (C) 2010 by Serge Poltavsky * + * serge.poltavski@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 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 "testcrtfverticalcolumn.h" +CPPUNIT_TEST_SUITE_REGISTRATION( TestCRtfVerticalColumn); +#include "rfrmt/crtfverticalcolumn.h" + +using namespace cf; + +void TestCRtfVerticalColumn::testInit() { + CRtfVerticalColumn vcol; +} + +struct DrawVColumn +{ + int * i_; + DrawVColumn(int * i) : + i_(i) { + } + void operator()(const CRtfVerticalColumn *) { + (*i_)++; + } +}; + +void TestCRtfVerticalColumn::testSetDrawCallback() { + RfrmtDrawVColumnFunction f; + CRtfVerticalColumn::setDrawCallback(f); + + CRtfVerticalColumn vcol; + vcol.drawLayout(); + + int call_count = 0; + f = DrawVColumn(&call_count); + CRtfVerticalColumn::setDrawCallback(f); + + CPPUNIT_ASSERT_EQUAL(0, call_count); + vcol.drawLayout(); + CPPUNIT_ASSERT_EQUAL(1, call_count); + vcol.drawLayout(); + CPPUNIT_ASSERT_EQUAL(2, call_count); + + RfrmtDrawVColumnFunction null; + CRtfVerticalColumn::setDrawCallback(null); + vcol.drawLayout(); + CPPUNIT_ASSERT_EQUAL(2, call_count); +} diff --git a/pool/shard007/C++/0095841_thread.cpp b/pool/shard007/C++/0095841_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e9720c5cf75f26e11c2d2ccdd6f98b4eba034aa --- /dev/null +++ b/pool/shard007/C++/0095841_thread.cpp @@ -0,0 +1,201 @@ +/* + Stockfish, a UCI chess playing engine derived from Glaurung 2.1 + Copyright (C) 2004-2008 Tord Romstad (Glaurung author) + Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad + Copyright (C) 2015-2018 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad + + Stockfish 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. + + Stockfish 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 // For std::count +#include + +#include "movegen.h" +#include "search.h" +#include "thread.h" +#include "uci.h" +#include "syzygy/tbprobe.h" + +ThreadPool Threads; // Global object + + +/// Thread constructor launches the thread and waits until it goes to sleep +/// in idle_loop(). Note that 'searching' and 'exit' should be alredy set. + +Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) { + + wait_for_search_finished(); +} + + +/// Thread destructor wakes up the thread in idle_loop() and waits +/// for its termination. Thread should be already waiting. + +Thread::~Thread() { + + assert(!searching); + + exit = true; + start_searching(); + stdThread.join(); +} + + +/// Thread::clear() reset histories, usually before a new game + +void Thread::clear() { + + counterMoves.fill(MOVE_NONE); + mainHistory.fill(0); + captureHistory.fill(0); + + for (auto& to : contHistory) + for (auto& h : to) + h.fill(0); + + contHistory[NO_PIECE][0].fill(Search::CounterMovePruneThreshold - 1); +} + +/// Thread::start_searching() wakes up the thread that will start the search + +void Thread::start_searching() { + + std::lock_guard lk(mutex); + searching = true; + cv.notify_one(); // Wake up the thread in idle_loop() +} + + +/// Thread::wait_for_search_finished() blocks on the condition variable +/// until the thread has finished searching. + +void Thread::wait_for_search_finished() { + + std::unique_lock lk(mutex); + cv.wait(lk, [&]{ return !searching; }); +} + + +/// Thread::idle_loop() is where the thread is parked, blocked on the +/// condition variable, when it has no work to do. + +void Thread::idle_loop() { + + // If OS already scheduled us on a different group than 0 then don't overwrite + // the choice, eventually we are one of many one-threaded processes running on + // some Windows NUMA hardware, for instance in fishtest. To make it simple, + // just check if running threads are below a threshold, in this case all this + // NUMA machinery is not needed. + if (Options["Threads"] >= 8) + WinProcGroup::bindThisThread(idx); + + while (true) + { + std::unique_lock lk(mutex); + searching = false; + cv.notify_one(); // Wake up anyone waiting for search finished + cv.wait(lk, [&]{ return searching; }); + + if (exit) + return; + + lk.unlock(); + + search(); + } +} + +/// ThreadPool::set() creates/destroys threads to match the requested number. +/// Created and launced threads wil go immediately to sleep in idle_loop. +/// Upon resizing, threads are recreated to allow for binding if necessary. + +void ThreadPool::set(size_t requested) { + + if (size() > 0) { // destroy any existing thread(s) + main()->wait_for_search_finished(); + + while (size() > 0) + delete back(), pop_back(); + } + + if (requested > 0) { // create new thread(s) + push_back(new MainThread(0)); + + while (size() < requested) + push_back(new Thread(size())); + clear(); + } +} + +/// ThreadPool::clear() sets threadPool data to initial values. + +void ThreadPool::clear() { + + for (Thread* th : *this) + th->clear(); + + main()->callsCnt = 0; + main()->previousScore = VALUE_INFINITE; + main()->previousTimeReduction = 1; +} + +/// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and +/// returns immediately. Main thread will wake up other threads and start the search. + +void ThreadPool::start_thinking(Position& pos, StateListPtr& states, + const Search::LimitsType& limits, bool ponderMode) { + + main()->wait_for_search_finished(); + + stopOnPonderhit = stop = false; + ponder = ponderMode; + Search::Limits = limits; + Search::RootMoves rootMoves; + + for (const auto& m : MoveList(pos)) + if ( limits.searchmoves.empty() + || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m)) + rootMoves.emplace_back(m); + + if (!rootMoves.empty()) + Tablebases::filter_root_moves(pos, rootMoves); + + // After ownership transfer 'states' becomes empty, so if we stop the search + // and call 'go' again without setting a new position states.get() == NULL. + assert(states.get() || setupStates.get()); + + if (states.get()) + setupStates = std::move(states); // Ownership transfer, states is now empty + + // We use Position::set() to set root position across threads. But there are + // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot + // be deduced from a fen string, so set() clears them and to not lose the info + // we need to backup and later restore setupStates->back(). Note that setupStates + // is shared by threads but is accessed in read-only mode. + StateInfo tmp = setupStates->back(); + + for (Thread* th : *this) + { + th->nodes = th->tbHits = 0; + th->rootDepth = th->completedDepth = DEPTH_ZERO; + th->rootMoves = rootMoves; + th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th); + th->nmp_ply = 0; + th->pair = -1; + } + + setupStates->back() = tmp; + + main()->start_searching(); +} diff --git a/pool/shard007/C++/0095845_Application.cpp b/pool/shard007/C++/0095845_Application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8306d749115a5d178636176bf7b27db62912e1e2 --- /dev/null +++ b/pool/shard007/C++/0095845_Application.cpp @@ -0,0 +1,85 @@ +/* + * THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode + * COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED. + * + * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE: + * https://github.com/arielm/Unicode/blob/master/LICENSE.md + */ + +#include "chronotext/cinder/CinderApp.h" +#include "chronotext/utils/Utils.h" + +#include "Sketch.h" + +using namespace std; +using namespace ci; +using namespace app; +using namespace chr; + +class Application : public CinderApp +{ + Sketch *target; + +public: + Application(); + void prepareSettings(Settings *settings); + void keyDown(KeyEvent event); +}; + +Application::Application() +{ + sketch = target = new Sketch(this); +} + +void Application::prepareSettings(Settings *settings) +{ +#if defined(CINDER_MAC) || defined(CINDER_MSW) + settings->setWindowSize(1024, 736); + settings->enableHighDensityDisplay(); + settings->disableFrameRate(); +#endif +} + +void Application::keyDown(KeyEvent event) +{ + switch (event.getCode()) + { + case KeyEvent::KEY_u: + target->fontManager.unload(); + break; + + case KeyEvent::KEY_k: + target->fontManager.unload("sans-serif"); + break; + + case KeyEvent::KEY_RETURN: + target->shuffleLines(); + break; + + case KeyEvent::KEY_SPACE: + target->oscillate ^= true; + break; + + case KeyEvent::KEY_t: + target->align = VirtualFont::ALIGN_TOP; + break; + + case KeyEvent::KEY_m: + target->align = VirtualFont::ALIGN_MIDDLE; + break; + + case KeyEvent::KEY_b: + target->align = VirtualFont::ALIGN_BOTTOM; + break; + + case KeyEvent::KEY_x: + cout << "TEXTURE MEMORY USAGE: " << prettyBytes(target->fontManager.getTextureMemoryUsage()) << endl; + break; + + case KeyEvent::KEY_ESCAPE: + quit(); + break; + } +} + +CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE)) diff --git a/pool/shard007/C++/0095848_vec.cpp b/pool/shard007/C++/0095848_vec.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df37bd35479dadd2c02e7d5c66afd41096e0789f --- /dev/null +++ b/pool/shard007/C++/0095848_vec.cpp @@ -0,0 +1,164 @@ +/**************************************************************************** + + Copyright (C) 2002-2013 Gilles Debunne. All rights reserved. + + This file is part of the QGLViewer library version 2.5.2. + + http://www.libqglviewer.com - contact@libqglviewer.com + + This file may be used under the terms of the GNU General Public License + versions 2.0 or 3.0 as published by the Free Software Foundation and + appearing in the LICENSE file included in the packaging of this file. + In addition, as a special exception, Gilles Debunne gives you certain + additional rights, described in the file GPL_EXCEPTION in this package. + + libQGLViewer uses dual licensing. Commercial/proprietary software must + purchase a libQGLViewer Commercial License. + + This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE + WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + +*****************************************************************************/ + +#include "domUtils.h" +#include "vec.h" + +// Most of the methods are declared inline in vec.h + +using namespace qglviewer; +using namespace std; + +/*! Projects the Vec on the axis of direction \p direction that passes through the origin. + +\p direction does not need to be normalized (but must be non null). */ +void Vec::projectOnAxis(const Vec& direction) +{ +#ifndef QT_NO_DEBUG + if (direction.squaredNorm() < 1.0E-10) + qWarning("Vec::projectOnAxis: axis direction is not normalized (norm=%f).", direction.norm()); +#endif + + *this = (((*this)*direction) / direction.squaredNorm()) * direction; +} + +/*! Projects the Vec on the plane whose normal is \p normal that passes through the origin. + +\p normal does not need to be normalized (but must be non null). */ +void Vec::projectOnPlane(const Vec& normal) +{ +#ifndef QT_NO_DEBUG + if (normal.squaredNorm() < 1.0E-10) + qWarning("Vec::projectOnPlane: plane normal is not normalized (norm=%f).", normal.norm()); +#endif + + *this -= (((*this)*normal) / normal.squaredNorm()) * normal; +} + +/*! Returns a Vec orthogonal to the Vec. Its norm() depends on the Vec, but is zero only for a + null Vec. Note that the function that associates an orthogonalVec() to a Vec is not continous. */ +Vec Vec::orthogonalVec() const +{ + // Find smallest component. Keep equal case for null values. + if ((fabs(y) >= 0.9*fabs(x)) && (fabs(z) >= 0.9*fabs(x))) + return Vec(0.0, -z, y); + else + if ((fabs(x) >= 0.9*fabs(y)) && (fabs(z) >= 0.9*fabs(y))) + return Vec(-z, 0.0, x); + else + return Vec(-y, x, 0.0); +} + +/*! Constructs a Vec from a \c QDomElement representing an XML code of the form + \code< anyTagName x=".." y=".." z=".." />\endcode + +If one of these attributes is missing or is not a number, a warning is displayed and the associated +value is set to 0.0. + +See also domElement() and initFromDOMElement(). */ +Vec::Vec(const QDomElement& element) +{ + QStringList attribute; + attribute << "x" << "y" << "z"; + for (int i=0; ioperator[](i) = DomUtils::doubleFromDom(element, attribute[i], 0.0); +#else + v_[i] = DomUtils::doubleFromDom(element, attribute[i], 0.0); +#endif +} + +/*! Returns an XML \c QDomElement that represents the Vec. + + \p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create + QDomElement. + + When output to a file, the resulting QDomElement will look like: + \code + + \endcode + + Use initFromDOMElement() to restore the Vec state from the resulting \c QDomElement. See also the + Vec(const QDomElement&) constructor. + + Here is complete example that creates a QDomDocument and saves it into a file: + \code + Vec sunPos; + QDomDocument document("myDocument"); + QDomElement sunElement = document.createElement("Sun"); + document.appendChild(sunElement); + sunElement.setAttribute("brightness", sunBrightness()); + sunElement.appendChild(sunPos.domElement("sunPosition", document)); + // Other additions to the document hierarchy... + + // Save doc document + QFile f("myFile.xml"); + if (f.open(IO_WriteOnly)) + { + QTextStream out(&f); + document.save(out, 2); + f.close(); + } + \endcode + + See also Quaternion::domElement(), Frame::domElement(), Camera::domElement()... */ +QDomElement Vec::domElement(const QString& name, QDomDocument& document) const +{ + QDomElement de = document.createElement(name); + de.setAttribute("x", QString::number(x)); + de.setAttribute("y", QString::number(y)); + de.setAttribute("z", QString::number(z)); + return de; +} + +/*! Restores the Vec state from a \c QDomElement created by domElement(). + + The \c QDomElement should contain \c x, \c y and \c z attributes. If one of these attributes is + missing or is not a number, a warning is displayed and the associated value is set to 0.0. + + To restore the Vec state from an xml file, use: + \code + // Load DOM from file + QDomDocument doc; + QFile f("myFile.xml"); + if (f.open(IO_ReadOnly)) + { + doc.setContent(&f); + f.close(); + } + // Parse the DOM tree and initialize + QDomElement main=doc.documentElement(); + myVec.initFromDOMElement(main); + \endcode + + See also the Vec(const QDomElement&) constructor. */ +void Vec::initFromDOMElement(const QDomElement& element) +{ + const Vec v(element); + *this = v; +} + +ostream& operator<<(ostream& o, const Vec& v) +{ + return o << v.x << '\t' << v.y << '\t' << v.z; +} + diff --git a/pool/shard007/C++/0095851_narf_feature_extraction.cpp b/pool/shard007/C++/0095851_narf_feature_extraction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cb20dcfba55aac66559c9f5e8b063c0d5fc79c6 --- /dev/null +++ b/pool/shard007/C++/0095851_narf_feature_extraction.cpp @@ -0,0 +1,224 @@ +/* \author Bastian Steder */ + +#include + +#include +#include "pcl/range_image/range_image.h" +#include "pcl/io/pcd_io.h" +#include "pcl/visualization/range_image_visualizer.h" +#include "pcl/visualization/pcl_visualizer.h" +#include "pcl/features/range_image_border_extractor.h" +#include "pcl/keypoints/narf_keypoint.h" +#include "pcl/features/narf_descriptor.h" +#include + +typedef pcl::PointXYZ PointType; + +// -------------------- +// -----Parameters----- +// -------------------- +float angular_resolution = 0.5f; +float support_size = 0.2f; +pcl::RangeImage::CoordinateFrame coordinate_frame = pcl::RangeImage::CAMERA_FRAME; +bool setUnseenToMaxRange = false; +bool rotation_invariant = true; + +// -------------- +// -----Help----- +// -------------- +void +printUsage (const char* progName) +{ + std::cout << "\n\nUsage: "<\n\n" + << "Options:\n" + << "-------------------------------------------\n" + << "-r angular resolution in degrees (default "< coordinate frame (default "<< (int)coordinate_frame<<")\n" + << "-m Treat all unseen points to max range\n" + << "-s support size for the interest points (diameter of the used sphere - " + "default "< switch rotational invariant version of the feature on/off" + << " (default "<< (int)rotation_invariant<<")\n" + << "-h this help\n" + << "\n\n"; +} + +void +setViewerPose (pcl::visualization::PCLVisualizer& viewer, const Eigen::Affine3f& viewer_pose) +{ + Eigen::Vector3f pos_vector = viewer_pose * Eigen::Vector3f (0, 0, 0); + Eigen::Vector3f look_at_vector = viewer_pose.rotation () * Eigen::Vector3f (0, 0, 1) + pos_vector; + Eigen::Vector3f up_vector = viewer_pose.rotation () * Eigen::Vector3f (0, -1, 0); + viewer.camera_.pos[0] = pos_vector[0]; + viewer.camera_.pos[1] = pos_vector[1]; + viewer.camera_.pos[2] = pos_vector[2]; + viewer.camera_.focal[0] = look_at_vector[0]; + viewer.camera_.focal[1] = look_at_vector[1]; + viewer.camera_.focal[2] = look_at_vector[2]; + viewer.camera_.view[0] = up_vector[0]; + viewer.camera_.view[1] = up_vector[1]; + viewer.camera_.view[2] = up_vector[2]; + viewer.updateCamera (); +} + +// -------------- +// -----Main----- +// -------------- +int +main (int argc, char** argv) +{ + // -------------------------------------- + // -----Parse Command Line Arguments----- + // -------------------------------------- + if (pcl::console::find_argument (argc, argv, "-h") >= 0) + { + printUsage (argv[0]); + return 0; + } + if (pcl::console::find_argument (argc, argv, "-m") >= 0) + { + setUnseenToMaxRange = true; + cout << "Setting unseen values in range image to maximum range readings.\n"; + } + if (pcl::console::parse (argc, argv, "-o", rotation_invariant) >= 0) + cout << "Switching rotation invariant feature version "<< (rotation_invariant ? "on" : "off")<<".\n"; + int tmp_coordinate_frame; + if (pcl::console::parse (argc, argv, "-c", tmp_coordinate_frame) >= 0) + { + coordinate_frame = pcl::RangeImage::CoordinateFrame (tmp_coordinate_frame); + cout << "Using coordinate frame "<< (int)coordinate_frame<<".\n"; + } + if (pcl::console::parse (argc, argv, "-s", support_size) >= 0) + cout << "Setting support size to "<= 0) + cout << "Setting angular resolution to "<::Ptr point_cloud_ptr (new pcl::PointCloud); + pcl::PointCloud& point_cloud = *point_cloud_ptr; + pcl::PointCloud far_ranges; + Eigen::Affine3f scene_sensor_pose (Eigen::Affine3f::Identity ()); + std::vector pcd_filename_indices = pcl::console::parse_file_extension_argument (argc, argv, "pcd"); + if (!pcd_filename_indices.empty ()) + { + std::string filename = argv[pcd_filename_indices[0]]; + if (pcl::io::loadPCDFile (filename, point_cloud) == -1) + { + cerr << "Was not able to open file \""< Genarating example point cloud.\n\n"; + for (float x=-0.5f; x<=0.5f; x+=0.01f) + { + for (float y=-0.5f; y<=0.5f; y+=0.01f) + { + PointType point; point.x = x; point.y = y; point.z = 2.0f - y; + point_cloud.points.push_back (point); + } + } + point_cloud.width = (int) point_cloud.points.size (); point_cloud.height = 1; + } + + // ----------------------------------------------- + // -----Create RangeImage from the PointCloud----- + // ----------------------------------------------- + float noise_level = 0.0; + float min_range = 0.0f; + int border_size = 1; + boost::shared_ptr range_image_ptr (new pcl::RangeImage); + pcl::RangeImage& range_image = *range_image_ptr; + range_image.createFromPointCloud (point_cloud, angular_resolution, pcl::deg2rad (360.0f), pcl::deg2rad (180.0f), + scene_sensor_pose, coordinate_frame, noise_level, min_range, border_size); + range_image.integrateFarRanges (far_ranges); + if (setUnseenToMaxRange) + range_image.setUnseenToMaxRange (); + + // -------------------------------------------- + // -----Open 3D viewer and add point cloud----- + // -------------------------------------------- + pcl::visualization::PCLVisualizer viewer ("3D Viewer"); + viewer.setBackgroundColor (1, 1, 1); + pcl::visualization::PointCloudColorHandlerCustom range_image_color_handler (range_image_ptr, 0, 0, 0); + viewer.addPointCloud (range_image_ptr, range_image_color_handler, "range image"); + viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "range image"); + //viewer.addCoordinateSystem (1.0f); + //PointCloudColorHandlerCustom point_cloud_color_handler (point_cloud_ptr, 150, 150, 150); + //viewer.addPointCloud (point_cloud_ptr, point_cloud_color_handler, "original point cloud"); + viewer.initCameraParameters (); + setViewerPose (viewer, range_image.getTransformationToWorldSystem ()); + + // -------------------------- + // -----Show range image----- + // -------------------------- + pcl::visualization::RangeImageVisualizer range_image_widget ("Range image"); + range_image_widget.setRangeImage (range_image); + + // -------------------------------- + // -----Extract NARF keypoints----- + // -------------------------------- + pcl::RangeImageBorderExtractor range_image_border_extractor; + pcl::NarfKeypoint narf_keypoint_detector; + narf_keypoint_detector.setRangeImageBorderExtractor (&range_image_border_extractor); + narf_keypoint_detector.setRangeImage (&range_image); + narf_keypoint_detector.getParameters ().support_size = support_size; + + pcl::PointCloud keypoint_indices; + narf_keypoint_detector.compute (keypoint_indices); + std::cout << "Found "< keypoints; + keypoints.points.resize (keypoint_indices.points.size ()); + for (size_t i=0; i keypoint_indices2; + keypoint_indices2.resize (keypoint_indices.points.size ()); + for (unsigned int i=0; i narf_descriptors; + narf_descriptor.compute (narf_descriptors); + cout << "Extracted "< bluetoothSupplement = adoptPtrWillBeNoop(new BluetoothSupplement(bluetooth)); + WillBeHeapSupplement::provideTo(frame, supplementName(), bluetoothSupplement.release()); +}; + +WebBluetooth* BluetoothSupplement::from(LocalFrame* frame) +{ + BluetoothSupplement* supplement = static_cast(WillBeHeapSupplement::from(frame, supplementName())); + + ASSERT(supplement); + ASSERT(supplement->m_bluetooth); + + return supplement->m_bluetooth; +} + +WebBluetooth* BluetoothSupplement::fromScriptState(ScriptState* scriptState) +{ + return fromExecutionContext(scriptState->executionContext()); +} + +WebBluetooth* BluetoothSupplement::fromExecutionContext(ExecutionContext* executionContext) +{ + if (!executionContext->isDocument()) { + return nullptr; + } + return BluetoothSupplement::from(static_cast(executionContext)->frame()); +} + +DEFINE_TRACE(BluetoothSupplement) +{ + WillBeHeapSupplement::trace(visitor); +} + +}; // blink diff --git a/pool/shard007/C++/0095854_3974.cc b/pool/shard007/C++/0095854_3974.cc new file mode 100644 index 0000000000000000000000000000000000000000..73f284e1a634fd34308414144ab743ba3bf73923 --- /dev/null +++ b/pool/shard007/C++/0095854_3974.cc @@ -0,0 +1,53 @@ +#include +#include + +using namespace std; + +int len; +char in[1000010], s[2000010]; +int nRad[2000010]; + +int manacher() { + memset(nRad, 0, sizeof(nRad)); + int maxRad, j, maxx; + maxRad = j = maxx = 0; + + for (int i = 1; i != len; ++i) { + if (i < maxx) + nRad[i] = min(nRad[2*j-i], maxx-i); + else + nRad[i] = 1; + + while (s[i - nRad[i]] == s[i + nRad[i]]) + ++nRad[i]; + + if (maxRad < nRad[i]) + maxRad = nRad[i]; + + if (i + nRad[i] > maxx) { + j = i; + maxx = i + nRad[i]; + } + } + + return maxRad - 1; +} + +int main() { + int cases = 1; + while (cin >> in) { + if (strncmp(in, "END", 3) == 0) + break; + len = strlen(in); + memset(s, '#', sizeof(s)); + s[0] = '$'; + for (int i = 0; i != len; ++i) + s[(i+1)*2] = in[i]; + len = (len + 1) * 2; + + int ans = manacher(); + cout << "Case " << cases++ << ": " << ans << endl; + } + return 0; +} + diff --git a/pool/shard007/C++/0095857_testqobjectuniqueptr.cpp b/pool/shard007/C++/0095857_testqobjectuniqueptr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e16c81971a5779508250766ef65f73d129d28be --- /dev/null +++ b/pool/shard007/C++/0095857_testqobjectuniqueptr.cpp @@ -0,0 +1,127 @@ +/*************************************************************************** + testqobjectuniqueptr.cpp + -------------------------------------- + Date : + Copyright : (C) 2019 by Matthias Kuhn + Email : matthias@opengis.ch + *************************************************************************** + * * + * 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. * + * * + ***************************************************************************/ + +#include "qgstest.h" +#include "qobjectuniqueptr.h" + +#include "qgstest.h" + +class TestQObjectUniquePtr : public QObject +{ + Q_OBJECT + + private slots: + void testMemLeak(); + void testParentDeletedFirst(); + void testParentDeletedAfter(); + void testOperatorBool(); + void testSwap(); + void testOperatorArrow(); + void testDeleteLater(); +}; + +void TestQObjectUniquePtr::testMemLeak() +{ + QObject *myobj = new QObject(); + QObjectUniquePtr obj( myobj ); +} + +void TestQObjectUniquePtr::testParentDeletedFirst() +{ + QObject *parent = new QObject(); + QObject *child = new QObject( parent ); + + QObjectUniquePtr obj( child ); + QVERIFY( !obj.isNull() ); + QVERIFY( obj ); + QCOMPARE( child, obj.get() ); + QCOMPARE( child, obj.data() ); + + delete parent; + QVERIFY( obj.isNull() ); + QVERIFY( !obj ); +} + +void TestQObjectUniquePtr::testParentDeletedAfter() +{ + QObject *parent = new QObject(); + QObject *child = new QObject( parent ); + QPointer observer( child ); + + { + QObjectUniquePtr obj( child ); + QVERIFY( !observer.isNull() ); + } + QVERIFY( observer.isNull() ); + + + // Basically shouldn't crash because of double delete on this line + delete parent; + QVERIFY( observer.isNull() ); +} + +void TestQObjectUniquePtr::testOperatorBool() +{ + QObjectUniquePtr obj; + QVERIFY( !obj ); + QObjectUniquePtr obj2( new QObject() ); + QVERIFY( obj2 ); +} + +void TestQObjectUniquePtr::testSwap() +{ + QObject *o = new QObject(); + QObjectUniquePtr obj; + QObjectUniquePtr obj2( o ); + obj.swap( obj2 ); + QCOMPARE( o, obj.get() ); + QCOMPARE( nullptr, obj2.get() ); + + QObject *o2 = new QObject(); + QObjectUniquePtr obj3( o2 ); + obj.swap( obj3 ); + QCOMPARE( o, obj3.get() ); + QCOMPARE( o2, obj.get() ); +} + +void TestQObjectUniquePtr::testOperatorArrow() +{ + QObject *o = new QObject(); + o->setObjectName( "Teddy" ); + QObjectUniquePtr obj( o ); + QCOMPARE( obj->objectName(), QStringLiteral( "Teddy" ) ); +} + +void TestQObjectUniquePtr::testDeleteLater() +{ + QObject *o = new QObject(); + QObject *o2 = new QObject(); + + QObjectUniquePtr obj( o ); + QObjectUniquePtr obj2( o2 ); + + obj2->deleteLater(); + obj->deleteLater(); + + obj2.reset(); + + connect( o, &QObject::destroyed, QgsApplication::instance(), &QgsApplication::quit ); + QgsApplication::instance()->exec(); + QVERIFY( obj.isNull() ); + QVERIFY( obj2.isNull() ); +} + +QGSTEST_MAIN( TestQObjectUniquePtr ) +#include "testqobjectuniqueptr.moc" diff --git a/pool/shard007/C++/0095858_TitleScene.cpp b/pool/shard007/C++/0095858_TitleScene.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f94ff5803f6995acffa4769b1bc91d1c1dc4d23 --- /dev/null +++ b/pool/shard007/C++/0095858_TitleScene.cpp @@ -0,0 +1,105 @@ +/* -------------------------------------------------------------------------- + * + * File TitleScene.cpp + * Description + * Ported By Young-Hwan Mun + * Created By giginet - 11/05/27 + * Contact xmsoft77@gmail.com + * + * -------------------------------------------------------------------------- + * + * Copyright (c) 2010-2013 XMSoft. + * Copyright (c) 2011-2013 Kawaz. All rights reserved. + * + * -------------------------------------------------------------------------- + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- */ + +#include "Precompiled.h" +#include "TitleScene.h" +#include "MainScene.h" +#include "HowtoScene.h" +#include "CreditScene.h" + +KDbool TitleScene::init ( KDvoid ) +{ + if ( !KWScene::init ( ) ) + { + return KD_FALSE; + } + + m_bPlayed = KD_FALSE; + + KWSprite* pBackground = KWSprite::create ( "image/title/title_background-hd.png" ); + pBackground->setPosition ( ccpMid ( m_tLyrSize ) ); + + + KWSprite* pLogo = KWSprite::create ( "image/title/logo-hd.png" ); + pLogo->setPosition ( ccp ( m_tLyrSize.cx / 2, m_tLyrSize.cy / 2 + 20 ) ); + + CCMenu* pMenu = CCMenu::create + ( + CCMenuItemImage::create ( "image/title/howto-hd.png" , "image/title/howto_selected-hd.png" , this, menu_selector ( TitleScene::pressHowtoButton ) ), + CCMenuItemImage::create ( "image/title/start-hd.png" , "image/title/start_selected-hd.png" , this, menu_selector ( TitleScene::pressStartButton ) ), + CCMenuItemImage::create ( "image/title/credit-hd.png", "image/title/credit_selected-hd.png", this, menu_selector ( TitleScene::pressCreditButton ) ), + KD_NULL + ); + pMenu->alignItemsHorizontally ( ); + pMenu->setPosition ( ccp ( m_tLyrSize.cx / 2, 80 ) ); + + this->addChild ( pBackground ); + this->addChild ( pLogo ); + this->addChild ( pMenu ); + + return KD_TRUE; +} + +KDvoid TitleScene::onEnterTransitionDidFinish ( KDvoid ) +{ + if ( !m_bPlayed ) + { + KWMusicManager::sharedManager ( )->playMusic ( "music/title.mp3", KD_FALSE ); + m_bPlayed = KD_TRUE; + } +} + +KDvoid TitleScene::pressStartButton ( CCObject* pSender ) +{ + SimpleAudioEngine::sharedEngine ( )->playEffect ( "se/pico.wav" ); + + CCTransitionPageTurn* pTransition = CCTransitionPageTurn::create ( 0.5f, MainScene::scene ( ), KD_FALSE ); + CCDirector::sharedDirector ( )->replaceScene ( pTransition ); + + KWMusicManager::sharedManager ( )->fadeout ( 0.5f ); +} + +KDvoid TitleScene::pressCreditButton ( CCObject* pSender ) +{ + SimpleAudioEngine::sharedEngine ( )->playEffect ( "se/pico.wav" ); + + CCTransitionCrossFade* pTransition = CCTransitionCrossFade::create ( 0.5f, CreditScene::scene ( ) ); + CCDirector::sharedDirector ( )->pushScene ( pTransition ); +} + +KDvoid TitleScene::pressHowtoButton ( CCObject* pSender ) +{ + SimpleAudioEngine::sharedEngine ( )->playEffect ( "se/pico.wav" ); + + CCTransitionCrossFade* pTransition = CCTransitionCrossFade::create ( 0.5f, HowtoScene::scene ( ) ); + CCDirector::sharedDirector ( )->pushScene ( pTransition ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0095860_templet.cpp b/pool/shard007/C++/0095860_templet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d66979977ded99bcbb03f664c93c523101d26d39 --- /dev/null +++ b/pool/shard007/C++/0095860_templet.cpp @@ -0,0 +1,162 @@ +/*$TET$templet$!cpp-copyright!*/ +/*--------------------------------------------------------------------------*/ +/* Copyright 2010-2015 Sergey Vostokin */ +/* */ +/* 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. */ +/*--------------------------------------------------------------------------*/ +/*$TET$*/ + +/*$TET$templet$!templet!*/ +/*~Link= + +Begin ? argSin2 -> Calc | argCos2 -> Calc; + Calc ! result -> End; + End. +*Parent= + p1 : Link ! result -> join; + p2 : Link ! result -> join; + +fork(p1!argCos2,p2!argSin2); + join(p1?result,p2?result). +*Child= + p : Link ? argCos2 -> calcCos2 | argSin2 -> calcSin2; + calcCos2(p?argCos2,p!result); + calcSin2(p?argSin2,p!result).*/ +/*$TET$*/ + +#include "templet.h" + +/*$TET$templet$!cpp-prologue!*/ +/*$TET$*/ +//////////////////////class Link//////////////////// +Link::Link(TEMPLET_DBG::Assemble*a):TEMPLET_DBG::Channel(a) +{ +/*$TET$Link$!constructor!*/ +/*$TET$*/ +} + +Link::~Link() +{ +/*$TET$Link$!destructor!*/ +/*$TET$*/ +} + +//////////////////////class Parent//////////////////// +Parent::Parent(TEMPLET_DBG::Assemble*a):TEMPLET_DBG::Process(a) +{ +/*$TET$Parent$!constructor!*/ +/*$TET$*/ +} + +Parent::~Parent() +{ +/*$TET$Parent$!destructor!*/ +/*$TET$*/ +} + +/*$TET$Parent$!usercode!*/ +/*$TET$*/ + +bool Parent::fork(/*out*/Link::argCos2*p1,/*out*/Link::argSin2*p2) +{ +/*$TET$Parent$fork*/ + p1->x=p2->x=0.333; + return true; +/*$TET$*/ +} + +bool Parent::join(/*in*/Link::result*p1,/*in*/Link::result*p2) +{ +/*$TET$Parent$join*/ + cout<<"sin2x+cos2x="<y+p2->y; + return true; +/*$TET$*/ +} + +void Parent::_run(int _selector,TEMPLET_DBG::Channel*_channel) +{ + bool res; +/*$TET$Parent$!run!*/ +/*$TET$*/ + +} + +//////////////////////class Child//////////////////// +Child::Child(TEMPLET_DBG::Assemble*a):TEMPLET_DBG::Process(a) +{ +/*$TET$Child$!constructor!*/ +/*$TET$*/ +} + +Child::~Child() +{ +/*$TET$Child$!destructor!*/ +/*$TET$*/ +} + +/*$TET$Child$!usercode!*/ +/*$TET$*/ + +bool Child::calcCos2(/*in*/Link::argCos2*p1,/*out*/Link::result*p2) +{ +/*$TET$Child$calcCos2*/ + p2->y=cos(p1->x)*cos(p1->x); + return true; +/*$TET$*/ +} + +bool Child::calcSin2(/*in*/Link::argSin2*p1,/*out*/Link::result*p2) +{ +/*$TET$Child$calcSin2*/ + p2->y=sin(p1->x)*sin(p1->x); + return true; +/*$TET$*/ +} + +void Child::_run(int _selector,TEMPLET_DBG::Channel*_channel) +{ + bool res; +/*$TET$Child$!run!*/ +/*$TET$*/ + +} + +//////////////////////class templet//////////////////// +templet::templet(int NT): TEMPLET_DBG::Assemble(NT) +{ +/*$TET$templet$!constructor!*/ +/*$TET$*/ +} + +templet::~templet() +{ +/*$TET$templet$!destructor!*/ +/*$TET$*/ +} + +/*$TET$templet$!cpp-epilogue!*/ +int main(int argc, char*argv[]) +{ + templet tet(2); + + Parent* p=tet.new_Parent(); + Child* c1=tet.new_Child(); + Child* c2=tet.new_Child(); + + c1->p_p(p->p_p1()); + c2->p_p(p->p_p2()); + + tet.run(); + + return 0; +} +/*$TET$*/ + diff --git a/pool/shard007/C++/0095861_SLLandscapeIndividual.cpp b/pool/shard007/C++/0095861_SLLandscapeIndividual.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6704e37c397fff326970de3b8215748213d99e1c --- /dev/null +++ b/pool/shard007/C++/0095861_SLLandscapeIndividual.cpp @@ -0,0 +1,191 @@ +// Copyright 2017-present, Institute for Artificial Intelligence - University of Bremen +// Author: Andrei Haidu (http://haidu.eu) + +#include "Individuals/Type/SLLandscapeIndividual.h" +#include "Materials/MaterialInstanceDynamic.h" +#include "Landscape.h" +#include "LandscapeProxy.h" + +// Ctor +USLLandscapeIndividual::USLLandscapeIndividual() +{ + LandscapeActor = nullptr; +} + +// Called before destroying the object. +void USLLandscapeIndividual::BeginDestroy() +{ + SetIsInit(false); + Super::BeginDestroy(); +} + +// Set pointer to the semantic owner +bool USLLandscapeIndividual::Init(bool bReset) +{ + if (bReset) + { + InitReset(); + } + + if (IsInit()) + { + return true; + } + + SetIsInit(Super::Init(bReset) && InitImpl()); + return IsInit(); +} + +// Load semantic data +bool USLLandscapeIndividual::Load(bool bReset, bool bTryImport) +{ + if (bReset) + { + LoadReset(); + } + + if (IsLoaded()) + { + return true; + } + + if (!IsInit()) + { + if (!Init(bReset)) + { + return false; + } + } + + SetIsLoaded(Super::Load(bReset, bTryImport) && LoadImpl(bTryImport)); + return IsLoaded(); +} + +// Apply visual mask material +bool USLLandscapeIndividual::ApplyMaskMaterials(bool bIncludeChildren /*= false*/) +{ + if (!IsInit()) + { + return false; + } + + if (!bIsMaskMaterialOn) + { +#if WITH_EDITOR + ParentActor->SetIsTemporarilyHiddenInEditor(true); +#endif // WITH_EDITOR + ParentActor->SetActorHiddenInGame(true); + +// //LandscapeActor->LandscapeMaterial = VisualMaskDynamicMaterial; +//#if WITH_EDITOR +// //LandscapeActor->EditorSetLandscapeMaterial(VisualMaskDynamicMaterial); +// +// UProperty* MaterialProperty = FindField(ALandscape::StaticClass(), "LandscapeMaterial"); +// LandscapeActor->PreEditChange(MaterialProperty); +// LandscapeActor->LandscapeMaterial = VisualMaskDynamicMaterial; +// FPropertyChangedEvent PropertyChangedEvent(MaterialProperty); +// LandscapeActor->PostEditChangeProperty(PropertyChangedEvent); +//#endif // WITH_EDITOR + + bIsMaskMaterialOn = true; + return true; + } + return false; +} + +// Apply original materials +bool USLLandscapeIndividual::ApplyOriginalMaterials() +{ + if (!IsInit()) + { + return false; + } + + if (bIsMaskMaterialOn) + { +#if WITH_EDITOR + ParentActor->SetIsTemporarilyHiddenInEditor(false); +#endif // WITH_EDITOR + ParentActor->SetActorHiddenInGame(false); + +// if (OriginalMaterials.Num() > 0) +// { +//#if WITH_EDITOR +// //LandscapeActor->EditorSetLandscapeMaterial(OriginalMaterials[0]); +// +// UProperty* MaterialProperty = FindField(ALandscape::StaticClass(), "LandscapeMaterial"); +// LandscapeActor->PreEditChange(MaterialProperty); +// LandscapeActor->LandscapeMaterial = OriginalMaterials[0]; +// FPropertyChangedEvent PropertyChangedEvent(MaterialProperty); +// LandscapeActor->PostEditChangeProperty(PropertyChangedEvent); +//#endif // WITH_EDITOR +// } + + bIsMaskMaterialOn = false; + return true; + } + return false; +} + +// Get class name, virtual since each invidiual type will have different name +FString USLLandscapeIndividual::CalcDefaultClassValue() +{ + return GetTypeName(); +} + +// Private init implementation +bool USLLandscapeIndividual::InitImpl() +{ + if (HasValidLandscapeActor() || SetLandscapeActor()) + { + + OriginalMaterials.Empty(); + OriginalMaterials.Add(LandscapeActor->LandscapeMaterial); + return true; + } + return false; +} + +// Private load implementation +bool USLLandscapeIndividual::LoadImpl(bool bTryImport) +{ + return true; +} + +// Clear all values of the individual +void USLLandscapeIndividual::InitReset() +{ + LoadReset(); + LandscapeActor = nullptr; + OriginalMaterials.Empty(); + SetIsInit(false); +} + +// Clear all data of the individual +void USLLandscapeIndividual::LoadReset() +{ + SetIsLoaded(false); +} + + +// Check if the static mesh component is set +bool USLLandscapeIndividual::HasValidLandscapeActor() const +{ + return LandscapeActor && LandscapeActor->IsValidLowLevel() && !LandscapeActor->IsPendingKill(); +} + +// Set the static mesh component +bool USLLandscapeIndividual::SetLandscapeActor() +{ + if (ALandscape* AsLandscape = Cast(ParentActor)) + { + LandscapeActor = AsLandscape; + return true; + } + else + { + UE_LOG(LogTemp, Error, TEXT("%s::%d %s's parent actor is not a ALandscape, this should not happen.."), + *FString(__FUNCTION__), __LINE__, *GetFullName()); + return false; + } +} diff --git a/pool/shard007/C++/0095864_paste_range_command.cpp b/pool/shard007/C++/0095864_paste_range_command.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb46f8def79b170c1048b6d10f1203d28d0bcf0f --- /dev/null +++ b/pool/shard007/C++/0095864_paste_range_command.cpp @@ -0,0 +1,104 @@ +/** + * \file + * Copyright (C) 2006-2010 Jedox AG + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License (Version 2) as published + * by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html. + * + * 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 + * + * You may obtain a copy of the License at + * + * + * http://www.jedox.com/license_palo_bi_suite.txt + * + * + * If you are developing and distributing open source applications under the + * GPL License, then you are free to use Worksheetserver under the GPL License. + * For OEMs, ISVs, and VARs who distribute Worksheetserver with their products, + * and do not license and distribute their source code under the GPL, Jedox provides + * a flexible OEM Commercial License. + * + * \author + * Florian Schaper + */ + +#include "precompiled_header.hpp" +#include "wss/paste_range_command.hpp" +#include "wss/invalid_worksheet_exception.hpp" +#include "wss/worksheet.hpp" +#include "wss/range.hpp" + +paste_range_command::paste_range_command( session& s, const sheet_range& target, clipboard::clipboard_id_type id, int paste_type /* = content_type::all_plus_cf */ ) + : abstract_undoable_command( s ) + , m_target( target ) + , m_clipboard_id( id ) + , m_paste_type( paste_type ) +{ + if ( m_paste_type & content_type::style ) { + m_paste_type |= content_type::border; + } +} + +void paste_range_command::execute() +{ + shared_worksheet_type ws = lock_worksheet_and_throw_if_not_there(); + + clipboard& cb = m_session.clipboard(); + + m_saved_clip_entry = cb.get( m_clipboard_id ); + if ( ( *m_saved_clip_entry ).type() != clipboard_entry::entry::range ) { + return; + } + + range source = boost::any_cast( ( *m_saved_clip_entry ).get() ); + range target = ws->range( m_target ); +#ifdef CORE_DO_UNDO_SUPPORT + if ( supports_do_undo::check( ws ) ) { + m_old_value_target = target.value( m_session ); + } +#endif + switch ( ( *m_saved_clip_entry ).method() ) { + case clipboard_entry::method::copy: + source.copy( m_session, target, false, insert_shift_direction::automatic, m_paste_type ); + break; + + case clipboard_entry::method::cut: + source.move( m_session, target, false, copy_format_from::left_or_above, insert_shift_direction::automatic, m_paste_type ); + break; + + case clipboard_entry::method::copy_fill: + source.copy_fill( m_session, target ); //TODO: m_paste_type + break; + + case clipboard_entry::method::copy_move: + source.copy_move( m_session, target, insert_shift_direction::automatic, m_paste_type ); + break; + + default: + assert( !"unknown clipboard command issued" ); + } +} + +void paste_range_command::un_execute() +{ +#ifdef CORE_DO_UNDO_SUPPORT + shared_worksheet_type ws = lock_worksheet_and_throw_if_not_there(); + assert( "un_execute called on a command that is on a temporary wb or on a cloned sheet!" && supports_do_undo::check( ws ) ); + range target = ws->range( m_target ); + target.value( m_session, m_old_value_target ); + if ( m_saved_clip_entry ) { + m_session.clipboard().add( *m_saved_clip_entry ); + } +#endif +} + +DEFINE_CLONEABLE( paste_range_command ); diff --git a/pool/shard007/C++/0095868_CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08.cpp b/pool/shard007/C++/0095868_CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08.cpp new file mode 100644 index 0000000000000000000000000000000000000000..63b4532125261095e72f899bd86058eb6fd3fd1d --- /dev/null +++ b/pool/shard007/C++/0095868_CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08.cpp @@ -0,0 +1,161 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml +Template File: sources-sink-08.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: declare Data buffer is declared on the stack + * GoodSource: Allocate memory on the heap + * Sink: + * BadSink : Print then free data + * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#include + +/* The two function below always return the same value, so a tool + should be able to identify that calls to the functions will always + return a fixed value. */ +static int staticReturnsTrue() +{ + return 1; +} + +static int staticReturnsFalse() +{ + return 0; +} + +namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08 +{ + +#ifndef OMITBAD + +void bad() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + if(staticReturnsTrue()) + { + { + /* FLAW: data is allocated on the stack and deallocated in the BadSink */ + twoIntsStruct dataBuffer[100]; + { + size_t i; + for (i = 0; i < 100; i++) + { + dataBuffer[i].intOne = 1; + dataBuffer[i].intTwo = 1; + } + } + data = dataBuffer; + } + } + printStructLine(&data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + delete [] data; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ +static void goodG2B1() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + if(staticReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + { + /* FIX: data is allocated on the heap and deallocated in the BadSink */ + twoIntsStruct * dataBuffer = new twoIntsStruct[100]; + { + size_t i; + for (i = 0; i < 100; i++) + { + dataBuffer[i].intOne = 1; + dataBuffer[i].intTwo = 1; + } + } + data = dataBuffer; + } + } + printStructLine(&data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + delete [] data; +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + if(staticReturnsTrue()) + { + { + /* FIX: data is allocated on the heap and deallocated in the BadSink */ + twoIntsStruct * dataBuffer = new twoIntsStruct[100]; + { + size_t i; + for (i = 0; i < 100; i++) + { + dataBuffer[i].intOne = 1; + dataBuffer[i].intTwo = 1; + } + } + data = dataBuffer; + } + } + printStructLine(&data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + delete [] data; +} + +void good() +{ + goodG2B1(); + goodG2B2(); +} + +#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 CWE590_Free_Memory_Not_on_Heap__delete_array_struct_declare_08; /* 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/shard007/C++/0095869_carbon_connector_test.cc b/pool/shard007/C++/0095869_carbon_connector_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..529ed22173187c3b7b7baa8c59dcdd27f6e5a4b4 --- /dev/null +++ b/pool/shard007/C++/0095869_carbon_connector_test.cc @@ -0,0 +1,276 @@ +/* graphite_connector_test.cc + Jeremy Barnes, 3 August 2011 + Copyright (c) 2011 Datacratic. All rights reserved. + + Test for the carbon connector. +*/ + +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK + +#include +#include "soa/service/carbon_connector.h" +#include "jml/arch/atomic_ops.h" +#include "jml/arch/timers.h" +#include "soa/service/passive_endpoint.h" +#include + + +using namespace std; +using namespace Datacratic; +using namespace ML; + + +BOOST_AUTO_TEST_CASE( test_counter_aggregator ) +{ + // We record events to aggregate from multiple threads with simultaneous + // occasional resets of the counter and we make sure that no events are + // lost. + + cerr << "counter aggregator" << endl; + + CounterAggregator aggregator; + + uint64_t nthreads = 8, iter = 100000; + boost::barrier barrier(nthreads); + uint64_t total = 0; + boost::thread_group tg; + for (unsigned i = 0; i < nthreads; ++i) { + auto doThread = [&] () + { + barrier.wait(); + + for (unsigned i = 0; i < iter; ++i) { + aggregator.record(1.0); + + if (random() % 100 == 0) { + double val = aggregator.reset().first; + uint64_t val2 = val; + + //cerr << "val2 = " << val2 << endl; + + //BOOST_CHECK_EQUAL(val, val2); + + atomic_add(total, val2); + } + } + }; + + tg.create_thread(doThread); + } + + tg.join_all(); + + double val = aggregator.reset().first; + uint64_t val2 = val; + + //cerr << "val2 = " << val2 << endl; + + BOOST_CHECK_EQUAL(val, val2); + atomic_add(total, val2); + + BOOST_CHECK_EQUAL(total, iter * nthreads); +} + +BOOST_AUTO_TEST_CASE( test_gauge_aggregator ) +{ + // We record events to aggregate from multiple threads with simultaneous + // occasional resets of the counter and we make sure that no events are + // lost. + + cerr << "gauge aggregator" << endl; + + GaugeAggregator aggregator; + + uint64_t nthreads = 8, iter = 100000; + boost::barrier barrier(nthreads); + boost::thread_group tg; + + boost::mutex mutex; + + ML::distribution allValues; + + for (unsigned i = 0; i < nthreads; ++i) { + auto doThread = [&] () + { + ML::distribution threadValues; + + barrier.wait(); + + for (unsigned i = 0; i < iter; ++i) { + aggregator.record(1.0 + (i % 2)); + + if (random() % 1000 == 0) { + ML::distribution * values + = aggregator.reset().first; + + threadValues.insert(threadValues.end(), + values->begin(), values->end()); + + delete values; + } + } + + boost::lock_guard lock(mutex); + allValues.insert(allValues.end(), + threadValues.begin(), threadValues.end()); + }; + + tg.create_thread(doThread); + } + + tg.join_all(); + + ML::distribution * values + = aggregator.reset().first; + + allValues.insert(allValues.end(), + values->begin(), values->end()); + std::sort(allValues.begin(), allValues.end()); + + BOOST_CHECK_EQUAL(allValues.size(), iter * nthreads); + BOOST_CHECK_EQUAL(allValues.mean(), 1.5); + BOOST_CHECK_EQUAL(allValues.std(), 0.5); +} + +BOOST_AUTO_TEST_CASE( test_multi_aggregator ) +{ + std::vector readings; + + boost::mutex m; + m.lock(); + + auto recordReading = [&] (const std::vector & stats) + { + cerr << "got reading of " << stats.size() << " counters" + << endl; + for (unsigned i = 0; i < stats.size(); ++i) + cerr << stats[i].name << " " << stats[i].value << endl; + readings.insert(readings.end(), stats.begin(), stats.end()); + + m.unlock(); + }; + + MultiAggregator agg("hello", recordReading, 0.0); + + for (unsigned i = 0; i <= 100; ++i) + agg.recordLevel("bonus", i); + + agg.dump(); + + // agg.dump() will eventually call recordReading from another thread, + // which will unlock m when it's finished, allowing this code to + // proceed. + + m.lock(); + + BOOST_REQUIRE_EQUAL(readings.size(), 8); + BOOST_CHECK_EQUAL(readings[0].name, "bonus.mean"); + BOOST_CHECK_EQUAL(readings[0].value, 50.0); +} + +struct FakeCarbon : public PassiveEndpointT { + + FakeCarbon() + : PassiveEndpointT("Carbon"), + numConnections(0), numDisconnections(0), + numDataMessages(0), numErrorMessages(0) + { + } + + struct CarbonConnection: public PassiveConnectionHandler { + + CarbonConnection(FakeCarbon * owner) + : owner(owner) + { + } + + FakeCarbon * owner; + + /** Function called out to when we got some data */ + virtual void handleData(const std::string & data) + { + cerr << "got data " << data << endl; + ML::atomic_inc(owner->numDataMessages); + } + + /** Function called out to when we got an error from the socket. */ + virtual void handleError(const std::string & message) + { + cerr << "got error " << message << endl; + ML::atomic_inc(owner->numErrorMessages); + } + + virtual void onGotTransport() + { + cerr << "on got transport" << endl; + startReading(); + } + + virtual void handleDisconnect() + { + cerr << "got disconnection" << endl; + ML::atomic_inc(owner->numDisconnections); + closeWhenHandlerFinished(); + } + }; + + virtual std::shared_ptr + makeNewHandler() + { + ML::atomic_inc(numConnections); + cerr << "got new connection" << endl; + return std::make_shared(this); + } + + int numConnections, numDisconnections, numDataMessages, numErrorMessages; +}; + +BOOST_AUTO_TEST_CASE( test_multiple_carbon_connectors ) +{ + FakeCarbon carbon1, carbon2; + int port1 = carbon1.init(); + int port2 = carbon2.init(); + + string addr1 = ML::format("localhost:%d", port1); + string addr2 = ML::format("localhost:%d", port2); + + cerr << "fake carbons are on " << port1 << " and " << port2 << endl; + + vector addrs({ addr1, addr2 }); + + CarbonConnector x(addrs, "test"); + + for (unsigned i = 0; i < 1000; ++i) { + x.recordHit("hit"); + } + + x.dump(); + + ML::sleep(0.5); + + BOOST_CHECK_EQUAL(carbon1.numConnections, 1); + BOOST_CHECK_EQUAL(carbon2.numConnections, 1); + BOOST_CHECK_EQUAL(carbon1.numDisconnections, 0); + BOOST_CHECK_EQUAL(carbon2.numDisconnections, 0); + BOOST_CHECK_EQUAL(carbon1.numDataMessages, 1); + BOOST_CHECK_EQUAL(carbon2.numDataMessages, 1); + BOOST_CHECK_EQUAL(carbon1.numErrorMessages, 0); + BOOST_CHECK_EQUAL(carbon2.numErrorMessages, 0); + + carbon1.shutdown(); + + for (unsigned i = 0; i < 1000; ++i) { + x.recordHit("hit"); + } + + x.dump(); + + ML::sleep(1.0); + + carbon1.init(port1); + + ML::sleep(10.0); + + cerr << "done carbon connectors" << endl; +} diff --git a/pool/shard007/C++/0095870_CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82a.cpp b/pool/shard007/C++/0095870_CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..494c7f90bfa162bcfe3d586c6192296a06c757c2 --- /dev/null +++ b/pool/shard007/C++/0095870_CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82a.cpp @@ -0,0 +1,92 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82a.cpp +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml +Template File: sources-sink-82a.tmpl.cpp +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sinks: ncpy + * BadSink : Copy data to string using wcsncpy + * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer + * + * */ + +#include "std_testcase.h" +#include "CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82.h" + +namespace CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82 +{ + +#ifndef OMITBAD + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[100]; + data = dataBuffer; + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + wmemset(data, L'A', 100-1); /* fill with L'A's */ + data[100-1] = L'\0'; /* null terminate */ + CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82_bad; + baseObject->action(data); + delete baseObject; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100]; + data = dataBuffer; + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82_goodG2B; + baseObject->action(data); + delete baseObject; +} + +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 CWE121_Stack_Based_Buffer_Overflow__CWE806_wchar_t_declare_ncpy_82; /* 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/shard007/C++/0095872_vmPSOperations.cpp b/pool/shard007/C++/0095872_vmPSOperations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a8f347bc8dbc55f89ba50b1b7ab1f1fc87edace --- /dev/null +++ b/pool/shard007/C++/0095872_vmPSOperations.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp" +#include "gc_implementation/parallelScavenge/psMarkSweep.hpp" +#include "gc_implementation/parallelScavenge/psScavenge.hpp" +#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp" +#include "gc_implementation/parallelScavenge/vmPSOperations.hpp" +#include "memory/gcLocker.inline.hpp" +#include "utilities/dtrace.hpp" + +// The following methods are used by the parallel scavenge collector +VM_ParallelGCFailedAllocation::VM_ParallelGCFailedAllocation(size_t size, + unsigned int gc_count) : + VM_GC_Operation(gc_count, GCCause::_allocation_failure), + _size(size), + _result(NULL) +{ +} + +void VM_ParallelGCFailedAllocation::doit() { + SvcGCMarker sgcm(SvcGCMarker::MINOR); + + ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); + assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "must be a ParallelScavengeHeap"); + + GCCauseSetter gccs(heap, _gc_cause); + _result = heap->failed_mem_allocate(_size); + + if (_result == NULL && GC_locker::is_active_and_needs_gc()) { + set_gc_locked(); + } +} + +// Only used for System.gc() calls +VM_ParallelGCSystemGC::VM_ParallelGCSystemGC(unsigned int gc_count, + unsigned int full_gc_count, + GCCause::Cause gc_cause) : + VM_GC_Operation(gc_count, gc_cause, full_gc_count, true /* full */) +{ +} + +void VM_ParallelGCSystemGC::doit() { + SvcGCMarker sgcm(SvcGCMarker::FULL); + + ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); + assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, + "must be a ParallelScavengeHeap"); + + GCCauseSetter gccs(heap, _gc_cause); + if (_gc_cause == GCCause::_gc_locker || _gc_cause == GCCause::_wb_young_gc + DEBUG_ONLY(|| _gc_cause == GCCause::_scavenge_alot)) { + // If (and only if) the scavenge fails, this will invoke a full gc. + heap->invoke_scavenge(); + } else { + heap->do_full_collection(false); + } +} diff --git a/pool/shard007/C++/0095876_BrokerageMainGUI.cpp b/pool/shard007/C++/0095876_BrokerageMainGUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6c366a2504737cbf8a886e9510596b893360cee --- /dev/null +++ b/pool/shard007/C++/0095876_BrokerageMainGUI.cpp @@ -0,0 +1,107 @@ +#include "Graph.h" +#include "GUI.h" +#include "std_lib_facilities_4.h" +#include "Brokerage_window.h" +#include +int main(){ + vector contractions = {"1st", "2nd", "3rd"}; + vector brokerages; + vector brk_ptrs; + bool breaker = false; + for (int i = 0; i < 3; ++i) { + string s, filename; + cout << "Setting name of " << contractions.at(i) << " Brokerage..." << endl; + cout << "Enter Brokerage name as a string (no spaces): " << endl; + cin >> s; + for (int i = 0; i < brokerages.size(); ++i) { + if (brokerages.at(i).get_name() == s) { + error("A Brokerage with that name already exists."); + } + } + cout << "Enter input File Name as a string with no spaces or special characters (e.g. BrokerFile1, or Q to skip input File read):"; + cin >> filename; + Brokerage b(s); + if (filename == "Q") + cout << "Skipping input File read and instead initializing a new Brokerage state" << endl; + else { + ifstream input_file; + input_file.open(filename); + string next_line; + if (input_file.is_open()) { //Ensures that ifstream is successful in opening the file. + while (getline(input_file, next_line)) { + char data_type = next_line.at(0); //The first character of every line (used to determine type of succeeding data) + next_line = next_line.substr(2, next_line.size()-2); //Remove first character and its succeeding space + istringstream iss = istringstream(next_line); + switch (data_type) { + case 'B': { + string broke_name = iss.str().erase(iss.str().size()-1); + try { + if (b.get_name() != broke_name) { + error("The name in the file and the name inputted do not match."); + } + } catch (...) { + cout << "Error: The name in the file and the name inputted do not match." << endl; + breaker = true; + break; + } + break; + } + case 'P': { //Patron type + Patron patron; + iss >> patron; //Initialize patron from istringstream + b.add_patron(patron); //Add patron to brokerage + break; + } + case 'X': { //Transaction type + Transaction transaction; + iss >> transaction; + b.add_transaction(transaction); + break; + } + default: + break; + } + } + } + else { + cout << "Error: Can't open input File " << filename << endl; + break; + } + input_file.close(); + } + if (breaker) { + break; + } + cout << b.get_name() << endl; + brokerages.push_back(b); + } + for (int i = 0; i < brokerages.size(); ++i) { + brk_ptrs.push_back(&brokerages.at(i)); + } + cout << endl; + try { + Brokerage_window b1(Point(200,300), 1300, 450, brk_ptrs.at(0)->get_name(), brk_ptrs, brk_ptrs.at(0)); + Brokerage_window b2(Point(200,300), 1300, 450, brk_ptrs.at(1)->get_name(), brk_ptrs, brk_ptrs.at(1)); + Brokerage_window b3(Point(200,300), 1300, 450, brk_ptrs.at(2)->get_name(), brk_ptrs, brk_ptrs.at(2)); + b1.wait_for_button(); + for (int i = 0; i < brokerages.size(); ++i) { + string file_name; + cout << "Closing Brokerage " << i+1 << " - " << brokerages.at(i).get_name() << "..." << endl; + cout << "Enter output File Name as a string with no spaces or special characters (e.g. BrokerFile1, or Q to quit without saving):"<> file_name; + if (file_name != "Q") { + try { + ofstream out(file_name); + cout << "Saving Brokerage state to output File " << file_name << endl; + out << brokerages.at(i); + cout << "Done saving Brokerage state to output File " << file_name << endl; + } catch (...) { + cout << "Error saving file... Try again." << endl; + } + } + } + } + catch (...) {} + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0095878_TestSyncHTTP.cpp b/pool/shard007/C++/0095878_TestSyncHTTP.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f82ec1435cf803515509f37c44e1fd9539908524 --- /dev/null +++ b/pool/shard007/C++/0095878_TestSyncHTTP.cpp @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (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.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is mozilla.org code. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include +#include +#include +#include +#include +#include +#include + +/* + * Test synchronous HTTP. + */ + +#define RETURN_IF_FAILED(rv, what) \ + PR_BEGIN_MACRO \ + if (NS_FAILED(rv)) { \ + printf(what ": failed - %08x\n", rv); \ + return -1; \ + } \ + PR_END_MACRO + +struct TestContext { + nsCOMPtr uri; + nsCOMPtr channel; + nsCOMPtr inputStream; + PRTime t1, t2; + PRUint32 bytesRead, totalRead; + + TestContext() + : t1(0), t2(0), bytesRead(0), totalRead(0) + { printf("TestContext [this=%p]\n", (void*)this); } + ~TestContext() + { printf("~TestContext [this=%p]\n", (void*)this); } +}; + +int +main(int argc, char **argv) +{ + nsresult rv; + TestContext *c; + int i, nc=0, npending=0; + char buf[256]; + + if (argc < 2) { + printf("Usage: TestSyncHTTP \n"); + return -1; + } + + c = new TestContext[argc-1]; + + for (i=0; i<(argc-1); ++i, ++nc) { + rv = NS_NewURI(getter_AddRefs(c[i].uri), argv[i+1]); + RETURN_IF_FAILED(rv, "NS_NewURI"); + + rv = NS_OpenURI(getter_AddRefs(c[i].channel), c[i].uri, nsnull, nsnull); + RETURN_IF_FAILED(rv, "NS_OpenURI"); + + nsCOMPtr httpChannel = do_QueryInterface(c[i].channel); + if (httpChannel) + httpChannel->SetOpenHasEventQueue(PR_FALSE); + + // initialize these fields for reading + c[i].bytesRead = 1; + c[i].totalRead = 0; + } + + for (i=0; iOpen(getter_AddRefs(c[i].inputStream)); + RETURN_IF_FAILED(rv, "nsIChannel::OpenInputStream"); + } + + npending = nc; + while (npending) { + for (i=0; i 0) { + rv = c[i].inputStream->Read(buf, sizeof buf, &c[i].bytesRead); + RETURN_IF_FAILED(rv, "nsIInputStream::Read"); + c[i].totalRead += c[i].bytesRead; + + if (c[i].bytesRead == 0) { + c[i].t2 = PR_Now(); + printf("finished GET of: %s\n", argv[i+1]); + printf("total read: %u bytes\n", c[i].totalRead); + printf("total read time: %0.3f\n", + ((double) (c[i].t2 - c[i].t1))/1000000.0); + npending--; + } + } + } + } + + delete[] c; + + NS_ShutdownXPCOM(nsnull); + return 0; +} diff --git a/pool/shard007/C++/0095880_DeviceConfig.cpp b/pool/shard007/C++/0095880_DeviceConfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac3c7a75e1e09d36443e504e48cfdceb2608f095 --- /dev/null +++ b/pool/shard007/C++/0095880_DeviceConfig.cpp @@ -0,0 +1,297 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2014 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "Profile/DeviceConfig.hpp" +#include "Profile/Profile.hpp" +#include "Util/Macros.hpp" +#include "Interface.hpp" +#include "Device/Config.hpp" + +#ifdef ANDROID +#include "Android/BluetoothHelper.hpp" +#include "Java/Global.hpp" +#endif + +#include + +static const char *const port_type_strings[] = { + "disabled", + "serial", + "rfcomm", + "rfcomm_server", + "ioio_uart", + "droidsoar_v2", + "nunchuck", + "i2c_baro", + "ioio_voltage", + "auto", + "internal", + "tcp_client", + "tcp_listener", + "udp_listener", + "pty", + NULL +}; + +static const char * +MakeDeviceSettingName(char *buffer, const char *prefix, unsigned n, + const char *suffix) +{ + strcpy(buffer, prefix); + + if (n > 0) + sprintf(buffer + strlen(buffer), "%u", n + 1); + + strcat(buffer, suffix); + + return buffer; +} + +static bool +StringToPortType(const char *value, DeviceConfig::PortType &type) +{ + for (auto i = port_type_strings; *i != NULL; ++i) { + if (StringIsEqual(value, *i)) { + type = (DeviceConfig::PortType)std::distance(port_type_strings, i); + return true; + } + } + + return false; +} + +static bool +ReadPortType(unsigned n, DeviceConfig::PortType &type) +{ + char name[64]; + + MakeDeviceSettingName(name, "Port", n, "Type"); + + const char *value = Profile::Get(name); + return value != NULL && StringToPortType(value, type); +} + +static bool +LoadPath(DeviceConfig &config, unsigned n) +{ + char buffer[64]; + MakeDeviceSettingName(buffer, "Port", n, "Path"); + return Profile::Get(buffer, config.path); +} + +static bool +LoadPortIndex(DeviceConfig &config, unsigned n) +{ + char buffer[64]; + MakeDeviceSettingName(buffer, "Port", n, "Index"); + + unsigned index; + if (!Profile::Get(buffer, index)) + return false; + + /* adjust the number, compatibility quirk for XCSoar 5 */ + if (index < 10) + ++index; + else if (index == 10) + index = 0; + + TCHAR path[64]; + _stprintf(path, _T("COM%u:"), index); + config.path = path; + return true; +} + +void +Profile::GetDeviceConfig(unsigned n, DeviceConfig &config) +{ + char buffer[64]; + + bool have_port_type = ReadPortType(n, config.port_type); + + MakeDeviceSettingName(buffer, "Port", n, "BluetoothMAC"); + Get(buffer, config.bluetooth_mac); + + MakeDeviceSettingName(buffer, "Port", n, "IOIOUartID"); + Get(buffer, config.ioio_uart_id); + + MakeDeviceSettingName(buffer, "Port", n, "IPAddress"); + if (!Get(buffer, config.ip_address)) + config.ip_address.clear(); + + MakeDeviceSettingName(buffer, "Port", n, "TCPPort"); + if (!Get(buffer, config.tcp_port)) + config.tcp_port = 4353; + + config.path.clear(); + if ((!have_port_type || + config.port_type == DeviceConfig::PortType::SERIAL) && + !LoadPath(config, n) && LoadPortIndex(config, n)) + config.port_type = DeviceConfig::PortType::SERIAL; + + MakeDeviceSettingName(buffer, "Port", n, "BaudRate"); + if (!Get(buffer, config.baud_rate)) { + /* XCSoar before 6.2 used to store a "speed index", not the real + baud rate - try to import the old settings */ + + static constexpr unsigned speed_index_table[] = { + 1200, + 2400, + 4800, + 9600, + 19200, + 38400, + 57600, + 115200 + }; + + MakeDeviceSettingName(buffer, "Speed", n, "Index"); + unsigned speed_index; + if (Get(buffer, speed_index) && + speed_index < ARRAY_SIZE(speed_index_table)) + config.baud_rate = speed_index_table[speed_index]; + } + + MakeDeviceSettingName(buffer, "Port", n, "BulkBaudRate"); + if (!Get(buffer, config.bulk_baud_rate)) + config.bulk_baud_rate = 0; + + strcpy(buffer, "DeviceA"); + buffer[strlen(buffer) - 1] += n; + Get(buffer, config.driver_name); + + MakeDeviceSettingName(buffer, "Port", n, "Enabled"); + Get(buffer, config.enabled); + + MakeDeviceSettingName(buffer, "Port", n, "SyncFromDevice"); + Get(buffer, config.sync_from_device); + + MakeDeviceSettingName(buffer, "Port", n, "SyncToDevice"); + Get(buffer, config.sync_to_device); + + MakeDeviceSettingName(buffer, "Port", n, "K6Bt"); + Get(buffer, config.k6bt); + + MakeDeviceSettingName(buffer, "Port", n, "I2C_Bus"); + Get(buffer, config.i2c_bus); + + MakeDeviceSettingName(buffer, "Port", n, "I2C_Addr"); + Get(buffer, config.i2c_addr); + + MakeDeviceSettingName(buffer, "Port", n, "PressureUse"); + GetEnum(buffer, config.press_use); + + MakeDeviceSettingName(buffer, "Port", n, "SensorOffset"); + Get(buffer, config.sensor_offset); + + MakeDeviceSettingName(buffer, "Port", n, "SensorFactor"); + Get(buffer, config.sensor_factor); +} + +static const char * +PortTypeToString(DeviceConfig::PortType type) +{ + const unsigned i = (unsigned)type; + return i < ARRAY_SIZE(port_type_strings) + ? port_type_strings[i] + : NULL; +} + +static void +WritePortType(unsigned n, DeviceConfig::PortType type) +{ + const char *value = PortTypeToString(type); + if (value == NULL) + return; + + char name[64]; + MakeDeviceSettingName(name, "Port", n, "Type"); + Profile::Set(name, value); +} + +void +Profile::SetDeviceConfig(unsigned n, const DeviceConfig &config) +{ + char buffer[64]; + + WritePortType(n, config.port_type); + + MakeDeviceSettingName(buffer, "Port", n, "BluetoothMAC"); + Set(buffer, config.bluetooth_mac); + + MakeDeviceSettingName(buffer, "Port", n, "IOIOUartID"); + Set(buffer, config.ioio_uart_id); + + MakeDeviceSettingName(buffer, "Port", n, "Path"); + Set(buffer, config.path); + + MakeDeviceSettingName(buffer, "Port", n, "BaudRate"); + Set(buffer, config.baud_rate); + + MakeDeviceSettingName(buffer, "Port", n, "BulkBaudRate"); + Set(buffer, config.bulk_baud_rate); + + MakeDeviceSettingName(buffer, "Port", n, "IPAddress"); + Set(buffer, config.ip_address); + + MakeDeviceSettingName(buffer, "Port", n, "TCPPort"); + Set(buffer, config.tcp_port); + + strcpy(buffer, "DeviceA"); + buffer[strlen(buffer) - 1] += n; + Set(buffer, config.driver_name); + + MakeDeviceSettingName(buffer, "Port", n, "Enabled"); + Set(buffer, config.enabled); + + MakeDeviceSettingName(buffer, "Port", n, "SyncFromDevice"); + Set(buffer, config.sync_from_device); + + MakeDeviceSettingName(buffer, "Port", n, "SyncToDevice"); + Set(buffer, config.sync_to_device); + + MakeDeviceSettingName(buffer, "Port", n, "K6Bt"); + Set(buffer, config.k6bt); + + MakeDeviceSettingName(buffer, "Port", n, "I2C_Bus"); + Set(buffer, config.i2c_bus); + + MakeDeviceSettingName(buffer, "Port", n, "I2C_Addr"); + Set(buffer, config.i2c_addr); + + MakeDeviceSettingName(buffer, "Port", n, "PressureUse"); + SetEnum(buffer, config.press_use); + + MakeDeviceSettingName(buffer, "Port", n, "SensorOffset"); + fixed offset = DeviceConfig::UsesCalibration(config.port_type) ? config.sensor_offset : fixed(0); + // Has new calibration data been delivered ? + if (CommonInterface::Basic().sensor_calibration_available) + offset = CommonInterface::Basic().sensor_calibration_offset; + Set(buffer, offset); + + MakeDeviceSettingName(buffer, "Port", n, "SensorFactor"); + fixed factor = DeviceConfig::UsesCalibration(config.port_type) ? config.sensor_factor : fixed(0); + // Has new calibration data been delivered ? + if (CommonInterface::Basic().sensor_calibration_available) + factor = CommonInterface::Basic().sensor_calibration_factor; + Set(buffer, factor); +} diff --git a/pool/shard007/C++/0095889_SLEPMachine.cpp b/pool/shard007/C++/0095889_SLEPMachine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85cf37dde26e076ad43daf6b6bf6c1cd9dafaaed --- /dev/null +++ b/pool/shard007/C++/0095889_SLEPMachine.cpp @@ -0,0 +1,105 @@ +/* + * 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. + * + * Written (W) 2012 Sergey Lisitsyn + * Copyright (C) 2012 Sergey Lisitsyn + */ + +#include +#include + +namespace shogun +{ + +CSLEPMachine::CSLEPMachine() : + CLinearMachine(), m_z(1.0) +{ +} + +CSLEPMachine::CSLEPMachine( + float64_t z, CDotFeatures* train_features, + CLabels* train_labels) : + CLinearMachine(), m_z(1.0) +{ + set_z(z); + set_q(2.0); + set_features(train_features); + set_labels(train_labels); + set_termination(2); + set_regularization(0); + set_tolerance(1e-3); + set_max_iter(1000); +} + +CSLEPMachine::~CSLEPMachine() +{ +} + +void CSLEPMachine::register_parameters() +{ + SG_ADD(&m_z, "z", "regularization coefficient", MS_AVAILABLE); + SG_ADD(&m_q, "q", "q of L1/Lq", MS_AVAILABLE); + SG_ADD(&m_termination, "termination", "termination", MS_NOT_AVAILABLE); + SG_ADD(&m_regularization, "regularization", "regularization", MS_NOT_AVAILABLE); + SG_ADD(&m_tolerance, "tolerance", "tolerance", MS_NOT_AVAILABLE); + SG_ADD(&m_max_iter, "max_iter", "maximum number of iterations", MS_NOT_AVAILABLE); +} + +int32_t CSLEPMachine::get_max_iter() const +{ + return m_max_iter; +} +int32_t CSLEPMachine::get_regularization() const +{ + return m_regularization; +} +int32_t CSLEPMachine::get_termination() const +{ + return m_termination; +} +float64_t CSLEPMachine::get_tolerance() const +{ + return m_tolerance; +} +float64_t CSLEPMachine::get_z() const +{ + return m_z; +} +float64_t CSLEPMachine::get_q() const +{ + return m_q; +} + +void CSLEPMachine::set_max_iter(int32_t max_iter) +{ + ASSERT(max_iter>=0); + m_max_iter = max_iter; +} +void CSLEPMachine::set_regularization(int32_t regularization) +{ + ASSERT(regularization==0 || regularization==1); + m_regularization = regularization; +} +void CSLEPMachine::set_termination(int32_t termination) +{ + ASSERT(termination>=0 && termination<=4); + m_termination = termination; +} +void CSLEPMachine::set_tolerance(float64_t tolerance) +{ + ASSERT(tolerance>0.0); + m_tolerance = tolerance; +} +void CSLEPMachine::set_z(float64_t z) +{ + m_z = z; +} +void CSLEPMachine::set_q(float64_t q) +{ + m_q = q; +} + +} diff --git a/pool/shard007/C++/0095893_GSDirtyRect.cpp b/pool/shard007/C++/0095893_GSDirtyRect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..003353538d5a868b2330310c4d30de893d0b8093 --- /dev/null +++ b/pool/shard007/C++/0095893_GSDirtyRect.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2007-2009 Gabest + * http://www.gabest.org + * + * 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, 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 GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#include "stdafx.h" +#include "GSDirtyRect.h" + +GSDirtyRect::GSDirtyRect() + : psm(PSM_PSMCT32) +{ + left = top = right = bottom = 0; +} + +GSDirtyRect::GSDirtyRect(const GSVector4i& r, uint32 psm) + : psm(psm) +{ + left = r.left; + top = r.top; + right = r.right; + bottom = r.bottom; +} + +const GSVector4i GSDirtyRect::GetDirtyRect(const GIFRegTEX0& TEX0) const +{ + GSVector4i r; + + const GSVector2i src = GSLocalMemory::m_psm[psm].bs; + + if(psm != TEX0.PSM) + { + const GSVector2i dst = GSLocalMemory::m_psm[TEX0.PSM].bs; + + r.left = left * dst.x / src.x; + r.top = top * dst.y / src.y; + r.right = right * dst.x / src.x; + r.bottom = bottom * dst.y / src.y; + } + else + { + r = GSVector4i(left, top, right, bottom).ralign(src); + } + + return r; +} + +// + +const GSVector4i GSDirtyRectList::GetDirtyRectAndClear(const GIFRegTEX0& TEX0, const GSVector2i& size) +{ + if(!empty()) + { + GSVector4i r(INT_MAX, INT_MAX, 0, 0); + + for(const auto& dirty_rect : *this) + { + r = r.runion(dirty_rect.GetDirtyRect(TEX0)); + } + + clear(); + + const GSVector2i bs = GSLocalMemory::m_psm[TEX0.PSM].bs; + + return r.ralign(bs).rintersect(GSVector4i(0, 0, size.x, size.y)); + } + + return GSVector4i::zero(); +} diff --git a/pool/shard007/C++/0095895_OutputCondition.cpp b/pool/shard007/C++/0095895_OutputCondition.cpp new file mode 100644 index 0000000000000000000000000000000000000000..980aff6b096dc6b9400b44de693dc3baea4cfdc1 --- /dev/null +++ b/pool/shard007/C++/0095895_OutputCondition.cpp @@ -0,0 +1,63 @@ +/** Copyright (C) 2011-2016 GSI Helmholtz Centre for Heavy Ion Research GmbH + * + * @author Wesley W. Terpstra + * + ******************************************************************************* + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + ******************************************************************************* + */ +#define ETHERBONE_THROWS 1 + +#define __STDC_FORMAT_MACROS +#define __STDC_CONSTANT_MACROS + +#include "RegisteredObject.h" +#include "OutputCondition.h" +#include "ActionSink.h" + +namespace saftlib { + +OutputCondition::OutputCondition(const ConstructorType& args) + : Condition(args) +{ +} + +bool OutputCondition::getOn() const +{ + return tag == 2; +} + +void OutputCondition::setOn(bool v) +{ + uint32_t val = v?2:1; // 2 = turn-on, 1 = turn-off + + ownerOnly(); + if (val == tag) return; + uint32_t old = tag; + + tag = val; + try { + if (active) sink->compile(); + } catch (...) { + tag = old; + throw; + } +} + +std::shared_ptr OutputCondition::create(const ConstructorType& args) +{ + return RegisteredObject::create(args.objectPath, args); +} + +} diff --git a/pool/shard007/C++/0095896_wxSpringCommand.cpp b/pool/shard007/C++/0095896_wxSpringCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84d24f8551674d14522bba41db6d0eba0a126973 --- /dev/null +++ b/pool/shard007/C++/0095896_wxSpringCommand.cpp @@ -0,0 +1,30 @@ +/* This file is part of the Springlobby (GPL v2 or later), see COPYING */ + +#include "wxSpringCommand.h" + +unsigned short wxSpringCommand::type_id = 0x2345u; + +wxSpringCommand::wxSpringCommand( const wxString& name, const wxString& descr, int id ) : + wxCmd( id /*wxID_INVALID*/, name, descr ) +{ +} + +wxSpringCommand::~wxSpringCommand(void) +{ +} + +wxCmd* wxSpringCommand::Clone() const +{ + wxCmd* pNewCmd = new wxSpringCommand( this->GetName(), this->GetDescription(), this->GetId() ); + pNewCmd->DeepCopy(this); + return pNewCmd; +} + +int wxSpringCommand::GetType() const +{ + return this->type_id; +} + +void wxSpringCommand::Exec(wxObject*, wxEvtHandler*) +{ +} diff --git a/pool/shard007/C++/0095900_mlp_evaluator_test.cc b/pool/shard007/C++/0095900_mlp_evaluator_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc8b380019e6cba5b560617389bdb2848425599c --- /dev/null +++ b/pool/shard007/C++/0095900_mlp_evaluator_test.cc @@ -0,0 +1,60 @@ +/****************************************************************************** + * Copyright 2017 The Apollo Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h" + +#include "cyber/common/file.h" +#include "modules/prediction/common/kml_map_based_test.h" +#include "modules/prediction/container/obstacles/obstacles_container.h" + +namespace apollo { +namespace prediction { + +class MLPEvaluatorTest : public KMLMapBasedTest { + public: + void SetUp() override { + std::string file = + "modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt"; + CHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_)); + } + + protected: + apollo::perception::PerceptionObstacles perception_obstacles_; +}; + +TEST_F(MLPEvaluatorTest, OnLaneCase) { + EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(), + 1501183430.161906); + apollo::perception::PerceptionObstacle perception_obstacle = + perception_obstacles_.perception_obstacle(0); + EXPECT_EQ(perception_obstacle.id(), 1); + MLPEvaluator mlp_evaluator; + ObstaclesContainer container; + container.Insert(perception_obstacles_); + container.BuildLaneGraph(); + Obstacle* obstacle_ptr = container.GetObstacle(1); + EXPECT_TRUE(obstacle_ptr != nullptr); + mlp_evaluator.Evaluate(obstacle_ptr); + const Feature& feature = obstacle_ptr->latest_feature(); + const LaneGraph& lane_graph = feature.lane().lane_graph(); + for (const auto& lane_sequence : lane_graph.lane_sequence()) { + EXPECT_TRUE(lane_sequence.has_probability()); + } + mlp_evaluator.Clear(); +} + +} // namespace prediction +} // namespace apollo diff --git a/pool/shard007/C++/0095910_SVGFEImage.cpp b/pool/shard007/C++/0095910_SVGFEImage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..092736de0aa5513a06812a9b71db7fab56a9de92 --- /dev/null +++ b/pool/shard007/C++/0095910_SVGFEImage.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann + * Copyright (C) 2004, 2005 Rob Buis + * Copyright (C) 2005 Eric Seidel + * Copyright (C) 2010 Dirk Schulze + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#if ENABLE(SVG) && ENABLE(FILTERS) +#include "SVGFEImage.h" + +#include "AffineTransform.h" +#include "Filter.h" +#include "GraphicsContext.h" +#include "RenderObject.h" +#include "RenderTreeAsText.h" +#include "SVGFilter.h" +#include "SVGPreserveAspectRatio.h" +#include "SVGRenderingContext.h" +#include "SVGStyledElement.h" +#include "SVGURIReference.h" +#include "TextStream.h" + +namespace WebCore { + +FEImage::FEImage(Filter* filter, PassRefPtr image, const SVGPreserveAspectRatio& preserveAspectRatio) + : FilterEffect(filter) + , m_image(image) + , m_document(0) + , m_preserveAspectRatio(preserveAspectRatio) +{ +} + +FEImage::FEImage(Filter* filter, Document* document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio) + : FilterEffect(filter) + , m_document(document) + , m_href(href) + , m_preserveAspectRatio(preserveAspectRatio) +{ +} + +PassRefPtr FEImage::createWithImage(Filter* filter, PassRefPtr image, const SVGPreserveAspectRatio& preserveAspectRatio) +{ + return adoptRef(new FEImage(filter, image, preserveAspectRatio)); +} + +PassRefPtr FEImage::createWithIRIReference(Filter* filter, Document* document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio) +{ + return adoptRef(new FEImage(filter, document, href, preserveAspectRatio)); +} + +void FEImage::determineAbsolutePaintRect() +{ + SVGFilter* svgFilter = static_cast(filter()); + + FloatRect paintRect = svgFilter->absoluteTransform().mapRect(filterPrimitiveSubregion()); + FloatRect srcRect; + if (m_image) { + srcRect.setSize(m_image->size()); + m_preserveAspectRatio.transformRect(paintRect, srcRect); + } else if (RenderObject* renderer = referencedRenderer()) + srcRect = svgFilter->absoluteTransform().mapRect(renderer->repaintRectInLocalCoordinates()); + + if (clipsToBounds()) + paintRect.intersect(maxEffectRect()); + else + paintRect.unite(maxEffectRect()); + setAbsolutePaintRect(enclosingIntRect(paintRect)); +} + +RenderObject* FEImage::referencedRenderer() const +{ + if (!m_document) + return 0; + Element* hrefElement = SVGURIReference::targetElementFromIRIString(m_href, m_document); + if (!hrefElement || !hrefElement->isSVGElement()) + return 0; + return hrefElement->renderer(); +} + +void FEImage::platformApplySoftware() +{ + RenderObject* renderer = referencedRenderer(); + if (!m_image && !renderer) + return; + + ImageBuffer* resultImage = createImageBufferResult(); + if (!resultImage) + return; + + SVGFilter* svgFilter = static_cast(filter()); + FloatRect destRect = svgFilter->absoluteTransform().mapRect(filterPrimitiveSubregion()); + + FloatRect srcRect; + if (renderer) + srcRect = svgFilter->absoluteTransform().mapRect(renderer->repaintRectInLocalCoordinates()); + else { + srcRect = FloatRect(FloatPoint(), m_image->size()); + m_preserveAspectRatio.transformRect(destRect, srcRect); + } + + IntPoint paintLocation = absolutePaintRect().location(); + destRect.move(-paintLocation.x(), -paintLocation.y()); + + // FEImage results are always in ColorSpaceDeviceRGB + setResultColorSpace(ColorSpaceDeviceRGB); + + if (renderer) { + const AffineTransform& absoluteTransform = svgFilter->absoluteTransform(); + resultImage->context()->concatCTM(absoluteTransform); + + SVGElement* contextNode = toSVGElement(renderer->node()); + if (contextNode->isSVGStyledElement() && toSVGStyledElement(contextNode)->hasRelativeLengths()) { + SVGLengthContext lengthContext(contextNode); + float width = 0; + float height = 0; + + // If we're referencing an element with percentage units, eg. those values were resolved against the viewport. + // Build up a transformation that maps from the viewport space to the filter primitive subregion. + if (lengthContext.determineViewport(width, height)) + resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(0, 0, width, height), destRect)); + } + + AffineTransform contentTransformation; + SVGRenderingContext::renderSubtreeToImageBuffer(resultImage, renderer, contentTransformation); + return; + } + + resultImage->context()->drawImage(m_image.get(), ColorSpaceDeviceRGB, destRect, srcRect); +} + +void FEImage::dump() +{ +} + +TextStream& FEImage::externalRepresentation(TextStream& ts, int indent) const +{ + IntSize imageSize; + if (m_image) + imageSize = m_image->size(); + else if (RenderObject* renderer = referencedRenderer()) + imageSize = enclosingIntRect(renderer->repaintRectInLocalCoordinates()).size(); + writeIndent(ts, indent); + ts << "[feImage"; + FilterEffect::externalRepresentation(ts); + ts << " image-size=\"" << imageSize.width() << "x" << imageSize.height() << "\"]\n"; + // FIXME: should this dump also object returned by SVGFEImage::image() ? + return ts; +} + +} // namespace WebCore + +#endif // ENABLE(SVG) && ENABLE(FILTERS) diff --git a/pool/shard007/C++/0095917_prog.cpp b/pool/shard007/C++/0095917_prog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dfb7246cb28aaff401ab520b696d18eab92afe1 --- /dev/null +++ b/pool/shard007/C++/0095917_prog.cpp @@ -0,0 +1,63 @@ +#include +#include +#include + +template +void Print(Class instance) { + std::cout << instance << std::endl; +} + +void Print() { + std::cout << std::endl; +} + +const size_t kBase = 10; +const size_t kMaxStepNumber = 50; + +size_t Reverse(size_t number, size_t log) { + size_t answer = 0; + for (size_t index = 0; index <= log; ++index) { + answer = answer * kBase + number % kBase; + number /= kBase; + } + return answer; +} + +bool IsPalindrom(size_t number, size_t log) { + return number == Reverse(number, log); +} + +bool IsLychrelNumber(size_t number, size_t log, size_t begin) { + for (size_t index = 0; index < kMaxStepNumber; ++index) { + number += Reverse(number, log); + if (number >= begin * kBase) { + ++log; + begin *= kBase; + } + if (IsPalindrom(number, log)) { + return false; + } + } + return true; +} + + +int main() { + std::ofstream output_stream("output.txt"); + size_t max_log = 3; + + size_t lychrel_numbers_count = 0; + size_t begin = 10; + for (size_t log = 1; log <= max_log; ++log) { + for (size_t index = begin; index < begin * kBase; ++index) { + if (IsLychrelNumber(index, log, begin)) { + ++lychrel_numbers_count; + } + } + begin *= kBase; + } + output_stream << lychrel_numbers_count; + return 0; +} + + diff --git a/pool/shard007/C++/0095920_Utils.cpp b/pool/shard007/C++/0095920_Utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..911c1236ed7658f93b8869d1073c8089930b764b --- /dev/null +++ b/pool/shard007/C++/0095920_Utils.cpp @@ -0,0 +1,143 @@ +#include +#include +#include +#include "jniutils.h" + +jlong ptr2jlong(void *ptr) +{ + jlong jl = 0; + if (sizeof(void *) > sizeof(jlong)) + { fprintf(stderr, "sizeof(void *) > sizeof(jlong)\n"); + return 0; + //(* (int *) 0) = 0; // crash. + } + + memcpy(&jl, &ptr, sizeof(void *)); + return jl; +} + +void *jlong2ptr(jlong jl) +{ + + void *ptr = 0; + if (sizeof(void *) > sizeof(jlong)) + { fprintf(stderr, "sizeof(void *) > sizeof(jlong)\n"); + return 0; + //(* (int *) 0) = 0; // crash. + } + + memcpy(&ptr, &jl, sizeof(void *)); + return ptr; +} + +// Get a peer ptr from a Java object which extends Peer. The peer ptr is the C++ pointer to the C++ peer. +void *getPeerPtr(JNIEnv *pEnv, jobject jObj) +{ + // TODO: we need to make sure the object passed in really is of the right class. + jclass jPeerClass = pEnv->FindClass("net/sf/jdshow/Peered"); + jmethodID jPeerGetPeerPtrMethodID = pEnv->GetMethodID(jPeerClass, "getPeerPtr", "()J"); + jlong result = pEnv->CallLongMethod(jObj, jPeerGetPeerPtrMethodID); + return jlong2ptr(result); + +} + + +// the following functions are needed because on some (non-windows) platforms, +// a wchar_t is larger than a jchar. A jchar is always 2 bytes, and on windows +// a wchar_t is 2 bytes, but on linux a wchar_t is 4 bytes. +jchar wchar_t_to_jchar(wchar_t wc) +{ + return (jchar) wc; +} +void wchar_t_to_jchar_array(const wchar_t *src, jchar *dest) +{ int len = wcslen(src); + for (int i = 0; i <= len; ++i) + { dest[i] = wchar_t_to_jchar(src[i]); + } +} +// caller must delete result. +jchar *wchar_t_to_jchar_array_alloc(const wchar_t *src) +{ jchar *result = new jchar[wcslen(src) + 1]; + wchar_t_to_jchar_array(src, result); + return result; +} + +size_t jslen(const jchar *s) +{ size_t result = 0; + while (*s != 0) + { ++s; + ++result; + } + return result; +} +wchar_t jchar_to_wchar_t(jchar jc) +{ + return (wchar_t) jc; +} +void jchar_to_wchar_t_array(const jchar *src, wchar_t *dest) +{ int len = jslen(src); + for (int i = 0; i <= len; ++i) + { dest[i] = jchar_to_wchar_t(src[i]); + } +} +// caller must delete result. +wchar_t *jchar_to_wchar_t_array_alloc(const jchar *src) +{ wchar_t *result = new wchar_t[jslen(src) + 1]; + jchar_to_wchar_t_array(src, result); + return result; +} + + +GUID toGUID(JNIEnv *pEnv, jobject jGuid) +{ + GUID result; + memset(&result, 0, sizeof(GUID)); + + jclass jGuidClass = pEnv->FindClass("net/sf/jdshow/GUID"); + + jfieldID data1FieldID = pEnv->GetFieldID(jGuidClass, "Data1", "I"); + jint jData1 = pEnv->GetIntField(jGuid, data1FieldID); + result.Data1 = jData1; + + jfieldID data2FieldID = pEnv->GetFieldID(jGuidClass, "Data2", "S"); + jshort jData2 = pEnv->GetIntField(jGuid, data2FieldID); + result.Data2 = jData2; + + jfieldID data3FieldID = pEnv->GetFieldID(jGuidClass, "Data3", "S"); + jshort jData3 = pEnv->GetShortField(jGuid, data3FieldID); + result.Data3 = jData3; + + jfieldID data4FieldID = pEnv->GetFieldID(jGuidClass, "Data4", "[B"); + jbyteArray jData4 = (jbyteArray) pEnv->GetObjectField(jGuid, data4FieldID); + jbyte *jData4Bytes = GetByteArr(pEnv, jData4); + memcpy(result.Data4, jData4Bytes, sizeof(result.Data4)); + ReleaseByteArr(pEnv, jData4, jData4Bytes); + + return result; + + +} + +void fromGUID(JNIEnv *pEnv, GUID src, jobject jGuid) +{ + + jclass jGuidClass = pEnv->FindClass("net/sf/jdshow/GUID"); + + jfieldID data1FieldID = pEnv->GetFieldID(jGuidClass, "Data1", "I"); + pEnv->SetIntField(jGuid, data1FieldID, src.Data1); + + jfieldID data2FieldID = pEnv->GetFieldID(jGuidClass, "Data2", "S"); + pEnv->SetIntField(jGuid, data2FieldID, src.Data2); + + jfieldID data3FieldID = pEnv->GetFieldID(jGuidClass, "Data3", "S"); + pEnv->SetShortField(jGuid, data3FieldID, src.Data3); + + jfieldID data4FieldID = pEnv->GetFieldID(jGuidClass, "Data4", "[B"); + jbyteArray jData4 = (jbyteArray) pEnv->GetObjectField(jGuid, data4FieldID); + jbyte *jData4Bytes = GetByteArr(pEnv, jData4); + memcpy(jData4Bytes, src.Data4, sizeof(src.Data4)); + ReleaseByteArr(pEnv, jData4, jData4Bytes); + + + +} \ No newline at end of file diff --git a/pool/shard007/C++/0095921_2.cc b/pool/shard007/C++/0095921_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..eec7681259865f8f3de28019e209f4d123696af5 --- /dev/null +++ b/pool/shard007/C++/0095921_2.cc @@ -0,0 +1,50 @@ +// { dg-require-namedlocale "de_DE.UTF-8" } +// { dg-options " -std=gnu++11 " } + +// 2014-04-14 Rüdiger Sonderfeld + +// Copyright (C) 2014-2016 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 +// . + +// 27.7.5. (C++11) Extended manipulators [ext.manip]: put_time + +#include +#include +#include +#include +#include + +void test01() +{ + using namespace std; + bool test __attribute__((unused)) = true; + locale loc_c = locale::classic(); + locale loc_de = locale("de_DE.UTF-8"); + VERIFY( loc_de != loc_c ); + wistringstream iss; + iss.imbue(loc_de); + iss.str(L"Montag 1971"); + tm time1; + iss >> get_time(&time1, L"%A %Y"); + VERIFY(time1.tm_wday == 1); + VERIFY(time1.tm_year == 71); +} + +int main() +{ + test01(); +} diff --git a/pool/shard007/C++/0095924_faceloaditerator.cpp b/pool/shard007/C++/0095924_faceloaditerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0f0b0acd8a17290529c32a635e39998920d35e0 --- /dev/null +++ b/pool/shard007/C++/0095924_faceloaditerator.cpp @@ -0,0 +1,162 @@ +// faceloaditerator.cpp +// +// Implementation of FaceLoadIterator. +// +// Copyright 2018-2019 by +// Armin Hasitzka, David Turner, Robert Wilhelm, and Werner Lemberg. +// +// This file is part of the FreeType project, and may only be used, +// modified, and distributed under the terms of the FreeType project +// license, LICENSE.TXT. By continuing to use, modify, or distribute +// this file you indicate that you have read the license and +// understand and accept it fully. + + +#include "iterators/faceloaditerator.h" + +#include + +#include "utils/logging.h" + + + void + freetype::FaceLoadIterator:: + set_supported_font_format( FaceLoader::FontFormat format ) + { + assert( face_loader != nullptr ); + (void) face_loader->set_supported_font_format( format ); + } + + + void + freetype::FaceLoadIterator:: + set_library( FT_Library library ) + { + assert( face_loader != nullptr ); + (void) face_loader->set_library( library ); + } + + + void + freetype::FaceLoadIterator:: + set_raw_bytes( const uint8_t* data, + size_t size ) + { + assert( face_loader != nullptr ); + (void) face_loader->set_raw_bytes( data, size ); + } + + +#ifdef HAVE_ARCHIVE + void + freetype::FaceLoadIterator:: + set_data_is_tar_archive( bool is_tar_archive ) + { + assert( face_loader != nullptr ); + (void) face_loader->set_data_is_tar_archive( is_tar_archive ); + } +#endif + + + void + freetype::FaceLoadIterator:: + add_once_visitor( std::unique_ptr visitor ) + { + (void) once_face_visitors.emplace_back( move( visitor ) ); + } + + + void + freetype::FaceLoadIterator:: + add_always_visitor( std::unique_ptr visitor ) + { + (void) always_face_visitors.emplace_back( move( visitor ) ); + } + + + void + freetype::FaceLoadIterator:: + add_iterator( std::unique_ptr iterator ) + { + (void) face_prep_iterators.emplace_back( move( iterator ) ); + } + + + void + freetype::FaceLoadIterator:: + run() + { + Unique_FT_Face face = make_unique_face(); + + const char* face_name; + + FT_Long num_faces; + FT_Long num_instances; + + + assert( face_loader != nullptr ); + + num_faces = face_loader->get_num_faces(); + + for ( auto face_index = 0; + face_index < num_faces && + face_index < FACE_INDEX_MAX; + face_index++ ) + { + (void) face_loader->set_face_index( face_index ); + + if ( face_loader->load() == nullptr ) + { + LOG( ERROR ) << "face_loader->load failed"; + continue; + } + + if ( face_index == 0 ) + { + LOG( INFO ) << "fs type flags: 0x" << std::hex + << FT_Get_FSType_Flags( face.get() ); + + for ( auto& visitor : once_face_visitors ) + visitor->run( face_loader->load() ); + } + + num_instances = face_loader->get_num_instances(); + + for ( auto instance_index = 0; + instance_index < num_instances && + instance_index < INSTANCE_INDEX_MAX; + instance_index++ ) + { + face_loader->set_instance_index( instance_index ); + + LOG( INFO ) << "using face " + << ( face_index + 1 ) << "/" << num_faces << ", " + << "instance " + << ( instance_index + 1 ) << "/" << num_instances; + + face = face_loader->load(); + + if ( face == nullptr ) + { + LOG( ERROR ) << "face_loader->load failed"; + continue; + } + + face_name = FT_Get_Postscript_Name( face.get() ); + LOG_IF( INFO, face_name != nullptr ) + << "postscript name: " << face_name; + + for ( auto& visitor : always_face_visitors ) + visitor->run( face_loader->load() ); + + for ( auto& iterator : face_prep_iterators ) + iterator->run( face_loader ); + } + + WARN_ABOUT_IGNORED_VALUES( num_instances, + INSTANCE_INDEX_MAX, + "instances" ); + } + + WARN_ABOUT_IGNORED_VALUES( num_faces, FACE_INDEX_MAX, "faces" ); + } diff --git a/pool/shard007/C++/0095931_Mesh.cpp b/pool/shard007/C++/0095931_Mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c7f080a614a2a4524e14d7ded1a10b273c634c0 --- /dev/null +++ b/pool/shard007/C++/0095931_Mesh.cpp @@ -0,0 +1,220 @@ +//Copyright (C) 2011-2013 by Jason L. McKesson +//This file is licensed by the MIT License. + + + +#include +#include +#include +#include +#include "glmesh/Mesh.h" + + +namespace glmesh +{ + namespace + { + struct RenderCmd + { + bool isIndexedCmd; + GLenum ePrimType; + GLsizei vertexCount; + + //Only valid if isIndexedCmd is false. + GLint startIndex; + + //Only valid if isIndexedCmd is true. + GLenum dataType; + GLintptr byteOffset; + GLint baseVertex; + bool hasPrimRestart; + int primRestart; + }; + } + + struct RenderCmdListData + { + RenderCmdListData() : hasRestartIndex(false) {} + + bool hasRestartIndex; + GLint restartIndex; + + std::vector cmds; + }; + + struct MeshData + { + MeshData(const std::vector &_bufferObjects, GLuint _mainVao, + const std::vector &_cmds, const MeshVariantMap &_variants) + : bufferObjects(_bufferObjects) + , mainVao(_mainVao) + , variants(_variants) + , cmds(_cmds) + {} + + ~MeshData() + { + std::set deletedVaos; + + if(mainVao) + { + deletedVaos.insert(mainVao); + gl::DeleteVertexArrays(1, &mainVao); + } + + for(MeshVariantMap::iterator currIt = variants.begin(); + currIt != variants.end(); + ++currIt) + { + if(currIt->second && (deletedVaos.find(currIt->second) != deletedVaos.end())) + { + deletedVaos.insert(currIt->second); + gl::DeleteVertexArrays(1, &currIt->second); + } + } + + gl::DeleteBuffers(bufferObjects.size(), &bufferObjects[0]); + } + + std::vector bufferObjects; + GLuint mainVao; + MeshVariantMap variants; + + std::vector cmds; + }; + + RenderCmdList::RenderCmdList() + : m_pData(new RenderCmdListData) + {} + + RenderCmdList::RenderCmdList( class RenderCmdList &anOther ) + : m_pData(new RenderCmdListData(*anOther.m_pData)) + {} + + RenderCmdList::~RenderCmdList() + {} + + RenderCmdList& RenderCmdList::operator=( class RenderCmdList &anOther ) + { + *m_pData = *anOther.m_pData; + return *this; + } + + void RenderCmdList::DrawArrays( GLenum primitive, GLint startIndex, GLsizei vertexCount ) + { + RenderCmd cmd; + + cmd.isIndexedCmd = false; + cmd.ePrimType = primitive; + cmd.vertexCount = vertexCount; + cmd.startIndex = startIndex; + + m_pData->cmds.push_back(cmd); + } + + void RenderCmdList::DrawElements( GLenum primitive, GLsizei vertexCount, GLenum dataType, + GLintptr byteOffset, GLint baseVertex ) + { + RenderCmd cmd; + + cmd.isIndexedCmd = true; + cmd.ePrimType = primitive; + cmd.vertexCount = vertexCount; + cmd.dataType = dataType; + cmd.byteOffset = byteOffset; + cmd.baseVertex = baseVertex; + cmd.hasPrimRestart = m_pData->hasRestartIndex; + cmd.primRestart = m_pData->restartIndex; + + m_pData->cmds.push_back(cmd); + } + + void RenderCmdList::PrimitiveRestartIndex() + { + m_pData->hasRestartIndex = false; + } + + void RenderCmdList::PrimitiveRestartIndex( GLuint index ) + { + m_pData->hasRestartIndex = true; + m_pData->restartIndex = index; + } + + Mesh::Mesh( const std::vector &bufferObjects, GLuint mainVao, + const RenderCmdList &renderCmds, const MeshVariantMap &variants ) + : m_pData(new MeshData(bufferObjects, mainVao, renderCmds.m_pData->cmds, variants)) + {} + + Mesh::~Mesh() + {} + + void Mesh::Render() const + { + if(m_pData->mainVao) + { + gl::BindVertexArray(m_pData->mainVao); + RenderWithCurrVao(); + gl::BindVertexArray(0); + } + } + + void Mesh::Render( const std::string &variantName ) const + { + MeshVariantMap::iterator currVariant = m_pData->variants.find(variantName); + if(currVariant == m_pData->variants.end() || (currVariant->second == 0)) + return; + + gl::BindVertexArray(currVariant->second); + RenderWithCurrVao(); + gl::BindVertexArray(0); + } + + void Mesh::RenderWithCurrVao() const + { + for(size_t loop = 0; loop < m_pData->cmds.size(); ++loop) + { + const RenderCmd &cmd = m_pData->cmds[loop]; + if(cmd.isIndexedCmd) + { + if(cmd.hasPrimRestart) + { + gl::Enable(gl::PRIMITIVE_RESTART); + gl::PrimitiveRestartIndex(cmd.primRestart); + } + else + gl::Disable(gl::PRIMITIVE_RESTART); + + if(cmd.baseVertex) + gl::DrawElementsBaseVertex(cmd.ePrimType, cmd.vertexCount, cmd.dataType, + reinterpret_cast(cmd.byteOffset), cmd.baseVertex); + else + gl::DrawElements(cmd.ePrimType, cmd.vertexCount, cmd.dataType, + reinterpret_cast(cmd.byteOffset)); + } + else + { + gl::Disable(gl::PRIMITIVE_RESTART); + gl::DrawArrays(cmd.ePrimType, cmd.startIndex, cmd.vertexCount); + } + } + + gl::Disable(gl::PRIMITIVE_RESTART); + } + + bool Mesh::DoesMainExist() const + { + if(m_pData->mainVao) + return true; + + return false; + } + + bool Mesh::DoesVariantExist( const std::string &variantName ) const + { + MeshVariantMap::iterator currVariant = m_pData->variants.find(variantName); + if(currVariant == m_pData->variants.end() || (currVariant->second == 0)) + return false; + + return true; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0095932_GLShaderManager.cpp b/pool/shard007/C++/0095932_GLShaderManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fbfd2f7b9a7fc17870ad04ea3c242f7e964d304 --- /dev/null +++ b/pool/shard007/C++/0095932_GLShaderManager.cpp @@ -0,0 +1,96 @@ +#include "GLShaderManager.hpp" +#include + +#include + +namespace mls { + +GLShaderManager::GLShaderManager() { + m_ExtToType["vs.glsl"] = GL_VERTEX_SHADER; + m_ExtToType["gs.glsl"] = GL_GEOMETRY_SHADER; + m_ExtToType["fs.glsl"] = GL_FRAGMENT_SHADER; + m_ExtToType["cs.glsl"] = GL_COMPUTE_SHADER; +} + +GLShaderManager::GLShaderManager(const FilePath& dirPath): + GLShaderManager() { + addDirectory(dirPath); +} + +void GLShaderManager::addDirectory(const FilePath& dirPath) { + m_pLogger->info("Compile shaders from directory %v...", dirPath); + + if (!isDirectory(dirPath)) { + m_pLogger->error("%v is not a directory", dirPath.c_str()); + } + + recursiveCompileShaders(FilePath{ "" }, dirPath); +} + +void GLShaderManager::recursiveCompileShaders(const FilePath& relativePath, const FilePath& dir) { + for (const auto& file : getContainedFiles(dir)) { + auto completePath = dir + file; + if (isRegularFile(completePath)) { + if (file.endsWith(".xs.glsl")) { + auto src = loadShaderSource(completePath.str()); + auto baseName = (relativePath + file).str(); + baseName = baseName.substr(0, baseName.size() - 2); + + for (const auto& pair : m_ExtToType) { + auto name = baseName + pair.first; + m_pLogger->info("Compile shader %v...", name); + try { + m_ShadersMap.emplace(name, compileShader(pair.second, src)); + } + catch (...) { + m_pLogger->error("Error compiling shader %v", completePath); + throw; + } + } + } + else { + for (auto pair : m_ExtToType) { + if (file.endsWith(pair.first)) { + m_pLogger->info("Compile shader %v...", relativePath + file); + try { + m_ShadersMap.emplace((relativePath + file).str(), compileShader(pair.second, loadShaderSource(completePath.str()))); + } + catch (...) { + m_pLogger->error("Error compiling shader %v", completePath); + throw; + } + } + } + } + } + else if (isDirectory(completePath)) { + recursiveCompileShaders(relativePath + file, completePath); + } + } +} + +const GLShader& GLShaderManager::getShader(const std::string& name) const { + FilePath path(name); + auto it = m_ShadersMap.find(path.str()); + if(it == std::end(m_ShadersMap)) { + m_pLogger->error("Shader %v not found.", name); + throw std::runtime_error("Shader " + name + " not found"); + } + return (*it).second; +} + +GLProgram GLShaderManager::buildProgram(const std::vector& shaders) const { + GLProgram program; + for (const auto& shader : shaders) { + program.attachShader(getShader(shader)); + } + + if (!program.link()) { + std::cerr << program.getInfoLog() << std::endl; + throw std::runtime_error(program.getInfoLog()); + } + + return program; +} + +} diff --git a/pool/shard007/C++/0095937_Codeforces_456_D2_D.cpp b/pool/shard007/C++/0095937_Codeforces_456_D2_D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e566d4b689b0c5156a6030cb2cdf96b21441d31 --- /dev/null +++ b/pool/shard007/C++/0095937_Codeforces_456_D2_D.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +typedef long long ll; +#define ten5 100000+10 +#define MOD 1000000007 +#define rep(i,a,n) for (int i=a;i=a;i--) +#define pb push_back +#define mp make_pair + +int intcmp(const void *v1,const void *v2){return *(int *)v1-*(int *)v2;} +long long minn(long long v1,long long v2){return v1v2?v1:v2;} + +const int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; +ll n, m, r, k; +struct Node { + ll x, y; + Node(ll _x, ll _y) : x(_x), y(_y){}; + Node() = default; +}; + +ll get_vs(Node const& node) { + return (min(n - r + 1, node.x) - max(1ll, node.x - r + 1) + 1) * (min(m - r + 1, node.y) - max(1ll, node.y - r + 1) + 1); +} + +bool operator < (Node const& n1, Node const& n2) { + return get_vs(n2) > get_vs(n1); +} +int main() { + cin >> n >> m >> r >> k; + map, bool> um; + priority_queue que; + que.emplace(Node((n + 1) / 2, (m + 1) / 2)); + um[{(n + 1) / 2, (m + 1) / 2}] = 1; + ll sum = 0; + while (!que.empty()) { + Node u = que.top(); + que.pop(); + sum += get_vs(u); + k--; + if (!k) + break; + for (int i = 0; i < 4; ++i) { + ll tx = u.x + dir[i][0]; + ll ty = u.y + dir[i][1]; + if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && um.find({tx, ty}) == um.end()) { + um[{tx, ty}] = 1; + que.emplace(tx, ty); + } + } + } + printf("%.10lf\n", sum * 1.0 / (n - r + 1) / (m - r + 1)); +} + diff --git a/pool/shard007/C++/0095941_web_drag_bookmark_handler_win.cc b/pool/shard007/C++/0095941_web_drag_bookmark_handler_win.cc new file mode 100644 index 0000000000000000000000000000000000000000..827796e03622502ee93bb45c9c6a547d2c2a467c --- /dev/null +++ b/pool/shard007/C++/0095941_web_drag_bookmark_handler_win.cc @@ -0,0 +1,117 @@ +// 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 "chrome/browser/tab_contents/web_drag_bookmark_handler_win.h" + +#include "chrome/browser/bookmarks/bookmark_node_data.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/web_contents.h" +#include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/base/dragdrop/os_exchange_data_provider_win.h" +#include "webkit/glue/webdropdata.h" + +using content::WebContents; + +WebDragBookmarkHandlerWin::WebDragBookmarkHandlerWin() + : bookmark_tab_helper_(NULL), + web_contents_(NULL) { +} + +WebDragBookmarkHandlerWin::~WebDragBookmarkHandlerWin() { +} + +void WebDragBookmarkHandlerWin::DragInitialize(WebContents* contents) { + // Ideally we would want to initialize the the BookmarkTabHelper member in + // the constructor. We cannot do that as the WebDragTargetWin object is + // created during the construction of the WebContents object. The + // BookmarkTabHelper is created much later. + web_contents_ = contents; + if (!bookmark_tab_helper_) + bookmark_tab_helper_ = BookmarkTabHelper::FromWebContents(contents); +} + +void WebDragBookmarkHandlerWin::OnDragOver(IDataObject* data_object) { + if (bookmark_tab_helper_ && bookmark_tab_helper_->GetBookmarkDragDelegate()) { + ui::OSExchangeData os_exchange_data( + new ui::OSExchangeDataProviderWin(data_object)); + BookmarkNodeData bookmark_drag_data; + if (bookmark_drag_data.Read(os_exchange_data)) + bookmark_tab_helper_->GetBookmarkDragDelegate()->OnDragOver( + bookmark_drag_data); + } +} + +void WebDragBookmarkHandlerWin::OnDragEnter(IDataObject* data_object) { + // This is non-null if the web_contents_ is showing an ExtensionWebUI with + // support for (at the moment experimental) drag and drop extensions. + if (bookmark_tab_helper_ && bookmark_tab_helper_->GetBookmarkDragDelegate()) { + ui::OSExchangeData os_exchange_data( + new ui::OSExchangeDataProviderWin(data_object)); + BookmarkNodeData bookmark_drag_data; + if (bookmark_drag_data.Read(os_exchange_data)) + bookmark_tab_helper_->GetBookmarkDragDelegate()->OnDragEnter( + bookmark_drag_data); + } +} + +void WebDragBookmarkHandlerWin::OnDrop(IDataObject* data_object) { + // This is non-null if the web_contents_ is showing an ExtensionWebUI with + // support for (at the moment experimental) drag and drop extensions. + if (bookmark_tab_helper_) { + if (bookmark_tab_helper_->GetBookmarkDragDelegate()) { + ui::OSExchangeData os_exchange_data( + new ui::OSExchangeDataProviderWin(data_object)); + BookmarkNodeData bookmark_drag_data; + if (bookmark_drag_data.Read(os_exchange_data)) { + bookmark_tab_helper_->GetBookmarkDragDelegate()->OnDrop( + bookmark_drag_data); + } + } + + // Focus the target browser. + Browser* browser = browser::FindBrowserWithWebContents(web_contents_); + if (browser) + browser->window()->Show(); + } +} + +void WebDragBookmarkHandlerWin::OnDragLeave(IDataObject* data_object) { + if (bookmark_tab_helper_ && bookmark_tab_helper_->GetBookmarkDragDelegate()) { + ui::OSExchangeData os_exchange_data( + new ui::OSExchangeDataProviderWin(data_object)); + BookmarkNodeData bookmark_drag_data; + if (bookmark_drag_data.Read(os_exchange_data)) + bookmark_tab_helper_->GetBookmarkDragDelegate()->OnDragLeave( + bookmark_drag_data); + } +} + +bool WebDragBookmarkHandlerWin::AddDragData(const WebDropData& drop_data, + ui::OSExchangeData* data) { + if (!drop_data.url.SchemeIs(chrome::kJavaScriptScheme)) + return false; + + // We don't want to allow javascript URLs to be dragged to the desktop, + // but we do want to allow them to be added to the bookmarks bar + // (bookmarklets). So we create a fake bookmark entry (BookmarkNodeData + // object) which explorer.exe cannot handle, and write the entry to data. + BookmarkNodeData::Element bm_elt; + bm_elt.is_url = true; + bm_elt.url = drop_data.url; + bm_elt.title = drop_data.url_title; + + BookmarkNodeData bm_drag_data; + bm_drag_data.elements.push_back(bm_elt); + + // Pass in NULL as the profile so that the bookmark always adds the url + // rather than trying to move an existing url. + bm_drag_data.Write(NULL, data); + + return true; +} diff --git a/pool/shard007/C++/0095944_rtp_header_parser.cc b/pool/shard007/C++/0095944_rtp_header_parser.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4cbe544cc6c1c9aa4ea5dba9b15e51b590e887e --- /dev/null +++ b/pool/shard007/C++/0095944_rtp_header_parser.cc @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ +#include "webrtc/modules/rtp_rtcp/include/rtp_header_parser.h" + +#include "webrtc/base/scoped_ptr.h" +#include "webrtc/modules/rtp_rtcp/source/rtp_header_extension.h" +#include "webrtc/modules/rtp_rtcp/source/rtp_utility.h" +#include "webrtc/system_wrappers/include/critical_section_wrapper.h" + +namespace webrtc { + +class RtpHeaderParserImpl : public RtpHeaderParser { + public: + RtpHeaderParserImpl(); + virtual ~RtpHeaderParserImpl() {} + + bool Parse(const uint8_t* packet, + size_t length, + RTPHeader* header) const override; + + bool RegisterRtpHeaderExtension(RTPExtensionType type, uint8_t id) override; + + bool DeregisterRtpHeaderExtension(RTPExtensionType type) override; + + private: + rtc::scoped_ptr critical_section_; + RtpHeaderExtensionMap rtp_header_extension_map_ GUARDED_BY(critical_section_); +}; + +RtpHeaderParser* RtpHeaderParser::Create() { + return new RtpHeaderParserImpl; +} + +RtpHeaderParserImpl::RtpHeaderParserImpl() + : critical_section_(CriticalSectionWrapper::CreateCriticalSection()) {} + +bool RtpHeaderParser::IsRtcp(const uint8_t* packet, size_t length) { + RtpUtility::RtpHeaderParser rtp_parser(packet, length); + return rtp_parser.RTCP(); +} + +bool RtpHeaderParserImpl::Parse(const uint8_t* packet, + size_t length, + RTPHeader* header) const { + RtpUtility::RtpHeaderParser rtp_parser(packet, length); + memset(header, 0, sizeof(*header)); + + RtpHeaderExtensionMap map; + { + CriticalSectionScoped cs(critical_section_.get()); + rtp_header_extension_map_.GetCopy(&map); + } + + const bool valid_rtpheader = rtp_parser.Parse(header, &map); + if (!valid_rtpheader) { + return false; + } + return true; +} + +bool RtpHeaderParserImpl::RegisterRtpHeaderExtension(RTPExtensionType type, + uint8_t id) { + CriticalSectionScoped cs(critical_section_.get()); + return rtp_header_extension_map_.Register(type, id) == 0; +} + +bool RtpHeaderParserImpl::DeregisterRtpHeaderExtension(RTPExtensionType type) { + CriticalSectionScoped cs(critical_section_.get()); + return rtp_header_extension_map_.Deregister(type) == 0; +} +} // namespace webrtc diff --git a/pool/shard007/C++/0095950_allTrees.cpp b/pool/shard007/C++/0095950_allTrees.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38611ee4a8b870fbb6588c480503a5ba04879de9 --- /dev/null +++ b/pool/shard007/C++/0095950_allTrees.cpp @@ -0,0 +1,134 @@ +// $Id: allTrees.cpp 962 2006-11-07 15:13:34Z privmane $ + +#include "definitions.h" +#include "allTrees.h" +#include "treeUtil.h" +#include "treeIt.h" +#include "bblEM.h" +#include +#include + +#include "someUtil.h" + +using namespace std; +#ifndef VERBOS +#define VERBOS +#endif + + +allTrees::allTrees(bool keepAllTrees) : _keepAllTrees(keepAllTrees) { + _bestScore = VERYSMALL; +} + +void get3seqTreeAndIdLeftVec(const sequenceContainer* sc, + tree& starT, + vector& idList){ + sequenceContainer::constTaxaIterator tIt; + sequenceContainer::constTaxaIterator tItEnd; + tIt.begin(*sc); + tItEnd.end(*sc); + while(tIt != tItEnd) { + idList.push_back(tIt->id()); + ++tIt; + } + if (sc->numberOfSeqs()<3) errorMsg::reportError(" searching a tree for number of sequences < 3 "); + starT.createRootNode(); + starT.createNode(starT.getRoot(),1); + starT.createNode(starT.getRoot(),2); + starT.createNode(starT.getRoot(),3); + + const string nameOfSeq1 = (*sc)[idList[idList.size()-1]].name(); + const string nameOfSeq2 = (*sc)[idList[idList.size()-2]].name(); + const string nameOfSeq3 = (*sc)[idList[idList.size()-3]].name(); + idList.pop_back(); + idList.pop_back(); + idList.pop_back(); + + starT.getRoot()->getSon(0)->setName(nameOfSeq1); + starT.getRoot()->getSon(1)->setName(nameOfSeq2); + starT.getRoot()->getSon(2)->setName(nameOfSeq3); + starT.createFlatLengthMatrix(); +} + +void allTrees::recursiveFind( const sequenceContainer* sc, + const stochasticProcess* sp, + const Vdouble * weights, + const int maxIterations, + const MDOUBLE epsilon){ + tree starT; + vector ids; + get3seqTreeAndIdLeftVec(sc,starT,ids); + recursiveFind(starT,*sp,*sc,ids,weights,maxIterations,epsilon); +} + +tree getAnewTreeFrom(const tree& et, tree::nodeP & mynode, + vector & idLeft, const string& nameToAdd) { + tree newT = et; + tree::nodeP mynodeInNewTree = newT.findNodeByName(mynode->name()); +// int NameToAdd = idLeft[idLeft.size()-1]; + idLeft.pop_back(); + tree::nodeP fatherNode = mynodeInNewTree->father(); + tree::nodeP newInternalNode = newT.createNode(fatherNode, newT.getNodesNum()); + mynodeInNewTree->setFather(newInternalNode); + newInternalNode->setSon(mynodeInNewTree); + + fatherNode->removeSon(mynodeInNewTree); + tree::nodeP newOTU= newT.createNode(newInternalNode, newT.getNodesNum());; + //string nameX = (*sc)[NameToAdd].name(); + newOTU->setName(nameToAdd); + newOTU->setDisToFather(tree::FLAT_LENGTH_VALUE); + newInternalNode->setDisToFather(tree::FLAT_LENGTH_VALUE); + newT.create_names_to_internal_nodes(); + + return newT; +} + +void allTrees::recursiveFind(tree et, + const stochasticProcess& sp, + const sequenceContainer& sc, + vector idLeft, + const Vdouble * weights, + const int maxIterations, + const MDOUBLE epsilon) { + + if (idLeft.empty()) { + //static int k=1; k++; + MDOUBLE treeScore = evalTree(et,sp,sc,maxIterations,epsilon,weights); + if (_keepAllTrees) { + _allPossibleTrees.push_back(et); + _allPossibleScores.push_back(treeScore); + } + LOG(5,<<"."); + //LOG(5,<<"tree: "< + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or ( at your option ) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "KPrPlaceholderShapeFactory.h" + +#include + +#include +#include +#include "KPrPlaceholderShape.h" + +#include + +KPrPlaceholderShapeFactory::KPrPlaceholderShapeFactory() +: KoShapeFactoryBase(KPrPlaceholderShapeId, i18n( "Placeholder shape" ) ) +{ + QStringList elementNames; + elementNames << "text-box" << "object" << "image"; + setOdfElementNames( KoXmlNS::draw, elementNames ); + // use a really high number as we want to be used before the normal shapes try to load it + setLoadingPriority( 1000 ); + setHidden(true); +} + +KPrPlaceholderShapeFactory::~KPrPlaceholderShapeFactory() +{ +} + +KoShape *KPrPlaceholderShapeFactory::createDefaultShape(KoResourceManager *) const +{ + return new KPrPlaceholderShape(); +} + +bool KPrPlaceholderShapeFactory::supports(const KoXmlElement & e, KoShapeLoadingContext &context) const +{ + Q_UNUSED(context); + // check parent if placeholder is set to true + KoXmlNode parent = e.parentNode(); + if ( !parent.isNull() ) { + KoXmlElement element = parent.toElement(); + if ( !element.isNull() ) { + bool supported = element.attributeNS( KoXmlNS::presentation, "placeholder", "false" ) == "true"; + kDebug(33001) << "placeholder:" << supported; +#ifndef NWORKAROUND_ODF_BUGS + if (!supported && KoOdfWorkaround::fixPresentationPlaceholder() && element.hasAttributeNS(KoXmlNS::presentation, "class")) { + supported = true; + kDebug(33001) << "workaround OO placeholder bug" << supported; + } +#endif + return supported; + } + } + return false; +} diff --git a/pool/shard007/C++/0095952_on_received_policy_update.cc b/pool/shard007/C++/0095952_on_received_policy_update.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f5901c9e2f10a1cab8efb3f7b4b24943f526e1c --- /dev/null +++ b/pool/shard007/C++/0095952_on_received_policy_update.cc @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2018, Ford Motor Company + * 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 Ford Motor Company nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "sdl_rpc_plugin/commands/hmi/on_received_policy_update.h" +#include +#include "application_manager/application_manager.h" +#include "application_manager/policies/policy_handler_interface.h" +#include "utils/file_system.h" + +namespace sdl_rpc_plugin { +using namespace application_manager; + +namespace commands { + +SDL_CREATE_LOG_VARIABLE("Commands") + +OnReceivedPolicyUpdate::OnReceivedPolicyUpdate( + const application_manager::commands::MessageSharedPtr& message, + ApplicationManager& application_manager, + rpc_service::RPCService& rpc_service, + HMICapabilities& hmi_capabilities, + policy::PolicyHandlerInterface& policy_handle) + : NotificationFromHMI(message, + application_manager, + rpc_service, + hmi_capabilities, + policy_handle) {} + +OnReceivedPolicyUpdate::~OnReceivedPolicyUpdate() {} + +void OnReceivedPolicyUpdate::Run() { + SDL_LOG_AUTO_TRACE(); +#if defined(PROPRIETARY_MODE) || defined(EXTERNAL_PROPRIETARY_MODE) + const std::string& file_path = + (*message_)[strings::msg_params][hmi_notification::policyfile].asString(); + policy::BinaryMessage file_content; + if (!file_system::ReadBinaryFile(file_path, file_content)) { + SDL_LOG_ERROR("Failed to read Update file."); + return; + } + policy_handler_.ReceiveMessageFromSDK(file_path, file_content); +#else + SDL_LOG_WARN( + "This RPC is part of extended policy flow. " + "Please re-build with extended policy mode enabled."); +#endif +} + +} // namespace commands + +} // namespace sdl_rpc_plugin diff --git a/pool/shard007/C++/0095959_to_string.cpp b/pool/shard007/C++/0095959_to_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c7048737ecf8e11761649a648bdb1a4c92b00e7 --- /dev/null +++ b/pool/shard007/C++/0095959_to_string.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +#include "ast.hpp" +#include "inspect.hpp" +#include "context.hpp" +#include "to_string.hpp" + +namespace Sass { + using namespace std; + + To_String::To_String(Context* ctx, bool in_declaration) + : ctx(ctx), in_declaration(in_declaration) { } + To_String::~To_String() { } + + inline string To_String::fallback_impl(AST_Node* n) + { + Emitter emitter(ctx); + Inspect i(emitter); + i.in_declaration = in_declaration; + if (n) n->perform(&i); + return i.get_buffer(); + } + + inline string To_String::operator()(String_Schema* s) + { + string acc(""); + for (size_t i = 0, L = s->length(); i < L; ++i) { + acc += s->elements()[i]->perform(this); + } + return acc; + } + + inline string To_String::operator()(String_Quoted* s) + { + return s->value(); + } + + inline string To_String::operator()(String_Constant* s) + { + return s->value(); + } + + inline string To_String::operator()(Null* n) + { return ""; } +} diff --git a/pool/shard007/C++/0095961_tray_details_view.cc b/pool/shard007/C++/0095961_tray_details_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..72efe4ffe0bf91c190dcaef2c1ac5ea6a70d3aab --- /dev/null +++ b/pool/shard007/C++/0095961_tray_details_view.cc @@ -0,0 +1,165 @@ +// 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 "ash/system/tray/tray_details_view.h" + +#include "ash/system/tray/fixed_sized_scroll_view.h" +#include "ash/system/tray/system_tray.h" +#include "ash/system/tray/system_tray_item.h" +#include "ash/system/tray/tray_constants.h" +#include "ui/gfx/canvas.h" +#include "ui/views/background.h" +#include "ui/views/border.h" +#include "ui/views/controls/scroll_view.h" +#include "ui/views/layout/box_layout.h" + +namespace ash { +namespace internal { + +class ScrollSeparator : public views::View { + public: + ScrollSeparator() {} + + virtual ~ScrollSeparator() {} + + private: + // Overriden from views::View. + virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { + canvas->FillRect(gfx::Rect(0, height() / 2, width(), 1), kBorderLightColor); + } + virtual gfx::Size GetPreferredSize() OVERRIDE { + return gfx::Size(1, kTrayPopupScrollSeparatorHeight); + } + + DISALLOW_COPY_AND_ASSIGN(ScrollSeparator); +}; + +class ScrollBorder : public views::Border { + public: + ScrollBorder() {} + virtual ~ScrollBorder() {} + + void set_visible(bool visible) { visible_ = visible; } + + private: + // Overridden from views::Border. + virtual void Paint(const views::View& view, gfx::Canvas* canvas) OVERRIDE { + if (!visible_) + return; + canvas->FillRect(gfx::Rect(0, view.height() - 1, view.width(), 1), + kBorderLightColor); + } + + virtual gfx::Insets GetInsets() const OVERRIDE { + return gfx::Insets(0, 0, 1, 0); + } + + virtual gfx::Size GetMinimumSize() const OVERRIDE { + return gfx::Size(0, 1); + } + + bool visible_; + + DISALLOW_COPY_AND_ASSIGN(ScrollBorder); +}; + +TrayDetailsView::TrayDetailsView(SystemTrayItem* owner) + : owner_(owner), + footer_(NULL), + scroller_(NULL), + scroll_content_(NULL), + scroll_border_(NULL) { + SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, + 0, 0, 0)); + set_background(views::Background::CreateSolidBackground(kBackgroundColor)); +} + +TrayDetailsView::~TrayDetailsView() { +} + +void TrayDetailsView::CreateSpecialRow(int string_id, + ViewClickListener* listener) { + DCHECK(!footer_); + footer_ = new SpecialPopupRow(); + footer_->SetTextLabel(string_id, listener); + AddChildViewAt(footer_, child_count()); +} + +void TrayDetailsView::CreateScrollableList() { + DCHECK(!scroller_); + scroll_content_ = new views::View; + scroll_content_->SetLayoutManager(new views::BoxLayout( + views::BoxLayout::kVertical, 0, 0, 1)); + scroller_ = new FixedSizedScrollView; + scroller_->SetContentsView(scroll_content_); + + // Note: |scroller_| takes ownership of |scroll_border_|. + scroll_border_ = new ScrollBorder; + scroller_->set_border(scroll_border_); + + AddChildView(scroller_); +} + +void TrayDetailsView::AddScrollSeparator() { + DCHECK(scroll_content_); + // Do not draw the separator if it is the very first item + // in the scrollable list. + if (scroll_content_->has_children()) + scroll_content_->AddChildView(new ScrollSeparator); +} + +void TrayDetailsView::Reset() { + RemoveAllChildViews(true); + footer_ = NULL; + scroller_ = NULL; + scroll_content_ = NULL; +} + +void TrayDetailsView::TransitionToDefaultView() { + // Cache pointer to owner in this function scope. TrayDetailsView will be + // deleted after called ShowDefaultView. + SystemTrayItem* owner = owner_; + if (footer_ && footer_->content() && footer_->content()->HasFocus()) + owner->set_restore_focus(true); + owner->system_tray()->ShowDefaultView(BUBBLE_USE_EXISTING); + owner->set_restore_focus(false); +} + +void TrayDetailsView::Layout() { + if (!scroller_ || !footer_ || bounds().IsEmpty()) { + views::View::Layout(); + return; + } + + scroller_->set_fixed_size(gfx::Size()); + gfx::Size size = GetPreferredSize(); + + // Set the scroller to fill the space above the bottom row, so that the + // bottom row of the detailed view will always stay just above the footer. + gfx::Size scroller_size = scroll_content_->GetPreferredSize(); + scroller_->set_fixed_size(gfx::Size( + width() + scroller_->GetScrollBarWidth(), + scroller_size.height() - (size.height() - height()))); + + views::View::Layout(); + // Always make sure the footer element is bottom aligned. + gfx::Rect fbounds = footer_->bounds(); + fbounds.set_y(height() - footer_->height()); + footer_->SetBoundsRect(fbounds); +} + +void TrayDetailsView::OnPaintBorder(gfx::Canvas* canvas) { + if (scroll_border_) { + int index = GetIndexOf(scroller_); + if (index < child_count() - 1 && child_at(index + 1) != footer_) + scroll_border_->set_visible(true); + else + scroll_border_->set_visible(false); + } + + views::View::OnPaintBorder(canvas); +} + +} // namespace internal +} // namespace ash diff --git a/pool/shard007/C++/0095962_testleaf_node.cpp b/pool/shard007/C++/0095962_testleaf_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7930e29ccfd23a2f151ed685db203040374256b --- /dev/null +++ b/pool/shard007/C++/0095962_testleaf_node.cpp @@ -0,0 +1,220 @@ +/** + * Testing the typesafe interface + */ +#include +#include "testhelpers.h" +#include "leaf_node.h" +#include + +#include + +using namespace libbruce; + +kv_pair mkPair(int key, int value) +{ + return kv_pair(intCopy(key), intCopy(value)); +} + +struct ApplyTests +{ + ApplyTests() + { + leaf = boost::make_shared(intToIntTree); + leaf->insert(mkPair(5, 5)); + leaf->insert(mkPair(10, 10)); + } + + void insert(int key, int value) + { + edits.push_back(pending_edit(INSERT, intCopy(key), intCopy(value), true)); + } + + void upsert(int key, int value) + { + edits.push_back(pending_edit(UPSERT, intCopy(key), intCopy(value), false)); + } + + void remove(int key) + { + edits.push_back(pending_edit(REMOVE_KEY, intCopy(key), memslice(), false)); + } + + void remove(int key, int value) + { + edits.push_back(pending_edit(REMOVE_KV, intCopy(key), intCopy(value), false)); + } + + void applyAll() + { + leaf->applyAll(edits.begin(), edits.end()); + + for (pairlist_t::iterator it = leaf->pairs.begin(); it != leaf->pairs.end(); ++it) + { + if (it != leaf->pairs.begin()) values += ", "; + int *p = (int*)it->second.ptr(); + if (p) values += boost::lexical_cast(*p); + } + } + + void verifySize() + { + // Construct a new leaf node and check that the size of the modified leaf node is the same. + leafnode_ptr reference = boost::make_shared(leaf->pairs.begin(), leaf->pairs.end(), intToIntTree); + REQUIRE( reference->elementsSize() == leaf->elementsSize() ); + } + + leafnode_ptr leaf; + editlist_t edits; + std::string values; +}; + +//---------------------------------------------------------------------- + +TEST_CASE_METHOD(ApplyTests, "multiple inserts") +{ + insert(1, 1); + insert(7, 7); + insert(12, 12); + + applyAll(); + + REQUIRE( values == "1, 5, 7, 10, 12" ); + verifySize(); +} + +TEST_CASE_METHOD(ApplyTests, "insert then remove by key") +{ + SECTION("in the middle") + { + insert(7, 7); + remove(7); + applyAll(); + + REQUIRE( values == "5, 10" ); + verifySize(); + } + + SECTION("at the end") + { + insert(12, 12); + remove(12); + applyAll(); + + REQUIRE( values == "5, 10" ); + verifySize(); + } +} + +TEST_CASE_METHOD(ApplyTests, "remove then insert") +{ + SECTION("in the middle") + { + remove(7); + insert(7, 7); + applyAll(); + + REQUIRE( values == "5, 7, 10" ); + verifySize(); + } + + SECTION("at the end") + { + remove(12); + insert(12, 12); + applyAll(); + + REQUIRE( values == "5, 10, 12" ); + verifySize(); + } +} + +TEST_CASE_METHOD(ApplyTests, "insert, insert then delete 1st by value") +{ + SECTION("in the middle") + { + insert(7, 7); + insert(7, 8); + remove(7, 7); + applyAll(); + + REQUIRE( values == "5, 8, 10" ); + verifySize(); + } + + SECTION("at the end") + { + insert(12, 12); + insert(12, 13); + remove(12, 12); + applyAll(); + + REQUIRE( values == "5, 10, 13" ); + verifySize(); + } +} + +TEST_CASE_METHOD(ApplyTests, "remove then upsert") +{ + SECTION("existing") + { + remove(5); + upsert(5, 6); + applyAll(); + + REQUIRE( values == "6, 10" ); + verifySize(); + } + + SECTION("in the middle") + { + remove(7); + upsert(7, 7); + applyAll(); + + REQUIRE( values == "5, 7, 10" ); + verifySize(); + } + + SECTION("at the end") + { + remove(12); + upsert(12, 12); + applyAll(); + + REQUIRE( values == "5, 10, 12" ); + verifySize(); + } +} + +TEST_CASE_METHOD(ApplyTests, "upsert then remove") +{ + SECTION("existing") + { + upsert(5, 6); + remove(5); + applyAll(); + + REQUIRE( values == "10" ); + verifySize(); + } + + SECTION("in the middle") + { + upsert(7, 7); + remove(7); + applyAll(); + + REQUIRE( values == "5, 10" ); + verifySize(); + } + + SECTION("at the end") + { + upsert(12, 12); + remove(12); + applyAll(); + + REQUIRE( values == "5, 10" ); + verifySize(); + } +} diff --git a/pool/shard007/C++/0095964_fpgathread.cpp b/pool/shard007/C++/0095964_fpgathread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59aaed7916b00d3e5f55e158399b7be2b0eef41c --- /dev/null +++ b/pool/shard007/C++/0095964_fpgathread.cpp @@ -0,0 +1,124 @@ +/*************************************************************************************/ +/* Copyright 2010 Barcelona Supercomputing Center */ +/* Copyright 2009 Barcelona Supercomputing Center */ +/* */ +/* This file is part of the NANOS++ library. */ +/* */ +/* NANOS++ 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. */ +/* */ +/* NANOS++ 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 NANOS++. If not, see . */ +/*************************************************************************************/ + +#include "fpgathread.hpp" +#include "fpgadd.hpp" +#include "fpgamemorytransfer.hpp" +#include "fpgaworker.hpp" + +using namespace nanos; +using namespace nanos::ext; + +void FPGAThread::initializeDependent() +{ + //initialize device + ( ( FPGAProcessor * ) myThread->runningOn() )->init(); +} + + +void FPGAThread::runDependent() +{ + verbose( "fpga run dependent" ); + WD &work = getThreadWD(); + setCurrentWD( work ); + SMPDD &dd = ( SMPDD & ) work.activateDevice( getSMPDevice() ); + dd.getWorkFct()( work.getData() ); + ( ( FPGAProcessor * ) myThread->runningOn() )->cleanUp(); +} + +bool FPGAThread::inlineWorkDependent( WD &wd ) +{ + verbose( "fpga nlineWorkDependent" ); + + wd.start( WD::IsNotAUserLevelThread ); + FPGAProcessor* fpga = ( FPGAProcessor * ) myThread->runningOn(); + + //Instrumentation event to record in which accelerator the task is running + NANOS_INSTRUMENT (InstrumentBurst i("accelerator#", fpga->getActiveAcc()+1) ); + //set flag to allow new opdate + fpga->setUpdate(true); + FPGADD &dd = ( FPGADD & )wd.getActiveDevice(); + ( dd.getWorkFct() )( wd.getData() ); + + return true; +} + +void FPGAThread::preOutlineWorkDependent ( WD &wd ) { + wd.preStart(WorkDescriptor::IsNotAUserLevelThread); +} + +void FPGAThread::outlineWorkDependent ( WD &wd ) { + //wd.start( WD::IsNotAUserLevelThread ); + FPGAProcessor* fpga = ( FPGAProcessor * ) myThread->runningOn(); + + //Instrumentation event to record in which accelerator the task is running + NANOS_INSTRUMENT (InstrumentBurst i("accelerator#", fpga->getActiveAcc()+1) ); + //set flag to allow new opdate + fpga->setUpdate(true); + FPGADD &dd = ( FPGADD & )wd.getActiveDevice(); + ( dd.getWorkFct() )( wd.getData() ); +} + +void FPGAThread::yield() { + verbose("FPGA yield"); + + //Synchronizing transfers here seems to yield slightly better performance + ((FPGAProcessor*)runningOn())->getOutTransferList()->syncAll(); + ((FPGAProcessor*)runningOn())->getInTransferList()->syncAll(); + + SMPThread::yield(); +} + +//Sync transfers on idle +void FPGAThread::idle( bool debug ) { + //TODO:get the number of transfers from config + //TODO: figure put a sensible default + int n = FPGAConfig::getIdleSyncBurst(); + ((FPGAProcessor*)runningOn())->getOutTransferList()->syncNTransfers(n); + ((FPGAProcessor*)runningOn())->getInTransferList()->syncNTransfers(n); +} + +int FPGAThread::getPendingWDs() const { + return _pendingWD.size(); +} + +void FPGAThread::finishPendingWD( int numWD ) { + int n = std::min(numWD, (int)_pendingWD.size() ); + for (int i=0; i + +#include "script_manager.h" + +#include + +#include +#include +#include +#include + +#include "ips_manager.h" +#include "plugin_manager.h" +#include "lua/lua.h" +#include "lua/lua_util.h" +#include "framework/ips_option.h" +#include "framework/logger.h" +#include "framework/lua_api.h" +#include "log/messages.h" +#include "helpers/directory.h" + +#ifdef PIGLET +#include "piglet/piglet_manager.h" +#endif + +// FIXIT-P this approach results in N * K lua states where +// N ::= number of instances of script + args and +// K ::= number of threads +// change to create K lua states here for each script + args +// and change LuaJit*() to get reference to thread states +// ultimately should look into changing detection engine to +// keep just one copy of rule option + args + +using namespace std; +#define script_pattern "*.lua" + +//------------------------------------------------------------------------- +// lua api stuff +//------------------------------------------------------------------------- + +static vector base_api; +static vector lua_api; + +//------------------------------------------------------------------------- +// ips option stuff +//------------------------------------------------------------------------- + +class IpsLuaApi : public LuaApi +{ +public: + IpsLuaApi(string& n, string& c, unsigned v); + + const BaseApi* get_base() const + { return &api.base; } + +public: + IpsApi api; + static const char* type; +}; + +const char* IpsLuaApi::type = "ips_option"; + +IpsLuaApi::IpsLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c) +{ + extern const IpsApi* ips_luajit; + api = *ips_luajit; + api.base.name = name.c_str(); + api.base.version = v; +} + +//------------------------------------------------------------------------- +// log api stuff +//------------------------------------------------------------------------- + +class LogLuaApi : public LuaApi +{ +public: + LogLuaApi(string& n, string& c, unsigned v); + + const BaseApi* get_base() const + { return &api.base; } + +public: + LogApi api; + static const char* type; +}; + +const char* LogLuaApi::type = "logger"; + +LogLuaApi::LogLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c) +{ + extern const LogApi* log_luajit; + api = *log_luajit; + api.base.name = name.c_str(); + api.base.version = v; +} + +//------------------------------------------------------------------------- +// lua foo +//------------------------------------------------------------------------- + +// FIXIT-M: could be a template +static bool get_field(lua_State* L, const char* key, int& value) +{ + lua_pushstring(L, key); + lua_gettable(L, -2); + + if ( !lua_isnumber(L, -1) ) + { + ParseWarning(WARN_SCRIPTS, "%s is not a number", key); + lua_pop(L, 1); + return false; + } + + value = (long)lua_tonumber(L, -1); + lua_pop(L, 1); + + return true; +} + +static bool get_field(lua_State* L, const char* key, string& value) +{ + lua_pushstring(L, key); + lua_gettable(L, -2); + + if ( !lua_isstring(L, -1) ) + { + ParseWarning(WARN_SCRIPTS, "%s is not a string", key); + lua_pop(L, 1); + return false; + } + + value = lua_tostring(L, -1); + lua_pop(L, 1); + + return true; +} + +// FIXIT-M: Move to helpers/lua +static int dump(lua_State*, const void* p, size_t sz, void* ud) +{ + string* s = static_cast(ud); + s->append(static_cast(p), sz); + return 0; +} + +// FIXIT-M: Use Lua::State to wrap lua_State +static void load_script(const char* f) +{ + Lua::State lua; + auto L = lua.get_ptr(); + + // Set this now so that dependent dofile()s can work correctly + Lua::set_script_dir(L, SCRIPT_DIR_VARNAME, f); + + if ( luaL_loadfile(L, f) ) + { + ParseWarning(WARN_SCRIPTS, "can't load %s: %s", f, lua_tostring(L, -1)); + return; + } + + // lua_pcall() pops the function so we push it again first + // if this is a copy, there must be a cheaper alternative + lua_pushvalue(L, -1); + + if ( lua_pcall(L, 0, 0, 0) ) + { + ParseWarning(WARN_SCRIPTS, "can't init %s: %s", f, lua_tostring(L, -1)); + return; + } + + lua_getglobal(L, "plugin"); + + if ( !lua_istable(L, -1) ) + { + ParseWarning(WARN_SCRIPTS, "can't get plugin from %s", f); + return; + } + + int ver = -1; + string type, name, chunk; + + if ( !get_field(L, "type", type) ) + { + ParseError("missing plugin type %s = '%s'", f, type.c_str()); + return; + } + + if ( !get_field(L, "name", name) ) + { + ParseError("%s::%s needs name", f, type.c_str()); + return; + } + + if ( !get_field(L, "version", ver) ) + ver = 0; + + lua_pop(L, 1); + + if ( lua_dump(L, dump, &chunk) ) + { + ParseError("%s::%s can't save chunk", f, name.c_str()); + return; + } + + if ( type == IpsLuaApi::type ) + lua_api.push_back(new IpsLuaApi(name, chunk, ver)); + + else if ( type == LogLuaApi::type ) + lua_api.push_back(new LogLuaApi(name, chunk, ver)); + +#ifdef PIGLET + else if ( type == "piglet" ) + Piglet::Manager::add_chunk(f, name, chunk); +#endif + + else + { + ParseError("unknown plugin type in %s = '%s'", f, type.c_str()); + return; + } +} + +//------------------------------------------------------------------------- +// public methods +//------------------------------------------------------------------------- + +void ScriptManager::load_scripts(const std::vector& paths) +{ + struct stat s; + + if ( paths.empty() ) + return; + + for ( auto path : paths ) + { + size_t pos = path.find_first_not_of(":"); + + while ( pos != std::string::npos ) + { + size_t end_pos = path.find_first_of(":", pos); + + std::string d = path.substr( + pos, (end_pos == std::string::npos) ? end_pos : end_pos - pos); + + pos = ( end_pos == std::string::npos ) ? end_pos : end_pos + 1; + + if ( d.empty() ) + continue; + + if ( stat(d.c_str(), &s) ) + continue; + + if ( s.st_mode & S_IFDIR ) + { + Directory dir(d.c_str(), script_pattern); + const char* f; + while ( (f = dir.next()) ) + load_script(f); + } + + else + load_script(d.c_str()); + } + } +} + +const BaseApi** ScriptManager::get_plugins() +{ + base_api.clear(); + + for ( auto p : lua_api ) + base_api.push_back(p->get_base()); + + base_api.push_back(nullptr); + + return (const BaseApi**)&base_api[0]; +} + +void ScriptManager::release_scripts() +{ + for ( auto p : lua_api ) + if ( p ) + delete p; + + lua_api.clear(); + base_api.clear(); +} + +string* ScriptManager::get_chunk(const char* key) +{ + for ( auto p : lua_api ) + if ( p->name == key ) + return &p->chunk; + + return nullptr; +} + diff --git a/pool/shard007/C++/0095969_dstreadshuffle.cpp b/pool/shard007/C++/0095969_dstreadshuffle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..756e922ea9cc55ef2cbf01ff7c06a13eb010fd62 --- /dev/null +++ b/pool/shard007/C++/0095969_dstreadshuffle.cpp @@ -0,0 +1,195 @@ + +/* + * Copyright 2013 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#include "gm.h" +#include "SkBitmap.h" +#include "SkRandom.h" +#include "SkShader.h" +#include "SkXfermode.h" + +namespace skiagm { + +/** + * Renders overlapping shapes with colorburn against a checkerboard. + */ +class DstReadShuffle : public GM { +public: + DstReadShuffle() { + this->setBGColor(SkColorSetARGB(0xff, 0xff, 0, 0xff)); + } + +protected: + enum ShapeType { + kCircle_ShapeType, + kRoundRect_ShapeType, + kRect_ShapeType, + kConvexPath_ShapeType, + kConcavePath_ShapeType, + kText_ShapeType, + kNumShapeTypes + }; + + SkString onShortName() override { + return SkString("dstreadshuffle"); + } + + SkISize onISize() override { + return SkISize::Make(kWidth, kHeight); + } + + void drawShape(SkCanvas* canvas, + SkPaint* paint, + ShapeType type) { + static const SkRect kRect = SkRect::MakeXYWH(SkIntToScalar(-50), SkIntToScalar(-50), + SkIntToScalar(75), SkIntToScalar(105)); + switch (type) { + case kCircle_ShapeType: + canvas->drawCircle(0, 0, 50, *paint); + break; + case kRoundRect_ShapeType: + canvas->drawRoundRect(kRect, SkIntToScalar(10), SkIntToScalar(20), *paint); + break; + case kRect_ShapeType: + canvas->drawRect(kRect, *paint); + break; + case kConvexPath_ShapeType: + if (fConvexPath.isEmpty()) { + SkPoint points[4]; + kRect.toQuad(points); + fConvexPath.moveTo(points[0]); + fConvexPath.quadTo(points[1], points[2]); + fConvexPath.quadTo(points[3], points[0]); + SkASSERT(fConvexPath.isConvex()); + } + canvas->drawPath(fConvexPath, *paint); + break; + case kConcavePath_ShapeType: + if (fConcavePath.isEmpty()) { + SkPoint points[5] = {{0, SkIntToScalar(-50)} }; + SkMatrix rot; + rot.setRotate(SkIntToScalar(360) / 5); + for (int i = 1; i < 5; ++i) { + rot.mapPoints(points + i, points + i - 1, 1); + } + fConcavePath.moveTo(points[0]); + for (int i = 0; i < 5; ++i) { + fConcavePath.lineTo(points[(2 * i) % 5]); + } + fConcavePath.setFillType(SkPath::kEvenOdd_FillType); + SkASSERT(!fConcavePath.isConvex()); + } + canvas->drawPath(fConcavePath, *paint); + break; + case kText_ShapeType: { + const char* text = "Hello!"; + paint->setTextSize(30); + canvas->drawText(text, strlen(text), 0, 0, *paint); + } + default: + break; + } + } + + static SkColor GetColor(SkRandom* random, int i, int nextColor) { + static SkColor colors[] = { SK_ColorRED, + 0xFFFF7F00, // Orange + SK_ColorYELLOW, + SK_ColorGREEN, + SK_ColorBLUE, + 0xFF4B0082, // indigo + 0xFF7F00FF }; // violet + SkColor color; + int index = nextColor % SK_ARRAY_COUNT(colors); + switch (i) { + case 0: + color = SK_ColorTRANSPARENT; + break; + case 1: + color = SkColorSetARGB(0xff, + SkColorGetR(colors[index]), + SkColorGetG(colors[index]), + SkColorGetB(colors[index])); + break; + default: + uint8_t alpha = 0x80; + color = SkColorSetARGB(alpha, + SkColorGetR(colors[index]), + SkColorGetG(colors[index]), + SkColorGetB(colors[index])); + break; + } + return color; + } + + static void SetStyle(SkPaint* p, int style, int width) { + switch (style) { + case 0: + p->setStyle(SkPaint::kStroke_Style); + p->setStrokeWidth((SkScalar)width); + break; + case 1: + p->setStyle(SkPaint::kStrokeAndFill_Style); + p->setStrokeWidth((SkScalar)width); + break; + default: + p->setStyle(SkPaint::kFill_Style); + break; + } + } + + void onDraw(SkCanvas* canvas) override { + SkRandom random; + SkScalar y = 100; + for (int i = 0; i < kNumShapeTypes; i++) { + ShapeType shapeType = static_cast(i); + SkScalar x = 25; + for (int style = 0; style < 3; style++) { + for (int width = 0; width <= 1; width++) { + for (int alpha = 0; alpha <= 2; alpha++) { + for (int r = 0; r <= 5; r++) { + SkColor color = GetColor(&random, alpha, style + width + alpha + r); + + SkPaint p; + p.setAntiAlias(true); + p.setColor(color); + // In order to get some batching on the GPU backend we do 2 src over for + // each xfer mode which requires a dst read + p.setXfermodeMode(r % 3 == 0 ? SkXfermode::kLighten_Mode : + SkXfermode::kSrcOver_Mode); + SetStyle(&p, style, width); + canvas->save(); + canvas->translate(x, y); + canvas->rotate((SkScalar)(r < 3 ? 10 : 0)); + this->drawShape(canvas, &p, shapeType); + canvas->restore(); + x += 8; + } + } + } + } + y += 50; + } + } + +private: + enum { + kNumShapes = 100, + }; + SkAutoTUnref fBG; + SkPath fConcavePath; + SkPath fConvexPath; + static const int kWidth = 900; + static const int kHeight = 400; + typedef GM INHERITED; +}; + +////////////////////////////////////////////////////////////////////////////// + +static GM* MyFactory(void*) { return new DstReadShuffle; } +static GMRegistry reg(MyFactory); + +} diff --git a/pool/shard007/C++/0095970_ShapeOrbitCameraEffect.cpp b/pool/shard007/C++/0095970_ShapeOrbitCameraEffect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..63b25324de04fcc7239863158f83c64ee41cac93 --- /dev/null +++ b/pool/shard007/C++/0095970_ShapeOrbitCameraEffect.cpp @@ -0,0 +1,40 @@ +// +// ShapeOrbitCameraEffect.cpp +// G3MiOSSDK +// +// Created by Diego Gomez Deck on 1/31/13. +// +// + +#include "ShapeOrbitCameraEffect.hpp" + +#include "Shape.hpp" +#include "Camera.hpp" + +void ShapeOrbitCameraEffect::doStep(const G3MRenderContext* rc, + const TimeInterval& when) { + const double alpha = getAlpha(when); + + const IMathUtils* mu = IMathUtils::instance(); + const double distance = mu->linearInterpolation(_fromDistance, _toDistance, alpha); + const double azimuthInRadians = mu->linearInterpolation(_fromAzimuthInRadians, _toAzimuthInRadians, alpha); + const double altitudeInRadians = mu->linearInterpolation(_fromAltitudeInRadians, _toAltitudeInRadians, alpha); + + rc->getNextCamera()->setPointOfView(_shape->getPosition(), + distance, + Angle::fromRadians(azimuthInRadians), + Angle::fromRadians(altitudeInRadians)); +} + +void ShapeOrbitCameraEffect::cancel(const TimeInterval& when) { + // do nothing +} + +void ShapeOrbitCameraEffect::stop(const G3MRenderContext* rc, + const TimeInterval& when) { + rc->getNextCamera()->setPointOfView(_shape->getPosition(), + _toDistance, + Angle::fromRadians(_toAzimuthInRadians), + Angle::fromRadians(_toAltitudeInRadians)); + +} diff --git a/pool/shard007/C++/0095973_crypter.cpp b/pool/shard007/C++/0095973_crypter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bb881ab4a5b2d6ad73b7225f38a1a5e7da52a43 --- /dev/null +++ b/pool/shard007/C++/0095973_crypter.cpp @@ -0,0 +1,138 @@ +// Copyright (c) 2009-2018 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 +#include +#include + +#include + +int CCrypter::BytesToKeySHA512AES(const std::vector& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const +{ + // This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc + // cipher and sha512 message digest. Because sha512's output size (64b) is + // greater than the aes256 block size (16b) + aes256 key size (32b), + // there's no need to process more than once (D_0). + + if(!count || !key || !iv) + return 0; + + unsigned char buf[CSHA512::OUTPUT_SIZE]; + CSHA512 di; + + di.Write((const unsigned char*)strKeyData.data(), strKeyData.size()); + di.Write(chSalt.data(), chSalt.size()); + di.Finalize(buf); + + for(int i = 0; i != count - 1; i++) + di.Reset().Write(buf, sizeof(buf)).Finalize(buf); + + memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE); + memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE); + memory_cleanse(buf, sizeof(buf)); + return WALLET_CRYPTO_KEY_SIZE; +} + +bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) +{ + if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) + return false; + + int i = 0; + if (nDerivationMethod == 0) + i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, vchKey.data(), vchIV.data()); + + if (i != (int)WALLET_CRYPTO_KEY_SIZE) + { + memory_cleanse(vchKey.data(), vchKey.size()); + memory_cleanse(vchIV.data(), vchIV.size()); + return false; + } + + fKeySet = true; + return true; +} + +bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector& chNewIV) +{ + if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE) + return false; + + memcpy(vchKey.data(), chNewKey.data(), chNewKey.size()); + memcpy(vchIV.data(), chNewIV.data(), chNewIV.size()); + + fKeySet = true; + return true; +} + +bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector &vchCiphertext) const +{ + if (!fKeySet) + return false; + + // max ciphertext len for a n bytes of plaintext is + // n + AES_BLOCKSIZE bytes + vchCiphertext.resize(vchPlaintext.size() + AES_BLOCKSIZE); + + AES256CBCEncrypt enc(vchKey.data(), vchIV.data(), true); + size_t nLen = enc.Encrypt(&vchPlaintext[0], vchPlaintext.size(), vchCiphertext.data()); + if(nLen < vchPlaintext.size()) + return false; + vchCiphertext.resize(nLen); + + return true; +} + +bool CCrypter::Decrypt(const std::vector& vchCiphertext, CKeyingMaterial& vchPlaintext) const +{ + if (!fKeySet) + return false; + + // plaintext will always be equal to or lesser than length of ciphertext + int nLen = vchCiphertext.size(); + + vchPlaintext.resize(nLen); + + AES256CBCDecrypt dec(vchKey.data(), vchIV.data(), true); + nLen = dec.Decrypt(vchCiphertext.data(), vchCiphertext.size(), &vchPlaintext[0]); + if(nLen == 0) + return false; + vchPlaintext.resize(nLen); + return true; +} + +bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector &vchCiphertext) +{ + CCrypter cKeyCrypter; + std::vector chIV(WALLET_CRYPTO_IV_SIZE); + memcpy(chIV.data(), &nIV, WALLET_CRYPTO_IV_SIZE); + if(!cKeyCrypter.SetKey(vMasterKey, chIV)) + return false; + return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); +} + +bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) +{ + CCrypter cKeyCrypter; + std::vector chIV(WALLET_CRYPTO_IV_SIZE); + memcpy(chIV.data(), &nIV, WALLET_CRYPTO_IV_SIZE); + if(!cKeyCrypter.SetKey(vMasterKey, chIV)) + return false; + return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); +} + +bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key) +{ + CKeyingMaterial vchSecret; + if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) + return false; + + if (vchSecret.size() != 32) + return false; + + key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); + return key.VerifyPubKey(vchPubKey); +} diff --git a/pool/shard007/C++/0095974_format_common.cpp b/pool/shard007/C++/0095974_format_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7205bf1be15adb482e3f54805338f1fc36608b5 --- /dev/null +++ b/pool/shard007/C++/0095974_format_common.cpp @@ -0,0 +1,263 @@ +//////////////////////////////////////////////////////////////////// +// Copyright (C) Alexander Telyatnikov, Ivan Keliukh, Yegor Anchishkin, SKIF Software, 1999-2013. Kiev, Ukraine +// All rights reserved +// This file was released under the GPLv2 on June 2015. +//////////////////////////////////////////////////////////////////// + +/// Initial drive selection from command line. +CHAR szDisc[4] = ""; +BOOL bChanger = FALSE; + +/// Return CD-RW device type +JS_DEVICE_TYPE +CheckCDType( + PCHAR m_szFile, + PCHAR VendorId + ) +{ + HANDLE hDevice; + CHAR szDeviceName[256]; + CHAR ioBuf[4096]; + ULONG RC; + BOOL DvdRW = false; + BOOL DvdpRW = false; + BOOL DvdRAM = false; + BOOL DvdpR = false; + BOOL DvdR = false; + + bChanger = FALSE; + + // Make string representing full path + sprintf(szDeviceName, "\\\\.\\%s", m_szFile); + if (szDeviceName[strlen(szDeviceName)-1] == '\\') szDeviceName[strlen(szDeviceName)-1] = '\0'; + + // Open device volume + hDevice = OpenOurVolume(szDeviceName); + + if (hDevice == ((HANDLE)-1)) { + strcpy(VendorId,""); + return BUSY; + } else { + + // Get our cdrw.sys signature + RC = UDFPhSendIOCTL(IOCTL_CDRW_GET_SIGNATURE,hDevice, + &ioBuf,sizeof(GET_SIGNATURE_USER_OUT), + &ioBuf,sizeof(GET_SIGNATURE_USER_OUT),FALSE,NULL); + + if (RC == 1) { + // Get device information + RC = UDFPhSendIOCTL(IOCTL_CDRW_GET_DEVICE_INFO,hDevice, + &ioBuf,sizeof(GET_DEVICE_INFO_USER_OUT), + &ioBuf,sizeof(GET_DEVICE_INFO_USER_OUT),FALSE,NULL); + if (RC != 1) { + strcpy(VendorId,"Unknown Vendor"); + } else { + if(((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features & CDRW_FEATURE_CHANGER) + bChanger = TRUE; + strcpy(VendorId,(PCHAR)&(((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->VendorId[0])); + if (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features & CDRW_FEATURE_GET_CFG) { + DvdRW = (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features2[0] >> PFNUM_DVDRW_RESTRICTED_OVERWRITE) & 1; + DvdRAM = (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features2[0] >> PFNUM_DVDRAM) & 1; + DvdpRW = (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features2[0] >> PFNUM_DVDpRW) & 1; + DvdR = (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features2[0] >> PFNUM_DVDR) & 1; + DvdpR = (((PGET_DEVICE_INFO_USER_OUT)&ioBuf)->Features2[0] >> PFNUM_DVDpR) & 1; + } + } + + // Get device capabilities + RC = UDFPhSendIOCTL(IOCTL_CDRW_GET_CAPABILITIES,hDevice, + &ioBuf,sizeof(GET_CAPABILITIES_USER_OUT), + &ioBuf,sizeof(GET_CAPABILITIES_USER_OUT),FALSE,NULL); + if(RC != 1) { + CloseHandle(hDevice); + return OTHER; + } + + // Check capabilities + if(((PGET_CAPABILITIES_USER_OUT)&ioBuf)->WriteCap & (DevCap_write_cd_r | DevCap_write_cd_rw | DevCap_write_dvd_ram | DevCap_write_dvd_r) || + DvdRW || DvdpRW || DvdRAM) { + + if (DvdRAM || ((PGET_CAPABILITIES_USER_OUT)&ioBuf)->WriteCap & DevCap_write_dvd_ram) { + CloseHandle(hDevice); + return DVDRAM; + } +/* if (DvdR) { + CloseHandle(hDevice); + return DVDR; + }*/ + if (DvdRW) { + CloseHandle(hDevice); + return DVDRW; + } + if (DvdpRW) { + CloseHandle(hDevice); + return DVDPRW; + } +/* if (DvdpR) { + CloseHandle(hDevice); + return DVDPR; + }*/ + if (((PGET_CAPABILITIES_USER_OUT)&ioBuf)->WriteCap & DevCap_write_dvd_r) { + CloseHandle(hDevice); + return DVDR; + } + if (((PGET_CAPABILITIES_USER_OUT)&ioBuf)->WriteCap & DevCap_write_cd_rw) { + CloseHandle(hDevice); + return CDRW; + } + if (((PGET_CAPABILITIES_USER_OUT)&ioBuf)->WriteCap & DevCap_write_cd_r) { + CloseHandle(hDevice); + return CDR; + } + } + else { + CloseHandle(hDevice); + return OTHER; + } + } else { + strcpy(VendorId,"Unknown Vendor"); + } + CloseHandle(hDevice); + } + + return OTHER; +} // end CheckCDType() + +/** Intialize asbtract device list via calls to CallBack function. + \param hDlg Not used. + \param hwndControl Passed to the CallBack function. See #PADD_DEVICE. + \param CallBack Callback function. Called on each CD device in system. +*/ +void +InitDeviceList( + HWND hDlg, + HWND hwndControl, + PADD_DEVICE CallBack + ) +{ + char Buffer[MAX_PATH] = ""; + char VendorId[25]; + char seps[] = ","; + char* token; + char info[MAX_PATH]; + bool add_drive = false; + + JS_DEVICE_TYPE drive_type; + + // Get all device letter in system + GetLogicalDriveStrings((DWORD)MAX_PATH,(LPTSTR)&Buffer); + token = (char *)&Buffer; + // Replace all zeroes with comma. + while (token != NULL) { + token = (char *)memchr(Buffer,'\0',MAX_PATH); + if (token) { + if (*(token-1) == ',') { + token = NULL; + } else { + *token=','; + } + } + } + // Parse string of drive letters separated by comma + token = strtok((char *)&Buffer,seps); + while (token != NULL) { + add_drive = false; + switch (GetDriveType(token)) { +/* + case DRIVE_FIXED: + add_drive = true; + break; +*/ + case DRIVE_CDROM: + // Determine CD/DVD-ROM type (R,RW,RAM,other) + drive_type = CheckCDType(token,&VendorId[0]); + add_drive = true; + break; + } + if (add_drive) { + + // Append to drive letter VendorId + strncpy(info,token,strlen(token)-1); + info[strlen(token)-1]='\0'; + strcat(info," "); + strcat(info,VendorId); + + BOOL bSelect = !strcmp(strupr(szDisc),strupr(token)); + if (drive_type != OTHER) { + CallBack(hwndControl,token,info,MediaTypeStrings[drive_type],bSelect); + } else { + CallBack(hwndControl,token,info,"[Unsupported]",FALSE); + } + + } + // Move to the next drive letter in string + token = strtok(NULL,seps); + } +} // end InitDeviceList() + +HANDLE +FmtAcquireDrive_( + PCHAR _Drive, + CHAR Level + ) +{ + WCHAR LockName[32]; + HANDLE evt; + + WCHAR Drive[1]; + Drive[0] = _Drive[0] & ~('a' ^ 'A'); + + swprintf(LockName, L"DwFmtLock_%1.1S%d", Drive, Level); + evt = CreatePublicEvent(LockName); + if(!evt) { + return NULL; + } + if(GetLastError() == ERROR_ALREADY_EXISTS) { + CloseHandle(evt); + return INVALID_HANDLE_VALUE; + } + return evt; +} // end FmtAcquireDrive_() + +HANDLE +FmtAcquireDrive( + PCHAR Drive, + CHAR Level + ) +{ + HANDLE evt; + + evt = FmtAcquireDrive_(Drive, Level); + if(!evt || evt == INVALID_HANDLE_VALUE) { + return NULL; + } + return evt; +} // end FmtAcquireDrive() + +BOOLEAN +FmtIsDriveAcquired( + PCHAR Drive, + CHAR Level + ) +{ + HANDLE evt; + + evt = FmtAcquireDrive_(Drive, Level); + if(evt == INVALID_HANDLE_VALUE) { + return TRUE; + } + if(evt) { + CloseHandle(evt); + } + return FALSE; +} // end FmtIsDriveAcquired() + +VOID +FmtReleaseDrive( + HANDLE evt + ) +{ + if(evt) { + CloseHandle(evt); + } +} // end FmtReleaseDrive() diff --git a/pool/shard007/C++/0095983_startup_utils.cc b/pool/shard007/C++/0095983_startup_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..70a4244639fc4a4bae41227e9e6e55dacd9e810c --- /dev/null +++ b/pool/shard007/C++/0095983_startup_utils.cc @@ -0,0 +1,156 @@ +// 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 "chrome/browser/chromeos/login/startup_utils.h" + +#include "base/bind.h" +#include "base/file_util.h" +#include "base/path_service.h" +#include "base/prefs/pref_registry_simple.h" +#include "base/prefs/pref_service.h" +#include "base/sys_info.h" +#include "base/threading/thread_restrictions.h" +#include "chrome/browser/browser_process.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/pref_names.h" +#include "content/public/browser/browser_thread.h" +#include "ui/base/l10n/l10n_util.h" + +using content::BrowserThread; + +namespace { + +// Saves boolean "Local State" preference and forces its persistence to disk. +void SaveBoolPreferenceForced(const char* pref_name, bool value) { + PrefService* prefs = g_browser_process->local_state(); + prefs->SetBoolean(pref_name, value); + prefs->CommitPendingWrite(); +} + +// Saves integer "Local State" preference and forces its persistence to disk. +void SaveIntegerPreferenceForced(const char* pref_name, int value) { + PrefService* prefs = g_browser_process->local_state(); + prefs->SetInteger(pref_name, value); + prefs->CommitPendingWrite(); +} + +// Saves string "Local State" preference and forces its persistence to disk. +void SaveStringPreferenceForced(const char* pref_name, + const std::string& value) { + PrefService* prefs = g_browser_process->local_state(); + prefs->SetString(pref_name, value); + prefs->CommitPendingWrite(); +} + +} // namespace + +namespace chromeos { + +// static +void StartupUtils::RegisterPrefs(PrefRegistrySimple* registry) { + registry->RegisterBooleanPref(prefs::kOobeComplete, false); + registry->RegisterIntegerPref(prefs::kDeviceRegistered, -1); + registry->RegisterStringPref(prefs::kInitialLocale, "en-US"); +} + +// static +bool StartupUtils::IsEulaAccepted() { + return g_browser_process->local_state()->GetBoolean(prefs::kEulaAccepted); +} + +// static +bool StartupUtils::IsOobeCompleted() { + return g_browser_process->local_state()->GetBoolean(prefs::kOobeComplete); +} + +// static +void StartupUtils::MarkEulaAccepted() { + SaveBoolPreferenceForced(prefs::kEulaAccepted, true); +} + +// static +void StartupUtils::MarkOobeCompleted() { + SaveBoolPreferenceForced(prefs::kOobeComplete, true); +} + +// Returns the path to flag file indicating that both parts of OOBE were +// completed. +// On chrome device, returns /home/chronos/.oobe_completed. +// On Linux desktop, returns {DIR_USER_DATA}/.oobe_completed. +static base::FilePath GetOobeCompleteFlagPath() { + // The constant is defined here so it won't be referenced directly. + const char kOobeCompleteFlagFilePath[] = "/home/chronos/.oobe_completed"; + + if (base::SysInfo::IsRunningOnChromeOS()) { + return base::FilePath(kOobeCompleteFlagFilePath); + } else { + base::FilePath user_data_dir; + PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); + return user_data_dir.AppendASCII(".oobe_completed"); + } +} + +static void CreateOobeCompleteFlagFile() { + // Create flag file for boot-time init scripts. + base::FilePath oobe_complete_path = GetOobeCompleteFlagPath(); + if (!base::PathExists(oobe_complete_path)) { + FILE* oobe_flag_file = file_util::OpenFile(oobe_complete_path, "w+b"); + if (oobe_flag_file == NULL) + DLOG(WARNING) << oobe_complete_path.value() << " doesn't exist."; + else + file_util::CloseFile(oobe_flag_file); + } +} + +// static +bool StartupUtils::IsDeviceRegistered() { + int value = + g_browser_process->local_state()->GetInteger(prefs::kDeviceRegistered); + if (value > 0) { + // Recreate flag file in case it was lost. + BrowserThread::PostTask( + BrowserThread::FILE, + FROM_HERE, + base::Bind(&CreateOobeCompleteFlagFile)); + return true; + } else if (value == 0) { + return false; + } else { + // Pref is not set. For compatibility check flag file. It causes blocking + // IO on UI thread. But it's required for update from old versions. + base::ThreadRestrictions::ScopedAllowIO allow_io; + base::FilePath oobe_complete_flag_file_path = GetOobeCompleteFlagPath(); + bool file_exists = base::PathExists(oobe_complete_flag_file_path); + SaveIntegerPreferenceForced(prefs::kDeviceRegistered, file_exists ? 1 : 0); + return file_exists; + } +} + +// static +void StartupUtils::MarkDeviceRegistered() { + SaveIntegerPreferenceForced(prefs::kDeviceRegistered, 1); + BrowserThread::PostTask( + BrowserThread::FILE, + FROM_HERE, + base::Bind(&CreateOobeCompleteFlagFile)); +} + +// static +std::string StartupUtils::GetInitialLocale() { + std::string locale = + g_browser_process->local_state()->GetString(prefs::kInitialLocale); + if (!l10n_util::IsValidLocaleSyntax(locale)) + locale = "en-US"; + return locale; +} + +// static +void StartupUtils::SetInitialLocale(const std::string& locale) { + if (l10n_util::IsValidLocaleSyntax(locale)) + SaveStringPreferenceForced(prefs::kInitialLocale, locale); + else + NOTREACHED(); +} + +} // namespace chromeos diff --git a/pool/shard007/C++/0095985_array6.cpp b/pool/shard007/C++/0095985_array6.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2cca910c14a9c864f1dcc610b40b2f21c50093f --- /dev/null +++ b/pool/shard007/C++/0095985_array6.cpp @@ -0,0 +1,60 @@ +/* tests for using class array<> specialization for size 0 + * (C) Copyright Alisdair Meredith 2006. + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) + */ + +#include +#include +#include +#include + +#include + +namespace { + template< class T > + void RunTests() + { + typedef boost::array< T, 5 > test_type; + typedef T arr[5]; + test_type test_case; // = { 1, 1, 2, 3, 5 }; + + arr &aRef = get_c_array ( test_case ); + BOOST_TEST ( &*test_case.begin () == &aRef[0] ); + + const arr &caRef = get_c_array ( test_case ); + typename test_type::const_iterator iter = test_case.begin (); + BOOST_TEST ( &*iter == &caRef[0] ); + + // Confirm at() throws the std lib defined exception + try { + test_case.at( test_case.size()); + BOOST_TEST(false); + } + catch ( const std::out_of_range & ) {} + + try { + test_case.at( test_case.size() + 1); + BOOST_TEST(false); + } + catch ( const std::out_of_range & ) {} + + try { + test_case.at( test_case.size() + 100); + BOOST_TEST(false); + } + catch ( const std::out_of_range & ) {} + } +} + +int main () +{ + RunTests< bool >(); + RunTests< void * >(); + RunTests< long double >(); + RunTests< std::string >(); + + return boost::report_errors(); +} + diff --git a/pool/shard007/C++/0095987_AlwaysBestAdaptationLogic.cpp b/pool/shard007/C++/0095987_AlwaysBestAdaptationLogic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..053f815c9bb79bfdea626512cf8cad687c9eb12e --- /dev/null +++ b/pool/shard007/C++/0095987_AlwaysBestAdaptationLogic.cpp @@ -0,0 +1,91 @@ +/* + * AlwaysBestAdaptationLogic.cpp + ***************************************************************************** + * Copyright (C) 2010 - 2011 Klagenfurt University + * + * Created on: Aug 10, 2010 + * Authors: Christopher Mueller + * Christian Timmerer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation; either version 2.1 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 Lesser 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 HAVE_CONFIG_H +# include "config.h" +#endif + +#include "AlwaysBestAdaptationLogic.h" + +using namespace dash::logic; +using namespace dash::xml; +using namespace dash::http; +using namespace dash::mpd; + +AlwaysBestAdaptationLogic::AlwaysBestAdaptationLogic (IMPDManager *mpdManager, stream_t *stream) : + AbstractAdaptationLogic (mpdManager, stream) +{ + this->mpdManager = mpdManager; + this->count = 0; + this->initSchedule(); +} +AlwaysBestAdaptationLogic::~AlwaysBestAdaptationLogic () +{ +} + +Chunk* AlwaysBestAdaptationLogic::getNextChunk() +{ + if(this->schedule.size() == 0) + return NULL; + + if(this->count == this->schedule.size()) + return NULL; + + if ( this->count < this->schedule.size() ) + { + Chunk *chunk = new Chunk(); + chunk->setUrl(this->schedule.at( this->count )->getSourceUrl()); + this->count++; + return chunk; + } + return NULL; +} + +const Representation *AlwaysBestAdaptationLogic::getCurrentRepresentation() const +{ + if ( this->count < this->schedule.size() ) + return this->schedule.at( this->count )->getParentRepresentation(); + return NULL; +} + +void AlwaysBestAdaptationLogic::initSchedule () +{ + if(this->mpdManager != NULL) + { + std::vector periods = this->mpdManager->getPeriods(); + + for(size_t i = 0; i < periods.size(); i++) + { + Representation *best = this->mpdManager->getBestRepresentation(periods.at(i)); + + if(best != NULL) + { + std::vector segments = this->mpdManager->getSegments(best); + for(size_t j = 0; j < segments.size(); j++) + { + this->schedule.push_back(segments.at(j)); + } + } + } + } +} diff --git a/pool/shard007/C++/0095989_Game.cpp b/pool/shard007/C++/0095989_Game.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb8f644763f4edf07825ca853fe44f80980aed56 --- /dev/null +++ b/pool/shard007/C++/0095989_Game.cpp @@ -0,0 +1,78 @@ +#include "stdafx.h" +#include "Game.h" + +Game * Game::instance = nullptr; +using namespace std::chrono; + +Game::Game(int windowwidth, int windowheight) +{ + const char* versionStr = (const char*)glGetString(GL_VERSION); + glVersion = 30; + if (strstr(versionStr, "OpenGL ES 3.0")) { + glVersion = 30; + } + if (strstr(versionStr, "OpenGL ES 3.1")) { + glVersion = 31; + } + if (strstr(versionStr, "OpenGL ES 3.2")) { + glVersion = 32; + } + ALOGV("GL WIDTH %d HEIGHT %d\n", windowheight, windowwidth); + instance = this; + width = windowwidth; + height = windowheight; + invokeQueue = queue>(); + onRenderFrame = {}; + asset = new AssetLoader(); + world = new World(); + mouse = glm::vec2(0.0); + renderer = new Renderer(width * 0.5, height*0.5); + shaders = new GenericShaders(); + screenFbo = new Framebuffer(width, height, (GLuint)0); + onRenderFrame = new EventHandler(); + onRenderUIFrame = new EventHandler(); + onWindowResize = new EventHandler(); + onKeyPress = new EventHandler(); + onKeyRelease = new EventHandler(); + onKeyRepeat = new EventHandler(); + time = 0.0; + glClearColor(0, 0, 0, 0); + glClearDepthf(1); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glDepthFunc(GL_LEQUAL); +} + +Game::~Game() +{ +} + +void Game::invoke(const function &func) +{ + invokeQueue.push(func); +} + +void Game::display(string str) +{ + cout << str; +} + +void Game::onRenderFrameFunc() +{ + time += 1.0/7.0; + firstFullDrawFinished = false; + while (invokeQueue.size() > 0) { + invokeQueue.front()(); + invokeQueue.pop(); + } + onRenderFrame->invoke(0); + + if (world->mainDisplayCamera != nullptr) { + /*vector lights = world->scene->getLights(); + for (int i = 0; i < lights.size(); i++) { + lights[i]->refreshShadowMap(); + }*/ + renderer->renderToFramebuffer(world->mainDisplayCamera, screenFbo); + } + onRenderUIFrame->invoke(0); +} \ No newline at end of file diff --git a/pool/shard007/C++/0095991_popup.cpp b/pool/shard007/C++/0095991_popup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0b2ce97ee7afce69a8e741f12fc8d00aac31d68 --- /dev/null +++ b/pool/shard007/C++/0095991_popup.cpp @@ -0,0 +1,71 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "ultima/shared/gfx/popup.h" +#include "ultima/shared/early/game_base.h" + +namespace Ultima { +namespace Shared { +namespace Gfx { + +BEGIN_MESSAGE_MAP(Popup, VisualItem) + ON_MESSAGE(ShowMsg) +END_MESSAGE_MAP() + +Popup::Popup(GameBase *game) : VisualItem(nullptr), _game(game), _respondTo(nullptr), _parentView(nullptr) { + game->addChild(this); +} + +Popup::~Popup() { + detach(); +} + +void Popup::show(TreeItem *respondTo) { + // Save a copy of the view the popup is being shown on, and activate it + _parentView = _game->getView(); + _respondTo = respondTo; + if (!_respondTo) + _respondTo = _parentView; + + _game->setPopup(this); + setDirty(); +} + + +void Popup::hide() { + CPopupHiddenMsg hiddenMsg(this); + hiddenMsg.execute(_respondTo, nullptr, 0); + + // Reset back to the parent view + _game->setView(_parentView); + _parentView->setDirty(); +} + +bool Popup::ShowMsg(CShowMsg &msg) { + CPopupShownMsg shownMsg(this); + shownMsg.execute(_respondTo, nullptr, 0); + return true; +} + +} // End of namespace Gfx +} // End of namespace Shared +} // End of namespace Ultima diff --git a/pool/shard007/C++/0095993_LuckyTicketSubstring.cpp b/pool/shard007/C++/0095993_LuckyTicketSubstring.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1dda60b4e851d9024cc063a9e06d2b4355ccdda8 --- /dev/null +++ b/pool/shard007/C++/0095993_LuckyTicketSubstring.cpp @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define all(v)begin(v),end(v) +#define dump(v)copy(all(v),ostream_iterator(cout,"\n")) +#define rg(i,a,b)for(int i=a,i##e=b;i=0;--i) +#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1) +#define sz(v)int(v.size()) +#define sr(v)sort(all(v)) +#define rs(v)sort(all(v),greater()) +#define rev(v)reverse(all(v)) +#define eb emplace_back +#define stst stringstream +#define big numeric_limits::max() +#define g(t,i)get(t) +#define cb(v,w)copy(all(v),back_inserter(w)) +#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v)) +#define vt(...)vector> +#define smx(a,b)a=max(a,b) +#define smn(a,b)a=min(a,b) +#define words(w,q)vectorw;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q); +#define digits(d,n,s)vectord;[&d](int m){while(m)d.eb(m%s),m/=s;}(n); +typedef long long ll; +using namespace std; + +struct LuckyTicketSubstring { + int maxLength(string s) { + const int q = sz(s); + int mx = 0; + for (int i = 0; i < q; ++i) for (int j = i + 2; j <= q; ++j) if ((j - i) % 2 == 0) { + int m = (j + i) / 2; + int t = 0; + for (int k = i; k < m; ++k) t += s[k] - '0'; + for (int k = m; k < j; ++k) t -= s[k] - '0'; + cout << s.substr(i, j - i) << ' ' << t << endl; + if (t == 0) mx = max(mx, j - i); + } + return mx; + } +}; + +// BEGIN KAWIGIEDIT TESTING +// Generated by KawigiEdit-pf 2.3.0 +#include +#include +#include +#include +#include +using namespace std; +bool KawigiEdit_RunTest(int testNum, string p0, bool hasAnswer, int p1) { + cout << "Test " << testNum << ": [" << "\"" << p0 << "\""; + cout << "]" << endl; + LuckyTicketSubstring *obj; + int answer; + obj = new LuckyTicketSubstring(); + clock_t startTime = clock(); + answer = obj->maxLength(p0); + clock_t endTime = clock(); + delete obj; + bool res; + res = true; + cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; + if (hasAnswer) { + cout << "Desired answer:" << endl; + cout << "\t" << p1 << endl; + } + cout << "Your answer:" << endl; + cout << "\t" << answer << endl; + if (hasAnswer) { + res = answer == p1; + } + if (!res) { + cout << "DOESN'T MATCH!!!!" << endl; + } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { + cout << "FAIL the timeout" << endl; + res = false; + } else if (hasAnswer) { + cout << "Match :-)" << endl; + } else { + cout << "OK, but is it right?" << endl; + } + cout << "" << endl; + return res; +} +int main() { + bool all_right; + bool disabled; + bool tests_disabled; + all_right = true; + tests_disabled = false; + + string p0; + int p1; + + // ----- test 0 ----- + disabled = false; + p0 = "123231"; + p1 = 6; + all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right; + tests_disabled = tests_disabled || disabled; + // ------------------ + + // ----- test 1 ----- + disabled = false; + p0 = "74233285"; + p1 = 4; + all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right; + tests_disabled = tests_disabled || disabled; + // ------------------ + + // ----- test 2 ----- + disabled = false; + p0 = "986561517416921217551395112859219257312"; + p1 = 36; + all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right; + tests_disabled = tests_disabled || disabled; + // ------------------ + + // ----- test 3 ----- + disabled = false; + p0 = "1"; + p1 = 0; + all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right; + tests_disabled = tests_disabled || disabled; + // ------------------ + + // ----- test 4 ----- + disabled = false; + p0 = "112"; + p1 = 2; + all_right = (disabled || KawigiEdit_RunTest(4, p0, true, p1) ) && all_right; + tests_disabled = tests_disabled || disabled; + // ------------------ + + if (all_right) { + if (tests_disabled) { + cout << "You're a stud (but some test cases were disabled)!" << endl; + } else { + cout << "You're a stud (at least on given cases)!" << endl; + } + } else { + cout << "Some of the test cases had errors." << endl; + } + return 0; +} +// END KAWIGIEDIT TESTING diff --git a/pool/shard007/C++/0095994_sendrecv_test.cpp b/pool/shard007/C++/0095994_sendrecv_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7fe3a3eeda4f8f7915da75447874d3e751e481b --- /dev/null +++ b/pool/shard007/C++/0095994_sendrecv_test.cpp @@ -0,0 +1,62 @@ +// Copyright Alain Miniussi 2014. +// 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) + +// A test of the sendrecv() operation. +#include +#include +#include +#include +#include +#include +#include +#include + +#define BOOST_TEST_MODULE mpi_sendrecv +#include + +namespace mpi = boost::mpi; + +struct blob { + blob(int i) : value(i) {} + int value; + template + void serialize(Archive& s, const unsigned int version) { + s & value; + } +}; + +std::ostream& operator<<(std::ostream& out, blob const& b) { + out << "blob(" << b.value << ")"; + return out; +} + +bool operator==(blob const& b1, blob const& b2) { + return b1.value == b2.value; +} + +template +void test_sendrecv(mpi::communicator& com) { + int const wrank = com.rank(); + int const wsize = com.size(); + int const wnext((wrank + 1) % wsize); + int const wprev((wrank + wsize - 1) % wsize); + T recv(-1); + com.sendrecv(wnext, 1, T(wrank), wprev, 1, recv); + for(int r = 0; r < wsize; ++r) { + com.barrier(); + if (r == wrank) { + std::cout << "rank " << wrank << " received " << recv << " from " << wprev << '\n'; + } + } + BOOST_CHECK(recv == T(wprev)); +} + +BOOST_AUTO_TEST_CASE(sendrecv) +{ + mpi::environment env; + mpi::communicator world; + test_sendrecv(world); + test_sendrecv(world); +} diff --git a/pool/shard007/C++/0095996_velocity2dwidget.cpp b/pool/shard007/C++/0095996_velocity2dwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90fdfe5942e3f59726d226f204de1c8274e8ccae --- /dev/null +++ b/pool/shard007/C++/0095996_velocity2dwidget.cpp @@ -0,0 +1,78 @@ +/*************************************************************************** + * Project: RAPI * + * Author: Jens Wawerla (jwawerla@sfu.ca) * + * $Id: $ + *************************************************************************** + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + **************************************************************************/ +#include "velocity2dwidget.h" +#include "utilities.h" +#include "unicodechar.h" + +#include + +namespace Rapi +{ + +//----------------------------------------------------------------------------- +CVelocity2dWidget::CVelocity2dWidget ( QWidget* parent ) + : QGroupBox ( parent ) +{ + setTitle ( "Velocity" ); + setFlat ( false ); + setCheckable ( true ); + + QHBoxLayout* layout = new QHBoxLayout ( this ); + + mXDotLine = new CDataLine ( this, "Vx [m/s]" ); + mXDotLine->setFloatPrecision(3); + layout->addWidget ( mXDotLine ); + mXDotLine->setColorEnable( true ); + + mYDotLine = new CDataLine ( this, "Vy [m/s]" ); + mYDotLine->setFloatPrecision(3); + layout->addWidget ( mYDotLine ); + mYDotLine->setColorEnable( true ); + + mYawDotLine = new CDataLine ( this, "V"+Q_YAW+" ["+Q_DEGREE+"/s]" ); + layout->addWidget ( mYawDotLine ); + + setLayout ( layout ); +} +//----------------------------------------------------------------------------- +CVelocity2dWidget::~CVelocity2dWidget() +{ +} +//----------------------------------------------------------------------------- +void CVelocity2dWidget::updateData(CVelocity2d velocity) +{ + if ( isChecked() ) { + mXDotLine->setHidden ( false ); + mYDotLine->setHidden ( false ); + mYawDotLine->setHidden ( false ); + + mXDotLine->setData ( velocity.mXDot ); + mYDotLine->setData ( velocity.mYDot ); + mYawDotLine->setData ( R2D ( velocity.mYawDot ) ); + } + else { + mXDotLine->setHidden ( true ); + mYDotLine->setHidden ( true ); + mYawDotLine->setHidden ( true ); + } +} +//----------------------------------------------------------------------------- +} // namespace diff --git a/pool/shard007/C++/0095998_polymorphysm.cpp b/pool/shard007/C++/0095998_polymorphysm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7146a798f7c518ab2dc2eb2cdc9c0b0debcb6652 --- /dev/null +++ b/pool/shard007/C++/0095998_polymorphysm.cpp @@ -0,0 +1,77 @@ +// polymorphysm.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" + +using namespace std; + +class ISerializable +{ +public: + virtual void Serialize(ostream & strm)const = 0; + virtual ~ISerializable(){} +}; + +class CCat : public ISerializable +{ +public: + void Serialize(ostream & strm)const override + { + strm << "cat" << endl; + } +}; + +class CShape : public ISerializable +{ +public: + virtual double GetArea()const = 0; +}; + +class CCircle : public CShape +{ +public: + void Serialize(ostream & strm)const override + { + strm << "circle:" << m_radius << endl; + } + double GetArea()const override + { + return M_PI * m_radius * m_radius; + } +private: + int m_radius = 42; +}; + +void DoSomethingWithShape(CShape & shape) +{ + shape.Serialize(cout); + ostringstream strm; + shape.Serialize(strm); + + cout << "Shape area is " << shape.GetArea() << endl; +} + +void Serialize(vector const & someSerializableObjects, ostream & strm) +{ + for (auto obj : someSerializableObjects) + { + obj->Serialize(strm); + } +} + +int _tmain(int argc, _TCHAR* argv[]) +{ + CCircle circle; + CCat cat; + DoSomethingWithShape(circle); + cout << "----" << endl; + vector objects = { &cat, &circle }; + Serialize(objects, cout); + ostringstream strm; + Serialize(objects, strm); + cout << "!!!" << strm.str() << "!!!" << endl; + + + return 0; +} + diff --git a/pool/shard007/C++/0095999_FreeSymmetricRateMatrixFunction.cpp b/pool/shard007/C++/0095999_FreeSymmetricRateMatrixFunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8be8b96c6e310a0e504b5a5c0ca9b8f45a5132e2 --- /dev/null +++ b/pool/shard007/C++/0095999_FreeSymmetricRateMatrixFunction.cpp @@ -0,0 +1,75 @@ +#include "FreeSymmetricRateMatrixFunction.h" + +#include +#include +#include + +#include "RateMatrix_FreeSymmetric.h" +#include "Cloneable.h" +#include "RbVector.h" +#include "TypedDagNode.h" + +namespace RevBayesCore { class DagNode; } + +using namespace RevBayesCore; + +/** + * Default constructor. + * + * This function takes three inputs: + * @param tr The vector of substitution rates, whose number of elements equals half the number of the off-diagonal entries of the rate matrix. + * @param r Should the rates be rescaled so that the average rate equals 1? + * @param method Matrix exponentiation method. + */ + +FreeSymmetricRateMatrixFunction::FreeSymmetricRateMatrixFunction(const TypedDagNode< RbVector > *tr, bool r, std::string method) : TypedFunction( NULL ), + transition_rates( tr ) +{ + double num_off_diag_states = 2*tr->getValue().size(); + double tmp_num_states = 0.5 + sqrt(0.25+num_off_diag_states); + size_t num_states = size_t( round( tmp_num_states ) ); + value = new RateMatrix_FreeSymmetric( num_states, r, method ); + + // add the rate and frequency parameters as parents + addParameter( transition_rates ); + + update(); +} + + +FreeSymmetricRateMatrixFunction::~FreeSymmetricRateMatrixFunction( void ) +{ + // We don't delete the parameters, because they might be used somewhere else too. The model needs to do that! +} + + + +FreeSymmetricRateMatrixFunction* FreeSymmetricRateMatrixFunction::clone( void ) const +{ + return new FreeSymmetricRateMatrixFunction( *this ); +} + + +void FreeSymmetricRateMatrixFunction::update( void ) +{ + // get the information from the arguments for reading the file + const std::vector& trr = transition_rates->getValue(); + + // set the base frequencies + static_cast< RateMatrix_FreeSymmetric* >(value)->setTransitionRates(trr); + + value->update(); +} + + + +void FreeSymmetricRateMatrixFunction::swapParameterInternal(const DagNode *oldP, const DagNode *newP) +{ + + if (oldP == transition_rates) + { + transition_rates = static_cast >* >( newP ); + } + +} + diff --git a/pool/shard007/C++/0096001_Debugger-Symbols.cpp b/pool/shard007/C++/0096001_Debugger-Symbols.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5392b6984efa6f7e3f885fa65840a567ffaf7e07 --- /dev/null +++ b/pool/shard007/C++/0096001_Debugger-Symbols.cpp @@ -0,0 +1,181 @@ +/**************************************************************************** +* * +* Project64 - A Nintendo 64 emulator. * +* http://www.pj64-emu.com/ * +* Copyright (C) 2012 Project64. All rights reserved. * +* * +* License: * +* GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html * +* * +****************************************************************************/ + +#include "stdafx.h" +#include "DebuggerUI.h" + +#include +#include + +#include "Symbols.h" + +CDebugSymbols::CDebugSymbols(CDebuggerUI * debugger) : + CDebugDialog(debugger) +{ +} + +LRESULT CDebugSymbols::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) +{ + DlgResize_Init(false, true); + + m_SymbolsListView.Attach(GetDlgItem(IDC_SYMBOLS_LIST)); + m_SymbolsListView.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER); + + m_SymbolsListView.AddColumn("Address", 0); + m_SymbolsListView.AddColumn("Type", 1); + m_SymbolsListView.AddColumn("Name", 2); + m_SymbolsListView.AddColumn("Value", 3); + m_SymbolsListView.AddColumn("Description", 4); + + m_SymbolsListView.SetColumnWidth(0, 70); + m_SymbolsListView.SetColumnWidth(1, 40); + m_SymbolsListView.SetColumnWidth(2, 120); + m_SymbolsListView.SetColumnWidth(3, 100); + m_SymbolsListView.SetColumnWidth(4, 120); + + Refresh(); + + m_AutoRefreshThread = CreateThread(NULL, 0, AutoRefreshProc, (void*)this, 0, NULL); + + WindowCreated(); + return 0; +} + +LRESULT CDebugSymbols::OnDestroy(void) +{ + m_SymbolsListView.Detach(); + if (m_AutoRefreshThread != NULL) + { + TerminateThread(m_AutoRefreshThread, 0); + CloseHandle(m_AutoRefreshThread); + } + return 0; +} + +DWORD WINAPI CDebugSymbols::AutoRefreshProc(void* _this) +{ + CDebugSymbols* self = (CDebugSymbols*)_this; + while (true) + { + self->RefreshValues(); + Sleep(100); + } +} + +LRESULT CDebugSymbols::OnClicked(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) +{ + switch (wID) + { + case IDCANCEL: + EndDialog(0); + break; + case IDC_ADDSYMBOL_BTN: + m_AddSymbolDlg.DoModal(m_Debugger); + break; + case IDC_REMOVESYMBOL_BTN: + { + int id = m_SymbolsListView.GetItemData(m_SymbolsListView.GetSelectedIndex()); + CSymbols::EnterCriticalSection(); + CSymbols::RemoveEntryById(id); + CSymbols::Save(); + CSymbols::LeaveCriticalSection(); + Refresh(); + break; + } + } + return FALSE; +} + +LRESULT CDebugSymbols::OnListDblClicked(NMHDR* pNMHDR) +{ + // Open it in memory viewer/commands viewer + NMITEMACTIVATE* pIA = reinterpret_cast(pNMHDR); + int nItem = pIA->iItem; + + int id = m_SymbolsListView.GetItemData(nItem); + CSymbolEntry* symbol = CSymbols::GetEntryById(id); + + if (symbol->m_Type == 0) // code + { + m_Debugger->Debug_ShowCommandsLocation(symbol->m_Address, true); + } + else // data/number + { + m_Debugger->Debug_ShowMemoryLocation(symbol->m_Address, true); + } + + return 0; +} + +void CDebugSymbols::Refresh() +{ + if (m_SymbolsListView.m_hWnd == NULL) + { + return; + } + m_SymbolsListView.SetRedraw(FALSE); + m_SymbolsListView.DeleteAllItems(); + + CSymbols::EnterCriticalSection(); + + int count = CSymbols::GetCount(); + + for (int i = 0; i < count; i++) + { + CSymbolEntry* lpSymbol = CSymbols::GetEntryByIndex(i); + + stdstr addrStr = stdstr_f("%08X", lpSymbol->m_Address); + + m_SymbolsListView.AddItem(i, 0, addrStr.c_str()); + m_SymbolsListView.AddItem(i, 1, lpSymbol->TypeName()); + m_SymbolsListView.AddItem(i, 2, lpSymbol->m_Name); + m_SymbolsListView.AddItem(i, 4, lpSymbol->m_Description); + + m_SymbolsListView.SetItemData(i, lpSymbol->m_Id); + + if (g_MMU) + { + char szValue[64]; + CSymbols::GetValueString(szValue, lpSymbol); + m_SymbolsListView.AddItem(i, 3, szValue); + } + } + + CSymbols::LeaveCriticalSection(); + + m_SymbolsListView.SetRedraw(TRUE); +} + +void CDebugSymbols::RefreshValues() +{ + if (g_MMU == NULL) + { + return; + } + + int count = m_SymbolsListView.GetItemCount(); + + CSymbols::EnterCriticalSection(); + + for (int i = 0; i < count; i++) + { + int symbolId = m_SymbolsListView.GetItemData(i); + + CSymbolEntry* lpSymbol = CSymbols::GetEntryById(symbolId); + + char szValue[64]; + CSymbols::GetValueString(szValue, lpSymbol); + + m_SymbolsListView.SetItemText(i, 3, szValue); + } + + CSymbols::LeaveCriticalSection(); +} \ No newline at end of file diff --git a/pool/shard007/C++/0096003_shell_main_delegate.cc b/pool/shard007/C++/0096003_shell_main_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..d2759270ba1ed2f108a0d1bac1e0b0589a258806 --- /dev/null +++ b/pool/shard007/C++/0096003_shell_main_delegate.cc @@ -0,0 +1,175 @@ +// 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 "extensions/shell/app/shell_main_delegate.h" + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "build/build_config.h" +#include "content/public/browser/browser_main_runner.h" +#include "content/public/common/content_switches.h" +#include "extensions/common/extension_paths.h" +#include "extensions/shell/browser/default_shell_browser_main_delegate.h" +#include "extensions/shell/browser/shell_content_browser_client.h" +#include "extensions/shell/common/shell_content_client.h" +#include "extensions/shell/renderer/shell_content_renderer_client.h" +#include "extensions/shell/utility/shell_content_utility_client.h" +#include "ui/base/resource/resource_bundle.h" + +#if defined(OS_CHROMEOS) +#include "chromeos/chromeos_paths.h" +#endif + +#if defined(OS_MACOSX) +#include "base/mac/foundation_util.h" +#include "extensions/shell/app/paths_mac.h" +#endif + +#if !defined(DISABLE_NACL) +#include "components/nacl/common/nacl_switches.h" +#if defined(OS_LINUX) +#include "components/nacl/common/nacl_paths.h" +#endif // OS_LINUX +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) +#include "components/nacl/zygote/nacl_fork_delegate_linux.h" +#endif // OS_POSIX && !OS_MACOSX && !OS_ANDROID +#endif // !DISABLE_NACL + +namespace { + +void InitLogging() { + base::FilePath log_filename; + PathService::Get(base::DIR_EXE, &log_filename); + log_filename = log_filename.AppendASCII("app_shell.log"); + logging::LoggingSettings settings; + settings.logging_dest = logging::LOG_TO_ALL; + settings.log_file = log_filename.value().c_str(); + settings.delete_old = logging::DELETE_OLD_LOG_FILE; + logging::InitLogging(settings); + logging::SetLogItems(true, true, true, true); +} + +// Returns the path to the extensions_shell_and_test.pak file. +base::FilePath GetResourcesPakFilePath() { +#if defined(OS_MACOSX) + return base::mac::PathForFrameworkBundleResource( + CFSTR("extensions_shell_and_test.pak")); +#else + base::FilePath extensions_shell_and_test_pak_path; + PathService::Get(base::DIR_MODULE, &extensions_shell_and_test_pak_path); + extensions_shell_and_test_pak_path = + extensions_shell_and_test_pak_path.AppendASCII( + "extensions_shell_and_test.pak"); + return extensions_shell_and_test_pak_path; +#endif // OS_MACOSX +} + +} // namespace + +namespace extensions { + +ShellMainDelegate::ShellMainDelegate() { +} + +ShellMainDelegate::~ShellMainDelegate() { +} + +bool ShellMainDelegate::BasicStartupComplete(int* exit_code) { + InitLogging(); + content_client_.reset(CreateContentClient()); + SetContentClient(content_client_.get()); + +#if defined(OS_MACOSX) + OverrideChildProcessFilePath(); + // This must happen before InitializeResourceBundle. + OverrideFrameworkBundlePath(); +#endif + +#if defined(OS_CHROMEOS) + chromeos::RegisterPathProvider(); +#endif +#if !defined(DISABLE_NACL) && defined(OS_LINUX) + nacl::RegisterPathProvider(); +#endif + extensions::RegisterPathProvider(); + return false; +} + +void ShellMainDelegate::PreSandboxStartup() { + std::string process_type = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kProcessType); + if (ProcessNeedsResourceBundle(process_type)) + InitializeResourceBundle(); +} + +content::ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() { + browser_client_.reset(CreateShellContentBrowserClient()); + return browser_client_.get(); +} + +content::ContentRendererClient* +ShellMainDelegate::CreateContentRendererClient() { + renderer_client_.reset(CreateShellContentRendererClient()); + return renderer_client_.get(); +} + +content::ContentUtilityClient* ShellMainDelegate::CreateContentUtilityClient() { + utility_client_.reset(CreateShellContentUtilityClient()); + return utility_client_.get(); +} + +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) +void ShellMainDelegate::ZygoteStarting( + ScopedVector* delegates) { +#if !defined(DISABLE_NACL) + nacl::AddNaClZygoteForkDelegates(delegates); +#endif // DISABLE_NACL +} +#endif // OS_POSIX && !OS_MACOSX && !OS_ANDROID + +content::ContentClient* ShellMainDelegate::CreateContentClient() { + return new ShellContentClient(); +} + +content::ContentBrowserClient* +ShellMainDelegate::CreateShellContentBrowserClient() { + return new ShellContentBrowserClient(new DefaultShellBrowserMainDelegate()); +} + +content::ContentRendererClient* +ShellMainDelegate::CreateShellContentRendererClient() { + return new ShellContentRendererClient(); +} + +content::ContentUtilityClient* +ShellMainDelegate::CreateShellContentUtilityClient() { + return new ShellContentUtilityClient(); +} + +void ShellMainDelegate::InitializeResourceBundle() { + ui::ResourceBundle::InitSharedInstanceWithPakPath( + GetResourcesPakFilePath()); +} + +// static +bool ShellMainDelegate::ProcessNeedsResourceBundle( + const std::string& process_type) { + // The browser process has no process type flag, but needs resources. + // On Linux the zygote process opens the resources for the renderers. + return process_type.empty() || + process_type == switches::kZygoteProcess || + process_type == switches::kRendererProcess || +#if !defined(DISABLE_NACL) + process_type == switches::kNaClLoaderProcess || +#endif +#if defined(OS_MACOSX) + process_type == switches::kGpuProcess || +#endif + process_type == switches::kUtilityProcess; +} + +} // namespace extensions diff --git a/pool/shard007/C++/0096004_CodeParser.cpp b/pool/shard007/C++/0096004_CodeParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da56eb06fe4a353a06cef244f4de210cde4acb58 --- /dev/null +++ b/pool/shard007/C++/0096004_CodeParser.cpp @@ -0,0 +1,227 @@ +/** + * NDS Toolkit - A suite of tools for hacking Nintendo video games. + * Copyright (C) 2012 Vinny Diehl + * + * 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 . +**/ + +/** + * @file CodeParser.cpp - Class with static methods for code verification. + * + * See #1 on the issue tracker. +**/ + +#include "CodeParser.h" + +/** Public Methods **/ + +wxString CodeParser::Beautify(wxString code, int flags) +{ + /** + * Fix the formatting of NDS code. + * + * @param code - Code to be beautified. + * @param flags - Code parser options. + **/ + + // First verify the input, or risk death. + if (!Verify(code)) + return _T("Invalid"); + + // Split the input into lines... + wxArrayString raw = wxc::wxSplit(code, _T('\n')); + + // Build the code onto here. + wxArrayString processed; + + for (size_t i = 0; i < raw.GetCount(); ++i) + { + // Trim everything. + wxString line = raw[i].Trim().Trim(false); + + // Skip comments/blank lines if they aren't allowed. + if ((flags & STRIP_COMMENTS && line[0] == _T(':')) || + (flags & STRIP_BLANK_LINES && line.IsEmpty())) + continue; + + // Add comments and blank lines directly... + if (line[0] == _T(':') || line.IsEmpty()) + processed.Add(line); + // Otherwise it's a line of code... + else + { + // Enforce the UPPER_HEX option. + if (flags & UPPER_HEX) + line.MakeUpper(); + + // Remove the whitespace. + wxString builder; + for (size_t j = 0; j < line.Len(); ++j) + if (!(wxString(_T(" \t"))).Contains(line[j])) + builder += line[j]; + + // Condense all hunks of code into one line. + // If processed is empty, or the last line in processed is + // either a blank or a comment, we need to start a new code line. + if (processed.IsEmpty() || + processed.Last().IsEmpty() || + processed.Last()[0] == _T(':')) + processed.Add(builder); + // Otherwise, append onto the current going code line. + else processed[processed.GetCount() - 1] += builder; + } + } + + // Build the final result onto here. + wxArrayString final; + + for (size_t i = 0; i < processed.GetCount(); ++i) + { + wxString line = processed[i]; + + if (line[0] == _T(':') || line.IsEmpty()) + final.Add(line); + else + { + // If we don't have the right number of characters, uh-oh... + // bail out and call it invalid. + if (line.Len() % 16 != 0) + return _T("Invalid"); + + while (!line.IsEmpty()) + { + final.Add(line.Left(16).insert(8, _T(" "))); + line.Remove(0, 16); + } + } + } + + // Trim any whitespace on either end before returning. + return wxc::wxJoin(final, _T('\n')).Trim().Trim(false); +} + +bool CodeParser::Verify(wxString code) +{ + /** + * Return true if the input is valid as NDS code, otherwise return false. + **/ + + /** Preprocessing **/ + + // Strip away stuff that we don't need; Comments, blanks, extra whitespace. + wxArrayString raw = wxc::wxSplit(code, _T('\n')); + + wxArrayString lines; + for (size_t i = 0; i < raw.GetCount(); ++i) + { + // Trim the current line so whitespace doesn't throw us off + wxString line = raw[i].Trim().Trim(false); + + if (!line.IsEmpty() && line[0] != _T(':')) + lines.Add(line); + } + + // Strip the rest of the whitespace. + // Yes, I know, I join with newlines and then strip the newlines. I just + // want to ensure that the code is returned to its previous state before + // all of the whitespace is removed. + code = mStripChar(wxc::wxJoin(lines, _T('\n')), _T(" \t\n\r")); + + // Now that it's parsed, we just need to see whether or not it has the + // right amount of digits (some multiple of 16), and if it is valid + // hexadecimal. We can return whatever result we get from that. + return code.Len() % 16 == 0 && IsHex(code); +} +bool CodeParser::IsHex(wxString str) +{ + /** + * Return true if str is a valid hexadecimal value, false otherwise. + **/ + + return HEX.Matches(str); +} + +wxArrayString CodeParser::LeftColumn(wxString code) +{ + wxArrayString output; + + wxArrayString lines = wxc::wxSplit(code, _T('\n')); + for (size_t i = 0; i < lines.GetCount(); ++i) + output.Add(lines[i].Left(8)); + + return output; +} +wxArrayString CodeParser::RightColumn(wxString code) +{ + wxArrayString output; + + wxArrayString lines = wxc::wxSplit(code, _T('\n')); + for (size_t i = 0; i < lines.GetCount(); ++i) + output.Add(lines[i].Right(8)); + + return output; +} +void CodeParser::SplitColumns(wxString code, wxArrayString *left, + wxArrayString *right) +{ + *left = LeftColumn(code); + *right = RightColumn(code); +} +wxString CodeParser::JoinColumns(wxArrayString left, wxArrayString right) +{ + wxArrayString pairs; + + // Just in case they gave us arrays of differing sizes, always use the + // smaller count to loop with... + size_t count = left.GetCount() > right.GetCount() + ? right.GetCount() + : left.GetCount(); + + for (size_t i = 0; i < count; ++i) + pairs.Add(left[i] + _T(' ') + right[i]); + + return wxc::wxJoin(pairs, _T('\n')); +} + +/** Private Methods **/ + +wxString CodeParser::mStripChar(wxString str, wxString ch) +{ + /** + * Remove all of a certain character/characters out of a string. + * + * @param str - The string to be processed. + * @param ch - The character(s) to be removed. + **/ + + wxString output; + + // Loop over the characters in str. + for (size_t i = 0; i < str.Len(); ++i) + { + bool isallowed = true; + + // Check if any of the characters in ch match the current character. + // If any of them do, the character will be stripped. + for (size_t j = 0; j < ch.Len(); ++j) + if (str[i] == ch[j]) + isallowed = false; + + // If it wasn't stripped, add it to the output. + if (isallowed) + output += str[i]; + } + + return output; +} diff --git a/pool/shard007/C++/0096005_init.cpp b/pool/shard007/C++/0096005_init.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0be09c7ac1cdc2a8ce78728cd1961e3982112ef --- /dev/null +++ b/pool/shard007/C++/0096005_init.cpp @@ -0,0 +1,41 @@ +#include "init.h" +#include "log.h" + +#include "bcm_host.h" +#include "OMX_consts.h" + +using v8::Value; + +namespace NodeOMX { + + void bcm_host_init(const Nan::FunctionCallbackInfo& info) { + plog("bcm_host_init"); + ::bcm_host_init(); + } + + void bcm_host_deinit(const Nan::FunctionCallbackInfo& info) { + plog("bcm_host_deinit"); + ::bcm_host_deinit(); + } + + void OMX_Init(const Nan::FunctionCallbackInfo& info) { + plog("OMX_Init"); + OMX_ERRORTYPE rc = ::OMX_Init(); + if (rc != OMX_ErrorNone) { + char buf[255]; + sprintf(buf, "OMX_Init() returned error: %s, have you called bcm_host_init?", OMX_consts::err2str(rc)); + Nan::ThrowError(buf); + return; + } + } + void OMX_Deinit(const Nan::FunctionCallbackInfo& info) { + plog("OMX_Deinit"); + OMX_ERRORTYPE rc = ::OMX_Deinit(); + if (rc != OMX_ErrorNone) { + char buf[255]; + sprintf(buf, "OMX_Deinit() returned error: %s", OMX_consts::err2str(rc)); + Nan::ThrowError(buf); + return; + } + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0096007_MCSchedule.cpp b/pool/shard007/C++/0096007_MCSchedule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..929bd7f6046cc3e19dc45a8df25c08281f9c5e8e --- /dev/null +++ b/pool/shard007/C++/0096007_MCSchedule.cpp @@ -0,0 +1,152 @@ +//===- MCSchedule.cpp - Scheduling ------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the default scheduling model. +// +//===----------------------------------------------------------------------===// + +#include "llvm/MC/MCSchedule.h" +#include "llvm/MC/MCInst.h" +#include "llvm/MC/MCInstrDesc.h" +#include "llvm/MC/MCInstrInfo.h" +#include "llvm/MC/MCSubtargetInfo.h" +#include + +using namespace llvm; + +static_assert(std::is_pod::value, + "We shouldn't have a static constructor here"); +const MCSchedModel MCSchedModel::Default = {DefaultIssueWidth, + DefaultMicroOpBufferSize, + DefaultLoopMicroOpBufferSize, + DefaultLoadLatency, + DefaultHighLatency, + DefaultMispredictPenalty, + false, + true, + 0, + nullptr, + nullptr, + 0, + 0, + nullptr, + nullptr}; + +int MCSchedModel::computeInstrLatency(const MCSubtargetInfo &STI, + const MCSchedClassDesc &SCDesc) { + int Latency = 0; + for (unsigned DefIdx = 0, DefEnd = SCDesc.NumWriteLatencyEntries; + DefIdx != DefEnd; ++DefIdx) { + // Lookup the definition's write latency in SubtargetInfo. + const MCWriteLatencyEntry *WLEntry = + STI.getWriteLatencyEntry(&SCDesc, DefIdx); + // Early exit if we found an invalid latency. + if (WLEntry->Cycles < 0) + return WLEntry->Cycles; + Latency = std::max(Latency, static_cast(WLEntry->Cycles)); + } + return Latency; +} + +int MCSchedModel::computeInstrLatency(const MCSubtargetInfo &STI, + unsigned SchedClass) const { + const MCSchedClassDesc &SCDesc = *getSchedClassDesc(SchedClass); + if (!SCDesc.isValid()) + return 0; + if (!SCDesc.isVariant()) + return MCSchedModel::computeInstrLatency(STI, SCDesc); + + llvm_unreachable("unsupported variant scheduling class"); +} + +int MCSchedModel::computeInstrLatency(const MCSubtargetInfo &STI, + const MCInstrInfo &MCII, + const MCInst &Inst) const { + unsigned SchedClass = MCII.get(Inst.getOpcode()).getSchedClass(); + const MCSchedClassDesc *SCDesc = getSchedClassDesc(SchedClass); + if (!SCDesc->isValid()) + return 0; + + unsigned CPUID = getProcessorID(); + while (SCDesc->isVariant()) { + SchedClass = STI.resolveVariantSchedClass(SchedClass, &Inst, CPUID); + SCDesc = getSchedClassDesc(SchedClass); + } + + if (SchedClass) + return MCSchedModel::computeInstrLatency(STI, *SCDesc); + + llvm_unreachable("unsupported variant scheduling class"); +} + +double +MCSchedModel::getReciprocalThroughput(const MCSubtargetInfo &STI, + const MCSchedClassDesc &SCDesc) { + Optional Throughput; + const MCSchedModel &SM = STI.getSchedModel(); + const MCWriteProcResEntry *I = STI.getWriteProcResBegin(&SCDesc); + const MCWriteProcResEntry *E = STI.getWriteProcResEnd(&SCDesc); + for (; I != E; ++I) { + if (!I->Cycles) + continue; + unsigned NumUnits = SM.getProcResource(I->ProcResourceIdx)->NumUnits; + double Temp = NumUnits * 1.0 / I->Cycles; + Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp; + } + if (Throughput.hasValue()) + return 1.0 / Throughput.getValue(); + + // If no throughput value was calculated, assume that we can execute at the + // maximum issue width scaled by number of micro-ops for the schedule class. + return ((double)SCDesc.NumMicroOps) / SM.IssueWidth; +} + +double +MCSchedModel::getReciprocalThroughput(const MCSubtargetInfo &STI, + const MCInstrInfo &MCII, + const MCInst &Inst) const { + unsigned SchedClass = MCII.get(Inst.getOpcode()).getSchedClass(); + const MCSchedClassDesc *SCDesc = getSchedClassDesc(SchedClass); + + // If there's no valid class, assume that the instruction executes/completes + // at the maximum issue width. + if (!SCDesc->isValid()) + return 1.0 / IssueWidth; + + unsigned CPUID = getProcessorID(); + while (SCDesc->isVariant()) { + SchedClass = STI.resolveVariantSchedClass(SchedClass, &Inst, CPUID); + SCDesc = getSchedClassDesc(SchedClass); + } + + if (SchedClass) + return MCSchedModel::getReciprocalThroughput(STI, *SCDesc); + + llvm_unreachable("unsupported variant scheduling class"); +} + +double +MCSchedModel::getReciprocalThroughput(unsigned SchedClass, + const InstrItineraryData &IID) { + Optional Throughput; + const InstrStage *I = IID.beginStage(SchedClass); + const InstrStage *E = IID.endStage(SchedClass); + for (; I != E; ++I) { + if (!I->getCycles()) + continue; + double Temp = countPopulation(I->getUnits()) * 1.0 / I->getCycles(); + Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp; + } + if (Throughput.hasValue()) + return 1.0 / Throughput.getValue(); + + // If there are no execution resources specified for this class, then assume + // that it can execute at the maximum default issue width. + return 1.0 / DefaultIssueWidth; +} diff --git a/pool/shard007/C++/0096013_shpleimu.cpp b/pool/shard007/C++/0096013_shpleimu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5bd959988dbdd434f10d6fee439ca65112e0e1b --- /dev/null +++ b/pool/shard007/C++/0096013_shpleimu.cpp @@ -0,0 +1,153 @@ +/* $Id: shpleimu.cpp,v 1.10 2005/07/11 00:25:32 geomannl Exp $ */ + +#include "../ship.h" +REGISTER_FILE + +#include "../frame.h" + +class LeiMule : public Ship +{ + public: + double weaponRange, weaponVelocity, weaponDamage, weaponArmour; + double specialRange, specialVelocity, specialDamage, specialArmour; + + bool shipmode; + + public: + LeiMule(Vector2 opos, double shipAngle, ShipData *shipData, unsigned int code); + + protected: + + virtual int activate_weapon(); + virtual int activate_special(); + + void engage_forward(double dweight); + void engage_backward(double dweight); + +}; + +LeiMule::LeiMule(Vector2 opos, double shipAngle, +ShipData *shipData, unsigned int code) +: +Ship(opos, shipAngle, shipData, code) +{ + STACKTRACE; + + weaponRange = scale_range(tw_get_config_float("Weapon", "Range", 0)); + weaponVelocity = scale_velocity(tw_get_config_float("Weapon", "Velocity", 0)); + weaponDamage = tw_get_config_int("Weapon", "Damage", 0); + weaponArmour = tw_get_config_int("Weapon", "Armour", 0); + + specialRange = scale_range(tw_get_config_float("Special", "Range", 0)); + specialVelocity = scale_velocity(tw_get_config_float("Special", "Velocity", 0)); + specialDamage = tw_get_config_int("Special", "Damage", 0); + specialArmour = tw_get_config_int("Special", "Armour", 0); + +} + + +void LeiMule::engage_forward(double dweight) +{ + STACKTRACE; + Vector2 P0; + double A0, R0, Aweapon; + + P0 = Vector2(0,0); + R0 = 50; + + Aweapon = 0.025 * PI; + + A0 = 0.5 * PI + Aweapon; + + int i, N; + + // per wing + N = 1; + + for ( i = -N; i <= N; ++i ) { + if (i == 0) + continue; + + Vector2 rpos; + + rpos = P0 + (fabs(i*R0) / N) * unit_vector(A0*sign(i) - PI/2); + + double aoffs; + aoffs = -i * Aweapon; + + Shot *s; + s = new Shot(this, rpos, angle + aoffs, + weaponVelocity, weaponDamage * dweight, weaponRange, weaponArmour, + this, data->spriteWeapon, 0.0); + s->isblockingweapons = true; + add(s); + } +} + + +void LeiMule::engage_backward(double dweight) +{ + STACKTRACE; + Vector2 P0; + double A0, R0, Aweapon; + + P0 = Vector2(0,0); + R0 = 50; + + Aweapon = 0.025 * PI; + + A0 = 0.5 * PI + Aweapon; + + int i, N; + + // per wing + N = 2; + + for ( i = -N; i <= N; ++i ) { + if (i == 0) + continue; + + Vector2 rpos; + + rpos = P0 + (fabs(i*R0) / N) * unit_vector(A0*sign(i) - PI/2); + + double aoffs; + aoffs = -i * Aweapon + PI; + + Shot *s; + s = new Shot(this, rpos, angle + aoffs, + specialVelocity, specialDamage * dweight, specialRange, specialArmour, + this, data->spriteSpecial, 0.0); + s->isblockingweapons = true; + add(s); + } +} + + +int LeiMule::activate_weapon() +{ + STACKTRACE; + engage_forward(1); + + // engage_backward(1); + + return TRUE; +} + + +int LeiMule::activate_special() +{ + STACKTRACE; + + // do something else, but what + // fire a dummy shot to confuse/irritate the enemy; this costs no energy. + + // engage_forward(0); + + engage_backward(1); + + return TRUE; +} + + +REGISTER_SHIP(LeiMule) diff --git a/pool/shard007/C++/0096016_DeCounterpointCommand.cpp b/pool/shard007/C++/0096016_DeCounterpointCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02729d8fa9f03cd916212505705013ec90afe78c --- /dev/null +++ b/pool/shard007/C++/0096016_DeCounterpointCommand.cpp @@ -0,0 +1,59 @@ +/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ + +/* + Rosegarden + A MIDI and audio sequencer and musical notation editor. + Copyright 2000-2021 the Rosegarden development team. + + Other copyrights also apply to some parts of this work. Please + see the AUTHORS file and individual file headers for details. + + 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. See the file + COPYING included with this distribution for more information. +*/ + + +#include "DeCounterpointCommand.h" + +#include "base/Segment.h" +#include "base/SegmentNotationHelper.h" +#include "base/Selection.h" +#include "document/BasicSelectionCommand.h" +#include "document/CommandRegistry.h" +#include + + +namespace Rosegarden +{ + +void +DeCounterpointCommand::registerCommand(CommandRegistry *r) +{ + r->registerCommand + ("de_counterpoint", + new SelectionCommandBuilder()); +} + +void +DeCounterpointCommand::modifySegment() +{ + Segment &segment(getSegment()); + SegmentNotationHelper helper(segment); + + if (m_selection) { + EventSelection::RangeTimeList ranges(m_selection->getRangeTimes()); + for (EventSelection::RangeTimeList::iterator i = ranges.begin(); + i != ranges.end(); ++i) { + helper.deCounterpoint(i->first, i->second); + segment.normalizeRests(i->first, i->second); + } + } else { + helper.deCounterpoint(getStartTime(), getEndTime()); + segment.normalizeRests(getStartTime(), getEndTime()); + } +} + +} diff --git a/pool/shard007/C++/0096017_tone_mapping_gbench.cc b/pool/shard007/C++/0096017_tone_mapping_gbench.cc new file mode 100644 index 0000000000000000000000000000000000000000..c87c9fcc21971e312f92e5f5567ac807f9318bce --- /dev/null +++ b/pool/shard007/C++/0096017_tone_mapping_gbench.cc @@ -0,0 +1,45 @@ +// Copyright (c) the JPEG XL 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. + +#include "benchmark/benchmark.h" +#include "lib/extras/codec.h" +#include "lib/extras/tone_mapping.h" +#include "lib/jxl/testdata.h" + +namespace jxl { + +static void BM_ToneMapping(benchmark::State& state) { + CodecInOut image; + const PaddedBytes image_bytes = + ReadTestData("imagecompression.info/flower_foveon.png"); + JXL_CHECK(SetFromBytes(Span(image_bytes), &image)); + + // Convert to linear Rec. 2020 so that `ToneMapTo` doesn't have to and we + // mainly measure the tone mapping itself. + ColorEncoding linear_rec2020; + linear_rec2020.SetColorSpace(ColorSpace::kRGB); + linear_rec2020.primaries = Primaries::k2100; + linear_rec2020.white_point = WhitePoint::kD65; + linear_rec2020.tf.SetTransferFunction(TransferFunction::kLinear); + JXL_CHECK(linear_rec2020.CreateICC()); + JXL_CHECK(image.TransformTo(linear_rec2020)); + + for (auto _ : state) { + state.PauseTiming(); + CodecInOut tone_mapping_input; + tone_mapping_input.SetFromImage(CopyImage(*image.Main().color()), + image.Main().c_current()); + tone_mapping_input.metadata.m.SetIntensityTarget( + image.metadata.m.IntensityTarget()); + state.ResumeTiming(); + + JXL_CHECK(ToneMapTo({0.1, 100}, &tone_mapping_input)); + } + + state.SetItemsProcessed(state.iterations() * image.xsize() * image.ysize()); +} +BENCHMARK(BM_ToneMapping); + +} // namespace jxl diff --git a/pool/shard007/C++/0096018_tsvconfig.cpp b/pool/shard007/C++/0096018_tsvconfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2907bd9262e3e5a7a367d4a7f31c0f633712856 --- /dev/null +++ b/pool/shard007/C++/0096018_tsvconfig.cpp @@ -0,0 +1,98 @@ +/* +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include "Pr0Wolf29/libwolfstring.hpp" +#include "tsvconfig.hpp" + +std::unordered_map tsv_to_map(const std::string &file, const bool &quiet) +{ + std::unordered_map temp = {}; + + wolfstring::svFileObject tsv1; + if(tsv1.safe(file, "\t")) + { + //Loop through std::vector>. + for(size_t i = 0; i < tsv1.svfile.size(); i++) + { + //Ensure that the vector has more than 1 value. + //I assume this will result in a segfault. + if(tsv1.svfile[i].size() > 0) + { + temp[tsv1.svfile[i][0]] = tsv1.svfile[i][1]; + } + } + } + + else + { + if(quiet) + { + std::cerr << "Could not open file for reading. Function: read_conf_2D safe: false ConfFile: " << file << std::endl; + } + } + + return temp; +} + +void conf_obj_2D::LoadFile(const std::string &file) +{ + conf_obj_2D::conf_map = tsv_to_map(file, conf_obj_2D::quiet); +} + +bool conf_obj_2D::WriteFile(const std::string &file) +{ + std::ofstream tsvout (file, std::ofstream::out); + if(tsvout.is_open()) + { + for(const auto& node : conf_obj_2D::conf_map) + { + tsvout << node.first << "\t" << node.second << std::endl; + } + tsvout.close(); + return true; + } + + else + { + if(!conf_obj_2D::quiet) + { + std::cerr << file << " not able to write." << std::endl; + } + } + return false; +} + +std::string conf_obj_2D::GetVal(const std::string &val) +{ + std::unordered_map::const_iterator it = conf_obj_2D::conf_map.find(val); + + if(it == conf_obj_2D::conf_map.end()) + { + if(!conf_obj_2D::quiet) + { + std::cerr << "Value " << val << " not found." << std::endl; + } + return ""; + } + + else + { + return it->second; + } +} diff --git a/pool/shard007/C++/0096019_RandomNameGenerator.cpp b/pool/shard007/C++/0096019_RandomNameGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a96128d26135b6241c58d83b650375be1c704298 --- /dev/null +++ b/pool/shard007/C++/0096019_RandomNameGenerator.cpp @@ -0,0 +1,105 @@ +// RandomNameGenerator.cpp: implementation of the CRandomNameGenerator class. +// +////////////////////////////////////////////////////////////////////// +/** + * Copyright (C) 1998 David Harvey + * + * 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 "stdafx.h" +#include "Byakhee.h" +#include "RandomNameGenerator.h" +#include "NamedOptionManager.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CRandomNameGenerator::CRandomNameGenerator() +{ + //create a named option object to hold the male, female and surname entries + m_pNamedOptionManager = new CNamedOptionManager( "names.lst", 3); + + //generate a name to start with + Generate(); +} + +CRandomNameGenerator::~CRandomNameGenerator() +{ + delete m_pNamedOptionManager; +} + +void CRandomNameGenerator::Generate() +{ + //get first name & sex + if( rand() % 4 == 0 ) //greater male than female weighting (sexist, I know) + { + CStringArray* pStringArray = m_pNamedOptionManager->GetOptions( "FemaleNames" ); + if( pStringArray ) + { + m_strName = pStringArray->GetAt( rand() % pStringArray->GetSize() ); + m_strSex = "F"; + } + } + else + { + CStringArray* pStringArray = m_pNamedOptionManager->GetOptions( "MaleNames" ); + if( pStringArray ) + { + m_strName = pStringArray->GetAt( rand() % pStringArray->GetSize() ); + m_strSex = "M"; + } + } + + //add a gap between names and get the surnames + CStringArray* pStringArray = m_pNamedOptionManager->GetOptions( "Surnames" ); + if( pStringArray ) + { + m_strName += " "; + + //possibly add something fancy + if( rand() % 7 == 0 ) //1 in 7 chance of a middle name or double-barrel name + { + m_strName += pStringArray->GetAt( rand() % pStringArray->GetSize() ); + if( rand() % 2 == 0 ) m_strName += "-"; else m_strName += " "; + } + else + if( rand() % 50 == 0 ) //1 in 50 chance of being a st-wossname + m_strName += "St. "; + + //get surname + m_strName += pStringArray->GetAt( rand() % pStringArray->GetSize() ); + } + else + m_strName = "name data not found"; +} + +CString CRandomNameGenerator::GetName() +{ + return m_strName; +} + +CString CRandomNameGenerator::GetSex() +{ + return m_strSex; +} + diff --git a/pool/shard007/C++/0096030_BasicSubscriber.cpp b/pool/shard007/C++/0096030_BasicSubscriber.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9c224fbbadaeb6ff3fe1ca88c09d18f1d777bb0 --- /dev/null +++ b/pool/shard007/C++/0096030_BasicSubscriber.cpp @@ -0,0 +1,166 @@ +/* + * Copyright 2014-2019 Real Logic Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "Configuration.h" +#include + +using namespace aeron::util; +using namespace aeron; + +std::atomic running (true); + +void sigIntHandler(int param) +{ + running = false; +} + +static const char optHelp = 'h'; +static const char optPrefix = 'p'; +static const char optChannel = 'c'; +static const char optStreamId = 's'; + +static const std::chrono::duration IDLE_SLEEP_MS(1); +static const int FRAGMENTS_LIMIT = 10; + +struct Settings +{ + std::string dirPrefix = ""; + std::string channel = samples::configuration::DEFAULT_CHANNEL; + std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID; +}; + +Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv) +{ + cp.parse(argc, argv); + if (cp.getOption(optHelp).isPresent()) + { + cp.displayOptionsHelp(std::cout); + exit(0); + } + + Settings s; + + s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix); + s.channel = cp.getOption(optChannel).getParam(0, s.channel); + s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId); + + return s; +} + +fragment_handler_t printStringMessage() +{ + return [&](const AtomicBuffer& buffer, util::index_t offset, util::index_t length, const Header& header) + { + std::cout << "Message to stream " << header.streamId() << " from session " << header.sessionId(); + std::cout << "(" << length << "@" << offset << ") <<"; + std::cout << std::string(reinterpret_cast(buffer.buffer()) + offset, static_cast(length)) << ">>" << std::endl; + }; +} + +int main(int argc, char** argv) +{ + CommandOptionParser cp; + cp.addOption(CommandOption(optHelp, 0, 0, " Displays help information.")); + cp.addOption(CommandOption(optPrefix, 1, 1, "dir Prefix directory for aeron driver.")); + cp.addOption(CommandOption(optChannel, 1, 1, "channel Channel.")); + cp.addOption(CommandOption(optStreamId, 1, 1, "streamId Stream ID.")); + + signal (SIGINT, sigIntHandler); + + try + { + Settings settings = parseCmdLine(cp, argc, argv); + + std::cout << "Subscribing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl; + + aeron::Context context; + + if (!settings.dirPrefix.empty()) + { + context.aeronDir(settings.dirPrefix); + } + + context.newSubscriptionHandler( + [](const std::string& channel, std::int32_t streamId, std::int64_t correlationId) + { + std::cout << "Subscription: " << channel << " " << correlationId << ":" << streamId << std::endl; + }); + + context.availableImageHandler([](Image &image) + { + std::cout << "Available image correlationId=" << image.correlationId() << " sessionId=" << image.sessionId(); + std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl; + }); + + context.unavailableImageHandler([](Image &image) + { + std::cout << "Unavailable image on correlationId=" << image.correlationId() << " sessionId=" << image.sessionId(); + std::cout << " at position=" << image.position() << " from " << image.sourceIdentity() << std::endl; + }); + + std::shared_ptr aeron = Aeron::connect(context); + + // add the subscription to start the process + std::int64_t id = aeron->addSubscription(settings.channel, settings.streamId); + + std::shared_ptr subscription = aeron->findSubscription(id); + // wait for the subscription to be valid + while (!subscription) + { + std::this_thread::yield(); + subscription = aeron->findSubscription(id); + } + + const std::int64_t channelStatus = subscription->channelStatus(); + + std::cout << "Subscription channel status (id=" << subscription->channelStatusId() << ") " + << (channelStatus == ChannelEndpointStatus::CHANNEL_ENDPOINT_ACTIVE ? "ACTIVE" : std::to_string(channelStatus)) + << std::endl; + + fragment_handler_t handler = printStringMessage(); + SleepingIdleStrategy idleStrategy(IDLE_SLEEP_MS); + + while (running) + { + const int fragmentsRead = subscription->poll(handler, FRAGMENTS_LIMIT); + idleStrategy.idle(fragmentsRead); + } + + } + catch (const CommandOptionException& e) + { + std::cerr << "ERROR: " << e.what() << std::endl << std::endl; + cp.displayOptionsHelp(std::cerr); + return -1; + } + catch (const SourcedException& e) + { + std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl; + return -1; + } + catch (const std::exception& e) + { + std::cerr << "FAILED: " << e.what() << " : " << std::endl; + return -1; + } + + return 0; +} diff --git a/pool/shard007/C++/0096032_MsiKeyboardActions.cpp b/pool/shard007/C++/0096032_MsiKeyboardActions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b36643638746b0c3098cde6a8355aef626389adc --- /dev/null +++ b/pool/shard007/C++/0096032_MsiKeyboardActions.cpp @@ -0,0 +1,152 @@ +// +// Copyright 2015-2016 +// Author(s): Neuro Morphy +// +// This file is part of Steel. +// +// Steel 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. +// +// Steel 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 Steel. If not, see . +// + + +#include +#include +#include +#include +#include "utils/SysLog.h" +#include "actions/MsiKeyboardActions.h" + + +using namespace steel::config; +using namespace steel::context; +using namespace steel::device; +using namespace steel::utils; + + +namespace steel +{ + namespace actions + { + MsiKeyboardActions::MsiKeyboardActions( const SteelConfig& config, const std::vector& devices ) + : IActions{ devices } + , _config( *dynamic_cast( config.devices().at( "msi-keyboard" ).get() ) ) // no uniform initialization because of gcc 4.8 bug + , _device{ std::unique_ptr( nullptr ) } + { + + for ( auto pos = _devices.begin(); pos != _devices.end(); ++pos ) + { + if ( pos->type() == HidDeviceInfo::Type::MsiKeyboard ) + { + _device = std::unique_ptr( new MsiKeyboard( *pos ) ); + break; + } + } + } + + + int MsiKeyboardActions::exec( int argc, char* argv[] ) + { + MsiKeyboardContext context( _config.deviceName() ); + int result = context.create( argc, argv ); + + if ( result == 0 ) + { + switch ( context.command() ) + { + case MsiKeyboardContext::Command::Help : + std::cout << context.syntax( 0 ) << std::endl; + return 0; + + case MsiKeyboardContext::Command::Active : + return _execActive( context ); + + case MsiKeyboardContext::Command::Profile : + return _execProfile( context ); + + default : + return _error( -102, "unsupported command \'%d\'", context.command() ); + } + } + + return result; + } + + + int MsiKeyboardActions::_execActive( const MsiKeyboardContext& context ) + { + (void) context; + return _execProfile( _config.active() ); + } + + + int MsiKeyboardActions::_execProfile( const MsiKeyboardContext& context ) + { + auto profiles = _config.profiles(); + + for ( auto pos = profiles.begin(); pos != profiles.end(); ++pos ) + { + if ( context.profile() == pos->name() ) + return _execProfile( *pos ); + } + + return _error( -200, "profile \'%s\' not found in configuration", context.profile().c_str() ); + } + + + int MsiKeyboardActions::_execProfile( const MsiKeyboardProfile& profile ) + { + if ( _device.get() == nullptr ) + return _error( -301, "device not found" ); + + typedef MsiKeyboard::Color Colors[]; + + switch ( profile.mode() ) + { + case MsiKeyboard::Mode::Disable : + return _device.get()->disable(); + + case MsiKeyboard::Mode::Normal : + return _device.get()->normal( profile.intensity(), std::move( Colors{ profile.color1(), profile.color2(), profile.color3() } ) ); + + case MsiKeyboard::Mode::Game : + return _device.get()->gaming( profile.intensity(), profile.color1() ); + + case MsiKeyboard::Mode::Breathe : + return _device.get()->breathing( profile.intensity(), std::move( Colors{ profile.color1(), profile.color2(), profile.color3() } ), profile.speed() ); + + case MsiKeyboard::Mode::Wave : + return _device.get()->wave( profile.intensity(), std::move( Colors{ profile.color1(), profile.color2(), profile.color3() } ), profile.speed() ); + + case MsiKeyboard::Mode::BiColor : + return _device.get()->bicolor( profile.intensity(), std::move( Colors{ profile.color1(), profile.color2() } ), profile.speed() ); + + default: + return _error( -300, "undefined mode \'%d\'", static_cast( profile.mode() ) ); + } + } + + + int MsiKeyboardActions::_error( int result, const char* fmt, ... ) + { + const int error = -10000; + std::vector buffer( 16384 ); + va_list vl; + + va_start( vl, fmt ); + std::vsprintf( buffer.data(), fmt, vl ); + syslog().error( "error (%d): %s: %s", result += error, _config.deviceName().c_str(), buffer.data() ); + std::fprintf( stderr, "\nerror (%d): %s: %s\n\n", result, _config.deviceName().c_str(), buffer.data() ); + return result; + } + } +} diff --git a/pool/shard007/C++/0096057_WebEditorClientGtk.cpp b/pool/shard007/C++/0096057_WebEditorClientGtk.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e33d72327cc4ef88f7c3af315cd6295c68c17633 --- /dev/null +++ b/pool/shard007/C++/0096057_WebEditorClientGtk.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2011 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "WebEditorClient.h" + +#include "Frame.h" +#include "FrameDestructionObserver.h" +#include "PlatformKeyboardEvent.h" +#include "WebPage.h" +#include "WebPageProxyMessages.h" +#include "WebProcess.h" +#include +#include +#include +#include + +using namespace WebCore; + +namespace WebKit { + +void WebEditorClient::getEditorCommandsForKeyEvent(const KeyboardEvent* event, Vector& pendingEditorCommands) +{ + ASSERT(event->type() == eventNames().keydownEvent || event->type() == eventNames().keypressEvent); + + /* First try to interpret the command in the UI and get the commands. + UI needs to receive event type because only knows current NativeWebKeyboardEvent.*/ + WebProcess::shared().connection()->sendSync(Messages::WebPageProxy::GetEditorCommandsForKeyEvent(event->type()), + Messages::WebPageProxy::GetEditorCommandsForKeyEvent::Reply(pendingEditorCommands), + m_page->pageID(), CoreIPC::Connection::NoTimeout); +} + +bool WebEditorClient::executePendingEditorCommands(Frame* frame, Vector pendingEditorCommands, bool allowTextInsertion) +{ + Vector commands; + for (size_t i = 0; i < pendingEditorCommands.size(); i++) { + Editor::Command command = frame->editor()->command(pendingEditorCommands.at(i).utf8().data()); + if (command.isTextInsertion() && !allowTextInsertion) + return false; + + commands.append(command); + } + + for (size_t i = 0; i < commands.size(); i++) { + if (!commands.at(i).execute()) + return false; + } + + return true; +} + +void WebEditorClient::handleKeyboardEvent(KeyboardEvent* event) +{ + Node* node = event->target()->toNode(); + ASSERT(node); + Frame* frame = node->document()->frame(); + ASSERT(frame); + + const PlatformKeyboardEvent* platformEvent = event->keyEvent(); + if (!platformEvent) + return; + + Vector pendingEditorCommands; + getEditorCommandsForKeyEvent(event, pendingEditorCommands); + if (!pendingEditorCommands.isEmpty()) { + + // During RawKeyDown events if an editor command will insert text, defer + // the insertion until the keypress event. We want keydown to bubble up + // through the DOM first. + if (platformEvent->type() == PlatformEvent::RawKeyDown) { + if (executePendingEditorCommands(frame, pendingEditorCommands, false)) + event->setDefaultHandled(); + + return; + } + + // Only allow text insertion commands if the current node is editable. + if (executePendingEditorCommands(frame, pendingEditorCommands, frame->editor()->canEdit())) { + event->setDefaultHandled(); + return; + } + } + + // Don't allow text insertion for nodes that cannot edit. + if (!frame->editor()->canEdit()) + return; + + // This is just a normal text insertion, so wait to execute the insertion + // until a keypress event happens. This will ensure that the insertion will not + // be reflected in the contents of the field until the keyup DOM event. + if (event->type() == eventNames().keypressEvent) { + + // FIXME: Add IM support + // https://bugs.webkit.org/show_bug.cgi?id=55946 + frame->editor()->insertText(platformEvent->text(), event); + event->setDefaultHandled(); + + } else { + // Don't insert null or control characters as they can result in unexpected behaviour + if (event->charCode() < ' ') + return; + + // Don't insert anything if a modifier is pressed + if (platformEvent->ctrlKey() || platformEvent->altKey()) + return; + + if (frame->editor()->insertText(platformEvent->text(), event)) + event->setDefaultHandled(); + } +} + +void WebEditorClient::handleInputMethodKeydown(KeyboardEvent*) +{ + notImplemented(); +} + +#if PLATFORM(X11) +class EditorClientFrameDestructionObserver : FrameDestructionObserver { +public: + EditorClientFrameDestructionObserver(Frame* frame, GClosure* closure) + : FrameDestructionObserver(frame) + , m_closure(closure) + { + g_closure_add_finalize_notifier(m_closure, this, destroyOnClosureFinalization); + } + + void frameDestroyed() + { + g_closure_invalidate(m_closure); + FrameDestructionObserver::frameDestroyed(); + } +private: + GClosure* m_closure; + + static void destroyOnClosureFinalization(gpointer data, GClosure* closure) + { + // Calling delete void* will free the memory but won't invoke + // the destructor, something that is a must for us. + EditorClientFrameDestructionObserver* observer = static_cast(data); + delete observer; + } +}; + +static Frame* frameSettingClipboard; + +static void collapseSelection(GtkClipboard* clipboard, Frame* frame) +{ + if (frameSettingClipboard && frameSettingClipboard == frame) + return; + + // Collapse the selection without clearing it. + ASSERT(frame); + frame->selection()->setBase(frame->selection()->extent(), frame->selection()->affinity()); +} +#endif + +void WebEditorClient::setSelectionPrimaryClipboardIfNeeded(Frame* frame) +{ +#if PLATFORM(X11) + GtkClipboard* clipboard = PasteboardHelper::defaultPasteboardHelper()->getPrimarySelectionClipboard(frame); + DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard); + + if (!frame->selection()->isRange()) + return; + + dataObject->clearAll(); + dataObject->setRange(frame->selection()->toNormalizedRange()); + + frameSettingClipboard = frame; + GClosure* callback = g_cclosure_new(G_CALLBACK(collapseSelection), frame, 0); + // This observer will be self-destroyed on closure finalization, + // that will happen either after closure execution or after + // closure invalidation. + new EditorClientFrameDestructionObserver(frame, callback); + g_closure_set_marshal(callback, g_cclosure_marshal_VOID__VOID); + PasteboardHelper::defaultPasteboardHelper()->writeClipboardContents(clipboard, PasteboardHelper::DoNotIncludeSmartPaste, callback); + frameSettingClipboard = 0; +#endif +} + +bool WebEditorClient::shouldShowUnicodeMenu() +{ + return true; +} + +} diff --git a/pool/shard007/C++/0096060_PricePair.cpp b/pool/shard007/C++/0096060_PricePair.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36313a9394d24c0b3b424462a8218871571348a9 --- /dev/null +++ b/pool/shard007/C++/0096060_PricePair.cpp @@ -0,0 +1,125 @@ +/**************************************************************************************************** +* +* Copyright (C) 2009 - 2014 Mark Burrows (mark_burrows_999_code@outlook.com). All rights reserved +* +* This file is part of the project ib_ptrader and is subject to the terms and conditions defined in +* the file 'LICENSE.txt', which is part of this source code package +* +*****************************************************************************************************/ + +#include "stdafx.h" + + + +#pragma region "PricePair" +BuyPricePair *PricePair::FindLowestSellPriceStartPoint (Ticker *ticker, int start) +{ + int finish = ticker->_sells.GetDataCount () - 1; + for (int i = start; i <= finish; i++) + { + SellPricePair *searchpricepair = ticker->_sells.GetData (i); + if (searchpricepair->_buypricepair->GetStatus () == PricePair::BOUGHT && + searchpricepair->GetStatus () == PricePair::ACTIVE) + { + return searchpricepair->_buypricepair; + } + } + return 0; +} + + +PricePair::PricePair (Status status, double price, long size) : _status (status), _price (price), _size (size), _pairindex (-1) +{ +} +#pragma endregion + + +#pragma region "BuyPricePair" +void BuyPricePair::SetStatus (Status status) +{ + if (status == PricePair::BOUGHT) + { + if (_ticker->_sellsstartpoint) + { + if (_sellpricepair->_price < _ticker->_sellsstartpoint->_sellpricepair->_price) + { + _ticker->_sellsstartpoint = this; + } + } + else + { + _ticker->_sellsstartpoint = this; + } + _sellpricepair->_trending_hitcount = 0; + _sellpricepair->_min_trend_over = 0; + _sellpricepair->_max_trend_over = 0; + _sellpricepair->_actual_sellgap = 0; + } + else if (status == PricePair::CANCELLED) + { + status = PricePair::ACTIVE; + } + _status = status; +} + + +bool BuyPricePair::AvailableForLiquidation (bool todayonly) +{ + if (_lastbuysset && GetStatus () == BOUGHT && _sellpricepair->GetStatus () == ACTIVE) + { + if (todayonly) + return _boughttoday; + return true; + } + return false; +} + + +BuyPricePair::BuyPricePair (Ticker *ticker, Status status, double price, long size) : PricePair (status, price, size), _ticker (ticker), _lastbuysset (false), + _boughttoday (false), _lastavgfill (0), _lastbuycommission (0), + _turnedon (true) +{ +} +#pragma endregion + + +#pragma region "SellPricePair" +void SellPricePair::SetStatus (Status status) +{ + bool gotopending = _status == PricePair::ACTIVE && status == PricePair::PENDING; + bool gotobought = _status == PricePair::PENDING && status == PricePair::BOUGHT; + bool cancelled = status == PricePair::CANCELLED; + if (gotopending) + { + if (_buypricepair == _buypricepair->_ticker->_sellsstartpoint) + { + _buypricepair->_ticker->_sellsstartpoint = FindLowestSellPriceStartPoint (_buypricepair->_ticker, + _buypricepair->_ticker->_sellsstartpoint->_sellpricepair->_pairindex + 1); + } + } + else if (cancelled) + { + if (_buypricepair->_ticker->_sellsstartpoint == 0 || _price < _buypricepair->_ticker->_sellsstartpoint->_sellpricepair->_price) + { + _buypricepair->_ticker->_sellsstartpoint = _buypricepair; + } + status = PricePair::ACTIVE; + } + else if (gotobought) + { + status = PricePair::ACTIVE; + } + _status = status; +} + + +void SellPricePair::FormatTrendForDisplay (CString &format) +{ + format.Format (" (%0.2f %0.2f A=%0.2f)", _min_trend_over, _max_trend_over, _actual_sellgap); +} + + +SellPricePair::SellPricePair (Status status, double price, long size) : PricePair (status, price, size) +{ +} +#pragma endregion \ No newline at end of file diff --git a/pool/shard007/C++/0096063_network-perf-benchmark.cc b/pool/shard007/C++/0096063_network-perf-benchmark.cc new file mode 100644 index 0000000000000000000000000000000000000000..26b2aae22a01a8937260053125d69f575e6d54c2 --- /dev/null +++ b/pool/shard007/C++/0096063_network-perf-benchmark.cc @@ -0,0 +1,247 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include + +#include +#include +#include +#include + +#include +#include +#include "gen-cpp/NetworkTest_types.h" +#include "gen-cpp/NetworkTestService.h" + +#include "common/logging.h" +#include "util/cpu-info.h" +#include "util/stopwatch.h" +#include "rpc/thrift-client.h" +#include "rpc/thrift-server.h" +#include "rpc/thrift-thread.h" + +#include "common/names.h" + +DEFINE_int32(port, 22222, "Port for NetworkTestService"); +DEFINE_int64(send_batch_size, 0, "Batch size (in bytes). Data is split up into batches"); + +// Simple client server network speed benchmark utility. This compiles to +// a binary that runs as both the client and server. The server can be started +// up by just running the binary. After the server starts up, it will drop into +// the client 'shell' where benchmarks can be run. +// The supported benchmarks are: +// 'send ' +// 'broadcast +// The command can also be passed in via command line in the same format. If +// run in this mode, the server does not start up. +// For broadcast, the data is sent in parallel to all nodes. +// +// The expected usage for measuring 'send' is to start up the server on one machine +// and issue the send from another. +// For 'broadcast', the server should be started on all the machines and then the +// broadcast is issued from one of them. + +using boost::algorithm::is_any_of; +using boost::algorithm::token_compress_on; +using boost::algorithm::split; + +using namespace apache::thrift; +using namespace apache::thrift::protocol; +using namespace apache::thrift::transport; +using namespace apache::thrift::server; +using namespace apache::thrift::concurrency; +using namespace impala; +using namespace impalatest; + + +class TestServer : public NetworkTestServiceIf { + public: + TestServer() { + } + + virtual ~TestServer() { + } + + virtual void Send(ThriftDataResult& result, const ThriftDataParams& params) { + result.__set_bytes_received(params.data.size()); + } + + void Server(ThriftServer* server) { + server->Start(); + server->Join(); + } +}; + +// Send bytes to client respecting the batch size +// Returns the rate in mb/s to send the data. +double Send(ThriftClient* client, int64_t bytes) { + int64_t batch_size = FLAGS_send_batch_size; + if (batch_size == 0) batch_size = bytes; + int64_t total_sent = 0; + + MonotonicStopWatch timer; + timer.Start(); + while (total_sent < bytes) { + int64_t send_size = min(bytes - total_sent, batch_size); + total_sent += send_size; + + ThriftDataParams data; + ThriftDataResult result; + data.data.resize(send_size); + client->iface()->Send(result, data); + + if (result.bytes_received != send_size) { + return -1; + } + } + timer.Stop(); + + double mb = bytes / (1024. * 1024.); + double sec = timer.ElapsedTime() / (1000.) / (1000.) / (1000.); + return mb/sec; +} + +// Send tokens[1] megabytes to tokens[2] +void HandleSend(const vector& tokens) { + if (tokens.size() != 3) { + return; + } + + int64_t mbs = atoi(tokens[1].c_str()); + int64_t bytes = mbs * (1024L * 1024L); + cout << "Sending " << mbs << " megabytes..." << endl; + const string& ip = tokens[2]; + + ThriftClient client(ip, FLAGS_port); + Status status = client.Open(); + if (!status.ok()) { + cerr << "Could not connect to server" << endl; + return; + } + + double rate = Send(&client, bytes); + if (rate < 0) { + cerr << "Send failed"; + return; + } + cout << "Send rate: (MB/s): " << rate << endl; +} + +// Broadcast tokens[1] megabytes to tokens[2...n] nodes in parallel. +void HandleBroadcast(const vector& tokens) { + if (tokens.size() <= 2) { + return; + } + int64_t mbs = atoi(tokens[1].c_str()); + int64_t bytes = mbs * (1024L * 1024L); + cout << "Broadcasting " << mbs << " megabytes..." << endl; + + vector* > clients; + for (int i = 2; i < tokens.size(); ++i) { + ThriftClient* client = + new ThriftClient(tokens[i], FLAGS_port); + Status status = client->Open(); + if (!status.ok()) { + cerr << "Could not connect to server: " << tokens[i] << endl; + return; + } + clients.push_back(client); + } + + MonotonicStopWatch timer; + timer.Start(); + thread_group threads; + for (int i = 0; i < clients.size(); ++i) { + threads.add_thread(new thread(Send, clients[i], bytes)); + } + threads.join_all(); + timer.Stop(); + + double mb = bytes / (1024 * 1024.); + double sec = timer.ElapsedTime() / (1000.) / (1000.) / (1000.); + + cout << "Send rate per node: (MB/s) " << (mb/sec) << endl; + cout << "Send rate cluster: (MB/s) " << (mb * clients.size() / sec) << endl; +} + +void ConvertToLowerCase(vector* tokens) { + for (int i = 0; i < tokens->size(); ++i) { + transform( + (*tokens)[i].begin(), (*tokens)[i].end(), (*tokens)[i].begin(), ::tolower); + } +} + +bool ProcessCommand(const vector& tokens) { + if (tokens.empty()) return false; + + if (tokens[0] == "quit") return true;; + + if (tokens[0] == "send") { + HandleSend(tokens); + } else if (tokens[0] == "broadcast") { + HandleBroadcast(tokens); + } else { + cerr << "Invalid command" << endl; + return false; + } + return false; +} + +int main(int argc, char** argv) { + google::ParseCommandLineFlags(&argc, &argv, true); + CpuInfo::Init(); + + if (argc != 1) { + // Just run client from command line args + vector tokens; + for (int i = 1; i < argc; ++i) { + tokens.push_back(argv[i]); + } + ConvertToLowerCase(&tokens); + ProcessCommand(tokens); + return 0; + } + + // Start up server and client shell + boost::shared_ptr handler(new TestServer); + boost::shared_ptr thread_factory( + new ThriftThreadFactory("test", "test")); + boost::shared_ptr processor(new NetworkTestServiceProcessor(handler)); + ThriftServer* server = new ThriftServer("Network Test Server", processor, + FLAGS_port, NULL, NULL, 100, ThriftServer::ThreadPool); + thread* server_thread = new thread(&TestServer::Server, handler.get(), server); + + string input; + while (1) { + vector tokens; + cout << "> "; + cout.flush(); + + getline(cin, input); + if (cin.eof()) break; + + split(tokens, input, is_any_of(" "), token_compress_on); + + ConvertToLowerCase(&tokens); + if (ProcessCommand(tokens)) break; + } + + server->StopForTesting(); + server_thread->join(); + + return 0; +} diff --git a/pool/shard007/C++/0096066_WebInspectorClient.cpp b/pool/shard007/C++/0096066_WebInspectorClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a91dcdd63f3a849b6ab464aa856c8a3b1402648 --- /dev/null +++ b/pool/shard007/C++/0096066_WebInspectorClient.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebInspectorClient.h" + +#if ENABLE(INSPECTOR) + +#include "WebInspectorFrontendClient.h" +#include "WebInspector.h" +#include "WebPage.h" +#include +#include +#include + +using namespace WebCore; + +namespace WebKit { + +void WebInspectorClient::inspectorDestroyed() +{ + delete this; +} + +void WebInspectorClient::openInspectorFrontend(InspectorController*) +{ + WebPage* inspectorPage = m_page->inspector()->createInspectorPage(); + ASSERT(inspectorPage); + if (!inspectorPage) + return; + + inspectorPage->corePage()->inspectorController()->setInspectorFrontendClient(adoptPtr(new WebInspectorFrontendClient(m_page, inspectorPage))); +} + +void WebInspectorClient::highlight(Node*) +{ + notImplemented(); +} + +void WebInspectorClient::hideHighlight() +{ + notImplemented(); +} + +void WebInspectorClient::populateSetting(const String& key, String*) +{ + notImplemented(); +} + +void WebInspectorClient::storeSetting(const String&, const String&) +{ + notImplemented(); +} + +bool WebInspectorClient::sendMessageToFrontend(const String& message) +{ + WebInspector* inspector = m_page->inspector(); + if (!inspector) + return false; + WebPage* inspectorPage = inspector->inspectorPage(); + if (!inspectorPage) + return false; + return doDispatchMessageOnFrontendPage(inspectorPage->corePage(), message); +} + +} // namespace WebKit + +#endif // ENABLE(INSPECTOR) diff --git a/pool/shard007/C++/0096067_CreateNetworkProfileRequest.cpp b/pool/shard007/C++/0096067_CreateNetworkProfileRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee851131e19e01958c858d11aaf71e8690a190fc --- /dev/null +++ b/pool/shard007/C++/0096067_CreateNetworkProfileRequest.cpp @@ -0,0 +1,124 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::AlexaForBusiness::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +CreateNetworkProfileRequest::CreateNetworkProfileRequest() : + m_networkProfileNameHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_ssidHasBeenSet(false), + m_securityType(NetworkSecurityType::NOT_SET), + m_securityTypeHasBeenSet(false), + m_eapMethod(NetworkEapMethod::NOT_SET), + m_eapMethodHasBeenSet(false), + m_currentPasswordHasBeenSet(false), + m_nextPasswordHasBeenSet(false), + m_certificateAuthorityArnHasBeenSet(false), + m_trustAnchorsHasBeenSet(false), + m_clientRequestToken(Aws::Utils::UUID::RandomUUID()), + m_clientRequestTokenHasBeenSet(true), + m_tagsHasBeenSet(false) +{ +} + +Aws::String CreateNetworkProfileRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_networkProfileNameHasBeenSet) + { + payload.WithString("NetworkProfileName", m_networkProfileName); + + } + + if(m_descriptionHasBeenSet) + { + payload.WithString("Description", m_description); + + } + + if(m_ssidHasBeenSet) + { + payload.WithString("Ssid", m_ssid); + + } + + if(m_securityTypeHasBeenSet) + { + payload.WithString("SecurityType", NetworkSecurityTypeMapper::GetNameForNetworkSecurityType(m_securityType)); + } + + if(m_eapMethodHasBeenSet) + { + payload.WithString("EapMethod", NetworkEapMethodMapper::GetNameForNetworkEapMethod(m_eapMethod)); + } + + if(m_currentPasswordHasBeenSet) + { + payload.WithString("CurrentPassword", m_currentPassword); + + } + + if(m_nextPasswordHasBeenSet) + { + payload.WithString("NextPassword", m_nextPassword); + + } + + if(m_certificateAuthorityArnHasBeenSet) + { + payload.WithString("CertificateAuthorityArn", m_certificateAuthorityArn); + + } + + if(m_trustAnchorsHasBeenSet) + { + Array trustAnchorsJsonList(m_trustAnchors.size()); + for(unsigned trustAnchorsIndex = 0; trustAnchorsIndex < trustAnchorsJsonList.GetLength(); ++trustAnchorsIndex) + { + trustAnchorsJsonList[trustAnchorsIndex].AsString(m_trustAnchors[trustAnchorsIndex]); + } + payload.WithArray("TrustAnchors", std::move(trustAnchorsJsonList)); + + } + + if(m_clientRequestTokenHasBeenSet) + { + payload.WithString("ClientRequestToken", m_clientRequestToken); + + } + + if(m_tagsHasBeenSet) + { + Array tagsJsonList(m_tags.size()); + for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) + { + tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); + } + payload.WithArray("Tags", std::move(tagsJsonList)); + + } + + return payload.View().WriteReadable(); +} + +Aws::Http::HeaderValueCollection CreateNetworkProfileRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AlexaForBusiness.CreateNetworkProfile")); + return headers; + +} + + + + diff --git a/pool/shard007/C++/0096068_Morph_C.cpp b/pool/shard007/C++/0096068_Morph_C.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c30351b0b28ff83edc996297d2ca4848199b097a --- /dev/null +++ b/pool/shard007/C++/0096068_Morph_C.cpp @@ -0,0 +1,131 @@ + +//C implementation of Morphological Opening Operation +//Author: Hasan Baig +//Email: hasan.baig@hotmail.com +//Web: http://www.hasanbaig.com + +#include "iostream" +#include "conio.h" +#include "time.h" +#include "../defines.h" +#include "../my_C_functions.h" + + + +int main () +{ + using std::cout; + + int temp[Rows][Cols]; + int img_erode[Rows][Cols]; + int Image_Out[Rows][Cols]; + int SE[3] = {1,1,1}; + + printf("Original Image with Noise\n\n"); + for (i=0;i + +#include "base/logging.h" +#include "media/base/bit_reader.h" +#include "media/formats/mp2t/mp2t_common.h" + +namespace media { +namespace mp2t { + +TsSectionPat::TsSectionPat(const RegisterPmtCb& register_pmt_cb) + : register_pmt_cb_(register_pmt_cb), + version_number_(-1) { +} + +TsSectionPat::~TsSectionPat() { +} + +bool TsSectionPat::ParsePsiSection(BitReader* bit_reader) { + // Read the fixed section length. + int table_id; + int section_syntax_indicator; + int dummy_zero; + int reserved; + int section_length; + int transport_stream_id; + int version_number; + int current_next_indicator; + int section_number; + int last_section_number; + RCHECK(bit_reader->ReadBits(8, &table_id)); + RCHECK(bit_reader->ReadBits(1, §ion_syntax_indicator)); + RCHECK(bit_reader->ReadBits(1, &dummy_zero)); + RCHECK(bit_reader->ReadBits(2, &reserved)); + RCHECK(bit_reader->ReadBits(12, §ion_length)); + RCHECK(section_length >= 5); + RCHECK(section_length <= 1021); + RCHECK(bit_reader->ReadBits(16, &transport_stream_id)); + RCHECK(bit_reader->ReadBits(2, &reserved)); + RCHECK(bit_reader->ReadBits(5, &version_number)); + RCHECK(bit_reader->ReadBits(1, ¤t_next_indicator)); + RCHECK(bit_reader->ReadBits(8, §ion_number)); + RCHECK(bit_reader->ReadBits(8, &last_section_number)); + section_length -= 5; + + // Perform a few verifications: + // - Table ID should be 0 for a PAT. + // - section_syntax_indicator should be one. + // - section length should not exceed 1021 + RCHECK(table_id == 0x0); + RCHECK(section_syntax_indicator); + RCHECK(!dummy_zero); + + // Both the program table and the CRC have a size multiple of 4. + // Note for pmt_pid_count: minus 4 to account for the CRC. + RCHECK((section_length % 4) == 0); + int pmt_pid_count = (section_length - 4) / 4; + + // Read the variable length section: program table & crc. + std::vector program_number_array(pmt_pid_count); + std::vector pmt_pid_array(pmt_pid_count); + for (int k = 0; k < pmt_pid_count; k++) { + int reserved; + RCHECK(bit_reader->ReadBits(16, &program_number_array[k])); + RCHECK(bit_reader->ReadBits(3, &reserved)); + RCHECK(bit_reader->ReadBits(13, &pmt_pid_array[k])); + } + int crc32; + RCHECK(bit_reader->ReadBits(32, &crc32)); + + // Just ignore the PAT if not applicable yet. + if (!current_next_indicator) { + DVLOG(1) << "Not supported: received a PAT not applicable yet"; + return true; + } + + // Ignore the program table if it hasn't changed. + if (version_number == version_number_) + return true; + + // Both the MSE and the HLS spec specifies that TS streams should convey + // exactly one program. + if (pmt_pid_count > 1) { + DVLOG(1) << "Multiple programs detected in the Mpeg2 TS stream"; + return false; + } + + // Can now register the PMT. +#if !defined(NDEBUG) + int expected_version_number = version_number; + if (version_number_ >= 0) + expected_version_number = (version_number_ + 1) % 32; + DVLOG_IF(1, version_number != expected_version_number) + << "Unexpected version number: " + << version_number << " vs " << version_number_; +#endif + for (int k = 0; k < pmt_pid_count; k++) { + if (program_number_array[k] != 0) { + // Program numbers different from 0 correspond to PMT. + register_pmt_cb_.Run(program_number_array[k], pmt_pid_array[k]); + // Even if there are multiple programs, only one can be supported now. + // HLS: "Transport Stream segments MUST contain a single MPEG-2 Program." + break; + } + } + version_number_ = version_number; + + return true; +} + +void TsSectionPat::ResetPsiSection() { + version_number_ = -1; +} + +} // namespace mp2t +} // namespace media + diff --git a/pool/shard007/C++/0096071_python.cpp b/pool/shard007/C++/0096071_python.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5fc191eb09f07b61c54ee053167c4a6d8a77234 --- /dev/null +++ b/pool/shard007/C++/0096071_python.cpp @@ -0,0 +1,239 @@ +#include + /* avoid warnigs :) */ +#undef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200112L +extern "C" void init_enigma(); +extern "C" void eBaseInit(void); +extern "C" void eConsoleInit(void); +extern void bsodFatal(const char *component); +extern void quitMainloop(int exitCode); + +#define SKIP_PART2 +#include +#undef SKIP_PART2 + +#ifdef PYTHON_REFCOUNT_DEBUG +ePyObject &ePyObject::operator=(PyObject *ob) +{ + m_ob=ob; + m_file=0; + m_line=0; + m_from=m_to=0; + m_erased=false; + return *this; +} + +ePyObject &ePyObject::operator=(const ePyObject &ob) +{ + m_ob=ob.m_ob; + m_file=ob.m_file; + m_line=ob.m_line; + m_from=ob.m_from; + m_to=ob.m_to; + m_erased=ob.m_erased; + return *this; +} + +ePyObject::operator PyObject*() +{ + if (m_ob) + { + if (!m_erased && m_ob->ob_refcnt > 0) + return m_ob; + eDebug("invalid access PyObject %s with refcount <= 0 %d", + m_erased ? "deleted" : "undeleted", m_ob->ob_refcnt); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + return 0; +} + +void ePyObject::incref(const char *file, int line) +{ + if (!m_ob) + { + eDebug("invalid incref python object with null pointer %s %d!!!", file, line); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + if (m_erased || m_ob->ob_refcnt <= 0) + { + eDebug("invalid incref %s python object with refcounting value %d in file %s line %d!!!", + m_erased ? "deleted" : "undeleted", m_ob->ob_refcnt, file, line); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + if (m_ob->ob_refcnt == 0x7FFFFFFF) + { + eDebug("invalid incref %s python object with refcounting value %d (MAX_INT!!!) in file %s line %d!!!", + m_erased ? "deleted" : "undeleted", m_ob->ob_refcnt, file, line); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + m_file = file; + m_line = line; + m_from = m_ob->ob_refcnt; + m_to = m_from+1; + Py_INCREF(m_ob); +} + +void ePyObject::decref(const char *file, int line) +{ + if (!m_ob) + { + eDebug("invalid decref python object with null pointer %s %d!!!", file, line); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + if (m_erased || m_ob->ob_refcnt <= 0) + { + eDebug("invalid decref %s python object with refcounting value %d in file %s line %d!!!", + m_erased ? "deleted" : "undeleted", m_ob->ob_refcnt, file, line); + if (m_file) + eDebug("last modified in file %s line %d from %d to %d", + m_file, m_line, m_from, m_to); + bsodFatal("enigma2, refcnt"); + } + m_file = file; + m_line = line; + m_from = m_ob->ob_refcnt; + m_to = m_from-1; + m_erased = !m_to; + Py_DECREF(m_ob); +} +#endif // PYTHON_REFCOUNT_DEBUG + +#define SKIP_PART1 +#include +#undef SKIP_PART1 + +ePython::ePython() +{ +// Py_VerboseFlag = 1; + +// Py_OptimizeFlag = 1; + + Py_Initialize(); + PyEval_InitThreads(); + + init_enigma(); + eBaseInit(); + eConsoleInit(); +} + +ePython::~ePython() +{ +// This appears to hang, sorry. +// Py_Finalize(); +} + +int ePython::execFile(const char *file) +{ + FILE *fp = fopen(file, "r"); + if (!fp) + return -ENOENT; + int ret = PyRun_SimpleFile(fp, file); + fclose(fp); + return ret; +} + +int ePython::execute(const std::string &pythonfile, const std::string &funcname) +{ + ePyObject pName, pModule, pDict, pFunc, pArgs, pValue; + pName = PyString_FromString(pythonfile.c_str()); + + pModule = PyImport_Import(pName); + Py_DECREF(pName); + + if (pModule) + { + pDict = PyModule_GetDict(pModule); + + pFunc = PyDict_GetItemString(pDict, funcname.c_str()); + + if (pFunc && PyCallable_Check(pFunc)) + { + pArgs = PyTuple_New(0); + // implement arguments.. + pValue = PyObject_CallObject(pFunc, pArgs); + Py_DECREF(pArgs); + if (pValue) + { + printf("Result of call: %ld\n", PyInt_AsLong(pValue)); + Py_DECREF(pValue); + } else + { + Py_DECREF(pModule); + PyErr_Print(); + return 1; + } + } + } else + { + if (PyErr_Occurred()) + PyErr_Print(); + return 1; + } + return 0; +} + +int ePython::call(ePyObject pFunc, ePyObject pArgs) +{ + int res = -1; + ePyObject pValue; + if (pFunc && PyCallable_Check(pFunc)) + { + pValue = PyObject_CallObject(pFunc, pArgs); + if (pValue) + { + if (PyInt_Check(pValue)) + res = PyInt_AsLong(pValue); + else + res = 0; + Py_DECREF(pValue); + } else + { + PyErr_Print(); + ePyObject FuncStr = PyObject_Str(pFunc); + ePyObject ArgStr = PyObject_Str(pArgs); + eDebug("(PyObject_CallObject(%s,%s) failed)", PyString_AS_STRING(FuncStr), PyString_AS_STRING(ArgStr)); + Py_DECREF(FuncStr); + Py_DECREF(ArgStr); + /* immediately show BSOD, so we have the actual error at the bottom */ + bsodFatal(0); + /* and make sure we quit (which would also eventually cause a bsod, but with useless termination messages) */ + quitMainloop(5); + } + } + return res; +} + +ePyObject ePython::resolve(const std::string &pythonfile, const std::string &funcname) +{ + ePyObject pName, pModule, pDict, pFunc; + + pName = PyString_FromString(pythonfile.c_str()); + + pModule = PyImport_Import(pName); + Py_DECREF(pName); + + if (pModule) + { + pDict = PyModule_GetDict(pModule); + pFunc = PyDict_GetItemString(pDict, funcname.c_str()); + Py_XINCREF(pFunc); + Py_DECREF(pModule); + } else if (PyErr_Occurred()) + PyErr_Print(); + return pFunc; +} diff --git a/pool/shard007/C++/0096072_round_robin_load_balancer_fuzz_test.cc b/pool/shard007/C++/0096072_round_robin_load_balancer_fuzz_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..75a456f44c87f0e1e4173ebd3e52db4fd3db7b40 --- /dev/null +++ b/pool/shard007/C++/0096072_round_robin_load_balancer_fuzz_test.cc @@ -0,0 +1,46 @@ +#include + +#include "test/common/upstream/round_robin_load_balancer_fuzz.pb.validate.h" +#include "test/common/upstream/zone_aware_load_balancer_fuzz_base.h" +#include "test/fuzz/fuzz_runner.h" +#include "test/test_common/utility.h" + +namespace Envoy { +namespace Upstream { + +DEFINE_PROTO_FUZZER(const test::common::upstream::RoundRobinLoadBalancerTestCase& input) { + try { + TestUtility::validate(input); + } catch (const ProtoValidationException& e) { + ENVOY_LOG_MISC(debug, "ProtoValidationException: {}", e.what()); + return; + } + + const test::common::upstream::ZoneAwareLoadBalancerTestCase& zone_aware_load_balancer_test_case = + input.zone_aware_load_balancer_test_case(); + + ZoneAwareLoadBalancerFuzzBase zone_aware_load_balancer_fuzz = ZoneAwareLoadBalancerFuzzBase( + zone_aware_load_balancer_test_case.need_local_priority_set(), + zone_aware_load_balancer_test_case.random_bytestring_for_weights()); + zone_aware_load_balancer_fuzz.initializeLbComponents( + zone_aware_load_balancer_test_case.load_balancer_test_case()); + + try { + zone_aware_load_balancer_fuzz.lb_ = std::make_unique( + zone_aware_load_balancer_fuzz.priority_set_, + zone_aware_load_balancer_fuzz.local_priority_set_.get(), + zone_aware_load_balancer_fuzz.stats_, zone_aware_load_balancer_fuzz.runtime_, + zone_aware_load_balancer_fuzz.random_, + zone_aware_load_balancer_test_case.load_balancer_test_case().common_lb_config(), + input.round_robin_lb_config(), zone_aware_load_balancer_fuzz.simTime()); + } catch (EnvoyException& e) { + ENVOY_LOG_MISC(debug, "EnvoyException; {}", e.what()); + return; + } + + zone_aware_load_balancer_fuzz.replay( + zone_aware_load_balancer_test_case.load_balancer_test_case().actions()); +} + +} // namespace Upstream +} // namespace Envoy diff --git a/pool/shard007/C++/0096076_HostlistColumn.cc b/pool/shard007/C++/0096076_HostlistColumn.cc new file mode 100644 index 0000000000000000000000000000000000000000..6cc8dc6f85e1e1f0fa01ffbbeb6fb8129cc813fe --- /dev/null +++ b/pool/shard007/C++/0096076_HostlistColumn.cc @@ -0,0 +1,64 @@ +// +------------------------------------------------------------------+ +// | ____ _ _ __ __ _ __ | +// | / ___| |__ ___ ___| | __ | \/ | |/ / | +// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | +// | | |___| | | | __/ (__| < | | | | . \ | +// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | +// | | +// | Copyright Mathias Kettner 2014 mk@mathias-kettner.de | +// +------------------------------------------------------------------+ +// +// This file is part of Check_MK. +// The official homepage is at http://mathias-kettner.de/check_mk. +// +// check_mk 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 in version 2. check_mk is distributed +// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- +// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public License for more de- +// tails. You should have received a copy of the GNU General Public +// License along with GNU Make; see the file COPYING. If not, write +// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, +// Boston, MA 02110-1301 USA. + +#include "HostlistColumn.h" +#include "HostlistFilter.h" +#include "Renderer.h" +#include "auth.h" +#include "opids.h" + +using std::string; + +hostsmember *HostlistColumn::getMembers(void *data) { + data = shiftPointer(data); + if (data == nullptr) { + return nullptr; + } + + return *reinterpret_cast(reinterpret_cast(data) + + _offset); +} + +void HostlistColumn::output(void *row, RowRenderer &r, contact *auth_user) { + ListRenderer l(r); + for (hostsmember *mem = getMembers(row); mem != nullptr; mem = mem->next) { + host *hst = mem->host_ptr; + if (auth_user == nullptr || + is_authorized_for(auth_user, hst, nullptr)) { + if (!_show_state) { + l.output(string(hst->name)); + } else { + SublistRenderer s(l); + s.output(string(hst->name)); + s.output(hst->current_state); + s.output(hst->has_been_checked); + } + } + } +} + +Filter *HostlistColumn::createFilter(RelationalOperator relOp, + const string &value) { + return new HostlistFilter(this, relOp, value); +} diff --git a/pool/shard007/C++/0096078_systemwrappers.cpp b/pool/shard007/C++/0096078_systemwrappers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62f0498824a59bff6e3cb68aa6dc1e506949c2b8 --- /dev/null +++ b/pool/shard007/C++/0096078_systemwrappers.cpp @@ -0,0 +1,91 @@ +/* + Copyright 2015-2020 Clément Gallet + + This file is part of libTAS. + + libTAS 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. + + libTAS 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 libTAS. If not, see . + */ + +#include "systemwrappers.h" +#include "logging.h" +#include "GlobalState.h" +#include "../shared/SharedConfig.h" +#include "backtrace.h" +#include +#ifdef __unix__ +#include "xlib/xdisplay.h" // x11::gameDisplays +#endif +#include + +namespace libtas { + +DEFINE_ORIG_POINTER(getpid) +DEFINE_ORIG_POINTER(fork) + +/* Override */ pid_t getpid (void) __THROW +{ + LINK_NAMESPACE_GLOBAL(getpid); + pid_t pid = orig::getpid(); + + if (GlobalState::isNative()) { + return pid; + } + + DEBUGLOGCALL(LCF_SYSTEM); + + /* A bit hackish: Dead Cells seeds the rng using the process pid. + * However, specifying a wrong pid for other calls will most likely crash + * games (mainly because OpenGL drivers need this value). So we look from + * which library was the call made. */ + void* return_address = __builtin_return_address(0); + char** symbols = backtrace_symbols(&return_address, 1); + if (symbols != nullptr) { + if (strstr(symbols[0], "libhl.so") || strstr(symbols[0], "PapersPlease(+0x")) + pid = 1234; + free(symbols); + } + + return pid; +} + +/* Override */ pid_t fork(void) __THROWNL +{ + LINK_NAMESPACE_GLOBAL(fork); + pid_t pid = orig::fork(); + + if (GlobalState::isNative()) { + return pid; + } + + DEBUGLOGCALL(LCF_SYSTEM); + + if (pid == 0) { + is_fork = true; + +#ifdef __unix__ + /* Invalidate the previous connections to the X server */ + for (int i=0; i + +#if ENABLE(WDS) + +using namespace WebCore; + +namespace android { + +namespace WDS { + +//------------------------------------------------------------------------------ +// Actual commands -- XXX should be moved somewhere else +//------------------------------------------------------------------------------ +static bool callDumpRenderTree(const Frame* frame, const Connection* conn) { + CString str = externalRepresentation(frame->contentRenderer()).latin1(); + conn->write(str.data(), str.length()); + return true; +} + +static bool callDumpDomTree(const Frame* frame, const Connection* conn) { + WebViewCore::getWebViewCore(frame->view())->dumpDomTree(true); + + FILE* f = fopen(DOM_TREE_LOG_FILE, "r"); + if (!f) { + conn->write("Dom tree written to logcat\n"); + } else { + char buf[512]; + while (true) { + int nread = fread(buf, 1, sizeof(buf), f); + if (nread <= 0) + break; + conn->write(buf, nread); + } + fclose(f); + } + return true; +} + +class WebCoreHandler : public Handler { +public: + virtual void post(TargetThreadFunction func, void* v) const { + callOnMainThread(func, v); + } +}; +static WebCoreHandler s_webcoreHandler; + +//------------------------------------------------------------------------------ +// End command section +//------------------------------------------------------------------------------ + +class InternalCommand : public Command { +public: + InternalCommand(const Command* comm, const Frame* frame, + const Connection* connection) + : Command(*comm) + , m_frame(frame) + , m_connection(connection) {} + virtual ~InternalCommand() { delete m_connection; } + + void doCommand() const { + LOGD("Executing command '%s' (%s)", m_name, m_description); + if (!m_dispatch(m_frame, m_connection)) + // XXX: Have useful failure messages + m_connection->write("EPIC FAIL!\n", 11); + } + +private: + const Frame* m_frame; + const Connection* m_connection; +}; + +static void commandDispatcher(void* v) { + InternalCommand* c = static_cast(v); + c->doCommand(); + delete c; +} + +void Command::dispatch() { + m_handler.post(commandDispatcher, this); +} + +Vector* Command::s_commands; + +void Command::Init() { + // Do not initialize twice. + if (s_commands) + return; + // XXX: Move this somewhere else. + s_commands = new Vector(); + s_commands->append(new Command("DDOM", "Dump Dom Tree", + callDumpDomTree, s_webcoreHandler)); + s_commands->append(new Command("DDRT", "Dump Render Tree", + callDumpRenderTree, s_webcoreHandler)); +} + +Command* Command::Find(const Connection* conn) { + char buf[COMMAND_LENGTH]; + if (conn->read(buf, sizeof(buf)) != COMMAND_LENGTH) + return NULL; + + // Linear search of commands. TODO: binary search when more commands are + // added. + Vector::const_iterator i = s_commands->begin(); + Vector::const_iterator end = s_commands->end(); + while (i != end) { + if (strncmp(buf, (*i)->name(), sizeof(buf)) == 0) + return new InternalCommand(*i, server()->getFrame(0), conn); + i++; + } + return NULL; +} + +} // end namespace WDS + +} // end namespace android + +#endif diff --git a/pool/shard007/C++/0096083_relation.cpp b/pool/shard007/C++/0096083_relation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0308bef396f7871e0f5f231c17b046f4eff0d96b --- /dev/null +++ b/pool/shard007/C++/0096083_relation.cpp @@ -0,0 +1,58 @@ +// Boost.Geometry (aka GGL, Generic Geometry Library) +// QuickBook Example + +// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. + +// This file was modified by Oracle on 2015. +// Modifications copyright (c) 2015 Oracle and/or its affiliates. + +// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle + +// Use, modification and distribution is subject to the Boost Software License, +// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +//[relation +//` Shows how to calculate the spatial relation between a point and a polygon + +#include +#include + +#include +#include +#include +/*<-*/ #include "create_svg_two.hpp" /*->*/ + +int main() +{ + typedef boost::geometry::model::d2::point_xy point_type; + typedef boost::geometry::model::polygon polygon_type; + + polygon_type poly; + boost::geometry::read_wkt( + "POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)" + "(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", poly); + + point_type p(4, 1); + + boost::geometry::de9im::matrix matrix = boost::geometry::relation(p, poly); + std::string code = matrix.str(); + + std::cout << "relation: " << code << std::endl; + /*<-*/ create_svg("relation.svg", poly, p); /*->*/ + return 0; +} + +//] + +//[relation_output +/*` +Output: +[pre +relation: 0FFFFF212 + +[$img/algorithms/within.png] +] + +*/ +//] diff --git a/pool/shard007/C++/0096084_genomeFile.cpp b/pool/shard007/C++/0096084_genomeFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b84948e6604776b55794cf3000e396e928ff0cb4 --- /dev/null +++ b/pool/shard007/C++/0096084_genomeFile.cpp @@ -0,0 +1,121 @@ +/***************************************************************************** + genomeFile.cpp + + (c) 2009 - Aaron Quinlan + Hall Laboratory + Department of Biochemistry and Molecular Genetics + University of Virginia + aaronquinlan@gmail.com + + Licensed under the GNU General Public License 2.0 license. +******************************************************************************/ +#include "lineFileUtilities.h" +#include "genomeFile.h" + + +GenomeFile::GenomeFile(const string &genomeFile) { + _genomeFile = genomeFile; + loadGenomeFileIntoMap(); +} + +GenomeFile::GenomeFile(const RefVector &genome) { + for (size_t i = 0; i < genome.size(); ++i) { + string chrom = genome[i].RefName; + int length = genome[i].RefLength; + + _chromSizes[chrom] = length; + _chromList.push_back(chrom); + } +} + +// Destructor +GenomeFile::~GenomeFile(void) { +} + + +void GenomeFile::loadGenomeFileIntoMap() { + + string genomeLine; + int lineNum = 0; + vector genomeFields; // vector for a GENOME entry + + // open the GENOME file for reading + ifstream genome(_genomeFile.c_str(), ios::in); + if ( !genome ) { + cerr << "Error: The requested genome file (" << _genomeFile << ") could not be opened. Exiting!" << endl; + exit (1); + } + + while (getline(genome, genomeLine)) { + + Tokenize(genomeLine,genomeFields); // load the fields into the vector + lineNum++; + + // ignore a blank line + if (genomeFields.size() > 0) { + if (genomeFields[0].find("#") != 0) { + // we need at least 2 columns + if (genomeFields.size() >= 2) { + char *p2End; + long c2; + // make sure the second column is numeric. + c2 = strtol(genomeFields[1].c_str(), &p2End, 10); + + // strtol will set p2End to the start of the string if non-integral, base 10 + if (p2End != genomeFields[1].c_str()) { + string chrom = genomeFields[0]; + int size = atoi(genomeFields[1].c_str()); + _chromSizes[chrom] = size; + _chromList.push_back(chrom); + _startOffsets.push_back(_genomeLength); + _genomeLength += size; + } + } + else { + cerr << "Less than the req'd two fields were encountered in the genome file (" << _genomeFile << ")"; + cerr << " at line " << lineNum << ". Exiting." << endl; + exit (1); + } + } + } + genomeFields.clear(); + } +} + +pair GenomeFile::projectOnGenome(uint32_t genome_pos) { + // search for the chrom that the position belongs on. + // add 1 to genome position b/c of zero-based, half open. + vector::const_iterator low = + lower_bound(_startOffsets.begin(), _startOffsets.end(), genome_pos + 1); + + // use the iterator to identify the appropriate index + // into the chrom name and start vectors + int i = int(low-_startOffsets.begin()); + string chrom = _chromList[i - 1]; + uint32_t start = genome_pos - _startOffsets[i - 1]; + return make_pair(chrom, start); +} + +uint32_t GenomeFile::getChromSize(const string &chrom) { + chromToSizes::const_iterator chromIt = _chromSizes.find(chrom); + if (chromIt != _chromSizes.end()) + return _chromSizes[chrom]; + else + return -1; // chrom not found. +} + +uint32_t GenomeFile::getGenomeSize(void) { + return _genomeLength; +} + +vector GenomeFile::getChromList() { + return _chromList; +} + +int GenomeFile::getNumberOfChroms() { + return _chromList.size(); +} + +string GenomeFile::getGenomeFileName() { + return _genomeFile; +} diff --git a/pool/shard007/C++/0096086_YProgressBar.cc b/pool/shard007/C++/0096086_YProgressBar.cc new file mode 100644 index 0000000000000000000000000000000000000000..e62fd21d0f5d95f23bee2274a9f896b2c71ba9c4 --- /dev/null +++ b/pool/shard007/C++/0096086_YProgressBar.cc @@ -0,0 +1,157 @@ +/* + Copyright (C) 2000-2012 Novell, Inc + This library is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation; either version 2.1 of the + License, or (at your option) version 3.0 of the License. This library + is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public + License for more details. You should have received a copy of the GNU + Lesser General Public License along with this library; if not, write + to the Free Software Foundation, Inc., 51 Franklin Street, Fifth + Floor, Boston, MA 02110-1301 USA +*/ + + +/*-/ + + File: YProgressBar.cc + + Author: Stefan Hundhammer + +/-*/ + + +#define YUILogComponent "ui" +#include "YUILog.h" + +#include "YUISymbols.h" +#include "YProgressBar.h" + +using std::string; + + +struct YProgressBarPrivate +{ + YProgressBarPrivate( const string & label, + int maxValue ) + : label( label ) + , maxValue( maxValue ) + , value( 0 ) + { + if ( maxValue < 1 ) + maxValue = 1; + } + + string label; + int maxValue; + int value; +}; + + + + +YProgressBar::YProgressBar( YWidget * parent, + const string & label, + int maxValue ) + : YWidget( parent ) + , priv( new YProgressBarPrivate( label, maxValue ) ) +{ + YUI_CHECK_NEW( priv ); + + setDefaultStretchable( YD_HORIZ, true ); + setStretchable( YD_VERT, false ); +} + + +YProgressBar::~YProgressBar() +{ + // NOP +} + + +string YProgressBar::label() +{ + return priv->label; +} + + +void YProgressBar::setLabel( const string & label ) +{ + priv->label = label; +} + + +int YProgressBar::maxValue() const +{ + return priv->maxValue; +} + + +int YProgressBar::value() const +{ + return priv->value; +} + + +void YProgressBar::setValue( int newValue ) +{ + if ( newValue < 0 ) + newValue = 0; + + if ( newValue > priv->maxValue ) + newValue = priv->maxValue; + + priv->value = newValue; +} + + +const YPropertySet & +YProgressBar::propertySet() +{ + static YPropertySet propSet; + + if ( propSet.isEmpty() ) + { + /* + * @property integer Value the current progress + * @property string Label caption above the progress bar + */ + propSet.add( YProperty( YUIProperty_Value, YIntegerProperty ) ); + propSet.add( YProperty( YUIProperty_Label, YStringProperty ) ); + propSet.add( YWidget::propertySet() ); + } + + return propSet; +} + + +bool +YProgressBar::setProperty( const string & propertyName, const YPropertyValue & val ) +{ + propertySet().check( propertyName, val.type() ); // throws exceptions if not found or type mismatch + + if ( propertyName == YUIProperty_Value ) setValue( val.integerVal() ); + else if ( propertyName == YUIProperty_Label ) setLabel( val.stringVal() ); + else + { + return YWidget::setProperty( propertyName, val ); + } + + return true; // success -- no special processing necessary +} + + +YPropertyValue +YProgressBar::getProperty( const string & propertyName ) +{ + propertySet().check( propertyName ); // throws exceptions if not found + + if ( propertyName == YUIProperty_Value ) return YPropertyValue( value() ); + else if ( propertyName == YUIProperty_Label ) return YPropertyValue( label() ); + else + { + return YWidget::getProperty( propertyName ); + } +} diff --git a/pool/shard007/C++/0096088_Canvas.cpp b/pool/shard007/C++/0096088_Canvas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8de886c1fbd1ea531dafc94e519a97ec31747ddd --- /dev/null +++ b/pool/shard007/C++/0096088_Canvas.cpp @@ -0,0 +1,234 @@ +/* + GWEN + Copyright (c) 2010 Facepunch Studios + See license in Gwen.h +*/ + + +#include "Gwen/Gwen.h" +#include "Gwen/Controls/Canvas.h" +#include "Gwen/Skin.h" +#include "Gwen/Controls/Menu.h" +#include "Gwen/DragAndDrop.h" +#include "Gwen/ToolTip.h" + +#ifndef GWEN_NO_ANIMATION +#include "Gwen/Anim.h" +#endif + +using namespace Gwen::Controls; + + +Canvas::Canvas( Gwen::Skin::Base* pSkin ) : BaseClass( NULL ), m_bAnyDelete( false ) +{ + SetBounds( 0, 0, 10000, 10000 ); + SetSkin( pSkin ); + SetScale( 1.0f ); + SetBackgroundColor( Color( 255, 255, 255, 255 ) ); + SetDrawBackground( false ); +} + +void Canvas::RenderCanvas() +{ + DoThink(); + + Gwen::Renderer::Base* render = m_Skin->GetRender(); + + render->Begin(); + + RecurseLayout( m_Skin ); + + render->SetClipRegion( GetBounds() ); + render->SetRenderOffset( Point( 0, 0 ) ); + render->SetScale( Scale() ); + + if ( m_bDrawBackground ) + { + render->SetDrawColor( m_BackgroundColor ); + render->DrawFilledRect( GetRenderBounds() ); + } + + DoRender( m_Skin ); + + DragAndDrop::RenderOverlay( this, m_Skin ); + + ToolTip::RenderToolTip( m_Skin ); + + render->EndClip(); + + render->End(); + + ProcessDelayedDeletes(); + +} + +void Canvas::Render( Gwen::Skin::Base* /*pRender*/ ) +{ + m_bNeedsRedraw = false; +} + +void Canvas::OnBoundsChanged( Rect oldBounds ) +{ + BaseClass::OnBoundsChanged( oldBounds ); + InvalidateChildren( true ); +} + + +void Canvas::DoThink() +{ + if ( Hidden() ) return; + + #ifndef GWEN_NO_ANIMATION + Gwen::Anim::Think(); + #endif + + // Reset tabbing + { + NextTab = NULL; + FirstTab = NULL; + } + + ProcessDelayedDeletes(); + // Check has focus etc.. + RecurseLayout( m_Skin ); + + // If we didn't have a next tab, cycle to the start. + if ( NextTab == NULL ) + NextTab = FirstTab; + + Gwen::Input::OnCanvasThink( this ); + +} + +void Canvas::SetScale( float f ) +{ + if ( m_fScale == f ) return; + + m_fScale = f; + + if ( m_Skin && m_Skin->GetRender() ) + m_Skin->GetRender()->SetScale( m_fScale ); + + OnScaleChanged(); + Redraw(); +} + +void Canvas::AddDelayedDelete( Gwen::Controls::Base* pControl ) +{ + if ( !m_bAnyDelete || m_DeleteSet.find( pControl ) == m_DeleteSet.end() ) + { + m_bAnyDelete = true; + m_DeleteSet.insert( pControl ); + m_DeleteList.push_back( pControl ); + } +} + +void Canvas::PreDelete( Controls::Base * pControl ) +{ + if ( m_bAnyDelete ) + { + std::set< Controls::Base * >::iterator itFind; + if ( ( itFind = m_DeleteSet.find( pControl ) ) != m_DeleteSet.end() ) + { + m_DeleteList.remove( pControl ); + m_DeleteSet.erase( pControl ); + m_bAnyDelete = !m_DeleteSet.empty(); + } + } +} + +void Canvas::ProcessDelayedDeletes() +{ + while( m_bAnyDelete ) + { + m_bAnyDelete = false; + + Controls::Base::List deleteList = m_DeleteList; + + m_DeleteList.clear(); + m_DeleteSet.clear(); + + for ( Gwen::Controls::Base::List::iterator it = deleteList.begin(); it != deleteList.end(); ++it ) + { + Gwen::Controls::Base* pControl = *it; + delete pControl; + } + } +} + +void Canvas::Release() +{ + Base::List::iterator iter = Children.begin(); + while ( iter != Children.end() ) + { + Base* pChild = *iter; + iter = Children.erase( iter ); + delete pChild; + } + + delete this; +} + +bool Canvas::InputMouseMoved( int x, int y, int deltaX, int deltaY ) +{ + if ( Hidden() ) return false; + + // Todo: Handle scaling here.. + //float fScale = 1.0f / Scale(); + + Gwen::Input::OnMouseMoved( this, x, y, deltaX, deltaY ); + + if ( !Gwen::HoveredControl ) return false; + if ( Gwen::HoveredControl == this ) return false; + if ( Gwen::HoveredControl->GetCanvas() != this ) return false; + + Gwen::HoveredControl->OnMouseMoved( x, y, deltaX, deltaY ); + Gwen::HoveredControl->UpdateCursor(); + + DragAndDrop::OnMouseMoved( Gwen::HoveredControl, x, y ); + return true; +} + +bool Canvas::InputMouseButton( int iButton, bool bDown ) +{ + if ( Hidden() ) return false; + + return Gwen::Input::OnMouseClicked( this, iButton, bDown ); +} + +bool Canvas::InputKey( int iKey, bool bDown ) +{ + if ( Hidden() ) return false; + if ( iKey <= Gwen::Key::Invalid ) return false; + if ( iKey >= Gwen::Key::Count ) return false; + + return Gwen::Input::OnKeyEvent( this, iKey, bDown ); +} + +bool Canvas::InputCharacter( Gwen::UnicodeChar chr ) +{ + if ( Hidden() ) return false; + if ( !iswprint( chr ) ) return false; + + //Handle Accelerators + if ( Gwen::Input::HandleAccelerator( this, chr ) ) + return true; + + //Handle characters + if ( !Gwen::KeyboardFocus ) return false; + if ( Gwen::KeyboardFocus->GetCanvas() != this ) return false; + if ( !Gwen::KeyboardFocus->Visible() ) return false; + if ( Gwen::Input::IsControlDown() ) return false; + + return KeyboardFocus->OnChar( chr ); +} + +bool Canvas::InputMouseWheel( int val ) +{ + if ( Hidden() ) return false; + if ( !Gwen::HoveredControl ) return false; + if ( Gwen::HoveredControl == this ) return false; + if ( Gwen::HoveredControl->GetCanvas() != this ) return false; + + return Gwen::HoveredControl->OnMouseWheeled( val ); +} \ No newline at end of file diff --git a/pool/shard007/C++/0096091_ConvertMQ0Bed.cpp b/pool/shard007/C++/0096091_ConvertMQ0Bed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ea573a38ce908b9deba533b7e3f3b247a07a401 --- /dev/null +++ b/pool/shard007/C++/0096091_ConvertMQ0Bed.cpp @@ -0,0 +1,68 @@ +/* + * ConvertMQ0Bed.cpp + * + * Created on: Mar 16, 2015 + * Author: fsedlaze + */ + +#include "ConvertMQ0Bed.h" + +void comp_mq0bed(std::string cov_file, int border, int cov_tresh) { + size_t buffer_size = 2000000; + char*buffer = new char[buffer_size]; + std::ifstream myfile; + + myfile.open(cov_file.c_str(), std::ifstream::in); + if (!myfile.good()) { + std::cout << "Cov Parser: could not open file: " << cov_file.c_str() << std::endl; + exit(0); + } + + myfile.getline(buffer, buffer_size); + int start = 0; + int current = -1; + int prev = current; + std::string start_chr; + std::string chr; + while (!myfile.eof()) { + int count = 0; + int cov = 0; + for (size_t i = 0; i < buffer_size && buffer[i] != '\0' && buffer[i] != '\n'; i++) { + + if (count == 0 && buffer[i] != '\t') { + chr += buffer[i]; + } + if (count == 1 && buffer[i - 1] == '\t') { + current = atoi(&buffer[i]); + } + if (count == 2 && buffer[i - 1] == '\t') { + cov = atoi(&buffer[i]); + break; + } + + if (buffer[i] == '\t') { + count++; + } + } + //std::cout< cov_tresh) { + if (prev != -1 && abs(current - prev) > border) { + //print + if (start - border > 1) { + std::cout << start_chr << "\t" << start - border << "\t" << prev + border << std::endl; + } else { + std::cout << start_chr << "\t" << 1 << "\t" << prev + border << std::endl; + } + start = current; + start_chr = chr; + } else if (prev == -1) { + start = current; + start_chr = chr; + } + prev = current; + } + chr.clear(); + myfile.getline(buffer, buffer_size); + } + myfile.close(); +} diff --git a/pool/shard007/C++/0096098_spxmlrpc.cpp b/pool/shard007/C++/0096098_spxmlrpc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8c974a34562db64d8588c258bbc855f7d2f64a1 --- /dev/null +++ b/pool/shard007/C++/0096098_spxmlrpc.cpp @@ -0,0 +1,294 @@ +/* + * Copyright 2010 Stephen Liu + * For license terms, see the file COPYING along with this library. + */ + +#include +#include +#include + +#include "spxmlrpc.hpp" + +#include "spxmlnode.hpp" +#include "spdomparser.hpp" +#include "spxmlhandle.hpp" +#include "spxmlcodec.hpp" +#include "spxmlutils.hpp" + +SP_XmlRpcReqObject :: SP_XmlRpcReqObject( const char * buffer, int len ) +{ + mPacketError = NULL; + + mParser = new SP_XmlDomParser(); + mParser->append( buffer, len ); + + SP_XmlHandle handle( mParser->getDocument()->getRootElement() ); + + mVersion = NULL; + + mMethod = handle.getChild( "methodName" ).getChild( 0 ).toCData(); + + mParams = handle.getChild( "params" ).getChild( "param" ) + .getChild( "value" ).getChild( 0 ).toElement(); + + if( NULL == mMethod ) { + mPacketError = "invalid xml stream, not methodName element"; + } else { + if( NULL == mParams ) { + mPacketError = "invalid xml stream, not params element"; + } + } + + mID = NULL; +} + +SP_XmlRpcReqObject :: ~SP_XmlRpcReqObject() +{ + delete mParser, mParser = NULL; +} + +const char * SP_XmlRpcReqObject :: getVersion() const +{ + return NULL == mVersion ? "" : mVersion->getText(); +} + +const char * SP_XmlRpcReqObject :: getMethod() const +{ + return NULL == mMethod ? "" : mMethod->getText(); +} + +SP_XmlElementNode * SP_XmlRpcReqObject :: getParams() const +{ + return mParams; +} + +const char * SP_XmlRpcReqObject :: getStrID() const +{ + return NULL == mID ? "" : mID->getText(); +} + +const char * SP_XmlRpcReqObject :: getPacketError() const +{ + return mPacketError; +} + +//============================================================================ + +SP_XmlRpcRespObject :: SP_XmlRpcRespObject( const char * buffer, int len ) +{ + mPacketError = NULL; + + mParser = new SP_XmlDomParser(); + mParser->append( buffer, len ); + + SP_XmlHandle handle( mParser->getDocument()->getRootElement() ); + + mVersion = NULL; + mID = NULL; + + mResult = handle.getChild( "params" ).getChild( "param" ) + .getChild( "value" ).getChild( 0 ).toElement(); + + mError = handle.getChild( "fault" ).getChild( "value" ).getChild( 0 ).toElement(); + + if( NULL == mResult && NULL == mError ) { + mPacketError = "invalid xml stream, not result element"; + } +} + +SP_XmlRpcRespObject :: ~SP_XmlRpcRespObject() +{ + delete mParser, mParser = NULL; +} + +const char * SP_XmlRpcRespObject :: getVersion() const +{ + return NULL == mVersion ? "" : mVersion->getText(); +} + +SP_XmlElementNode * SP_XmlRpcRespObject :: getResult() const +{ + return mResult; +} + +const char * SP_XmlRpcRespObject :: getStrID() const +{ + return NULL == mID ? "" : mID->getText(); +} + +SP_XmlElementNode * SP_XmlRpcRespObject :: getError() const +{ + return mError; +} + +int SP_XmlRpcRespObject :: getErrorCode() const +{ + SP_XmlHandle handle( mError ); + + SP_XmlCDataNode * node = NULL; + + for( int i = 0; i < 2; i++ ) { + SP_XmlCDataNode * name = handle.getChild( "member", i ).getChild( "name" ) + .getChild( 0 ).toCData(); + + if( NULL == name ) break; + + if( 0 == strcmp( "faultCode", name->getText() ) ) { + node = handle.getChild( "member", i ).getChild( "value" ) + .getChild( "int" ).getChild( 0 ).toCData(); + } + } + + return NULL != node ? atoi( node->getText() ) : 0; +} + +const char * SP_XmlRpcRespObject :: getErrorMsg() const +{ + SP_XmlHandle handle( mError ); + + SP_XmlCDataNode * node = NULL; + + for( int i = 0; i < 2; i++ ) { + SP_XmlCDataNode * name = handle.getChild( "member", i ).getChild( "name" ) + .getChild( 0 ).toCData(); + + if( NULL == name ) break; + + if( 0 == strcmp( "faultString", name->getText() ) ) { + node = handle.getChild( "member", i ).getChild( "value" ) + .getChild( "string" ).getChild( 0 ).toCData(); + } + } + + return NULL != node ? node->getText() : NULL; +} + +const char * SP_XmlRpcRespObject :: getPacketError() const +{ + return mPacketError; +} + +//============================================================================ + +int SP_XmlRpcUtils :: toReqBuffer( const char * method, const char * id, + const SP_XmlElementNode * params, SP_XmlStringBuffer * buffer ) +{ + buffer->append( "" ); + buffer->append( "" ); + + buffer->append( "" ); + SP_XmlStringCodec::encode( "utf-8", method, buffer ); + buffer->append( "" ); + + buffer->append( "" ); + + SP_XmlDomBuffer::dump( "utf-8", params, buffer, -1 ); + + buffer->append( "" ); + + buffer->append( "" ); + + return 0; +} + +int SP_XmlRpcUtils :: toRespBuffer( const char * id, const SP_XmlElementNode * result, + const SP_XmlElementNode * error, SP_XmlStringBuffer * buffer ) +{ + buffer->append( "" ); + buffer->append( "" ); + + if( NULL != error ) { + buffer->append( "" ); + buffer->append( "" ); + + SP_XmlDomBuffer::dump( "utf-8", error, buffer, -1 ); + + buffer->append( "" ); + buffer->append( "" ); + } else { + buffer->append( "" ); + + SP_XmlDomBuffer::dump( "utf-8", result, buffer, -1 ); + + buffer->append( "" ); + } + + buffer->append( "" ); + + return 0; +} + +int SP_XmlRpcUtils :: setError( SP_XmlElementNode * error, int code, const char * msg ) +{ + char strCode[ 32 ] = { 0 }; + snprintf( strCode, sizeof( strCode ), "%d", code ); + + // faultCode + { + SP_XmlElementNode * mcode = new SP_XmlElementNode(); + mcode->setName( "member" ); + + SP_XmlElementNode * name = new SP_XmlElementNode(); + name->setName( "name" ); + + SP_XmlCDataNode * cname = new SP_XmlCDataNode(); + cname->setText( "faultCode" ); + + name->addChild( cname ); + + mcode->addChild( name ); + + SP_XmlElementNode * value = new SP_XmlElementNode(); + value->setName( "value" ); + + SP_XmlElementNode * intNode = new SP_XmlElementNode(); + intNode->setName( "int" ); + + SP_XmlCDataNode * cvalue = new SP_XmlCDataNode(); + cvalue->setText( strCode ); + + intNode->addChild( cvalue ); + + value->addChild( intNode ); + + mcode->addChild( value ); + + error->addChild( mcode ); + } + + // faultString + { + SP_XmlElementNode * mcode = new SP_XmlElementNode(); + mcode->setName( "member" ); + + SP_XmlElementNode * name = new SP_XmlElementNode(); + name->setName( "name" ); + + SP_XmlCDataNode * cname = new SP_XmlCDataNode(); + cname->setText( "faultString" ); + + name->addChild( cname ); + + mcode->addChild( name ); + + SP_XmlElementNode * value = new SP_XmlElementNode(); + value->setName( "value" ); + + SP_XmlElementNode * strNode = new SP_XmlElementNode(); + strNode->setName( "string" ); + + SP_XmlCDataNode * cvalue = new SP_XmlCDataNode(); + cvalue->setText( msg ); + + strNode->addChild( cvalue ); + + value->addChild( strNode ); + + mcode->addChild( value ); + + error->addChild( mcode ); + } + + return 0; +} + diff --git a/pool/shard007/C++/0096100_StackDirectory.cpp b/pool/shard007/C++/0096100_StackDirectory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3912b4585d6a7f90c81b09158fc0bb851bef74fa --- /dev/null +++ b/pool/shard007/C++/0096100_StackDirectory.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * + * 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, 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 XBMC; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#include "StackDirectory.h" +#include "utils/log.h" +#include "Util.h" +#include "FileItem.h" +#include "StringUtils.h" +#include "AdvancedSettings.h" + +#define PRE_2_1_STACK_COMPATIBILITY + +using namespace std; +namespace XFILE +{ + CStackDirectory::CStackDirectory() + { + } + + CStackDirectory::~CStackDirectory() + { + } + + bool CStackDirectory::GetDirectory(const CStdString& strPath, CFileItemList& items) + { + items.Clear(); + // format is: + // stack://file1 , file2 , file3 , file4 + // filenames with commas are double escaped (ie replaced with ,,), thus the " , " separator used. + //CStdString folder, file; + //CUtil::Split(strPath, folder, file); + // split files on the single comma + CStdStringArray files; + StringUtils::SplitString(strPath, " , ", files); + if (files.empty()) + return false; // error in path + // remove "stack://" from the folder + for (unsigned int i = 0; i < files.size(); i++) + { + CStdString file = files[i]; + if (i == 0) + file = file.Mid(8); +#ifdef PRE_2_1_STACK_COMPATIBILITY + if (i > 0 && file.Find("\\") == -1 && file.Find('/') == -1) + { + CStdString strPath; + CUtil::GetDirectory(items[0]->m_strPath,strPath); + CStdString strFile = file; + CUtil::AddFileToFolder(strPath,strFile,file); + } +#endif + // replace double comma's with single ones. + file.Replace(",,", ","); + CFileItemPtr item(new CFileItem(file)); + //CUtil::AddFileToFolder(folder, file, item->m_strPath); + item->m_strPath = file; + item->m_bIsFolder = false; + items.Add(item); + } + return true; + } + + CStdString CStackDirectory::GetStackedTitlePath(const CStdString &strPath) + { + // Load up our REs + VECCREGEXP RegExps; + CRegExp tempRE(true); + const CStdStringArray& strRegExps = g_advancedSettings.m_videoStackRegExps; + CStdStringArray::const_iterator itRegExp = strRegExps.begin(); + vector > badStacks; + while (itRegExp != strRegExps.end()) + { + tempRE.RegComp(*itRegExp); + if (tempRE.GetCaptureTotal() == 4) + RegExps.push_back(tempRE); + else + CLog::Log(LOGERROR, "Invalid video stack RE (%s). Must have exactly 4 captures.", itRegExp->c_str()); + itRegExp++; + } + return GetStackedTitlePath(strPath, RegExps); + } + + CStdString CStackDirectory::GetStackedTitlePath(const CStdString &strPath, VECCREGEXP& RegExps) + { + CStackDirectory stack; + CFileItemList files; + CStdString strStackTitlePath, + strCommonDir = CUtil::GetParentPath(strPath); + + stack.GetDirectory(strPath, files); + + if (files.Size() > 1) + { + CStdString strStackTitle; + + CStdString File1 = CUtil::GetFileName(files[0]->m_strPath); + CStdString File2 = CUtil::GetFileName(files[1]->m_strPath); + + std::vector::iterator itRegExp = RegExps.begin(); + int offset = 0; + + while (itRegExp != RegExps.end()) + { + if (itRegExp->RegFind(File1, offset) != -1) + { + CStdString Title1 = itRegExp->GetMatch(1), + Volume1 = itRegExp->GetMatch(2), + Ignore1 = itRegExp->GetMatch(3), + Extension1 = itRegExp->GetMatch(4); + if (offset) + Title1 = File1.substr(0, itRegExp->GetSubStart(2)); + if (itRegExp->RegFind(File2, offset) != -1) + { + CStdString Title2 = itRegExp->GetMatch(1), + Volume2 = itRegExp->GetMatch(2), + Ignore2 = itRegExp->GetMatch(3), + Extension2 = itRegExp->GetMatch(4); + if (offset) + Title2 = File2.substr(0, itRegExp->GetSubStart(2)); + if (Title1.Equals(Title2)) + { + if (!Volume1.Equals(Volume2)) + { + if (Ignore1.Equals(Ignore2) && Extension1.Equals(Extension2)) + { + // got it + strStackTitle = Title1 + Ignore1 + Extension1; + itRegExp = RegExps.end(); + break; + } + else // Invalid stack + break; + } + else // Early match, retry with offset + { + offset = itRegExp->GetSubStart(3); + continue; + } + } + } + } + offset = 0; + itRegExp++; + } + if (!strCommonDir.empty() && !strStackTitle.empty()) + strStackTitlePath = strCommonDir + strStackTitle; + } + + return strStackTitlePath; + } + + CStdString CStackDirectory::GetFirstStackedFile(const CStdString &strPath) + { + // the stacked files are always in volume order, so just get up to the first filename + // occurence of " , " + CStdString path, file, folder; + int pos = strPath.Find(" , "); + if (pos > 0) + CUtil::Split(strPath.Left(pos), folder, file); + else + CUtil::Split(strPath, folder, file); // single filed stacks - should really not happen + + // remove "stack://" from the folder + folder = folder.Mid(8); + file.Replace(",,", ","); + CUtil::AddFileToFolder(folder, file, path); + + return path; + } + + CStdString CStackDirectory::ConstructStackPath(const CFileItemList &items, const vector &stack) + { + // no checks on the range of stack here. + // we replace all instances of comma's with double comma's, then separate + // the files using " , ". + CStdString stackedPath = "stack://"; + CStdString folder, file; + CUtil::Split(items[stack[0]]->m_strPath, folder, file); + stackedPath += folder; + // double escape any occurence of commas + file.Replace(",", ",,"); + stackedPath += file; + for (unsigned int i = 1; i < stack.size(); ++i) + { + stackedPath += " , "; + file = items[stack[i]]->m_strPath; + + // double escape any occurence of commas + file.Replace(",", ",,"); + stackedPath += file; + } + return stackedPath; + } + + bool CStackDirectory::ConstructStackPath(const vector &paths, CStdString& stackedPath) + { + if (paths.size() < 2) + return false; + stackedPath = "stack://"; + CStdString folder, file; + CUtil::Split(paths[0], folder, file); + stackedPath += folder; + // double escape any occurence of commas + file.Replace(",", ",,"); + stackedPath += file; + for (unsigned int i = 1; i < paths.size(); ++i) + { + stackedPath += " , "; + file = paths[i]; + + // double escape any occurence of commas + file.Replace(",", ",,"); + stackedPath += file; + } + return true; + } +} + diff --git a/pool/shard007/C++/0096103_RedirectorAccess.cpp b/pool/shard007/C++/0096103_RedirectorAccess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4dafeeaedacd47b20b63c1c013026768095203b --- /dev/null +++ b/pool/shard007/C++/0096103_RedirectorAccess.cpp @@ -0,0 +1,81 @@ +/********************************************************************** +* Copyright (c) 2013-2014 Red Hat, Inc. +* +* Developed by Daynix Computing LTD. +* +* Authors: +* Dmitry Fleytman +* Pavel Gurvich +* +* 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 "stdafx.h" +#include "RedirectorAccess.h" +#include "Public.h" + +void UsbDkRedirectorAccess::AbortPipe(ULONG64 PipeAddress) +{ + IoctlSync(IOCTL_USBDK_DEVICE_ABORT_PIPE, false, &PipeAddress, sizeof(PipeAddress)); +} + +void UsbDkRedirectorAccess::SetAltsetting(ULONG64 InterfaceIdx, ULONG64 AltSettingIdx) +{ + USBDK_ALTSETTINGS_IDXS AltSetting; + AltSetting.InterfaceIdx = InterfaceIdx; + AltSetting.AltSettingIdx = AltSettingIdx; + + IoctlSync(IOCTL_USBDK_DEVICE_SET_ALTSETTING, false, &AltSetting, sizeof(AltSetting)); +} + +void UsbDkRedirectorAccess::ResetDevice() +{ + IoctlSync(IOCTL_USBDK_DEVICE_RESET_DEVICE); +} + +bool UsbDkRedirectorAccess::IoctlSync(DWORD Code, + bool ShortBufferOk, + LPVOID InBuffer, + DWORD InBufferSize, + LPVOID OutBuffer, + DWORD OutBufferSize, + LPDWORD BytesReturned) +{ + UsbDkHandleHolder Event(CreateEvent(nullptr, FALSE, FALSE, nullptr)); + if (!Event) + { + throw UsbDkDriverFileException(TEXT("CreateEvent failed")); + } + + OVERLAPPED Overlapped; + Overlapped.hEvent = Event; + auto res = Ioctl(Code, ShortBufferOk, InBuffer, InBufferSize, OutBuffer, OutBufferSize, BytesReturned, &Overlapped); + + switch (res) + { + case TransferSuccessAsync: + DWORD NumberOfBytesTransferred; + if (!GetOverlappedResult(m_hDriver, &Overlapped, &NumberOfBytesTransferred, TRUE)) + { + throw UsbDkDriverFileException(TEXT("GetOverlappedResult failed")); + } + return true; + case TransferSuccess: + return true; + case TransferFailure: + return false; + } + + return false; +} diff --git a/pool/shard007/C++/0096106_CallbackNextOrdinal.cpp b/pool/shard007/C++/0096106_CallbackNextOrdinal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffd0bd2f191e6117150c53ed9b9325a309a2fb3c --- /dev/null +++ b/pool/shard007/C++/0096106_CallbackNextOrdinal.cpp @@ -0,0 +1,38 @@ +/****************************************************************************************************** + * (C) 2014 markummitchell@github.com. This file is part of Engauge Digitizer, which is released * + * under GNU General Public License version 2 (GPLv2) or (at your option) any later version. See file * + * LICENSE or go to gnu.org/licenses for details. Distribution requires prior written permission. * + ******************************************************************************************************/ + +#include "CallbackNextOrdinal.h" +#include "Logger.h" +#include "Point.h" +#include + +CallbackNextOrdinal::CallbackNextOrdinal(const QString &curveName) : + m_curveName (curveName), + m_maxOrdinalUsed (0) +{ +} + +CallbackSearchReturn CallbackNextOrdinal::callback (const QString &curveName, + const Point &point) +{ + if (curveName == m_curveName) { + if (point.ordinal() > m_maxOrdinalUsed) { + m_maxOrdinalUsed = point.ordinal(); + } + } + + return CALLBACK_SEARCH_RETURN_CONTINUE; +} + +double CallbackNextOrdinal::nextOrdinal () const +{ + int nextOrdinal = qFloor (m_maxOrdinalUsed) + 1; + + LOG4CPP_INFO_S ((*mainCat)) << "CallbackNextOrdinal::nextOrdinal" + << " ordinal=" << nextOrdinal; + + return nextOrdinal; +} diff --git a/pool/shard007/C++/0096111_binary.cpp b/pool/shard007/C++/0096111_binary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13c39c1b0b2c1e95360d38760274e01bf925c625 --- /dev/null +++ b/pool/shard007/C++/0096111_binary.cpp @@ -0,0 +1,150 @@ +#include "binary.h" +#include +#include +#include +#include + +namespace coda +{ + binary::binary() : val_(nullptr), sz_(0), alloc_(nullptr), copy_(nullptr), free_(nullptr), cmp_(nullptr) + { + } + binary::binary(const void *p, size_t sz, alloc_fn construct, copy_fn copy, free_fn destroy, cmp_fn compare) + : val_(nullptr), sz_(0), alloc_(construct), copy_(copy), free_(destroy), cmp_(compare) + { + copy_mem(p, sz, construct, copy); + } + binary::binary(const binary &p) : val_(p.val_), sz_(p.sz_), alloc_(p.alloc_), copy_(p.copy_), free_(p.free_), cmp_(p.cmp_) + { + copy_mem(p.val_, p.sz_, p.alloc_, p.copy_); + } + binary::binary(binary &&p) : val_(p.val_), sz_(p.sz_), alloc_(p.alloc_), copy_(p.copy_), free_(p.free_), cmp_(p.cmp_) + { + p.val_ = nullptr; + p.sz_ = 0; + p.alloc_ = nullptr; + p.copy_ = nullptr; + p.free_ = nullptr; + p.cmp_ = nullptr; + } + binary::~binary() + { + if (val_ && free_) { + free_(val_); + } + } + binary &binary::operator=(const binary &other) + { + if (free_ && val_) { + free_(val_); + } + val_ = other.val_; + sz_ = other.sz_; + alloc_ = other.alloc_; + copy_ = other.copy_; + free_ = other.free_; + cmp_ = other.cmp_; + copy_mem(other.val_, other.sz_, other.alloc_, other.copy_); + return *this; + } + + binary &binary::operator=(binary &&other) + { + val_ = other.val_; + sz_ = other.sz_; + alloc_ = other.alloc_; + copy_ = other.copy_; + free_ = other.free_; + cmp_ = other.cmp_; + other.val_ = nullptr; + other.sz_ = 0; + other.alloc_ = nullptr; + other.copy_ = nullptr; + other.free_ = nullptr; + other.cmp_ = nullptr; + return *this; + } + + void binary::copy_mem(const void *p, size_t size, alloc_fn construct, copy_fn copy) + { + if (size > 0 && construct != nullptr) { + val_ = construct(size); + sz_ = size; + if (val_ == nullptr) { + throw std::bad_alloc(); + } + if (p != nullptr && copy != nullptr) { + copy(val_, p, size); + } else { + memset(val_, 0, size); + } + } + } + + size_t binary::size() const + { + return sz_; + } + + void *binary::value() const + { + return val_; + } + + bool binary::is_null() const + { + return val_ == nullptr || sz_ == 0; + } + + bool binary::is_transient() const + { + return free_ != nullptr; + } + + std::string binary::to_string() const + { + if (val_ == nullptr || sz_ == 0) { + return "0x0"; + } + + std::ostringstream os; + os << *this; + return os.str(); + } + + bool binary::operator==(const binary &p) const + { + return cmp_ && val_ && p.val_ && sz_ > 0 && cmp_(val_, p.val_, sz_) == 0; + } + + bool binary::operator==(const void *p) const + { + return cmp_ && val_ && sz_ > 0 && p && cmp_(val_, p, sz_) == 0; + } + + bool binary::operator==(const std::nullptr_t &null) const + { + return is_null(); + } + + std::ostream &operator<<(std::ostream &out, const binary &value) + { + out << std::hex << value.val_; + return out; + } + + bool operator==(const void *ptr, const coda::binary &p) + { + return p == ptr; + } + + bool operator==(const std::nullptr_t &null, const coda::binary &bin) + { + return bin == null; + } + + std::string to_string(const coda::binary &p) + { + return p.to_string(); + } +} diff --git a/pool/shard007/C++/0096113_dx12_utils.cc b/pool/shard007/C++/0096113_dx12_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff15c630329238c5d8f807301f5f0f8962f40dda --- /dev/null +++ b/pool/shard007/C++/0096113_dx12_utils.cc @@ -0,0 +1,185 @@ +//============================================================================== +// Copyright (c) 2015-2021 Advanced Micro Devices, Inc. All rights reserved. +/// @author AMD Developer Tools Team +/// @file +/// @brief DX12 utility function implementations +//============================================================================== + +#include "gpu_perf_api_dx12/dx12_utils.h" + +#include "d3d12.h" + +#include "gpu_perf_api_common/logging.h" + +GpaStatus dx12_utils::Dx12GetAdapterDesc(IUnknown* device, DXGI_ADAPTER_DESC& adapter_desc) +{ + GpaStatus status = kGpaStatusOk; + + if (nullptr == device) + { + GPA_LOG_ERROR("Parameter 'device' is NULL."); + status = kGpaStatusErrorNullPointer; + } + else + { + ID3D12Device* dx12_device = static_cast(device); + LUID adapter_luid = dx12_device->GetAdapterLuid(); + + IDXGIFactory* dxgi_factory = nullptr; + HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast(&dxgi_factory)); + + if (FAILED(hr) || (nullptr == dxgi_factory)) + { + GPA_LOG_ERROR("Unable to get IDXGIFactory interface from ID3D12Device."); + status = kGpaStatusErrorFailed; + } + else + { + IDXGIAdapter* adapter = nullptr; + + for (UINT index = 0; dxgi_factory->EnumAdapters(index, &adapter) != DXGI_ERROR_NOT_FOUND; ++index) + { + memset(&adapter_desc, 0, sizeof(adapter_desc)); + hr = adapter->GetDesc(&adapter_desc); + + if (FAILED(hr)) + { + GPA_LOG_ERROR("Could not get adapter description, hardware cannot be supported."); + status = kGpaStatusErrorFailed; + } + else + { + if (adapter_desc.AdapterLuid.HighPart == adapter_luid.HighPart && adapter_desc.AdapterLuid.LowPart == adapter_luid.LowPart) + { + // We found the matching adapter luid, so we're done. + break; + } + } + } + } + + dxgi_factory->Release(); + } + + return status; +} + +bool dx12_utils::IsD3D12CommandList(void* cmd, D3D12_COMMAND_LIST_TYPE* cmd_type) +{ + IUnknown* unknown = static_cast(cmd); + ID3D12GraphicsCommandList* d3d_command_list; + HRESULT hr = unknown->QueryInterface(__uuidof(ID3D12GraphicsCommandList), reinterpret_cast(&d3d_command_list)); + bool result = SUCCEEDED(hr); + + if (result && nullptr != cmd_type) + { + *cmd_type = d3d_command_list->GetType(); + d3d_command_list->Release(); // We need to release this as QueryInterface will call AddRef. + } + + return result; +} + +bool dx12_utils::IsSameCmdType(const D3D12_COMMAND_LIST_TYPE* dx12_cmd_type, const GpaCommandListType* gpa_cmd_type) +{ + if (nullptr != dx12_cmd_type && nullptr != gpa_cmd_type) + { + if (D3D12_COMMAND_LIST_TYPE_BUNDLE == *dx12_cmd_type && kGpaCommandListSecondary == *gpa_cmd_type) + { + return true; + } + + if (D3D12_COMMAND_LIST_TYPE_BUNDLE != *dx12_cmd_type && kGpaCommandListPrimary == *gpa_cmd_type) + { + return true; + } + } + + return false; +} + +bool dx12_utils::GetD3D12Device(IUnknown* interface_pointer, ID3D12Device** d3d12_device) +{ + bool success = false; + *d3d12_device = nullptr; + + // Check to see if it's an ID3D12Device. + HRESULT hr = interface_pointer->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast(d3d12_device)); + + if (hr == E_NOINTERFACE) + { + // It's not an ID3D12device, so see if it is an ID3D12DeviceChild-derived interface (like a ID3D12CommandList). + ID3D12DeviceChild* device_child = nullptr; + + hr = interface_pointer->QueryInterface(__uuidof(ID3D12DeviceChild), reinterpret_cast(&device_child)); + + if (SUCCEEDED(hr)) + { + // Note: GetDevice increments a ref on out parameter. + hr = device_child->GetDevice(__uuidof(ID3D12Device), reinterpret_cast(d3d12_device)); + device_child->Release(); + } + } + + success = SUCCEEDED(hr); + + if (success) + { + (*d3d12_device)->Release(); + } + + return success; +} + +bool dx12_utils::IsFeatureLevelSupported(ID3D12Device* d3d12_device) +{ + D3D12_FEATURE_DATA_FEATURE_LEVELS feature_levels = {}; + const D3D_FEATURE_LEVEL requested_feature_levels[] = { + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL_12_1, + }; + + feature_levels.NumFeatureLevels = _countof(requested_feature_levels); + feature_levels.pFeatureLevelsRequested = requested_feature_levels; + + HRESULT hr = d3d12_device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &feature_levels, sizeof(feature_levels)); + + return SUCCEEDED(hr); +} + +bool dx12_utils::GetTimestampFrequency(ID3D12Device* d3d12_device, UINT64& timestamp_frequency) +{ + bool is_succeeded = false; + ID3D12CommandQueue* queue = nullptr; + D3D12_COMMAND_QUEUE_DESC queue_desc; + ZeroMemory(&queue_desc, sizeof(queue_desc)); + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + HRESULT hr = d3d12_device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast(&queue)); + + if (SUCCEEDED(hr) || nullptr != queue) + { + UINT64 frequency = 0; + hr = queue->GetTimestampFrequency(&frequency); + + if (SUCCEEDED(hr)) + { + is_succeeded = true; + timestamp_frequency = frequency; + } + else + { + GPA_LOG_ERROR("Calling GetTimestampFrequency on Direct Command Queue failed"); + } + + queue->Release(); + } + else + { + GPA_LOG_ERROR("GetTimestampFrequency Create Command Queue failed"); + } + + return is_succeeded; +} diff --git a/pool/shard007/C++/0096119_WebserverContentManager.cpp b/pool/shard007/C++/0096119_WebserverContentManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aecdf7c383ef8cc524db0b0365fec3f0360c980f --- /dev/null +++ b/pool/shard007/C++/0096119_WebserverContentManager.cpp @@ -0,0 +1,99 @@ +#include "WebserverContentManager.h" +#include +#include "Application.h" +#include "FileTools.h" + +std::string escapeString(const std::string& s) +{ + std::string out; + for(const auto& c: s) + { + if(std::isspace(c)) + out += '\\'; + out += c; + } + return out; +} + +WebserverContentManager::WebserverContentManager() { + //Testpages + webPages["/hello"] = "

Hello GreenField!

"; + webPages["/test-text"] = "test"; + webPages["test-with-function"] = "test"; + webFunctions["/test-with-function"] = [this](argumentMap_t args) { + auto& app = Application::get(); + app.testFlag = true; + }; + //End Testpages + + webFunctions["/"] = [this](argumentMap_t args) { + HTML website; + auto& app = Application::get(); + + auto fileList = FileTools::getPathListOfDirectoryRecursive(std::string("./usb/")); + auto filteredFiles = FileTools::filterFiles(fileList, [](std::experimental::filesystem::path path)->bool + { + return path.extension().string() == std::string(".wav"); + }); + + website = "

available files:

trackqueue:

    "; + auto& musicManager = app.getMusicManager(); + for(auto track: musicManager.getTrackDeque()) + { + website += "
  • " + track + "
  • "; + } + website += "
"; + + webPages["/"] = website; + return true; + }; + + webFunctions["/add-track-queue"] = [this](argumentMap_t args) { + auto const& track = args["track"]; + + std::cout << track << '\n'; + + if(track.empty() == false) { + auto &musicManager = Application::get().getMusicManager(); + musicManager.addTrackToQueue(track); + std::cout << "trackqueue added: " << track << '\n'; + assert(musicManager.getTrackDeque().size() != 0); + } + webFunctions["/"]; + webPages["/add-track-queue"] = webPages["/"]; + return true; + }; +} + +WebserverContentManager::HTML WebserverContentManager::handleRequest(URL url) { + return handleRequest(url, argumentMap_t()); +} + +WebserverContentManager::HTML WebserverContentManager::handleRequest(URL url, argumentMap_t args) { + runWebFunction(url, args); + auto webpage = getWebContent(url); + return webpage; +} + +WebserverContentManager::HTML WebserverContentManager::getWebContent(URL url) { + try { + return webPages.at(url); + } catch(...) { + return "

404 Page Not Found!"; + } +} + +bool WebserverContentManager::runWebFunction(URL url, argumentMap_t args) { + try { + webFunctions.at(url)(args); + return true; + } catch (...) { + return false; + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0096128_CreateCertificateAuthorityAuditReportResult.cpp b/pool/shard007/C++/0096128_CreateCertificateAuthorityAuditReportResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da82fd618ea33e2e1831195603c99814f0a242dc --- /dev/null +++ b/pool/shard007/C++/0096128_CreateCertificateAuthorityAuditReportResult.cpp @@ -0,0 +1,46 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::ACMPCA::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +CreateCertificateAuthorityAuditReportResult::CreateCertificateAuthorityAuditReportResult() +{ +} + +CreateCertificateAuthorityAuditReportResult::CreateCertificateAuthorityAuditReportResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +CreateCertificateAuthorityAuditReportResult& CreateCertificateAuthorityAuditReportResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("AuditReportId")) + { + m_auditReportId = jsonValue.GetString("AuditReportId"); + + } + + if(jsonValue.ValueExists("S3Key")) + { + m_s3Key = jsonValue.GetString("S3Key"); + + } + + + + return *this; +} diff --git a/pool/shard007/C++/0096131_simple_recv.cpp b/pool/shard007/C++/0096131_simple_recv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f669e30925005f2d0b4174fc38ab84f233194bfb --- /dev/null +++ b/pool/shard007/C++/0096131_simple_recv.cpp @@ -0,0 +1,85 @@ +/* + * + * 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 "options.hpp" + +#include "proton/container.hpp" +#include "proton/messaging_handler.hpp" +#include "proton/link.hpp" + +#include +#include + + + +class simple_recv : public proton::messaging_handler { + private: + proton::url url; + proton::counted_ptr receiver; + int expected; + int received; + public: + + simple_recv(const std::string &s, int c) : url(s), expected(c), received(0) {} + + void on_start(proton::event &e) { + receiver = e.container().create_receiver(url).ptr(); + std::cout << "simple_recv listening on " << url << std::endl; + } + + void on_message(proton::event &e) { + proton::message& msg = e.message(); + proton::data_value id = msg.id(); + if (id.type() == proton::ULONG) { + if (id.get() < received) + return; // ignore duplicate + } + if (expected == 0 || received < expected) { + std::cout << msg.body() << std::endl; + received++; + if (received == expected) { + e.receiver().close(); + e.connection().close(); + } + } + } +}; + +int main(int argc, char **argv) { + // Command line options + std::string address("127.0.0.1:5672/examples"); + int message_count = 100; + options opts(argc, argv); + opts.add_value(address, 'a', "address", "connect to and receive from URL", "URL"); + opts.add_value(message_count, 'm', "messages", "receive COUNT messages", "COUNT"); + + try { + opts.parse(); + simple_recv recv(address, message_count); + proton::container(recv).run(); + return 0; + } catch (const bad_option& e) { + std::cout << opts << std::endl << e.what() << std::endl; + } catch (const std::exception& e) { + std::cerr << e.what() << std::endl; + } + return 1; +} diff --git a/pool/shard007/C++/0096132_bgp_show_neighbor.cc b/pool/shard007/C++/0096132_bgp_show_neighbor.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa598d6a750b08c2d2fea81ce620f5f78a625c14 --- /dev/null +++ b/pool/shard007/C++/0096132_bgp_show_neighbor.cc @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. + */ + +#include "bgp/bgp_show_handler.h" + +#include "base/regex.h" +#include "bgp/bgp_peer.h" +#include "bgp/bgp_peer_internal_types.h" +#include "bgp/bgp_server.h" +#include "bgp/routing-instance/peer_manager.h" +#include "bgp/routing-instance/routing_instance.h" + +using contrail::regex; +using contrail::regex_match; +using contrail::regex_search; +using std::string; +using std::vector; + +// +// Build the list of BgpPeers in one shot for now. +// +static bool FillBgpNeighborInfoList(const BgpSandeshContext *bsc, + bool summary, uint32_t page_limit, uint32_t iter_limit, + const string &start_neighbor, const string &search_string, + vector *show_list, string *next_instance) { + regex search_expr(search_string); + + for (const BgpPeer *peer = bsc->bgp_server->FindNextPeer(); peer != NULL; + peer = bsc->bgp_server->FindNextPeer(peer->peer_name())) { + if ((!regex_search(peer->peer_basename(), search_expr)) && + (!regex_search(peer->peer_address_string(), search_expr)) && + (search_string != "deleted" || !peer->IsDeleted())) { + continue; + } + + BgpNeighborResp bnr; + peer->FillNeighborInfo(bsc, &bnr, summary); + show_list->push_back(bnr); + } + return true; +} + +// +// Specialization of BgpShowHandler<>::CallbackCommon for regular introspect. +// +// Note that we don't both paginating bgp neighbors since the list should be +// pretty small. We always add at least one xmpp neighbor to the list and then +// paginate the xmpp neighbors as needed. +// +template <> +bool BgpShowHandler::CallbackCommon( + const BgpSandeshContext *bsc, Data *data) { + uint32_t page_limit = bsc->page_limit() ? bsc->page_limit() : kPageLimit; + uint32_t iter_limit = bsc->iter_limit() ? bsc->iter_limit() : kIterLimit; + + // Build the list of BgpPeers in one shot for now. + if (data->next_entry.empty()) { + FillBgpNeighborInfoList(bsc, false, page_limit, iter_limit, string(), + data->search_string, &data->show_list, NULL); + } + + // Add xmpp neighbors. + string next_neighbor; + bool done = bsc->ShowNeighborExtension(bsc, false, page_limit, iter_limit, + data->next_entry, data->search_string, &data->show_list, + &next_neighbor); + if (!next_neighbor.empty()) + SaveContextToData(next_neighbor, done, data); + return done; +} + +// +// Specialization of BgpShowHandler<>::FillShowList for regular introspect. +// +template <> +void BgpShowHandler::FillShowList( + BgpNeighborListResp *resp, const vector &show_list) { + resp->set_neighbors(show_list); +} + +// +// Specialization of BgpShowHandler<>::CallbackCommon for summary introspect. +// +// Note that we don't both paginating bgp neighbors since the list should be +// pretty small. We always add at least one xmpp neighbor to the list and then +// paginate the xmpp neighbors as needed. +// +template <> +bool BgpShowHandler::CallbackCommon( + const BgpSandeshContext *bsc, Data *data) { + uint32_t page_limit = bsc->page_limit() ? bsc->page_limit() : kPageLimit; + uint32_t iter_limit = bsc->iter_limit() ? bsc->iter_limit() : kIterLimit; + + // Build the list of BgpPeers in one shot for now. + if (data->next_entry.empty()) { + FillBgpNeighborInfoList(bsc, true, page_limit, iter_limit, string(), + data->search_string, &data->show_list, NULL); + } + + // Add xmpp neighbors. + string next_neighbor; + bool done = bsc->ShowNeighborExtension(bsc, true, page_limit, iter_limit, + data->next_entry, data->search_string, &data->show_list, + &next_neighbor); + if (!next_neighbor.empty()) + SaveContextToData(next_neighbor, done, data); + return done; +} + +// +// Specialization of BgpShowHandler<>::FillShowList for summary introspect. +// +template <> +void BgpShowHandler::FillShowList( + ShowBgpNeighborSummaryResp *resp, + const vector &show_list) { + resp->set_neighbors(show_list); +} + +// +// Handler for BgpNeighborReq. +// +void BgpNeighborReq::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + BgpNeighborReq, + BgpNeighborReqIterate, + BgpNeighborListResp, + BgpNeighborResp>::Callback, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + BgpNeighborReq, + BgpNeighborReqIterate, + BgpNeighborListResp, + BgpNeighborResp>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} + +// +// Handler for BgpNeighborReqIterate. +// +void BgpNeighborReqIterate::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + BgpNeighborReq, + BgpNeighborReqIterate, + BgpNeighborListResp, + BgpNeighborResp>::CallbackIterate, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + BgpNeighborReq, + BgpNeighborReqIterate, + BgpNeighborListResp, + BgpNeighborResp>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} + +// +// Handler for ShowBgpNeighborSummaryReq. +// +void ShowBgpNeighborSummaryReq::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + ShowBgpNeighborSummaryReq, + ShowBgpNeighborSummaryReqIterate, + ShowBgpNeighborSummaryResp, + BgpNeighborResp>::Callback, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + ShowBgpNeighborSummaryReq, + ShowBgpNeighborSummaryReqIterate, + ShowBgpNeighborSummaryResp, + BgpNeighborResp>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} + +// +// Handler for ShowBgpNeighborSummaryReqIterate. +// +void ShowBgpNeighborSummaryReqIterate::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + ShowBgpNeighborSummaryReq, + ShowBgpNeighborSummaryReqIterate, + ShowBgpNeighborSummaryResp, + BgpNeighborResp>::CallbackIterate, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + ShowBgpNeighborSummaryReq, + ShowBgpNeighborSummaryReqIterate, + ShowBgpNeighborSummaryResp, + BgpNeighborResp>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} diff --git a/pool/shard007/C++/0096135_Stats.cpp b/pool/shard007/C++/0096135_Stats.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3152b6b11167c2f36cf6109b008b30dd49d56c8 --- /dev/null +++ b/pool/shard007/C++/0096135_Stats.cpp @@ -0,0 +1,55 @@ +/* Stats.cpp: EGRET stats + + Copyright (C) 2016-2018 Eric Larson and Anna Kirk + elarson@seattleu.edu + + This file is part of EGRET. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include "Stats.h" +using namespace std; + +void +Stats::add(string tag, string name, int value) +{ + Stat stat = { tag, name, value }; + statList.push_back(stat); +} + +void +Stats::print() +{ + const int WIDTH = 30; + + string prev_tag = ""; + vector ::iterator it; + for (it = statList.begin(); it != statList.end(); it++) { + + // print divider line between different tags + if (it->tag != prev_tag && prev_tag != "") { + for (int i = 0; i < WIDTH + 8; i++) cout << "-"; + cout << endl; + } + + cout << left << setw(WIDTH) << it->name << "| " << it->value << endl; + prev_tag = it->tag; + } +} + diff --git a/pool/shard007/C++/0096136_handlers.cpp b/pool/shard007/C++/0096136_handlers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8437bd7da4c023b532e7205ac49db78d5e31f97 --- /dev/null +++ b/pool/shard007/C++/0096136_handlers.cpp @@ -0,0 +1,196 @@ +/* + Copyright (C) 2003 - 2016 by David White + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + 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. + + See the COPYING file for more details. +*/ + +/** + * @file + * The structure that tracks WML event handlers. + * (Typically, handlers are defined by [event] tags.) + */ + +#include "global.hpp" +#include "handlers.hpp" +#include "manager.hpp" +#include "manager_impl.hpp" +#include "menu_item.hpp" +#include "pump.hpp" + +#include "formula/string_utils.hpp" +#include "game_data.hpp" +#include "log.hpp" +#include "reports.hpp" +#include "scripting/game_lua_kernel.hpp" +#include "serialization/string_utils.hpp" +#include "soundsource.hpp" +#include "util.hpp" + +#include +#include + + +static lg::log_domain log_engine("engine"); +#define DBG_NG LOG_STREAM(debug, log_engine) +#define LOG_NG LOG_STREAM(info, log_engine) +#define WRN_NG LOG_STREAM(warn, log_engine) + +static lg::log_domain log_event_handler("event_handler"); +#define DBG_EH LOG_STREAM(debug, log_event_handler) + + +// This file is in the game_events namespace. +namespace game_events { + +/* ** handler_list::iterator ** */ + +/** + * Dereference. + * If the current element has become invalid, we will increment first. + */ +handler_ptr handler_list::iterator::operator*() +{ + // Check for an available handler. + while ( iter_.derefable() ) { + // Handler still accessible? + if ( handler_ptr lock = iter_->lock() ) + return lock; + else + // Remove the now-defunct entry. + iter_ = list_t::erase(iter_); + } + + // End of the list. + return handler_ptr(); +} + + +/* ** event_handler ** */ + +event_handler::event_handler(const config &cfg, bool imi, handler_vec::size_type index, manager & man) + : first_time_only_(cfg["first_time_only"].to_bool(true)) + , is_menu_item_(imi) + , index_(index) + , man_(&man) + , cfg_(cfg) +{} + +/** + * Disables *this, removing it from the game. + * (Technically, the handler is only removed once no one is hanging on to a + * handler_ptr to *this. So be careful how long they persist.) + * + * WARNING: *this may be destroyed at the end of this call, unless + * the caller maintains a handler_ptr to this. + */ +void event_handler::disable() +{ + assert(man_); + assert(man_->event_handlers_); + // Handlers must have an index after they're created. + assert ( index_ < man_->event_handlers_->size() ); + // Disable this handler. + (*man_->event_handlers_)[index_].reset(); +} + +/** + * Handles the queued event, according to our WML instructions. + * WARNING: *this may be destroyed at the end of this call, unless + * the caller maintains a handler_ptr to this. + * + * @param[in] event_info Information about the event that needs handling. + * @param[in,out] handler_p The caller's smart pointer to *this. It may be + * reset() during processing. + */ +void event_handler::handle_event(const queued_event& event_info, handler_ptr& handler_p, game_lua_kernel & lk) +{ + // We will need our config after possibly self-destructing. Make a copy now. + // TODO: instead of copying possibly huge config objects we should use shared things and only increase a refcount here. + vconfig vcfg(cfg_, true); + + if (is_menu_item_) { + DBG_NG << cfg_["name"] << " will now invoke the following command(s):\n" << cfg_; + } + + if (first_time_only_) + { + // Disable this handler. + disable(); + // Also remove our caller's hold on us. + handler_p.reset(); + } + // *WARNING*: At this point, dereferencing this could be a memory violation! + + lk.run_wml_action("command", vcfg, event_info); +} + +bool event_handler::matches_name(const std::string &name, const game_data * gd) const +{ + const std::string my_names = !gd ? cfg_["name"].str() : + utils::interpolate_variables_into_string(cfg_["name"], *gd); + std::string::const_iterator itor, + it_begin = my_names.begin(), + it_end = my_names.end(), + match_it = name.begin(), + match_begin = name.begin(), + match_end = name.end(); + int skip_count = 0; + for(itor = it_begin; itor != it_end; ++itor) { + bool do_eat = false, + do_skip = false; + switch(*itor) { + case ',': + if(itor - it_begin - skip_count == match_it - match_begin && match_it == match_end) { + return true; + } + it_begin = itor + 1; + match_it = match_begin; + skip_count = 0; + continue; + case '\f': + case '\n': + case '\r': + case '\t': + case '\v': + do_skip = (match_it == match_begin || match_it == match_end); + break; + case ' ': + do_skip = (match_it == match_begin || match_it == match_end); + // fall through to case '_' + case '_': + do_eat = (match_it != match_end && (*match_it == ' ' || *match_it == '_')); + break; + default: + do_eat = (match_it != match_end && *match_it == *itor); + break; + } + if(do_eat) { + ++match_it; + } else if(do_skip) { + ++skip_count; + } else { + itor = std::find(itor, it_end, ','); + if(itor == it_end) { + return false; + } + it_begin = itor + 1; + match_it = match_begin; + skip_count = 0; + } + } + if(itor - it_begin - skip_count == match_it - match_begin && match_it == match_end) { + return true; + } + return false; +} + +} // end namespace game_events + diff --git a/pool/shard007/C++/0096138_collective_nccl_reducer.cc b/pool/shard007/C++/0096138_collective_nccl_reducer.cc new file mode 100644 index 0000000000000000000000000000000000000000..113f1487f0189aa351e5f89e37be116b0ac33ee5 --- /dev/null +++ b/pool/shard007/C++/0096138_collective_nccl_reducer.cc @@ -0,0 +1,204 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "tensorflow/core/kernels/collective_nccl_reducer.h" + +#ifdef GOOGLE_CUDA + +#include "tensorflow/core/common_runtime/collective_util.h" +#include "tensorflow/core/nccl/nccl_manager.h" + +namespace tensorflow { +namespace { +string NcclCollectiveKey(const string& exec_key, int step_id) { + return strings::StrCat(exec_key, ":", step_id); +} +} // namespace + +NcclReducer::NcclReducer() : col_ctx_(nullptr), col_params_(nullptr) {} + +Status NcclReducer::InitializeCollectiveParams(CollectiveParams* col_params) { + if (col_params->instance.type != REDUCTION_COLLECTIVE || + col_params->instance.impl_details.collective_name != "NcclReduce") { + return errors::Internal("Unexpected collective type ", + col_params->instance.type, " expected ", + REDUCTION_COLLECTIVE, "; or collective name ", + col_params->instance.impl_details.collective_name, + " expected NcclReduce"); + } else { + return Status::OK(); + } +} + +Status NcclReducer::InitializeCollectiveContext(CollectiveContext* col_ctx) { + col_ctx_ = col_ctx; + col_params_ = &col_ctx->col_params; + return collective_util::InitializeDeviceAndLocality( + col_ctx->dev_mgr, col_ctx->device_name, &col_ctx->device, + &col_ctx->device_locality); +} + +Status NcclReducer::InitializeInstanceBeforeGroupDiscovery( + CollectiveParams* col_params) { + if (col_params->default_rank == 0 && col_params->group.num_tasks > 1) { + col_params->instance.communicator_key = + NcclManager::instance()->GenerateCommunicatorKey(); + } + return Status::OK(); +} + +Status ReductionOp(const string& merge_op, ncclRedOp_t* reduction_op) { + if (merge_op == "Add") { + *reduction_op = ncclSum; + return Status::OK(); + } else if (merge_op == "Mul") { + *reduction_op = ncclProd; + return Status::OK(); + } else { + return errors::Internal("Expected merge_op to be either Add or Mul, found ", + merge_op); + } +} + +void NcclReducer::Run(StatusCallback done) { + ncclRedOp_t reduction_op; + Status s = ReductionOp(col_params_->merge_op->type_string(), &reduction_op); + if (!s.ok()) { + done(s); + return; + } + + Tensor group_size; + Notification group_size_ready; + Status group_size_status; + if (col_params_->final_op) { + // Create an on-device scalar value from group_size_. + // TODO(ayushd, tucker): avoid this copy by either reusing across + // invocations or providing the scalar to the kernel in host memory. + Tensor group_size_val(col_ctx_->output->dtype(), TensorShape({})); + switch (col_ctx_->output->dtype()) { + case DT_FLOAT: + group_size_val.scalar()() = col_params_->group.group_size; + break; + case DT_DOUBLE: + group_size_val.scalar()() = col_params_->group.group_size; + break; + case DT_INT32: + group_size_val.scalar()() = col_params_->group.group_size; + break; + case DT_INT64: + group_size_val.scalar()() = col_params_->group.group_size; + break; + default: + done(errors::Internal("Unsupported type ", col_ctx_->output->dtype())); + return; + } + group_size = Tensor( + col_ctx_->device->GetAllocator(col_ctx_->op_ctx->input_alloc_attr(0)), + col_ctx_->output->dtype(), TensorShape({})); + DeviceContext* op_dev_ctx = col_ctx_->op_ctx->op_device_context(); + // Enqueue copy on gpu stream. + op_dev_ctx->CopyCPUTensorToDevice( + &group_size_val, col_ctx_->device, &group_size, + [&group_size_ready, &group_size_status](const Status& s) { + group_size_status = s; + group_size_ready.Notify(); + }); + } else { + group_size_ready.Notify(); + } + + Notification nccl_done; + Status nccl_status; + auto* compute_stream = col_ctx_->op_ctx->op_device_context()->stream(); + auto* gpu_info = col_ctx_->op_ctx->device()->tensorflow_gpu_device_info(); + // `AddToAllReduce` performs consistency checks for the NCCL call and enqueues + // the `Participant` struct locally. When all local participants with this + // `nccl_collective_key` have called `AddToAllReduce` and + // `SignalMultiNodeReady`, all devices at this worker are ready to process + // this NCCL op. + // + // The `NcclManager` uses a dedicated CUDA stream for NCCL kernels. At this + // point, it synchronizes the NCCL stream with the compute stream, and then + // enqueues the NCCL kernel on the NCCL stream. + const int num_global_devices = col_params_->group.group_size; + const int num_local_devices = col_params_->instance.num_devices_per_task.at( + col_params_->instance.task_names[col_params_->default_rank]); + const string nccl_collective_key = + NcclCollectiveKey(col_ctx_->exec_key, col_ctx_->step_id); + auto done_callback = [&nccl_done, &nccl_status](const Status& s) { + nccl_status = s; + nccl_done.Notify(); + }; + auto participant = absl::make_unique( + compute_stream->parent(), compute_stream, gpu_info->event_mgr, + gpu_info->gpu_id, col_ctx_->input, col_ctx_->output, + col_params_->default_rank, std::move(done_callback)); + VLOG(1) << "NcclReducer calling NcclManager::AddToAllReduce num_tasks " + << col_params_->group.num_tasks << " current task " + << col_params_->instance.task_names[col_params_->default_rank] + << " num local devices " << num_local_devices + << " num global devices " << num_global_devices; + NcclManager::instance()->AddToAllReduce( + std::move(participant), + {nccl_collective_key, num_local_devices, num_global_devices, + col_params_->instance.communicator_key}, + reduction_op); + + // NOTE(ayushd): We need to synchronize NCCL launches across nodes to prevent + // deadlocks. In the current implementation, we define a deterministic + // sequential launch order between potentially concurrent collective instances + // by introducing control information during static graph analysis in + // graph/collective_order.cc. This can be either in the form of explicit + // control edges or via `wait_for` attribute on the collective op. + // + // The other end of the design spectrum would have a distinguished node + // dynamically signal the next collective to launch to all other participants. + // This has higher degree of runtime coordination, but it may be able to + // achieve better performance if the (arbitrary) static execution order + // assigned in the first approach turns out to not be good from a scheduling + // perspective. e.g. consider a graph in which c1, c2, and c3 are three + // concurrent collective instances, and the static ordering assigns c1 -> c2 + // -> c3. In practice, it could turn out that c3 is always ready to execute + // before c1 or c2. + // + // `WaitForDependencies` may block if the collective instances on which this + // op depends have not yet launched. When this function returns, this op is + // ready to go. + col_ctx_->col_exec->WaitForDependencies(*col_params_); + NcclManager::instance()->SignalMultiNodeReady(nccl_collective_key); + // When all devices at this worker have called `SignalMultiNodeReady`, the + // `NcclManager` will enqueue the NCCL kernel on the NCCL stream. Thus the + // implementation of `Launched` keeps track of the number of devices that have + // launched. + col_ctx_->col_exec->Launched(*col_params_); + + // Wait for nccl op and group_size copy to succeed, then do final_op. + group_size_ready.WaitForNotification(); + nccl_done.WaitForNotification(); + Status final_status = + group_size_status.ok() ? nccl_status : group_size_status; + if (final_status.ok() && col_params_->final_op) { + final_status = collective_util::ComputeBinOp( + col_ctx_->op_ctx, col_ctx_->op_params, col_ctx_->device, + col_params_->final_op.get(), col_ctx_->output, &group_size); + } + done(final_status); +} + +REGISTER_COLLECTIVE(NcclReduce, NcclReducer); + +} // namespace tensorflow + +#endif // GOOGLE_CUDA diff --git a/pool/shard007/C++/0096141_test_nc_beta.cpp b/pool/shard007/C++/0096141_test_nc_beta.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9dbcc44c1ddb4a26241657fb9d81040ed54e9ae0 --- /dev/null +++ b/pool/shard007/C++/0096141_test_nc_beta.cpp @@ -0,0 +1,65 @@ +// Copyright John Maddock 2006-15. +// Copyright Paul A. Bristow 2007 +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#define BOOST_TEST_MAIN +#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error +#include "bindings.hpp" +#include "../../test/test_nc_beta.hpp" +#include + +BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_main, 10000); + +BOOST_AUTO_TEST_CASE(test_main) +{ + BOOST_MATH_CONTROL_FP; + + error_stream_replacer rep; + +#ifdef TYPE_TO_TEST + + test_accuracy(static_cast(0), NAME_OF_TYPE_TO_TEST); + +#else + bool test_float = false; + bool test_double = false; + bool test_long_double = false; + + if(std::numeric_limits::digits == std::numeric_limits::digits) + { + // + // Don't bother with long double, it's the same as double: + // + if(BOOST_MATH_PROMOTE_FLOAT_POLICY == false) + test_float = true; + test_double = true; + } + else + { + if(BOOST_MATH_PROMOTE_FLOAT_POLICY == false) + test_float = true; + if(BOOST_MATH_PROMOTE_DOUBLE_POLICY == false) + test_double = true; + test_long_double = true; + } + +#ifdef ALWAYS_TEST_DOUBLE + test_double = true; +#endif + + if(test_float) + test_accuracy(0.0f, "float"); + if(test_double) + test_accuracy(0.0, "double"); + if(test_long_double) + test_accuracy(0.0L, "long double"); +#ifdef BOOST_MATH_USE_FLOAT128 + //test_accuracy(0.0Q, "__float128"); +#endif + + +#endif +} + diff --git a/pool/shard007/C++/0096142_FSUnknownAction.cpp b/pool/shard007/C++/0096142_FSUnknownAction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4684764dd14429508104f72544183e2c51e8414 --- /dev/null +++ b/pool/shard007/C++/0096142_FSUnknownAction.cpp @@ -0,0 +1,137 @@ +/* + * FSUnknownAction.cpp + * Transform SWF + * + * Created by smackay on Tue Feb 18 2003. + * Copyright (c) 2001-2003 Flagstone Software Ltd. All rights reserved. + * + * This file contains Original Code and/or Modifications of Original Code as defined in + * and that are subject to the Flagstone Software Source License Version 1.0 (the + * 'License'). You may not use this file except in compliance with the License. Please + * obtain a copy of the License at http://www.flagstonesoftware.com/licenses/source.html + * and read it before using this file. + * + * The Original Code and all software distributed under the License are distributed on an + * 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND Flagstone + * HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY + * RIGHTS. Please see the License for the specific language governing rights and limitations + * under the License. + */ + +#include "FSUnknownAction.h" + +#include "FSInputStream.h" +#include "FSOutputStream.h" +#include "FSException.h" + +using namespace transform; + +namespace transform +{ + FSUnknownAction::FSUnknownAction(FSInputStream* aStream) : FSActionObject(0) , data(0) + { + decodeFromStream(aStream); + } + + FSUnknownAction::FSUnknownAction(int aType, byte* bytes, size_t numberOfBytes) : FSActionObject(aType), data(0) + { + setData(bytes, numberOfBytes); + } + + FSUnknownAction::FSUnknownAction(const FSUnknownAction& rhs) : FSActionObject(rhs) , data(0) + { + if (rhs.data) + { + data = new byte[length]; + + if (length > 0 && data == 0) + throw FSAllocationException("Cannot allocate memory to copy and FSUnknownAction."); + + memcpy(data, rhs.data, length*sizeof(byte)); + } + } + + FSUnknownAction::~FSUnknownAction() + { + delete [] data; + data = 0; + } + + FSUnknownAction* FSUnknownAction::clone() const + { + return new FSUnknownAction(*this); + } + + const char* FSUnknownAction::className() const + { + const static char _name[] = "FSUnknownAction"; + + return _name; + } + + FSUnknownAction& FSUnknownAction::operator= (const FSUnknownAction& rhs) + { + if (this != &rhs) + { + this->FSActionObject::operator=(rhs); + + data = new byte[length]; + + if (length > 0 && data == 0) + throw FSAllocationException("Cannot allocate memory to copy and FSUnknownAction."); + + memcpy(data, rhs.data, length*sizeof(byte)); + } + return *this; + } + + const byte* FSUnknownAction::getData() const + { + return data; + } + + void FSUnknownAction::setData(byte* bytes, size_t numberOfBytes) + { + delete [] data; + + length = numberOfBytes; + data = bytes; + } + + int FSUnknownAction::lengthInStream(FSOutputStream* aStream) + { + return length; + } + + void FSUnknownAction::encodeToStream(FSOutputStream* aStream) + { +#ifdef _DEBUG + aStream->startEncoding(className()); +#endif + FSActionObject::encodeToStream(aStream); + + aStream->write(data, length); + +#ifdef _DEBUG + aStream->endEncoding(className()); +#endif + } + + void FSUnknownAction::decodeFromStream(FSInputStream* aStream) + { +#ifdef _DEBUG + aStream->startDecoding(className()); +#endif + FSActionObject::decodeFromStream(aStream); + + if (length > 0) + data = aStream->read(length); + else + data = 0; + +#ifdef _DEBUG + aStream->endDecoding(className()); +#endif + } +} diff --git a/pool/shard007/C++/0096144_macro.cc b/pool/shard007/C++/0096144_macro.cc new file mode 100644 index 0000000000000000000000000000000000000000..7cb942940b4ed0e60f8d0795a524f511ea3dcee8 --- /dev/null +++ b/pool/shard007/C++/0096144_macro.cc @@ -0,0 +1,264 @@ +/* + * macro.cc + * Expanding macros + * AYM 1999-11-30 + */ + + +/* +This file is part of Yadex. + +Yadex incorporates code from DEU 5.21 that was put in the public domain in +1994 by Raphaël Quinet and Brendon Wyber. + +The rest of Yadex is Copyright © 1997-2003 André Majorel and others. + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307, USA. +*/ + + +#include "yadex.h" +#include "macro.h" + + +/* + * macro_expand, vmacro_expand - expand macro references in a string + * + * Copies the NUL-terminated string in into the + * buffer , replacing certain strings by other + * strings. must be at least ( + 1) characters + * long. + * + * The macro definitions are provided by the optional + * arguments that follow . You must pass two (const + * char *) for each macro. The first is the name of the + * macro, NUL-terminated. The second is the value of the + * macro, also NUL-terminated. The last macro value must be + * followed by a null pointer ((const char *) 0). + * + * Matching is case-sensitive. The first match is used. + * For example, + * + * macro_expand (buf, 99, "a%bcd", "%b", "1", "%bc", "2", (char *) 0); + * + * puts "a1cd" in buf. + * + * If the value of a macro to expand is a null pointer, the + * macro expands to an empty string. + * + * If expands to more than characters, only + * the first characters of the expansion are stored + * in . After the function returns, is + * guaranteed to be NUL-terminated. + * + * Return 0 if successful, non-zero if one of the macros + * could not be expanded (value was a null pointer). In + * that case, the actual number returned is the number of + * the first macro that could not be expanded, starting + * from 1. + */ +int macro_expand (char *buf, size_t size, const char *fmt, ...) +{ + va_list list; + va_start (list, fmt); + return vmacro_expand (buf, size, fmt, list); +} + + +int vmacro_expand (char *buf, size_t size, const char *fmt, va_list list) +{ + int rc = 0; + int macro_no = 0; + + *buf = '\0'; + // This is awful, but who cares ? + while (*fmt) + { + va_list l; + const char *macro_name = 0; + const char *macro_value = 0; + +#ifdef __va_copy + __va_copy(l, list); +#else + l = list; +#endif + + while (macro_name = va_arg (l, const char *)) + { + macro_value = va_arg (l, const char *); + size_t len1 = strlen (fmt); + size_t len2 = strlen (macro_name); + if (len1 >= len2 && ! memcmp (fmt, macro_name, len2)) + break; + } + if (macro_name != 0) + { + macro_no++; + if (macro_value == 0) + { + if (rc == 0) + rc = macro_no; + } + else + al_saps (buf, macro_value, size); + fmt += strlen (macro_name); + } + else + { + al_sapc (buf, *fmt, size); + fmt++; + } + } + return rc; +} + + +/* + * macro_expand - expand macro references in a string + * + * Copies the NUL-terminated string in into the + * buffer , replacing certain strings by other + * strings. must be at least ( + 1) characters + * long. + * + * The macro definitions are obtained by scanning the + * iterator range through . The + * only constraints on these iterators are that they must + * be input iterators and iterator->name and + * iterator->value must be defined and point to + * NUL-terminated strings. + * + * Matching is case-sensitive. If several names would + * match, the first one is used. For example, + * + * struct macdef + * { + * const char *name; + * const char *value; + * macdef (const char *name, const char *value) : + * name (name), value (value); + * }; + * std::list macdefs; + * macdefs.push_back (macdef ("%b", "1")); + * macdefs.push_back (macdef ("%bc", "2")); + * macro_expand (buf, 99, "a%bcd", macdefs.begin (), macdefs.end ()); + * + * puts "a1cd" in buf, not "a2d". + * + * If the value of a macro to expand is a null pointer, the + * macro expands to an empty string. + * + * If expands to more than characters, only + * the first characters of the expansion are stored + * in . After the function returns, is + * guaranteed to be NUL-terminated. + * + * Return 0 if successful, non-zero if one of the macros + * could not be expanded (value was a null pointer). In + * that case, the actual number returned is the number of + * the first macro that could not be expanded, starting + * from 1. + */ +template +int macro_expand (char *buf, size_t size, const char *fmt, + const_iterator macdef_begin, const_iterator macdef_end) +{ + int rc = 0; + int macro_no = 0; + + *buf = '\0'; + size_t fmt_len = strlen (fmt); + while (*fmt != '\0') + { + const char *macro_name = 0; + const char *macro_value = 0; + size_t macro_name_len = 0; + bool match = false; + for (const_iterator i = macdef_begin; i != macdef_end; ++i) + { + macro_name = i->name; + macro_value = i->value; + macro_name_len = strlen (macro_name); + if (macro_name_len <= fmt_len + && memcmp (fmt, macro_name, macro_name_len) == 0) + { + match = true; + break; + } + } + if (match) + { + macro_no++; + if (macro_value == 0) + { + if (rc == 0) + rc = macro_no; + } + else + al_saps (buf, macro_value, size); + fmt += macro_name_len; + fmt_len -= macro_name_len; + } + else + { + al_sapc (buf, *fmt, size); + fmt++; + fmt_len--; + } + } + return rc; +} + + +#ifdef TEST +/* + make CXXFLAGS='-DTEST -DY_UNIX -DY_X11' + LDFLAGS=../obj/0/atclib/al_saps.o\ ../obj/0/atclib/al_sapc.o + macro +*/ + +#include +#include + + +struct macdef +{ + const char *name; + const char *value; + macdef (const char *name, const char *value) : + name (name), value (value) { } +}; + + +void dump (const macdef& m) +{ + fprintf (stderr, "%s=%s\n", m.name, m.value); +} + + +int main () +{ + char buf[100]; + std::list macdefs; + macdefs.push_back (macdef ("%b", "1")); + macdefs.push_back (macdef ("%bc", "2")); + std::for_each (macdefs.begin (), macdefs.end (), dump); + macro_expand (buf, sizeof buf - 1, "a%bcd", macdefs.begin (), macdefs.end ()); + puts (buf); + return 0; +} + + +#endif diff --git a/pool/shard007/C++/0096145_listprincipalsresponse.cpp b/pool/shard007/C++/0096145_listprincipalsresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86fd47cc7c90cb74a6a2ac1a76b576ec60a9c37e --- /dev/null +++ b/pool/shard007/C++/0096145_listprincipalsresponse.cpp @@ -0,0 +1,109 @@ +/* + 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 "listprincipalsresponse.h" +#include "listprincipalsresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace RAM { + +/*! + * \class QtAws::RAM::ListPrincipalsResponse + * \brief The ListPrincipalsResponse class provides an interace for RAM ListPrincipals responses. + * + * \inmodule QtAwsRAM + * + * Use AWS Resource Access Manager to share AWS resources between AWS accounts. To share a resource, you create a resource + * share, associate the resource with the resource share, and specify the principals that can access the resources + * associated with the resource share. The following principals are supported: AWS accounts, organizational units (OU) from + * AWS Organizations, and organizations from AWS + * + * Organizations> + * + * For more information, see the AWS Resource Access Manager + * User + * + * \sa RamClient::listPrincipals + */ + +/*! + * Constructs a ListPrincipalsResponse object for \a reply to \a request, with parent \a parent. + */ +ListPrincipalsResponse::ListPrincipalsResponse( + const ListPrincipalsRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : RamResponse(new ListPrincipalsResponsePrivate(this), parent) +{ + setRequest(new ListPrincipalsRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const ListPrincipalsRequest * ListPrincipalsResponse::request() const +{ + Q_D(const ListPrincipalsResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful RAM ListPrincipals \a response. + */ +void ListPrincipalsResponse::parseSuccess(QIODevice &response) +{ + //Q_D(ListPrincipalsResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::RAM::ListPrincipalsResponsePrivate + * \brief The ListPrincipalsResponsePrivate class provides private implementation for ListPrincipalsResponse. + * \internal + * + * \inmodule QtAwsRAM + */ + +/*! + * Constructs a ListPrincipalsResponsePrivate object with public implementation \a q. + */ +ListPrincipalsResponsePrivate::ListPrincipalsResponsePrivate( + ListPrincipalsResponse * const q) : RamResponsePrivate(q) +{ + +} + +/*! + * Parses a RAM ListPrincipals response element from \a xml. + */ +void ListPrincipalsResponsePrivate::parseListPrincipalsResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("ListPrincipalsResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace RAM +} // namespace QtAws diff --git a/pool/shard007/C++/0096148_hourselector.cpp b/pool/shard007/C++/0096148_hourselector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06544c2ccf92ba15f780b58d1945dcffc5ba72bb --- /dev/null +++ b/pool/shard007/C++/0096148_hourselector.cpp @@ -0,0 +1,143 @@ +// hourselector.cpp +// +// Hour Selector widget for RDAirPlay +// +// (C) Copyright 2012,2016 Fred Gleason +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License version 2 as +// published by the Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +// + +#include +//Added by qt3to4: +#include + +#include + +HourSelector::HourSelector(QWidget *parent) + : QWidget(parent) +{ + // + // Fonts + // + QFont font("helvetica",16,QFont::Bold); + font.setPixelSize(16); + + // + // Palettes + // + hour_active_palette= + QPalette(QColor(BUTTON_STOPPED_BACKGROUND_COLOR),backgroundColor()); + + // + // Buttons + // + QSignalMapper *mapper=new QSignalMapper(this); + connect(mapper,SIGNAL(mapped(int)),this,SLOT(hourClicked(int))); + for(unsigned i=0;i<24;i++) { + hour_button[i]=new QPushButton(this); + hour_button[i]->setFont(font); + hour_button[i]->setDisabled(true); + mapper->setMapping(hour_button[i],i); + connect(hour_button[i],SIGNAL(clicked()),mapper,SLOT(map())); + } + + // + // Update Timer + // + hour_update_timer=new QTimer(this); + connect(hour_update_timer,SIGNAL(timeout()),this,SLOT(updateTimeData())); + updateTimeData(); +} + + +QSizePolicy HourSelector::sizePolicy() const +{ + return QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); +} + + +void HourSelector::setTimeMode(RDAirPlayConf::TimeMode mode) +{ + switch(mode) { + case RDAirPlayConf::TwelveHour: + hour_button[0]->setText(tr("12a")); + hour_button[1]->setText(tr("1a")); + hour_button[2]->setText(tr("2a")); + hour_button[3]->setText(tr("3a")); + hour_button[4]->setText(tr("4a")); + hour_button[5]->setText(tr("5a")); + hour_button[6]->setText(tr("6a")); + hour_button[7]->setText(tr("7a")); + hour_button[8]->setText(tr("8a")); + hour_button[9]->setText(tr("9a")); + hour_button[10]->setText(tr("10a")); + hour_button[11]->setText(tr("11a")); + hour_button[12]->setText(tr("12p")); + hour_button[13]->setText(tr("1p")); + hour_button[14]->setText(tr("2p")); + hour_button[15]->setText(tr("3p")); + hour_button[16]->setText(tr("4p")); + hour_button[17]->setText(tr("5p")); + hour_button[18]->setText(tr("6p")); + hour_button[19]->setText(tr("7p")); + hour_button[20]->setText(tr("8p")); + hour_button[21]->setText(tr("9p")); + hour_button[22]->setText(tr("10p")); + hour_button[23]->setText(tr("11p")); + break; + + case RDAirPlayConf::TwentyFourHour: + for(unsigned i=0;i<24;i++) { + hour_button[i]->setText(QString().sprintf("%02u",i)); + } + break; + } +} + + +void HourSelector::updateHours(bool states[24]) +{ + for(unsigned i=0;i<24;i++) { + hour_button[i]->setEnabled(states[i]); + } +} + + +void HourSelector::resizeEvent(QResizeEvent *e) +{ + for(unsigned i=0;i<2;i++) { + for(unsigned j=0;j<12;j++) { + unsigned hour=12*i+j; + hour_button[hour]->setGeometry(j*size().width()/12,i*size().height()/2, + size().width()/12,size().height()/2); + } + } +} + + +void HourSelector::hourClicked(int hour) +{ + emit hourSelected(hour); +} + + +void HourSelector::updateTimeData() +{ + QTime now=QTime::currentTime(); + for(unsigned i=0;i<24;i++) { + hour_button[i]->setPalette(palette()); + } + hour_button[now.hour()]->setPalette(hour_active_palette); + hour_update_timer->start(now.msecsTo(QTime(now.hour()+1,0,1)),true); +} diff --git a/pool/shard007/C++/0096151_volt_distr_viz.cpp b/pool/shard007/C++/0096151_volt_distr_viz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d9d8e2458b20a3b5bb2385a6ca65b4b38c15608 --- /dev/null +++ b/pool/shard007/C++/0096151_volt_distr_viz.cpp @@ -0,0 +1,135 @@ +/* + * volt_distr_viz.cpp + * Copyright 2013 University of Massachusetts Lowell + * Author: Jonathan Hasenzahl + */ + +#include "volt_distr/volt_distr_viz.h" + +#define ROWS 8 +#define COLS ROWS +#define C_WIDTH 75 // Width of each channel (px) +#define C_HEIGHT C_WIDTH // Height of each channel (px) +#define P_WIDTH (C_WIDTH * COLS) // Width of plotter window (px) +#define P_HEIGHT (C_HEIGHT * ROWS) // Height of plotter window (px) +#define X_START 0 +#define Y_START X_START +#define X_STEP C_WIDTH +#define Y_STEP X_STEP +#define MAX_COLOR 65535 + +VoltDistrViz::~VoltDistrViz() +{ + delete plotter_; +} + +/*! + * \brief Initializes the visualizer + */ +void VoltDistrViz::init(const std::string& file_name) +{ + is_ok_ = true; + file_.open(file_name.c_str()); + + if (!file_.is_open()) + { + ROS_ERROR("Cannot open %s. Imaging will be disabled.", + file_name.c_str()); + is_ok_ = false; + return; + } + + // Set plotter parameters + PlotterParams params; + //ostringstream bitmapsize; + //bitmapsize << P_WIDTH << 'x' << P_HEIGHT; + //params.setplparam("BITMAPSIZE", (void*) bitmapsize.str().c_str()); + params.setplparam("BG_COLOR", (char*) "none"); + + plotter_ = new SVGPlotter(cin, file_, cerr, params); + + if (plotter_->openpl() < 0) + { + ROS_ERROR("Cannot initialize plotter. Imaging will be disabled."); + is_ok_ = false; + return; + } + + // Drawing boundaries: lower left X/Y, upper right X/Y (px) + plotter_->space(0, 0, P_WIDTH, P_HEIGHT); + plotter_->pencolorname("white"); + plotter_->filltype(1); + plotter_->erase(); + + // Calculate coordinates of the channels + for (int y = ROWS - 1; y >= 0; y--) + { + for (int x = 0; x < COLS; x++) + { + if (!((x == 0 && y == 0) || (x == 0 && y == ROWS - 1) || + (x == COLS - 1 && y == 0) || + (x == COLS - 1 && y == ROWS - 1))) + { + boost::array coords; + coords[0] = x * X_STEP + X_START; // x1 + coords[1] = y * Y_STEP + Y_START; // y1 + coords[2] = (x + 1) * X_STEP + X_START; // x2 + coords[3] = (y + 1) * Y_STEP + Y_START; // y2 + coords_.push_back(coords); + } + } + } +} + +/*! + * \brief Plots the voltage distribution of each channel + * \param percents an array of doubles, each representing what percentage of + * total voltages were negative for that channel + */ +void VoltDistrViz::draw(const boost::array& percents) +{ + if (!is_ok_) + return; + + for (int i = 0; i < 60; i++) + { + // Draw the colored box + if (percents[i] > 0.5) + { + // Channel has more than 50% negative voltages + int red = MAX_COLOR * 2 * (percents[i] - .5); + plotter_->fillcolor(red, 0, 0); + } + else + { + // Channel has not more than 50% negative voltages + int blue = MAX_COLOR * 2 * (.5 - percents[i]); + plotter_->fillcolor(0, 0, blue); + } + plotter_->box(coords_[i][0], coords_[i][1], coords_[i][2], coords_[i][3]); + plotter_->endpath(); + + // Draw the label over the center/center of the box + plotter_->move((coords_[i][0] + coords_[i][2]) / 2, + (coords_[i][1] + coords_[i][3]) / 2); + ostringstream volt; + volt << fixed << setprecision(2) << (percents[i] * 100) << '%'; + plotter_->alabel('c', 'c', volt.str().c_str()); + plotter_->endpath(); + } + + plotter_->closepl(); + file_.close(); +} + +/* + * Reference + * + * move(x,y) <-- cursor + * box(x1,y1,x2,y2) or circle(xc,yc,r) + * pencolor(r,g,b) + * fillcolor(r,g,b) + * color(r,g,b) = pen + fill + * endpath() + * alabel (int horiz_justify, int vert_justify, const char *s); + */ diff --git a/pool/shard007/C++/0096156_test-dd.cc b/pool/shard007/C++/0096156_test-dd.cc new file mode 100644 index 0000000000000000000000000000000000000000..675e8564249fe7fb4997ec8b555b4aedd4ba6600 --- /dev/null +++ b/pool/shard007/C++/0096156_test-dd.cc @@ -0,0 +1,67 @@ +#include + +typedef kv::dd dd; + +int main() +{ + std::cout.precision(32); + dd x, y, z; + + x = 1.; + y = 3.; + z = "0.1"; + std::cout << z << "\n"; + std::cout << z * "11.8" << "\n"; + std::cout << x + y << "\n"; + std::cout << x - y << "\n"; + std::cout << x * y << "\n"; + std::cout << x / y << "\n"; + std::cout << sqrt(z) << "\n"; + std::cout << abs(z) << "\n"; + std::cout << pow(x, y) << "\n"; + std::cout << pow(2, y) << "\n"; + std::cout << pow(x, 2) << "\n"; + std::cout << pow(x, 2.) << "\n"; + std::cout << exp(x) << "\n"; + std::cout << log(x) << "\n"; + std::cout << sin(x) << "\n"; + std::cout << cos(x) << "\n"; + std::cout << tan(x) << "\n"; + std::cout << asin(x) << "\n"; + std::cout << acos(x) << "\n"; + std::cout << atan(x) << "\n"; + std::cout << atan2(x, y) << "\n"; + std::cout << sinh(x) << "\n"; + std::cout << cosh(x) << "\n"; + std::cout << tanh(x) << "\n"; + std::cout << asinh(x) << "\n"; + std::cout << acosh(y) << "\n"; + std::cout << atanh(x/y) << "\n"; + std::cout << floor(z + 3) << "\n"; + std::cout << ceil(z + 3) << "\n"; + int i; + std::cout << frexp(z / 7., &i) << "\n"; + std::cout << i << "\n"; + std::cout << ldexp(z, 5) << "\n"; + std::cout << std::boolalpha; + std::cout << (z < 0.2) << "\n"; + std::cout << (z < "0.100001") << "\n"; + + std::cout << kv::constants

::pi() << "\n"; + std::cout << kv::constants
::e() << "\n"; + std::cout << kv::constants
::ln2() << "\n"; + std::cout << kv::constants
::str("0.1") << "\n"; + + std::cout << std::numeric_limits
::epsilon() << "\n"; + std::cout << std::numeric_limits
::infinity() << "\n"; + std::cout << std::numeric_limits
::max() << "\n"; + std::cout << std::numeric_limits
::min() << "\n"; + + std::cout << std::numeric_limits
::digits << "\n"; + std::cout << std::numeric_limits
::digits10 << "\n"; + std::cout << std::numeric_limits
::radix << "\n"; + std::cout << std::numeric_limits
::min_exponent << "\n"; + std::cout << std::numeric_limits
::min_exponent10 << "\n"; + std::cout << std::numeric_limits
::max_exponent << "\n"; + std::cout << std::numeric_limits
::max_exponent10 << "\n"; +} diff --git a/pool/shard007/C++/0096157_JamFunctions.cpp b/pool/shard007/C++/0096157_JamFunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2c09e5282a8887532a49bf587e3159d329e9948 --- /dev/null +++ b/pool/shard007/C++/0096157_JamFunctions.cpp @@ -0,0 +1,49 @@ +#include "JamFunctions.h" + +bool GroupVtable::IsJam(__int16 opcode) +{ + pIsJam _isJam = pIsJam(isJam); + + return _isJam(opcode); +} + +bool __thiscall GroupVtable::IsInstanceServer(uint32 opcode) +{ + if (!isInstanceServer) + return false; + pIsInstanceServer _isInstance = pIsInstanceServer(isInstanceServer); + + return _isInstance(opcode); +} + +char GroupVtable::Call(FakeStore* a1, int a2, int a3, int a4, unsigned int a5, FakeStore* a6) +{ + pCall call = (pCall)Exec; + char result = call((int)a1, a2, a3, a4, a5, (int)a6); + + return result; +} + +int* GroupVtable::GetRealCallFunction() +{ + uint8 pattern[] = { 0xE8, 0x00, 0x00, 0x00, 0x00, 0x5D }; + int* ptr = (int*)((int)FindPattern((uint8*)Exec, 0x20, pattern, sizeof(pattern), "paaaap") + 1); + + return (int*)((int)ptr + *ptr + 4); +} + +int GroupVtable::GetRealCallFunctionLen() +{ + uint8* func = (uint8*)GetRealCallFunction(); + + uint8 pattern[4] = { 0xC9, 0xC2, 0x10, 0x00 }; + int addr = (int)FindPattern(func, 30000, pattern, sizeof(pattern), "pppp"); + + if (!addr) + { + pattern[0] = 0x5B; + addr = (int)FindPattern(func, 30000, pattern, sizeof(pattern), "pppp"); + } + + return (addr + sizeof(pattern) - (int)func); +} \ No newline at end of file diff --git a/pool/shard007/C++/0096165_misc.cpp b/pool/shard007/C++/0096165_misc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b03ae41db5e4b5f4a71d168e7c6c32e6514987b --- /dev/null +++ b/pool/shard007/C++/0096165_misc.cpp @@ -0,0 +1,255 @@ +/**************************************************************************** +* Hyper's CD Catalog +* A multiplatform qt and xml based catalog program +* +* Author : Peter Deak (hyperr@freemail.hu) +* License : GPL +* Copyright : (C) 2003 Peter Deak +****************************************************************************/ + +#include "misc.h" + +#include "config.h" +#include "cdcat.h" + +#include +#include +#include + +#ifdef _WIN32 + #include +#endif + +#include +#include +#include +#include +#include + +#ifndef _WIN32 +// Linux: + +FILE *openDevice( const char *CDpath ) { + QString devicename = ""; + FILE *result; + QString cfgcdpath = QString( CDpath ).replace( QRegExp( "/$" ), "" ); + bool device_found = false; + + QFile f( "/etc/fstab" ); + QString line; + + if (f.open( QIODevice::ReadOnly )) { // file opened successfully + QTextStream t( &f ); // use a text stream + while (!t.atEnd()) { + line = t.readLine(); // line of text excluding '\n' + + if (!line.startsWith( "#" ) && !line.isEmpty()) { + if (((line.section( "\t", 1, 1, QString::SectionSkipEmpty )).replace( QRegExp( "/$" ), "" )).compare( cfgcdpath ) == 0) { + devicename = line.section( "\t", 0, 0 ); + device_found = true; + } + if (((line.section( " ", 1, 1, QString::SectionSkipEmpty )).replace( QRegExp( "/$" ), "" )).compare( cfgcdpath ) == 0) { + devicename = line.section( " ", 0, 0 ); + device_found = true; + } + } + } + f.close(); + } + + if (!device_found) { + // its the pure device name (e.g. /dev/sr0) + devicename = QString( CDpath ); + } + + fprintf( stderr, "openDevice(): devicename: |%s|\n", devicename.toLocal8Bit().constData()); + result = fopen( devicename.toLocal8Bit().constData(), "r" ); + return result; +} + +bool diskIsDVD( const char *CDpath ) { + int size = 0; + FILE *deviceptr = NULL; + char *field = NULL; + + deviceptr = openDevice( CDpath ); + if (!deviceptr) { + return false; + } + fseek( deviceptr, 32848, SEEK_SET ); + field = new char(9); + fread( field, sizeof(char), 8, deviceptr ); + fclose( deviceptr ); + + size = ((field[0] & 0xff) | ((field[1] & 0xff) << 8) + | ((field[2] & 0xff) << 16) | ((field[3] & 0xff) << 24)); + delete field; + + // fprintf(stderr,"Size: %i\n",size); + // return DVD if there is more data than a CD can ever have + return size > 450000; +} + +QString getCDName( const char *CDpath ) { + char *name = new char[64]; // return value + FILE *deviceptr = NULL; + + DEBUG_INFO_ENABLED = init_debug_info(); + + + strcpy( name, "" ); + if (strlen( CDpath ) != 0) { + /** Read the volume name of the device *******************/ + + deviceptr = openDevice( CDpath ); + if (*DEBUG_INFO_ENABLED) { + qWarning() << "getCDName(): could not open device"; + } + if (!deviceptr) { + return name; + } + fseek( deviceptr, 32808, SEEK_SET ); + fread( name, sizeof(char), 32, deviceptr ); + fclose( deviceptr ); + + if (*DEBUG_INFO_ENABLED) { + qDebug() << "getCDName():" << name; + } + name[32] = '\0'; + + // strip whitespaces + strcpy( name, (const char *)QString( name ).trimmed().toLocal8Bit().constData()); + } + return QString( name ); +} +QString getCDSerial( const char *CDpath ) { + // FIXME + + + + return ""; +} +#endif + +#ifdef _WIN32 +// Win32: +void TCharToChar( const wchar_t *Src, char *Dest, int Size ) { + WideCharToMultiByte( CP_ACP, 0, Src, wcslen( Src ) + 1, Dest, Size, NULL, NULL ); +} + +QString getCDName( const char *CDpath ) { + /* wide char */ + /* + * // this does not work correctly! + * char *name = new char[64]; + * + * DWORD dwDummy; + * DWORD dwFlags; + * LPWSTR WSTR_CDpath = NULL; + * + * int length = MultiByteToWideChar(CP_ACP,0,CDpath ,strlen(CDpath)+1,NULL,0); + * MultiByteToWideChar(CP_ACP,0,CDpath ,strlen(CDpath)+1,WSTR_CDpath,length); + * LPWSTR LPW_name=L""; + * DWORD dwVolumeSerialNumber; + * if ( !GetVolumeInformationW(WSTR_CDpath, LPW_name, 64, NULL, NULL, NULL, NULL, 0) ) + * //if ( !GetVolumeInformation ( WSTR_CDpath, LPW_name, 0, 0, 0, 0, 0, 0 )) + * { + * return QString(""); + * } + * + * WideCharToMultiByte(CP_ACP, 0, (LPWSTR)LPW_name, 64,name, 64, NULL, NULL); + * QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + * return QString(name); + */ + /*end wide char */ + + /* test2 */ + /* + * char *name = new char[64]; + * DWORD dwDummy; + * DWORD dwFlags; + * + * if(!GetVolumeInformationW((LPCSTR)CDpath,(LPSTR)name,64,NULL,&dwDummy,&dwFlags,NULL,0)) + * strcpy(name,""); + * QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + * return QString(name); + */ + /* end test2 */ + + + /* ANSI */ + // works with german special chars too :) + char bufName1[64]; + DWORD dwSerial; + char *name; + + if (!GetVolumeInformationA( CDpath, bufName1, 64, &dwSerial, NULL, NULL, NULL, 0 )) { + return QString( "" ); + } + name = QString( bufName1 ).toLocal8Bit().data(); + // QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + return QString( bufName1 ); + /* end ANSI */ +} + +QString getCDSerial( const char *CDpath ) { + /* wide char */ + /* + * // this does not work correctly! + * char *name = new char[64]; + * + * DWORD dwDummy; + * DWORD dwFlags; + * LPWSTR WSTR_CDpath = NULL; + * + * int length = MultiByteToWideChar(CP_ACP,0,CDpath ,strlen(CDpath)+1,NULL,0); + * MultiByteToWideChar(CP_ACP,0,CDpath ,strlen(CDpath)+1,WSTR_CDpath,length); + * LPWSTR LPW_name=L""; + * DWORD dwVolumeSerialNumber; + * if ( !GetVolumeInformationW(WSTR_CDpath, LPW_name, 64, NULL, NULL, NULL, NULL, 0) ) + * //if ( !GetVolumeInformation ( WSTR_CDpath, LPW_name, 0, 0, 0, 0, 0, 0 )) + * { + * return QString(""); + * } + * + * WideCharToMultiByte(CP_ACP, 0, (LPWSTR)LPW_name, 64,name, 64, NULL, NULL); + * QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + * return QString(name); + */ + /*end wide char */ + + /* test2 */ + /* + * char *name = new char[64]; + * DWORD dwDummy; + * DWORD dwFlags; + * + * if(!GetVolumeInformationW((LPCSTR)CDpath,(LPSTR)name,64,NULL,&dwDummy,&dwFlags,NULL,0)) + * strcpy(name,""); + * QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + * return QString(name); + */ + /* end test2 */ + + + /* ANSI */ + // works with german special chars too :) + char bufName1[64]; + DWORD dwSerial; + char *name; + + if (!GetVolumeInformationA( CDpath, bufName1, 64, &dwSerial, NULL, NULL, NULL, 0 )) { + return QString( "" ); + } +// char *myChar = "Hello World"; + // DWORD dw = reinterpret_cast ( myChar ); + // bufName1 = reinterpret_cast ( dw ); +// bufName1 = strncpy(&bufName1, myChar, 63); + // name = QString ( bufName1 ).toLocal8Bit().data(); + // QMessageBox::information(0, "vol1", "path: "+QString(CDpath)+"\nname: \""+QString(name)+"\""); + return QString( bufName1 ); + /* end ANSI */ +} + +#endif + diff --git a/pool/shard007/C++/0096168_EEPROM_Project.cpp b/pool/shard007/C++/0096168_EEPROM_Project.cpp new file mode 100644 index 0000000000000000000000000000000000000000..594d971e2052073a4968248e7998a2d9559e3f30 --- /dev/null +++ b/pool/shard007/C++/0096168_EEPROM_Project.cpp @@ -0,0 +1,27 @@ +// Project-specific code for Serial EEPROM +// Copyright (c) 2014 Chris Merck + +#include "ch.h" +#include "hal.h" +#include"EEPROM.h" +#define SYS_CURRENT_SUBSYS SYS_SUBSYS_EEPROM +#include"Sys.h" +#include"I2C.h" + +EEPROM_24XX512 * g_pEEPROM = NULL; + +void CreateEEPROM() +{ + // allocate memory for each device + g_pEEPROM = new EEPROM_24XX512(0b000); + + // initialize each device + g_pEEPROM->Init(); +} + +int32_t EEPROM_24XX512::ProjI2CTransfer(uint8_t addr, + const uint8_t* txbuf, int txbytes, uint8_t* rxbuf, int rxbytes) +{ + return I2C_Transfer(&I2CD1, addr, txbuf, txbytes, rxbuf, rxbytes); +} + diff --git a/pool/shard007/C++/0096174_ProjectileObject.cpp b/pool/shard007/C++/0096174_ProjectileObject.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27f439bcc77fd909fba8ec017f37ae4e05d38a80 --- /dev/null +++ b/pool/shard007/C++/0096174_ProjectileObject.cpp @@ -0,0 +1,186 @@ +#include "objects/ProjectileObject.hpp" + +#ifdef _MSC_VER +#pragma warning(disable : 4305) +#endif +#include +#include +#ifdef _MSC_VER +#pragma warning(default : 4305) +#endif + +#include + +#include "data/WeaponData.hpp" +#include "engine/GameData.hpp" +#include "engine/GameWorld.hpp" + +void ProjectileObject::checkPhysicsContact() { + btManifoldArray manifoldArray; + btBroadphasePairArray& pairArray = + _ghostBody->getOverlappingPairCache()->getOverlappingPairArray(); + int numPairs = pairArray.size(); + + for (int i = 0; i < numPairs; i++) { + manifoldArray.clear(); + + const btBroadphasePair& pair = pairArray[i]; + + // unless we manually perform collision detection on this pair, the + // contacts are in the dynamics world paircache: + btBroadphasePair* collisionPair = + engine->dynamicsWorld->getPairCache()->findPair(pair.m_pProxy0, + pair.m_pProxy1); + if (!collisionPair) { + continue; + } + + if (collisionPair->m_algorithm) { + collisionPair->m_algorithm->getAllContactManifolds(manifoldArray); + } + + for (int j = 0; j < manifoldArray.size(); j++) { + // btPersistentManifold* manifold = manifoldArray[j]; + // const btCollisionObject* B = manifold->getBody0() == _ghostBody ? + // manifold->getBody1() : manifold->getBody0(); + // GameObject* go = static_cast(B->getUserPointer()); + + /// @todo check if this is a suitable level to check c.f + /// btManifoldPoint + // It's happening + explode(); + + return; + } + } +} + +void ProjectileObject::explode() { + if (!_exploded) { + // Remove our physics objects + cleanup(); + + const float exp_size = 10.f; + const float damageSize = 5.f; + const float damage = static_cast(_info.weapon->damage); + + for (auto& o : engine->allObjects) { + if (o == this) continue; + switch (o->type()) { + case GameObject::Instance: + case GameObject::Vehicle: + case GameObject::Character: + break; + default: + continue; + } + + float d = glm::distance(getPosition(), o->getPosition()); + if (d > damageSize) continue; + + o->takeDamage({DamageInfo::DamageType::Explosion, + getPosition(), getPosition(), + damage / glm::max(d, 1.f), + 0.f}); + } + + auto& explosion = engine->createParticleEffect(); + + auto texPtr = engine->data->findSlotTexture("particle", "explo02"); + explosion.texture = texPtr; + explosion.size = glm::vec2(exp_size); + explosion.starttime = engine->getGameTime(); + explosion.lifetime = 0.5f; + explosion.orientation = ParticleFX::Camera; + explosion.colour = glm::vec4(1.0f); + explosion.position = getPosition(); + explosion.direction = glm::vec3(0.f, 0.f, 1.f); + + _exploded = true; + engine->destroyObjectQueued(this); + } +} + +void ProjectileObject::cleanup() { + if (_body) { + engine->dynamicsWorld->removeRigidBody(_body.get()); + _body = nullptr; + } + if (_ghostBody) { + engine->dynamicsWorld->removeCollisionObject(_ghostBody.get()); + _ghostBody = nullptr; + } + if(_shape) { + _shape = nullptr; + } +} + +ProjectileObject::ProjectileObject(GameWorld* world, const glm::vec3& position, + const ProjectileObject::ProjectileInfo& info) + : GameObject(world, position, glm::quat{1.0f, 0.0f, 0.0f, 0.0f}, nullptr) + , _info(info) + , _motionState(this) { + _shape = std::make_unique(0.45f); + btVector3 inertia(0.f, 0.f, 0.f); + _shape->calculateLocalInertia(1.f, inertia); + btRigidBody::btRigidBodyConstructionInfo riginfo(1.f, nullptr, _shape.get(), + inertia); + + btTransform ws; + ws.setIdentity(); + ws.setOrigin(btVector3(position.x, position.y, position.z)); + riginfo.m_startWorldTransform = ws; + riginfo.m_mass = 1.f; + riginfo.m_motionState = &_motionState; + + _body = std::make_unique(riginfo); + _body->setUserPointer(this); + _body->setLinearVelocity( + btVector3(_info.direction.x, _info.direction.y, _info.direction.z) * + _info.velocity); + engine->dynamicsWorld->addRigidBody( + _body.get(), btBroadphaseProxy::DefaultFilter, + btBroadphaseProxy::StaticFilter | btBroadphaseProxy::DefaultFilter); + + if (_info.type == RPG) { + // RPGs aren't affected by gravity + _body->setGravity({0.f, 0.f, 0.f}); + } + + if (_info.type != Grenade) { + // Projectiles that aren't grenades explode on contact. + _ghostBody = std::make_unique(); + _ghostBody->setWorldTransform(_body->getWorldTransform()); + _ghostBody->setCollisionShape(_shape.get()); + _ghostBody->setUserPointer(this); + _ghostBody->setCollisionFlags( + btCollisionObject::CF_KINEMATIC_OBJECT | + btCollisionObject::CF_NO_CONTACT_RESPONSE); + engine->dynamicsWorld->addCollisionObject( + _ghostBody.get(), btBroadphaseProxy::SensorTrigger, + btBroadphaseProxy::AllFilter); + } + + const auto& modelData = world->data->findModelInfo( + getProjectileInfo().weapon->modelID); + setModel(modelData->getAtomic(0)->clone(std::make_shared())); +} + +ProjectileObject::~ProjectileObject() { + cleanup(); +} + +void ProjectileObject::tick(float dt) { + if (_body == nullptr) return; + + _info.time -= dt; + + if (_ghostBody) { + _ghostBody->setWorldTransform(_body->getWorldTransform()); + checkPhysicsContact(); + } + + if (_info.time <= 0.f) { + explode(); + } +} diff --git a/pool/shard007/C++/0096175_registerdockwidget.cpp b/pool/shard007/C++/0096175_registerdockwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..180b90a9095e457f2ca29127970982c2ee67ed4b --- /dev/null +++ b/pool/shard007/C++/0096175_registerdockwidget.cpp @@ -0,0 +1,70 @@ +/* + * LegacySPC - A portable object-oriented SPC emulator. + * Copyright 2007-2008 by Michaël Larouche + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Library General Public License as + * published by the Free Software Foundation; version 2 of the + * 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. + */ +#include "registerdockwidget.h" + +// Qt includes +#include +#include + +// LegacySPC includes +#include +#include + +// Local includes +#include "ui_registerdockwidget.h" + +class RegisterDockWidget::Private +{ +public: + Ui::RegisterDockWidget ui; +}; + +RegisterDockWidget::RegisterDockWidget(QWidget *parent) + : QDockWidget(tr("Register Window"), parent), d(new Private) +{ + QWidget *theWidget = new QWidget(this); + d->ui.setupUi(theWidget); + setWidget(theWidget); +} + +RegisterDockWidget::~RegisterDockWidget() +{ + delete d; +} + +void RegisterDockWidget::processorUpdated(LegacySPC::Processor *processor) +{ + // Update each register value + d->ui.lineA->setText( QString::number(processor->registers()->A(), 16) ); + d->ui.lineX->setText( QString::number(processor->registers()->X(), 16) ); + d->ui.lineY->setText( QString::number(processor->registers()->Y(), 16) ); + d->ui.lineYA->setText( QString::number((quint16)processor->registers()->YA(), 16) ); + d->ui.linePC->setText( QString::number((quint16)processor->registers()->programCounter(), 16) ); + d->ui.lineSP->setText( QString::number(processor->registers()->stackPointer(), 16) ); + + // Update each processor status flag + int processorStatus = static_cast( processor->registers()->programStatus() ); + + d->ui.checkCarry->setChecked( processorStatus & LegacySPC::CarryFlag ); + d->ui.checkZero->setChecked( processorStatus & LegacySPC::ZeroFlag ); + d->ui.checkOverflow->setChecked( processorStatus & LegacySPC::OverflowFlag ); + d->ui.checkNegative->setChecked( processorStatus & LegacySPC::NegativeFlag ); + d->ui.checkDirectPage->setChecked( processorStatus & LegacySPC::DirectPageFlag ); + d->ui.checkInterrupt->setChecked( processorStatus & LegacySPC::InterruptFlag ); + d->ui.checkHalfCarry->setChecked( processorStatus & LegacySPC::HalfCarryFlag ); + d->ui.checkBreak->setChecked( processorStatus & LegacySPC::BreakFlag ); +} + +#include "registerdockwidget.moc" diff --git a/pool/shard007/C++/0096178_RenX_Listen.cpp b/pool/shard007/C++/0096178_RenX_Listen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d153430a2a1f4d315d2c09b31d84e659fa7c6a6a --- /dev/null +++ b/pool/shard007/C++/0096178_RenX_Listen.cpp @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2015-2021 Jessica James. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Written by Jessica James + */ + +#include "Jupiter/IRC_Client.h" +#include "RenX_Listen.h" +#include "RenX_Core.h" +#include "RenX_Server.h" + +using namespace std::literals; + +RenX_ListenPlugin::~RenX_ListenPlugin() { + RenX_ListenPlugin::socket.close(); +} + +bool RenX_ListenPlugin::initialize() { + uint16_t port = this->config.get("Port"sv, 21337); + std::string_view address = this->config.get("Address"sv, "0.0.0.0"sv); + RenX_ListenPlugin::serverSection = this->config.get("ServerSection"sv, this->getName()); + + return RenX_ListenPlugin::socket.bind(static_cast(address).c_str(), port, true) && RenX_ListenPlugin::socket.setBlocking(false); +} + +int RenX_ListenPlugin::think() { + Jupiter::Socket *sock = socket.accept(); + if (sock != nullptr) { + sock->setBlocking(false); + std::unique_ptr server = std::make_unique(std::move(*sock), RenX_ListenPlugin::serverSection); + printf("Incoming server connected from %s:%u" ENDL, server->getSocketHostname().c_str(), server->getSocketPort()); + server->sendLogChan("Incoming server connected from " IRCCOLOR "12%s:%u", server->getSocketHostname().c_str(), server->getSocketPort()); + RenX::getCore()->addServer(std::move(server)); + delete sock; + } + return 0; +} + +int RenX_ListenPlugin::OnRehash() { + RenX::Plugin::OnRehash(); + + uint16_t port = this->config.get("Port"sv, 21337); + std::string_view address = this->config.get("Address"sv, "0.0.0.0"sv); + RenX_ListenPlugin::serverSection = this->config.get("ServerSection"sv, this->getName()); + + if (port != RenX_ListenPlugin::socket.getBoundPort() || address != RenX_ListenPlugin::socket.getBoundHostname()) { + puts("Notice: The Renegade-X listening socket has been changed!"); + RenX_ListenPlugin::socket.close(); + return RenX_ListenPlugin::socket.bind(static_cast(address).c_str(), port, true) == false || RenX_ListenPlugin::socket.setBlocking(false) == false; + } + return 0; +} + +// Plugin instantiation and entry point. +RenX_ListenPlugin pluginInstance; + +extern "C" JUPITER_EXPORT Jupiter::Plugin *getPlugin() +{ + return &pluginInstance; +} diff --git a/pool/shard007/C++/0096180_CslDlgConnectPass.cpp b/pool/shard007/C++/0096180_CslDlgConnectPass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c42034d82c0d5ada6718248c71c877395f86f06 --- /dev/null +++ b/pool/shard007/C++/0096180_CslDlgConnectPass.cpp @@ -0,0 +1,128 @@ +/*************************************************************************** + * Copyright (C) 2007-2009 by Glen Masgai * + * mimosius@users.sourceforge.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., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "Csl.h" +#include "CslDlgConnectPass.h" + +BEGIN_EVENT_TABLE(CslDlgConnectPass,wxDialog) + EVT_BUTTON(wxID_ANY,CslDlgConnectPass::OnCommandEvent) + EVT_TEXT(wxID_ANY,CslDlgConnectPass::OnCommandEvent) + EVT_CHECKBOX(wxID_ANY,CslDlgConnectPass::OnCommandEvent) +END_EVENT_TABLE() + +enum { TEXT_PASSWORD = wxID_HIGHEST + 1, CHECK_ADMIN }; + + +CslDlgConnectPass::CslDlgConnectPass(wxWindow* parent,CslConnectPassInfo *info,int id, + const wxString& title,const wxPoint& pos, + const wxSize& size,long style): + wxDialog(parent,id,title,pos,size,wxDEFAULT_DIALOG_STYLE), m_info(info) +{ + // begin wxGlade: CslDlgConnectPass::CslDlgConnectPass + sizer_ctrl_staticbox = new wxStaticBox(this, -1, wxEmptyString); + text_ctrl_password = new wxTextCtrl(this, TEXT_PASSWORD, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD); + checkbox_admin = new wxCheckBox(this, CHECK_ADMIN, _("Ad&min connect")); + button_ok = new wxButton(this, wxID_OK, _("&Ok")); + button_cancel = new wxButton(this, wxID_CANCEL, _("&Cancel")); + + set_properties(); + do_layout(); + // end wxGlade +} + +void CslDlgConnectPass::set_properties() +{ + // begin wxGlade: CslDlgConnectPass::set_properties + SetTitle(_("CSL - Server password")); + text_ctrl_password->SetFocus(); + button_ok->Enable(false); + button_ok->SetDefault(); + // end wxGlade + + if (!m_info->Password.IsEmpty()) + text_ctrl_password->SetValue(m_info->Password); +} + +void CslDlgConnectPass::do_layout() +{ + // begin wxGlade: CslDlgConnectPass::do_layout + wxFlexGridSizer* grid_sizer_main = new wxFlexGridSizer(2, 1, 0, 0); + wxFlexGridSizer* grid_sizer_button = new wxFlexGridSizer(1, 3, 0, 0); + wxStaticBoxSizer* sizer_ctrl = new wxStaticBoxSizer(sizer_ctrl_staticbox, wxHORIZONTAL); + wxFlexGridSizer* grid_sizer_ctrl = new wxFlexGridSizer(2, 1, 0, 0); + wxFlexGridSizer* grid_sizer_password = new wxFlexGridSizer(1, 2, 0, 0); + wxStaticText* label_password_static = new wxStaticText(this, wxID_ANY, _("Password:")); + grid_sizer_password->Add(label_password_static, 0, wxALL|wxALIGN_CENTER_VERTICAL, 4); + grid_sizer_password->Add(text_ctrl_password, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 4); + grid_sizer_password->AddGrowableCol(1); + grid_sizer_ctrl->Add(grid_sizer_password, 1, wxEXPAND, 0); + grid_sizer_ctrl->Add(checkbox_admin, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 4); + grid_sizer_ctrl->AddGrowableCol(0); + sizer_ctrl->Add(grid_sizer_ctrl, 1, wxEXPAND, 0); + grid_sizer_main->Add(sizer_ctrl, 1, wxALL|wxEXPAND, 4); + grid_sizer_button->Add(1, 1, 0, 0, 0); + grid_sizer_button->Add(button_ok, 0, wxALL, 4); + grid_sizer_button->Add(button_cancel, 0, wxALL, 4); + grid_sizer_button->AddGrowableCol(0); + grid_sizer_main->Add(grid_sizer_button, 1, wxBOTTOM|wxEXPAND, 4); + SetSizer(grid_sizer_main); + grid_sizer_main->Fit(this); + Layout(); + // end wxGlade + + if (!m_info->Admin) + { + checkbox_admin->Hide(); + grid_sizer_ctrl->Detach(checkbox_admin); + grid_sizer_main->Fit(this); + Layout(); + } + + CentreOnParent(); +} + +void CslDlgConnectPass::OnCommandEvent(wxCommandEvent& event) +{ + switch (event.GetId()) + { + case TEXT_PASSWORD: + button_ok->Enable(!event.GetString().IsEmpty()); + break; + + case CHECK_ADMIN: + text_ctrl_password->SetValue(event.IsChecked() ? m_info->AdminPassword:m_info->Password); + text_ctrl_password->SetFocus(); + break; + + case wxID_OK: + m_info->Admin=checkbox_admin->IsChecked(); + if (m_info->Admin) + m_info->AdminPassword=text_ctrl_password->GetValue(); + else + m_info->Password=text_ctrl_password->GetValue(); + EndModal(wxID_OK); + break; + + default: + break; + } + + event.Skip(); +} diff --git a/pool/shard007/C++/0096183_assign.cc b/pool/shard007/C++/0096183_assign.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a7b6a76b5fcbf1188a1423696fe7e8b04ef5a48 --- /dev/null +++ b/pool/shard007/C++/0096183_assign.cc @@ -0,0 +1,55 @@ +#include "mystring.h" +#include "trace.h" +#include +#include + +void mystring::dupnil() +{ + trace(""); + rep = &nil; + rep->attach(); +} + +void mystring::assign(const char* in) +{ + if(in) + assign(in, strlen(in)); + else { + mystringrep* tmp = rep; + dupnil(); + tmp->detach(); + } +} + +void mystring::assign(const char* in, size_t len) +{ + trace("in='" << in << "'"); + if(in != rep->buf) { + mystringrep* tmp = rep; + dup(in, len); + tmp->detach(); + } +} + +void mystring::dup(const char* in, size_t len) +{ + trace("in='" << in << "'"); + rep = mystringrep::dup(in, len); + rep->attach(); +} + +void mystring::dup(const char* in) +{ + if(in) + dup(in, strlen(in)); + else + dupnil(); +} + +void mystring::operator=(const mystringjoin& in) +{ + mystringrep* tmp = rep; + rep = in.traverse(); + rep->attach(); + tmp->detach(); +} diff --git a/pool/shard007/C++/0096186_rpc_test_server.cc b/pool/shard007/C++/0096186_rpc_test_server.cc new file mode 100644 index 0000000000000000000000000000000000000000..713e95329d17df6dc0a7ff02a95a68b6f27389e0 --- /dev/null +++ b/pool/shard007/C++/0096186_rpc_test_server.cc @@ -0,0 +1,163 @@ +/** Copyright (c) 2011, Urban Engines inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Urban Engines inc nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Catalin Popescu + */ + + +#include "whisperlib/rpc/test/rpc_test_proto.pb.h" +#include "whisperlib/rpc/rpc_http_server.h" +#include "whisperlib/rpc/rpc_controller.h" +#include "whisperlib/http/http_server_protocol.h" +#include "whisperlib/net/selector.h" +#include "whisperlib/base/gflags.h" + +DEFINE_int32(port, 8980, "Serve on this port"); +DEFINE_int32(num_threads, 4, "Serve with these may worker threads"); +DEFINE_int64(min_delay_ms, 100, "Delay the response by at least this time"); +DEFINE_int64(max_delay_ms, 100 + 256, "Delay the response by at most this time"); + +namespace whisper { +namespace rpc { +void Complete(::google::protobuf::Closure* done) { + done->Run(); +} + +class TestServiceImpl : public TestService { +public: + TestServiceImpl() { + } + + virtual void Mirror(::google::protobuf::RpcController* controller, + const ::rpc::TestReq* request, + ::rpc::TestReq* response, + ::google::protobuf::Closure* done) { + response->CopyFrom(*request); + DelayedResponse(controller, done); + } + virtual void Sum(::google::protobuf::RpcController* controller, + const ::rpc::TestReq* request, + ::rpc::TestReply* response, + ::google::protobuf::Closure* done) { + if (request->has_s()) { + response->set_s(request->s()); + } + response->set_z(int64(request->x()) + int64(request->y())); + DelayedResponse(controller, done); + } + virtual void Multiply(::google::protobuf::RpcController* controller, + const ::rpc::TestReq* request, + ::rpc::TestReply* response, + ::google::protobuf::Closure* done) { + if (request->has_s()) { + response->set_s(request->s()); + } + response->set_z(int64(request->x()) * int64(request->y())); + DelayedResponse(controller, done); + } + +private: + void DelayedResponse(::google::protobuf::RpcController* controller, + ::google::protobuf::Closure* done) { + if (FLAGS_max_delay_ms < FLAGS_min_delay_ms) { + done->Run(); + } else { + const int64 delay = FLAGS_min_delay_ms + random() % (FLAGS_max_delay_ms - + FLAGS_min_delay_ms); + rpc::Controller* rpc_controller = reinterpret_cast(controller); + rpc_controller->transport()->selector()->RegisterAlarm( + ::NewCallback(&Complete, done), delay); + } + } + + DISALLOW_EVIL_CONSTRUCTORS(TestServiceImpl); +}; +} + +using namespace whisper; + +void QuitServer(net::Selector* selector, http::ServerRequest* req) { + selector->RunInSelectLoop(::NewCallback(selector, &net::Selector::MakeLoopExit)); +} + + +int main(int argc, char* argv[]) { + common::Init(argc, argv); + + // Drives the networking show: + net::Selector selector; + + // Prepare the serving therads + vector working_threads; + for ( int i = 0; i < FLAGS_num_threads; ++i ) { + working_threads.push_back(new net::SelectorThread()); + working_threads.back()->Start(); + } + + // Setup connection worker threads - these are the ones that process the requests + net::NetFactory net_factory(&selector); + net::TcpAcceptorParams acceptor_params; + acceptor_params.set_client_threads(&working_threads); + net_factory.SetTcpParams(acceptor_params); + + // Parameters for the http server (how requests from clients are processed) + http::ServerParams params; + params.max_reply_buffer_size_ = 1<<18; + // params.dlog_level_ = true; + + // The server that knows to talk http + http::Server server("Test Server", // the name of the server + &selector, // drives networking + net_factory, // parametes for connections + params); // parameters for http + server.AddAcceptor(net::PROTOCOL_TCP, net::HostPort(0, FLAGS_port)); + + rpc::TestServiceImpl service; + rpc::HttpServer rpc_server(&server, NULL, "/baserpc", true, 100, ""); + CHECK(rpc_server.RegisterService("test", &service)); + + // Register the quit function. + server.RegisterProcessor("/quitquitquit", + ::NewPermanentCallback(&QuitServer, &selector), + true, true); + + // Start the server as soon as networking starts + selector.RunInSelectLoop(NewCallback(&server, &http::Server::StartServing)); + + // Write a message for the user: + LOG_INFO << " ==========> Starting. Point your client to: " + << "http://localhost:" << FLAGS_port << "/"; + + selector.Loop(); + for (int i = 0; i < working_threads.size(); ++i) { + delete working_threads[i]; + } + + LOG_INFO << "DONE"; +} diff --git a/pool/shard007/C++/0096187_waitable_event_win.cc b/pool/shard007/C++/0096187_waitable_event_win.cc new file mode 100644 index 0000000000000000000000000000000000000000..feed49922aa7990a10035976a5bd8c618e143740 --- /dev/null +++ b/pool/shard007/C++/0096187_waitable_event_win.cc @@ -0,0 +1,111 @@ +/* + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include +#include + +#include "base/logging.h" +#include "base/time.h" +#include "base/synchronization/waitable_event.h" + + +namespace base { + +WaitableEvent::WaitableEvent(bool manual_reset, bool signaled) + : handle_(CreateEvent(NULL, manual_reset, signaled, NULL)) { + // We're probably going to crash anyways if this is ever NULL, so we might as + // well make our stack reports more informative by crashing here. + DCHECK(handle_); +} + +WaitableEvent::WaitableEvent(HANDLE handle) + : handle_(handle) { + DCHECK(handle) << "Tried to create WaitableEvent from NULL handle"; +} + +WaitableEvent::~WaitableEvent() { + CloseHandle(handle_); +} + +HANDLE WaitableEvent::Release() { + HANDLE rv = handle_; + handle_ = INVALID_HANDLE_VALUE; + return rv; +} + +void WaitableEvent::Reset() { + ResetEvent(handle_); +} + +void WaitableEvent::Signal() { + SetEvent(handle_); +} + +bool WaitableEvent::IsSignaled() { + return TimedWait(TimeDelta::FromMilliseconds(0)); +} + +bool WaitableEvent::Wait() { + DWORD result = WaitForSingleObject(handle_, INFINITE); + // It is most unexpected that this should ever fail. Help consumers learn + // about it if it should ever fail. + DCHECK(result == WAIT_OBJECT_0) << "WaitForSingleObject failed"; + return result == WAIT_OBJECT_0; +} + +bool WaitableEvent::TimedWait(const TimeDelta& max_time) { + DCHECK(max_time >= TimeDelta::FromMicroseconds(0)); + // Be careful here. TimeDelta has a precision of microseconds, but this API + // is in milliseconds. If there are 5.5ms left, should the delay be 5 or 6? + // It should be 6 to avoid returning too early. + double timeout = ceil(max_time.InMillisecondsF()); + DWORD result = WaitForSingleObject(handle_, static_cast(timeout)); + switch (result) { + case WAIT_OBJECT_0: + return true; + case WAIT_TIMEOUT: + return false; + } + // It is most unexpected that this should ever fail. Help consumers learn + // about it if it should ever fail. + NOTREACHED() << "WaitForSingleObject failed"; + return false; +} + +// static +size_t WaitableEvent::WaitMany(WaitableEvent** events, size_t count) { + HANDLE handles[MAXIMUM_WAIT_OBJECTS]; + DCHECK_LE(count, MAXIMUM_WAIT_OBJECTS) + << "Can only wait on " << MAXIMUM_WAIT_OBJECTS << " with WaitMany"; + + for (size_t i = 0; i < count; ++i) + handles[i] = events[i]->handle(); + + // The cast is safe because count is small - see the CHECK above. + DWORD result = + WaitForMultipleObjects(static_cast(count), + handles, + FALSE, // don't wait for all the objects + INFINITE); // no timeout + if (result >= WAIT_OBJECT_0 + count) { + NOTREACHED() << "WaitForMultipleObjects failed: " << GetLastError(); + return 0; + } + + return result - WAIT_OBJECT_0; +} + +} // namespace base diff --git a/pool/shard007/C++/0096188_dbusplugin.cpp b/pool/shard007/C++/0096188_dbusplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..126a4d9d6f27f88ffe9c39c2c21eb97283cb61e4 --- /dev/null +++ b/pool/shard007/C++/0096188_dbusplugin.cpp @@ -0,0 +1,57 @@ +/** This file is part of Contacts daemon + ** + ** Copyright (c) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). + ** + ** Contact: Nokia Corporation (info@qt.nokia.com) + ** + ** GNU Lesser General Public License Usage + ** 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, Nokia gives you certain additional rights. + ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included + ** in the file LGPL_EXCEPTION.txt in this package. + ** + ** Other Usage + ** Alternatively, this file may be used in accordance with the terms and + ** conditions contained in a signed written agreement between you and Nokia. + **/ + +#include "dbusplugin.h" +#include +#include + +DbusPlugin::DbusPlugin() +{ + fakeSignals(); +} + +DbusPlugin::~DbusPlugin() +{ +} + +void DbusPlugin::init() +{ +} + +DbusPlugin::MetaData DbusPlugin::metaData() +{ + MetaData data; + data[metaDataKeyName] = QVariant(QString("dbusplugin")); + return data; +} + +void DbusPlugin::fakeSignals() +{ + Q_EMIT importStarted(QString("IM Service"), + QString("/fake/account/")); + + Q_EMIT importEnded(QString("IM Service"), + QString("/fake/account/"), 10, 30, 1); +} + +Q_EXPORT_PLUGIN2(dbusplugin, DbusPlugin) diff --git a/pool/shard007/C++/0096191_EvtxLogParser.cpp b/pool/shard007/C++/0096191_EvtxLogParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7de991e61403ccd5418885fb44c998f74b54bdd7 --- /dev/null +++ b/pool/shard007/C++/0096191_EvtxLogParser.cpp @@ -0,0 +1,243 @@ +/* + * This file is part of TADpole. + * + * TADpole 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. + * + * TADpole 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 TADpole. If not, see . + */ + +#include "EvtxLogParser.h" +#include +#include +#include +#include +#include "Crc32.h" +#include "exceptions/Exception.h" + +#define EPOCH_DIFF 0x019DB1DED53E8000LL /* 116444736000000000 nsecs */ +#define RATE_DIFF 10000000 /* 100 nsecs */ + +#define HEADER_SIZE 128 + +#define HEADER_MAGIC "ElfFile\x00" +#define CHUNK_MAGIC "ElfChnk\x00" +#define EVENT_MAGIC "**\x00\x00" + +typedef struct EvtxHeader +{ + char magic[8]; + int64_t oldest_chunk_number; + int64_t current_chunk_number; + int64_t next_record_number; + uint32_t header_part_len; + uint16_t version_minor; + uint16_t version_major; + uint16_t header_len; + uint16_t chunk_count; + char unknown[76]; + uint32_t flags; + uint32_t check_sum; +} +EvtxHeader_t; + +typedef struct EvtxChunkHeader +{ + char magic[8]; + int64_t oldest_log_record_number; + int64_t last_log_record_number; + int64_t oldest_file_record_number; + int64_t last_file_record_number; + uint32_t header_len; + uint32_t offset_last; + uint32_t offset_next; + uint32_t data_check_sum; + char unknown[68]; + uint32_t header_check_sum; + uint32_t string_table[64]; + uint32_t template_table[32]; +} +EvtxChunkHeader_t; + +typedef struct EvtxEventRecord +{ + char magic[4]; + uint32_t length; + int64_t record_id; + int64_t time_created; + //char *bin_xml_stream; + //uint32_t length2; +} +EvtxEventRecord_t; + +/* Convert a Windows filetime_t into a UNIX time_t */ +time_t fileTimeToUnixTime(int64_t ftime) { + int64_t tconv = (ftime - EPOCH_DIFF) / RATE_DIFF; + return (time_t)tconv; +} + +bool checkHeader(EvtxHeader_t *header) +{ + if (strncmp(header->magic, HEADER_MAGIC, 8)) + return false; + + Crc32 crc32; + crc32.addData((uint8_t*)header, 0x78); + + return crc32.getCrc32() == header->check_sum; +} + +void printHeader(EvtxHeader_t *header) +{ + std::cerr << "HEADER\nMagic: "; + for(int i; i < 8; i++) + std::cerr << header->magic[i]; + std::cerr << std::endl; + std::cerr << "Oldest Chunk: " << header->oldest_chunk_number << std::endl; + std::cerr << "Current Chunk: " << header->current_chunk_number << std::endl; + std::cerr << "Next Record: " << header->next_record_number << std::endl; + std::cerr << "Header Part: " << header->header_part_len << std::endl; + std::cerr << "Version Major: " << header->version_major << std::endl; + std::cerr << "Version Minor: " << header->version_minor << std::endl; + std::cerr << "Header Length: " << header->header_len << std::endl; + std::cerr << "Chunk Count: " << header->chunk_count << std::endl; + std::cerr << "Flags: " << header->flags << std::endl; + std::cerr << "Checksum: " << header->check_sum << std::endl; +} + +void printChunkHeader(EvtxChunkHeader_t *chunk_head) +{ + std::cerr << "\nCHUNK\nMagic: "; + for(int i; i < 8; i++) + std::cerr << chunk_head->magic[i]; + std::cerr << std::endl; + std::cerr << "First Log Record Number: " + << chunk_head->oldest_log_record_number << std::endl; + std::cerr << "Last Log Record Number: " + << chunk_head->last_log_record_number << std::endl; + std::cerr << "First File Record Number: " + << chunk_head->oldest_file_record_number << std::endl; + std::cerr << "Last File Record Number: " + << chunk_head->last_file_record_number << std::endl; + std::cerr << "Header Size: " + << chunk_head->header_len << std::endl; + std::cerr << "Last Offset: " + << chunk_head->offset_last << std::endl; + std::cerr << "Next Offset: " + << chunk_head->offset_next << std::endl; +} + +bool checkChunkHeader(EvtxChunkHeader_t *chunk_head) +{ + if (strncmp(chunk_head->magic, CHUNK_MAGIC, 8)) + return false; + + Crc32 crc32; + crc32.addData((uint8_t*)chunk_head, 0x78); + crc32.addData(((uint8_t*)chunk_head) + 0x80, 0x180); + + return crc32.getCrc32() == chunk_head->header_check_sum; +} + +bool checkChunkData(uint8_t *data, uint32_t length, uint32_t crc) +{ + Crc32 crc32; + crc32.addData(data, length); + + return crc == crc32.getCrc32(); +} + +bool checkEvent(EvtxEventRecord_t *event) +{ + return strncmp(event->magic, EVENT_MAGIC, 4) == 0; +} + +std::vector +EvtxLogParser::parseLogFile(TSK_FS_FILE *file, const char *path) +{ + if (tsk_verbose) + std::cerr << "\nattempting to parse (" << file->name->name << ")\n"; + std::vector events; + + EvtxHeader_t header; + int size = tsk_fs_file_read(file, 0, (char*)&header, sizeof(header), + TSK_FS_FILE_READ_FLAG_NONE); + if (!checkHeader(&header)) + { + throw ReadException("could not find header record"); + } + if (size != HEADER_SIZE) + { + throw ReadException("Header record was too short"); + } + + if (tsk_verbose) + printHeader(&header); + + //read chunks + EvtxChunkHeader_t chunk_head; + int32_t chunk_offset = header.header_len; + for (int chunk = 0; chunk < header.chunk_count; chunk++) + { + size = tsk_fs_file_read(file, chunk_offset, (char*)&chunk_head, + sizeof(chunk_head), TSK_FS_FILE_READ_FLAG_NONE); + if (!checkChunkHeader(&chunk_head)) + { + throw ReadException("chunk header not valid"); + } + + if (tsk_verbose) + printChunkHeader(&chunk_head); + + int len = chunk_head.offset_next - 0x200; + char data[len]; + size = tsk_fs_file_read(file, chunk_offset + 0x200, data, + len, TSK_FS_FILE_READ_FLAG_NONE); + + if (!checkChunkData((uint8_t*)data, len, chunk_head.data_check_sum)) + { + throw ReadException("chunk data not valid"); + } + + //read events + int event_offset = 0x200; + EvtxEventRecord_t event; + while (event_offset < chunk_head.offset_next) + { + size = tsk_fs_file_read(file, chunk_offset + event_offset, + (char*)&event, sizeof(event), TSK_FS_FILE_READ_FLAG_NONE); + + if (!checkEvent(&event)) + { + throw Exception("event not valid"); + } + + time_t time = fileTimeToUnixTime(event.time_created); + events.push_back(new LogEvent( + event.record_id, + time, + time)); + + //next offset + event_offset += event.length; + } + + chunk_offset += 0x10000; + } + + return events; +} + +std::string +EvtxLogParser::getExtension() +{ + return std::string("evtx"); +} diff --git a/pool/shard007/C++/0096193_Netherstorm.cpp b/pool/shard007/C++/0096193_Netherstorm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3914fffd5423cd303399bff4300d579510d4e324 --- /dev/null +++ b/pool/shard007/C++/0096193_Netherstorm.cpp @@ -0,0 +1,192 @@ +/* + * WEmu Scripts for WEmu MMORPG Server + * Copyright (C) 2008 WEmu 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 3 of the License, or + * 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 "StdAfx.h" +#include "Setup.h" +#include "../Common/EasyFunctions.h" + +class Veronia : public GossipScript +{ +public: + void GossipHello(Object * pObject, Player * plr, bool AutoSend) + { + GossipMenu *Menu; + if(plr->GetQuestLogForEntry(10652)) + { + objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 1, plr); + Menu->AddItem( 0, "I'm ready", 1); + Menu->SendTo(plr); + } + } + + void GossipSelectOption(Object * pObject, Player * plr, uint32 Id, uint32 IntId, const char * Code) + { + Creature * creat = TO_CREATURE(pObject); + switch(IntId) + { + case 1: + creat->CastSpell(plr, dbcSpell.LookupEntry(34905), true); + break; + } + } + + void Destroy() + { + delete this; + }; +}; + +bool FindingTheKeymaster(uint32 i, Spell * pSpell) +{ + if(!pSpell->u_caster->IsPlayer()) + return true; + + Player * plr = TO_PLAYER(pSpell->u_caster); + + QuestLogEntry *qle = plr->GetQuestLogForEntry(10256); + if(!qle) + return true; + + qle->SetMobCount(0, qle->GetMobCount(0)+1); + qle->SendUpdateAddKill(0); + qle->UpdatePlayerFields(); + return true; +} + +bool TheFleshLies(uint32 i, Spell * pSpell) +{ + if(!pSpell->u_caster->IsPlayer()) + return true; + + Player * plr = TO_PLAYER(pSpell->u_caster); + Creature * target = plr->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(plr->GetPositionX(), plr->GetPositionY() , plr->GetPositionZ(), 20561); + + if(target == NULL) + return true; + + QuestLogEntry *qle = plr->GetQuestLogForEntry(10345); + + if(qle == NULL) + return true; + + GameObject * obj = NULLGOB; + + if(qle && qle->GetMobCount(0) < qle->GetQuest()->required_mobcount[0]) + { + qle->SetMobCount(0, qle->GetMobCount(0)+1); + qle->SendUpdateAddKill(0); + + obj = sEAS.SpawnGameobject(plr, 183816, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 1, 0, 0, 0, 0); + sEAS.GameobjectDelete(obj, 1*30*1000); + } + target->Despawn(2000, 60*1000); + plr->UpdateNearbyGameObjects(); + qle->UpdatePlayerFields(); + return true; +} + +bool SurveyingtheRuins(uint32 i, Spell * pSpell) +{ + if ( pSpell == NULL || pSpell->u_caster == NULL || !pSpell->u_caster->IsPlayer() ) + return true; + + Player * pPlayer = TO_PLAYER( pSpell->u_caster ); + + QuestLogEntry *pQuest = pPlayer->GetQuestLogForEntry( 10335 ); + if ( pQuest == NULL ) + return true; + + if ( pQuest->GetMobCount( 0 ) < pQuest->GetQuest()->required_mobcount[0] ) + { + GameObject * mark1 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4695.2f, 2603.39f, 209.878f, 184612 ); + if( mark1 == NULL ) + mark1 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4695.28f, 2602.73f, 209.84f, 300095 ); + + if ( mark1 != NULL && pPlayer->CalcDistance( pPlayer, mark1 ) < 15 ) + { + pQuest->SetMobCount( 0, pQuest->GetMobCount( 0 ) + 1 ); + pQuest->SendUpdateAddKill( 0 ); + pQuest->UpdatePlayerFields(); + + //if you know a GO which can/should be spawned after marking the point... uncomment and add GO ID pls :) + //GameObject * pGameobject = sEAS.SpawnGameobject( pPlayer, , 4695.28f, 2602.73f, 209.84f, 0, 4, 0, 0, 0, 0 ); + //if ( pGameobject != NULL ) + //{ + // sEAS.GameobjectDelete( pGameobject, 1 * 60 * 1000 ); + //} + + return true; + } + } + + if ( pQuest->GetMobCount( 1 ) < pQuest->GetQuest()->required_mobcount[1] ) + { + GameObject * mark2 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4608.08f, 2442.02f, 195.71f, 184612 ); + if( mark2 == NULL ) + mark2 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4607.71f, 2440.72f, 195.65f, 300095 ); + + if ( mark2 != NULL && pPlayer->CalcDistance( pPlayer, mark2 ) < 15 ) + { + pQuest->SetMobCount( 1, pQuest->GetMobCount( 1 ) + 1 ); + pQuest->SendUpdateAddKill( 1 ); + pQuest->UpdatePlayerFields(); + + //if you know a GO which can/should be spawned after marking the point... uncomment and add GO ID pls :) + //GameObject * pGameobject = sEAS.SpawnGameobject( pPlayer, , 4607.71f, 2440.72f, 195.65f, 0, 4, 0, 0, 0, 0 ); + //if ( pGameobject != NULL ) + //{ + // sEAS.GameobjectDelete( pGameobject, 1 * 60 * 1000 ); + //} + + return true; + } + } + + if ( pQuest->GetMobCount( 2 ) < pQuest->GetQuest()->required_mobcount[2] ) + { + GameObject * mark3 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4716.37f, 2371.59f, 198.168f, 184612 ); + if( mark3 == NULL ) + mark3 = pPlayer->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords( 4716.77f, 2371.6f, 198.19f, 300095 ); + + if ( mark3 != NULL && pPlayer->CalcDistance( pPlayer, mark3 ) < 15 ) + { + pQuest->SetMobCount( 2, pQuest->GetMobCount( 2 ) + 1 ); + pQuest->SendUpdateAddKill( 2 ); + pQuest->UpdatePlayerFields(); + + //if you know a GO which can/should be spawned after marking the point... uncomment and add GO ID pls :) + //GameObject * pGameobject = sEAS.SpawnGameobject( pPlayer, , 4716.77f, 2371.6f, 198.19f, 0, 4 ); + //if ( pGameobject != NULL ) + //{ + // sEAS.GameobjectDelete( pGameobject, 1 * 60 * 1000 ); + //} + + return true; + } + } + + return true; +} + +void SetupNetherstorm(ScriptMgr* mgr) +{ + mgr->register_gossip_script(20162, CREATE_GOSSIPSCRIPT(Veronia)); + mgr->register_dummy_spell(34717, &FindingTheKeymaster); + mgr->register_dummy_spell(35372, &TheFleshLies); + mgr->register_dummy_spell(35246, &SurveyingtheRuins); +} diff --git a/pool/shard007/C++/0096201_textnodecontent.cpp b/pool/shard007/C++/0096201_textnodecontent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6928ddeaa9cc37463c8e724a099f6abc978510bc --- /dev/null +++ b/pool/shard007/C++/0096201_textnodecontent.cpp @@ -0,0 +1,183 @@ +/* + * Silence + * + * Copyright (C) 2009, 2010 Manuel Unglaub + * + * This file is part of Silence. + * + * Silence 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, version GPLv2 only of the License. + * + * Silence 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 Silence. If not, see . + */ + +#include +#include "src/constants.h" +#include "src/controller.h" +#include "src/data/node/textnodecontent.h" +#include "src/gui/view/textedit.h" + + +TextNodeContent::TextNodeContent() +{ + text = ""; + metaInfos = new QHash; + metaInfos->insert("Syntax", "None"); +} + +TextNodeContent::~TextNodeContent() +{ + delete metaInfos; +} + +void TextNodeContent::setText(QString text) +{ + this->text = text; + emit changed(); +} + +QString TextNodeContent::getText() const +{ + return text; +} + +AbstractContentView* TextNodeContent::getWidget() +{ + TextEdit *widget = Controller::create()->getTextEdit(); + widget->setContent(this); + widget->setSyntax(metaInfos->value("Syntax")); + return widget; +} + +QHash* TextNodeContent::getMetaInfos() +{ + return metaInfos; +} + +void TextNodeContent::addMetaInfo(QString key, QString value) +{ + metaInfos->insert(key, value); + emit changed(); +} + +QString TextNodeContent::getMimeType() +{ + return MimeType::TEXT_PLAIN; +} + +bool TextNodeContent::contains(const QString& value) +{ + return text.contains(value, Qt::CaseInsensitive); +} + +void TextNodeContent::setSyntax(QString syntax) +{ + metaInfos->insert("Syntax", syntax); + emit changed(); +} + +QDomElement TextNodeContent::getXmlData(QDomDocument &doc) +{ + QDomElement text = doc.createElement("text"); + QDomText textData = doc.createTextNode(this->text); + text.appendChild(textData); + return text; +} + +void TextNodeContent::setXmlData(QDomElement &xmlNode) +{ + QDomNode n = xmlNode.firstChild(); + while (!n.isNull()) + { + QDomElement e = n.toElement(); + + if (e.tagName() == "metainfo") + metaInfos->insert(e.attribute("key"), e.text()); + if (e.tagName() == "text") + text = e.text(); + + n = n.nextSibling(); + } +} + +QPixmap TextNodeContent::getPixmap() +{ + return getIcon().pixmap(16, 16); +} + +QIcon TextNodeContent::getIcon() +{ + if (metaInfos->value("Syntax") == "None") + return KIcon("text-plain"); + if (metaInfos->value("Syntax") == "JavaScript") + return KIcon("application-javascript"); + if (metaInfos->value("Syntax") == "Perl") + return KIcon("application-x-perl"); + if (metaInfos->value("Syntax") == "Ruby") + return KIcon("application-x-ruby"); + if (metaInfos->value("Syntax") == "CSS") + return KIcon("text-css"); + if (metaInfos->value("Syntax") == "HTML") + return KIcon("text-html"); + if (metaInfos->value("Syntax") == "CMake") + return KIcon("text-x-cmake"); + if (metaInfos->value("Syntax") == "C#") + return KIcon("text-x-csharp"); + if (metaInfos->value("Syntax") == "C++") + return KIcon("text-x-c++src"); + if (metaInfos->value("Syntax") == "Java") + return KIcon("text-x-java"); + if (metaInfos->value("Syntax") == "Makefile") + return KIcon("text-x-makefile"); + if (metaInfos->value("Syntax") == "Python") + return KIcon("text-x-python"); + if (metaInfos->value("Syntax") == "SQL") + return KIcon("text-x-sql"); + if (metaInfos->value("Syntax") == "LaTeX") + return KIcon("text-x-tex"); + if (metaInfos->value("Syntax") == "BibTeX") + return KIcon("text-x-bibtex"); + if (metaInfos->value("Syntax") == "PHP (HTML)") + return KIcon("application-x-php"); + if (metaInfos->value("Syntax") == "XML") + return KIcon("application-xml"); + if (metaInfos->value("Syntax") == "Pascal") + return KIcon("text-x-pascal"); + return KIcon("text-plain"); +} + +QString TextNodeContent::toString() +{ + QString result; + + result.append("Metainfos\n"); + QHashIterator itr(*metaInfos); + while (itr.hasNext()) + { + itr.next(); + result.append('\t' + itr.key() + " : " + itr.value() + '\n'); + } + + result.append("Text:\n"); + result.append(text); + + return result; +} + +void TextNodeContent::setParentNode(Node*) +{ +} + +QString TextNodeContent::getHtml() +{ + return "
" + text + "
"; +} + + diff --git a/pool/shard007/C++/0096203_NodeLocations.cc b/pool/shard007/C++/0096203_NodeLocations.cc new file mode 100644 index 0000000000000000000000000000000000000000..64f3d3f829199cd7a7b60a5d7907f2d1fae446ed --- /dev/null +++ b/pool/shard007/C++/0096203_NodeLocations.cc @@ -0,0 +1,47 @@ +//---------------------------------------------------------------------------- +// XC program; finite element analysis code +// for structural analysis and design. +// +// Copyright (C) Luis Claudio Pérez Tato +// +// This program derives from OpenSees +// developed by the «Pacific earthquake engineering research center». +// +// Except for the restrictions that may arise from the copyright +// of the original program (see copyright_opensees.txt) +// XC 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 software 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 . +//---------------------------------------------------------------------------- +//NodeLocations.cpp + +#include "NodeLocations.h" + +XC::NodeLocations::NodeLocations(int tag) +:TaggedObject(tag), numPartitions(0) + {} + +void XC::NodeLocations::Print(std::ostream &s, int flag) + { + s << "NodeLocations tag: " << getTag() << " partitions: "; + for(std::set::const_iterator i= nodePartitions.begin();i!= nodePartitions.end();i++) + s << " " << *i; + } + +int XC::NodeLocations::addPartition(int partition) + { + nodePartitions.insert(partition); + numPartitions= nodePartitions.size(); + return 0; + } diff --git a/pool/shard007/C++/0096206_frame_controller.cc b/pool/shard007/C++/0096206_frame_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..381dc0243e64295997115986c7ca65d6295d075f --- /dev/null +++ b/pool/shard007/C++/0096206_frame_controller.cc @@ -0,0 +1,120 @@ +// 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/examples/wm_flow/wm/frame_controller.h" + +#include "base/strings/utf_string_conversions.h" +#include "mojo/services/public/cpp/view_manager/view.h" +#include "mojo/views/native_widget_view_manager.h" +#include "ui/views/background.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/layout/layout_manager.h" +#include "ui/views/widget/widget.h" + +class FrameController::LayoutManager : public views::LayoutManager, + public views::ButtonListener { + public: + explicit LayoutManager(FrameController* controller) + : controller_(controller), + close_button_( + new views::LabelButton(this, base::ASCIIToUTF16("Begone"))), + maximize_button_( + new views::LabelButton(this, base::ASCIIToUTF16("Embiggen"))) {} + virtual ~LayoutManager() {} + + private: + static const int kButtonFrameMargin = 5; + static const int kButtonFrameSpacing = 2; + static const int kFrameSize = 10; + + // Overridden from views::LayoutManager: + virtual void Installed(views::View* host) OVERRIDE { + host->AddChildView(close_button_); + host->AddChildView(maximize_button_); + } + virtual void Layout(views::View* host) OVERRIDE { + gfx::Size ps = close_button_->GetPreferredSize(); + gfx::Rect bounds = host->GetLocalBounds(); + close_button_->SetBounds(bounds.right() - kButtonFrameMargin - ps.width(), + kButtonFrameMargin, ps.width(), ps.height()); + + ps = maximize_button_->GetPreferredSize(); + maximize_button_->SetBounds( + close_button_->x() - kButtonFrameSpacing - ps.width(), + kButtonFrameMargin, ps.width(), ps.height()); + + bounds.Inset(kFrameSize, + close_button_->bounds().bottom() + kButtonFrameMargin, + kFrameSize, kFrameSize); + controller_->app_view_->SetBounds(bounds); + } + virtual gfx::Size GetPreferredSize(const views::View* host) const OVERRIDE { + return gfx::Size(); + } + + // Overridden from views::ButtonListener: + virtual void ButtonPressed(views::Button* sender, + const ui::Event& event) OVERRIDE { + if (sender == close_button_) + controller_->CloseWindow(); + else if (sender == maximize_button_) + controller_->ToggleMaximize(); + } + + FrameController* controller_; + views::Button* close_button_; + views::Button* maximize_button_; + + DISALLOW_COPY_AND_ASSIGN(LayoutManager); +}; + +//////////////////////////////////////////////////////////////////////////////// +// FrameController, public: + +FrameController::FrameController(mojo::View* view, mojo::View** app_view) + : view_(view), + app_view_(mojo::View::Create(view->view_manager())), + frame_view_(new views::View), + frame_view_layout_manager_(new LayoutManager(this)), + widget_(new views::Widget), + maximized_(false) { + view_->AddChild(app_view_); + view_->AddObserver(this); + *app_view = app_view_; + frame_view_->set_background( + views::Background::CreateSolidBackground(SK_ColorBLUE)); + frame_view_->SetLayoutManager(frame_view_layout_manager_); + views::Widget::InitParams params( + views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + params.native_widget = new mojo::NativeWidgetViewManager(widget_, view_); + params.bounds = gfx::Rect(view_->bounds().size()); + widget_->Init(params); + widget_->SetContentsView(frame_view_); + widget_->Show(); +} + +FrameController::~FrameController() {} + +void FrameController::CloseWindow() { + app_view_->Destroy(); + view_->Destroy(); +} + +void FrameController::ToggleMaximize() { + if (!maximized_) + restored_bounds_ = view_->bounds(); + maximized_ = !maximized_; + if (maximized_) + view_->SetBounds(view_->parent()->bounds()); + else + view_->SetBounds(restored_bounds_); +} + +//////////////////////////////////////////////////////////////////////////////// +// FrameController, mojo::ViewObserver implementation: + +void FrameController::OnViewDestroyed(mojo::View* view) { + view_->RemoveObserver(this); + delete this; +} diff --git a/pool/shard007/C++/0096207_Eg27Main.cpp b/pool/shard007/C++/0096207_Eg27Main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf000d1e58e7a366ff0cdbcfd9f4d4911ed9204b --- /dev/null +++ b/pool/shard007/C++/0096207_Eg27Main.cpp @@ -0,0 +1,61 @@ +#include +#include + +using namespace std; +using namespace cv; + +int main() +{ + Mat src = imread("..\\pic\\building.jpg"); + if (src.empty()) + { + cout << "Cannot read image" << endl; + return -1; + } + + Point2f srcTri[] = { + Point2f(0,0), //top left + Point2f(src.cols - 1, 0), //top right + Point2f(0,src.rows - 1) //bottom left + }; + Point2f dstTri[] = { + Point2f(src.cols * 0.f, src.rows * 0.33f), //top left + Point2f(src.cols * 0.85f, src.rows * 0.25f), //top right + Point2f(src.cols * 0.15f, src.rows * 0.7f) //dst bottom left + }; + + //compute affine matrix + Mat warpMat = getAffineTransform(srcTri, dstTri); + Mat dst; + warpAffine(src, dst, warpMat, src.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar()); + + //mark the triangle + for (int i = 0; i < 3; ++i) + { + circle(src, srcTri[i], 5, Scalar(255, 0, 255), -1, LINE_AA); + circle(dst, dstTri[i], 5, Scalar(255, 0, 255), -1, LINE_AA); + } + + //show result + imshow("Origin Image", src); + imshow("Affine Transform Result", dst); + waitKey(); + + + //compute rotation matrix + Mat dst2; + for (int frame = 0; ; ++frame) + { + Point2f center(src.cols * 0.5f, src.rows * 0.5f); + double angle = frame * 3 % 360; + double scale = (cos((angle - 60) * CV_PI / 180) + 1.05) * 0.8; + Mat rotationMat = getRotationMatrix2D(center, angle, scale); + + warpAffine(src, dst2, rotationMat, src.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar()); + imshow("Rotated Image", dst2); + if (waitKey(30) >= 0) + break; + } + + return 0; +} \ No newline at end of file diff --git a/pool/shard007/C++/0096209_ks7017.cpp b/pool/shard007/C++/0096209_ks7017.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f119cf6e63c07af97334f12f0d27afc221a36fb --- /dev/null +++ b/pool/shard007/C++/0096209_ks7017.cpp @@ -0,0 +1,115 @@ +/* FCE Ultra - NES/Famicom Emulator + * + * Copyright notice for this file: + * Copyright (C) 2007 CaH4e3 + * + * 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 + * + * FDS Conversion + * + */ + +#include "mapinc.h" + +static uint8 reg, mirr; +static int32 IRQa, IRQCount, IRQLatch; +static uint8 *WRAM = NULL; +static uint32 WRAMSIZE; + +static SFORMAT StateRegs[] = +{ + { &mirr, 1, "MIRR" }, + { ®, 1, "REGS" }, + { &IRQa, 4, "IRQA" }, + { &IRQCount, 4, "IRQC" }, + { &IRQLatch, 4, "IRQL" }, + { 0 } +}; + +static void Sync(void) { + setprg16(0x8000, reg); + setprg16(0xC000, 2); + setmirror(mirr); +} + +static DECLFW(UNLKS7017Write) { +// FCEU_printf("bs %04x %02x\n",A,V); + if ((A & 0xFF00) == 0x4A00) { + reg = ((A >> 2) & 3) | ((A >> 4) & 4); + } else if ((A & 0xFF00) == 0x5100) { + Sync(); + } else if (A == 0x4020) { + X6502_IRQEnd(FCEU_IQEXT); + IRQCount &= 0xFF00; + IRQCount |= V; + } else if (A == 0x4021) { + X6502_IRQEnd(FCEU_IQEXT); + IRQCount &= 0xFF; + IRQCount |= V << 8; + IRQa = 1; + } else if (A == 0x4025) { + mirr = ((V & 8) >> 3) ^ 1; + } +} +static DECLFR(FDSRead4030) { + X6502_IRQEnd(FCEU_IQEXT); + return X.IRQlow & FCEU_IQEXT ? 1 : 0; +} + +static void UNL7017IRQ(int a) { + if (IRQa) { + IRQCount -= a; + if (IRQCount <= 0) { + IRQa = 0; + X6502_IRQBegin(FCEU_IQEXT); + } + } +} + +static void UNLKS7017Power(void) { + Sync(); + setchr8(0); + setprg8r(0x10, 0x6000, 0); + SetReadHandler(0x6000, 0x7FFF, CartBR); + SetWriteHandler(0x6000, 0x7FFF, CartBW); + SetReadHandler(0x8000, 0xFFFF, CartBR); + SetReadHandler(0x4030, 0x4030, FDSRead4030); + SetWriteHandler(0x4020, 0x5FFF, UNLKS7017Write); + FCEU_CheatAddRAM(WRAMSIZE >> 10, 0x6000, WRAM); +} + +static void UNLKS7017Close(void) { + if (WRAM) + FCEU_gfree(WRAM); + WRAM = NULL; +} + +static void StateRestore(int version) { + Sync(); +} + +void UNLKS7017_Init(CartInfo *info) { + info->Power = UNLKS7017Power; + info->Close = UNLKS7017Close; + MapIRQHook = UNL7017IRQ; + + WRAMSIZE = 8192; + WRAM = (uint8*)FCEU_gmalloc(WRAMSIZE); + SetupCartPRGMapping(0x10, WRAM, WRAMSIZE, 1); + AddExState(WRAM, WRAMSIZE, 0, "WRAM"); + + GameStateRestore = StateRestore; + AddExState(&StateRegs, ~0, 0, 0); +} diff --git a/pool/shard007/C++/0096210_relation.cpp b/pool/shard007/C++/0096210_relation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45ba8e1fc335ca05ef59e91a7364ed74de1c81b5 --- /dev/null +++ b/pool/shard007/C++/0096210_relation.cpp @@ -0,0 +1,73 @@ +/* Copyright (C) 2012 Olga Yakovleva */ + +/* This program is free software: you can redistribute it and/or modify */ +/* it under the terms of the GNU Lesser General Public License as published by */ +/* the Free Software Foundation, 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 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 "core/relation.hpp" +#include "core/item.hpp" +#include "core/utterance.hpp" + +namespace RHVoice +{ + item& relation::append(item& existing_item) + { + if(tail) + return tail->append(existing_item); + else + { + head=tail=new item(existing_item,this); + return *tail; + } + } + + item& relation::append() + { + if(tail) + return tail->append(); + else + { + head=tail=new item(this); + return *tail; + } + } + + item& relation::prepend(item& existing_item) + { + if(head) + return head->prepend(existing_item); + else + { + head=tail=new item(existing_item,this); + return *head; + } + } + + item& relation::prepend() + { + if(head) + return head->prepend(); + else + { + head=tail=new item(this); + return *head; + } + } + + void relation::clear() + { + while(!empty()) + { + head->remove(); + } + } +} diff --git a/pool/shard007/C++/0096211_CJ2017QC.cpp b/pool/shard007/C++/0096211_CJ2017QC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41fa17cffc3fb77bd417c6d127b2262b3b827a48 --- /dev/null +++ b/pool/shard007/C++/0096211_CJ2017QC.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define INF 1023123123 +#define EPS 1e-11 +#define LSOne(S) (S & (-S)) + +#define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X)) +#define FORB(X,Y) for (int (X) = (Y);(X) >= 0;--(X)) +#define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X)) +#define REPB(X,Y,Z) for (int (X) = (Y);(X) >= (Z);--(X)) + +#define SZ(Z) ((int)(Z).size()) +#define ALL(W) (W).begin(), (W).end() +#define PB push_back + +#define MP make_pair +#define A first +#define B second + +#define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++) + +using namespace std; + +typedef long long ll; +typedef double db; +typedef vector vi; +typedef pair ii; +typedef vector vii; + +void print_case(int i) +{ + cout << "Case #" << i + 1 << ": "; +} + +pair decompose(ll num) +{ + pair p; + p.first = num % 2 == 0 ? num / 2 - 1 : num / 2; + p.second = num / 2; + return p; +} + +int main() +{ + int ntc; + cin >> ntc; + + FORN(kk, ntc) + { + print_case(kk); + ll n, k; + cin >> n >> k; + map> tree; + tree[n] = 1; + + while (k > 1) + { + auto start = tree.begin(); + auto decomposed = decompose(start->first); + ll todo = min(k - 1, start->second); + tree[decomposed.first] += todo; + tree[decomposed.second] += todo; + start->second -= todo; + if (start->second == 0) + tree.erase(start); + k -= todo; + } + auto ans = decompose(tree.begin()->first); + cout << ans.second << ' ' << ans.first << endl; + } +} diff --git a/pool/shard007/C++/0096212_mscorlib_System_Runtime_CompilerServices_TaskAwaiter.cpp b/pool/shard007/C++/0096212_mscorlib_System_Runtime_CompilerServices_TaskAwaiter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dad9eab88903cef1859ec694c8e65807577595e5 --- /dev/null +++ b/pool/shard007/C++/0096212_mscorlib_System_Runtime_CompilerServices_TaskAwaiter.cpp @@ -0,0 +1,53 @@ +#include +#include +#include + + + +namespace mscorlib +{ + namespace System + { + namespace Runtime + { + namespace CompilerServices + { + + //Public Methods + void TaskAwaiterBase::GetResult() + { + Global::InvokeMethod("mscorlib", "System.Runtime.CompilerServices", "TaskAwaiter", 0, NULL, "GetResult", __native_object__, 0, NULL, NULL, NULL); + } + + void TaskAwaiterBase::OnCompleted(mscorlib::Callback continuation) + { + MonoType *__parameter_types__[1]; + void *__parameters__[1]; + __parameter_types__[0] = Global::GetType(typeid(continuation).name()); + __parameters__[0] = &continuation; + Global::InvokeMethod("mscorlib", "System.Runtime.CompilerServices", "TaskAwaiter", 0, NULL, "OnCompleted", __native_object__, 1, __parameter_types__, __parameters__, NULL); + } + + void TaskAwaiterBase::UnsafeOnCompleted(mscorlib::Callback continuation) + { + MonoType *__parameter_types__[1]; + void *__parameters__[1]; + __parameter_types__[0] = Global::GetType(typeid(continuation).name()); + __parameters__[0] = &continuation; + Global::InvokeMethod("mscorlib", "System.Runtime.CompilerServices", "TaskAwaiter", 0, NULL, "UnsafeOnCompleted", __native_object__, 1, __parameter_types__, __parameters__, NULL); + } + + //Get Set Properties Methods + // Get:IsCompleted + mscorlib::System::Boolean TaskAwaiterBase::get_IsCompleted() const + { + MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.CompilerServices", "TaskAwaiter", 0, NULL, "get_IsCompleted", __native_object__, 0, NULL, NULL, NULL); + return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); + } + + + + } + } + } +} diff --git a/pool/shard007/C++/0096215_partition.cc b/pool/shard007/C++/0096215_partition.cc new file mode 100644 index 0000000000000000000000000000000000000000..256fb6c23f956b3185194731a54fa9b9182b6a53 --- /dev/null +++ b/pool/shard007/C++/0096215_partition.cc @@ -0,0 +1,128 @@ +/** + * (n+1)Sec Multiparty Off-the-Record Messaging library + * Copyright (C) 2016, eQualit.ie + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of version 3 of the GNU Lesser General + * Public License as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "partition.h" + +namespace np1sec +{ + +/* + * Given a set of users that each want to kick a certain subset of the users + * in the set, find the largest partition of the user set such that in each + * part P of the partition, there is no subset Q of P such that everyone in Q + * wants to kick everyone in P\Q. + * + * We implement this by taking the complement of the wants-to-kick graph + * (the does-not-want-to-kick graph), and computing the strongly connected + * components of that graph. Each SCC of the does-not-want-to-kick-graph + * becomes one part of the partition of the user set. + * + * This is an implementation of Tarjan's strongly connected component + * algorithm. Ideally, it would be linear in the number of edges of the + * does-not-want-to-kick graph; but because the input is a wants-to-kick graph, + * the algorithm ends up being O(n^2). More involved bookkeeping in conversation + * could fix this. + */ + +struct SccAlgorithm +{ + struct Node + { + std::string username; + int index; + int minimal_backpointer; + bool on_stack; + }; + + SccAlgorithm(const std::map*>& complement_graph_): + complement_graph(complement_graph_) {} + + std::vector nodes; + const std::map*>& complement_graph; + int free_index; + std::vector stack; + std::vector> components; + + void visit(size_t node_id); +}; + +void SccAlgorithm::visit(size_t node_id) +{ + const std::set* edges_complement = complement_graph.at(nodes[node_id].username); + + nodes[node_id].index = free_index; + nodes[node_id].minimal_backpointer = free_index; + nodes[node_id].on_stack = true; + free_index++; + size_t stack_position = stack.size(); + stack.push_back(node_id); + + for (size_t i = 0; i < nodes.size(); i++) { + if (i == node_id) { + continue; + } + + if (edges_complement->count(nodes[i].username)) { + continue; + } + + if (nodes[i].index == -1) { + visit(i); + if (nodes[node_id].minimal_backpointer > nodes[i].minimal_backpointer) { + nodes[node_id].minimal_backpointer = nodes[i].minimal_backpointer; + } + } else if (nodes[i].on_stack) { + if (nodes[node_id].minimal_backpointer > nodes[i].index) { + nodes[node_id].minimal_backpointer = nodes[i].index; + } + } + } + + if (nodes[node_id].minimal_backpointer == nodes[node_id].index) { + std::set component; + while (stack.size() > stack_position) { + size_t i = stack.back(); + stack.pop_back(); + nodes[i].on_stack = false; + component.insert(nodes[i].username); + } + components.push_back(std::move(component)); + } +} + +std::vector> compute_conversation_partition(const std::map*>& kick_graph) +{ + SccAlgorithm algorithm(kick_graph); + for (const auto& i : kick_graph) { + SccAlgorithm::Node node; + node.username = i.first; + node.index = -1; + algorithm.nodes.push_back(node); + } + algorithm.free_index = 0; + + for (size_t i = 0; i < algorithm.nodes.size(); i++) { + if (algorithm.nodes[i].index == -1) { + algorithm.visit(i); + } + } + + return algorithm.components; +} + +} // namespace np1sec diff --git a/pool/shard007/C++/0096218_Tabbed.cpp b/pool/shard007/C++/0096218_Tabbed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93973b503644f3c4c68bccb8fa9eb1cadd460d66 --- /dev/null +++ b/pool/shard007/C++/0096218_Tabbed.cpp @@ -0,0 +1,130 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2013 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "Tabbed.hpp" +#include "Widget/WindowWidget.hpp" + +#include + +TabbedControl::TabbedControl(ContainerWindow &parent, PixelRect rc, + const WindowStyle style) + :page_flipped_callback(NULL) +{ + Create(parent, rc, style); +} + +TabbedControl::~TabbedControl() +{ + Destroy(); +} + +void +TabbedControl::AddPage(Widget *w) +{ + assert(IsDefined()); + + pager.Add(w); +} + +void +TabbedControl::AddClient(Window *w) +{ + /* backwards compatibility: make sure the Window is hidden */ + w->Hide(); + + AddPage(new WindowWidget(w)); +} + +bool +TabbedControl::SetCurrentPage(unsigned i, bool click) +{ + const unsigned old_current = pager.GetCurrentIndex(); + + bool success = pager.SetCurrent(i, click); + + if (success && old_current != pager.GetCurrentIndex() && + page_flipped_callback != NULL) + page_flipped_callback(); + + return success; +} + +void +TabbedControl::NextPage() +{ + if (pager.Next(true) && page_flipped_callback != NULL) + page_flipped_callback(); +} + +void +TabbedControl::PreviousPage() +{ + if (pager.Previous(true) && page_flipped_callback != NULL) + page_flipped_callback(); +} + +bool +TabbedControl::ClickPage(unsigned i) +{ + return pager.SetCurrent(i, true); +} + +bool +TabbedControl::Save(bool &changed) +{ + return pager.Save(changed); +} + +void +TabbedControl::UpdateLayout() +{ + pager.Move(GetClientRect()); +} + +void +TabbedControl::OnResize(PixelSize new_size) +{ + ContainerWindow::OnResize(new_size); + + UpdateLayout(); +} + +void +TabbedControl::OnCreate() +{ + ContainerWindow::OnCreate(); + + const PixelRect rc = GetClientRect(); + pager.Initialise(*this, rc); + pager.Prepare(*this, rc); + pager.Show(rc); +} + +void +TabbedControl::OnDestroy() +{ + pager.Hide(); + pager.Unprepare(); + + ContainerWindow::OnDestroy(); +} diff --git a/pool/shard007/C++/0096223_dbformat_test.cc b/pool/shard007/C++/0096223_dbformat_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1209369c31a038ca1c895b213b509155a8d54a8f --- /dev/null +++ b/pool/shard007/C++/0096223_dbformat_test.cc @@ -0,0 +1,131 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/dbformat.h" +#include "util/logging.h" +#include "util/testharness.h" + +namespace leveldb { + +static std::string IKey(const std::string& user_key, uint64_t seq, + ValueType vt) { + std::string encoded; + AppendInternalKey(&encoded, ParsedInternalKey(user_key, seq, vt)); + return encoded; +} + +static std::string Shorten(const std::string& s, const std::string& l) { + std::string result = s; + InternalKeyComparator(BytewiseComparator()).FindShortestSeparator(&result, l); + return result; +} + +static std::string ShortSuccessor(const std::string& s) { + std::string result = s; + InternalKeyComparator(BytewiseComparator()).FindShortSuccessor(&result); + return result; +} + +static void TestKey(const std::string& key, uint64_t seq, ValueType vt) { + std::string encoded = IKey(key, seq, vt); + + Slice in(encoded); + ParsedInternalKey decoded("", 0, kTypeValue); + + ASSERT_TRUE(ParseInternalKey(in, &decoded)); + ASSERT_EQ(key, decoded.user_key.ToString()); + ASSERT_EQ(seq, decoded.sequence); + ASSERT_EQ(vt, decoded.type); + + ASSERT_TRUE(!ParseInternalKey(Slice("bar"), &decoded)); +} + +class FormatTest {}; + +TEST(FormatTest, InternalKey_EncodeDecode) { + const char* keys[] = {"", "k", "hello", "longggggggggggggggggggggg"}; + const uint64_t seq[] = {1, + 2, + 3, + (1ull << 8) - 1, + 1ull << 8, + (1ull << 8) + 1, + (1ull << 16) - 1, + 1ull << 16, + (1ull << 16) + 1, + (1ull << 32) - 1, + 1ull << 32, + (1ull << 32) + 1}; + for (int k = 0; k < sizeof(keys) / sizeof(keys[0]); k++) { + for (int s = 0; s < sizeof(seq) / sizeof(seq[0]); s++) { + TestKey(keys[k], seq[s], kTypeValue); + TestKey("hello", 1, kTypeDeletion); + } + } +} + +TEST(FormatTest, InternalKey_DecodeFromEmpty) { + InternalKey internal_key; + + ASSERT_TRUE(!internal_key.DecodeFrom("")); +} + +TEST(FormatTest, InternalKeyShortSeparator) { + // When user keys are same + ASSERT_EQ(IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 99, kTypeValue))); + ASSERT_EQ( + IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 101, kTypeValue))); + ASSERT_EQ( + IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 100, kTypeValue))); + ASSERT_EQ( + IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 100, kTypeDeletion))); + + // When user keys are misordered + ASSERT_EQ(IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("bar", 99, kTypeValue))); + + // When user keys are different, but correctly ordered + ASSERT_EQ( + IKey("g", kMaxSequenceNumber, kValueTypeForSeek), + Shorten(IKey("foo", 100, kTypeValue), IKey("hello", 200, kTypeValue))); + + // When start user key is prefix of limit user key + ASSERT_EQ( + IKey("foo", 100, kTypeValue), + Shorten(IKey("foo", 100, kTypeValue), IKey("foobar", 200, kTypeValue))); + + // When limit user key is prefix of start user key + ASSERT_EQ( + IKey("foobar", 100, kTypeValue), + Shorten(IKey("foobar", 100, kTypeValue), IKey("foo", 200, kTypeValue))); +} + +TEST(FormatTest, InternalKeyShortestSuccessor) { + ASSERT_EQ(IKey("g", kMaxSequenceNumber, kValueTypeForSeek), + ShortSuccessor(IKey("foo", 100, kTypeValue))); + ASSERT_EQ(IKey("\xff\xff", 100, kTypeValue), + ShortSuccessor(IKey("\xff\xff", 100, kTypeValue))); +} + +TEST(FormatTest, ParsedInternalKeyDebugString) { + ParsedInternalKey key("The \"key\" in 'single quotes'", 42, kTypeValue); + + ASSERT_EQ("'The \"key\" in 'single quotes'' @ 42 : 1", key.DebugString()); +} + +TEST(FormatTest, InternalKeyDebugString) { + InternalKey key("The \"key\" in 'single quotes'", 42, kTypeValue); + ASSERT_EQ("'The \"key\" in 'single quotes'' @ 42 : 1", key.DebugString()); + + InternalKey invalid_key; + ASSERT_EQ("(bad)", invalid_key.DebugString()); +} + +} // namespace leveldb + +int main(int argc, char** argv) { return leveldb::test::RunAllTests(); } diff --git a/pool/shard007/C++/0096225_handles.cpp b/pool/shard007/C++/0096225_handles.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61c2557508a2054454d035a8b372c3e30317dce2 --- /dev/null +++ b/pool/shard007/C++/0096225_handles.cpp @@ -0,0 +1,82 @@ +#include "uv11/requests.hh" +#include "uv11/loop.hh" +#include "uv11/handles.hh" + +using namespace uv11; + +Handle::Handle(uv_handle_t* h, void* data) : handle_ptr(h) { + h->data = data; +} + +Handle::~Handle() {} + +uv_handle_t& Handle::GetHandle() { + return *handle_ptr; +} + +uv_handle_t const& Handle::GetHandle() const { + return *handle_ptr; +} + +void Handle::close() { + closing = true; + ::uv_close(&GetHandle(), [](uv_handle_t*){}); +} + +void Handle::close(CloseCb const& close_cb) { + on_close = close_cb; + + closing = true; + ::uv_close(&GetHandle(), [](uv_handle_t* handle){ + Handle* h = reinterpret_cast(handle->data); + h->on_close(*h); + }); +} + +bool Handle::is_closing() const { + return closing; +} + + +bool uv11::is_active(Handle const& handle) { + return ::uv_is_active(&handle.GetHandle()); +} + +bool uv11::is_closing(Handle const& handle) { + return handle.is_closing(); +} + +void uv11::close(Handle& handle) { + return handle.close(); +} + +void uv11::close(Handle& handle, CloseCb const& close_cb) { + return handle.close(close_cb); +} + +void uv11::ref(Handle& handle) { + return ::uv_ref(&handle.GetHandle()); +} + +void uv11::unref(Handle& handle) { + return ::uv_unref(&handle.GetHandle()); +} + +bool uv11::has_ref(Handle const& handle) { + return ::uv_has_ref(&handle.GetHandle()); +} + +Error uv11::send_buffer_size(Handle& handle, int* value) { + int s = ::uv_send_buffer_size(&handle.GetHandle(), value); + return make_error(s); +} + +Error uv11::recv_buffer_size(Handle& handle, int* value) { + int s = ::uv_recv_buffer_size(&handle.GetHandle(), value); + return make_error(s); +} + +Error uv11::fileno(Handle const& handle, uv_os_fd_t* fd) { + int s = ::uv_fileno(&handle.GetHandle(), fd); + return make_error(s); +} diff --git a/pool/shard007/C++/0096226_configcompilercontext.cpp b/pool/shard007/C++/0096226_configcompilercontext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7be89fff64b933be100372bfa94bd55798285385 --- /dev/null +++ b/pool/shard007/C++/0096226_configcompilercontext.cpp @@ -0,0 +1,68 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "config/configcompilercontext.hpp" +#include "base/singleton.hpp" +#include "base/json.hpp" +#include "base/netstring.hpp" +#include "base/exception.hpp" +#include "base/application.hpp" +#include "base/utility.hpp" + +using namespace icinga; + +ConfigCompilerContext *ConfigCompilerContext::GetInstance() +{ + return Singleton::GetInstance(); +} + +void ConfigCompilerContext::OpenObjectsFile(const String& filename) +{ + m_ObjectsPath = filename; + + auto *fp = new std::fstream(); + try { + m_ObjectsTempFile = Utility::CreateTempFile(filename + ".XXXXXX", 0600, *fp); + } catch (const std::exception& ex) { + Log(LogCritical, "cli", "Could not create temporary objects file: " + DiagnosticInformation(ex, false)); + Application::Exit(1); + } + + if (!*fp) + BOOST_THROW_EXCEPTION(std::runtime_error("Could not open '" + m_ObjectsTempFile + "' file")); + + m_ObjectsFP = fp; +} + +void ConfigCompilerContext::WriteObject(const Dictionary::Ptr& object) +{ + if (!m_ObjectsFP) + return; + + String json = JsonEncode(object); + + { + boost::mutex::scoped_lock lock(m_Mutex); + NetString::WriteStringToStream(*m_ObjectsFP, json); + } +} + +void ConfigCompilerContext::CancelObjectsFile() +{ + delete m_ObjectsFP; + m_ObjectsFP = nullptr; + +#ifdef _WIN32 + _unlink(m_ObjectsTempFile.CStr()); +#else /* _WIN32 */ + unlink(m_ObjectsTempFile.CStr()); +#endif /* _WIN32 */ +} + +void ConfigCompilerContext::FinishObjectsFile() +{ + delete m_ObjectsFP; + m_ObjectsFP = nullptr; + + Utility::RenameFile(m_ObjectsTempFile, m_ObjectsPath); +} + diff --git a/pool/shard007/C++/0096227_winrtdevicefactory.cpp b/pool/shard007/C++/0096227_winrtdevicefactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..900d88faf1dccd9786c74a8a6e5bb8acb1f2c898 --- /dev/null +++ b/pool/shard007/C++/0096227_winrtdevicefactory.cpp @@ -0,0 +1,289 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** 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 General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** 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-3.0.html. +** +****************************************************************************/ + +#include "winrtdevicefactory.h" + +#include "winrtconstants.h" +#include "winrtdevice.h" +#include "winrtqtversion.h" + +#include +#include +#include +#include + +#include + +using Core::MessageManager; +using ProjectExplorer::DeviceManager; +using ProjectExplorer::IDevice; +using QtSupport::BaseQtVersion; +using QtSupport::QtVersionManager; + +namespace WinRt { +namespace Internal { + +WinRtDeviceFactory::WinRtDeviceFactory() + : m_process(0) + , m_initialized(false) +{ + if (allPrerequisitesLoaded()) { + onPrerequisitesLoaded(); + } else { + connect(DeviceManager::instance(), &DeviceManager::devicesLoaded, + this, &WinRtDeviceFactory::onPrerequisitesLoaded, Qt::QueuedConnection); + connect(QtVersionManager::instance(), + &QtVersionManager::qtVersionsLoaded, + this, &WinRtDeviceFactory::onPrerequisitesLoaded, Qt::QueuedConnection); + } +} + +QString WinRtDeviceFactory::displayNameForId(Core::Id type) const +{ + return WinRtDevice::displayNameForType(type); +} + +QList WinRtDeviceFactory::availableCreationIds() const +{ + return QList() << Constants::WINRT_DEVICE_TYPE_LOCAL + << Constants::WINRT_DEVICE_TYPE_PHONE + << Constants::WINRT_DEVICE_TYPE_EMULATOR; +} + +IDevice::Ptr WinRtDeviceFactory::create(Core::Id id) const +{ + Q_UNUSED(id); + QTC_CHECK(false); + return IDevice::Ptr(); +} + +bool WinRtDeviceFactory::canRestore(const QVariantMap &map) const +{ + return availableCreationIds().contains(IDevice::typeFromMap(map)); +} + +IDevice::Ptr WinRtDeviceFactory::restore(const QVariantMap &map) const +{ + const IDevice::Ptr device(new WinRtDevice); + device->fromMap(map); + return device; +} + +void WinRtDeviceFactory::autoDetect() +{ + MessageManager::write(tr("Running Windows Runtime device detection.")); + const QString runnerFilePath = findRunnerFilePath(); + if (runnerFilePath.isEmpty()) { + MessageManager::write(tr("No winrtrunner.exe found.")); + return; + } + + if (!m_process) { + m_process = new Utils::QtcProcess(this); + connect(m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(onProcessError())); + connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), + SLOT(onProcessFinished(int,QProcess::ExitStatus))); + } + + const QString args = QStringLiteral("--list-devices"); + m_process->setCommand(runnerFilePath, args); + MessageManager::write(runnerFilePath + QLatin1Char(' ') + args); + m_process->start(); +} + +void WinRtDeviceFactory::onPrerequisitesLoaded() +{ + if (!allPrerequisitesLoaded() || m_initialized) + return; + + m_initialized = true; + disconnect(DeviceManager::instance(), &DeviceManager::devicesLoaded, + this, &WinRtDeviceFactory::onPrerequisitesLoaded); + disconnect(QtVersionManager::instance(), &QtVersionManager::qtVersionsLoaded, + this, &WinRtDeviceFactory::onPrerequisitesLoaded); + autoDetect(); + connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, + this, &WinRtDeviceFactory::autoDetect); +} + +void WinRtDeviceFactory::onProcessError() +{ + MessageManager::write(tr("Error while executing winrtrunner: %1") + .arg(m_process->errorString()), MessageManager::Flash); +} + +void WinRtDeviceFactory::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) +{ + if (exitStatus == QProcess::CrashExit) { + // already handled in onProcessError + return; + } + + if (exitCode != 0) { + MessageManager::write(tr("winrtrunner returned with exit code %1.") + .arg(exitCode), MessageManager::Flash); + return; + } + + parseRunnerOutput(m_process->readAllStandardOutput()); +} + +bool WinRtDeviceFactory::allPrerequisitesLoaded() +{ + return QtVersionManager::isLoaded() && DeviceManager::instance()->isLoaded(); +} + +QString WinRtDeviceFactory::findRunnerFilePath() const +{ + const QString winRtQtType = QLatin1String(Constants::WINRT_WINRTQT); + const QString winPhoneQtType = QLatin1String(Constants::WINRT_WINPHONEQT); + const QString winRtRunnerExe = QStringLiteral("/winrtrunner.exe"); + QString filePath; + BaseQtVersion *qt = 0; + foreach (BaseQtVersion *v, QtVersionManager::versions()) { + if (!v->isValid() || (v->type() != winRtQtType && v->type() != winPhoneQtType)) + continue; + if (!qt || qt->qtVersion() < v->qtVersion()) { + QFileInfo fi(v->binPath().toString() + winRtRunnerExe); + if (fi.isFile() && fi.isExecutable()) { + qt = v; + filePath = fi.absoluteFilePath(); + } + } + } + return filePath; +} + +static int extractDeviceId(QByteArray *line) +{ + int pos = line->indexOf(' '); + if (pos < 0) + return -1; + bool ok; + int id = line->left(pos).toInt(&ok); + if (!ok) + return -1; + line->remove(0, pos + 1); + return id; +} + +static IDevice::MachineType machineTypeFromLine(const QByteArray &line) +{ + return line.contains("Emulator ") ? IDevice::Emulator : IDevice::Hardware; +} + +/* + * The output of "winrtrunner --list-devices" looks like this: + * + * Available devices: + * Appx: + * 0 local + * Phone: + * 0 Device + * 1 Emulator 8.1 WVGA 4 inch 512MB + * 2 Emulator 8.1 WVGA 4 inch + * 3 Emulator 8.1 WXGA 4 inch + * 4 Emulator 8.1 720P 4.7 inch + * 5 Emulator 8.1 1080P 5.5 inch + * 6 Emulator 8.1 1080P 6 inch + * 7 WE8.1H Emulator WVGA 512MB + * 8 WE8.1H Emulator WVGA + * 9 WE8.1H Emulator WXGA + * 10 WE8.1H Emulator 720P + * 11 WE8.1H Emulator 1080P + * Xap: + * 0 Device + * 1 Emulator WVGA 512MB + * 2 Emulator WVGA + * 3 Emulator WXGA + * 4 Emulator 720P + */ +void WinRtDeviceFactory::parseRunnerOutput(const QByteArray &output) const +{ + ProjectExplorer::DeviceManager *deviceManager = ProjectExplorer::DeviceManager::instance(); + enum State { StartState, AppxState, PhoneState, XapState }; + State state = StartState; + int numFound = 0; + int numSkipped = 0; + foreach (QByteArray line, output.split('\n')) { + line = line.trimmed(); + if (line == "Appx:") { + state = AppxState; + } else if (line == "Phone:") { + state = PhoneState; + } else if (line == "Xap:") { + state = XapState; + } else { + const int deviceId = extractDeviceId(&line); + if (deviceId < 0) + continue; + + const IDevice::MachineType machineType = machineTypeFromLine(line); + Core::Id deviceType; + QString name; + QString internalName = QStringLiteral("WinRT."); + if (state == AppxState) { + internalName += QStringLiteral("appx."); + deviceType = Constants::WINRT_DEVICE_TYPE_LOCAL; + name = tr("Windows Runtime local UI"); + } else if (state == PhoneState) { + internalName += QStringLiteral("phone."); + name = QString::fromLocal8Bit(line); + if (machineType == IDevice::Emulator) + deviceType = Constants::WINRT_DEVICE_TYPE_EMULATOR; + else + deviceType = Constants::WINRT_DEVICE_TYPE_PHONE; + } else if (state == XapState) { + internalName += QStringLiteral("xap."); + name = QString::fromLocal8Bit(line); + if (machineType == IDevice::Emulator) + deviceType = Constants::WINRT_DEVICE_TYPE_EMULATOR; + else + deviceType = Constants::WINRT_DEVICE_TYPE_PHONE; + } + internalName += QString::number(deviceId); + const Core::Id internalId = Core::Id::fromString(internalName); + ++numFound; + if (DeviceManager::instance()->find(internalId)) { + ++numSkipped; + continue; + } + + WinRtDevice *device = new WinRtDevice(deviceType, machineType, + internalId, deviceId); + device->setDisplayName(name); + deviceManager->addDevice(ProjectExplorer::IDevice::ConstPtr(device)); + } + } + QString message = tr("Found %n Windows Runtime devices.", 0, numFound); + if (const int numNew = numFound - numSkipped) { + message += QLatin1Char(' '); + message += tr("%n of them are new.", 0, numNew); + } + MessageManager::write(message); +} + +} // Internal +} // WinRt diff --git a/pool/shard007/C++/0096230_SkChunkAlloc.cpp b/pool/shard007/C++/0096230_SkChunkAlloc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..847319949db0995095a391103827d8201dd0339d --- /dev/null +++ b/pool/shard007/C++/0096230_SkChunkAlloc.cpp @@ -0,0 +1,62 @@ +/* libs/corecg/SkChunkAlloc.cpp +** +** Copyright 2006, Google Inc. +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +*/ + +#include "SkChunkAlloc.h" + +SkChunkAlloc::~SkChunkAlloc() +{ + this->reset(); +} + +void SkChunkAlloc::reset() +{ + Block* block = fBlock; + + while (block) + { + Block* next = block->fNext; + sk_free(block); + block = next; + } + fBlock = NULL; +} + +void* SkChunkAlloc::alloc(size_t bytes, AllocFailType ftype) +{ + bytes = SkAlign4(bytes); + + if (fBlock == NULL || bytes > fBlock->fFreeSize) + { + size_t size = SkMax32((int32_t)bytes, (int32_t)fMinSize); + Block* block = (Block*)sk_malloc_flags(sizeof(Block) + size, ftype == kThrow_AllocFailType ? SK_MALLOC_THROW : 0); + if (block == NULL) + return NULL; + + block->fNext = fBlock; + block->fFreeSize = size; + block->fFreePtr = (char*)block + sizeof(Block); + fBlock = block; + } + + SkASSERT(fBlock && bytes <= fBlock->fFreeSize); + void* ptr = fBlock->fFreePtr; + + fBlock->fFreeSize -= bytes; + fBlock->fFreePtr += bytes; + return ptr; +} + diff --git a/pool/shard007/C++/0096231_main.cpp b/pool/shard007/C++/0096231_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..593428e7931bcc45d1022ba48b7e1ff9dbd25e12 --- /dev/null +++ b/pool/shard007/C++/0096231_main.cpp @@ -0,0 +1,131 @@ +/* GA-related headers */ +#include + +/* ARGoS-related headers */ +#include +#include + +#include + +/****************************************/ +/****************************************/ + +/* + * Launch ARGoS to evaluate a genome. + */ +float LaunchARGoS(GAGenome& c_genome) { + /* Convert the received genome to the actual genome type */ + GARealGenome& cRealGenome = dynamic_cast(c_genome); + /* The CSimulator class of ARGoS is a singleton. Therefore, to + * manipulate an ARGoS experiment, it is enough to get its instance. + * This variable is declared 'static' so it is created + * once and then reused at each call of this function. + * This line would work also without 'static', but written this way + * it is faster. */ + static argos::CSimulator& cSimulator = argos::CSimulator::GetInstance(); + /* Get a reference to the loop functions */ + static CGALibPhototaxisLoopFunctions& cLoopFunctions = dynamic_cast(cSimulator.GetLoopFunctions()); + /* + * Run 5 trials and take the worst performance as final value. + * Performance in this experiment is defined as the distance from the light. + * Thus, we keep the max distance found. + */ + Real fDistance = 0.0f; + for(size_t i = 0; i < 5; ++i) { + /* Tell the loop functions to get ready for the i-th trial */ + cLoopFunctions.SetTrial(i); + /* Reset the experiment. + * This internally calls also CEvolutionLoopFunctions::Reset(). */ + cSimulator.Reset(); + /* Configure the controller with the genome */ + cLoopFunctions.ConfigureFromGenome(cRealGenome); + /* Run the experiment */ + cSimulator.Execute(); + /* Update performance */ + fDistance = Max(fDistance, cLoopFunctions.Performance()); + } + /* Return the result of the evaluation */ + return fDistance; +} + +/* + * Flush best individual + */ +void FlushBest(const GARealGenome& c_genome, + size_t un_generation) { + std::ostringstream cOSS; + cOSS << "best_" << un_generation << ".dat"; + std::ofstream cOFS(cOSS.str().c_str(), std::ios::out | std::ios::trunc); + cOFS << GENOME_SIZE // first write the number of values to dump + << " " + << c_genome // then write the actual values + << std::endl; +} + +/****************************************/ +/****************************************/ + +int main(int argc, char** argv) { + /* + * Initialize GALIB + */ + /* Create an allele whose values can be in the range [-10,10] */ + GAAlleleSet cAlleleSet(-10.0f, 10.0f); + /* Create a genome with 10 genes, using LaunchARGoS() to evaluate it */ + GARealGenome cGenome(GENOME_SIZE, cAlleleSet, LaunchARGoS); + /* Create and configure a basic genetic algorithm using the genome */ + GASimpleGA cGA(cGenome); + cGA.minimize(); // the objective function must be minimized + cGA.populationSize(5); // population size for each generation + cGA.nGenerations(500); // number of generations + cGA.pMutation(0.05f); // prob of gene mutation + cGA.pCrossover(0.15f); // prob of gene crossover + cGA.scoreFilename("evolution.dat"); // filename for the result log + cGA.flushFrequency(1); // log the results every generation + + /* + * Initialize ARGoS + */ + /* The CSimulator class of ARGoS is a singleton. Therefore, to + * manipulate an ARGoS experiment, it is enough to get its instance */ + argos::CSimulator& cSimulator = argos::CSimulator::GetInstance(); + /* Set the .argos configuration file + * This is a relative path which assumed that you launch the executable + * from argos3-examples (as said also in the README) */ + cSimulator.SetExperimentFileName("experiments/galib.argos"); + /* Load it to configure ARGoS */ + cSimulator.LoadExperiment(); + + /* + * Launch the evolution, setting the random seed + */ + cGA.initialize(12345); + do { + argos::LOG << "Generation #" << cGA.generation() << "..."; + cGA.step(); + argos::LOG << "done."; + if(cGA.generation() % cGA.flushFrequency() == 0) { + argos::LOG << " Flushing..."; + /* Flush scores */ + cGA.flushScores(); + /* Flush best individual */ + FlushBest(dynamic_cast(cGA.statistics().bestIndividual()), + cGA.generation()); + argos::LOG << "done."; + } + LOG << std::endl; + LOG.Flush(); + } + while(! cGA.done()); + + /* + * Dispose of ARGoS stuff + */ + cSimulator.Destroy(); + + /* All is OK */ + return 0; +} + +/****************************************/ +/****************************************/ diff --git a/pool/shard007/C++/0096233_sql_data_change.cc b/pool/shard007/C++/0096233_sql_data_change.cc new file mode 100644 index 0000000000000000000000000000000000000000..849208c38aaedbee607884e2111de79299b85877 --- /dev/null +++ b/pool/shard007/C++/0096233_sql_data_change.cc @@ -0,0 +1,172 @@ +/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. 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; version 2 of the 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 + along with this program; if not, write to the Free Software Foundation, + 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ + + +/** + @file sql_data_change.cc + + Contains classes representing SQL-data change statements. Currently + the only data change functionality implemented here is function + defaults. +*/ + +#include "sql/sql_data_change.h" + +#include "current_thd.h" +#include "field.h" +#include "handler.h" +#include "item.h" +#include "my_dbug.h" +#include "my_inttypes.h" +#include "my_sys.h" +#include "sql_class.h" // THD +#include "sql_list.h" +#include "table.h" // TABLE + +/** + Allocates and initializes a MY_BITMAP bitmap, containing one bit per column + in the table. The table THD's MEM_ROOT is used to allocate memory. + + @param table The table whose columns should be used as a template + for the bitmap. + @param[out] bitmap A pointer to the allocated bitmap. + + @retval false Success. + @retval true Memory allocation error. +*/ +static bool allocate_column_bitmap(TABLE *table, MY_BITMAP **bitmap) +{ + DBUG_ENTER("allocate_column_bitmap"); + const uint number_bits= table->s->fields; + MY_BITMAP *the_struct; + my_bitmap_map *the_bits; + + DBUG_ASSERT(current_thd == table->in_use); + if (multi_alloc_root(table->in_use->mem_root, + &the_struct, sizeof(MY_BITMAP), + &the_bits, bitmap_buffer_size(number_bits), + NULL) == NULL) + DBUG_RETURN(true); + + if (bitmap_init(the_struct, the_bits, number_bits, FALSE) != 0) + DBUG_RETURN(true); + + *bitmap= the_struct; + + DBUG_RETURN(false); +} + + +bool COPY_INFO::get_function_default_columns(TABLE *table) +{ + DBUG_ENTER("COPY_INFO::get_function_default_columns"); + + if (m_function_default_columns != NULL) + DBUG_RETURN(false); + + if (allocate_column_bitmap(table, &m_function_default_columns)) + DBUG_RETURN(true); + + if (!m_manage_defaults) + DBUG_RETURN(false); // leave bitmap full of zeroes + + /* + Find columns with function default on insert or update, mark them in + bitmap. + */ + for (uint i= 0; i < table->s->fields; ++i) + { + Field *f= table->field[i]; + if ((m_optype == INSERT_OPERATION && f->has_insert_default_function()) || + (m_optype == UPDATE_OPERATION && f->has_update_default_function())) + bitmap_set_bit(m_function_default_columns, f->field_index); + } + + if (bitmap_is_clear_all(m_function_default_columns)) + DBUG_RETURN(false); // no bit set, next step unneeded + + /* + Remove explicitly assigned columns from the bitmap. The assignment + target (lvalue) may not always be a column (Item_field), e.g. we could + be inserting into a view, whose column is actually a base table's column + converted with COLLATE: the lvalue would then be an + Item_func_set_collation. + If the lvalue is an expression tree, we clear all columns in it from the + bitmap. + */ + List *all_changed_columns[2]= + { m_changed_columns, m_changed_columns2 }; + for (uint i= 0; i < 2; i++) + { + if (all_changed_columns[i] != NULL) + { + List_iterator lvalue_it(*all_changed_columns[i]); + Item *lvalue_item; + while ((lvalue_item= lvalue_it++) != NULL) + lvalue_item->walk(&Item::remove_column_from_bitmap, + Item::enum_walk(Item::WALK_POSTFIX | Item::WALK_SUBQUERY), + reinterpret_cast(m_function_default_columns)); + } + } + + DBUG_RETURN(false); +} + + +void COPY_INFO::set_function_defaults(TABLE *table) +{ + DBUG_ENTER("COPY_INFO::set_function_defaults"); + + DBUG_ASSERT(m_function_default_columns != NULL); + + /* Quick reject test for checking the case when no defaults are invoked. */ + if (bitmap_is_clear_all(m_function_default_columns)) + DBUG_VOID_RETURN; + + for (uint i= 0; i < table->s->fields; ++i) + if (bitmap_is_set(m_function_default_columns, i)) + { + DBUG_ASSERT(bitmap_is_set(table->write_set, i)); + switch (m_optype) + { + case INSERT_OPERATION: + table->field[i]->evaluate_insert_default_function(); + break; + case UPDATE_OPERATION: + table->field[i]->evaluate_update_default_function(); + break; + } + } + + /** + @todo combine this call to update_generated_write_fields() with the + one in fill_record() to avoid updating virtual generated fields twice. + */ + if (table->has_gcol()) + update_generated_write_fields(table->write_set, table); + + DBUG_VOID_RETURN; +} + + +bool COPY_INFO::ignore_last_columns(TABLE *table, uint count) +{ + if (get_function_default_columns(table)) + return true; + for (uint i= 0; i < count; i++) + bitmap_clear_bit(m_function_default_columns, + table->s->fields - 1 - i); + return false; +} diff --git a/pool/shard007/C++/0096234_OAI_DEFE.cpp b/pool/shard007/C++/0096234_OAI_DEFE.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc6b0c75266e8f0b71a3890db7f3fade35a81402 --- /dev/null +++ b/pool/shard007/C++/0096234_OAI_DEFE.cpp @@ -0,0 +1,96 @@ +/* + * Seven Kingdoms: Ancient Adversaries + * + * Copyright 1997,1998 Enlight Software Ltd. + * + * 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, see . + * + */ + +//Filename : OAI_DEFE.CPP +//Description: AI on defense + +#include +#include +#include + +//----- Begin of function Nation::ai_defend -----// +// +// attackerUnitRecno - unit recno of the attacker. +// +int Nation::ai_defend(int attackerUnitRecno) +{ + //--- don't call for defense too frequently, only call once 7 days (since this function will be called every time our king/firm/town is attacked, so this filtering is necessary ---// + + if( info.game_date < ai_last_defend_action_date+7 ) + return 0; + + ai_last_defend_action_date = info.game_date; + + //---------- analyse the situation first -----------// + + Unit* attackerUnit = unit_array[attackerUnitRecno]; + + err_when( attackerUnit->nation_recno == nation_recno ); + + int attackerXLoc = attackerUnit->next_x_loc(); + int attackerYLoc = attackerUnit->next_y_loc(); + + int hasWar; + + int enemyCombatLevel = mobile_defense_combat_level( attackerXLoc, attackerYLoc, + attackerUnit->nation_recno, 0, hasWar ); // 0-don't return immediately even if there is war around this town + + //-- the value returned is enemy strength minus your own strength, so if it's positive, it means that your enemy is stronger than you, otherwise you're stronger than your enemy --// + + int attackCombatLevel = ai_attack_target(attackerXLoc, attackerYLoc, enemyCombatLevel, 1); // 1-defense mode + + //------ request military aid from allies ----// + + if( attackCombatLevel < enemyCombatLevel && attackerUnit->nation_recno ) + { + ai_request_military_aid(); + } + + return 1; +} +//----- End of function Nation::ai_defend -----// + + +//----- Begin of function Nation::ai_request_military_aid -----// +// +// Request allied nations to provide immediate military aid. +// +int Nation::ai_request_military_aid() +{ + return 0; //**BUGHERE, multiplayer sync error, disabled temporarily + + for( int i=nation_array.size() ; i>0 ; i-- ) + { + if( nation_array.is_deleted(i) ) + continue; + + if( get_relation(i)->status != NATION_ALLIANCE ) + continue; + + if( should_diplomacy_retry(TALK_REQUEST_MILITARY_AID, i) ) + { + talk_res.ai_send_talk_msg(i, nation_recno, TALK_REQUEST_MILITARY_AID); + return 1; + } + } + + return 0; +} +//----- End of function Nation::ai_request_military_aid -----// diff --git a/pool/shard007/C++/0096235_file.cpp b/pool/shard007/C++/0096235_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f3d4a22aa27d91001348134474fd7f71ec480bc --- /dev/null +++ b/pool/shard007/C++/0096235_file.cpp @@ -0,0 +1,26 @@ +#include "file.h" + +#include +#include + +#include "logger.h" + +namespace util +{ + void BackupFile(const std::string& src, const std::string& dst /*= ""*/) + { + std::ifstream ifs(src.c_str()); + std::string backupPath = dst.empty() ? src + ".bak" : dst; + std::ofstream ofs(backupPath.c_str()); + ofs << ifs.rdbuf(); + Logger::GetInstance().Log("ok backup " + src); + } + + void CopyFile_(const std::string& src, const std::string& dst) + { + std::ifstream ifs(src.c_str(), std::fstream::binary | std::fstream::in); + std::ofstream ofs(dst.c_str(), std::fstream::binary | std::fstream::out); + ofs << ifs.rdbuf(); + Logger::GetInstance().Log("ok copy " + src); + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0096237_Slider.cpp b/pool/shard007/C++/0096237_Slider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7e67ea64fc4eaede4bc6f633595b996e1dcb6f6 --- /dev/null +++ b/pool/shard007/C++/0096237_Slider.cpp @@ -0,0 +1,191 @@ +/** + * This file is part of NCC-GameMachine. + * + * NCC-GameMachine 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. + * + * NCC-GameMachine 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 NCC-GameMachine. If not, see . +**/ + +#include "Slider.h" +#include "engine/System.h" +#include "engine/utils/Log.h" +#include + +Slider::Slider(){} + +Slider::~Slider(){ + free_textures(); +} + + +/** + * Libera texturas da memória + */ +void Slider::free_textures(){ + for (auto logo : logos) + delete logo.second; +} + +/** + * Reccarega as logos dos jogos + */ +void Slider::reload(std::vector games){ + free_textures(); + names.clear(); + positions.clear(); + render_order.clear(); + dests.clear(); + + for (std::string game : games){ + names.push_back(game); + render_order.push_back(game); + positions[game] = Point(0,0,1); + dests[game] = {0,0,300,300}; + logos[game] = new Texture(); + logos[game]->load(System::get_renderer(), System::GAME_FOLDER() + game + "/media/logo.png"); + } + current_game = names[0]; + // ajusta novos posicionamentos iniciais na tela + ajust_game(); + sort_in_z(); + set_perspective(); +} + +/** + * Método de comparação para definir qual ponto está mais atrśa em z + */ +bool Slider::compare_in_z(std::string a, std::string b){ + return positions[a].z <= positions[b].z; +} + +/** + * Ordena a fila de renderização baseado no valor de z + */ +void Slider::sort_in_z(){ + using namespace std::placeholders; + auto comp = std::bind(&Slider::compare_in_z, this, _1, _2); + std::sort(render_order.begin(), render_order.end(), comp); +} + +/** + * Atribui posicionamentos aos retângulos de destino para renderização + * baseado no cálculo de projeção em perspectiva + */ +void Slider::set_perspective(){ + for (std::string game : names){ + Point center = positions[game]; + Point topleft = Point(-0.5,-0.5,0) + center; + Point bottomright = Point(0.5,0.5,0) + center; + + topleft = (topleft * DISTANCE) / (topleft.z + DISTANCE - 1); + bottomright = (bottomright * DISTANCE) / (bottomright.z + DISTANCE - 1); + dests[game] = { + (int)(topleft.x * DEFAULT_SIZE.x + CENTER_VIEWPORT.x), + (int)(topleft.y * DEFAULT_SIZE.y + CENTER_VIEWPORT.y), + (int)((bottomright.x - topleft.x) * DEFAULT_SIZE.x), + (int)((bottomright.y - topleft.y) * DEFAULT_SIZE.y) + }; + } +} + +/** + * Comando para vançar na lista de jogos + */ +void Slider::goto_next(int direction){ + if (!rotating || rot_direction/abs(rot_direction) == direction){ + rotating = true; + rot_direction += direction; + } +} + +/** + * Posiciona com exatidão as logos no espaço de mundo tomando por base + * o jogo que está a frente (current_game) + */ +void Slider::ajust_game(){ + int n_games = logos.size(); + double ang = 360.0 / n_games; + int idx = (int)(std::find(names.begin(), names.end(), current_game) - names.begin()); + for (int i=0; i 0) j += n_games; + std::string name = names[i]; + positions[name] = BASE_VEC.rotate_3d(Point::X_AXIS, deg2rad(ang * j)) * SCALE; + } +} + +/** + * Rotaciona todos os logos em um ângulo theta + */ +void Slider::rotate(double theta){ + for (std::string game : names){ + Point vec = positions[game]; + vec.y /= SCALE.y; + positions[game] = vec.rotate_3d(Point::X_AXIS, deg2rad(theta)) * SCALE; + } +} + +/** + * Método de update. + * Se em animação de rotação, calcula o angulo necessário para o frame + * e rotaciona. Se terminar a rotação, ajusta a tela com o novo jogo + * na frente. Por fim, usa a callback para notificar a GameList que um + * novo jogo foi selecionado. + */ +void Slider::update(double delta){ + if(rotating){ + double ang = 360.0 / names.size() * abs(rot_direction); + double step = ang * delta * rot_direction; + rotate(step); + rot_accum += step; + if (abs(rot_accum) >= abs(ang)){ + rot_accum = 0; + rotating = false; + current_game = get_next_game(rot_direction); + ajust_game(); + rot_direction = 0; + game_selected(current_game); + } + sort_in_z(); + set_perspective(); + } +} + +/** + * encapsulamento da callback + */ +void Slider::set_callback(std::function game_selected){ + this->game_selected = game_selected; +} + +/** + * Retorna o jogo selcionado baseado na posição do jogo atual + deslocamento + */ +std::string Slider::get_next_game(int offset){ + // rotação no sentido contrário da direção da lista + offset = -offset; + auto game_it = std::find(names.begin(), names.end(), current_game); + int idx = game_it - names.begin(); + int n_idx = (idx + offset) % names.size(); + if (n_idx >= 0) + return names[n_idx]; + else + return names[names.size() + n_idx]; +} + +/** + * Renderiza as logos na tela + */ +void Slider::render(){ + for(std::string game : render_order) + System::blit(logos[game]->get(), logos[game]->get_src_rect(), dests[game]); +} \ No newline at end of file diff --git a/pool/shard007/C++/0096243_SocketServer_unix.cpp b/pool/shard007/C++/0096243_SocketServer_unix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1105bf11ec5e30649812bb9f2df98249212b668d --- /dev/null +++ b/pool/shard007/C++/0096243_SocketServer_unix.cpp @@ -0,0 +1,220 @@ +/** Original implementation supporting both UNIX and TCP sockets. + * + * The UNIX socket implementation is based on the behaviour defined in the FastCGI specification, and also + * includes optional support for logging via syslog, as defined in the specification. + * + * This implementation is *NOT* portable. + */ +#include "SocketServer.h" + +#include "fastcgi.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace FastCgiQt +{ + class SocketServer::Private + { + public: + /// Lock the socket with the specified socket id. + void lockSocket(int socket); + /// Unlock the socket with the specified socket id. + void releaseSocket(int socket); + + /// Socket handle + int m_socket; + + /// Type of socket + SocketServer::SocketType m_socketType; + + /** Notifier used to watch for new connections to the + * FastCGI socket. + */ + QSocketNotifier* m_socketNotifier; + }; + + SocketServer::SocketTypes SocketServer::activeSocketTypes() + { + // Check we're running as a FastCGI application + sockaddr_un sa; + socklen_t len = sizeof(sa); + ::memset(&sa, 0, len); + + // The recommended way of telling if we're running as fastcgi or not. + const int error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast(&sa), &len); + if(error == -1 && errno != ENOTCONN) + { + // Nope, not FastCGI over unix socket + return SocketTypes(); + } + return UnixSocket; + } + + bool SocketServer::isFinished() const + { + return !(d->m_socketNotifier && d->m_socketNotifier->isEnabled()); + } + + void SocketServer::Private::lockSocket(int socket) + { +#ifdef WITHOUT_FLOCK + struct flock fl; + ::bzero(&fl, sizeof(fl)); + + fl.l_type = F_WRLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + + ::fcntl(socket, F_SETLKW, &fl); +#else + ::flock(socket, LOCK_EX); +#endif + } + + void SocketServer::Private::releaseSocket(int socket) + { +#ifdef WITHOUT_FLOCK + struct flock fl; + ::bzero(&fl, sizeof(fl)); + + fl.l_type = F_UNLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + + ::fcntl(socket, F_SETLK, &fl); +#else + ::flock(socket, LOCK_UN); +#endif + } + + bool SocketServer::listen(SocketType type, quint16 parameter) + { + d->m_socketType = type; + if(type == UnixSocket) + { + if(! (activeSocketTypes() & UnixSocket)) + { + qWarning("Asked to run FastCGI on a UNIX socket, but not being run correctly"); + return false; + } + d->m_socket = FCGI_LISTENSOCK_FILENO; + } + else + { + Q_ASSERT(type == TcpSocket); + // SOCK_STREAM specifies TCP instead of UDP + d->m_socket = ::socket(AF_INET, SOCK_STREAM, 0); + const in_port_t port = static_cast(parameter); + if(port == 0) + { + qWarning("Configured to listen on TCP, but there isn't a valid Port Number configured. Try --configure-fastcgi"); + return false; + } + + // Initialise the socket address structure + sockaddr_in sa; + ::memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = qToBigEndian(port); + + int one = 1; + if(setsockopt(d->m_socket, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) + { + qWarning("Failed to set SO_REUSEADDR option - error: %s", ::strerror(errno)); + } + // Try and bind to the port + if(::bind(d->m_socket, reinterpret_cast(&sa), sizeof(sa)) == -1) + { + qWarning("Failed to bind() to TCP port %d with error: %s", port, ::strerror(errno)); + return false; + } + // Now we've bound to the port, start listening + if(::listen(d->m_socket, 1) == -1) + { + qWarning("Failed to listen() on port %d with error: %s", port, ::strerror(errno)); + return false; + } + } + + d->m_socketNotifier = new QSocketNotifier(d->m_socket, QSocketNotifier::Read, this), + connect( + d->m_socketNotifier, + SIGNAL(activated(int)), + this, + SIGNAL(newConnection()) + ); + + return true; + } + + SocketServer::SocketType SocketServer::socketType() const + { + return d->m_socketType; + } + + QTcpSocket* SocketServer::nextPendingConnection() + { + // Initialise socket address structure + sockaddr_un sa; + socklen_t len = sizeof(sa); + ::memset(&sa, 0, len); + + // Listen on the socket + d->lockSocket(d->m_socket); + const int newSocket = ::accept(d->m_socket, reinterpret_cast(&sa), &len); + d->releaseSocket(d->m_socket); + + if(newSocket == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) + { + return 0; + } + else + { + QTcpSocket* socket = new QTcpSocket(this); + socket->setSocketDescriptor(newSocket); + return socket; + } + } + + SocketServer::SocketTypes SocketServer::supportedSocketTypes() + { + return TcpSocket | UnixSocket; + } + + SocketServer::SocketServer(QObject* parent) + : QObject(parent) + , d(new SocketServer::Private) + { + d->m_socketNotifier = 0; + } + + SocketServer::~SocketServer() + { + if(d->m_socketNotifier) + { + Q_ASSERT(d->m_socket == d->m_socketNotifier->socket()); + // stop listening + ::close(d->m_socket); + // stop watching + d->m_socketNotifier->setEnabled(false); + } + delete d; + } +}; diff --git a/pool/shard007/C++/0096247_control_loiter.cpp b/pool/shard007/C++/0096247_control_loiter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b2bb6bd464e10d7097376c4c6d5a89e7bed7a30 --- /dev/null +++ b/pool/shard007/C++/0096247_control_loiter.cpp @@ -0,0 +1,149 @@ +/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- + +#include "Copter.h" + +/* + * control_loiter.pde - init and run calls for loiter flight mode + */ + +// loiter_init - initialise loiter controller +bool Copter::loiter_init(bool ignore_checks) +{ + if (position_ok() || ignore_checks) { + + // set target to current position + wp_nav.init_loiter_target(); + + // initialize vertical speed and accelerationj + pos_control.set_speed_z(-g.pilot_velocity_z_max, g.pilot_velocity_z_max); + pos_control.set_accel_z(g.pilot_accel_z); + + // initialise position and desired velocity + pos_control.set_alt_target(inertial_nav.get_altitude()); + pos_control.set_desired_velocity_z(inertial_nav.get_velocity_z()); + + return true; + }else{ + return false; + } +} + +// loiter_run - runs the loiter controller +// should be called at 100hz or more +void Copter::loiter_run() +{ + LoiterModeState loiter_state; + float target_yaw_rate = 0.0f; + float target_climb_rate = 0.0f; + float takeoff_climb_rate = 0.0f; + + // process pilot inputs unless we are in radio failsafe + if (!failsafe.radio) { + // apply SIMPLE mode transform to pilot inputs + update_simple_mode(); + + // process pilot's roll and pitch input + wp_nav.set_pilot_desired_acceleration(channel_roll->control_in, channel_pitch->control_in); + + // get pilot's desired yaw rate + target_yaw_rate = get_pilot_desired_yaw_rate(channel_yaw->control_in); + + // get pilot desired climb rate + target_climb_rate = get_pilot_desired_climb_rate(channel_throttle->control_in); + target_climb_rate = constrain_float(target_climb_rate, -g.pilot_velocity_z_max, g.pilot_velocity_z_max); + } else { + // clear out pilot desired acceleration in case radio failsafe event occurs and we do not switch to RTL for some reason + wp_nav.clear_pilot_desired_acceleration(); + } + + // relax loiter target if we might be landed + if (ap.land_complete_maybe) { + wp_nav.loiter_soften_for_landing(); + } + + // Loiter State Machine Determination + if(!ap.auto_armed || !motors.get_interlock()) { + loiter_state = Loiter_Disarmed; + } else if (takeoff_state.running || (ap.land_complete && (channel_throttle->control_in > get_takeoff_trigger_throttle()))){ + loiter_state = Loiter_Takeoff; + } else if (ap.land_complete){ + loiter_state = Loiter_Landed; + } else { + loiter_state = Loiter_Flying; + } + + // Loiter State Machine + switch (loiter_state) { + + case Loiter_Disarmed: + + wp_nav.init_loiter_target(); +#if FRAME_CONFIG == HELI_FRAME // Helicopters always stabilize roll/pitch/yaw + // call attitude controller + attitude_control.angle_ef_roll_pitch_rate_ef_yaw_smooth(0, 0, 0, get_smoothing_gain()); + attitude_control.set_throttle_out(0,false,g.throttle_filt); +#else // multicopters do not stabilize roll/pitch/yaw when disarmed + attitude_control.set_throttle_out_unstabilized(0,true,g.throttle_filt); +#endif // HELI_FRAME + pos_control.relax_alt_hold_controllers(get_throttle_pre_takeoff(channel_throttle->control_in)-throttle_average); + break; + + case Loiter_Takeoff: + + if (!takeoff_state.running) { + takeoff_timer_start(constrain_float(g.pilot_takeoff_alt,0.0f,1000.0f)); + // indicate we are taking off + set_land_complete(false); + // clear i term when we're taking off + set_throttle_takeoff(); + } + + // get takeoff adjusted pilot and takeoff climb rates + takeoff_get_climb_rates(target_climb_rate, takeoff_climb_rate); + + // run loiter controller + wp_nav.update_loiter(ekfGndSpdLimit, ekfNavVelGainScaler); + + // call attitude controller + attitude_control.angle_ef_roll_pitch_rate_ef_yaw(wp_nav.get_roll(), wp_nav.get_pitch(), target_yaw_rate); + + // update altitude target and call position controller + pos_control.set_alt_target_from_climb_rate_ff(target_climb_rate, G_Dt, false); + pos_control.add_takeoff_climb_rate(takeoff_climb_rate, G_Dt); + pos_control.update_z_controller(); + break; + + case Loiter_Landed: + + wp_nav.init_loiter_target(); +#if FRAME_CONFIG == HELI_FRAME // Helicopters always stabilize roll/pitch/yaw + // call attitude controller + attitude_control.angle_ef_roll_pitch_rate_ef_yaw_smooth(0, 0, 0, get_smoothing_gain()); + attitude_control.set_throttle_out(get_throttle_pre_takeoff(channel_throttle->control_in),false,g.throttle_filt); +#else // multicopters do not stabilize roll/pitch/yaw when disarmed + // move throttle to between minimum and non-takeoff-throttle to keep us on the ground + attitude_control.set_throttle_out_unstabilized(get_throttle_pre_takeoff(channel_throttle->control_in),true,g.throttle_filt); +#endif + pos_control.relax_alt_hold_controllers(get_throttle_pre_takeoff(channel_throttle->control_in)-throttle_average); + break; + + case Loiter_Flying: + + // run loiter controller + wp_nav.update_loiter(ekfGndSpdLimit, ekfNavVelGainScaler); + + // call attitude controller + attitude_control.angle_ef_roll_pitch_rate_ef_yaw(wp_nav.get_roll(), wp_nav.get_pitch(), target_yaw_rate); + + // run altitude controller + if (sonar_enabled && (sonar_alt_health >= SONAR_ALT_HEALTH_MAX)) { + // if sonar is ok, use surface tracking + target_climb_rate = get_surface_tracking_climb_rate(target_climb_rate, pos_control.get_alt_target(), G_Dt); + } + + // update altitude target and call position controller + pos_control.set_alt_target_from_climb_rate_ff(target_climb_rate, G_Dt, false); + pos_control.update_z_controller(); + break; + } +} diff --git a/pool/shard007/C++/0096253_priority_queue.cpp b/pool/shard007/C++/0096253_priority_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4f42b2bc3dedda98536086cd762424125af3b41 --- /dev/null +++ b/pool/shard007/C++/0096253_priority_queue.cpp @@ -0,0 +1,64 @@ +#include "priority_queue.h" +#include "priority_queue-inl.h" + +#include "urlearning/base/node.h" + +#define __STDC_FORMAT_MACROS +#include + +PriorityQueue::PriorityQueue() { + // nothing to init +} + +PriorityQueue::~PriorityQueue() { + //clear(); +} + +void PriorityQueue::clear() { + printf("Clearing the priority queue\n"); + for (Node *n : pq_) { + printf("pq deleting node: '%s'\n", varsetToString(n->getSubnetwork()).c_str()); + if (n != NULL) { + printf("the node was not null\n"); + delete n; + printf("the node was deleted\n"); + } + } + printf("the pq is completely clear\n"); + + pq_.clear(); +} + +void PriorityQueue::clearNoDelete() { + pq_.clear(); +} + +void PriorityQueue::push(Node* n) { + pq_.push_back(n); + priority_queue::push_heap(pq_.begin(), pq_.end(), cns, 0); +} + +Node* PriorityQueue::pop() { + Node *ret = pq_.front(); + priority_queue::pop_heap(pq_.begin(), pq_.end(), cns, 0); + pq_.pop_back(); + return ret; +} + +Node* PriorityQueue::peek() { + Node *ret = pq_.front(); + return ret; +} + +/** + * This method assumes the node n is in the priority queue, + * and that it has been given a better priority (f value). + * (So n->getPqPos() gives the position of n in the array representing the heap. + * It adjusts the heap accordingly. + * + * @param n the node + */ +void PriorityQueue::update(Node *n) { + std::vector::iterator itN = pq_.begin() + n->getPqPos(); + priority_queue::update_heap_pos(pq_.begin(), pq_.end(), itN, cns); +} diff --git a/pool/shard007/C++/0096255_UCaMDb.cpp b/pool/shard007/C++/0096255_UCaMDb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af3d732b91d5b0abbd4c3816ccf9ad966a0de479 --- /dev/null +++ b/pool/shard007/C++/0096255_UCaMDb.cpp @@ -0,0 +1,93 @@ +//================================================================================================= +/*! +// \file src/mathtest/smatdmatadd/UCaMDb.cpp +// \brief Source file for the UCaMDb sparse matrix/dense matrix addition math test +// +// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved +// +// This file is part of the Blaze library. You can redistribute it and/or modify it under +// the terms of the New (Revised) BSD License. Redistribution and use in source and binary +// forms, with or without modification, are permitted provided that the following conditions +// are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other materials +// provided with the distribution. +// 3. Neither the names of the Blaze development group 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. +*/ +//================================================================================================= + + +//************************************************************************************************* +// Includes +//************************************************************************************************* + +#include +#include +#include +#include +#include +#include +#include +#include + + +//================================================================================================= +// +// MAIN FUNCTION +// +//================================================================================================= + +//************************************************************************************************* +int main() +{ + std::cout << " Running 'UCaMDb'..." << std::endl; + + using blazetest::mathtest::TypeA; + using blazetest::mathtest::TypeB; + + try + { + // Matrix type definitions + typedef blaze::UpperMatrix< blaze::CompressedMatrix > UCa; + typedef blaze::DynamicMatrix MDb; + + // Creator type definitions + typedef blazetest::Creator CUCa; + typedef blazetest::Creator CMDb; + + // Running tests with small matrices + for( size_t i=0UL; i<=6UL; ++i ) { + for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) { + RUN_SMATDMATADD_OPERATION_TEST( CUCa( i, j ), CMDb( i, i ) ); + } + } + + // Running tests with large matrices + RUN_SMATDMATADD_OPERATION_TEST( CUCa( 67UL, 7UL ), CMDb( 67UL, 67UL ) ); + RUN_SMATDMATADD_OPERATION_TEST( CUCa( 128UL, 16UL ), CMDb( 128UL, 128UL ) ); + } + catch( std::exception& ex ) { + std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix addition:\n" + << ex.what() << "\n"; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} +//************************************************************************************************* diff --git a/pool/shard007/C++/0096256_ping.cpp b/pool/shard007/C++/0096256_ping.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01da87b68c7baf9dc5a038514cf9a90456e2618b --- /dev/null +++ b/pool/shard007/C++/0096256_ping.cpp @@ -0,0 +1,196 @@ +#include +#include +#include +#include + +#include +#include + +#include "nlohmann/json.hpp" + +#include "logp/cmd/ping.h" +#include "logp/websocket.h" +#include "logp/util.h" + + +namespace logp { namespace cmd { + + +const char *ping::usage() { + static const char *u = + "logp ping [options]\n" + " -c/--count Number of pings to send\n" + ; + + return u; +} + +const char *ping::getopt_string() { return "c:"; } + +struct option *ping::get_long_options() { + static struct option opts[] = { + {"count", required_argument, 0, 'c'}, + {0, 0, 0, 0} + }; + + return opts; +} + +void ping::process_option(int arg, int, char *optarg) { + switch (arg) { + case 'c': + { + long c = atol(optarg); + if (c <= 0) throw logp::error("bad value for count"); + count = c; + } + break; + + case 0: + break; + }; +} + + + +std::string format_ms(int64_t time_us) { + double d = time_us / 1000.0; + char buf[100]; + + snprintf(buf, sizeof(buf), "%.1f", d); + + return std::string(buf); +} + + +std::string format_time(uint64_t time_us) { + time_t secs = time_us / 1000000; + uint64_t usecs = time_us - ((uint64_t)secs * 1000000); + char buf[100]; + struct tm tm; + + localtime_r(&secs, &tm); + + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S.", &tm); + + std::string output(buf); + + snprintf(buf, sizeof(buf), "%06g ", (double)usecs); + output += buf; + + strftime(buf, sizeof(buf), "%Z", &tm); + output += buf; + + return output; +} + + +std::string format_ping_delta(uint64_t local_start, uint64_t local_end, uint64_t remote) { + uint64_t d = local_end - local_start; + d /= 2; + d += local_start; + int64_t delta = (int64_t)remote - d; + std::string output = format_ms(delta) + "ms"; + if (std::abs(delta) >= 1000000) return logp::util::colour_red(output); + return output; +} + + +void ping::execute() { + logp::websocket::worker ws_worker; + + std::cout << "Connecting to:\n"; + std::cout << " URI: " << ws_worker.uri << "\n"; + if (ws_worker.uri.substr(0, 4) == "wss:") { + if (ws_worker.tls_no_verify) std::cout << logp::util::colour_red(" TLS Verification OFF!\n"); + } else if (ws_worker.uri.substr(0, 3) == "ws:") { + std::cout << logp::util::colour_red(" Plain-text connection (not wss://)!\n"); + } + std::cout << " Key: " << ws_worker.token.substr(0, 4) << "******************\n"; + std::cout << std::endl; + + uint64_t pings_left = count; + + std::function send_ping = [&]() { + { + uint64_t start = logp::util::curr_time(); + + logp::websocket::request_png r; + r.on_pong = [&, start](nlohmann::json &res){ + uint64_t end = logp::util::curr_time(); + + uint64_t server_time = res["time"]; + std::cout << "PONG rtt=" << format_ms(end-start) << "ms clock_skew=" << format_ping_delta(start, end, server_time) << std::endl; + if (pings_left == 1) exit(0); + else if (pings_left > 1) pings_left--; + + logp::util::sleep_seconds(1); + send_ping(); + }; + + ws_worker.push_move_new_request(r); + } + }; + + uint64_t ini_start = logp::util::curr_time(); + + ws_worker.on_ini_response = [&](nlohmann::json &r){ + uint64_t ini_end = logp::util::curr_time(); + + if (r["ini"] == "ok") { + uint64_t prot = r["prot"]; + uint64_t time = r["time"]; + + std::cout << "Connection info:\n"; + std::cout << " Established in: " << format_ms(ini_end-ini_start) << "ms\n"; + std::cout << " Logp Protocol: " << prot << "\n"; + std::cout << " Remote clock: " << format_time(time) << "\n"; + std::cout << std::endl; + + uint64_t perm = r["perm"]; + + std::cout << "Access permissions:\n"; + if (perm == 0) { + std::cout << logp::util::colour_red(" Permissions: NONE (exiting)\n"); + exit(1); + } + std::string perm_str; + if (perm & 1) perm_str += " READ"; + if (perm & 2) perm_str += " WRITE"; + std::cout << " Permissions:" << perm_str << "\n"; + std::cout << std::endl; + + send_ping(); + } else { + PRINT_ERROR << "ini request failed"; + exit(1); + } + }; + + int retries = 3; + + ws_worker.on_disconnect = [&](std::string reason){ + std::string msg = "Connection failure: "; + msg += reason; + + retries--; + + if (retries > 0) { + msg += " [retrying "; + msg += std::to_string(retries); + msg += " more times]"; + } else { + msg += " [aborting]"; + } + + PRINT_ERROR << msg; + + if (retries <= 0) exit(1); + }; + + ws_worker.run(); + + logp::util::sleep_forever(); +} + +}} diff --git a/pool/shard007/C++/0096261_Preferences.cpp b/pool/shard007/C++/0096261_Preferences.cpp new file mode 100644 index 0000000000000000000000000000000000000000..218a0f6ec58237e28c7a0f8dcd963b929f4ea0ae --- /dev/null +++ b/pool/shard007/C++/0096261_Preferences.cpp @@ -0,0 +1,136 @@ +/** + * \brief Methods for the Preferences class. + * + * Copyright (c) 2009-2010 by R. Douglas Barbieri + * + * The source code in this file ("Source Code") is provided by R. Douglas Barbieri + * to you under the terms of the GNU General Public License, version 2.0 + * ("GPL"). Terms of the GPL can be found in doc/GPL-license.txt in this distribution. + * + * By copying, modifying or distributing this software, you acknowledge + * that you have read and understood your obligations described above, + * and agree to abide by those obligations. + * + * ALL SOURCE CODE IN THIS DISTRIBUTION IS PROVIDED "AS IS." THE AUTHOR MAKES NO + * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, + * COMPLETENESS OR PERFORMANCE. + */ + +#include "LLChatLib.h" + +#include "Preferences.h" +#include "Common.h" +#include "Utility.h" + +#include +#include +#include + +Preferences::Preferences( QWidget* parent ) + : QDialog(parent) + , m_ui(new Ui_Preferences) +{ + m_ui->setupUi(this); + + FillLanguageList(); + + QSettings settings; + settings.beginGroup( GUI_SECTION ); + m_font.fromString( settings.value( GUIFONT, font().toString() ).toString() ); + SetFontString(); + settings.endGroup(); + // + LLC::Manager llmgr; + m_ui->m_persistImHistory ->setChecked ( llmgr.GetBool( PERSISTIM ) ); + m_ui->m_persistLcHistory ->setChecked ( llmgr.GetBool( PERSISTLC ) ); + m_ui->m_showTimestamps ->setChecked ( llmgr.GetBool( TIMESTAMPS ) ); + m_ui->m_ignoreAllGroupCheckBox ->setChecked ( llmgr.GetBool( IGNORE_GROUP_IMS ) ); + m_ui->m_localLanguage ->setCurrentIndex ( llmgr.GetUInt( LOCAL_LANGUAGE ) ); + m_ui->m_enableGoogleTranslate ->setChecked ( llmgr.GetBool( GOOGLE_XLATE ) ); + m_ui->m_echoSourceLanguage ->setChecked ( llmgr.GetBool( ECHO_SOURCE ) ); +} + + +Preferences::~Preferences() +{ + delete m_ui; +} + + +void Preferences::SetFontString() +{ + QString name = tr("%1, %2").arg(m_font.family()).arg(m_font.pointSize()); + m_ui->m_fontEditBox->setText( name ); +} + +void Preferences::OnAccepted() +{ + // Persist settings + // + QSettings settings; + settings.beginGroup( GUI_SECTION ); + QString fontName = m_font.toString(); + settings.setValue( GUIFONT , fontName ); + settings.endGroup(); + settings.sync(); + // + LLC::Manager llmgr; + const int langIdx = m_ui->m_localLanguage->currentIndex(); + const QString lang_code = m_langIdList[langIdx]; + llmgr.SetBool ( PERSISTIM , m_ui->m_persistImHistory ->isChecked () ); + llmgr.SetBool ( PERSISTLC , m_ui->m_persistLcHistory ->isChecked () ); + llmgr.SetBool ( TIMESTAMPS , m_ui->m_showTimestamps ->isChecked () ); + llmgr.SetBool ( IGNORE_GROUP_IMS , m_ui->m_ignoreAllGroupCheckBox ->isChecked () ); + llmgr.SetUInt ( LOCAL_LANGUAGE , langIdx ); + llmgr.SetString ( LOCAL_LANGUAGE_CODE , Q2LS(lang_code) ); + llmgr.SetBool ( GOOGLE_XLATE , m_ui->m_enableGoogleTranslate ->isChecked () ); + llmgr.SetBool ( ECHO_SOURCE , m_ui->m_echoSourceLanguage ->isChecked () ); + // + // + accept(); + + // Set into LLChatLib + // + LLC::Manager mgr; + mgr.SetTranslateMessages( m_ui->m_enableGoogleTranslate->isChecked() ); + mgr.SetLanguage( lang_code == "sys"? Q2LS(GetSystemLangCode()): Q2LS(lang_code) ); +} + + +void Preferences::OnFontButtonClicked() +{ + bool ok; + QFont font = QFontDialog::getFont( &ok, m_font ); + // + if( ok ) + { + m_font = font; + SetFontString(); + } +} + + +void Preferences::FillLanguageList() +{ + Common::QStringMap supported_langs = Common::GetLanguageMap(); + // + Common::QStringMap::iterator iter = supported_langs.begin(); + const Common::QStringMap::iterator end = supported_langs.end(); + // + m_langIdList.push_back( "sys" ); + // + for( ; iter != end; ++iter ) + { + QString code = iter->first; + QString lang = iter->second; + // + if( code != "???" ) + { + m_ui->m_localLanguage->addItem( lang, code ); + m_langIdList.push_back( code ); + } + } +} + + +// vim: ts=4 sw=4 noexpandtab syntax=cpp.doxygen diff --git a/pool/shard007/C++/0096266_json_types.cpp b/pool/shard007/C++/0096266_json_types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc9173e56db8ccd8c6ffd0aef1008e261cec994a --- /dev/null +++ b/pool/shard007/C++/0096266_json_types.cpp @@ -0,0 +1,131 @@ +#include "json/tree.hpp" + +#include "debug.hpp" +#include "maths.hpp" +#include "tap.hpp" + +#include +#include + +int +main (void) +{ + util::TAP::logger tap; + + static const std::string TEST_STRING = R"_( + { + "string":"brad", + "integer":1, + "null":null, + "false":false, + "true":true, + "double":3.14, + "object":{ + "test": "test" + }, + "array":[ + 1, 2, 3, 4 + ] + })_"; + + std::unique_ptr ptr = json::tree::parse (util::make_view (TEST_STRING)); + tap.expect (ptr->is_object (), "is_object"); + CHECK (ptr->is_object ()); + + const json::tree::node &ref = *ptr; + + { + tap.expect ( ref["string"].is_string (), "string is_string"); + tap.expect (!ref["string"].is_array (), "string not is_array"); + tap.expect (!ref["string"].is_boolean (), "string not is_boolean"); + tap.expect (!ref["string"].is_null (), "string not is_null"); + tap.expect (!ref["string"].is_number (), "string not is_number"); + tap.expect (!ref["string"].is_object (), "string not is_object"); + + tap.expect_eq (ref["string"].as_string (), "brad", "string value equality"); + } + + { + tap.expect ( ref["integer"].is_number (), "integer is_number"); + tap.expect (!ref["integer"].is_array (), "integer not is_array"); + tap.expect (!ref["integer"].is_boolean (), "integer not is_boolean"); + tap.expect (!ref["integer"].is_null (), "integer not is_null"); + tap.expect (!ref["integer"].is_object (), "integer not is_object"); + tap.expect (!ref["integer"].is_string (), "integer not is_string"); + tap.expect ( + util::exactly_equal ( + (unsigned)ref["integer"].as_number ().as_uint (), + 1u + ), + "integer value equality" + ); + } + + { + tap.expect ( ref["null"].is_null (), "null is_null"); + tap.expect (!ref["null"].is_array (), "null not is_array"); + tap.expect (!ref["null"].is_boolean (), "null not is_boolean"); + tap.expect (!ref["null"].is_number (), "null not is_number"); + tap.expect (!ref["null"].is_object (), "null not is_object"); + tap.expect (!ref["null"].is_string (), "null not is_string"); + } + + { + tap.expect ( ref["false"].is_boolean (), "false is_boolean"); + tap.expect (!ref["false"].is_array (), "false not is_array"); + tap.expect (!ref["false"].is_null (), "false not is_null"); + tap.expect (!ref["false"].is_number (), "false not is_number"); + tap.expect (!ref["false"].is_object (), "false not is_object"); + tap.expect (!ref["false"].is_string (), "false not is_string"); + + tap.expect_eq (ref["false"].as_boolean (), false, "false value equality"); + } + + { + tap.expect ( ref["true"].is_boolean (), "true, is_boolean"); + tap.expect (!ref["true"].is_array (), "true not is_array"); + tap.expect (!ref["true"].is_null (), "true not is_null"); + tap.expect (!ref["true"].is_number (), "true not is_number"); + tap.expect (!ref["true"].is_object (), "true not is_object"); + tap.expect (!ref["true"].is_string (), "true not is_string"); + + tap.expect_eq ( ref["true"].as_boolean (), true, "true value equality"); + } + + { + tap.expect ( ref["double"].is_number (), "double is_number"); + + tap.expect (!ref["double"].is_array (), "double not is_array"); + tap.expect (!ref["double"].is_boolean (), "double not is_boolean"); + tap.expect (!ref["double"].is_null (), "double not is_null"); + tap.expect (!ref["double"].is_object (), "double not is_object"); + tap.expect (!ref["double"].is_string (), "double not is_string"); + tap.expect ( + util::exactly_equal ( + ref["double"].as_number ().as (), + 3.14 + ), + "double value equality" + ); + } + + { + tap.expect ( ref["object"].is_object (), "object is_object"); + tap.expect (!ref["object"].is_array (), "object not is_array"); + tap.expect (!ref["object"].is_boolean (), "object not is_boolean"); + tap.expect (!ref["object"].is_null (), "object not is_null"); + tap.expect (!ref["object"].is_number (), "object not is_number"); + tap.expect (!ref["object"].is_string (), "object not is_string"); + } + + { + tap.expect ( ref["array"].is_array (), "array is_array"); + tap.expect (!ref["array"].is_boolean (), "array not is_boolean"); + tap.expect (!ref["array"].is_null (), "array not is_null"); + tap.expect (!ref["array"].is_number (), "array not is_number"); + tap.expect (!ref["array"].is_object (), "array not is_object"); + tap.expect (!ref["array"].is_string (), "array not is_string"); + } + + return tap.status (); +} diff --git a/pool/shard007/C++/0096271_CanvasState.cpp b/pool/shard007/C++/0096271_CanvasState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cf46af852e84bece4aa6982ae8533c25fcd6a0e --- /dev/null +++ b/pool/shard007/C++/0096271_CanvasState.cpp @@ -0,0 +1,83 @@ +/*************************************************************** + * Name: CanvasState.cpp + * Purpose: Implements container for stored canvas state + * Author: Michal Bližňák (michal.bliznak@tiscali.cz) + * Created: 2007-07-22 + * Copyright: Michal Bližňák + * License: wxWidgets license (www.wxwidgets.org) + * Notes: + **************************************************************/ + +#include "wx_pch.h" + +#ifdef _DEBUG_MSVC +#define new DEBUG_NEW +#endif + +#include + +#include "wx/wxsf/CanvasState.h" +#include "wx/wxsf/ShapeCanvas.h" + +#include + +WX_DEFINE_LIST(StateList); + +wxSFCanvasState::wxSFCanvasState(wxStreamBuffer *data) +{ + // copy content of stream buffer to local memory buffer + if(data) + { + data->ResetBuffer(); + m_dataBuffer.AppendData(data->GetBufferStart(), data->GetDataLeft()); + m_dataBuffer.AppendByte(0); + } + + m_pDataManager = NULL; +} + +wxSFCanvasState::wxSFCanvasState(wxSFDiagramManager *data) +{ + wxASSERT(data); + + m_pDataManager = data; +} + +wxSFCanvasState::~wxSFCanvasState(void) +{ + if( m_pDataManager) + { + delete m_pDataManager; + } +} + +//----------------------------------------------------------------------------------// +// Public functions +//----------------------------------------------------------------------------------// + +void wxSFCanvasState::Restore(wxSFShapeCanvas* canvas) +{ + wxASSERT(canvas); + wxASSERT(canvas->GetDiagramManager()); + + if( m_pDataManager ) + { + // copy content of stored temporal data manager into the currently used one + canvas->GetDiagramManager()->CopyItems(*m_pDataManager); + canvas->Refresh(false); + } + else + { + // create input stream from local memory buffer + wxMemoryInputStream instream(m_dataBuffer.GetData(), m_dataBuffer.GetDataLen()-1); + + // deserialize canvas content + if(instream.IsOk() && canvas && canvas->GetDiagramManager()) + { + // clear all previous canvas content + canvas->GetDiagramManager()->Clear(); + canvas->GetDiagramManager()->DeserializeFromXml(instream); + canvas->Refresh(false); + } + } +} diff --git a/pool/shard007/C++/0096275_convert_graphdef_memmapped_format_lib.cc b/pool/shard007/C++/0096275_convert_graphdef_memmapped_format_lib.cc new file mode 100644 index 0000000000000000000000000000000000000000..9675428e56e93c9669753371dbca47d56325b0c4 --- /dev/null +++ b/pool/shard007/C++/0096275_convert_graphdef_memmapped_format_lib.cc @@ -0,0 +1,175 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "tensorflow/contrib/util/convert_graphdef_memmapped_format_lib.h" + +#include +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/immutable_constant_op.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/util/memmapped_file_system_writer.h" + +namespace tensorflow { +namespace { +class NodeConverter { + public: + // Converts one node. In-place updates node_def, writes the tensor in + // memmapped + // format, using writer. If the conversion has been done, convert_counter is + // increased. + Status ConvertConstantsToImmutable(NodeDef* node_def, + MemmappedFileSystemWriter* writer, + int* convert_counter, + int min_conversion_size_bytes) { + // Check the size. + const AttrValue& value = node_def->attr().at("value"); + const TensorProto& tensor_proto = value.tensor(); + + // Create copies of tensor datatype and shape, to put into the operator + // after + // the tensor is destroyed. + const DataType tensor_data_type = tensor_proto.dtype(); + const TensorShapeProto tensor_shape = tensor_proto.tensor_shape(); + + // Check that the tensor type is POD, only these types are supported for + // memmapping. + // DataType enum is explicitly converted to int to avoid errors with passing + // enum type are a parameter type to std::unordered_set. + static std::unordered_set supported_types{ +#define TYPE_FOR_SET(type) static_cast(DataTypeToEnum::value), + TF_CALL_POD_TYPES(TYPE_FOR_SET) +#undef ADD_TYPE + }; + + if (supported_types.count(static_cast(tensor_data_type)) == 0) { + return Status::OK(); + } + + // Create Tensor from value and write it in memmapped format. + Tensor parsed(tensor_proto.dtype()); + if (!parsed.FromProto(cpu_allocator(), tensor_proto)) { + return errors::InvalidArgument("Cannot parse tensor from proto: ", + tensor_proto.DebugString()); + } + if (parsed.TotalBytes() < static_cast(min_conversion_size_bytes)) { + return Status::OK(); + } + + const string memmapped_region_name = + MemmappedFileSystem::kMemmappedPackagePrefix + + ConvertVariableNameToUniqueRegionName(node_def->name()); + + TF_RETURN_IF_ERROR(writer->SaveTensor(parsed, memmapped_region_name)); + + node_def->set_op("ImmutableConst"); + + // Erase all attributes and leave only attributes that can be understood by + // ImmutableConst. + auto* mutable_attr = node_def->mutable_attr(); + mutable_attr->clear(); + + { + AttrValue attr_value; + attr_value.set_type(tensor_data_type); + mutable_attr->insert({ImmutableConstantOp::kDTypeAttr, attr_value}); + } + { + AttrValue attr_value; + *(attr_value.mutable_shape()) = tensor_shape; + mutable_attr->insert({ImmutableConstantOp::kShapeAttr, attr_value}); + } + { + AttrValue attr_value; + attr_value.set_s(memmapped_region_name); + mutable_attr->insert( + {ImmutableConstantOp::kMemoryRegionNameAttr, attr_value}); + } + ++*convert_counter; + return Status::OK(); + } + + private: + string ConvertVariableNameToUniqueRegionName(const string& variable_name) { + string region_name = SanitizeVariableName(variable_name); + while (!used_names_.insert(region_name).second) { + region_name += '_'; + } + return region_name; + } + + static string SanitizeVariableName(const string& variable_name) { + string result; + for (char c : variable_name) { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '_' || c == '.') { + result += c; + } else { + result += '_'; + } + } + return result; + } + std::unordered_set used_names_; +}; + +} // namespace + +// Loads the graph, replaces operators, and writes it out. +Status ConvertConstantsToImmutable(const string& in_graph_filename, + const string& out_graph_filename, + int min_conversion_size_bytes) { + Env* default_env = Env::Default(); + GraphDef graph_def; + const auto load_graph_status = + ReadBinaryProto(default_env, in_graph_filename, &graph_def); + if (!load_graph_status.ok()) { + return tensorflow::errors::NotFound( + "Failed to load graph at '", in_graph_filename, + "' : ", load_graph_status.error_message()); + } + + NodeConverter node_converter; + + // Create output writer. + MemmappedFileSystemWriter writer; + TF_RETURN_IF_ERROR(writer.InitializeToFile(default_env, out_graph_filename)); + + // Iterate over graph nodes, looking for Const and replacing it with + // ImmutableConst. + int convert_counter = 0; + for (int i = 0; i < graph_def.node_size(); ++i) { + const NodeDef& node = graph_def.node(i); + if (node.op() == "Const") { + // Try to convert to ImmutableConst + TF_RETURN_IF_ERROR(node_converter.ConvertConstantsToImmutable( + graph_def.mutable_node(i), &writer, &convert_counter, + min_conversion_size_bytes)); + } + } + TF_RETURN_IF_ERROR(writer.SaveProtobuf( + graph_def, MemmappedFileSystem::kMemmappedPackageDefaultGraphDef)); + TF_RETURN_IF_ERROR(writer.FlushAndClose()); + LOG(INFO) << "Converted " << convert_counter << " nodes"; + return Status::OK(); +} + +} // namespace tensorflow diff --git a/pool/shard007/C++/0096277_1.cc b/pool/shard007/C++/0096277_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..0604d4cc37b02e73e07191a4efcfd7e87d309472 --- /dev/null +++ b/pool/shard007/C++/0096277_1.cc @@ -0,0 +1,94 @@ +// { dg-options "-std=gnu++11" } +// 2005-01-15 Douglas Gregor +// +// Copyright (C) 2005-2015 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// 20.7.15 polymorphic function object wrapper +#include +#include + +using namespace __gnu_test; + +bool test __attribute__((unused)) = true; + +// Operations on empty function<> objects +void test01() +{ + using std::function; + using std::bad_function_call; + + // Default-construction + function f1; + VERIFY( ((bool)f1 == false) ); + VERIFY( !f1 ); + VERIFY( f1 == 0 ); + VERIFY( 0 == f1 ); + VERIFY( !(f1 != 0) ); + VERIFY( !(0 != f1) ); + + // Copy-construction + function f2(f1); + VERIFY( !f2 ); + + // Construct with NULL pointer + function f3(0); + VERIFY( !f3 ); + + // Assignment + f1 = f2; + VERIFY( !f1); + + // Assignment to NULL pointer + f1 = 0; + VERIFY( !f1 ); + + // Swap + swap(f1, f2); + VERIFY( !f1 ); + VERIFY( !f2 ); + + // Invocation should throw bad_function_call + bool thrown = false; + try + { + f1(3.14159f); + VERIFY( false ); + } + catch (bad_function_call) + { + thrown = true; + } + VERIFY( thrown ); + + // target_type returns typeid(void) + VERIFY( f1.target_type() == typeid(void) ); + + // target() always returns a NULL pointer + VERIFY( f1.target() == 0); + + // Check const version + const function& f1c = f1; + VERIFY( f1c.target() == 0 ); + VERIFY( !f1c ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard007/C++/0096281_wifi-ap.cc b/pool/shard007/C++/0096281_wifi-ap.cc new file mode 100644 index 0000000000000000000000000000000000000000..e825c09687fcaaa91186013e3c4ba8b781037ea5 --- /dev/null +++ b/pool/shard007/C++/0096281_wifi-ap.cc @@ -0,0 +1,196 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2005,2006,2007 INRIA + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * 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 + * + * Author: Mathieu Lacage + */ + + +#include "ns3/core-module.h" +#include "ns3/network-module.h" +#include "ns3/applications-module.h" +#include "ns3/mobility-module.h" +#include "ns3/config-store-module.h" +#include "ns3/wifi-module.h" +#include "ns3/athstats-helper.h" + +#include + +using namespace ns3; + +static bool g_verbose = true; + +void +DevTxTrace (std::string context, Ptr p) +{ + if (g_verbose) + { + std::cout << " TX p: " << *p << std::endl; + } +} +void +DevRxTrace (std::string context, Ptr p) +{ + if (g_verbose) + { + std::cout << " RX p: " << *p << std::endl; + } +} +void +PhyRxOkTrace (std::string context, Ptr packet, double snr, WifiMode mode, enum WifiPreamble preamble) +{ + if (g_verbose) + { + std::cout << "PHYRXOK mode=" << mode << " snr=" << snr << " " << *packet << std::endl; + } +} +void +PhyRxErrorTrace (std::string context, Ptr packet, double snr) +{ + if (g_verbose) + { + std::cout << "PHYRXERROR snr=" << snr << " " << *packet << std::endl; + } +} +void +PhyTxTrace (std::string context, Ptr packet, WifiMode mode, WifiPreamble preamble, uint8_t txPower) +{ + if (g_verbose) + { + std::cout << "PHYTX mode=" << mode << " " << *packet << std::endl; + } +} +void +PhyStateTrace (std::string context, Time start, Time duration, enum WifiPhy::State state) +{ + if (g_verbose) + { + std::cout << " state=" << state << " start=" << start << " duration=" << duration << std::endl; + } +} + +static void +SetPosition (Ptr node, Vector position) +{ + Ptr mobility = node->GetObject (); + mobility->SetPosition (position); +} + +static Vector +GetPosition (Ptr node) +{ + Ptr mobility = node->GetObject (); + return mobility->GetPosition (); +} + +static void +AdvancePosition (Ptr node) +{ + Vector pos = GetPosition (node); + pos.x += 5.0; + if (pos.x >= 210.0) + { + return; + } + SetPosition (node, pos); + + if (g_verbose) + { + //std::cout << "x="<GetIfIndex ()); + socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress ()); + socket.SetProtocol (1); + + OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket)); + onoff.SetConstantRate (DataRate ("500kb/s")); + + ApplicationContainer apps = onoff.Install (stas.Get (0)); + apps.Start (Seconds (0.5)); + apps.Stop (Seconds (43.0)); + + Simulator::Stop (Seconds (44.0)); + + Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback (&DevTxTrace)); + Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback (&DevRxTrace)); + Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxOk", MakeCallback (&PhyRxOkTrace)); + Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError", MakeCallback (&PhyRxErrorTrace)); + Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx", MakeCallback (&PhyTxTrace)); + Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State", MakeCallback (&PhyStateTrace)); + + AthstatsHelper athstats; + athstats.EnableAthstats ("athstats-sta", stas); + athstats.EnableAthstats ("athstats-ap", ap); + + Simulator::Run (); + + Simulator::Destroy (); + + return 0; +} diff --git a/pool/shard007/C++/0096282_reclaimable_codec_test.cc b/pool/shard007/C++/0096282_reclaimable_codec_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ded858f06b4b6e56ac8b233f5de764288c4224b5 --- /dev/null +++ b/pool/shard007/C++/0096282_reclaimable_codec_test.cc @@ -0,0 +1,66 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/modules/webcodecs/reclaimable_codec.h" + +#include "media/base/test_helpers.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" + +namespace blink { + +namespace { + +class FakeReclaimableCodec final + : public GarbageCollected, + public ReclaimableCodec { + public: + void SimulateActivity() { MarkCodecActive(); } + + void SimulateReset() { PauseCodecReclamation(); } + + void OnCodecReclaimed(DOMException* ex) final {} + + // GarbageCollected override. + void Trace(Visitor* visitor) const override { + ReclaimableCodec::Trace(visitor); + } +}; + +} // namespace + +class ReclaimableCodecTest : public testing::Test { + public: + ReclaimableCodecTest() = default; + ~ReclaimableCodecTest() override = default; +}; + +TEST_F(ReclaimableCodecTest, InactivityTimerStartStops) { + auto* codec = MakeGarbageCollected(); + + // Codecs should not be reclaimable for inactivity until first activity. + EXPECT_FALSE(codec->IsReclamationTimerActiveForTesting()); + + codec->SimulateReset(); + EXPECT_FALSE(codec->IsReclamationTimerActiveForTesting()); + + // Activity should start the timer. + codec->SimulateActivity(); + EXPECT_TRUE(codec->IsReclamationTimerActiveForTesting()); + + // More activity should not stop the timer. + codec->SimulateActivity(); + EXPECT_TRUE(codec->IsReclamationTimerActiveForTesting()); + + // The timer should be stopped when asked. + codec->SimulateReset(); + EXPECT_FALSE(codec->IsReclamationTimerActiveForTesting()); + + // It should be possible to restart the timer after stopping it. + codec->SimulateActivity(); + EXPECT_TRUE(codec->IsReclamationTimerActiveForTesting()); +} + +} // namespace blink diff --git a/pool/shard007/C++/0096285_ff-triangle.cpp b/pool/shard007/C++/0096285_ff-triangle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba4e933043d415636ff87b890f0ec07811640a78 --- /dev/null +++ b/pool/shard007/C++/0096285_ff-triangle.cpp @@ -0,0 +1,52 @@ +#include "Base/Math/Constants.h" +#include "Sample/HardParticle/PolyhedralComponents.h" +#include "Tests/GTestWrapper/google_test.h" +#include + +//! Ad-hoc test of triangle form factor. +//! +//! Used while preparing polyhedral form factor manuscript for publication - JWu, dec 2020. +//! +//! To reactivate this code, just move in to ../UnitTest/Numeric/. + +class FFTriangleTest : public ::testing::Test { +}; + +TEST_F(FFTriangleTest, Triangle) +{ + const double a = 1.; + const double as = a / 2; + const double ac = a / sqrt(3) / 2; + const double ah = a / sqrt(3); + const std::vector V{{-ac, as, 0.}, {-ac, -as, 0.}, {ah, 0., 0.}}; + + const PolyhedralFace T(V, false); + EXPECT_NEAR(T.area(), sqrt(3) / 4, 1e-15); + + int failures = 0; + const int M = 37; + for (int j = 0; j < M; ++j) { + const double phi = M_PI_2 * j / (M - 1); + const cvector_t uQ{sin(phi), cos(phi), 0.}; + const int N = 2800 + j; + for (int i = 0; i < N; ++i) { + const double q = 1e-17 * pow(1.7e17, i / (N - 1.)); + const cvector_t Q = uQ * q; + const double f1 = std::abs(T.ff_2D_direct(Q)); + const double f2 = std::abs(T.ff_2D_expanded(Q)); + const double relerr = std::abs(f1 - f2) / f2; + if (relerr > 7e-16) { + printf("ERR1 %9.6f %16.11e %21.16e %21.16e %10.4e\n", phi, q, f1, f2, relerr); + ++failures; + } + if (q > 1e-7) + continue; + const double relerr2 = std::abs(f1 - T.area()) / f2; + if (relerr2 > 7e-16) { + printf("ERR2 %9.6f %16.11e %21.16e %21.16e %10.4e\n", phi, q, f1, f2, relerr2); + ++failures; + } + } + } + EXPECT_EQ(failures, 0); +} diff --git a/pool/shard007/C++/0096286_strtrim.cpp b/pool/shard007/C++/0096286_strtrim.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8088d8e7ec46fae93ff28230ce6f646621b7dfe --- /dev/null +++ b/pool/shard007/C++/0096286_strtrim.cpp @@ -0,0 +1,134 @@ +/*================================================================= + Copyright (C) 2000 2013 BizStation Corp 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 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. +=================================================================*/ +#include +#pragma hdrstop + +#include "strtrim.h" + +#pragma package(smart_init) + +namespace bzs +{ +namespace rtl +{ + +char* strtrimA(char* str) +{ // trim right space + if (str == NULL) + return NULL; + int k = (int)strlen(str) - 1; + + for (; k >= 0; --k) + { + if (str[k] == 0x20) + str[k] = 0x00; + else + break; + } + return str; +} + +wchar_t* wcstrim(wchar_t* str) +{ + // trim right space + if (str == NULL) + return NULL; + int k = (int)wcslen(str) - 1; + + for (; k >= 0; k--) + { + if (str[k] == 0x20) + str[k] = 0x00; + else + break; + } + return str; +} + +char* strltrimA(char* str) +{ // trim left space + if (str == NULL) + return NULL; + + size_t i; + char* point = NULL; + size_t len = strlen(str); + for (i = 0; i < len; i++) + { + if (str[i] == 0x20) + point = str + i + 1; + else + break; + } + if (point) + memmove(str, point, len - i + 1); + return str; +} + +wchar_t* wcsltrim(wchar_t* str) +{ // trim left space + if (str == NULL) + return NULL; + + size_t i; + wchar_t* point = NULL; + size_t len = wcslen(str); + for (i = 0; i < len; i++) + { + if (str[i] == 0x20) + point = str + i + 1; + else + break; + } + if (point) + memmove(str, point, (len - i + 1) * sizeof(wchar_t)); + return str; +} + +#ifdef _UNICODE +int wcslen_a(wchar_t* str) +{ // How meny charctors of multibyte charctor. + int retVale = 0; + size_t len = wcslen(str); + if (len) + { + LPWORD charType = new WORD[len + 1]; + if (GetStringTypeEx(LOCALE_USER_DEFAULT, CT_CTYPE3, str, -1, charType)) + { + for (size_t i = 0; i < len; i++) + { // If Zenkaku_katakana or Hiragana then return not Zenkaku. Kanji + // is C3_IDEOGRAPH. + if (!(charType[i] & C3_HALFWIDTH) && + ((charType[i] & C3_KATAKANA) || + (charType[i] & C3_HIRAGANA) || + (charType[i] & C3_FULLWIDTH) || + (charType[i] & C3_IDEOGRAPH) || (charType[i] & C3_SYMBOL))) + retVale += 2; + else + retVale += 1; + } + } + delete[] charType; + } + return retVale; +} +#endif + +} // namespace rtl +} // namespace bzs diff --git a/pool/shard007/C++/0096287_WKMutableDictionary.cpp b/pool/shard007/C++/0096287_WKMutableDictionary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecd680cbed4162546f455e620a36934ada89499f --- /dev/null +++ b/pool/shard007/C++/0096287_WKMutableDictionary.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKMutableDictionary.h" + +#include "MutableDictionary.h" +#include "WKAPICast.h" + +using namespace WebKit; + +WKMutableDictionaryRef WKMutableDictionaryCreate() +{ + RefPtr dictionary = MutableDictionary::create(); + return toAPI(dictionary.release().releaseRef()); +} + +bool WKDictionaryIsMutable(WKDictionaryRef dictionaryRef) +{ + return toImpl(dictionaryRef)->isMutable(); +} + +bool WKDictionaryAddItem(WKMutableDictionaryRef dictionaryRef, WKStringRef keyRef, WKTypeRef itemRef) +{ + return toImpl(dictionaryRef)->add(toImpl(keyRef)->string(), toImpl(itemRef)); +} + +bool WKDictionarySetItem(WKMutableDictionaryRef dictionaryRef, WKStringRef keyRef, WKTypeRef itemRef) +{ + return toImpl(dictionaryRef)->set(toImpl(keyRef)->string(), toImpl(itemRef)); +} + +void WKDictionaryRemoveItem(WKMutableDictionaryRef dictionaryRef, WKStringRef keyRef) +{ + toImpl(dictionaryRef)->remove(toImpl(keyRef)->string()); +} diff --git a/pool/shard007/C++/0096291_stitching.cc b/pool/shard007/C++/0096291_stitching.cc new file mode 100644 index 0000000000000000000000000000000000000000..afc1846ccbd07ffb9042bfc9dedd5dfa5f200667 --- /dev/null +++ b/pool/shard007/C++/0096291_stitching.cc @@ -0,0 +1,166 @@ + +#include "stitching.h" + +#include +#include + +#include // cvtColor +#include // CV_RANSAC + +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace { +const int kAllowedNumberOfImages = 2; +std::string print(int i) { + char buffer[100]; + sprintf(buffer, "%d", i); + return(std::string(buffer)); +} +} + +Stitching::Stitching(int num_images) + : num_images_(num_images) { +} + +bool Stitching::InitialiseOpenCV(int width, int height) { + if (num_images_ != kAllowedNumberOfImages) + return false; + + image_size_ = cv::Size(width, height); + + for (int i = 0; i < num_images_; ++i) { + input_img_rgba_.push_back(new cv::Mat(height, width, CV_8UC4)); + input_img_rgb_.push_back(new cv::Mat(height, width, CV_8UC3)); + input_img_.push_back(new cv::Mat(height, width, CV_8UC1)); + } + + // Not all combinations of Feature Detector - Extractor - Matcher would work, + // see http://stackoverflow.com/questions/14808429/classification-of-detectors-extractors-and-matchers/14912160 + // resumed here: + // (FAST, SURF) / SURF / FlannBased <-- in "flann" OpenCV module. + // (FAST, SIFT) / SIFT / FlannBased + // (FAST, ORB) / ORB / BruteForce <-- BruteForce in OpenCV legacy module. + // (FAST, ORB) / BRIEF / BruteForce + // (FAST, SURF) / FREAK / BruteForce + + detector_ = cv::FeatureDetector::create("FAST"); + if (!detector_) + last_error_ += "Creating feature detector failed. "; + + extractor_ = cv::DescriptorExtractor::create("FREAK"); + if (!extractor_) + last_error_ += "Creating feature descriptor extractor failed. "; + + matcher_ = cv::DescriptorMatcher::create("BruteForce"); + if (!matcher_) + last_error_ += "Creating feature matcher failed. "; + + descriptors_[0] = new cv::Mat(); + descriptors_[1] = new cv::Mat(); + + keypoints_[0].clear(); + keypoints_[1].clear(); + + return (detector_ && extractor_ && matcher_); +} + +bool Stitching::CalculateHomography() { + bool ret = true; + last_error_.clear(); + + double t_0 = (double)cv::getTickCount(); + msg_handler_->SendMessage("Starting homography calculation"); + + // Extract keypoints from image. This is expensive compared to the other ops. + detector_->detect(*input_img_[0], keypoints_[0]); + msg_handler_->SendMessage("Detected keypoints image 0: " + + print(keypoints_[0].size())); + detector_->detect(*input_img_[1], keypoints_[1]); + msg_handler_->SendMessage("Detected keypoints image 1: " + + print(keypoints_[1].size())); + + // Now let's compute the descriptors. + extractor_->compute(*input_img_[0], keypoints_[0], *descriptors_[0]); + extractor_->compute(*input_img_[1], keypoints_[1], *descriptors_[1]); + msg_handler_->SendMessage("Computed descriptors: " + + print(descriptors_[0]->rows) + " and " + print(descriptors_[1]->rows)); + + // Let's match the descriptors. + matches_.clear(); + matcher_->match(*descriptors_[0], *descriptors_[1], matches_); + msg_handler_->SendMessage("Matched descriptors, #matches: " + + print(matches_.size())); + + // Quick calculation of max and min distances between keypoints + //double max_dist = -1.0; double min_dist = 1000.0; + //for( int i = 0; i < descriptors_[0]->rows; i++ ) { + // double dist = matches_[i].distance; + // if( dist < min_dist ) min_dist = dist; + // if( dist > max_dist ) max_dist = dist; + //} + //msg_handler_->SendMessage("Calculated min-max descriptor distance, min=" + + // print(min_dist) + " max=" + print(max_dist) ); + + // Use only "good" matches (i.e. whose distance is less than 3*min_dist ) + //cv::vector new_good_matches; + //for( int i = 0; i < descriptors_[0]->rows; i++ ) { + // if( matches_[i].distance < 10*min_dist ) { + // new_good_matches.push_back(matches_[i]); + // } + //} + //if (new_good_matches.size() > 10) good_matches_ = new_good_matches; + //msg_handler_->SendMessage("Filtered descriptor pairs, matches: " + + // print(good_matches_.size())); + good_matches_ = matches_; + + // Redistribute feature points according to selected matches. + std::vector obj; + std::vector scene; + for( unsigned int i = 0; i < good_matches_.size(); i++ ) { + obj.push_back(keypoints_[0][good_matches_[i].queryIdx].pt); + scene.push_back(keypoints_[1][good_matches_[i].trainIdx].pt); + } + + // Find the Homography Matrix, if we have enough points. + if (good_matches_.size() > 10) { + homography_ = findHomography(obj, scene, CV_RANSAC); + + if (cv::getTickFrequency() > 1.0) { + double t = ((double)cv::getTickCount() - t_0)/cv::getTickFrequency(); + msg_handler_->SendMessage("Homography calculated in: " + + print(t*1000000) + "ns"); + } + msg_handler_->SendMessage("H=[[" + print(homography_.at(0,0)) + print(homography_.at(0,1)) + print(homography_.at(0,2)) + ']'); + msg_handler_->SendMessage(" [" + print(homography_.at(1,0)) + print(homography_.at(1,1)) + print(homography_.at(1,2)) + ']'); + msg_handler_->SendMessage(" [" + print(homography_.at(2,0)) + print(homography_.at(2,1)) + print(homography_.at(2,2)) + "]]"); + + for (int row = 0; row < 3; ++row) + for ( int column=0; column < 3; ++column) + PostHomographyValue("H", row, column, homography_.at(row, column)); + + } else { + ret = false; + last_error_ = "Not enough features for homography calculation. "; + } + + return ret; +} + +void Stitching::PostHomographyValue( + const char* message_name, int row, int col, double value) { + pp::VarDictionary message_dic; + message_dic.Set("message", message_name); + message_dic.Set("row", row); + message_dic.Set("column", col); + message_dic.Set("value", value); + msg_handler_->SendMessage(message_dic); +} + +const void Stitching::SetImageData( + int idx, int height, int width, const uint32_t* array) { + memcpy(input_img_rgba_[idx]->ptr(), array, height * width * 4); + cv::cvtColor(*input_img_rgba_[idx], *input_img_rgb_[idx], CV_RGBA2RGB); + cv::cvtColor(*input_img_rgb_[idx], *input_img_[idx], CV_RGB2GRAY); +} diff --git a/pool/shard007/C++/0096296_geomobject.cpp b/pool/shard007/C++/0096296_geomobject.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ac265163fee188cc5a1124a7dec83804d27d156 --- /dev/null +++ b/pool/shard007/C++/0096296_geomobject.cpp @@ -0,0 +1,249 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (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.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Python Computer Graphics Kit. + * + * The Initial Developer of the Original Code is Matthias Baas. + * Portions created by the Initial Developer are Copyright (C) 2004 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#define DLL_EXPORT_GEOMOBJECT +#include "geomobject.h" +#include "slot.h" +#include "arrayslot.h" +#include "vec3.h" +#include "vec4.h" +#include "mat4.h" + +namespace support3d { + +GeomObject::~GeomObject() +{ + deleteAllVariables(); +} + +// Return the uniform count by retrieving a constraint object +int GeomObject::uniformCount() const +{ + boost::shared_ptr c = slotSizeConstraint(UNIFORM); + if (c.get()==0) + return -1; + return c->getSize(); +} + +// Return the varying count by retrieving a constraint object +int GeomObject::varyingCount() const +{ + boost::shared_ptr c = slotSizeConstraint(VARYING); + if (c.get()==0) + return -1; + return c->getSize(); +} + +// Return the vertex count by retrieving a constraint object +int GeomObject::vertexCount() const +{ + boost::shared_ptr c = slotSizeConstraint(VERTEX); + if (c.get()==0) + return -1; + return c->getSize(); +} + +// Return the facevarying count by retrieving a constraint object +int GeomObject::faceVaryingCount() const +{ + boost::shared_ptr c = slotSizeConstraint(FACEVARYING); + if (c.get()==0) + return -1; + return c->getSize(); +} + +// Return the facevertex count by retrieving a constraint object +int GeomObject::faceVertexCount() const +{ + boost::shared_ptr c = slotSizeConstraint(FACEVERTEX); + if (c.get()==0) + return -1; + return c->getSize(); +} + + +/** + Create a new primitive variable. + + A new primitive variable is created which will also create a corresponding + ArraySlot of the same name. If you want to manipulate the data items you + have to retrieve the slot after you have created the variable. + + The meaning of the storage class and type arguments are borrowed from the + RenderMan API (except for the USER storage class). The storage class determines + how man individual data items will be stored. The exact number depends on the + primitive type. For example, if you have a triangle mesh and you create a + variable with storage class UNIFORM you will be able to store one data item + per triangle while storage classes VARYING and VERTEX will result in one data + item per vertex (the difference between VARYING and VERTEX is how the values + are interpolated in between vertices). + + \param name The name of the new variable + \param storage Storage class of the new variable + \param type The type of the new variable + \param multiplicity The array length of an individual item (1=no array) + \param user_n The number of elements for storage class USER. + \see slot (), findVariable (), deleteVariable (), deleteAllVariables (), variablesBegin (), variablesEnd () + \todo Was wenn Name schon existiert? + */ +void GeomObject::newVariable(string name, VarStorage storage, VarType type, int multiplicity, int user_n) +{ + PrimVarInfo info; + ArraySlot* intslot; + ArraySlot* doubleslot; + ArraySlot* vec3slot; + ArraySlot* vec4slot; + ArraySlot* mat4slot; + ArraySlot* strslot; + auto_ptr slot; + + info.storage = storage; + info.type = type; + info.multiplicity = multiplicity; + + // Obtain an appropriate constraint object for the slot + boost::shared_ptr constraint; + switch(storage) + { + case CONSTANT: + // Always constrain the size to 1 + constraint = boost::shared_ptr(new UserSizeConstraint(1)); + break; + case UNIFORM: + case VARYING: + case VERTEX: + case FACEVARYING: + case FACEVERTEX: + // The constraint depends on the geometry... + constraint = slotSizeConstraint(storage); + break; + case USER: + // No constraint + constraint = boost::shared_ptr(); + break; + } + + // Create the slot... + switch(type) + { + case INT: intslot = new ArraySlot(multiplicity, constraint); + info.slot = intslot; + slot = auto_ptr(intslot); + break; + case FLOAT: doubleslot = new ArraySlot(multiplicity, constraint); + info.slot = doubleslot; + slot = auto_ptr(doubleslot); + break; + case COLOR: + case NORMAL: + case POINT: + case VECTOR: vec3slot = new ArraySlot(multiplicity, constraint); + info.slot = vec3slot; + slot = auto_ptr(vec3slot); + break; + case HPOINT: vec4slot = new ArraySlot(multiplicity, constraint); + info.slot = vec4slot; + slot = auto_ptr(vec4slot); + break; + case MATRIX: mat4slot = new ArraySlot(multiplicity, constraint); + info.slot = mat4slot; + slot = auto_ptr(mat4slot); + break; + case STRING: strslot = new ArraySlot(multiplicity, constraint); + info.slot = strslot; + slot = auto_ptr(strslot); + break; + } + + // Resize if it's a user slot... + if (storage==USER) + info.slot->resize(user_n); + + variables[name] = info; + addSlot(name, slot); +} + +/** + Delete a primitive variable. + + \param name Name of the primitive variable + \see newVariable (), findVariable (), deleteAllVariables (), variablesBegin (), variablesEnd () + \todo What happens if name does not exist? + */ +void GeomObject::deleteVariable(string name) +{ + std::map::iterator it = variables.find(name); + if (it!=variables.end()) + { + removeSlot(name); + variables.erase(it); + } +} + +/** + Delete all primitive variables. + + \see newVariable (), findVariable (), deleteVariable (), variablesBegin (), variablesEn d() + */ +void GeomObject::deleteAllVariables() +{ + while(variables.begin()!=variables.end()) + { + deleteVariable(variables.begin()->first); + } +} + +/** + Search for a particular primitive variable and return its variable descriptor. + + \param name The name of the primitive variable. + \return Primitive variable descriptor or 0 if the variable wasn't found. + \see newVariable (), deleteVariable (), deleteAllVariables (), variablesBegin (), variablesEn d() + */ +PrimVarInfo* GeomObject::findVariable(string name) +{ + std::map::iterator it = variables.find(name); + if (it!=variables.end()) + { + return &(it->second); + } + else + { + return 0; + } +} + + +} // end of namespace diff --git a/pool/shard007/C++/0096297_randomplayer.cpp b/pool/shard007/C++/0096297_randomplayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26d2205f3e77914446947fbd5e807758b83fed69 --- /dev/null +++ b/pool/shard007/C++/0096297_randomplayer.cpp @@ -0,0 +1,111 @@ +#include "randomplayer.h" +#include "actions/action.h" +#include "vptr.h" +#include "iorequest.h" +#include +#include "character.h" +#include "player.h" +#include +#include +#include + +RandomPlayer::RandomPlayer(bool writeResult) : + PlayerInput(NULL), + mMe(NULL), + mWriteResults(writeResult) +{ + +} + +RandomPlayer::~RandomPlayer() +{ + +} + +void RandomPlayer::attachPlayer(Player* p) +{ + mMe = p; +} + +void RandomPlayer::onGameEnded(IORequest *ir) +{ + if (!mWriteResults) + return; + + static const QString fname = QString("scriptedrand_s%1.txt").arg(QApplication::arguments().at(9).toInt()); + + QFile f(fname); + QLockFile lock(f.fileName() + ".lock"); + + lock.lock(); + bool opened = f.open(QFile::Append); + Q_ASSERT(opened); + switch (ir->type()) { + case IORequest::LOST: + f.write("0\n"); + break; + + case IORequest::WON: + f.write("1\n"); + break; + + case IORequest::TIE: + f.write("2\n"); + break; + + default: + f.write("-1\n"); + break; + } + f.close(); + lock.unlock(); + + ir->clearRef(); +} + + + +void RandomPlayer::onEventTriggered(IORequest* ir) +{ + Q_UNUSED(ir); +} + +void RandomPlayer::askForAction(IORequest* ir) +{ + QVector* actions = VPtr >::AsPtr(ir->extra("availableActions")); + + // Let 3 turns advance to Nora + /*if (mMe->maxMana() < 4) { + foreach (Action* a, *actions) { + if (a->type() == ActionTypes::END_TURN) { + ir->setResponse(a); + return; + } + } + }*/ + + // Subsequent turns? Play as long as possible + int size = actions->size(); + if (size == 1) { + ir->setResponse(actions->first()); + return; + } + + Action* a = NULL; + do { + a = actions->at(qrand() % size); + } while (a->type() == ActionTypes::END_TURN); + + ir->setResponse(a); +} + +void RandomPlayer::askForPosition(IORequest* ir) +{ + ir->setResponse(new int(0)); +} + +void RandomPlayer::askForTarget(IORequest* ir) +{ + QVector* targets = VPtr >::AsPtr(ir->extra("availableTargets")); + ir->setResponse(targets->at(qrand() % targets->size())); +} diff --git a/pool/shard007/C++/0096299_GlLabelledColorScale.cpp b/pool/shard007/C++/0096299_GlLabelledColorScale.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70ac4bbb2a4b91c105f075d68a1aae3f990031e7 --- /dev/null +++ b/pool/shard007/C++/0096299_GlLabelledColorScale.cpp @@ -0,0 +1,119 @@ +/** + * + * Copyright (C) 2019-2021 The Talipot developers + * + * Talipot is a fork of Tulip, created by David Auber + * and the Tulip development Team from LaBRI, University of Bordeaux + * + * See the AUTHORS file at the top-level directory of this distribution + * License: GNU General Public License version 3, or any later version + * See top-level LICENSE file for more information + * + */ + +#include "GlLabelledColorScale.h" + +#include + +#include + +using namespace std; +using namespace tlp; + +GlLabelledColorScale::GlLabelledColorScale(Coord position, Size size, ColorScale *colorScale, + double minValue, double maxValue, bool colorScaleAtTop) + : GlComposite(), position(position), size(size), minValue(minValue), maxValue(maxValue), + colorScaleAtTop(colorScaleAtTop) { + + buildComposite(colorScale); +} + +void GlLabelledColorScale::buildComposite(ColorScale *colorScale) { + float labelHeightSize = size.getH() * 0.5; + float scaleLength = size.getW(); + float scaleThickness = (1 - 0.5) * size.getH(); + Size valueLabelSize = {size.getW() / 3, labelHeightSize}; + + Coord minValueLabelPosition; + Coord maxValueLabelPosition; + Coord scalePosition; + + if (colorScaleAtTop) { + minValueLabelPosition.set(position.getX() + valueLabelSize.getW() / 2, + position.getY() + labelHeightSize / 2, 0); + maxValueLabelPosition.set((position.getX() + size.getW()) - valueLabelSize.getW() / 2, + minValueLabelPosition.getY(), 0); + scalePosition.set(position.getX(), position.getY() + labelHeightSize + (scaleThickness / 2)); + } else { + minValueLabelPosition.set(position.getX() + valueLabelSize.getW() / 2, + position.getY() + size.getH() - labelHeightSize / 2, 0); + maxValueLabelPosition.set((position.getX() + size.getW()) - valueLabelSize.getW() / 2, + minValueLabelPosition.getY(), 0); + scalePosition.set(position.getX(), position.getY() + (scaleThickness / 2)); + } + + minLabel = new GlLabel(minValueLabelPosition, valueLabelSize, tlp::Color(0, 0, 0), true); + ostringstream oss; + oss << minValue; + minLabel->setText(oss.str()); + addGlEntity(minLabel, "minLabel"); + + maxLabel = new GlLabel(maxValueLabelPosition, valueLabelSize, tlp::Color(0, 0, 0), true); + oss.str(""); + oss << maxValue; + maxLabel->setText(oss.str()); + addGlEntity(maxLabel, "maxLabel"); + + glColorScale = new GlColorScale(colorScale, scalePosition, scaleLength, scaleThickness, + GlColorScale::Horizontal); + glColorScale->getColorScalePolyQuad()->setOutlined(true); + glColorScale->getColorScalePolyQuad()->setOutlineColor(Color(0, 0, 0)); + + addGlEntity(glColorScale, "scale"); +} + +GlLabelledColorScale::~GlLabelledColorScale() { + reset(true); +} + +void GlLabelledColorScale::setMinValue(double value) { + ostringstream oss; + oss << value; + minLabel->setText(oss.str()); + minValue = value; +} +void GlLabelledColorScale::setMaxValue(double value) { + ostringstream oss; + oss << value; + maxLabel->setText(oss.str()); + maxValue = value; +} + +void GlLabelledColorScale::setColorScale(tlp::ColorScale *cs) { + glColorScale->setColorScale(cs); +} +BoundingBox GlLabelledColorScale::getColorScaleBoundingBox() { + return BoundingBox(Coord(position.getX(), position.getY() + size.getH() * 0.5), + Coord(position.getX() + size.getW(), position.getY() + size.getH())); +} + +void GlLabelledColorScale::setPosition(tlp::Coord nPosition) { + + Coord move = nPosition - position; + + glColorScale->translate(move); + minLabel->translate(move); + maxLabel->translate(move); + + position = nPosition; +} + +void GlLabelledColorScale::setSize(tlp::Size nSize) { + + ColorScale *cs = glColorScale->getColorScale(); + size = nSize; + reset(true); + buildComposite(cs); +} + +void GlLabelledColorScale::addLayerParent(tlp::GlLayer *) {} diff --git a/pool/shard007/C++/0096302_numericfunctionnode.cpp b/pool/shard007/C++/0096302_numericfunctionnode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cb10a813355079112ce63f0eef4e0f4f6b84753 --- /dev/null +++ b/pool/shard007/C++/0096302_numericfunctionnode.cpp @@ -0,0 +1,156 @@ +// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +#include "numericfunctionnode.h" +#include + +namespace search::expression { + +IMPLEMENT_ABSTRACT_EXPRESSIONNODE(NumericFunctionNode, MultiArgFunctionNode); + +NumericFunctionNode::NumericFunctionNode() = default; +NumericFunctionNode::~NumericFunctionNode() = default; + +NumericFunctionNode::NumericFunctionNode(const NumericFunctionNode & rhs) : + MultiArgFunctionNode(rhs), + _handler() +{ +} + +NumericFunctionNode & NumericFunctionNode::operator = (const NumericFunctionNode & rhs) +{ + if (this != &rhs) { + MultiArgFunctionNode::operator =(rhs); + _handler.reset(); + } + return *this; +} + +void NumericFunctionNode::onPrepare(bool preserveAccurateTypes) +{ + MultiArgFunctionNode::onPrepare(preserveAccurateTypes); + if (getNumArgs() == 1) { + if (getArg(0).getResult().getClass().inherits(IntegerResultNodeVector::classId)) { + _handler.reset(new FlattenIntegerHandler(*this)); + } else if (getArg(0).getResult().getClass().inherits(FloatResultNodeVector::classId)) { + _handler.reset(new FlattenFloatHandler(*this)); + } else if (getArg(0).getResult().getClass().inherits(StringResultNodeVector::classId)) { + _handler.reset(new FlattenStringHandler(*this)); + } else { + throw std::runtime_error(vespalib::string("No FlattenHandler for ") + getArg(0).getResult().getClass().name()); + } + } else { + if (getResult().getClass().inherits(IntegerResultNodeVector::classId)) { + _handler.reset(new VectorIntegerHandler(*this)); + } else if (getResult().getClass().inherits(FloatResultNodeVector::classId)) { + _handler.reset(new VectorFloatHandler(*this)); + } else if (getResult().getClass().inherits(StringResultNodeVector::classId)) { + _handler.reset(new VectorStringHandler(*this)); + } else if (getResult().getClass().inherits(IntegerResultNode::classId)) { + _handler.reset(new ScalarIntegerHandler(*this)); + } else if (getResult().getClass().inherits(FloatResultNode::classId)) { + _handler.reset(new ScalarFloatHandler(*this)); + } else if (getResult().getClass().inherits(StringResultNode::classId)) { + _handler.reset(new ScalarStringHandler(*this)); + } else if (getResult().getClass().inherits(RawResultNode::classId)) { + _handler.reset(new ScalarRawHandler(*this)); + } else { + throw std::runtime_error(vespalib::make_string("NumericFunctionNode::onPrepare does not handle results of type %s", getResult().getClass().name())); + } + } +} + +bool NumericFunctionNode::onCalculate(const ExpressionNodeVector & args, ResultNode & result) const +{ + bool retval(true); + (void) result; + _handler->handleFirst(args[0]->getResult()); + for (size_t i(1), m(args.size()); i < m; i++) { + _handler->handle(args[i]->getResult()); + } + return retval; +} + +template +void NumericFunctionNode::VectorHandler::handle(const ResultNode & arg) +{ + typename T::Vector & result = _result.getVector(); + if (arg.getClass().inherits(ResultNodeVector::classId)) { + const ResultNodeVector & av = static_cast (arg); + const size_t argSize(av.size()); + const size_t oldRSize(result.size()); + if (argSize > oldRSize) { + result.resize(argSize); + for (size_t i(oldRSize); i < argSize; i++) { + result[i] = result[i%oldRSize]; + } + } + for (size_t i(0), m(result.size()), isize(argSize); i < m; i++) { + function().executeIterative(av.get(i%isize), result[i]); + } + } else { + for (size_t i(0), m(result.size()); i < m; i++) { + function().executeIterative(arg, result[i]); + } + } +} + +template +void NumericFunctionNode::VectorHandler::handleFirst(const ResultNode & arg) +{ + typename T::Vector & result = _result.getVector(); + if (arg.getClass().inherits(ResultNodeVector::classId)) { + const ResultNodeVector & av = static_cast (arg); + result.resize(av.size()); + for (size_t i(0), m(result.size()); i < m; i++) { + result[i].set(av.get(i)); + } + } else { + result.resize(1); + result[0].set(arg); + } +} + + +void NumericFunctionNode::ScalarIntegerHandler::handle(const ResultNode & arg) +{ + function().executeIterative(arg, _result); +} + +void NumericFunctionNode::ScalarFloatHandler::handle(const ResultNode & arg) +{ + function().executeIterative(arg, _result); +} + +void NumericFunctionNode::ScalarStringHandler::handle(const ResultNode & arg) +{ + function().executeIterative(arg, _result); +} + +void NumericFunctionNode::ScalarRawHandler::handle(const ResultNode & arg) +{ + function().executeIterative(arg, _result); +} + +void NumericFunctionNode::FlattenIntegerHandler::handle(const ResultNode & arg) +{ + _result.set(_initial); + function().flatten(static_cast (arg), _result); +} + +void NumericFunctionNode::FlattenFloatHandler::handle(const ResultNode & arg) +{ + _result.set(_initial); + function().flatten(static_cast (arg), _result); +} + +void NumericFunctionNode::FlattenStringHandler::handle(const ResultNode & arg) +{ + _result.set(_initial); + function().flatten(static_cast (arg), _result); +} + +} + +// this function was added by ../../forcelink.sh + +// this function was added by ../../forcelink.sh +void forcelink_file_searchlib_expression_numericfunctionnode() {} diff --git a/pool/shard007/C++/0096305_node-locations.cpp b/pool/shard007/C++/0096305_node-locations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41a4e04ec5e63ce80955f2698587c0bedaf0e5fe --- /dev/null +++ b/pool/shard007/C++/0096305_node-locations.cpp @@ -0,0 +1,88 @@ +/** + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of osm2pgsql (https://osm2pgsql.org/). + * + * Copyright (C) 2006-2021 by the osm2pgsql developer community. + * For a full list of authors see the git log. + */ + +#include "node-locations.hpp" + +// Workaround: This must be included before buffer_string.hpp due to a missing +// include in the upstream code. https://github.com/mapbox/protozero/pull/104 +#include + +#include +#include + +#include + +bool node_locations_t::set(osmid_t id, osmium::Location location) +{ + if (used_memory() >= m_max_size && will_resize()) { + return false; + } + + if (first_entry_in_block()) { + m_did.clear(); + m_dx.clear(); + m_dy.clear(); + m_index.add(id, m_data.size()); + } + + auto const delta = m_did.update(id); + // Always true because ids in input must be unique and ordered + assert(delta > 0); + protozero::add_varint_to_buffer(&m_data, static_cast(delta)); + + protozero::add_varint_to_buffer( + &m_data, protozero::encode_zigzag64(m_dx.update(location.x()))); + protozero::add_varint_to_buffer( + &m_data, protozero::encode_zigzag64(m_dy.update(location.y()))); + + ++m_count; + + return true; +} + +osmium::Location node_locations_t::get(osmid_t id) const +{ + auto const offset = m_index.get_block(id); + if (offset == ordered_index_t::not_found_value()) { + return osmium::Location{}; + } + + assert(offset < m_data.size()); + + char const *begin = m_data.data() + offset; + char const *const end = m_data.data() + m_data.size(); + + osmium::DeltaDecode did; + osmium::DeltaDecode dx; + osmium::DeltaDecode dy; + + for (std::size_t n = 0; n < block_size && begin != end; ++n) { + auto const bid = did.update( + static_cast(protozero::decode_varint(&begin, end))); + int32_t const x = dx.update( + protozero::decode_zigzag64(protozero::decode_varint(&begin, end))); + int32_t const y = dy.update( + protozero::decode_zigzag64(protozero::decode_varint(&begin, end))); + if (bid == id) { + return osmium::Location{x, y}; + } + if (bid > id) { + break; + } + } + return osmium::Location{}; +} + +void node_locations_t::clear() +{ + m_data.clear(); + m_data.shrink_to_fit(); + m_index.clear(); + m_count = 0; +} diff --git a/pool/shard007/C++/0096306_simple_mdrangepolicy.cpp b/pool/shard007/C++/0096306_simple_mdrangepolicy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ac7f4fbb060ae952a0685313ec357ffa05abf96 --- /dev/null +++ b/pool/shard007/C++/0096306_simple_mdrangepolicy.cpp @@ -0,0 +1,211 @@ +/* +//@HEADER +// ************************************************************************ +// +// Kokkos v. 3.0 +// Copyright (2020) National Technology & Engineering +// Solutions of Sandia, LLC (NTESS). +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. Neither the name of the Corporation nor the names of the +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE +// 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. +// +// Questions? Contact Christian R. Trott (crtrott@sandia.gov) +// +// ************************************************************************ +//@HEADER +*/ + +#include +#include + +// +// MDRangePolicy example with parallel_for and parallel_reduce: +// 1. Start up Kokkos +// 2. Execute a parallel_for loop in the default execution space, +// using a functor to define the loop body +// 3. Shut down Kokkos +// +// Two examples are provided: +// Example 1: Rank 2 case with minimal default parameters and arguments used +// in the MDRangePolicy +// +// Example 2: Rank 3 case with additional outer/inner iterate pattern parameters +// and tile dims passed to the ctor + +// Simple functor for computing/storing the product of indices in a View v +template +struct MDFunctor { + using value_type = long; + + ViewType v; + size_t size; + + MDFunctor(const ViewType& v_, const size_t size_) : v(v_), size(size_) {} + + // 2D case - used by parallel_for + KOKKOS_INLINE_FUNCTION + void operator()(const int i, const int j) const { + v(i, j) = i * j; // compute the product of indices + } + + // 3D case - used by parallel_for + KOKKOS_INLINE_FUNCTION + void operator()(const int i, const int j, const int k) const { + v(i, j, k) = i * j * k; // compute the product of indices + } + + // 2D case - reduction + KOKKOS_INLINE_FUNCTION + void operator()(const int i, const int j, value_type& incorrect_count) const { + if (v(i, j) != i * j) { + incorrect_count += 1; + } + } + + // 3D case - reduction + KOKKOS_INLINE_FUNCTION + void operator()(const int i, const int j, const int k, + value_type& incorrect_count) const { + if (v(i, j, k) != i * j * k) { + incorrect_count += 1; + } + } +}; + +int main(int argc, char* argv[]) { + Kokkos::initialize(argc, argv); + + // Bound(s) for MDRangePolicy + const int n = 100; + + // ViewType aliases for Rank<2>, Rank<3> for example usage + using ScalarType = double; + using ViewType_2D = Kokkos::View; + using ViewType_3D = Kokkos::View; + + ///////////////////////////////////////////////////////////////////////////// + // Explanation of MDRangePolicy usage, template parameters, constructor + // arguments + // + // MDRangePolicy aliases for Rank<2>, Rank<3> cases + // Required template parameters: + // Kokkos::Rank: where N=rank + // + // Optional template parameters to Rank<...>: + // Kokkos::Iterate::{Default,Left,Right}: Outer iteration pattern across + // tiles; + // defaults based on the execution space similar to Kokkos::Layout + // Kokkos::Iterate::{Default,Left,Right}: Inner iteration pattern within + // tiles; + // defaults based on the execution space similar to Kokkos::Layout + // + // e.g. using rank2ll = Rank<2, Iterate::Left, Iterate::Left>; + // + // + // Optional template parameters to MDRangePolicy: + // ExecutionSpace: Kokkos::Serial, Kokkos::OpenMP, Kokkos::Cuda, etc. + // + // Kokkos::IndexType< T >: where T = int, long, unsigned int, etc. + // + // struct Tag{}: A user-provided tag for tagging functor operators + // + // e.g. 1: MDRangePolicy< Kokkos::Serial, Rank<2, Iterate::Left, + // Iterate::Left>, IndexType, Tag > mdpolicy; e.g. 2: MDRangePolicy< + // Kokkos::Serial, rank2ll, IndexType, Tag > mdpolicy; + // + // + // Required arguments to ctor: + // {{ l0, l1, ... }}: Lower bounds, provided as Kokkos::Array or + // std::initializer_list + // {{ u0, u1, ... }}: Upper bounds, provided as Kokkos::Array or + // std::initializer_list + // + // Optional arguments to ctor: + // {{ t0, t1, ... }}: Tile dimensions, provided as Kokkos::Array or + // std::initializer_list + // defaults based on the execution space + // + // e.g. mdpolicy( {{0,0}}, {{u0,u1}}, {{t0,t1}}; + // + ///////////////////////////////////////////////////////////////////////////// + + // Example 1: + long incorrect_count_2d = 0; + { + // Rank<2> Case: Rank is provided, all other parameters are default + using MDPolicyType_2D = Kokkos::MDRangePolicy >; + + // Construct 2D MDRangePolicy: lower and upper bounds provided, tile dims + // defaulted + MDPolicyType_2D mdpolicy_2d({{0, 0}}, {{n, n}}); + + // Construct a 2D view to store result of product of indices + ViewType_2D v2("v2", n, n); + + // Execute parallel_for with rank 2 MDRangePolicy + Kokkos::parallel_for("md2d", mdpolicy_2d, MDFunctor(v2, n)); + + // Check results with a parallel_reduce using the MDRangePolicy + Kokkos::parallel_reduce("md2dredux", mdpolicy_2d, + MDFunctor(v2, n), incorrect_count_2d); + + printf("Rank 2 MDRangePolicy incorrect count: %ld\n", + incorrect_count_2d); // should be 0 + } + + // Example 2: + long incorrect_count_3d = 0; + { + // Rank<3> Case: Rank, inner iterate pattern, outer iterate pattern provided + using MDPolicyType_3D = Kokkos::MDRangePolicy< + Kokkos::Rank<3, Kokkos::Iterate::Left, Kokkos::Iterate::Left> >; + + // Construct 3D MDRangePolicy: lower, upper bounds, tile dims provided + MDPolicyType_3D mdpolicy_3d({{0, 0, 0}}, {{n, n, n}}, {{4, 4, 4}}); + + // Construct a 3D view to store result of product of indices + ViewType_3D v3("v3", n, n, n); + + // Execute parallel_for with rank 3 MDRangePolicy + Kokkos::parallel_for("md3d", mdpolicy_3d, MDFunctor(v3, n)); + + // Check results with a parallel_reduce using the MDRangePolicy + Kokkos::parallel_reduce("md3dredux", mdpolicy_3d, + MDFunctor(v3, n), incorrect_count_3d); + + printf("Rank 3 MDRangePolicy incorrect count: %ld\n", + incorrect_count_3d); // should be 0 + } + + Kokkos::finalize(); + + return (incorrect_count_2d == long(0) && incorrect_count_3d == long(0)) ? 0 + : -1; +} diff --git a/pool/shard007/C++/0096307_responsestats.cc b/pool/shard007/C++/0096307_responsestats.cc new file mode 100644 index 0000000000000000000000000000000000000000..45eaad0d82a506c4c869746aa63745e94a9cb30a --- /dev/null +++ b/pool/shard007/C++/0096307_responsestats.cc @@ -0,0 +1,76 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "responsestats.hh" +#include +#include "namespaces.hh" +#include "logger.hh" +#include "boost/foreach.hpp" +#include "dnsparser.hh" + +ResponseStats::ResponseStats() +{ + d_qtypecounters.resize(std::numeric_limits::max()+1); + d_sizecounters.push_back(make_pair(20,0)); + d_sizecounters.push_back(make_pair(40,0)); + d_sizecounters.push_back(make_pair(60,0)); + d_sizecounters.push_back(make_pair(80,0)); + d_sizecounters.push_back(make_pair(100,0)); + d_sizecounters.push_back(make_pair(150,0)); + for(int n=200; n < 65000 ; n+=200) + d_sizecounters.push_back(make_pair(n,0)); + d_sizecounters.push_back(make_pair(std::numeric_limits::max(),0)); +} + +ResponseStats g_rs = ResponseStats(); + +static bool pcomp(const pair&a , const pair&b) +{ + return a.first < b.first; +} + +void ResponseStats::submitResponse(uint16_t qtype, uint16_t respsize, bool udpOrTCP) +{ + d_qtypecounters[qtype]++; + pair s(respsize, 0); + sizecounters_t::iterator iter = std::upper_bound(d_sizecounters.begin(), d_sizecounters.end(), s, pcomp); + if(iter!= d_sizecounters.begin()) + --iter; + iter->second++; +} + +map ResponseStats::getQTypeResponseCounts() +{ + map ret; + uint64_t count; + for(unsigned int i = 0 ; i < d_qtypecounters.size() ; ++i) { + count= d_qtypecounters[i]; + if(count) + ret[i]=count; + } + return ret; +} + +map ResponseStats::getSizeResponseCounts() +{ + map ret; + for(sizecounters_t::const_iterator iter = d_sizecounters.begin(); + iter != d_sizecounters.end(); + ++iter) { + ret[iter->first]=iter->second; + } + return ret; +} + +string ResponseStats::getQTypeReport() +{ + typedef map qtypenums_t; + qtypenums_t qtypenums = getQTypeResponseCounts(); + ostringstream os; + boost::format fmt("%s\t%d\n"); + BOOST_FOREACH(const qtypenums_t::value_type& val, qtypenums) { + os << (fmt %DNSRecordContent::NumberToType( val.first) % val.second).str(); + } + return os.str(); +} + diff --git a/pool/shard007/C++/0096311_CPU.cpp b/pool/shard007/C++/0096311_CPU.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54971cdd8972a470a88b0f418733d1b6ef3ff96a --- /dev/null +++ b/pool/shard007/C++/0096311_CPU.cpp @@ -0,0 +1,187 @@ +// Copyright 2008 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#include + +#include "AudioCommon/AudioCommon.h" +#include "Common/CommonTypes.h" +#include "Common/Event.h" +#include "Core/Core.h" +#include "Core/DSPEmulator.h" +#include "Core/Host.h" +#include "Core/Movie.h" +#include "Core/HW/CPU.h" +#include "Core/HW/DSP.h" +#include "Core/HW/Memmap.h" +#include "Core/PowerPC/PowerPC.h" +#include "VideoCommon/VideoBackendBase.h" + +namespace +{ + static Common::Event m_StepEvent; + static Common::Event *m_SyncEvent = nullptr; + static std::mutex m_csCpuOccupied; +} + +namespace CPU +{ + +void Init(int cpu_core) +{ + PowerPC::Init(cpu_core); + m_SyncEvent = nullptr; +} + +void Shutdown() +{ + PowerPC::Shutdown(); + m_SyncEvent = nullptr; +} + +void Run() +{ + std::lock_guard lk(m_csCpuOccupied); + Host_UpdateDisasmDialog(); + + while (true) + { + switch (PowerPC::GetState()) + { + case PowerPC::CPU_RUNNING: + //1: enter a fast runloop + PowerPC::RunLoop(); + break; + + case PowerPC::CPU_STEPPING: + m_csCpuOccupied.unlock(); + + //1: wait for step command.. + m_StepEvent.Wait(); + + m_csCpuOccupied.lock(); + if (PowerPC::GetState() == PowerPC::CPU_POWERDOWN) + return; + if (PowerPC::GetState() != PowerPC::CPU_STEPPING) + continue; + + //3: do a step + PowerPC::SingleStep(); + + //4: update disasm dialog + if (m_SyncEvent) + { + m_SyncEvent->Set(); + m_SyncEvent = nullptr; + } + Host_UpdateDisasmDialog(); + break; + + case PowerPC::CPU_POWERDOWN: + //1: Exit loop!! + return; + } + } +} + +void Stop() +{ + PowerPC::Stop(); + m_StepEvent.Set(); +} + +bool IsStepping() +{ + return PowerPC::GetState() == PowerPC::CPU_STEPPING; +} + +void Reset() +{ +} + +void StepOpcode(Common::Event* event) +{ + m_StepEvent.Set(); + if (PowerPC::GetState() == PowerPC::CPU_STEPPING) + { + m_SyncEvent = event; + } +} + +void EnableStepping(const bool stepping) +{ + if (stepping) + { + PowerPC::Pause(); + m_StepEvent.Reset(); + g_video_backend->EmuStateChange(EMUSTATE_CHANGE_PAUSE); + AudioCommon::ClearAudioBuffer(true); + } + else + { + // SingleStep so that the "continue", "step over" and "step out" debugger functions + // work when the PC is at a breakpoint at the beginning of the block + // If watchpoints are enabled, any instruction could be a breakpoint. + bool could_be_bp; +#ifdef ENABLE_MEM_CHECK + could_be_bp = true; +#else + could_be_bp = PowerPC::breakpoints.IsAddressBreakPoint(PC); +#endif + if (could_be_bp && PowerPC::GetMode() != PowerPC::MODE_INTERPRETER) + { + PowerPC::CoreMode oldMode = PowerPC::GetMode(); + PowerPC::SetMode(PowerPC::MODE_INTERPRETER); + PowerPC::SingleStep(); + PowerPC::SetMode(oldMode); + } + PowerPC::Start(); + m_StepEvent.Set(); + g_video_backend->EmuStateChange(EMUSTATE_CHANGE_PLAY); + AudioCommon::ClearAudioBuffer(false); + } +} + +void Break() +{ + EnableStepping(true); +} + +bool PauseAndLock(bool do_lock, bool unpause_on_unlock) +{ + static bool s_have_fake_cpu_thread; + bool wasUnpaused = !IsStepping(); + if (do_lock) + { + // we can't use EnableStepping, that would causes deadlocks with both audio and video + PowerPC::Pause(); + if (!Core::IsCPUThread()) + { + m_csCpuOccupied.lock(); + s_have_fake_cpu_thread = true; + Core::DeclareAsCPUThread(); + } + else + { + s_have_fake_cpu_thread = false; + } + } + else + { + if (unpause_on_unlock) + { + PowerPC::Start(); + m_StepEvent.Set(); + } + + if (s_have_fake_cpu_thread) + { + Core::UndeclareAsCPUThread(); + m_csCpuOccupied.unlock(); + s_have_fake_cpu_thread = false; + } + } + return wasUnpaused; +} + +} diff --git a/pool/shard007/C++/0096314_paymentserver.cpp b/pool/shard007/C++/0096314_paymentserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b9fd8ba71cdc33c5d45cc8e28c4b93a99058be7 --- /dev/null +++ b/pool/shard007/C++/0096314_paymentserver.cpp @@ -0,0 +1,162 @@ +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include "paymentserver.h" + +#include "guiconstants.h" +#include "ui_interface.h" +#include "util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION < 0x050000 +#include +#endif + +using namespace boost; + +const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds +const QString BITCOIN_IPC_PREFIX("plncoin:"); + +// +// Create a name that is unique for: +// testnet / non-testnet +// data directory +// +static QString ipcServerName() +{ + QString name("BitcoinQt"); + + // Append a simple hash of the datadir + // Note that GetDataDir(true) returns a different path + // for -testnet versus main net + QString ddir(GetDataDir(true).string().c_str()); + name.append(QString::number(qHash(ddir))); + + return name; +} + +// +// This stores payment requests received before +// the main GUI window is up and ready to ask the user +// to send payment. +// +static QStringList savedPaymentRequests; + +// +// Sending to the server is done synchronously, at startup. +// If the server isn't already running, startup continues, +// and the items in savedPaymentRequest will be handled +// when uiReady() is called. +// +bool PaymentServer::ipcSendCommandLine() +{ + bool fResult = false; + + const QStringList& args = qApp->arguments(); + for (int i = 1; i < args.size(); i++) + { + if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) + continue; + savedPaymentRequests.append(args[i]); + } + + foreach (const QString& arg, savedPaymentRequests) + { + QLocalSocket* socket = new QLocalSocket(); + socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); + if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) + return false; + + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_0); + out << arg; + out.device()->seek(0); + socket->write(block); + socket->flush(); + + socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); + socket->disconnectFromServer(); + delete socket; + fResult = true; + } + return fResult; +} + +PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) +{ + // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) + parent->installEventFilter(this); + + QString name = ipcServerName(); + + // Clean up old socket leftover from a crash: + QLocalServer::removeServer(name); + + uriServer = new QLocalServer(this); + + if (!uriServer->listen(name)) + qDebug() << tr("Cannot start plncoin: click-to-pay handler"); + else + connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); +} + +bool PaymentServer::eventFilter(QObject *object, QEvent *event) +{ + // clicking on bitcoin: URLs creates FileOpen events on the Mac: + if (event->type() == QEvent::FileOpen) + { + QFileOpenEvent* fileEvent = static_cast(event); + if (!fileEvent->url().isEmpty()) + { + if (saveURIs) // Before main window is ready: + savedPaymentRequests.append(fileEvent->url().toString()); + else + emit receivedURI(fileEvent->url().toString()); + return true; + } + } + return false; +} + +void PaymentServer::uiReady() +{ + saveURIs = false; + foreach (const QString& s, savedPaymentRequests) + emit receivedURI(s); + savedPaymentRequests.clear(); +} + +void PaymentServer::handleURIConnection() +{ + QLocalSocket *clientConnection = uriServer->nextPendingConnection(); + + while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) + clientConnection->waitForReadyRead(); + + connect(clientConnection, SIGNAL(disconnected()), + clientConnection, SLOT(deleteLater())); + + QDataStream in(clientConnection); + in.setVersion(QDataStream::Qt_4_0); + if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { + return; + } + QString message; + in >> message; + + if (saveURIs) + savedPaymentRequests.append(message); + else + emit receivedURI(message); +} diff --git a/pool/shard007/C++/0096316_rom.cpp b/pool/shard007/C++/0096316_rom.cpp new file mode 100644 index 0000000000000000000000000000000000000000..883b36eb739fe53ecd7d728588212f117f3eecac --- /dev/null +++ b/pool/shard007/C++/0096316_rom.cpp @@ -0,0 +1,230 @@ +// license:BSD-3-Clause +// copyright-holders:Sandro Ronco +/*************************************************************************** + + rom.c + + KC 85 ROM modules emulation + + Supported modules: + - Generic 8KB ROM module + - M006 BASIC + - M033 TypeStar + +***************************************************************************/ + +#include "emu.h" +#include "rom.h" + +#define REGION_TAG "rom" + +/*************************************************************************** + IMPLEMENTATION +***************************************************************************/ + +ROM_START( kc_rom ) + ROM_REGION(0x4000, REGION_TAG, ROMREGION_ERASEFF) +ROM_END + +//************************************************************************** +// GLOBAL VARIABLES +//************************************************************************** + +const device_type KC_STANDARD = &device_creator; +const device_type KC_M006 = &device_creator; +const device_type KC_M033 = &device_creator; + +//************************************************************************** +// LIVE DEVICE +//************************************************************************** + +//------------------------------------------------- +// kc_8k_device - constructor +//------------------------------------------------- + +kc_8k_device::kc_8k_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) + : device_t(mconfig, KC_STANDARD, "Standard 8K ROM module", tag, owner, clock, "kc_8k", __FILE__), + device_kcexp_interface( mconfig, *this ), m_slot(nullptr), m_mei(0), m_rom(nullptr), m_enabled(0), m_base(0) + { +} + +kc_8k_device::kc_8k_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source) + : device_t(mconfig, type, name, tag, owner, clock, shortname, source), + device_kcexp_interface( mconfig, *this ), m_slot(nullptr), m_mei(0), m_rom(nullptr), m_enabled(0), m_base(0) + { +} + + +//------------------------------------------------- +// device_start - device-specific startup +//------------------------------------------------- + +void kc_8k_device::device_start() +{ + m_slot = dynamic_cast(owner()); + m_rom = memregion(REGION_TAG)->base(); +} + +//------------------------------------------------- +// device_reset - device-specific reset +//------------------------------------------------- + +void kc_8k_device::device_reset() +{ + m_enabled = 0; + m_base = 0; + m_mei = 0; +} + +//------------------------------------------------- +// rom_region - device-specific ROM region +//------------------------------------------------- + +const rom_entry *kc_8k_device::device_rom_region() const +{ + return ROM_NAME( kc_rom ); +} + +/*------------------------------------------------- + get_cart_base +-------------------------------------------------*/ + +UINT8* kc_8k_device::get_cart_base() +{ + return m_rom; +} + +/*------------------------------------------------- + module control write +-------------------------------------------------*/ + +void kc_8k_device::control_w(UINT8 data) +{ + if (m_mei) + { + m_enabled = BIT(data, 0); + m_base = (data & 0xe0) << 8; + } +} + +/*------------------------------------------------- + read +-------------------------------------------------*/ + +void kc_8k_device::read(offs_t offset, UINT8 &data) +{ + if (offset >= m_base && offset < (m_base + 0x2000) && m_enabled && m_mei) + { + data = m_rom[offset - m_base]; + + // clear the MEO line for disable other modules with less priority + m_slot->meo_w(CLEAR_LINE); + } +} + +/*------------------------------------------------- + MEI line write +-------------------------------------------------*/ + +WRITE_LINE_MEMBER( kc_8k_device::mei_w ) +{ + m_mei = state; + + // update MEO line + m_slot->meo_w(state); +} + +//************************************************************************** +// M006 BASIC +//************************************************************************** + +//------------------------------------------------- +// kc_m006_device - constructor +//------------------------------------------------- + +kc_m006_device::kc_m006_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) + : kc_8k_device(mconfig, KC_M006, "M006 BASIC", tag, owner, clock, "kc_m006", __FILE__) +{ +} + +/*------------------------------------------------- + module control write +-------------------------------------------------*/ + +void kc_m006_device::control_w(UINT8 data) +{ + if (m_mei) + { + m_enabled = BIT(data, 0); + m_base = (data & 0xc0) << 8; + } +} + +/*------------------------------------------------- + read +-------------------------------------------------*/ + +void kc_m006_device::read(offs_t offset, UINT8 &data) +{ + if (offset >= m_base && offset < (m_base + 0x4000) && m_enabled) + { + data = m_rom[offset - m_base]; + + // clear the MEO line for disable other modules with less priority + m_slot->meo_w(CLEAR_LINE); + } +} + + +//************************************************************************** +// M033 TypeStar module +//************************************************************************** + +//------------------------------------------------- +// kc_m033_device - constructor +//------------------------------------------------- + +kc_m033_device::kc_m033_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) + : kc_8k_device(mconfig, KC_M033, "M033 TypeStar", tag, owner, clock, "kc_m033", __FILE__), m_bank(0) + { +} + +//------------------------------------------------- +// device_reset - device-specific reset +//------------------------------------------------- + +void kc_m033_device::device_reset() +{ + kc_8k_device::device_reset(); + + m_bank = 0; +} + +/*------------------------------------------------- + module control write +-------------------------------------------------*/ + +void kc_m033_device::control_w(UINT8 data) +{ + if (m_mei) + { + m_enabled = BIT(data, 0); + m_base = (data & 0xc0) << 8; + m_bank = BIT(data, 4); + } +} + +/*------------------------------------------------- + read +-------------------------------------------------*/ + +void kc_m033_device::read(offs_t offset, UINT8 &data) +{ + if (offset >= m_base && offset < (m_base + 0x2000) && m_enabled && m_mei) + { + data = m_rom[(offset - m_base) | (m_bank<<13)]; + + // clear the MEO line for disable other modules with less priority + m_slot->meo_w(CLEAR_LINE); + } +} diff --git a/pool/shard007/C++/0096318_subresource_filter_devtools_browsertest.cc b/pool/shard007/C++/0096318_subresource_filter_devtools_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..5f8cf6606dcf7972f199d1f875d1dc96e5f291b8 --- /dev/null +++ b/pool/shard007/C++/0096318_subresource_filter_devtools_browsertest.cc @@ -0,0 +1,200 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "base/json/json_string_value_serializer.h" +#include "base/memory/ref_counted.h" +#include "base/values.h" +#include "chrome/browser/subresource_filter/subresource_filter_browser_test_harness.h" +#include "chrome/common/chrome_features.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/subresource_filter/core/browser/subresource_filter_constants.h" +#include "content/public/browser/devtools_agent_host.h" +#include "content/public/browser/devtools_agent_host_client.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +namespace subresource_filter { + +namespace { + +class TestClient : public content::DevToolsAgentHostClient { + public: + TestClient() {} + ~TestClient() override {} + void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, + base::span message) override {} + void AgentHostClosed(content::DevToolsAgentHost* agent_host) override {} +}; + +class ScopedDevtoolsOpener { + public: + explicit ScopedDevtoolsOpener( + scoped_refptr agent_host) + : agent_host_(std::move(agent_host)) { + EXPECT_TRUE(agent_host_); + agent_host_->AttachClient(&test_client_); + // Send Page.enable, which is required before any Page methods. + constexpr char kMsg[] = R"({"id": 0, "method": "Page.enable"})"; + agent_host_->DispatchProtocolMessage( + &test_client_, base::as_bytes(base::make_span(kMsg, strlen(kMsg)))); + } + + explicit ScopedDevtoolsOpener(content::WebContents* web_contents) + : ScopedDevtoolsOpener( + content::DevToolsAgentHost::GetOrCreateFor(web_contents)) {} + + ScopedDevtoolsOpener(const ScopedDevtoolsOpener&) = delete; + ScopedDevtoolsOpener& operator=(const ScopedDevtoolsOpener&) = delete; + + ~ScopedDevtoolsOpener() { agent_host_->DetachClient(&test_client_); } + + void EnableAdBlocking(bool enabled) { + // Send Page.setAdBlockingEnabled, should force activation. + base::DictionaryValue ad_blocking_command; + ad_blocking_command.SetInteger("id", 1); + ad_blocking_command.SetString("method", "Page.setAdBlockingEnabled"); + auto params = std::make_unique(); + params->SetBoolean("enabled", enabled); + ad_blocking_command.SetDictionary("params", std::move(params)); + std::string json_string; + JSONStringValueSerializer serializer(&json_string); + ASSERT_TRUE(serializer.Serialize(ad_blocking_command)); + agent_host_->DispatchProtocolMessage( + &test_client_, base::as_bytes(base::make_span(json_string))); + } + + private: + TestClient test_client_; + scoped_refptr agent_host_; +}; + +} // namespace + +class SubresourceFilterDevtoolsBrowserTest + : public SubresourceFilterBrowserTest {}; + +IN_PROC_BROWSER_TEST_F(SubresourceFilterDevtoolsBrowserTest, + ForceActivation_RequiresDevtools) { + const GURL url( + GetTestUrl("subresource_filter/frame_with_included_script.html")); + ASSERT_NO_FATAL_FAILURE( + SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); + + // Should not trigger activation, the URL is not on the blocklist. + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + + // Open up devtools and trigger forced activation. + { + ScopedDevtoolsOpener devtools(web_contents()); + devtools.EnableAdBlocking(true); + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + + // Close devtools, should stop forced activation. + } + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); +} + +IN_PROC_BROWSER_TEST_F(SubresourceFilterListInsertingBrowserTest, + WarningSiteWithForceActivation_LogsWarning) { + const GURL url( + GetTestUrl("subresource_filter/frame_with_included_script.html")); + ASSERT_NO_FATAL_FAILURE( + SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); + ConfigureURLWithWarning(url, + {safe_browsing::SubresourceFilterType::BETTER_ADS}); + + Configuration config(subresource_filter::mojom::ActivationLevel::kEnabled, + subresource_filter::ActivationScope::ACTIVATION_LIST, + subresource_filter::ActivationList::BETTER_ADS); + ResetConfiguration(std::move(config)); + + // Should not trigger activation, the URL is not on the blocklist. + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + + content::WebContentsConsoleObserver console_observer(web_contents()); + console_observer.SetPattern(kActivationWarningConsoleMessage); + + // Open up devtools and trigger forced activation. + { + ScopedDevtoolsOpener devtools(web_contents()); + devtools.EnableAdBlocking(true); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + console_observer.Wait(); + EXPECT_EQ(kActivationWarningConsoleMessage, + console_observer.GetMessageAt(0u)); + // Close devtools, should stop forced activation. + } + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_TRUE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); +} + +IN_PROC_BROWSER_TEST_F(SubresourceFilterDevtoolsBrowserTest, + ForceActivation_SubresourceLogging) { + content::WebContentsConsoleObserver console_observer(web_contents()); + console_observer.SetPattern(kActivationConsoleMessage); + const GURL url( + GetTestUrl("subresource_filter/frame_with_included_script.html")); + ASSERT_NO_FATAL_FAILURE( + SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); + ScopedDevtoolsOpener devtools(web_contents()); + devtools.EnableAdBlocking(true); + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + EXPECT_FALSE(console_observer.messages().empty()); +} + +class SubresourceFilterDevtoolsBrowserTestWithSitePerProcess + : public SubresourceFilterDevtoolsBrowserTest { + public: + SubresourceFilterDevtoolsBrowserTestWithSitePerProcess() { + feature_list_.InitAndEnableFeature(features::kSitePerProcess); + } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +// See crbug.com/813197, where agent hosts from subframes could send messages to +// disable ad blocking when they are detached (e.g. when the subframe goes +// away). +IN_PROC_BROWSER_TEST_F(SubresourceFilterDevtoolsBrowserTestWithSitePerProcess, + IsolatedSubframe_DoesNotSendAdBlockingMessages) { + ASSERT_NO_FATAL_FAILURE( + SetRulesetToDisallowURLsWithPathSuffix("included_script.js")); + ScopedDevtoolsOpener page_opener(web_contents()); + page_opener.EnableAdBlocking(true); + + const GURL frame_with_script = + GetTestUrl("subresource_filter/frame_with_included_script.html"); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), frame_with_script)); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); + + const GURL cross_site_frames = embedded_test_server()->GetURL( + "a.com", "/subresource_filter/frame_cross_site_set.html"); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), cross_site_frames)); + + // Simulate attaching and detaching subframe clients. The browser should not + // process any of the ad blocking messages when the frames detach. + for (const auto& host : content::DevToolsAgentHost::GetOrCreateAll()) { + if (host->GetType() == content::DevToolsAgentHost::kTypeFrame) + ScopedDevtoolsOpener opener(host); + } + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), frame_with_script)); + EXPECT_FALSE(WasParsedScriptElementLoaded(web_contents()->GetMainFrame())); +} + +} // namespace subresource_filter diff --git a/pool/shard007/C++/0096321_mscorlib_System_Runtime_Versioning_TargetFrameworkAttribute.cpp b/pool/shard007/C++/0096321_mscorlib_System_Runtime_Versioning_TargetFrameworkAttribute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13984fe650ade6b192b314a6be5ebef05ece9c09 --- /dev/null +++ b/pool/shard007/C++/0096321_mscorlib_System_Runtime_Versioning_TargetFrameworkAttribute.cpp @@ -0,0 +1,63 @@ +#include +#include + + + +namespace mscorlib +{ + namespace System + { + namespace Runtime + { + namespace Versioning + { + + //Public Methods + //Get Set Properties Methods + // Get/Set:FrameworkName + mscorlib::System::String TargetFrameworkAttribute::get_FrameworkName() const + { + MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Versioning", "TargetFrameworkAttribute", 0, NULL, "get_FrameworkName", __native_object__, 0, NULL, NULL, NULL); + return mscorlib::System::String(__result__); + } + + void TargetFrameworkAttribute::set_FrameworkName(mscorlib::System::String value) + { + MonoType *__parameter_types__[1]; + void *__parameters__[1]; + __parameter_types__[0] = Global::GetType(typeid(value).name()); + __parameters__[0] = (MonoObject*)value; + Global::InvokeMethod("mscorlib", "System.Runtime.Versioning", "TargetFrameworkAttribute", 0, NULL, "set_FrameworkName", __native_object__, 1, __parameter_types__, __parameters__, NULL); + } + + + // Get/Set:FrameworkDisplayName + mscorlib::System::String TargetFrameworkAttribute::get_FrameworkDisplayName() const + { + MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Versioning", "TargetFrameworkAttribute", 0, NULL, "get_FrameworkDisplayName", __native_object__, 0, NULL, NULL, NULL); + return mscorlib::System::String(__result__); + } + + void TargetFrameworkAttribute::set_FrameworkDisplayName(mscorlib::System::String value) + { + MonoType *__parameter_types__[1]; + void *__parameters__[1]; + __parameter_types__[0] = Global::GetType(typeid(value).name()); + __parameters__[0] = (MonoObject*)value; + Global::InvokeMethod("mscorlib", "System.Runtime.Versioning", "TargetFrameworkAttribute", 0, NULL, "set_FrameworkDisplayName", __native_object__, 1, __parameter_types__, __parameters__, NULL); + } + + + // Get:TypeId + mscorlib::System::Object TargetFrameworkAttribute::get_TypeId() const + { + MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Attribute", 0, NULL, "get_TypeId", __native_object__, 0, NULL, NULL, NULL); + return mscorlib::System::Object(__result__); + } + + + + } + } + } +} diff --git a/pool/shard007/C++/0096324_car.cpp b/pool/shard007/C++/0096324_car.cpp new file mode 100644 index 0000000000000000000000000000000000000000..897595346848a0d85c8c9e571261c7a49aaf2ca9 --- /dev/null +++ b/pool/shard007/C++/0096324_car.cpp @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2016 Tolga Ceylan + * + * CopyPolicy: Released under the terms of the GNU GPL v3.0. + */ +#include "car.h" +#include "logger.h" +#include "timer.h" +#include "sensor_state.h" +#include "utils.h" +#include +#include +#include + +// diameter of the rotary encoder shaft is 2.0 cm. +// with 1024 ticks for each rotation +#define WHEEL_CIRC (2.0 * (M_PIl)) +#define ENCODER_SCALER (1024.0l / (WHEEL_CIRC) * 2.0l) + +#define PID_KP (0.45f) +#define PID_KI (0.0f) +#define PID_KD (9.0f) + +#define SPEED_STEP (25) + +namespace robo +{ + +int Car::convert_to_speed(const Pid &pid) +{ + const int speed = linear_map( + static_cast(pid.output), + -1024.0l, 1024.0l, + -255.0l, 255.0l + ); + return speed; +} + + +Car::Car(MotorDriver *driver, SensorState *sensors) + : + m_driver(driver), + m_sensors(sensors), + m_left(driver), + m_right(driver), + m_leftSpeed(0), + m_rightSpeed(0), + m_previous(0), + m_period(1) +{ + assert(driver); + assert(sensors); + reset_state(); +} + +Car::~Car() +{ + shutdown(); +} + +void Car::shutdown() +{ + logger(LOG_INFO, "car shutting down"); + m_right.shutdown(); + m_left.shutdown(); + m_driver->execute(); + reset_state(); +} + +void Car::reset_state() +{ + m_leftSpeed = 0; + m_rightSpeed = 0; + + pid_init(m_leftPid, 0, PID_KP, PID_KI, PID_KD); + pid_init(m_rightPid, 1, PID_KP, PID_KI, PID_KD); +} + +int Car::initialize(int left_id, int right_id, uint64_t period) +{ + logger(LOG_INFO, "car initializing with period=%llu", period); + reset_state(); + + int res = 0; + + m_period = period; + m_previous = 0; + + res = m_left.initialize(left_id); + if (res) + goto fail; + + res = m_right.initialize(right_id); + if (res) + goto fail; + + return 0; + +fail: + if (res) + logger(LOG_ERROR, "cannot initialize car err=%d", res); + return res; +} + +int Car::run(int distance) +{ + const int ticks = distance * ENCODER_SCALER; + logger(LOG_INFO, "car run distance=%d ticks=%d", distance, ticks); + + pid_init(m_leftPid, 0, PID_KP, PID_KI, PID_KD); + pid_init(m_rightPid, 1, PID_KP, PID_KI, PID_KD); + + m_leftPid.target = ticks; + m_rightPid.target = ticks; + + m_previous = 0; + return 0; +} + +void Car::stop() +{ + logger(LOG_INFO, "car stopping"); + + m_left.set_speed(0); + m_right.set_speed(0); + + m_driver->execute(); + + reset_state(); +} + +int Car::turn(int angle) +{ + // this is BS, but let's start with something. + const int ticks = angle * ENCODER_SCALER / 5.0f; + + logger(LOG_INFO, "car turn angle=%d ticks=%d", angle, ticks); + + pid_init(m_leftPid, 0, PID_KP, PID_KI, PID_KD); + pid_init(m_rightPid, 1, PID_KP, PID_KI, PID_KD); + + m_leftPid.target = ticks > 0 ? ticks : -ticks; + m_rightPid.target = ticks > 0 ? -ticks : ticks; + + m_previous = 0; + return 0; +} + +int Car::update_pid(uint64_t now, Pid &pid_left, Pid &pid_right) +{ + int res = 0; + int res2 = 0; + + res = m_sensors->m_encoder.error; + if (res) + goto out; + + pid_left.actual = -m_sensors->m_encoder.left; + pid_right.actual = m_sensors->m_encoder.right; + + if (pid_left.target != 0) + logger(LOG_INFO, "Car id=%d left=%u", pid_left.id, pid_left.actual); + if (pid_right.target != 0) + logger(LOG_INFO, "Car id=%d right=%u", pid_right.id, pid_right.actual); + + pid_update(pid_left, now); + pid_update(pid_right, now); + + if (pid_left.target != 0) + pid_logger(pid_left); + if (pid_right.target != 0) + pid_logger(pid_right); + + out: + return res; +} + +int Car::update_wheel(Wheel &wheel, int &speed, Pid &pid, bool &isExecute) +{ + int new_speed = pid.target ? convert_to_speed(pid) : 0; + if (speed == new_speed) + return 0; + + // ramp up slowly + const int delta = new_speed - speed; + if (delta > 0 && delta > SPEED_STEP) + new_speed = speed + SPEED_STEP; + + logger(LOG_INFO, "Car pid=%d old_speed=%d new_speed=%d delta=%d", pid.id, speed, new_speed, delta); + + isExecute = true; + speed = new_speed; + + int res = wheel.set_speed(speed); + if (res) + logger(LOG_ERROR, "Error in wheel set/release err=%d", res); + + return res; +} + +int Car::update(uint64_t now) +{ + if (Timer::get_elapsed_usec(m_previous, now) <= m_period) + return 0; + m_previous = now; + + int res = 0; + bool isExecute = false; + + res = update_pid(now, m_leftPid, m_rightPid); + if (res) { + logger(LOG_ERROR, "Error Car::update update_pid err=%d", res); + goto fail; + } + + res = update_wheel(m_left, m_leftSpeed, m_leftPid, isExecute); + if (res) { + logger(LOG_ERROR, "Error in Car::update update_wheel(left) err=%d", res); + goto fail; + } + + res = update_wheel(m_right, m_rightSpeed, m_rightPid, isExecute); + if (res) { + logger(LOG_ERROR, "Error in Car::update update_wheel(right) err=%d", res); + goto fail; + } + + if (isExecute) { + res = m_driver->execute(); + if (res) { + logger(LOG_ERROR, "Error in Car::update driver execute err=%d", res); + goto fail; + } + } + +fail: + return res; +} + +} // namespace robo + + + diff --git a/pool/shard007/C++/0096325_lomse_doorway.cpp b/pool/shard007/C++/0096325_lomse_doorway.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69a2c193e9c844aeb63ccc04ea474c99a687e8dc --- /dev/null +++ b/pool/shard007/C++/0096325_lomse_doorway.cpp @@ -0,0 +1,266 @@ +//--------------------------------------------------------------------------------------- +// This file is part of the Lomse library. +// Lomse is copyrighted work (c) 2010-2021. 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. +// +// 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. +// +// For any comment, suggestion or feature request, please contact the manager of +// the project at cecilios@users.sourceforge.net +//--------------------------------------------------------------------------------------- + +#define LOMSE_INTERNAL_API +#include "lomse_doorway.h" + +#include "lomse_injectors.h" +#include "lomse_presenter.h" +#include "lomse_import_options.h" +#include "lomse_graphic_view.h" +#include "lomse_bitmap_drawer.h" + +#include "lomse_reader.h" +#include "lomse_events.h" + +#include "agg_basics.h" +#include "agg_pixfmt_rgba.h" +#include "agg_rendering_buffer.h" +#include "agg_trans_viewport.h" +#include "lomse_agg_types.h" +using namespace agg; + +#include +using namespace std; + + +namespace lomse +{ + +//======================================================================================= +//platform independent methods +//======================================================================================= +LomseDoorway::LomseDoorway(std::ostream* logStream, std::ostream* forensicLogStream) + : m_pLibraryScope(nullptr) + , m_platform{ EPixelFormat::k_pix_format_undefined, false, 72.0 } + , m_pFunc_notify(null_notify_function) + , m_pFunc_request(null_request_function) + , m_pObj_notify(nullptr) + , m_pObj_request(nullptr) +{ + logger.init(logStream, forensicLogStream); +} + +//--------------------------------------------------------------------------------------- +LomseDoorway::~LomseDoorway() +{ + delete m_pLibraryScope; +} + +//--------------------------------------------------------------------------------------- +Presenter* LomseDoorway::new_document(int viewType, Drawer* screenDrawer, + Drawer* printDrawer) +{ + if (screenDrawer == nullptr) + screenDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + if (printDrawer == nullptr) + printDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + PresenterBuilder builder(*m_pLibraryScope); + return builder.new_document(viewType, screenDrawer, printDrawer); +} + +//--------------------------------------------------------------------------------------- +Presenter* LomseDoorway::new_document(int viewType, const string& source, int format, + ostream& reporter, Drawer* screenDrawer, + Drawer* printDrawer) + +{ + if (screenDrawer == nullptr) + screenDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + if (printDrawer == nullptr) + printDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + PresenterBuilder builder(*m_pLibraryScope); + return builder.new_document(viewType, screenDrawer, printDrawer, source, + reporter, format); +} + +//--------------------------------------------------------------------------------------- +Presenter* LomseDoorway::open_document(int viewType, const string& filename, + ostream& reporter, Drawer* screenDrawer, + Drawer* printDrawer) +{ + if (screenDrawer == nullptr) + screenDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + if (printDrawer == nullptr) + printDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + PresenterBuilder builder(*m_pLibraryScope); + return builder.open_document(viewType, filename, screenDrawer, printDrawer, reporter); +} + +//--------------------------------------------------------------------------------------- +Presenter* LomseDoorway::open_document(int viewType, LdpReader& reader, + ostream& reporter, Drawer* screenDrawer, + Drawer* printDrawer) +{ + if (screenDrawer == nullptr) + screenDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + if (printDrawer == nullptr) + printDrawer = Injector::inject_BitmapDrawer(*m_pLibraryScope); + + PresenterBuilder builder(*m_pLibraryScope); + return builder.open_document(viewType, reader, screenDrawer, printDrawer, reporter); +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::init_library(int pixel_format, int ppi, bool reverse_y_axis, + ostream& reporter) +{ + //DEPRECATED method Jan/2021 + + m_platform.pixel_format = EPixelFormat(pixel_format); + m_platform.flip_y = reverse_y_axis; + m_platform.screen_ppi = float(ppi); + + delete m_pLibraryScope; + m_pLibraryScope = LOMSE_NEW LibraryScope(reporter, this); +// m_pLibraryScope->get_threads_poll(); //force to create the threads +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::init_library(int pixel_format, int ppi, ostream& reporter) +{ + m_platform.pixel_format = EPixelFormat(pixel_format); + m_platform.screen_ppi = float(ppi); + + delete m_pLibraryScope; + m_pLibraryScope = LOMSE_NEW LibraryScope(reporter, this); +// m_pLibraryScope->get_threads_poll(); //force to create the threads +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::set_notify_callback(void* pThis, + void (*pt2Func)(void* pObj, SpEventInfo event)) +{ + m_pFunc_notify = pt2Func; + m_pObj_notify = pThis; +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::set_request_callback(void* pThis, + void (*pt2Func)(void* pObj, Request* event)) +{ + m_pFunc_request = pt2Func; + m_pObj_request = pThis; +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::set_default_fonts_path(const string& fontsPath) +{ + m_pLibraryScope->set_default_fonts_path(fontsPath); +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::null_notify_function(void* UNUSED(pObj), SpEventInfo UNUSED(event)) +{ + //This is just a mock method to avoid crashes when using the libary without + //initializing it +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::null_request_function(void* UNUSED(pObj), Request* UNUSED(pRequest)) +{ + //This is just a mock method to avoid crashes when using the libary without + //initializing it +} + +//--------------------------------------------------------------------------------------- +int LomseDoorway::get_version_major() +{ + return m_pLibraryScope->get_version_major(); +} + +//--------------------------------------------------------------------------------------- +int LomseDoorway::get_version_minor() +{ + return m_pLibraryScope->get_version_minor(); +} + +//--------------------------------------------------------------------------------------- +int LomseDoorway::get_version_patch() +{ + return m_pLibraryScope->get_version_patch(); +} + +//--------------------------------------------------------------------------------------- +string LomseDoorway::get_version_string() +{ + return m_pLibraryScope->get_version_string(); +} + +//--------------------------------------------------------------------------------------- +string LomseDoorway::get_version_long_string() +{ + return m_pLibraryScope->get_version_long_string(); +} + +//--------------------------------------------------------------------------------------- +string LomseDoorway::get_build_date() +{ + return m_pLibraryScope->get_build_date(); +} + +//--------------------------------------------------------------------------------------- +ScorePlayer* LomseDoorway::create_score_player(MidiServerBase* pSoundServer) +{ + return Injector::inject_ScorePlayer(*m_pLibraryScope, pSoundServer); +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::set_global_metronome_and_replace_local(Metronome* pMtr) +{ + m_pLibraryScope->set_global_metronome_and_replace_local(pMtr); +} + +//--------------------------------------------------------------------------------------- +MusicXmlOptions* LomseDoorway::get_musicxml_options() +{ + return m_pLibraryScope->get_musicxml_options(); +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::post_event(SpEventInfo pEvent) +{ + m_pFunc_notify(m_pObj_notify, pEvent); +} + +//--------------------------------------------------------------------------------------- +void LomseDoorway::post_request(Request* pRequest) +{ + m_pFunc_request(m_pObj_request, pRequest); +} + + +} //namespace lomse diff --git a/pool/shard007/C++/0096326_SASAReader.cpp b/pool/shard007/C++/0096326_SASAReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf7d3a62581d1fd578fb50fd70c02096b540a0ce --- /dev/null +++ b/pool/shard007/C++/0096326_SASAReader.cpp @@ -0,0 +1,78 @@ +/** + k_amber-reader + SASAReader.cpp + Implementation of SASAReader.h + + Author(s): Kevin B. Krause + Version: unreleased +*/ + +#include "SASAReader.h" +#include "Compute.h" + +SASAReader::SASAReader(string filePath) : FileReader(filePath) +{ + +} +//-- +string SASAReader::analyze() +{ + pre_read_greeting(__FUNCTION__, "Finds the average SASA of the molecule and its highest/lowest points"); + + string retVal = ""; + + retVal += "*-*-*-*-*-*-*-*-*-*-* SURFACE.DAT ANALYSIS *-*-*-*-*-*-*-*-*-*-*\n"; + retVal += "INPUT = " + this->getFilePath() + "\n"; + + this->ioFile.open(this->filePath); + + double lowestSurface = DBL_MAX; + double highestSurface = DBL_MIN; + + int lowestFrame = INT_MAX; + int highestFrame = INT_MIN; + + int currentFrame; + double currentSurface; + + vector surfaces; + + // seekg - seek "get" pointer, move it past the initial strings + this->ioFile.seekg(sizeof("#Frame") + sizeof("SA_00000")); + + if (this->ioFile.good()) + { + this->ioFile >> currentFrame; + this->ioFile >> currentSurface; + + while (this->ioFile.good()) + { + surfaces.push_back(currentSurface); + + if (currentSurface < lowestSurface) + { + lowestSurface = currentSurface; + lowestFrame = currentFrame; + } + else if (currentSurface > highestSurface) + { + highestSurface = currentSurface; + highestFrame = currentFrame; + } + + ioFile >> currentFrame >> currentSurface; + } + } + + retVal += "The highest frame was " + to_string(highestFrame) + " with a surface area of " + to_string(highestSurface) + + " squared angstroms" + "\n"; + retVal += "The lowest frame was " + to_string(lowestFrame) + " with a surface area of " + to_string(lowestSurface) + + " squared angstroms" + "\n"; + retVal += "The average exposed surface area was " + to_string(Compute::average(surfaces)) + " angstroms" + "\n"; + retVal += "The standard deviation is +/- " + to_string(Compute::standard_deviation(surfaces)) + " angstroms\n"; + + this->ioFile.close(); + + return retVal; +} +//-- \ No newline at end of file diff --git a/pool/shard007/C++/0096328_classdocument.cpp b/pool/shard007/C++/0096328_classdocument.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccceaa2ef162b13f085d75e271e634dcfc66de01 --- /dev/null +++ b/pool/shard007/C++/0096328_classdocument.cpp @@ -0,0 +1,68 @@ +#include "classdocument.h" + +#include +#include + +#include +#include +#include + +using qf::qmlwidgets::framework::getPlugin; +using Event::EventPlugin; + +namespace Classes { + +ClassDocument::ClassDocument(QObject *parent) + : Super(parent) +{ + qf::core::sql::QueryBuilder qb; + qb.select2("classes", "*") + .from("classes") + .where("classes.id={{ID}}"); + setQueryBuilder(qb); +} + +bool ClassDocument::saveData() +{ + RecordEditMode old_mode = mode(); + bool ret = Super::saveData(); + //Log.info("CompetitorDocument", saveData_qml, "ret:", ret, "old_mode", old_mode, "vs", DataDocument.ModeInsert, old_mode == DataDocument.ModeInsert); + if(ret) { + if(old_mode == DataDocument::ModeInsert) { + // insert classdefs + int class_id = dataId().toInt(); + //int si_id = value("competitors.siId").toInt(); + + int stage_count = getPlugin()->stageCount(); + qf::core::sql::Query q(model()->connectionName()); + q.prepare("INSERT INTO classdefs (classId, stageId) VALUES (:classId, :stageId)"); + for(int i=0; iconnectionName()); + q.prepare("DELETE FROM classdefs WHERE classId = :classId"); + q.bindValue(":classId", id); + q.exec(qf::core::Exception::Throw); + //if(!ret) + // qfError() << q.lastError().text(); + ret = Super::dropData(); + } + return ret; +} + +} diff --git a/pool/shard007/C++/0096331_NewInfoMenu.cpp b/pool/shard007/C++/0096331_NewInfoMenu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80a494be81c90e8f00a7c23f00216ea44242e8c5 --- /dev/null +++ b/pool/shard007/C++/0096331_NewInfoMenu.cpp @@ -0,0 +1,157 @@ +// +// NewInfoMenu.cpp +// tdgame +// +// Created by Wang Nero on 13-7-4. +// +// + +#include "NewInfoMenu.h" +#include "MessageBox.h" +#include "GameScene.h" +#include "SkillTreeMenu.h" +#include "SimpleAudioEngine.h" + +#define MAXCOUNT 3 + +bool NewInfoMenu::init() +{ + if (!CCMenu::init()) + { + return false; + } + + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + infoX = 0; + infoY = winSize.height * 0.5; + this->flush(); + return true; +} + +void NewInfoMenu::createNewInfo(const int messageId) +{ + CCMenuItemImage* newInfo = CCMenuItemImage::create("UI/button/new_normal.png", "UI/button/new_pressed.png"); + newInfo->setTarget(this, menu_selector(NewInfoMenu::showInfoMessage)); + this->addToList(messageId, newInfo); + this->flush(); +} + +void NewInfoMenu::setLocation(const float x,const float y) +{ + this->infoX = x; + this->infoY = y; +} + +void NewInfoMenu::flush() +{ + this->removeAllChildrenWithCleanup(false); + showSkillTreeIcon(); + if(infoBtnList.size() > 0){ + auto p = this->infoBtnList.begin(); + for (int count = 0; count < MAXCOUNT; ++count) { + if(p == this->infoBtnList.end()){ + break; + } + CCMenuItemImage *buffer = p->second; + + this->addAction(buffer); + this->setLocation(buffer, count); + this->addChild(buffer); + p++; + } + } +} + +void NewInfoMenu::addToList(const int message,CCMenuItemImage* const button) +{ + CC_SAFE_RETAIN(button); + this->infoBtnList.push_back(std::pair(message, button)); +} + +bool NewInfoMenu::addAction(CCMenuItemImage* const infoButton) +{ + if(infoButton != NULL){ + infoButton->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCFadeTo::create(1.5f, 100), + CCFadeTo::create(1.5f, 255), + NULL))); + return true; + }else{ + return false; + } +} + +bool NewInfoMenu::setLocation(CCMenuItemImage* const infoButton,int index) +{ + if(infoButton != NULL && index <= 3){ + int distance = infoY - infoButton->getContentSize().height * 1.1 * index; + Function::scaleNodeForScreen(infoButton, ccp(0.5f,0.5f)); + infoButton->setAnchorPoint(ccp(0.0f,0.5f)); + infoButton->setPosition(ccp(infoX,distance)); + return true; + }else{ + return false; + } +} + +int NewInfoMenu::foundMessageAndRemove(CCMenuItemImage* button) +{ + int result = -1; + for(auto p = this->infoBtnList.begin();p != this->infoBtnList.end();p++){ + if(p->second == button){ + result = p->first; + CC_SAFE_RELEASE(p->second); + this->infoBtnList.remove(*p); + break; + } + } + return result; +} + +void NewInfoMenu::showInfoMessage(CCObject* pSender) +{ + if(!CCDirector::sharedDirector()->isPaused()){ + MessageBox* pMessageBox = GameScene::getInstance()->sharedMainUI->getStageUI()->getMessageBox(); + pMessageBox->showEnemyIntroduction(this->foundMessageAndRemove((CCMenuItemImage*)pSender)); + this->flush(); + } +} + +void NewInfoMenu::showSkillTreeIcon() +{ + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + + m_pSkillTreeIcon = CCMenuItemImage::create("UI/button/book_normal.png", "UI/button/book_pressed.png", this, menu_selector(NewInfoMenu::onSkillTree)); + float vx = 0; + float vy = winSize.height * 0.60; + Function::scaleNodeForScreen(m_pSkillTreeIcon, ccp(0.5f,0.5f)); + m_pSkillTreeIcon->setAnchorPoint(ccp(0,0)); + m_pSkillTreeIcon->setPosition(vx,vy); + addChild(m_pSkillTreeIcon); +} + +void NewInfoMenu::onSkillTree(cocos2d::CCObject *pSender) +{ + + if (!GameScene::getInstance()->sharedGameStage->isReady() || + GameScene::getInstance()->sharedGameStage->isPaused()) + { + return; + } + + + if (GameScene::getInstance()->sharedMainUI->getStageUI()->hasMessageBox()) + { + return; + } + + + if (!Player::getInstance()->hasCompletedTutorial()) + { + return; + } + + CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sound/button.wav"); + + GameScene::getInstance()->sharedMainUI->getStageUI()->showSkillTreeMenu(); + +} diff --git a/pool/shard007/C++/0096332_Qt_dispatch_serialqueue_lambda.cpp b/pool/shard007/C++/0096332_Qt_dispatch_serialqueue_lambda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b591a342c9d77ea95ba8988a376e39f66e9359c --- /dev/null +++ b/pool/shard007/C++/0096332_Qt_dispatch_serialqueue_lambda.cpp @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2008-2009 Apple Inc. All rights reserved. +* Copyright (c) 2011-2012 MLBA-Team. All rights reserved. +* +* @MLBA_OPEN_LICENSE_HEADER_START@ +* +* 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. +* +* @MLBA_OPEN_LICENSE_HEADER_END@ +*/ + + +#include +#include + +#include "Qt_tests.h" + + +#define JOBS_NO 20 + +#if TARGET_OS_EMBEDDED +#define LOOP_COUNT 2000000 +#else +#define LOOP_COUNT 100000 +#endif + +/* + Little tests mainly checking the correct mapping of the Qt api + to the underlying C Api + */ + +extern "C" void Qt_dispatch_serialqueue_lambda(){ + char* argv = QString("test").toAscii().data(); + int argc = 1; + QDispatchApplication app(argc,&argv); + + MU_BEGIN_TEST(Qt_dispatch_serialqueue_lambda); + + unsigned int* worker = new unsigned int; + *worker = 0; + + QDispatchQueue q("Qt_dispatch_serialqueue"); + + // dispatch some jobs + for(unsigned int x = 0; x < JOBS_NO; x++) { + q.async(new QLambdaRunnable([=]{ + MU_ASSERT_EQUAL(*worker,x); + // keep cpu busy + for(int i = 0; i < LOOP_COUNT;i++); + *worker = x+1; + })); + + } + + q.async(new QLambdaRunnable([=]{ + MU_ASSERT_EQUAL(*worker,JOBS_NO); + // Test passed + MU_PASS("Blocks were executed in correct order"); + })); + + app.exec(); + MU_END_TEST; +} diff --git a/pool/shard007/C++/0096334_MXADataRecord.cpp b/pool/shard007/C++/0096334_MXADataRecord.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3479491d73385212b7bc3d2d9802904cb187fb49 --- /dev/null +++ b/pool/shard007/C++/0096334_MXADataRecord.cpp @@ -0,0 +1,319 @@ +#include +#include + +// Set the initial value of the _uniqueGUIDValue +int32_t MXADataRecord::_uniqueGUIDValue(0); + +// ----------------------------------------------------------------------------- +// Constructor +// ----------------------------------------------------------------------------- +MXADataRecord::MXADataRecord() : +_luid(0), +_recordName(""), +_altName("") +{ + +} + +// ----------------------------------------------------------------------------- +// Static New Method that is used to construct a new DataRecord Node +// ----------------------------------------------------------------------------- +MXADataRecord::Pointer MXADataRecord::New(int luid, std::string name, std::string altName) +{ + MXADataRecord* rec = new MXADataRecord(); + MXADataRecord::Pointer record(rec); + record->_setWeakPtr(boost::weak_ptr(record)); // Set the Weak Pointer + rec->setLuid(luid); + rec->setGuid( MXADataRecord::nextGUIDValue() ); + rec->setRecordName(name); + rec->setAltName(altName); + return record; +} + +// ----------------------------------------------------------------------------- +// Destructor +// ----------------------------------------------------------------------------- +MXADataRecord::~MXADataRecord() +{ + //std::cout << logTime() << "~MXADataRecord {" << this->_uniqueId << "}" << std::endl; +} + + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::generateLUT(IDataRecord::LookupTable &lut, IDataRecord::Container &nodes) +{ + for ( IDataRecord::Container::iterator iter = nodes.begin(); iter < nodes.end(); ++iter ) + { + // rec = dynamic_cast ( (*(iter)).get() ); //get the Raw pointer to the object + IDataRecord::Pointer node = ( *(iter) ); + lut[node->getUniqueId()] = node; + if (node->hasChildren() ) { + // std::cout << "Creating Group for " << rec->getRecordName() << std::endl; + IDataRecord::Container children = node->getChildren(); + MXADataRecord::generateLUT( lut, children ); + } + } +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- + +void MXADataRecord::printDataRecord(std::ostream& os, int32_t indent) +{ + os << StringUtils::indent(indent) << "*-Record Name: " << this->_recordName << std::endl; + os << StringUtils::indent(indent) << " |-Alternate Name: " << this->_altName << std::endl; + os << StringUtils::indent(indent) << " |-Display Name: " << this->_nodeName << std::endl; + os << StringUtils::indent(indent) << " |-LUID: " << this->_luid << std::endl; + os << StringUtils::indent(indent) << " |-GUID: " << this->getGuid() << std::endl; +#if 0 + for (MXAAttributes::iterator iter = _attributes.begin(); iter != _attributes.end(); ++iter ) + { + os << StringUtils::indent(indent) << " |- Attribute: " << std::endl; + } +#endif + if (this->hasChildren() ) { indent++;} + for (IDataRecord::Container::iterator iter = _children.begin(); iter != _children.end(); ++iter) + { + (*(iter))->printDataRecord(os, indent); + } +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::printDataRecordTree(int32_t depth) +{ + if ( this->hasChildren() ) { + IDataRecord::Container::const_iterator iter; + for (iter=this->_children.begin(); iter!=this->_children.end(); iter++) { + (*iter)->printDataRecordTree(depth+1); + } + } +} + + + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +std::string MXADataRecord::generatePath() +{ + std::string path; + path = StringUtils::numToString(this->_luid); + MXADataRecord* parent = dynamic_cast( this->_parent.lock().get() ); + while( NULL != parent ) + { + path = StringUtils::numToString(parent->getLuid() ) + "/" + path; + parent = dynamic_cast(parent->getParent().lock().get() ); + } + return path; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +std::string MXADataRecord::generateParentPath() +{ + std::string path; + + MXADataRecord* parent = dynamic_cast( this->_parent.lock().get() ); + while( NULL != parent ) + { + path = StringUtils::numToString(parent->getLuid() ) + "/" + path; + parent = dynamic_cast(parent->getParent().lock().get() ); + } + return path; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +int32_t MXADataRecord::writeRecord(IDataRecordWriter* writer) +{ + return writer->writeDataRecord(this); +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +bool MXADataRecord::isValid(std::string &message) +{ + bool valid = true; + if (this->_recordName.empty() || this->_altName.empty()) + { + valid = false; + message.append("Either the Data Record Name or the Alt Name is empty. Both are required to have a value.\n"); + } + return valid; +} + + +// ----------------------------------------------------------------------------- +// This is used to set a weak ptr to itself. The weak ptr is then used when +// another node needs to set this object as its parent. If we did NOT use a weak +// ptr and used a shared ptr then we would end up with a cyclic reference and the +// object would never get deleted because the ref count would never hit zero +// ----------------------------------------------------------------------------- +void MXADataRecord::_setWeakPtr(IDataRecord::WeakPointer weakPtr) +{ + this->_selfPtr = weakPtr; +} + +// ----------------------------------------------------------------------------- +// Used for Unique Ids +// ----------------------------------------------------------------------------- +void MXADataRecord::resetGUIDValue() +{ + _uniqueGUIDValue = 0; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +int32_t MXADataRecord::nextGUIDValue() +{ + return MXADataRecord::_uniqueGUIDValue++; +} + + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::setParent(IDataRecord::WeakPointer parent) +{ + this->_parent = parent; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +IDataRecord::WeakPointer MXADataRecord::getParent() +{ + return this->_parent; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +int32_t MXADataRecord::getNumChildren() const +{ + return static_cast(this->_children.size()); +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +bool MXADataRecord::hasChildren() const +{ + return (this->_children.size() != 0); +} + +// ----------------------------------------------------------------------------- +// Adds a child ONLY if it is NOT already inserted into the children vector +// ----------------------------------------------------------------------------- +void MXADataRecord::addChild(IDataRecord::Pointer child) +{ + child->setParent(this->_selfPtr); + bool alreadyInserted = false; + for (IDataRecord::Container::iterator iter = this->_children.begin(); iter != this->_children.end(); ++iter) + { + if ( (*(iter)).get() == child.get() ) //Compare the raw pointers + { + alreadyInserted = true; + break; + } + } + if (alreadyInserted == false) { + this->_children.push_back(child); + } +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::removeChild(int index) +{ + IDataRecord::Container::iterator iter = this->_children.begin() + index; + this->_children.erase(iter); +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::removeChild(IDataRecord* child) +{ + for (IDataRecord::Container::iterator iter = this->_children.begin(); iter != this->_children.end(); ++iter) + { + if ( (*(iter)).get() == child ) + { + this->_children.erase(iter); + break; + } + } +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::removeAllChildren() +{ + this->_children.clear(); +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +int32_t MXADataRecord::indexOfChild(IDataRecord* child) +{ + int32_t retVal = -1; + int32_t index = 0; + for (IDataRecord::Container::iterator iter = this->_children.begin(); iter != this->_children.end(); ++iter) + { + if ( (*(iter)).get() == child ) + { + return index; + } + index++; + } + return retVal; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +IDataRecord::Pointer MXADataRecord::getChildAt(int32_t index) +{ + if (static_cast(index) < this->_children.size()) + return this->_children[index]; + else { + //std::cout << "MXADataRecord(GUID): " << this->getUniqueId() << " Num Children: " << this->_children.size() << " Index:" << index << std::endl; + } + MXADataRecord::Pointer ptr; + return ptr; +} + +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +IDataRecord::Container& MXADataRecord::getChildren() +{ + return this->_children; +} + +#if 0 +// ----------------------------------------------------------------------------- +// +// ----------------------------------------------------------------------------- +void MXADataRecord::removeAttribute(std::string label) +{ + _nodeAttributes.erase(label); +} + +#endif + + + + diff --git a/pool/shard007/C++/0096336_downscaler.cpp b/pool/shard007/C++/0096336_downscaler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f4f81a2281b836b878d3f467513167bf882e7c8 --- /dev/null +++ b/pool/shard007/C++/0096336_downscaler.cpp @@ -0,0 +1,145 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "graphics/scaler/downscaler.h" +#include "graphics/scaler/intern.h" + +#ifdef USE_ARM_SCALER_ASM +extern "C" { + void DownscaleAllByHalfARM(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height, int mask, int round); +} + +void DownscaleAllByHalf(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + // Rounding constants and masks used for different pixel formats + static const int roundingconstants[] = { 0x00200802, 0x00201002 }; + static const int redbluegreenMasks[] = { 0x03E07C1F, 0x07E0F81F }; + + extern int gBitFormat; + + const int maskUsed = (gBitFormat == 565); + DownscaleAllByHalfARM(srcPtr, srcPitch, dstPtr, dstPitch, width, height, redbluegreenMasks[maskUsed], roundingconstants[maskUsed]); +} + +#else + +template +void DownscaleAllByHalfTemplate(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + uint8 *work; + uint16 srcPitch16 = (uint16)(srcPitch / sizeof(uint16)); + + while ((height -= 2) >= 0) { + work = dstPtr; + + for (int i=0; i(color1, color2, color3, color4); + + work += sizeof(uint16); + } + srcPtr += 2 * srcPitch; + dstPtr += dstPitch; + } +} + +void DownscaleAllByHalf(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + extern int gBitFormat; + if (gBitFormat == 565) + DownscaleAllByHalfTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); + else + DownscaleAllByHalfTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); +} + +#endif + + +/** + * This filter (down)scales the source image horizontally by a factor of 1/2. + * For example, a 320x200 image is scaled to 160x200. + */ +template +void DownscaleHorizByHalfTemplate(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + uint16 *work; + + // Various casts below go via (void *) to avoid warning. This is + // safe as these are all even addresses. + while (height--) { + work = (uint16 *)(void *)dstPtr; + + for (int i = 0; i < width; i += 2) { + uint16 color1 = *(((const uint16 *)(const void *)srcPtr) + i); + uint16 color2 = *(((const uint16 *)(const void *)srcPtr) + (i + 1)); + *work++ = interpolate32_1_1(color1, color2); + } + srcPtr += srcPitch; + dstPtr += dstPitch; + } +} + +void DownscaleHorizByHalf(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + extern int gBitFormat; + if (gBitFormat == 565) + DownscaleHorizByHalfTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); + else + DownscaleHorizByHalfTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); +} + +/** + * This filter (down)scales the source image horizontally by a factor of 3/4. + * For example, a 320x200 image is scaled to 240x200. + */ +template +void DownscaleHorizByThreeQuartersTemplate(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + uint16 *work; + + // Various casts below go via (void *) to avoid warning. This is + // safe as these are all even addresses. + while (height--) { + work = (uint16 *)(void *)dstPtr; + + for (int i = 0; i < width; i += 4) { + // Work with 4 pixels + uint16 color1 = *(((const uint16 *)(const void *)srcPtr) + i); + uint16 color2 = *(((const uint16 *)(const void *)srcPtr) + (i + 1)); + uint16 color3 = *(((const uint16 *)(const void *)srcPtr) + (i + 2)); + uint16 color4 = *(((const uint16 *)(const void *)srcPtr) + (i + 3)); + + work[0] = interpolate32_3_1(color1, color2); + work[1] = interpolate32_1_1(color2, color3); + work[2] = interpolate32_3_1(color4, color3); + + work += 3; + } + srcPtr += srcPitch; + dstPtr += dstPitch; + } +} + +void DownscaleHorizByThreeQuarters(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) { + extern int gBitFormat; + if (gBitFormat == 565) + DownscaleHorizByThreeQuartersTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); + else + DownscaleHorizByThreeQuartersTemplate >(srcPtr, srcPitch, dstPtr, dstPitch, width, height); +} diff --git a/pool/shard007/C++/0096337_cudnn_conv_pad_for_tensor_cores.cc b/pool/shard007/C++/0096337_cudnn_conv_pad_for_tensor_cores.cc new file mode 100644 index 0000000000000000000000000000000000000000..958e0b9c6e7b7885f87b90d61ee5b3bbf6ab2702 --- /dev/null +++ b/pool/shard007/C++/0096337_cudnn_conv_pad_for_tensor_cores.cc @@ -0,0 +1,243 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/compiler/xla/service/gpu/cudnn_conv_pad_for_tensor_cores.h" + +#include "tensorflow/compiler/xla/literal_util.h" +#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" +#include "tensorflow/compiler/xla/service/hlo_casting_utils.h" +#include "tensorflow/compiler/xla/util.h" +#include "tensorflow/compiler/xla/window_util.h" + +namespace xla { +namespace gpu { + +// We won't pad a conv if doing so increases the total number of bytes in the +// lhs, rhs, or result by more than this amount. +// +// TODO(jlebar): This number was tuned experimentally. It represents a +// compromise on our current benchmarks; it speeds some up significantly, and +// doesn't slow any down. But we can observe by changing this value that +// there's additional room for speedups. Achieving those speedups without +// also slowing other things down will likely require a more sophisticated +// heuristic, possibly some form of auto-tuning. +static constexpr double kMaxBytesTouchedIncrease = 1.35; + +// Creates and returns an HLO that zero-pads one or more dimensions in the given +// instruction so that its shape is equal to the given shape. +// +// Padding is added to the end of each relevant dimension. +// +// If the instruction already has the given shape, simply returns it without an +// intervening pad. +static HloInstruction* PadInstruction(HloInstruction* instr, + const Shape& new_shape) { + HloComputation* comp = instr->parent(); + + const Shape& shape = instr->shape(); + auto* zero = comp->AddInstruction( + HloInstruction::CreateConstant(LiteralUtil::Zero(shape.element_type()))); + + PaddingConfig pad_config = MakeNoPaddingConfig(shape.rank()); + + bool added_padding = false; + for (int64 dim = 0; dim < shape.rank(); ++dim) { + if (shape.dimensions(dim) == new_shape.dimensions(dim)) { + continue; + } + CHECK_GT(new_shape.dimensions(dim), shape.dimensions(dim)); + pad_config.mutable_dimensions(dim)->set_edge_padding_high( + new_shape.dimensions(dim) - shape.dimensions(dim)); + added_padding = true; + } + + if (!added_padding) { + return instr; + } + return comp->AddInstruction( + HloInstruction::CreatePad(new_shape, instr, zero, pad_config)); +} + +// Modifies the given convolution to have the given LHS/RHS/result shapes. +static Status PadConv(HloCustomCallInstruction* conv, + const Shape& new_lhs_shape, const Shape& new_rhs_shape, + const Shape& new_result_shape) { + CHECK_EQ(0, conv->shape().tuple_shapes(1).dimensions(0)) + << "conv must use 0 scratch bytes, i.e. this pass must be run " + "before CudnnConvAlgorithmPicker."; + + auto* lhs = conv->mutable_operand(0); + auto* rhs = conv->mutable_operand(1); + auto* new_lhs = PadInstruction(lhs, new_lhs_shape); + auto* new_rhs = PadInstruction(rhs, new_rhs_shape); + const Shape& result_shape = conv->shape().tuple_shapes(0); + CHECK(new_lhs != lhs || new_rhs != rhs) + << "We should have had to pad either LHS or RHS."; + + auto add = [&](std::unique_ptr new_instr) { + return conv->parent()->AddInstruction(std::move(new_instr)); + }; + + Shape new_conv_shape = ShapeUtil::MakeTupleShape( + {new_result_shape, ShapeUtil::MakeShape(U8, {0})}); + auto* new_conv = + add(conv->CloneWithNewOperands(new_conv_shape, {new_lhs, new_rhs})); + + // Slice the new conv result if necessary, keeping in mind that new_conv has + // tuple shape (new_result_shape, u8[0]). + if (!ShapeUtil::Equal(result_shape, new_result_shape)) { + std::vector start_indices(result_shape.dimensions_size(), 0); + std::vector end_indices(result_shape.dimensions().begin(), + result_shape.dimensions().end()); + std::vector strides(result_shape.dimensions_size(), 1); + + auto* new_conv_result = add( + HloInstruction::CreateGetTupleElement(new_result_shape, new_conv, 0)); + auto* empty_temp_buffer = + add(HloInstruction::CreateConstant(LiteralUtil::CreateR1({}))); + auto* sliced_result = add(HloInstruction::CreateSlice( + result_shape, new_conv_result, start_indices, end_indices, strides)); + new_conv = + add(HloInstruction::CreateTuple({sliced_result, empty_temp_buffer})); + } + + VLOG(2) << "Padded features of " << conv->ToString() << ", replaced with " + << new_conv->ToString(); + return conv->parent()->ReplaceInstruction(conv, new_conv); +} + +static StatusOr PadForTensorCores(HloCustomCallInstruction* conv) { + TF_ASSIGN_OR_RETURN(auto kind, GetCudnnConvKind(conv)); + const auto& dnums = conv->convolution_dimension_numbers(); + auto* lhs = conv->mutable_operand(0); + auto* rhs = conv->mutable_operand(1); + const Shape& result_shape = conv->shape().tuple_shapes(0); + + // Nothing to do on non-f16 convolutions. + if (result_shape.element_type() != PrimitiveType::F16) { + return false; + } + + // TODO(timshen): Don't skip forward-activation convs if we find a benchmark + // where there's a speedup. + if (kind == CudnnConvKind::kForwardActivation) { + return false; + } + + Shape new_lhs_shape = lhs->shape(); + Shape new_rhs_shape = rhs->shape(); + Shape new_result_shape = conv->shape().tuple_shapes(0); + + // new_{input,filter_output}_shape points to the appropriate one of + // new_{lhs,rhs,result}_shape. + Shape* new_input_shape; + Shape* new_filter_shape; + Shape* new_output_shape; + std::tie(new_input_shape, new_filter_shape, new_output_shape) = [&] { + switch (kind) { + case CudnnConvKind::kForward: + case CudnnConvKind::kForwardActivation: + return std::make_tuple(&new_lhs_shape, &new_rhs_shape, + &new_result_shape); + case CudnnConvKind::kBackwardInput: + return std::make_tuple(&new_result_shape, &new_rhs_shape, + &new_lhs_shape); + case CudnnConvKind::kBackwardFilter: + return std::make_tuple(&new_lhs_shape, &new_result_shape, + &new_rhs_shape); + } + }(); + + // If there are 3 input features and 32 or 64 output features, pad the input + // features to 4. Otherwise, try padding to multiples of 8 and check that + // this doesn't make any of the conv buffers too much larger. + auto input_features = + new_input_shape->dimensions(dnums.input_feature_dimension()); + auto output_features = + new_output_shape->dimensions(dnums.output_feature_dimension()); + if (input_features == 3 && (output_features == 32 || output_features == 64)) { + new_input_shape->set_dimensions(dnums.input_feature_dimension(), 4); + new_filter_shape->set_dimensions(dnums.kernel_input_feature_dimension(), 4); + } else { + auto pad_dim = [](Shape* s, int64 dim) { + s->set_dimensions(dim, RoundUpToNearest(s->dimensions(dim), 8)); + }; + pad_dim(new_input_shape, dnums.input_feature_dimension()); + pad_dim(new_filter_shape, dnums.kernel_input_feature_dimension()); + pad_dim(new_filter_shape, dnums.kernel_output_feature_dimension()); + pad_dim(new_output_shape, dnums.output_feature_dimension()); + + // Check that padding wouldn't increase the total bytes read/written by this + // operation too much. + auto check_size_increase = [&](const Shape& old_shape, + const Shape& new_shape) { + int64 old_bytes = ShapeUtil::ByteSizeOf(old_shape); + int64 new_bytes = ShapeUtil::ByteSizeOf(new_shape); + if (new_bytes <= old_bytes * kMaxBytesTouchedIncrease) { + return true; + } + VLOG(3) + << "Not padding convolution; doing so would change input / result " + "shape from " + << ShapeUtil::HumanString(old_shape) << " to " + << ShapeUtil::HumanString(new_shape) << ", a size increase of " + << new_bytes / static_cast(old_bytes) << "x > " + << kMaxBytesTouchedIncrease << "x: " << conv->ToString(); + return false; + }; + + if (!check_size_increase(lhs->shape(), new_lhs_shape) || + !check_size_increase(rhs->shape(), new_rhs_shape) || + !check_size_increase(result_shape, new_result_shape)) { + return false; + } + } + + if (ShapeUtil::Equal(lhs->shape(), new_lhs_shape) && + ShapeUtil::Equal(rhs->shape(), new_rhs_shape)) { + VLOG(3) << "No need to pad features of " << conv->ToString(); + return false; + } + + // OK, let's do the transformation! + TF_RETURN_IF_ERROR( + PadConv(conv, new_lhs_shape, new_rhs_shape, new_result_shape)); + return true; +} + +static std::vector GetRelevantConvs( + HloComputation* comp) { + std::vector convs; + for (HloInstruction* instr : comp->instructions()) { + if (IsCustomCallToDnnConvolution(*instr)) { + convs.push_back(Cast(instr)); + } + } + return convs; +} + +StatusOr CudnnConvPadForTensorCores::Run(HloModule* module) { + bool changed = false; + for (HloComputation* comp : module->MakeNonfusionComputations()) { + for (HloCustomCallInstruction* conv : GetRelevantConvs(comp)) { + TF_ASSIGN_OR_RETURN(bool result, PadForTensorCores(conv)); + changed |= result; + } + } + return changed; +} + +} // namespace gpu +} // namespace xla diff --git a/pool/shard007/C++/0096340_UnitDefinition.cpp b/pool/shard007/C++/0096340_UnitDefinition.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4889d3d4e0afe49b61765ac98cd17308854f1cb0 --- /dev/null +++ b/pool/shard007/C++/0096340_UnitDefinition.cpp @@ -0,0 +1,256 @@ +#include +#include +//Begin section for file UnitDefinition.cpp +//TODO: Add definitions that you want preserved +//End section for file UnitDefinition.cpp + +UniPAX::UnitDefinition::UnitDefinition() : UniPAX::SBase()//, pathway(0) +{ +} + +UniPAX::UnitDefinition::UnitDefinition(const UnitDefinition & arg) : UniPAX::SBase(arg) , + id(arg.id), + name(arg.name), + //pathway(arg.pathway), + unit(arg.unit) +{} + +UniPAX::UnitDefinition & UniPAX::UnitDefinition::operator =(const UnitDefinition & arg) { + UniPAX::SBase::operator=(arg); + id = arg.id; + name = arg.name; + //pathway = arg.pathway; + unit = arg.unit; + + return *this; +} + +UniPAX::UnitDefinition::~UnitDefinition() { +} + +bool UniPAX::UnitDefinition::merge(UnitDefinition& object) +{ + if (id.empty()) + { + id = object.getId(); + } + else + { + if (id.compare(object.getId()) != 0) + { + std::cerr << "Error during merging: UniPAX::Model::id not equal ..." + << id << " != " << object.getId() << std::endl; + return false; + } + } + + if (name.empty()) + { + name = object.getName(); + } + else + { + if (name.compare(object.getName()) != 0) + { + std::cerr << "Error during merging: UniPAX::Model::name not equal ..." + << name << " != " << object.getName() << std::endl; + return false; + } + } + + { + std::set tmp(getUnits().begin(), getUnits().end()); + for (std::vector::iterator it = object.getUnits().begin(); it != object.getUnits().end(); it++) + { + if (*it != 0) + { + tmp.insert(*it); + } + } + getUnits().assign(tmp.begin(), tmp.end()); + } + + return UniPAX::SBase::merge(object); +} + +bool UniPAX::UnitDefinition::update(PersistenceManager& manager) +{ + + { + std::vector > tmp_vec; + std::vector >::iterator it; + for (it = unit.begin(); it != unit.end(); it++) + { + if (manager.isMerged(*it)) + tmp_vec.push_back(boost::dynamic_pointer_cast(manager.getMergedObject(*it))); + else + tmp_vec.push_back(*it); + } + setUnits(tmp_vec); + } + + return UniPAX::SBase::update(manager); +} + +/*const boost::shared_ptr UniPAX::UnitDefinition::getPathway() const { + return pathway; + } + + boost::shared_ptr UniPAX::UnitDefinition::getPathway() { + return pathway; + } + + void boost::shared_ptr _pathway) { + pathway = _pathway; + }*/ + +const std::string & UniPAX::UnitDefinition::getId() const { + return id; +} + +std::string & UniPAX::UnitDefinition::getId() { + return id; +} + +void UniPAX::UnitDefinition::setId(std::string _id) { + id = _id; +} + +const std::string & UniPAX::UnitDefinition::getName() const { + return name; +} + +std::string & UniPAX::UnitDefinition::getName() { + return name; +} + +void UniPAX::UnitDefinition::setName(std::string _name) { + name = _name; +} + +const std::vector > UniPAX::UnitDefinition::getUnits() const { + return unit; +} + +std::vector > UniPAX::UnitDefinition::getUnits() { + return unit; +} +void UniPAX::UnitDefinition::setUnits(std::vector > _units) { + unit = _units; +} +void UniPAX::UnitDefinition::addUnit(boost::shared_ptr _unit) +{ + unit.push_back(_unit); +} + + +bool UniPAX::UnitDefinition::setAttribute(std::string& attribute, std::string& value, PersistenceManager& manager) { + if (UniPAX::SBase::setAttribute(attribute, value, manager)) + return true; + + if (boost::iequals(attribute,"id")) + { + setId(value); + return true; + } + if (boost::iequals(attribute,"name")) + { + setName(value); + return true; + } + /*if (boost::iequals(attribute,"pathway")) + { + if (value == "NIL" || value.empty()) + return true; + boost::shared_ptr object = manager.getInstance(value,""); + if (object == 0) + { + std::cerr << "UnitDefinition::setAttribute - object not known (value = " << value << ")" << std::endl; + return false; + } + + pathway = boost::dynamic_pointer_cast(object); + return true; + + }*/ + if (boost::iequals(attribute,"unit")) + { + // if sometimes set to NIL or empty string neglect + if (value == "NIL" || value.empty()) + return true; + + boost::shared_ptr object = manager.getInstance(value,""); + if (object == 0) + { + std::cerr << "UnitDefinition::setAttribute - object not known (value = " << value << ")" << std::endl; + return false; + } + + unit.push_back(boost::dynamic_pointer_cast(object)); + return true; + } + + return false; +} + + +bool UniPAX::UnitDefinition::getAttribute(std::vector >& value, PersistenceManager& manager) { + if (!UniPAX::SBase::getAttribute(value, manager)) + return false; + { + if (! getId().empty()) + value.push_back(std::pair("id", getId())); + } + { + if (! getName().empty()) + value.push_back(std::pair("name", getName())); + } + std::string tmp = ""; + { + std::vector >::iterator it; + for (it = unit.begin(); it != unit.end(); it++) + { + if (*it == 0) + { + } + else + { + if (!manager.getId(*it,tmp)) + { + manager.setError(this->type() + ":unit contains unknown reference."); + return false; + } + value.push_back(std::pair("#unit", tmp)); + + } + } + } + tmp.clear(); + /*{ + if (*pathway == 0) + { + } + else + { + if (!manager.getId(*pathway,tmp)) + { + manager.setError(this->type() + ":pathway contains unknown reference."); + return false; + } + value.push_back(std::pair("#pathway", tmp)); + + } + + }*/ + + return true; + +} + + +//void UniPAX::UnitDefinition::init (odb::callback_event e, odb::database& db) const +//{ +// UniPAX::SBase::init(e,db); +// +// return; +//} diff --git a/pool/shard007/C++/0096342_PMovie.cpp b/pool/shard007/C++/0096342_PMovie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1871c743c1a80f4ddba1368a5288b27da2e419d4 --- /dev/null +++ b/pool/shard007/C++/0096342_PMovie.cpp @@ -0,0 +1,169 @@ +//* -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- */ +///////////////////////////////////////////////////////////////////////////////// +// Name: src/objects/PMovie.cpp +// Purpose: Contains generic specification for a movie player widget. +// Author: Shane T. Mueller, Ph.D. +// Copyright: (c) 2012-2013 Shane T. Mueller +// License: GPL 2 +// +// +// +// This file is part of the PEBL project. +// +// PEBL 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. +// +// PEBL 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 PEBL; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + + +#include "PMovie.h" +#include "../utility/Defs.h" +#include + +using std::cout; + +PMovie::PMovie(): + PWidget() +{ + InitializeProperty("NAME",Variant("")); + InitializeProperty("FILENAME","UNKNOWN"); + InitializeProperty("DURATION",0); + InitializeProperty("PLAYBACKPOSITION",0); + InitializeProperty("VOLUME",1); + __SetProps__(); + +} + +///This sets the imagebox's position on its parent widget. +///It overrides the parent method because images positions +///are set by their centers. +void PMovie::SetPosition(int x, int y) +{ + + + PWidget::SetPosition(x,y); + mDrawX = x - GetWidth()/2; + mDrawY = y - GetHeight()/2; +} + +void PMovie::SetSize(int width, int height) +{ + mWidth = width; + mHeight = height; + + PEBLObjectBase::SetProperty("WIDTH",width); + PEBLObjectBase::SetProperty("HEIGHT",height); + +} + + +void PMovie::SetPlaybackPosition(long unsigned int pos) +{ + mPlaybackPosition = pos; + PEBLObjectBase::SetProperty("PLAYBACKPOSITION",pos); + +} + + +void PMovie::SetVolume(long double v) +{ + PEBLObjectBase::SetProperty("VOLUME",(pDouble)v); +} + + +//overloaded generic PEBLObjectBase methods +bool PMovie::SetProperty(std::string name, Variant v) +{ + + //Width and height are not currently 'settable', in that + //they are properties of the object. + + if(name == "X") SetPosition(v,mY); + else if (name == "Y") SetPosition(mX,v); + else if (name == "HEIGHT") SetSize(v,mWidth); + else if (name == "WIDTH") SetSize(mHeight, v); + else if (name == "DURATION") + PEBLObjectBase::SetProperty("DURATION",v); + else if (name == "PLAYBACKPOSITION") SetPlaybackPosition(v); + else if (name == "VOLUME") SetVolume((pDouble)v); + else if (name == "FILENAME") + PEBLObjectBase::SetProperty("FILENAME",v); + else if (name == "VISIBLE") + { + if(v.GetInteger()) + Show(); + else + Hide(); + } + else return PWidget::SetProperty(name,v); + + return true; +} + + + +Variant PMovie::GetProperty(std::string name)const +{ + + return PEBLObjectBase::GetProperty(name); +} + + +ObjectValidationError PMovie::ValidateProperty(std::string name, Variant v)const +{ + ObjectValidationError code = ValidateProperty(name); + if((code==OVE_VALID) & (name == "VOLUME")) + { + + if((pDouble)v < 0) + { + code = OVE_INVALID_PROPERTY_VALUE; + } + } + + return code; +} + +ObjectValidationError PMovie::ValidateProperty(std::string name)const +{ + //All valid properties are also valid Widget properties + ObjectValidationError ove = PWidget::ValidateProperty(name); + if(ove == OVE_VALID) + { + return ove; + } + else if(name =="WIDTH" || + name == "HEIGHT"|| + name == "DURATION"|| + name == "FILENAME"|| + name == "PLAYBACKPOSITION" || + name == "VOLUME" ) + + return OVE_VALID; + else + return OVE_INVALID_PROPERTY_NAME; +} + + + +//This makes sure that the object properties are synced with the class properties. +void PMovie::__SetProps__() +{ + + SetProperty("X",mX); + SetProperty("Y",mY); + SetProperty("VISIBLE",mIsVisible); + SetProperty("WIDTH",mWidth); + SetProperty("HEIGHT",mHeight); + +} diff --git a/pool/shard007/C++/0096343_records.cpp b/pool/shard007/C++/0096343_records.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2262e7d19bb005ef79733623fce9550989d363a --- /dev/null +++ b/pool/shard007/C++/0096343_records.cpp @@ -0,0 +1,122 @@ + +/* + +Repair -- an implementation of Larsson and Moffat's compression and +decompression algorithms. +Copyright (C) 2010-current_year Gonzalo Navarro + +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. + +Author's contact: Gonzalo Navarro, Dept. of Computer Science, University of +Chile. Blanco Encalada 2120, Santiago, Chile. gnavarro@dcc.uchile.cl + +*/ + + // extendible array for pairs + +#include +#include "records.h" + +int +Records::insertRecord (Trarray *Rec, Tpair pair) +{ + int id; + Trecord *rec; + if (Rec->size == Rec->maxsize) + { if (Rec->maxsize == 0) + { Rec->maxsize = Rec->minsize; + Rec->records = (Trecord*)malloc (Rec->maxsize * sizeof(Trecord)); + } + else + { Rec->maxsize /= Rec->factor; + Rec->records = (Trecord*)realloc (Rec->records, Rec->maxsize * sizeof(Trecord)); + } + } + id = Rec->size++; + rec = &Rec->records[id]; + rec->pair = pair; + Hash::insertHash ((Thash*)Rec->Hash,id); + Heap::insertHeap ((Theap*)Rec->Heap,id); + return id; +} + +void +Records::deleteRecord (Trarray *Rec) +{ + Rec->size--; + if (Rec->size == 0) + { Rec->maxsize = 0; + free (Rec->records); + Rec->records = NULL; + } + else if ((Rec->size < Rec->maxsize * Rec->factor * Rec->factor) && + (Rec->size * Rec->factor >= Rec->minsize)) + { Rec->maxsize *= Rec->factor; + Rec->records = (Trecord*)realloc (Rec->records, Rec->maxsize * sizeof(Trecord)); + } +} + +Trarray +Records::createRecords (float factor, int minsize) +{ + Trarray Rec; + Rec.records = NULL; + Rec.maxsize = 0; + Rec.size = 0; + Rec.factor = factor; + Rec.minsize = minsize; + Rec.Hash = NULL; + Rec.Heap = NULL; + Rec.List = NULL; + return Rec; +} + +void +Records::assocRecords (Trarray *Rec, void *Hash, void *Heap, void *List) +{ + Rec->Hash = Hash; + Rec->Heap = Heap; + Rec->List = List; +} + +void +Records::destroyRecords (Trarray *Rec) +{ + if (Rec->maxsize == 0) return; + free (Rec->records); + Rec->records = NULL; + Rec->maxsize = 0; + Rec->size = 0; + Rec->Hash = NULL; + Rec->Heap = NULL; + Rec->List = NULL; +} + +void +Records::removeRecord (Trarray *Rec, int id) +{ + Tlist *L = (Tlist*)Rec->List; + Hash::deleteHash ((Thash*)Rec->Hash,id); // mark del in hash + if ((Rec->records[id].cpos != -1) && + (L[Rec->records[id].cpos].prev == -id-1)) + L[Rec->records[id].cpos].prev = NullFreq; // null ptr from L + if (id != Rec->size-1) + { Rec->records[id] = Rec->records[Rec->size-1]; + Hash::hashRepos ((Thash*)Rec->Hash,id); + Heap::heapRepos ((Theap*)Rec->Heap,id); + L[Rec->records[id].cpos].prev = -id-1; + } + deleteRecord (Rec); +} diff --git a/pool/shard007/C++/0096347_StringPool.cpp b/pool/shard007/C++/0096347_StringPool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8eef9580560bb35bf9390ca3ae62fe781949c64 --- /dev/null +++ b/pool/shard007/C++/0096347_StringPool.cpp @@ -0,0 +1,109 @@ +// Copyright (C) by Ashton Mason. See LICENSE.txt for licensing information. + + +#include +#include + +#include +#include + + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning (disable:4996) // function or variable may be unsafe. +#endif //_MSC_VER + + +namespace Theron +{ +namespace Detail +{ + + +StringPool::Container *StringPool::smContainer = 0; +Mutex StringPool::smMutex; +uint32_t StringPool::smReferenceCount = 0; + + +void StringPool::Reference() +{ + Lock lock(smMutex); + + // Create the singleton instance if this is the first reference. + if (smReferenceCount++ == 0) + { + IAllocator *const allocator(AllocatorManager::GetCache()); + void *const memory(allocator->AllocateAligned(sizeof(Container), THERON_CACHELINE_ALIGNMENT)); + smContainer = new (memory) Container(); + } +} + + +void StringPool::Dereference() +{ + Lock lock(smMutex); + + // Destroy the singleton instance if this was the last reference. + if (--smReferenceCount == 0) + { + IAllocator *const allocator(AllocatorManager::GetCache()); + smContainer->~Container(); + allocator->Free(smContainer, sizeof(Container)); + } +} + + +StringPool::Container::Container() +{ +} + + +StringPool::Container::~Container() +{ + IAllocator *const allocator(AllocatorManager::GetCache()); + + // Free all entries. + while (!mEntries.Empty()) + { + Entry *const entry(mEntries.Front()); + mEntries.Remove(entry); + + entry->~Entry(); + allocator->Free(entry, sizeof(Entry)); + } +} + + +const char *StringPool::Container::Get(const char *const str) +{ + Lock lock(mMutex); + + // TODO: For now we linear search and strcmp every entry! + // Search for an existing entry for this string. + List::Iterator entries(mEntries.GetIterator()); + while (entries.Next()) + { + Entry *const entry(entries.Get()); + if (strcmp(entry->Value(), str) == 0) + { + return entry->Value(); + } + } + + // Create a new entry. + IAllocator *const allocator(AllocatorManager::GetCache()); + void *const memory(allocator->Allocate(sizeof(Entry))); + Entry *const entry = new (memory) Entry(str); + + mEntries.Insert(entry); + return entry->Value(); +} + + +} // namespace Detail +} // namespace Theron + + +#ifdef _MSC_VER +#pragma warning(pop) +#endif //_MSC_VER diff --git a/pool/shard007/C++/0096348_outputmessage.cpp b/pool/shard007/C++/0096348_outputmessage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7f85688b77e0d88141a3138b8f03d3c1567d105 --- /dev/null +++ b/pool/shard007/C++/0096348_outputmessage.cpp @@ -0,0 +1,202 @@ +/** + * The Forgotten Server - a free and open-source MMORPG server emulator + * Copyright (C) 2014 Mark Samman + * + * 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 "otpch.h" + +#include "outputmessage.h" +#include "protocol.h" +#include "scheduler.h" + +#ifdef ENABLE_SERVER_DIAGNOSTIC +uint32_t OutputMessagePool::OutputMessagePoolCount = OUTPUT_POOL_SIZE; +#endif + +OutputMessage::OutputMessage() +{ + freeMessage(); +} + +//*********** OutputMessagePool ****************// + +OutputMessagePool::OutputMessagePool() +{ + for (uint32_t i = 0; i < OUTPUT_POOL_SIZE; ++i) { + OutputMessage* msg = new OutputMessage(); + m_outputMessages.push_back(msg); + } + + m_frameTime = OTSYS_TIME(); +} + +void OutputMessagePool::startExecutionFrame() +{ + //std::lock_guard lockClass(m_outputPoolLock); + m_frameTime = OTSYS_TIME(); + m_isOpen = true; +} + +OutputMessagePool::~OutputMessagePool() +{ + for (OutputMessage* msg : m_outputMessages) { + delete msg; + } +} + +void OutputMessagePool::send(OutputMessage_ptr msg) +{ + m_outputPoolLock.lock(); + OutputMessage::OutputMessageState state = msg->getState(); + m_outputPoolLock.unlock(); + + if (state == OutputMessage::STATE_ALLOCATED_NO_AUTOSEND) { + Connection_ptr connection = msg->getConnection(); + if (connection && !connection->send(msg)) { + // Send only fails when connection is closing (or in error state) + // This call will free the message + msg->getProtocol()->onSendMessage(msg); + } + } +} + +void OutputMessagePool::sendAll() +{ + std::lock_guard lockClass(m_outputPoolLock); + + const int64_t dropTime = m_frameTime - 10000; + const int64_t frameTime = m_frameTime - 10; + + for (OutputMessage_ptr omsg : m_toAddQueue) { + const int64_t msgFrame = omsg->getFrame(); + if (msgFrame >= dropTime) { + omsg->setState(OutputMessage::STATE_ALLOCATED); + + if (frameTime > msgFrame) { + m_autoSendOutputMessages.push_front(omsg); + } else { + m_autoSendOutputMessages.push_back(omsg); + } + } else { + //drop messages that are older than 10 seconds + omsg->getProtocol()->onSendMessage(omsg); + } + } + m_toAddQueue.clear(); + + for (auto it = m_autoSendOutputMessages.begin(), end = m_autoSendOutputMessages.end(); it != end; it = m_autoSendOutputMessages.erase(it)) { + OutputMessage_ptr omsg = *it; + if (frameTime <= omsg->getFrame()) { + break; + } + + Connection_ptr connection = omsg->getConnection(); + if (connection && !connection->send(omsg)) { + // Send only fails when connection is closing (or in error state) + // This call will free the message + omsg->getProtocol()->onSendMessage(omsg); + } + } +} + +void OutputMessagePool::releaseMessage(OutputMessage* msg) +{ + g_dispatcher.addTask( + createTask(std::bind(&OutputMessagePool::internalReleaseMessage, this, msg))); +} + +void OutputMessagePool::internalReleaseMessage(OutputMessage* msg) +{ + if (msg->getProtocol()) { + msg->getProtocol()->unRef(); + } else { + std::cout << "No protocol found." << std::endl; + } + + if (msg->getConnection()) { + msg->getConnection()->unRef(); + } else { + std::cout << "No connection found." << std::endl; + } + + msg->freeMessage(); + + m_outputPoolLock.lock(); + m_outputMessages.push_back(msg); + m_outputPoolLock.unlock(); +} + +OutputMessage_ptr OutputMessagePool::getOutputMessage(Protocol* protocol, bool autosend /*= true*/) +{ + if (!m_isOpen) { + return OutputMessage_ptr(); + } + + std::lock_guard lockClass(m_outputPoolLock); + + if (!protocol->getConnection()) { + return OutputMessage_ptr(); + } + + if (m_outputMessages.empty()) { + OutputMessage* msg = new OutputMessage(); + m_outputMessages.push_back(msg); + +#ifdef ENABLE_SERVER_DIAGNOSTIC + OutputMessagePoolCount++; +#endif + } + + OutputMessage_ptr outputmessage; + outputmessage.reset(m_outputMessages.back(), + std::bind(&OutputMessagePool::releaseMessage, this, std::placeholders::_1)); + + m_outputMessages.pop_back(); + + configureOutputMessage(outputmessage, protocol, autosend); + return outputmessage; +} + +void OutputMessagePool::configureOutputMessage(OutputMessage_ptr msg, Protocol* protocol, bool autosend) +{ + msg->Reset(); + + if (autosend) { + msg->setState(OutputMessage::STATE_ALLOCATED); + m_autoSendOutputMessages.push_back(msg); + } else { + msg->setState(OutputMessage::STATE_ALLOCATED_NO_AUTOSEND); + } + + Connection_ptr connection = protocol->getConnection(); + assert(connection); + + msg->setProtocol(protocol); + protocol->addRef(); + + msg->setConnection(connection); + connection->addRef(); + + msg->setFrame(m_frameTime); +} + +void OutputMessagePool::addToAutoSend(OutputMessage_ptr msg) +{ + m_outputPoolLock.lock(); + m_toAddQueue.push_back(msg); + m_outputPoolLock.unlock(); +} diff --git a/pool/shard007/C++/0096354_CollisionDetector.cpp b/pool/shard007/C++/0096354_CollisionDetector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a970a80224cc6cb5aa0f1f09c21de541dfed1b55 --- /dev/null +++ b/pool/shard007/C++/0096354_CollisionDetector.cpp @@ -0,0 +1,42 @@ +#include "stdafx.h" +#include "CollisionDetector.h" +#include "Vect2D.h" + +cCollisionDetector::cCollisionDetector() +{ +} + + +cCollisionDetector::~cCollisionDetector() +{ +} + +bool cCollisionDetector::EntityCollision(const cEntity & entity1 , const cEntity & entity2) +{ + + bool bReturn; + float distE1, distE2, distPositionE12; + cVect2D dir, entity1Pos, entity2Pos; + + dir = entity1.GetPosition(); + dir -= entity2.GetPosition(); + + entity1Pos = entity1.GetPosition(); + entity2Pos = entity2.GetPosition(); + + distE1 = entity1.GetDistance(dir); + dir *= -1; + distE2 = entity2.GetDistance(dir); + + distPositionE12 = sqrt(pow(entity1Pos.GetX() - entity2Pos.GetX(), 2) + pow(entity1Pos.GetY() - entity2Pos.GetY(), 2)); + + if (distPositionE12 < distE1 + distE2) + { + bReturn = true; + } + else + { + bReturn = false; + } + return bReturn; +} diff --git a/pool/shard007/C++/0096356_imagemodel.cpp b/pool/shard007/C++/0096356_imagemodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3c30657894298ee5b200cb6fab295b57037b710 --- /dev/null +++ b/pool/shard007/C++/0096356_imagemodel.cpp @@ -0,0 +1,237 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crawler/crawler.hpp" +#include "crawler/types.hpp" +#include "tags/image.hpp" +#include "tags/tagdataroles.hpp" +#include "tags/tagcontainer.hpp" +#include "imagemodel.hpp" + +namespace Coquillo { + namespace TagEditor { + + QVariantMap read_file(const QString & path) { + return Crawler::FileReader().read(path, true); + } + + ImageModel::ImageModel(QObject * parent) + : QAbstractTableModel(parent), _source(0) { + _nam = new QNetworkAccessManager(this); + } + + Tags::Image ImageModel::image(int pos) const { + return container().image(pos); + } + + QVariant ImageModel::data(const QModelIndex & idx, int role) const { + if (!sourceModel()) { + return QVariant(); + } + + if (role == Qt::SizeHintRole) { + const auto size = container().image(idx.row()).scaled(QSize(128, 128)).size(); + return size + QSize(0, 10); + } + + if (role == Qt::DecorationRole and (idx.column() == 0 or idx.column() == 3)) { + const auto image = container().image(idx.row()); + return image.scaled(QSize(128, 128)); + } + + if (role == Qt::DisplayRole or role == Qt::EditRole) { + const auto file = container(); + const auto image = file.image(idx.row()); + + switch (idx.column()) { + case 0: + return image.description(); + case 1: + return image.type(); + case 2: + return image.mimeType(); + case 3: { + const QStringList info = { + image.description(), + QString("%1x%2 px").arg(image.width()).arg(image.height()), + image.mimeType(), + }; + return info.join('\n'); + } + } + } + + return QVariant(); + } + + void ImageModel::download(const QUrl & url) { + QNetworkReply * reply = _nam->get(QNetworkRequest(url)); + + connect(reply, &QNetworkReply::finished, [=]() { + if (reply->isReadable()) { + addRawImage(QImage::fromData(reply->readAll())); + reply->deleteLater(); + } else { + qWarning() << "Failed to read data" << reply->error(); + } + }); + } + + bool ImageModel::dropMimeData(const QMimeData * data, Qt::DropAction, int, int, const QModelIndex &) { + foreach (const QUrl & url, data->urls()) { + if (url.isLocalFile()) { + addRawImage(QImage(url.path())); + } else { + download(url); + } + } + + if (data->hasImage()) { + addRawImage(qvariant_cast(data->imageData())); + } + + return false; + } + + Qt::ItemFlags ImageModel::flags(const QModelIndex & idx) const { + return QAbstractTableModel::flags(idx) | Qt::ItemIsDropEnabled; + } + + QVariant ImageModel::headerData(int section, Qt::Orientation orientation, int role) const { + if ((role == Qt::DisplayRole or role == Qt::EditRole) and orientation == Qt::Horizontal) { + return ((QStringList){tr("Image"), tr("Type"), tr("Description")})[section]; + } + return QVariant(); + } + + QStringList ImageModel::mimeTypes() const { + return { "text/uri-list", "image/png", "image/jpeg", "image/gif" }; + } + + bool ImageModel::removeRows(int row, int count, const QModelIndex & parent) { + if (row < 0 || row + count > rowCount() || parent.isValid()) { + return false; + } else { + beginRemoveRows(parent, row, row + count - 1); + QList images = container().images(); + images.erase(images.begin() + row, images.begin() + row + count); + sourceModel()->setData(_index, QVariant::fromValue(images)); + endRemoveRows(); + return true; + } + } + + int ImageModel::rowCount(const QModelIndex & parent) const { + if (!sourceModel() || parent.isValid()) { + return 0; + } + + return container().images().size(); + } + + bool ImageModel::setData(const QModelIndex & idx, const QVariant & value, int role) { + if (!idx.isValid() || role != Qt::EditRole) { + return false; + } + + auto images = container().images(); + auto & image = images[idx.row()]; + + // Dirty hack to filter the fake edits by data widget mapper. + switch (idx.column()) { + case 0: + if (image.description() == value.toString()) { + return false; + } + image.setDescription(value.toString()); + break; + case 1: + if (image.type() == value.toInt()) { + return false; + } + image.setType(value.toInt()); + break; + default: + return false; + } + + if (sourceModel()->setData(_index, QVariant::fromValue(images))) { + emit dataChanged(idx, idx); + return true; + } + + return false; + } + + void ImageModel::setSourceIndex(const QModelIndex & idx) { + beginResetModel(); + _index = idx; + endResetModel(); + + initializeImages(idx); + } + + void ImageModel::initializeImages(const QPersistentModelIndex & idx) { + const auto file = container(); + + if (file.imageCount() > 0 && file.images().size() == 0) { + auto watcher = new QFutureWatcher(this); + const QString path = idx.data(Tags::FilePathRole).toString(); + + watcher->setFuture(QtConcurrent::run(&read_file, path)); + + connect(watcher, &QFutureWatcher::finished, watcher, [this, watcher, idx]{ + if (idx != _index) { + return; + } + + const ImageDataList result = watcher->result().value("images").value(); + QList images; + + foreach (const ImageData item, result) { + images << Tags::Image::fromValues(item); + } + + if (images.size() > 0) { + // setSourceIndex(idx); + + beginInsertRows(QModelIndex(), 0, images.size() - 1); + sourceModel()->setData(idx, QVariant::fromValue(images)); + endInsertRows(); + } + watcher->deleteLater(); + }); + } + } + + Tags::Container ImageModel::container() const { + return _index.data(Tags::ContainerRole).value(); + } + + void ImageModel::addRawImage(const QImage & source) { + if (source.isNull()) { + return; + } + + Tags::Image image(source); + addImage(image); + } + + void ImageModel::addImage(const Tags::Image & image) { + auto images = container().images() << image; + + beginInsertRows(QModelIndex(), 0, images.size() - 1); + sourceModel()->setData(_index, QVariant::fromValue(images)); + endInsertRows(); + } + } +} diff --git a/pool/shard007/C++/0096368_Homework-1.cpp b/pool/shard007/C++/0096368_Homework-1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fcbcf3f303c2bc0132864021bf191778433b3e4 --- /dev/null +++ b/pool/shard007/C++/0096368_Homework-1.cpp @@ -0,0 +1,135 @@ +#include +#include +#include + +using namespace std; + +/* Declaration of the Structure used to store the different budget variables. */ +struct MonthlyBudget { + double housing; + double utilities; + double household_expenses; + double transportation; + double food; + double medical; + double insurance; + double entertainment; + double clothing; + double misc; +}; + +MonthlyBudget AskUser(); +string Calculate(double budget, double goal); +string Round(double dbl); +void Report(MonthlyBudget budget); + +/* Declared Constants for the budget goals. */ +const double +HOUSING = 500.0, +UTILITIES = 150.0, +HOUSEHOLD_EXPENSES = 65.0, +TRANSPORTATION = 50.0, +FOOD = 250.00, +MEDICAL = 30.0, +INSURANCE = 100.0, +ENTERTAINMENT = 150.0, +CLOTHING = 75.0, +MISC = 50.0; + +const int COLUMNSIZE = 25; + +/* Constants for the result strings. */ +const string +OVER_BUDGET = "Over Budget by ", +UNDER_BUDGET = "Under Budget by ", +MET_BUDGET = "Met Budget!"; + +int main() { + + MonthlyBudget budget = AskUser(); + Report(budget); + + return 0; + +} + +MonthlyBudget AskUser() { + MonthlyBudget budget; + cout << "Please enter the amounts spent in each budget category during a month." << endl << endl; + + cout << "Housing: "; + cin >> budget.housing; + + cout << "Utilities: "; + cin >> budget.utilities; + + cout << "Household Expenses: "; + cin >> budget.household_expenses; + + cout << "Transportation: "; + cin >> budget.transportation; + + cout << "Food: "; + cin >> budget.food; + + cout << "Medical: "; + cin >> budget.medical; + + cout << "Insurance: "; + cin >> budget.insurance; + + cout << "Entertainment: "; + cin >> budget.entertainment; + + cout << "Clothing: "; + cin >> budget.clothing; + + cout << "Misc: "; + cin >> budget.misc; + + return budget; +} + +string Calculate(double spent, const double goal) { + /* This function finds out if the spent amount meets, or is higher/lower, than the goal budget. */ + string result; + double difference; + if (spent > goal) { + difference = spent - goal; + result.append(OVER_BUDGET); + result.append(Round(difference)); + } + else if (spent < goal) { + difference = goal - spent; + result.append(UNDER_BUDGET); + result.append(Round(difference)); + } + else if (spent == goal) { + result.append(MET_BUDGET); + } + return result; +} + +string Round(double dbl) { + stringstream buffer; + buffer.precision(2); + buffer << fixed << dbl; + return buffer.str(); +} + +void Report(MonthlyBudget budget) { + cout << "Results:" << endl; + cout << "-------------------------------------------------" << endl; + cout << "BUDGET OVER/UNDER " << endl; + cout << "-------------------------------------------------" << endl; + cout << "HOUSING " << Calculate(budget.housing, HOUSING) << endl; + cout << "UTILITIES " << Calculate(budget.utilities, UTILITIES) << endl; + cout << "HOUSEHOLD EXPENSES " << Calculate(budget.household_expenses, HOUSEHOLD_EXPENSES) << endl; + cout << "TRANSPORTATION " << Calculate(budget.transportation, TRANSPORTATION) << endl; + cout << "FOOD " << Calculate(budget.food, FOOD) << endl; + cout << "MEDICAL " << Calculate(budget.medical, MEDICAL) << endl; + cout << "INSURANCE " << Calculate(budget.insurance, INSURANCE) << endl; + cout << "ENTERTAINMENT " << Calculate(budget.entertainment, ENTERTAINMENT) << endl; + cout << "CLOTHING " << Calculate(budget.clothing, CLOTHING) << endl; + cout << "MISC " << Calculate(budget.misc, MISC) << endl; +} diff --git a/pool/shard007/C++/0096369_Eater.cpp b/pool/shard007/C++/0096369_Eater.cpp new file mode 100644 index 0000000000000000000000000000000000000000..014eee305ef2040c82eab90d7cbdcc252637e7ef --- /dev/null +++ b/pool/shard007/C++/0096369_Eater.cpp @@ -0,0 +1,84 @@ +// +// Eater.cpp +// zeek +// +// Created by enh on 15/3/29. +// +// + +#include "Eater.h" +#include "AI/stateMachine/EaterState.h" + +Eater::Eater() +: m_currentState(false) +, m_currentAni(eater_ani_end) +, m_isPlayingAnimation(false) +{ + m_isDestructible = true; + m_isMoveable = false; +} +Eater::~Eater() +{ + delete m_stateMachine; +} + +Eater * Eater::create(cocos2d::Vec2 coord,bool state) +{ + auto ptr = new Eater(); + + if(ptr && ptr->init(state?tiledGid_openEater:tiledGid_closeEater, nullptr, coord)) + { + ptr->autorelease(); + return ptr; + } + CC_SAFE_DELETE(ptr); + return nullptr; +} + +bool Eater::init(tiledGid gid, cocostudio::Armature *bodyArmature, cocos2d::Vec2 coord) +{ + if(!GameObject::init(gid, bodyArmature, coord)) + return false; + + if(gid == tiledGid_closeEater) + m_currentState = false; + else + m_currentState = true; + + if(!bodyArmature) + { + m_bodyArmature = Armature::create("eater"); + m_bodyArmature->setAnchorPoint(Vec2::ANCHOR_MIDDLE); + this->addChild(m_bodyArmature); + } + + auto movementCallFunc = [=](Armature *armature, MovementEventType movementType, const std::string& movementID) + { + if (movementType == MovementEventType::COMPLETE) { + m_isPlayingAnimation = false; + } + }; + + m_bodyArmature->getAnimation()->setMovementEventCallFunc(movementCallFunc); + + m_stateMachine = new StateMachine(this); + if(m_currentState) + m_stateMachine->changeState(EaterOpenState::getInstance()); + else + m_stateMachine->changeState(EaterClosedState::getInstance()); + scheduleUpdate(); + return true; +} + +void Eater::playAnimationWithIndex(EaterAniIndex idx) +{ + if(idx == m_currentAni) + return; + m_isPlayingAnimation = true; + m_bodyArmature->getAnimation()->play(EaterAniStr[idx]); +} + +void Eater::update(float delta) +{ + m_stateMachine->update(delta); +} \ No newline at end of file diff --git a/pool/shard007/C++/0096370_ch7_test.cpp b/pool/shard007/C++/0096370_ch7_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e991650c79d8719243ca500072382b93b377ab61 --- /dev/null +++ b/pool/shard007/C++/0096370_ch7_test.cpp @@ -0,0 +1,179 @@ + +#undef NDEBUG + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ch7.hpp" + +using namespace std; +using namespace study; + +namespace { + + default_random_engine g_re(42); + uniform_int_distribution g_dist; + + void testIntToString() { + cout << "[ch7] IntToString" << endl; + assert(IntToString(5).compare("5") == 0); + assert(IntToString(12345).compare("12345") == 0); + assert(IntToString(0).compare("0") == 0); + assert(IntToString(-23).compare("-23") == 0); + } + + void testStringToInt() { + cout << "[ch7] StringToInt" << endl; + assert(StringToInt("5") == 5); + assert(StringToInt("12345") == 12345); + assert(StringToInt("0") == 0); + assert(StringToInt("-23") == -23); + } + + void testConvertBase() { + cout << "[ch7] ConvertBase" << endl; + string str; + for (size_t base=2; base<=16; ++base) { + + g_re.discard(1); + for (size_t i=0; i<100; ++i) { + str.clear(); + for (size_t j=0; j<4; ++j) { + int digit = (j==0) ? uniform_int_distribution(1, base-1)(g_re) : + uniform_int_distribution(0, base-1)(g_re); + if (digit > 9) + str.append(1, 'A'+(digit-10)); + else + str.append(1, '0'+digit); + } + size_t toBase = uniform_int_distribution(2, 16)(g_re); + assert(ConvertBase(ConvertBase(str, base, toBase), toBase, base).compare(str) == 0); + } + } + } + + void testSSDecodeColId() { + cout << "[ch7] SSDecodeColId" << endl; + assert(SSDecodeColId("D") == 4); + assert(SSDecodeColId("AA") == 27); + assert(SSDecodeColId("ZZ") == 702); + } + + void testReplaceAndRemove() { + cout << "[ch7] ReplaceAndRemove" << endl; + assert(ReplaceAndRemove("bbb").empty()); + assert(ReplaceAndRemove("a").compare("dd") == 0); + assert(ReplaceAndRemove("acaa").compare("ddcdddd") == 0); + assert(ReplaceAndRemove("acabcab").compare("ddcddcdd") == 0); + } + + void testIsPalindrome() { + cout << "[ch7] IsPalindrome" << endl; + assert(IsPalindrome("A man, a plan, a canal, Panama.")); + assert(IsPalindrome("Able was I, ere I saw Elba!")); + assert(!IsPalindrome("Ray a Ray")); + } + + void testReverseWords() { + cout << "[ch7] ReverseWords" << endl; + string phrase("ram is costly"); + ReverseWords(&phrase); + assert(phrase.compare("costly is ram") == 0); + } + + void testLookAndSay() { + cout << "[ch7] LookAndSay" << endl; + assert(LookAndSay(1) == "1"); + assert(LookAndSay(2) == "11"); + assert(LookAndSay(3) == "21"); + assert(LookAndSay(4) == "1211"); + assert(LookAndSay(5) == "111221"); + assert(LookAndSay(6) == "312211"); + assert(LookAndSay(7) == "13112221"); + assert(LookAndSay(8) == "1113213211"); + } + + void testRomanToInteger() { + cout << "[ch7] RomanToInteger" << endl; + assert(RomanToInteger("III") == 3); + assert(RomanToInteger("VI") == 6); + assert(RomanToInteger("VII") == 7); + assert(RomanToInteger("XVII") == 17); + assert(RomanToInteger("XXV") == 25); + assert(RomanToInteger("XXVII") == 27); + assert(RomanToInteger("XLI") == 41); + assert(RomanToInteger("XLVII") == 47); + assert(RomanToInteger("XXXXXIIIIIIIII") == 59); + assert(RomanToInteger("LVIIII") == 59); + assert(RomanToInteger("LIX") == 59); + } + + void testGetValidIPAddresses() { + cout << "[ch7] GetValidIPAddresses" << endl; + auto ret = GetValidIPAddresses("19216811"); + std::vector expected = + { "1.92.168.11", "19.2.168.11", "19.21.68.11", "19.216.8.11", + "19.216.81.1", "192.1.68.11", "192.16.8.11", "192.16.81.1", + "192.168.1.1" }; + assert(ret == expected); + } + + void testSnakeString() { + cout << "[ch7] SnakeString" << endl; + assert(SnakeString("Hello, World!") == "e,rHlo ol!lWd"); + } + + void testRle() { + cout << "[ch7] RunLengthEncode" << endl; + assert(RleEncode("aaaabcccaa") == "4a1b3c2a"); + assert(RleDecode(RleEncode("aaaabcccaa")) == "aaaabcccaa"); + assert(RleDecode(RleEncode("a")) == "a"); + assert(RleDecode(RleEncode("aabbacccdddeeef")) == "aabbacccdddeeef"); + } + + void testRabinKarp() { + cout << "[ch7] RabinKarp" << endl; + const string input("GTTATAGCTGATCGCGGCGTAGCGGCGAAGGCGATTTAGCGGCGTAAGTAGCGGCGATAGCGGCGAAGCGGCGAGCGGCGACGGCGAGGCGAGCGACGAGGTAGCGGCG"); + const string pattern("GTAGCGGCG"); + const vector expected { 18, 47, 100 }; + vector matches; + int offset; + int consumed {}; + while ((offset = RabinKarp(input.substr(consumed), pattern)) != -1) { + matches.push_back(consumed+offset); + consumed += offset + 1; + } + assert(matches == expected); + } + +} + +namespace study { + + void ch7_test() { + testIntToString(); + testStringToInt(); + testConvertBase(); + testSSDecodeColId(); + testReplaceAndRemove(); + testIsPalindrome(); + testReverseWords(); + testLookAndSay(); + testRomanToInteger(); + testGetValidIPAddresses(); + testSnakeString(); + testRle(); + testRabinKarp(); + } + +} + + diff --git a/pool/shard007/C++/0096371_partitioning.cpp b/pool/shard007/C++/0096371_partitioning.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52b0fd9399e1e4a50f7ba5c272f3e894b99462cd --- /dev/null +++ b/pool/shard007/C++/0096371_partitioning.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +using namespace std; + + +int main() { + vector nums; + for (int i=1; i <= 10; ++i) nums.push_back(i); + random_shuffle(nums.begin(), nums.end()); + + auto isEven = [](int n) { return n%2 == 0; }; + auto display = [](int n) { cout << n << " "; }; + + // std::partition() partitions the entire collection into two parts based on the supplied predicate and return a iterator to the point where the end of the true part. + // This point can also be retrieved using the std::partition_point() + + auto point = partition(nums.begin(), nums.end(), isEven); + for_each(nums.begin(), point, display); + cout << endl; + + for_each(point, nums.end(), display); + cout << endl; + + return 0; +} diff --git a/pool/shard007/C++/0096374_userdefinedLiteralsConstexpr.cpp b/pool/shard007/C++/0096374_userdefinedLiteralsConstexpr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cef8fcc38ee5e3e47aa7d3d64bd563884f80b7c --- /dev/null +++ b/pool/shard007/C++/0096374_userdefinedLiteralsConstexpr.cpp @@ -0,0 +1,81 @@ +// userdefinedLiteralsConstexpr.cpp + +#include + +namespace Distance{ + + class MyDistance{ + public: + constexpr MyDistance(double i):m(i){} + + friend constexpr MyDistance operator+(const MyDistance& a, const MyDistance& b){ + return MyDistance(a.m + b.m); + } + friend constexpr MyDistance operator-(const MyDistance& a,const MyDistance& b){ + return MyDistance(a.m - b.m); + } + + friend constexpr MyDistance operator*(double m, const MyDistance& a){ + return MyDistance(m*a.m); + } + + friend constexpr MyDistance operator/(const MyDistance& a, int n){ + return MyDistance(a.m/n); + } + + friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){ + out << myDist.m << " m"; + return out; + } + private: + double m; + }; + + namespace Unit{ + constexpr MyDistance operator "" _km(long double d){ + return MyDistance(1000*d); + } + constexpr MyDistance operator "" _m(long double m){ + return MyDistance(m); + } + constexpr MyDistance operator "" _dm(long double d){ + return MyDistance(d/10); + } + constexpr MyDistance operator "" _cm(long double c){ + return MyDistance(c/100); + } + } + +} + +constexpr Distance::MyDistance getAverageDistance(std::initializer_list inList){ + auto sum= Distance::MyDistance{0.0}; + for (auto i: inList) sum = sum + i ; + return sum/inList.size(); +} + + +using namespace Distance::Unit; + +int main(){ + + std:: cout << std::endl; + + constexpr auto work= 63.0_km; + constexpr auto workPerDay= 2 * work; + constexpr auto abbrevationToWork= 5400.0_m; + constexpr auto workout= 2 * 1600.0_m; + constexpr auto shopping= 2 * 1200.0_m; + + constexpr auto distPerWeek1= 4*workPerDay-3*abbrevationToWork+ workout+ shopping; + constexpr auto distPerWeek2= 4*workPerDay-3*abbrevationToWork+ 2*workout; + constexpr auto distPerWeek3= 4*workout + 2*shopping; + constexpr auto distPerWeek4= 5*workout + shopping; + + constexpr auto averageDistance= getAverageDistance({distPerWeek1,distPerWeek2,distPerWeek3,distPerWeek4}); + + std::cout << "averageDistance: " << averageDistance << std::endl; + + std::cout << std::endl; + +} diff --git a/pool/shard007/C++/0096379_ExecutionContextAdapter.cpp b/pool/shard007/C++/0096379_ExecutionContextAdapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e685b9a43c561e400395261c84c1a939d29f049e --- /dev/null +++ b/pool/shard007/C++/0096379_ExecutionContextAdapter.cpp @@ -0,0 +1,123 @@ +// -*- C++ -*- +/*! + * @file IRTC.h + * @brief RTC interfaces + * @date $Date$ + * @author Noriaki Ando + * + * Copyright (C) 2008 + * Noriaki Ando + * Task-intelligence Research Group, + * Intelligent Systems Research Institute, + * National Institute of + * Advanced Industrial Science and Technology (AIST), Japan + * All rights reserved. + * + * $Id$ + * + */ +#include +#include +#include + +namespace RTC +{ +namespace CORBA +{ + using namespace doil::CORBA; + ExecutionContextAdapter::ExecutionContextAdapter(RTC::ExecutionContext_ptr obj) + : m_obj(obj) + { + } + + ExecutionContextAdapter::~ExecutionContextAdapter() + { + } + + bool ExecutionContextAdapter::is_running() const + { + return m_obj->is_running(); + } + + ReturnCode_t ExecutionContextAdapter::start() + { + return to_local(m_obj->start()); + } + + ReturnCode_t ExecutionContextAdapter::stop() + { + return to_local(m_obj->stop()); + } + + double ExecutionContextAdapter::get_rate() const + { + return m_obj->get_rate(); + } + + ReturnCode_t ExecutionContextAdapter::set_rate(double rate) + { + return to_local(m_obj->set_rate(rate)); + } + + ReturnCode_t + ExecutionContextAdapter::add_component(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->add_component(rtobj)); + } + + ReturnCode_t + ExecutionContextAdapter::remove_component(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->remove_component(rtobj)); + } + + ReturnCode_t + ExecutionContextAdapter::activate_component(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->activate_component(rtobj)); + } + + ReturnCode_t + ExecutionContextAdapter::deactivate_component(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->deactivate_component(rtobj)); + } + + ReturnCode_t + ExecutionContextAdapter::reset_component(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->reset_component(rtobj)); + } + + LifeCycleState + ExecutionContextAdapter::get_component_state(ILightweightRTObject& comp) + { + RTC::LightweightRTObject_ptr rtobj; + rtobj = to_reference(&comp); + return to_local(m_obj->get_component_state(rtobj)); + } + + ExecutionKind + ExecutionContextAdapter::get_kind() const + { + return to_local(m_obj->get_kind()); + } + +// const ExecutionContextProfile& +// ExecutionContextAdapter::get_profile() const +// { +// m_profile = to_local(m_obj->get_profile()); +// return m_profile; +// } +}; // namespace CORBA +}; // namespace RTC diff --git a/pool/shard007/C++/0096381_Streamout.cc b/pool/shard007/C++/0096381_Streamout.cc new file mode 100644 index 0000000000000000000000000000000000000000..871cecb24f52e0a31769179efd690143b5606356 --- /dev/null +++ b/pool/shard007/C++/0096381_Streamout.cc @@ -0,0 +1,141 @@ +#include "Streamout.h" +#include "Global.h" +//#include "BufferNavigator.h" +//#include "LMGenericObject.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "IMPL/LCCollectionVec.h" +#include "IMPL/LCFlagImpl.h" +#include "IMPL/LCParametersImpl.h" +#include "IMPL/RawCalorimeterHitImpl.h" +#include +#include "UTIL/LCTOOLS.h" +#include "UTIL/CellIDEncoder.h" +#include "IMPL/LCEventImpl.h" +#include "IMPL/CalorimeterHitImpl.h" +#include +#include +#include +#include +using namespace lcio; + +Streamout aStreamout; + +Streamout::Streamout() : Processor("Streamout") +{ + _description = "Streamout converts SDHCAL RawData into collection easier to analyse"; + registerInputCollection(LCIO::LCGENERICOBJECT,"XDAQCollectionName","XDAQ produced collection name", _XDAQCollectionNames,std::string("RU_XDAQ")); + registerOutputCollection(LCIO::RAWCALORIMETERHIT, "OutputRawCaloHitCollectionName","Name of output collection containing raw calorimeter hits", + _RawHitCollectionName, std::string("DHCALRawHits2")); + _nevt = _nWrongObj = _nProcessedObject = _hasSlowControl =_hasBadSlowControl = 0; + _BitsToSkip = 24; + registerProcessorParameter("BitsToSkip", "BitsToSkip (default 24)",_BitsToSkip, _BitsToSkip); + virer_full_asic = false; + registerProcessorParameter("Virer_full_asic", "Virer_full_asic",virer_full_asic, virer_full_asic); + _DataFormatType="SDHCAL"; + registerProcessorParameter("Data_Format_Type", "Data_Format_Type",_DataFormatType,_DataFormatType); + chFlag.setBit(bitinfo.RCHBIT_LONG); // raw calorimeter data -> format long // //(sert a qq chose?) + chFlag.setBit(bitinfo.RCHBIT_BARREL); // barrel + chFlag.setBit(bitinfo.RCHBIT_ID1); // cell ID + chFlag.setBit(bitinfo.RCHBIT_TIME); // timestamp + chFlag.setBit(bitinfo.RCHBIT_ENERGY_ERROR); +} + +void Streamout::init() +{ + printParameters(); + parseDataFormat= new ParseDataFormat(); + if(parseDataFormat->set_DataFormat(_DataFormatType)==false) std::exit(1); +} + +void Streamout::modifyEvent( EVENT::LCEvent* evt ) +{ + LCEventImpl *raw = dynamic_cast( evt) ; + raw->setTimeStamp(evt->getTimeStamp()*1000000000); + evt=raw; +} + +void Streamout::modifyRunHeader(EVENT::LCRunHeader * rh) +{ + LCRunHeaderImpl *raw=nullptr; + if(rh!=nullptr) + { + raw = dynamic_cast(rh); + raw->setRunNumber(rh->getRunNumber()); + raw->setDetectorName(rh->getDetectorName()); + } + else + { + raw=new LCRunHeaderImpl; + raw->setRunNumber(0); + raw->setDetectorName(""); + raw->setDescription(""); + } + rh=raw; +} + +void Streamout::processRunHeader(LCRunHeader *run) +{ +} + +void Streamout::processEvent(LCEvent *evt) +{ + IMPL::LCCollectionVec *RawVec = new IMPL::LCCollectionVec(LCIO::RAWCALORIMETERHIT); + RawVec->setFlag(chFlag.getFlag()); + CellIDEncodercd("DIF_Id:8,Asic_Id:8,Channel:6,BarrelEndcapModule:10,FrameBCID:32",RawVec ) ; + parseDataFormat->SetCellIDEncoder(cd); + parseDataFormat->SetLCCollectionVec(RawVec); + try + { + LCCollection *col = evt->getCollection(_XDAQCollectionNames); + _nevt++; + cd.setCellIDFlag(); + int nElement = col->getNumberOfElements(); + _CollectionSizeCounter[nElement]++; + for (int iel = 0; iel < nElement; iel++) + { + EVENT::LCObject* obj=col->getElementAt(iel); + parseDataFormat->SetRawBuffer(obj); + parseDataFormat->Parse(); + } // for (int iel=0; ieladdCollection(RawVec,_RawHitCollectionName); +} + +void Streamout::printCounter(std::string description, std::map &m) +{ + std::cout << " statistics for " << description << " : "; + for (std::map::iterator it = m.begin(); it != m.end(); it++) + { + if (it != m.begin()) std::cout << ","; + std::cout << " [" << it->first << "]=" << it->second; + } + std::cout << std::endl; +} + +void Streamout::end() +{ + std::cout << "FINAL STATISTICS : " << std::endl; + std::cout << " runs for " << _nevt << " events." << std::endl; + printCounter("Size of GenericObject collections", _CollectionSizeCounter); + std::cout << "Number of badly extracted LCGenericObject : "<< _nWrongObj << std::endl; + std::cout << "Number of processed LCGenericObject : "<< _nProcessedObject << std::endl; + printCounter("Start of DIF header", _DIFStarter); + printCounter("Value after DIF data are processed", _DIFPtrValueAtReturnedPos); + printCounter("Size remaining in buffer after end of DIF data",_SizeAfterDIFPtr); + std::cout << "Number of Slow Control found " << _hasSlowControl<< " out of which " << _hasBadSlowControl << " are bad"<< std::endl; + printCounter("Size remaining after all of data have been processed",_SizeAfterAllData); + printCounter("Number on non zero values in end of data buffer",_NonZeroValusAtEndOfData); + delete parseDataFormat; +} diff --git a/pool/shard007/C++/0096386_x64_dbg_exe.cpp b/pool/shard007/C++/0096386_x64_dbg_exe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06f14550302542d87a34f839df2628cacaa85cc4 --- /dev/null +++ b/pool/shard007/C++/0096386_x64_dbg_exe.cpp @@ -0,0 +1,20 @@ +#include +#include +#include "..\x64_dbg_bridge\bridgemain.h" + +int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) +{ + const char* errormsg = BridgeInit(); + if(errormsg) + { + MessageBoxA(0, errormsg, "BridgeInit Error", MB_ICONERROR | MB_SYSTEMMODAL); + return 1; + } + errormsg = BridgeStart(); + if(errormsg) + { + MessageBoxA(0, errormsg, "BridgeStart Error", MB_ICONERROR | MB_SYSTEMMODAL); + return 1; + } + return 0; +} diff --git a/pool/shard007/C++/0096387_ValidateFixtures.cpp b/pool/shard007/C++/0096387_ValidateFixtures.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e51a5806fa55f3967d166e0d69121eb90bdc884e --- /dev/null +++ b/pool/shard007/C++/0096387_ValidateFixtures.cpp @@ -0,0 +1,95 @@ +// Copyright (c) 2015-2016 The Khronos Group Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and/or associated documentation files (the +// "Materials"), to deal in the Materials without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Materials, and to +// permit persons to whom the Materials are furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Materials. +// +// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS +// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS +// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT +// https://www.khronos.org/registry/ +// +// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +// Common validation fixtures for unit tests + +#include "UnitSPIRV.h" +#include "ValidateFixtures.h" + +#include +#include +#include + +namespace spvtest { + +template +ValidateBase::ValidateBase() + : context_(spvContextCreate()), binary_(), diagnostic_() {} + +template +ValidateBase::~ValidateBase() { + spvContextDestroy(context_); +} + +template +spv_const_binary ValidateBase::get_const_binary() { + return spv_const_binary(binary_); +} + +template +void ValidateBase::TearDown() { + if (diagnostic_) { + spvDiagnosticPrint(diagnostic_); + } + spvDiagnosticDestroy(diagnostic_); + spvBinaryDestroy(binary_); +} + +template +void ValidateBase::CompileSuccessfully(std::string code) { + spv_diagnostic diagnostic = nullptr; + ASSERT_EQ(SPV_SUCCESS, spvTextToBinary(context_, code.c_str(), code.size(), + &binary_, &diagnostic)) + << "ERROR: " << diagnostic->error + << "\nSPIR-V could not be compiled into binary:\n" + << code; +} + +template +spv_result_t ValidateBase::ValidateInstructions() { + return spvValidate(context_, get_const_binary(), &diagnostic_); +} + +template +std::string ValidateBase::getDiagnosticString() { + return std::string(diagnostic_->error); +} + +template +spv_position_t ValidateBase::getErrorPosition() { + return diagnostic_->position; +} + +template class spvtest::ValidateBase; +template class spvtest::ValidateBase; +template class spvtest::ValidateBase; +template class spvtest::ValidateBase>; +template class spvtest::ValidateBase< + std::tuple>>>; +template class spvtest::ValidateBase< + std::tuple, + std::function>>>; +} diff --git a/pool/shard007/C++/0096388_awn-overlayable.cc b/pool/shard007/C++/0096388_awn-overlayable.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a814ccf427c05cc9ac59594d855c20945e2b0ce --- /dev/null +++ b/pool/shard007/C++/0096388_awn-overlayable.cc @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2009 Michal Hruby + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + */ + +#include "awn-overlayable.h" + +static void awn_overlayable_base_init(AwnOverlayableIface* iface); + +GType +awn_overlayable_get_type(void) +{ + static GType overlayable_type = 0; + + if (G_UNLIKELY(overlayable_type == 0)) { + const GTypeInfo overlayable_info = { + sizeof(AwnOverlayableIface), + (GBaseInitFunc) awn_overlayable_base_init, + (GBaseFinalizeFunc) NULL, + }; + + overlayable_type = g_type_register_static(G_TYPE_INTERFACE, + "AwnOverlayable", + &overlayable_info, 0); + } + + return overlayable_type; +} + +static void +awn_overlayable_base_init(AwnOverlayableIface* iface) +{ + iface->get_effects = NULL; // perhaps show a warning? +} + +/** + * awn_overlayable_get_effects: + * @self: #AwnOverlayable instance. + * + * Returns: #AwnEffects instance managing animations for this instance. + */ +AwnEffects* +awn_overlayable_get_effects(AwnOverlayable* self) +{ + g_return_val_if_fail(AWN_IS_OVERLAYABLE(self), NULL); + + return AWN_OVERLAYABLE_GET_INTERFACE(self)->get_effects(self); +} + +/** + * awn_overlayable_add_overlay: + * @self: #AwnOverlayable instance. + * @overlay: #AwnOverlay instance which should be added. + * + * Adds an overlay to the list of rendered overlays. + */ +void +awn_overlayable_add_overlay(AwnOverlayable* self, AwnOverlay* overlay) +{ + awn_effects_add_overlay(awn_overlayable_get_effects(self), overlay); +} + +/** + * awn_overlayable_remove_overlay: + * @self: #AwnOverlayable instance. + * @overlay: #AwnOverlay which was previously added using + * awn_overlayable_add_overlay. + * + * Removes overlay from the list of rendered overlays. + */ +void +awn_overlayable_remove_overlay(AwnOverlayable* self, AwnOverlay* overlay) +{ + awn_effects_remove_overlay(awn_overlayable_get_effects(self), overlay); +} + +/** + * awn_overlayable_get_overlays: + * @self: #AwnOverlayable instance. + * + * Returns: a newly-allocated list of the overlays added for this instance. + */ +GList* +awn_overlayable_get_overlays(AwnOverlayable* self) +{ + return awn_effects_get_overlays(awn_overlayable_get_effects(self)); +} + diff --git a/pool/shard007/C++/0096389_FormFactorPyramid.cpp b/pool/shard007/C++/0096389_FormFactorPyramid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cbdf40ce30a021a6256a27998bd5b36917e18c5 --- /dev/null +++ b/pool/shard007/C++/0096389_FormFactorPyramid.cpp @@ -0,0 +1,90 @@ +// ************************************************************************************************ +// +// BornAgain: simulate and fit reflection and scattering +// +//! @file Sample/HardParticle/FormFactorPyramid.cpp +//! @brief Implements class FormFactorPyramid. +//! +//! @homepage http://www.bornagainproject.org +//! @license GNU General Public License v3 or higher (see COPYING) +//! @copyright Forschungszentrum Jülich GmbH 2018 +//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) +// +// ************************************************************************************************ + +#include "Sample/HardParticle/FormFactorPyramid.h" +#include "Base/Math/Constants.h" +#include "Base/Math/Functions.h" + +const PolyhedralTopology FormFactorPyramid::topology = {{ + {{3, 2, 1, 0}, true}, // TODO -> true + {{0, 1, 5, 4}, false}, + {{1, 2, 6, 5}, false}, + {{2, 3, 7, 6}, false}, + {{3, 0, 4, 7}, false}, + {{4, 5, 6, 7}, true} // TODO -> true + }, + false}; + +FormFactorPyramid::FormFactorPyramid(const std::vector P) + : IFormFactorPolyhedron({"Pyramid", + "frustum with quadratic base", + {{"BaseEdge", "nm", "base edge length", 0, +INF, 0}, + {"Height", "nm", "height", 0, +INF, 0}, + {"Alpha", "rad", "angle between base and a side face", 0., M_PI, 0}}}, + P) + , m_base_edge(m_P[0]) + , m_height(m_P[1]) + , m_alpha(m_P[2]) +{ + onChange(); +} + +FormFactorPyramid::FormFactorPyramid(double base_edge, double height, double alpha) + : FormFactorPyramid(std::vector{base_edge, height, alpha}) +{ +} + +IFormFactor* FormFactorPyramid::sliceFormFactor(ZLimits limits, const IRotation& rot, + kvector_t translation) const +{ + auto effects = computeSlicingEffects(limits, translation, m_height); + double dbase_edge = 2 * effects.dz_bottom * Math::cot(m_alpha); + FormFactorPyramid slicedff(m_base_edge - dbase_edge, + m_height - effects.dz_bottom - effects.dz_top, m_alpha); + return createTransformedFormFactor(slicedff, rot, effects.position); +} + +void FormFactorPyramid::onChange() +{ + double cot_alpha = Math::cot(m_alpha); + if (!std::isfinite(cot_alpha)) + throw std::runtime_error("pyramid angle alpha out of bounds"); + double r = cot_alpha * 2 * m_height / m_base_edge; // [L(base)-L(top)]/L(base) + if (r > 1) { + std::ostringstream ostr; + ostr << "FormFactorPyramid() -> Error in class initialization with parameters"; + ostr << " base_edge:" << m_base_edge; + ostr << " height:" << m_height; + ostr << " alpha[rad]:" << m_alpha << "\n\n"; + ostr << "Check for 'height <= base_edge*tan(alpha)' failed."; + throw std::runtime_error(ostr.str()); + } + + double a = m_base_edge / 2; + double b = a * (1 - r); + + double zcom = m_height * (.5 - 2 * r / 3 + r * r / 4) / (1 - r + r * r / 3); // center of mass + + setPolyhedron(topology, -zcom, + {// base: + {-a, -a, -zcom}, + {a, -a, -zcom}, + {a, a, -zcom}, + {-a, a, -zcom}, + // top: + {-b, -b, m_height - zcom}, + {b, -b, m_height - zcom}, + {b, b, m_height - zcom}, + {-b, b, m_height - zcom}}); +} diff --git a/pool/shard007/C++/0096394_CachedFont.cpp b/pool/shard007/C++/0096394_CachedFont.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2000884d1a4e8feacc5ef0f74f6a6b506f597943 --- /dev/null +++ b/pool/shard007/C++/0096394_CachedFont.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2009 Torch Mobile, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "CachedFont.h" + +#include "CachedFontClient.h" +#include "CachedResourceClientWalker.h" +#include "CachedResourceLoader.h" +#include "FontCustomPlatformData.h" +#include "FontPlatformData.h" +#include "MemoryCache.h" +#include "ResourceBuffer.h" +#include "TextResourceDecoder.h" +#include + +#if ENABLE(SVG_FONTS) +#include "NodeList.h" +#include "SVGDocument.h" +#include "SVGElement.h" +#include "SVGFontElement.h" +#include "SVGGElement.h" +#include "SVGNames.h" +#endif + +namespace WebCore { + +CachedFont::CachedFont(const ResourceRequest& resourceRequest) + : CachedResource(resourceRequest, FontResource) + , m_fontData(0) + , m_loadInitiated(false) + , m_hasCreatedFontData(false) +{ +} + +CachedFont::~CachedFont() +{ + delete m_fontData; +} + +void CachedFont::load(CachedResourceLoader*, const ResourceLoaderOptions& options) +{ + // Don't load the file yet. Wait for an access before triggering the load. + setLoading(true); + m_options = options; +} + +void CachedFont::didAddClient(CachedResourceClient* c) +{ + ASSERT(c->resourceClientType() == CachedFontClient::expectedType()); + if (!isLoading()) + static_cast(c)->fontLoaded(this); +} + +void CachedFont::data(PassRefPtr data, bool allDataReceived) +{ + if (!allDataReceived) + return; + + m_data = data; + setEncodedSize(m_data.get() ? m_data->size() : 0); + setLoading(false); + checkNotify(); +} + +void CachedFont::beginLoadIfNeeded(CachedResourceLoader* dl) +{ + if (!m_loadInitiated) { + m_loadInitiated = true; + CachedResource::load(dl, m_options); + } +} + +bool CachedFont::ensureCustomFontData() +{ + if (!m_fontData && !errorOccurred() && !isLoading() && m_data) { + m_fontData = createFontCustomPlatformData(m_data.get()->sharedBuffer()); + if (m_fontData) + m_hasCreatedFontData = true; + else + setStatus(DecodeError); + } + return m_fontData; +} + +FontPlatformData CachedFont::platformDataFromCustomData(float size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant widthVariant, FontRenderingMode renderingMode) +{ +#if ENABLE(SVG_FONTS) + if (m_externalSVGDocument) + return FontPlatformData(size, bold, italic); +#endif + ASSERT(m_fontData); + return m_fontData->fontPlatformData(static_cast(size), bold, italic, orientation, widthVariant, renderingMode); +} + +#if ENABLE(SVG_FONTS) +bool CachedFont::ensureSVGFontData() +{ + if (!m_externalSVGDocument && !errorOccurred() && !isLoading() && m_data) { + m_externalSVGDocument = SVGDocument::create(0, KURL()); + + RefPtr decoder = TextResourceDecoder::create("application/xml"); + String svgSource = decoder->decode(m_data->data(), m_data->size()); + svgSource.append(decoder->flush()); + + m_externalSVGDocument->setContent(svgSource); + + if (decoder->sawError()) + m_externalSVGDocument = 0; + } + + return m_externalSVGDocument; +} + +SVGFontElement* CachedFont::getSVGFontById(const String& fontName) const +{ + RefPtr list = m_externalSVGDocument->getElementsByTagNameNS(SVGNames::fontTag.namespaceURI(), SVGNames::fontTag.localName()); + if (!list) + return 0; + + unsigned listLength = list->length(); + if (!listLength) + return 0; + +#ifndef NDEBUG + for (unsigned i = 0; i < listLength; ++i) { + ASSERT(list->item(i)); + ASSERT(list->item(i)->hasTagName(SVGNames::fontTag)); + } +#endif + + if (fontName.isEmpty()) + return static_cast(list->item(0)); + + for (unsigned i = 0; i < listLength; ++i) { + SVGFontElement* element = static_cast(list->item(i)); + if (element->getIdAttribute() == fontName) + return element; + } + + return 0; +} +#endif + +void CachedFont::allClientsRemoved() +{ + if (m_fontData) { + delete m_fontData; + m_fontData = 0; + } +} + +void CachedFont::checkNotify() +{ + if (isLoading()) + return; + + CachedResourceClientWalker w(m_clients); + while (CachedFontClient* c = w.next()) + c->fontLoaded(this); +} + +bool CachedFont::mayTryReplaceEncodedData() const +{ + // If the FontCustomPlatformData has ever been constructed then it still might be in use somewhere. + // That platform font object might directly reference the encoded data buffer behind this CachedFont, + // so replacing it is unsafe. + + return !m_hasCreatedFontData; +} + +} diff --git a/pool/shard007/C++/0096400_test_r2t2.cc b/pool/shard007/C++/0096400_test_r2t2.cc new file mode 100644 index 0000000000000000000000000000000000000000..b87c46320e3d9aed95fa45d6e7e975eeb9cb8fdc --- /dev/null +++ b/pool/shard007/C++/0096400_test_r2t2.cc @@ -0,0 +1,48 @@ +/* -*- c++ -*- */ +/* + * Copyright 2012 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * GNU Radio 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. + * + * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include "qa_r2t2.h" +#include +#include + +int +main (int argc, char **argv) +{ + CppUnit::TextTestRunner runner; + std::ofstream xmlfile(get_unittest_path("r2t2.xml").c_str()); + CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); + + runner.addTest(qa_r2t2::suite()); + runner.setOutputter(xmlout); + + bool was_successful = runner.run("", false); + + return was_successful ? 0 : 1; +} diff --git a/pool/shard007/C++/0096402_historyLog.cpp b/pool/shard007/C++/0096402_historyLog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..344492f935241cd19b2e72509c20f18e1f9fc727 --- /dev/null +++ b/pool/shard007/C++/0096402_historyLog.cpp @@ -0,0 +1,153 @@ +/********************************************************************************************** + * historyLog is a Service that maintains the 1 minute interval historical data log. + * Primarily due to constraints in the fat32 file system, the 5 second interval log has a + * capacity of about 485 days (1.3 years). So it will wrap around at some point and + * older data overwritten. + * + * The history log has 60 second resolution and therefore has a capacity of nearly + * 16 years. Moreover, because it is built by this process using the iotalog, it has + * no "holes", so all keyed reads are direct without searching. + * + * Queries from graph, and other well behaved users, will request data beginning at a + * minute boundary, with an interval that is a multiple of one minute. So most requests + * should be serviceable from this history log. + * + * An added benefit is that it serves as low-resolution backup for the 5 second log, so + * even if the 5 minute log is lost, most queries will still be satisfied. + * + * The records in this log are simply an identical subset of the one-minute entries, + * real or virtual, that are (or were) in the Current_log. + * + **********************************************************************************************/ +#include "IotaWatt.h" +#define GapFill 600 // Fill in gaps of less than this seconds +bool synchronized = false; // Set true when history log is synchronized with the current log + +void logtoHistory(IotaLogRecord* logRecord){ + if(synchronized && (logRecord->UNIXtime % History_log.interval() == 0)){ + History_log.write(logRecord); + } +} + +uint32_t historyLog(struct serviceBlock* _serviceBlock){ + enum states {initialize, logFill, logData}; + static states state = initialize; + static uint32_t lastExitTime = 0; + static uint32_t fillTarget = 0; + static IotaLogRecord* logRecord = nullptr; + trace(T_history,0); + + switch(state){ + + case initialize: { + trace(T_history,1); + + // If iotaLog not open or empty, check back later. + + if( ! Current_log.isOpen() || (Current_log.lastKey() - Current_log.firstKey()) < History_log.interval()){ + return UTCtime() + 5; + //History_log.interval(); + } + + log("historyLog: service started."); + + // Initialize the historyLog class + + trace(T_history,2); + if(int rtc = History_log.begin(IOTA_HISTORY_LOG_PATH)){ + log("historyLog: Log file open failed: %d, service halted.", rtc); + return 0; + } + + // If it's not a new log, get the last entry. + + if(History_log.firstKey() != 0){ + log("historyLog: Last log entry %s", localDateString(History_log.lastKey()).c_str()); + } + + // New history log, start with first even increment in IotaLog + + else { + if( ! logRecord) logRecord = new IotaLogRecord; + logRecord->UNIXtime = Current_log.firstKey(); + if(logRecord->UNIXtime % History_log.interval()){ + logRecord->UNIXtime += History_log.interval() - (logRecord->UNIXtime % History_log.interval()); + } + log("historyLog: first entry %s", localDateString(logRecord->UNIXtime).c_str()); + Current_log.readKey(logRecord); + History_log.write(logRecord); + delete logRecord; + logRecord = nullptr; + } + + trace(T_history,3); + if(History_log.lastKey() < Current_log.firstKey()){ + fillTarget = Current_log.firstKey(); + state = logFill; + } else { + state = logData; + } + return 1; + } + + // logFill replicates the last history file record until fillTarget. + // Used primarily to fill large gaps as when the current log has been + // deleted after an interruption. + + case logFill: { + if( ! logRecord) { + logRecord = new IotaLogRecord; + History_log.readSerial(logRecord, History_log.lastSerial()); + } + logRecord->UNIXtime += History_log.interval(); + if(logRecord->UNIXtime < fillTarget){ + History_log.write(logRecord); + } + else { + delete logRecord; + logRecord = nullptr; + state = logData; + } + return 1; + } + + case logData: { + trace(T_history,4); + while((History_log.lastKey() + History_log.interval()) <= Current_log.lastKey()){ + + trace(T_history,5); + if( ! logRecord){ + logRecord = new IotaLogRecord; + logRecord->UNIXtime = History_log.lastKey(); + } + logRecord->UNIXtime += History_log.interval(); + if(Current_log.readKey(logRecord)){ + log("historyLog: primary log file read failure. Service suspended."); + delete logRecord; + logRecord = nullptr; + return 0; + } + trace(T_history,7); + if(logRecord->UNIXtime % History_log.interval()){ + Serial.print("log file record not multiple of history interval: "); + Serial.println(logRecord->UNIXtime); + delete logRecord; + logRecord = nullptr; + return 0; + } + + trace(T_history,8); + History_log.write(logRecord); + + if(micros() > bingoTime){ + delete logRecord; + logRecord = nullptr; + return 15; + } + } + trace(T_history, 9); + synchronized = true; + return 0; + } + } +} \ No newline at end of file diff --git a/pool/shard007/C++/0096415_full_matrix_vector_02.cc b/pool/shard007/C++/0096415_full_matrix_vector_02.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ba10e528d8b2b7762e13371a9996692ed17b71e --- /dev/null +++ b/pool/shard007/C++/0096415_full_matrix_vector_02.cc @@ -0,0 +1,103 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2004 - 2015 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. +// +// --------------------------------------------------------------------- + + + +// check FullMatrix::Tvmult + +#include "../tests.h" +#include +#include +#include +#include +#include + + +void test (PETScWrappers::MPI::Vector &v, + PETScWrappers::MPI::Vector &w) +{ + PETScWrappers::FullMatrix m(v.size(),v.size()); + for (unsigned int i=0; i +#include + +namespace zx{ + ZXWString TranslateString(ZXString str) + { + int dwNum = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); + wchar_t *pwText = new wchar_t[dwNum]; + memset(pwText,0, dwNum*sizeof(wchar_t)); + MultiByteToWideChar (CP_ACP, 0, str.c_str(), -1, pwText, dwNum); + ZXWString res = pwText; + if(!pwText) delete []pwText; + return res; + } +}; diff --git a/pool/shard007/C++/0096420_Dragger.cpp b/pool/shard007/C++/0096420_Dragger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..117585075fe392dcd07fc89685a64e75de01ad4a --- /dev/null +++ b/pool/shard007/C++/0096420_Dragger.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include + +// TransformUpdating +static bool checkTransformUpdating( const osgManipulator::Dragger& dragger ) +{ + return dragger.getDraggerCallbacks().size()>0; +} + +static bool readTransformUpdating( osgDB::InputStream& is, osgManipulator::Dragger& dragger ) +{ + unsigned int size = is.readSize(); is >> is.BEGIN_BRACKET; + for ( unsigned int i=0; i> name >> is.BEGIN_BRACKET; + if ( name=="DraggerTransformCallback" ) + { + osg::MatrixTransform* transform = dynamic_cast( is.readObject() ); + if ( transform ) dragger.addTransformUpdating( transform ); + } + is >> is.END_BRACKET; + } + is >> is.END_BRACKET; + return true; +} + +static bool writeTransformUpdating( osgDB::OutputStream& os, const osgManipulator::Dragger& dragger ) +{ + const osgManipulator::Dragger::DraggerCallbacks& callbacks = dragger.getDraggerCallbacks(); + os.writeSize( callbacks.size() ); os << os.BEGIN_BRACKET << std::endl; + for ( osgManipulator::Dragger::DraggerCallbacks::const_iterator itr=callbacks.begin(); + itr!=callbacks.end(); ++itr ) + { + osgManipulator::DraggerTransformCallback* dtcb = + dynamic_cast( itr->get() ); + if ( dtcb ) + { + os << std::string("DraggerTransformCallback") << os.BEGIN_BRACKET << std::endl; + os << dtcb->getTransform(); + } + else + { + os << std::string("DraggerCallback") << os.BEGIN_BRACKET << std::endl; + } + os << os.END_BRACKET << std::endl; + } + os << os.END_BRACKET << std::endl; + return true; +} + +// DefaultGeometry: FIXME - add a setUseDefaultGeometry(bool) here? +static bool checkDefaultGeometry( const osgManipulator::Dragger& dragger ) +{ return true; } + +static bool readDefaultGeometry( osgDB::InputStream& is, osgManipulator::Dragger& dragger ) +{ + bool useDefGeometry = false; is >> useDefGeometry; + dragger.setupDefaultGeometry(); + return true; +} + +static bool writeDefaultGeometry( osgDB::OutputStream& os, const osgManipulator::Dragger& dragger ) +{ + os << true << std::endl; + return true; +} + +REGISTER_OBJECT_WRAPPER( osgManipulator_Dragger, + /*new osgManipulator::Dragger*/NULL, + osgManipulator::Dragger, + "osg::Object osg::Node osg::Transform osg::MatrixTransform osgManipulator::Dragger" ) +{ + // Dragger should not record children seperately, so ignore the osg::Group class wrapper + + ADD_BOOL_SERIALIZER( HandleEvents, false ); // _handleEvents + ADD_BOOL_SERIALIZER( DraggerActive, false ); // _draggerActive + ADD_UINT_SERIALIZER( ActivationModKeyMask, 0 ); // _activationModKeyMask + ADD_INT_SERIALIZER( ActivationKeyEvent, 0 ); // _activationKeyEvent + ADD_USER_SERIALIZER( TransformUpdating ); // _draggerCallbacks + ADD_USER_SERIALIZER( DefaultGeometry ); +} diff --git a/pool/shard007/C++/0096422_excluded_volume_evaluator.cc b/pool/shard007/C++/0096422_excluded_volume_evaluator.cc new file mode 100644 index 0000000000000000000000000000000000000000..93076eb8ed8e08b50198b2cea99dbbc20078482f --- /dev/null +++ b/pool/shard007/C++/0096422_excluded_volume_evaluator.cc @@ -0,0 +1,71 @@ +/* -*- mode: c++; indent-tabs-mode: nil -*- */ + +/* + The dynamic subgrid model evaluator gets the subgrid parameters and evolve polygons. + + Authors: Ahmad Jan (jana@ornl.gov) +*/ + +#include "excluded_volume_evaluator.hh" + +namespace Amanzi { +namespace Flow { + + +ExcludedVolumeEvaluator::ExcludedVolumeEvaluator(Teuchos::ParameterList& plist) : + SecondaryVariableFieldEvaluator(plist){ + + std::string domain_name=Keys::getDomain(my_key_); + if (my_key_.empty()) + my_key_ = Keys::getKey(domain_name, "excluded_volume"); + delta_init_key_ = plist_.get("excluded volume initial key"); + dependencies_.insert(delta_init_key_); + delta_evolve_key_ = plist_.get("excluded volume evolution key"); + dependencies_.insert(delta_evolve_key_); + sg_entity_key_ = plist_.get("subgrid entity key"); + dependencies_.insert(sg_entity_key_); +} + + +ExcludedVolumeEvaluator::ExcludedVolumeEvaluator(const ExcludedVolumeEvaluator& other) : + SecondaryVariableFieldEvaluator(other), + delta_init_key_(other.delta_init_key_), + delta_evolve_key_(other.delta_evolve_key_), + sg_entity_key_(other.sg_entity_key_) {} + + +Teuchos::RCP +ExcludedVolumeEvaluator::Clone() const { + return Teuchos::rcp(new ExcludedVolumeEvaluator(*this)); +} +void ExcludedVolumeEvaluator::EvaluateField_(const Teuchos::Ptr& S, + const Teuchos::Ptr& result) { + + Epetra_MultiVector& res_c = *result->ViewComponent("cell",false); + const Epetra_MultiVector& delta_init_c = *S->GetFieldData(delta_init_key_)->ViewComponent("cell", false); + const Epetra_MultiVector& delta_evolve_c = *S->GetFieldData(delta_evolve_key_)->ViewComponent("cell",false); + const Epetra_MultiVector& sg_entity_c = *S->GetFieldData(sg_entity_key_)->ViewComponent("cell",false); + + Key domain = Keys::getDomain(delta_init_key_); + assert(!domain.empty()); + + int ncells = res_c.MyLength(); + for (int c=0; c!=ncells; c++){ + if (sg_entity_c[0][c] == 1) // 1 is for HCP, 0 is for LCP + res_c[0][c] = delta_init_c[0][c]; + else { + res_c[0][c] = delta_evolve_c[0][c]; + } + } + +} + +void ExcludedVolumeEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr& S, + Key wrt_key, const Teuchos::Ptr& result){} + +} //namespace +} //namespace + + + + diff --git a/pool/shard007/C++/0096429_quota_reservation.cc b/pool/shard007/C++/0096429_quota_reservation.cc new file mode 100644 index 0000000000000000000000000000000000000000..85a404cac368cf70bb409394b61aafb65be19b53 --- /dev/null +++ b/pool/shard007/C++/0096429_quota_reservation.cc @@ -0,0 +1,142 @@ +// 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 "content/browser/renderer_host/pepper/quota_reservation.h" + +#include "base/bind.h" +#include "base/callback.h" +#include "content/public/browser/browser_thread.h" +#include "webkit/browser/fileapi/file_system_operation_runner.h" +#include "webkit/browser/fileapi/quota/open_file_handle.h" +#include "webkit/browser/fileapi/quota/quota_reservation.h" +#include "webkit/common/fileapi/file_system_util.h" + +namespace content { + +// static +scoped_refptr QuotaReservation::Create( + scoped_refptr file_system_context, + const GURL& origin_url, + fileapi::FileSystemType type) { + return scoped_refptr( + new QuotaReservation(file_system_context, origin_url, type)); +} + +QuotaReservation::QuotaReservation( + scoped_refptr file_system_context, + const GURL& origin_url, + fileapi::FileSystemType file_system_type) + : file_system_context_(file_system_context) { + quota_reservation_ = + file_system_context->CreateQuotaReservationOnFileTaskRunner( + origin_url, file_system_type); +} + +// For unit testing only. +QuotaReservation::QuotaReservation( + scoped_refptr quota_reservation, + const GURL& /* origin_url */, + fileapi::FileSystemType /* file_system_type */) + : quota_reservation_(quota_reservation) {} + +QuotaReservation::~QuotaReservation() { + // We should have no open files at this point. + DCHECK(files_.size() == 0); + for (FileMap::iterator it = files_.begin(); it != files_.end(); ++it) + delete it->second; +} + +int64_t QuotaReservation::OpenFile(int32_t id, + const fileapi::FileSystemURL& url) { + base::FilePath platform_file_path; + if (file_system_context_) { + base::File::Error error = + file_system_context_->operation_runner()->SyncGetPlatformPath( + url, &platform_file_path); + if (error != base::File::FILE_OK) { + NOTREACHED(); + return 0; + } + } else { + // For test. + platform_file_path = url.path(); + } + + scoped_ptr file_handle = + quota_reservation_->GetOpenFileHandle(platform_file_path); + std::pair insert_result = + files_.insert(std::make_pair(id, file_handle.get())); + if (insert_result.second) { + int64_t max_written_offset = file_handle->GetMaxWrittenOffset(); + ignore_result(file_handle.release()); + return max_written_offset; + } + NOTREACHED(); + return 0; +} + +void QuotaReservation::CloseFile(int32_t id, + const ppapi::FileGrowth& file_growth) { + FileMap::iterator it = files_.find(id); + if (it != files_.end()) { + it->second->UpdateMaxWrittenOffset(file_growth.max_written_offset); + it->second->AddAppendModeWriteAmount(file_growth.append_mode_write_amount); + delete it->second; + files_.erase(it); + } else { + NOTREACHED(); + } +} + +void QuotaReservation::ReserveQuota(int64_t amount, + const ppapi::FileGrowthMap& file_growths, + const ReserveQuotaCallback& callback) { + for (FileMap::iterator it = files_.begin(); it != files_.end(); ++it) { + ppapi::FileGrowthMap::const_iterator growth_it = + file_growths.find(it->first); + if (growth_it != file_growths.end()) { + it->second->UpdateMaxWrittenOffset(growth_it->second.max_written_offset); + it->second->AddAppendModeWriteAmount( + growth_it->second.append_mode_write_amount); + } else { + NOTREACHED(); + } + } + + quota_reservation_->RefreshReservation( + amount, base::Bind(&QuotaReservation::GotReservedQuota, this, callback)); +} + +void QuotaReservation::OnClientCrash() { quota_reservation_->OnClientCrash(); } + +void QuotaReservation::GotReservedQuota(const ReserveQuotaCallback& callback, + base::File::Error error) { + ppapi::FileSizeMap file_sizes; + for (FileMap::iterator it = files_.begin(); it != files_.end(); ++it) + file_sizes[it->first] = it->second->GetMaxWrittenOffset(); + + if (file_system_context_) { + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind( + callback, quota_reservation_->remaining_quota(), file_sizes)); + } else { + // Unit testing code path. + callback.Run(quota_reservation_->remaining_quota(), file_sizes); + } +} + +void QuotaReservation::DeleteOnCorrectThread() const { + if (file_system_context_ && !file_system_context_->default_file_task_runner() + ->RunsTasksOnCurrentThread()) { + file_system_context_->default_file_task_runner()->DeleteSoon(FROM_HERE, + this); + } else { + // We're on the right thread to delete, or unit test. + delete this; + } +} + +} // namespace content diff --git a/pool/shard007/C++/0096433_dbdoc.cpp b/pool/shard007/C++/0096433_dbdoc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ecab4c185a1dcb4e774aae6e2b4e06f5acd2b8f --- /dev/null +++ b/pool/shard007/C++/0096433_dbdoc.cpp @@ -0,0 +1,93 @@ +#include "dbdoc.h" +#include +#include +#include + +#include +dbdoc::dbdoc() +{ +} + + +bool dbdoc::save(QString dbname, csvmodel *model) +{ + QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(dbname); + if (!db.open()) { + QMessageBox::critical(NULL,"Error","Can't Open Database" + db.lastError().databaseText()); + return false; + } + QSqlQuery query(db); + bool b; + QString q0; + QString q1; + QString q; + QString col; + b=query.exec("Create table if not exists csvcolumns (name text)"); + b=query.exec("delete from csvcolumns"); + q1=q0="("; + bool first=true; + foreach(col,model->getRow(0)) { + q="insert into csvcolumns (name) values (" + QString("\"") + col + "\")"; + + if (!first) { + q0+=","; + q1+=","; + } + else { + first=false; + } + col.replace(" ","_"); + q0+=col+" text"; + q1+=col; + b=query.exec(q); + } + q0+=")"; + q1+=")"; + q="create table if not exists csvdata " + q0; + b=query.exec(q); + b=query.exec("delete from csvdata"); + for (int i=1;icount();i++) + { + q="insert into csvdata " + q1 + " VALUES ("; + for (int j=0;jgetRow(i).count();j++) { + QString v=model->getCol(i,j); + v.replace("\"","\"\""); + q+="\""+v+"\""; + if (j+1!=model->getRow(i).count()) q+=","; + } + q+=")"; + b=query.exec(q); + } + b=db.commit(); + db.close(); + return true; +} + +bool dbdoc::load(QString dbname, csvmodel *model) +{ + QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(dbname); + if (!db.open()) { + QMessageBox::critical(NULL,"Error","Can't Open Database"); + return false; + } + model->newdoc(true); + QSqlQuery query(db); + bool b; + // query columns + b=query.exec("select name from csvcolumns"); + model->insertrow(0); + while (query.next()) + { + qDebug()<getRow(0)<getRow(1)<colct++; + } + // put them in row[0] + // get all rows and put each one in a row + db.close(); + QMessageBox::critical(NULL,"Error","Unimplemented"); + return true; +} diff --git a/pool/shard007/C++/0096436_slicer.cpp b/pool/shard007/C++/0096436_slicer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..771d6f3c728a4a6a4e0977a52944398a18751994 --- /dev/null +++ b/pool/shard007/C++/0096436_slicer.cpp @@ -0,0 +1,168 @@ +/* + * + * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * Further, this software is distributed without any warranty that it is + * free of the rightful claim of any third person regarding infringement + * or the like. Any license provided herein, whether implied or + * otherwise, applies only to this software file. Patent licenses, if + * any, provided herein do not apply to combinations of this program with + * other software, or any other product whatsoever. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, + * Mountain View, CA 94043, or: + * + * http://www.sgi.com + * + * For further information regarding this notice, see: + * + * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ + * + */ + +/* + * slicer.c++ - $Revision: 1.1.1.1 $ + * Derrick Burns - 1991 + */ + +#include "glimports.h" +#include "mystdio.h" +#include "myassert.h" +#include "bufpool.h" +#include "slicer.h" +#include "backend.h" +#include "arc.h" +#include "gridtrimvertex.h" +#include "trimvertex.h" +#include "varray.h" + +Slicer::Slicer( Backend &b ) + : CoveAndTiler( b ), Mesher( b ), backend( b ) +{ +} + +Slicer::~Slicer() +{ +} + +void +Slicer::setisolines( int x ) +{ + isolines = x; +} + +void +Slicer::setstriptessellation( REAL x, REAL y ) +{ + assert(x > 0 && y > 0); + du = x; + dv = y; + setDu( du ); +} + +void +Slicer::slice( Arc_ptr loop ) +{ + loop->markverts(); + + Arc_ptr extrema[4]; + loop->getextrema( extrema ); + + unsigned int npts = loop->numpts(); + TrimRegion::init( npts, extrema[0] ); + + Mesher::init( npts ); + + long ulines = uarray.init( du, extrema[1], extrema[3] ); + + Varray varray; + long vlines = varray.init( dv, extrema[0], extrema[2] ); + long botv = 0; + long topv; + TrimRegion::init( varray.varray[botv] ); + getGridExtent( &extrema[0]->pwlArc->pts[0], &extrema[0]->pwlArc->pts[0] ); + + for( long quad=0; quadmarkverts(); + + if( jarc->pwlArc->npts >= 2 ) { + backend.bgnoutline(); + for( int j = jarc->pwlArc->npts-1; j >= 0; j-- ) + backend.linevert( &(jarc->pwlArc->pts[j]) ); + backend.endoutline(); + } +} + diff --git a/pool/shard007/C++/0096440_main.cpp b/pool/shard007/C++/0096440_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b1dfc69ebb1d21423460d68310369742775536e --- /dev/null +++ b/pool/shard007/C++/0096440_main.cpp @@ -0,0 +1,48 @@ +#include "iconnconfigmain.h" + +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + QCoreApplication::setOrganizationName("punkt-k"); + QCoreApplication::setOrganizationDomain("www.punkt-k.de"); + QCoreApplication::setApplicationName("iConnConfig"); + QCoreApplication::setApplicationVersion("0.1.5-alpha"); + + QTranslator mioConfigTranslator; + QTranslator qtTranslator; + if (mioConfigTranslator.load(QLocale(), QLatin1String("iconnconfig"), + QLatin1String("_"), + QLatin1String(":/translations/tr"))) { + app.installTranslator(&mioConfigTranslator); + + qtTranslator.load( + QLocale(), QLatin1String("qt"), QLatin1String("_"), + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + app.installTranslator(&qtTranslator); + } + + QCommandLineParser *parser = new QCommandLineParser(); + parser->setApplicationDescription("Mio Config"); + parser->addHelpOption(); + parser->addVersionOption(); + + // A boolean option with multiple names (-f, --filename) + QCommandLineOption filenameOption( + QStringList() << "f" + << "filename", + QCoreApplication::translate("main", "filename to read settings from."), + "filename"); + parser->addOption(filenameOption); + + // Process the actual command line arguments given by the user + parser->process(app); + MioMain w(parser); + w.show(); + return app.exec(); +} diff --git a/pool/shard007/C++/0096446_01.cpp b/pool/shard007/C++/0096446_01.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5280596169ae9fa530cbde731951ef5b9b20d6f2 --- /dev/null +++ b/pool/shard007/C++/0096446_01.cpp @@ -0,0 +1,63 @@ +// +// Created by 曹玉华 on 22/08/2017. +/** +8 +1 2 +5 3 +4 6 +7 5 +9 0 +10 2 +13 1 +14 0 + */ + + +//#define LOCAL +#ifdef LOCAL + +#include +#include + +using namespace std; +struct Node { + int first; + int second; +}; + +bool cmp(Node *a, Node *b) { + return a->first < b->first; +} + +int main() { + freopen("file.txt", "r", stdin); + int pairnum; + cin >> pairnum; + vector coll(pairnum); + for (int i = 0; i < pairnum; ++i) { + Node *node = new Node(); + cin >> node->first >> node->second; + coll[i] = node; + } + sort(coll.begin(), coll.end(), cmp); + vector v; + int i = 0, j = -1; + for (; i < coll.size(); ++i) { + Node *n = coll[i]; + if (!v.empty() && v[j]->first <= n->first && v[j]->second <= n->second) { + v[j]->first = n->first, v[j]->second = n->second; + } else { + Node *node = new Node(); + node->first = n->first, node->second = n->second; + v.push_back(node); + j++; + } + } + sort(v.begin(), v.end(), cmp); + for (int i = 0; i < v.size(); ++i) { + cout << v[i]->first << " " << v[i]->second << endl; + } + return 0; +} + +#endif \ No newline at end of file diff --git a/pool/shard007/C++/0096452_webapk_icon_hasher_browsertest.cc b/pool/shard007/C++/0096452_webapk_icon_hasher_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..975690a69cceb03f34aa9bac4b9447f7b1cd1cb3 --- /dev/null +++ b/pool/shard007/C++/0096452_webapk_icon_hasher_browsertest.cc @@ -0,0 +1,128 @@ +// 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 "components/webapps/browser/android/webapk/webapk_icon_hasher.h" + +#include +#include + +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" +#include "chrome/test/base/chrome_test_utils.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/manifest_icon_downloader.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "net/base/features.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" +#include "url/origin.h" + +// Browser tests for WebApkIconHasher. +class WebApkIconHasherBrowserTest : public PlatformBrowserTest { + public: + WebApkIconHasherBrowserTest() + : http_server_(net::EmbeddedTestServer::TYPE_HTTP) { + scoped_feature_list_.InitAndEnableFeature( + net::features::kSplitCacheByNetworkIsolationKey); + } + + WebApkIconHasherBrowserTest(const WebApkIconHasherBrowserTest&) = delete; + WebApkIconHasherBrowserTest& operator=(const WebApkIconHasherBrowserTest&) = + delete; + + ~WebApkIconHasherBrowserTest() override = default; + + void SetUpOnMainThread() override { + http_server_.RegisterRequestHandler(base::BindRepeating( + &WebApkIconHasherBrowserTest::OnResourceLoad, base::Unretained(this))); + http_server_.ServeFilesFromSourceDirectory("chrome/test/data/banners"); + ASSERT_TRUE(http_server_.Start()); + + ASSERT_TRUE(content::NavigateToURL( + GetActiveWebContents(), + http_server_.GetURL("/no_manifest_test_page.html"))); + + PlatformBrowserTest::SetUpOnMainThread(); + } + + content::WebContents* GetActiveWebContents() { + return chrome_test_utils::GetActiveWebContents(this); + } + + std::unique_ptr OnResourceLoad( + const net::test_server::HttpRequest& request) { + network_requests_.insert(request.GetURL()); + return nullptr; + } + + net::EmbeddedTestServer http_server_; + std::set network_requests_; + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + +namespace { + +void OnDownloadedManifestIcon(base::OnceClosure callback, + const SkBitmap& unused_icon) { + std::move(callback).Run(); +} + +void OnGotMurmur2Hash( + base::OnceClosure callback, + absl::optional> + hashes) { + std::move(callback).Run(); +} + +} // anonymous namespace + +// Checks that WebApkIconHasher fetches the icon cached in the HTTP cache by +// ManifestIconDownloader. +// +// Disabled due to flakiness. https://crbug.com/1111439 +IN_PROC_BROWSER_TEST_F(WebApkIconHasherBrowserTest, + DISABLED_HasherUsesIconFromCache) { + const GURL kIconUrl = http_server_.GetURL("/launcher-icon-max-age.png"); + + content::WebContents* web_contents = GetActiveWebContents(); + + { + base::RunLoop run_loop; + content::ManifestIconDownloader::Download( + web_contents, kIconUrl, 0, 0, std::numeric_limits::max(), + base::BindOnce(&OnDownloadedManifestIcon, run_loop.QuitClosure()), + false /* square_only */); + run_loop.Run(); + } + + ASSERT_TRUE(network_requests_.count(kIconUrl)); + network_requests_.clear(); + + { + scoped_refptr url_loader_factory = + web_contents->GetBrowserContext() + ->GetDefaultStoragePartition() + ->GetURLLoaderFactoryForBrowserProcess(); + + base::RunLoop run_loop; + webapps::WebApkIconHasher::DownloadAndComputeMurmur2Hash( + url_loader_factory.get(), web_contents->GetWeakPtr(), + url::Origin::Create(kIconUrl), {kIconUrl}, + base::BindOnce(&OnGotMurmur2Hash, run_loop.QuitClosure())); + run_loop.Run(); + } + + EXPECT_FALSE(network_requests_.count(kIconUrl)); +} diff --git a/pool/shard007/C++/0096453_CWE590_Free_Memory_Not_on_Heap__free_int64_t_static_72b.cpp b/pool/shard007/C++/0096453_CWE590_Free_Memory_Not_on_Heap__free_int64_t_static_72b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86d26b22476225f962c035c9012e9b015f5b3020 --- /dev/null +++ b/pool/shard007/C++/0096453_CWE590_Free_Memory_Not_on_Heap__free_int64_t_static_72b.cpp @@ -0,0 +1,53 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__free_int64_t_static_72b.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__free.label.xml +Template File: sources-sink-72b.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: static Data buffer is declared static on the stack + * GoodSource: Allocate memory on the heap + * Sinks: + * BadSink : Print then free data + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +#include + +using namespace std; + +namespace CWE590_Free_Memory_Not_on_Heap__free_int64_t_static_72 +{ + +#ifndef OMITBAD + +void badSink(vector dataVector) +{ + /* copy data out of dataVector */ + int64_t * data = dataVector[2]; + printLongLongLine(data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + free(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector dataVector) +{ + int64_t * data = dataVector[2]; + printLongLongLine(data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + free(data); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard007/C++/0096455_simple_bindings_support.cc b/pool/shard007/C++/0096455_simple_bindings_support.cc new file mode 100644 index 0000000000000000000000000000000000000000..eba5cccf09a742e5a2e5e7ffe0b84250ef6e8ab2 --- /dev/null +++ b/pool/shard007/C++/0096455_simple_bindings_support.cc @@ -0,0 +1,101 @@ +// 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 "mojo/public/tests/simple_bindings_support.h" + +#include + +#include + +namespace mojo { +namespace test { + +SimpleBindingsSupport::SimpleBindingsSupport() + : buf_(NULL) { + BindingsSupport::Set(this); +} + +SimpleBindingsSupport::~SimpleBindingsSupport() { + BindingsSupport::Set(NULL); + + for (WaiterList::iterator it = waiters_.begin(); it != waiters_.end(); ++it) + delete *it; +} + +Buffer* SimpleBindingsSupport::SetCurrentBuffer(Buffer* buf) { + // This is a simplistic implementation that assumes it is only ever used from + // a single thread, which is common in tests. + std::swap(buf_, buf); + return buf; +} + +Buffer* SimpleBindingsSupport::GetCurrentBuffer() { + return buf_; +} + +BindingsSupport::AsyncWaitID SimpleBindingsSupport::AsyncWait( + const Handle& handle, + MojoWaitFlags flags, + AsyncWaitCallback* callback) { + Waiter* waiter = new Waiter(); + waiter->handle = handle; + waiter->flags = flags; + waiter->callback = callback; + waiters_.push_back(waiter); + return waiter; +} + +void SimpleBindingsSupport::CancelWait(AsyncWaitID async_wait_id) { + Waiter* waiter = static_cast(async_wait_id); + + WaiterList::iterator it = waiters_.begin(); + while (it != waiters_.end()) { + if (*it == waiter) { + WaiterList::iterator doomed = it++; + waiters_.erase(doomed); + } else { + ++it; + } + } + + delete waiter; +} + +void SimpleBindingsSupport::Process() { + for (;;) { + typedef std::pair Result; + std::list results; + + WaiterList::iterator it = waiters_.begin(); + while (it != waiters_.end()) { + Waiter* waiter = *it; + MojoResult result; + if (IsReady(waiter->handle, waiter->flags, &result)) { + results.push_back(std::make_pair(waiter->callback, result)); + WaiterList::iterator doomed = it++; + waiters_.erase(doomed); + delete waiter; + } else { + ++it; + } + } + + for (std::list::const_iterator it = results.begin(); + it != results.end(); + ++it) { + it->first->OnHandleReady(it->second); + } + if (results.empty()) + break; + } +} + +bool SimpleBindingsSupport::IsReady(const Handle& handle, MojoWaitFlags flags, + MojoResult* result) { + *result = Wait(handle, flags, 0); + return *result != MOJO_RESULT_DEADLINE_EXCEEDED; +} + +} // namespace test +} // namespace mojo diff --git a/pool/shard007/C++/0096456_NoSuchAlgorithmException.cpp b/pool/shard007/C++/0096456_NoSuchAlgorithmException.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9220f652dd75763f04ca37d05db9f6725eaf682f --- /dev/null +++ b/pool/shard007/C++/0096456_NoSuchAlgorithmException.cpp @@ -0,0 +1,65 @@ +/* + * 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 "NoSuchAlgorithmException.h" + +using namespace decaf; +using namespace decaf::security; + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException() : GeneralSecurityException() { +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException(const Exception& ex) : GeneralSecurityException() { + *(Exception*) this = ex; +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException(const NoSuchAlgorithmException& ex) : GeneralSecurityException() { + *(Exception*) this = ex; +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException(const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...) : GeneralSecurityException(cause) { + + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); + + // Set the first mark for this exception. + setMark(file, lineNumber); +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException(const std::exception* cause) : GeneralSecurityException(cause) { +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::NoSuchAlgorithmException(const char* file, const int lineNumber, const char* msg, ...) : GeneralSecurityException() { + + va_list vargs; + va_start(vargs, msg); + buildMessage(msg, vargs); + + // Set the first mark for this exception. + setMark(file, lineNumber); +} + +//////////////////////////////////////////////////////////////////////////////// +NoSuchAlgorithmException::~NoSuchAlgorithmException() throw () { +} diff --git a/pool/shard007/JavaScript/0044033_main.js b/pool/shard007/JavaScript/0044033_main.js new file mode 100644 index 0000000000000000000000000000000000000000..93ca8bbd2fb4174918e657510ee4391b75d0d6d6 --- /dev/null +++ b/pool/shard007/JavaScript/0044033_main.js @@ -0,0 +1,48 @@ +import angular from 'angular'; + +// angular modules +import constants from './constants'; +import onConfig from './on_config'; +import onRun from './on_run'; +import 'angular-ui-router'; +import 'angular-material'; +import './templates'; +import './filters'; +import './controllers'; +import './services'; +import './directives'; + +// create and bootstrap application +const requires = [ + 'ui.router', + 'ngMaterial', + 'templates', + 'app.filters', + 'app.controllers', + 'app.services', + 'app.directives' +]; + +// mount on window for testing +window.app = angular.module('app', requires); + +window.app.controller('mainCtrl', ['$scope', '$timeout', function($scope, $timeout){ + this.name = 'mainCtrl'; + console.log('in mainCtrl'); + + function tick(){ + $scope.time = new Date(); + $timeout(tick, 1000); + } + tick(); + }]); + +angular.module('app').constant('AppSettings', constants); + +angular.module('app').config(onConfig); + +angular.module('app').run(onRun); + +angular.bootstrap(document, ['app'], { + strictDi: true +}); diff --git a/pool/shard007/JavaScript/0044036_AppCacheStore.js b/pool/shard007/JavaScript/0044036_AppCacheStore.js new file mode 100644 index 0000000000000000000000000000000000000000..1d12f1e8d3a18ce05bad0877f5f4e2cee02af869 --- /dev/null +++ b/pool/shard007/JavaScript/0044036_AppCacheStore.js @@ -0,0 +1,47 @@ +import { EventEmitter } from 'events'; +import ActorAppDispatcher from 'dispatcher/ActorAppDispatcher'; +import { ActionTypes } from 'constants/ActorAppConstants'; + +const CHANGE_EVENT = 'change'; + +let _isModalOpen = false; + +class AppCacheStore extends EventEmitter { + constructor() { + super(); + } + + isModalOpen() { + return _isModalOpen; + } + + emitChange() { + this.emit(CHANGE_EVENT); + } + + addChangeListener(callback) { + this.on(CHANGE_EVENT, callback); + } + + removeChangeListener(callback) { + this.removeListener(CHANGE_EVENT, callback); + } +} + +let AppCacheStoreInstance = new AppCacheStore(); + +AppCacheStoreInstance.dispatchToken = ActorAppDispatcher.register(action => { + switch(action.type) { + case ActionTypes.APP_UPDATE_MODAL_SHOW: + _isModalOpen = true; + break; + case ActionTypes.APP_UPDATE_MODAL_HIDE: + _isModalOpen = false; + break; + default: + return; + } + AppCacheStoreInstance.emitChange(); +}); + +export default AppCacheStoreInstance; diff --git a/pool/shard007/JavaScript/0044038_jquery.scrollagent.js b/pool/shard007/JavaScript/0044038_jquery.scrollagent.js new file mode 100644 index 0000000000000000000000000000000000000000..805e3f85295573034d78579c992a6c78676d8b30 --- /dev/null +++ b/pool/shard007/JavaScript/0044038_jquery.scrollagent.js @@ -0,0 +1,88 @@ +/*! jQuery.scrollagent (c) 2012, Rico Sta. Cruz. MIT License. + * https://github.com/rstacruz/jquery-stuff/tree/master/scrollagent */ + +// Call $(...).scrollagent() with a callback function. +// +// The callback will be called everytime the focus changes. +// +// Example: +// +// $("h2").scrollagent(function(cid, pid, currentElement, previousElement) { +// if (pid) { +// $("[href='#"+pid+"']").removeClass('active'); +// } +// if (cid) { +// $("[href='#"+cid+"']").addClass('active'); +// } +// }); + +(function($) { + + $.fn.scrollagent = function(options, callback) { + // Account for $.scrollspy(function) + if (typeof callback === 'undefined') { + callback = options; + options = {}; + } + + var $sections = $(this); + var $parent = options.parent || $(window); + + // Find the top offsets of each section + var offsets = []; + $sections.each(function(i) { + var offset = $(this).attr('data-anchor-offset') ? + parseInt($(this).attr('data-anchor-offset'), 10) : + (options.offset || 0); + + offsets.push({ + top: $(this).offset().top + offset, + id: $(this).attr('id'), + index: i, + el: this + }); + }); + + // State + var current = null; + var height = null; + var range = null; + + // Save the height. Do this only whenever the window is resized so we don't + // recalculate often. + $(window).on('resize', function() { + height = $parent.height(); + range = $(document).height(); + }); + + // Find the current active section every scroll tick. + $parent.on('scroll', function() { + var y = $parent.scrollTop(); + y += height * (0.3 + 0.7 * Math.pow(y/range, 2)); + + var latest = null; + + for (var i in offsets) { + if (offsets.hasOwnProperty(i)) { + var offset = offsets[i]; + if (offset.top < y) latest = offset; + } + } + + if (latest && (!current || (latest.index !== current.index))) { + callback.call($sections, + latest ? latest.id : null, + current ? current.id : null, + latest ? latest.el : null, + current ? current.el : null); + current = latest; + } + }); + + $(window).trigger('resize'); + $parent.trigger('scroll'); + + return this; + }; + +})(jQuery); diff --git a/pool/shard007/JavaScript/0044040_native_topology.js b/pool/shard007/JavaScript/0044040_native_topology.js new file mode 100644 index 0000000000000000000000000000000000000000..778ddc9fab75b85bdaf7bbd07ff890066c2d72ee --- /dev/null +++ b/pool/shard007/JavaScript/0044040_native_topology.js @@ -0,0 +1,68 @@ +'use strict'; + +const Topology = require('../core').Topology; +const ServerCapabilities = require('./topology_base').ServerCapabilities; +const Cursor = require('../cursor'); +const translateOptions = require('../utils').translateOptions; + +class NativeTopology extends Topology { + constructor(servers, options) { + options = options || {}; + + let clonedOptions = Object.assign( + {}, + { + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + maxPoolSize: typeof options.poolSize === 'number' ? options.poolSize : 5, + minPoolSize: typeof options.minSize === 'number' ? options.minSize : 0, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + super(servers, clonedOptions); + } + + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + super.command(ns.toString(), cmd, options, callback); + } + + // Insert + insert(ns, ops, options, callback) { + super.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + super.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + super.remove(ns.toString(), ops, options, callback); + } +} + +module.exports = NativeTopology; diff --git a/pool/shard007/JavaScript/0044041_debounced.js b/pool/shard007/JavaScript/0044041_debounced.js new file mode 100644 index 0000000000000000000000000000000000000000..bd7992a75dc070359077356ef4ef84b06f528eba --- /dev/null +++ b/pool/shard007/JavaScript/0044041_debounced.js @@ -0,0 +1,161 @@ +/** + * API Bound Models for AngularJS + * @version v1.1.8 - 2015-02-18 + * @link https://github.com/angular-platanus/restmod + * @author Ignacio Baixas + * @license MIT License, http://www.opensource.org/licenses/MIT + */ + +(function(angular, undefined) { +'use strict'; +/** + * @mixin DebouncedModel + * + * @description Adds debouncing to `$save` operations so rapid consecutive calls result in only one server request. + * + * Usage: + * + * First add mixin to a model's mixin chain, the following config variables are available: + * * DM_TIMEOUT: sets the debounce timeout, if 0 then debouncing is deactivated. Defaults to 500 + * * DM_ADJOURN: if true, then save operation is rescheduled on every $save call. Default to false + * + * ```javascript + * var Bike = restmod.model('api/bikes', 'DebouncedModel', { + * // This is optional. + * DM_TIMEOUT: 100 // change timeout! + * }), + * bike = Bike.build({ id: 1, brand: 'Yeti' }); + * ``` + * + * Then use `$save` as always + * + * ```javascript + * // The following code will just generate 1 request + * bike.$save(); + * bike.$save(); + * bike.$save(); + * ``` + * + * Or with options + * + * ```javascript + * bike.$save({ timeout: 0, adjourn: false }); + * // same as + * bike.$saveNow(); + * ``` + * + */ + +var isObject = angular.isObject; + +angular.module('restmod').factory('DebouncedModel', ['restmod', '$timeout', '$q', function(restmod, $timeout, $q) { + + // builds a new async save function bound to a given context and promise. + function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) { + return function() { + + // swap promises so save behaves like it has been called during the original call. + var currentPromise = _this.$promise; + _this.$promise = _oldPromise; + + // when save resolves, the timeout promise is resolved and the last resource promise returned + // so it behaves + _oldSave.call(_this).$promise.then( + function(_data) { + _promise.resolve(_data); + _this.$promise = currentPromise; + }, function(_reason) { + _promise.reject(_reason); + _this.$promise = currentPromise; + } + ); + + _this.$dmStatus = null; + }; + } + + return restmod.mixin(function() { + this.setProperty('dmTimeout', 500) + .setProperty('dmAdjourn', true) + + /** + * @method $save + * @memberOf DebouncedModel + * + * @description Debounced `$save` implementation + * + * IDEA: think of a way of separating the scheduling-rescheduling logic from + * the async save implementation, this way it can be used for other actions. + * Something like: + * + * this.$debounce('$save', fun, timeout, adjourn); + * + * This would call fun with a promise in the model context. + * + * @param {object} _opt Same as `setDebounceOptions` options. + * @return {Model} self + */ + .define('$save', function(_opt) { + + var timeout = this.$type.getProperty('dmTimeout'), + adjourn = this.$type.getProperty('dmAdjourn'), + status = this.$dmStatus; + + // apply configuration overrides + if(_opt !== undefined) { + if(isObject(_opt)) { + if(_opt.timeout !== undefined) timeout = _opt.timeout; + if(_opt.adjourn !== undefined) adjourn = _opt.adjourn; + } + } + + if(!status) { + + // if timeout is set to 0, then just call save inmediatelly. + if(!timeout) return this.$super(); + + var deferred = $q.defer(), + asyncSave = buildAsyncSaveFun(this, this.$super, deferred, this.$promise); + + this.$dmStatus = { + save: asyncSave, + promise: deferred.promise, + timeout: $timeout(asyncSave, timeout) + }; + + this.$promise = deferred.promise; + + } else { + + // reschedule only if adjourn hasnt been deactivated. + if(adjourn) { + $timeout.cancel(status.timeout); + + // depending on timeout schedule or save inmediatelly. + if(timeout) { + status.timeout = $timeout(status.save, timeout); + } else { + status.save(); + } + } + + // keep the last promise. + this.$promise = status.promise; + } + + return this; + }) + + /** + * @method $saveNow + * @memberOf DebouncedModel + * + * @description Convenience method that will cancel any pending save and save inmediatelly. + * + * @return {Model} self + */ + .define('$saveNow', function() { + return this.$save({ timeout: 0, adjourn: true }); + }); + }); +}]);})(angular); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044045_actions.js b/pool/shard007/JavaScript/0044045_actions.js new file mode 100644 index 0000000000000000000000000000000000000000..9067654c1d2ecb221f8fe60365a5a6ba33cbe65a --- /dev/null +++ b/pool/shard007/JavaScript/0044045_actions.js @@ -0,0 +1,224 @@ +define(function(require) { + /* + DEPENDENCIES + */ + + var Locale = require('utils/locale'); + var Sunstone = require('sunstone'); + var Humanize = require('utils/humanize'); + var TemplateUtils = require('utils/template-utils'); + + /* + CONSTANTS + */ + + var TAB_ID = require('../tabId'); + var PANEL_ID = require('./actions/panelId'); + var RESOURCE = "VM"; + var XML_ROOT = "VM"; + + /* + CONSTRUCTOR + */ + + function Panel(info) { + this.panelId = PANEL_ID; + this.title = Locale.tr("Actions"); + this.icon = "fa-calendar"; + + this.element = info[XML_ROOT]; + + return this; + }; + + Panel.PANEL_ID = PANEL_ID; + Panel.prototype.html = _html; + Panel.prototype.setup = _setup; + + return Panel; + + /* + FUNCTION DEFINITIONS + */ + + function _html() { + var that = this; + var html = '
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + ' + + fromJSONtoActionsTable(that.element.USER_TEMPLATE.SCHED_ACTION) + + '
' + Locale.tr("ID") + '' + Locale.tr("ACTION") + '' + Locale.tr("TIME") + '' + Locale.tr("DONE") + '' + Locale.tr("MESSAGE") + '' + Locale.tr("Actions") + '
\ +
\ +
'; + + return html; + } + + function _setup(context) { + var that = this; + context.off('click', '#add_scheduling_action'); + context.on('click', '#add_scheduling_action', function() { + $("#add_scheduling_action", context).attr("disabled", "disabled"); + $("#scheduling_actions_table").append('\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + '); + + return false; + }); + + context.off("click", "#submit_scheduling_action"); + context.on("click", "#submit_scheduling_action", function() { + var date_input_value = $("#date_input", context).val(); + var time_input_value = $("#time_input", context).val(); + + if (date_input_value == "" || time_input_value == "") + return false; + + var time_value = date_input_value + ' ' + time_input_value + + // Calculate MAX_ID + var max_id = -1; + + if (that.element.USER_TEMPLATE.SCHED_ACTION) { + if (!that.element.USER_TEMPLATE.SCHED_ACTION.length) { + var tmp_element = that.element.USER_TEMPLATE.SCHED_ACTION; + that.element.USER_TEMPLATE.SCHED_ACTION = new Array(); + that.element.USER_TEMPLATE.SCHED_ACTION.push(tmp_element); + } + + $.each(that.element.USER_TEMPLATE.SCHED_ACTION, function(i, element) { + if (max_id < element.ID) + max_id = element.ID + }) + } else { + that.element.USER_TEMPLATE.SCHED_ACTION = new Array(); + } + + var new_action = {}; + new_action.ID = parseInt(max_id) + 1; + new_action.ACTION = $("#select_new_action", context).val(); + var epoch_str = new Date(time_value); + + new_action.TIME = parseInt(epoch_str.getTime()) / 1000; + + that.element.USER_TEMPLATE.SCHED_ACTION.push(new_action); + + // Let OpenNebula know + var template_str = TemplateUtils.templateToString(that.element.USER_TEMPLATE); + Sunstone.runAction("VM.update_template", that.element.ID, template_str); + + $("#add_scheduling_action", context).removeAttr("disabled"); + return false; + }); + + // Listener for key,value pair remove action + context.off("click", ".remove_action_x"); + context.on("click", ".remove_action_x", function() { + var index = this.id.substring(6, this.id.length); + var tmp_tmpl = new Array(); + + $.each(that.element.USER_TEMPLATE.SCHED_ACTION, function(i, element) { + if (element.ID != index) + tmp_tmpl[i] = element + }) + + that.element.USER_TEMPLATE.SCHED_ACTION = tmp_tmpl; + var template_str = TemplateUtils.templateToString(that.element.USER_TEMPLATE); + + // Let OpenNebula know + Sunstone.runAction("VM.update_template", that.element.ID, template_str); + }); + + } + + // Returns an HTML string with the json keys and values + function fromJSONtoActionsTable(actions_array) { + var str = "" + var empty = '\ + \ + ' + Locale.tr("No actions to show") + '\ + ' ; + + if (!actions_array) { + return empty; + } + + if (!$.isArray(actions_array)) { + var tmp_array = new Array(); + tmp_array[0] = actions_array; + actions_array = tmp_array; + } + + if (!actions_array.length) { + return empty; + } + + $.each(actions_array, function(index, scheduling_action) { + str += fromJSONtoActionRow(scheduling_action); + }); + + return str; + } + + // Helper for fromJSONtoHTMLTable function + function fromJSONtoActionRow(scheduling_action) { + var done_str = scheduling_action.DONE ? (Humanize.prettyTime(scheduling_action.DONE)) : ""; + var message_str = scheduling_action.MESSAGE ? scheduling_action.MESSAGE : ""; + var time_str = Humanize.prettyTime(scheduling_action.TIME); + + var str = ""; + str += '\ + ' + scheduling_action.ID + '\ + ' + scheduling_action.ACTION + '\ + ' + time_str + '\ + ' + done_str + '\ + ' + message_str + '\ + \ +
\ + \ +
\ + \ + '; + + return str; + } +}); diff --git a/pool/shard007/JavaScript/0044047_text.js b/pool/shard007/JavaScript/0044047_text.js new file mode 100644 index 0000000000000000000000000000000000000000..4acd236ed1d6aebc3171c8b0e80ce4c05c525823 --- /dev/null +++ b/pool/shard007/JavaScript/0044047_text.js @@ -0,0 +1,210 @@ + +// List font style attributes as they should be applied to style +var _styleAttr = ('size family weight stretch variant style').split(' ') + +SVG.Text = function() { + this.constructor.call(this, SVG.create('text')) + + /* define default style */ + this.styles = { + 'font-size': 16 + , 'font-family': 'Helvetica, Arial, sans-serif' + , 'text-anchor': 'start' + } + + this._leading = new SVG.Number('1.2em') + this._rebuild = true +} + +// Inherit from SVG.Element +SVG.Text.prototype = new SVG.Shape + +// +SVG.extend(SVG.Text, { + // Move over x-axis + x: function(x, a) { + /* act as getter */ + if (x == null) + return a ? this.attr('x') : this.bbox().x + + /* set x taking anchor in mind */ + if (!a) { + a = this.style('text-anchor') + x = a == 'start' ? x : a == 'end' ? x + this.bbox().width : x + this.bbox().width / 2 + } + + /* move lines as well if no textPath si present */ + if (!this.textPath) + this.lines.each(function() { if (this.newLined) this.x(x) }) + + return this.attr('x', x) + } + // Move center over x-axis +, cx: function(x, a) { + return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2) + } + // Move center over y-axis +, cy: function(y, a) { + return y == null ? this.bbox().cy : this.y(a ? y : y - this.bbox().height / 2) + } + // Move element to given x and y values +, move: function(x, y, a) { + return this.x(x, a).y(y) + } + // Move element by its center +, center: function(x, y, a) { + return this.cx(x, a).cy(y, a) + } + // Set the text content +, text: function(text) { + /* act as getter */ + if (text == null) + return this.content + + /* remove existing lines */ + this.clear() + + if (typeof text === 'function') { + this._rebuild = false + + text(this) + + } else { + this._rebuild = true + + /* make sure text is not blank */ + text = SVG.regex.isBlank.test(text) ? 'text' : text + + var i, il + , lines = text.split('\n') + + /* build new lines */ + for (i = 0, il = lines.length; i < il; i++) + this.tspan(lines[i]).newLine() + + this.rebuild() + } + + return this + } + // Create a tspan +, tspan: function(text) { + var node = this.textPath ? this.textPath.node : this.node + , tspan = new SVG.TSpan().text(text) + , style = this.style() + + /* add new tspan */ + node.appendChild(tspan.node) + this.lines.add(tspan) + + /* add style if any */ + if (!SVG.regex.isBlank.test(style)) + tspan.style(style) + + /* store content */ + this.content += text + + /* store text parent */ + tspan.parent = this + + return tspan + } + // Set font size +, size: function(size) { + return this.attr('font-size', size) + } + // Set / get leading +, leading: function(value) { + /* act as getter */ + if (value == null) + return this._leading + + /* act as setter */ + value = new SVG.Number(value) + this._leading = value + + /* apply leading */ + this.lines.each(function() { + if (this.newLined) + this.attr('dy', value) + }) + + return this + } + // rebuild appearance type +, rebuild: function() { + var self = this + + /* define position of all lines */ + if (this._rebuild) { + this.lines.attr({ + x: this.attr('x') + , dy: this._leading + , style: this.style() + }) + } + + return this + } + // Clear all lines +, clear: function() { + var node = this.textPath ? this.textPath.node : this.node + + /* remove existing child nodes */ + while (node.hasChildNodes()) + node.removeChild(node.lastChild) + + /* refresh lines */ + delete this.lines + this.lines = new SVG.Set + + /* initialize content */ + this.content = '' + + return this + } + +}) + +// +SVG.extend(SVG.Container, { + // Create text element + text: function(text) { + return this.put(new SVG.Text).text(text) + } + +}) + +// tspan class +SVG.TSpan = function() { + this.constructor.call(this, SVG.create('tspan')) +} + +// Inherit from SVG.Shape +SVG.TSpan.prototype = new SVG.Shape + +// Include the container object +SVG.extend(SVG.TSpan, { + // Set text content + text: function(text) { + this.node.appendChild(document.createTextNode(text)) + + return this + } + // Shortcut dx +, dx: function(dx) { + return this.attr('dx', dx) + } + // Shortcut dy +, dy: function(dy) { + return this.attr('dy', dy) + } + // Create new line +, newLine: function() { + this.newLined = true + this.parent.content += '\n' + this.dy(this.parent._leading) + return this.attr('x', this.parent.x()) + } + +}) diff --git a/pool/shard007/JavaScript/0044051_application.js b/pool/shard007/JavaScript/0044051_application.js new file mode 100644 index 0000000000000000000000000000000000000000..782353eed2c7cec84c09910e57d0329ca91e443c --- /dev/null +++ b/pool/shard007/JavaScript/0044051_application.js @@ -0,0 +1,41 @@ +$(document).ready(function() { + + clickChecker(); + customeMessage(); + +}); + +var clickChecker = function(){ + $('.contact').on('click', function(event){ + event.preventDefault(); + + var contact_id = $(this).attr('id'); + + var request = $.ajax ({ + url: "/messages", + method: "GET", + dataType: "html", + data: {contact_id: contact_id} + }); + + request.done(function(response){ + // debugger + if (!$('#' + contact_id ).find('.message').length == 0){ + $('#' + contact_id + ' .message').toggle() + } + else { + $('#' + contact_id).append(response) + } + }); + + }); +}; + +var customeMessage = function(){ + $('#text_button').on('click', function(event){ + event.preventDefault(); + $(this).hide(); + $('#customTextField').toggle(); + }); + +}; diff --git a/pool/shard007/JavaScript/0044057_FileName.js b/pool/shard007/JavaScript/0044057_FileName.js new file mode 100644 index 0000000000000000000000000000000000000000..b933dce67a151956941403a28502f6caf125c027 --- /dev/null +++ b/pool/shard007/JavaScript/0044057_FileName.js @@ -0,0 +1,43 @@ +"use babel"; + +const Metadata = require('lupa').Metadata; +const getMetadata = Metadata.getMetadata; + +const getLines = (f) => { + const item = getMetadata(f).filter((item) => item.type == 'lines')[0] || {} + return item.data || 0; +} + + +const React = require('react'); +const div = React.createFactory('div'); +const span = React.createFactory('span'); +const LineCount = require('./LineCount'); + + +class FileName extends React.Component { + render() { + const f = this.props.file; + const preview = this.props.preview; + const onClick = () => { + // if !fs.existsSync(path) + // path = getFileForRequire(allFiles, path).path + + preview.getBuffer().setPath(f.path) + preview.setText(f.contents + ''); + console.log("ON CHANGEX", this.props.onChange, this.props.line) + this.props.onChange && this.props.onChange(this.props.line); + preview.scrollToBufferPosition([this.props.line || 0, 0]); + //atom.workspace.open(f.path, {initialLine: this.props.line || 0}); + }; + return div({className: 'lupa-file', onClick: onClick}, [ + this.props.desc? + {this.props.desc} + {f.path} + : f.path, + React.createElement(LineCount, {lines: getLines(f)}) + ]) + } +} + +module.exports = FileName; diff --git a/pool/shard007/JavaScript/0044058_events_router.js b/pool/shard007/JavaScript/0044058_events_router.js new file mode 100644 index 0000000000000000000000000000000000000000..653084a4182ec2da77c616c91daa26308bf52c89 --- /dev/null +++ b/pool/shard007/JavaScript/0044058_events_router.js @@ -0,0 +1,27 @@ +var EventsRouter = Ne.Class("EventsRouter")({ + setupRoutes : function setupRoutes(app) { + app.get('/api/v1/events', function (req, res) { + EventsController.index(req, res); + }); + app.get('/api/v1/events/:id', function (req, res) { + EventsController.show(req, res); + }); + app.post('/api/v1/events/:id/teams', function (req, res) { + EventsController.addTeam(req, res); + }); + app.get('/api/v1/events/:id/teams', function (req, res) { + EventsController.getTeams(req, res); + }); + app.post('/api/v1/events/:id/players', function (req, res) { + EventsController.addPlayer(req, res); + }); + app.get('/api/v1/events/:id/players', function (req, res) { + EventsController.getPlayers(req, res); + }); + app.get('/api/v1/events/:id/players/:playerId/remove', function (req, res) { + EventsController.removePlayer(req, res); + }); + } +}); + +module.exports = EventsRouter; diff --git a/pool/shard007/JavaScript/0044060_user.plugins.error.js b/pool/shard007/JavaScript/0044060_user.plugins.error.js new file mode 100644 index 0000000000000000000000000000000000000000..59ec8a5edf80fec29cbc1d65b300d7522c25a8f1 --- /dev/null +++ b/pool/shard007/JavaScript/0044060_user.plugins.error.js @@ -0,0 +1,33 @@ +"use strict"; + +var browserSync = require("../../../"); +var utils = require("../../../lib/utils"); +var path = require("path"); +var pkg = require(path.resolve("package.json")); +var cli = require(path.resolve(pkg.bin)); +var assert = require("chai").assert; + +describe("Plugins: Exit when plugin not found", function () { + it("returns an error if a plugin cannot be located", function (done) { + var stub = require("sinon").stub(utils, "fail"); + browserSync.reset(); + + cli({ + cli: { + input: ["start"], + flags: { + logLevel: "silent", + plugins: ["bs-oops-typos"], + open: false + } + }, + cb: function (err, bs) { + var err = stub.getCall(0).args[1]; + assert.include(err.message, "bs-oops-typos"); + utils.fail.restore(); + bs.cleanup(); + done(); + } + }); + }); +}); diff --git a/pool/shard007/JavaScript/0044062_getTask.js b/pool/shard007/JavaScript/0044062_getTask.js new file mode 100644 index 0000000000000000000000000000000000000000..161303707263a7cfe99f827ccf02b64fa59b8396 --- /dev/null +++ b/pool/shard007/JavaScript/0044062_getTask.js @@ -0,0 +1,9 @@ +const { db } = require('./_helper'); + +module.exports = function(data, sess, cookie, qs) { + const value = db.get('task').value(); + if (value && value[data.id]) + return {resultCode:0, data:value[data.id]} + else + return {resultCode:404,resultDescription:'NOT_FOUND'} +} diff --git a/pool/shard007/JavaScript/0044063_todo2.js b/pool/shard007/JavaScript/0044063_todo2.js new file mode 100644 index 0000000000000000000000000000000000000000..b19e3510adbd1bb50f217b3ee3eccb7d96730bf7 --- /dev/null +++ b/pool/shard007/JavaScript/0044063_todo2.js @@ -0,0 +1,53 @@ +var Todo = ng + .core + .Component({ + selector: 'todo', + templateUrl: 'partials/todo2.html' , + directives: [ng.common.CORE_DIRECTIVES, ng.common.FORM_DIRECTIVES], + }) + .Class({ + constructor: function() { + this.label = ''; + this.todos = [{ + label: 'Learn Angular', + complete: false + },{ + label: 'Learn Angular2', + complete: false + },{ + label: 'Learn React', + complete: false + },{ + label: 'Learn Redux', + complete: false + },{ + label: 'Learn Alt', + complete: false + }]; + }, + + updateIncomplete: function() { + return this.todos.filter(function(item) { + return !item.complete; + }).length; + }, + + deleteItem: function(index) { + this.todos.splice(index, 1); + }, + + onSubmit: function(event) { + event.preventDefault(); + if (this.label.length) { + this.todos.unshift({ + label: this.label, + complete: false + }); + this.label = ''; + } + } + }); + +document.addEventListener('DOMContentLoaded', function() { + ng.platform.browser.bootstrap(Todo); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044067_fanout-logic.js b/pool/shard007/JavaScript/0044067_fanout-logic.js new file mode 100644 index 0000000000000000000000000000000000000000..f115f4d9618e021aecf93157d35175a426459cbe --- /dev/null +++ b/pool/shard007/JavaScript/0044067_fanout-logic.js @@ -0,0 +1,25 @@ +'use strict' + +var _ = require('lodash') + +module.exports = function fanout (options) { + var seneca = this + + seneca.add('fanout:entry', function(msg, done) { + done() + + var entry = this.util.clean(msg) + delete entry.fanout + + this.act('follow:list,kind:followers',{user:entry.user},function(err,userlist){ + if(err) return + + if( userlist && 0 < userlist.length ) { + this.act({ + timeline: 'insert', + users: userlist, + }, entry) + } + }) + }) +} diff --git a/pool/shard007/JavaScript/0044068_report-message.controller.js b/pool/shard007/JavaScript/0044068_report-message.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..686112e9f621ddd402104e8636ef4298294da2b9 --- /dev/null +++ b/pool/shard007/JavaScript/0044068_report-message.controller.js @@ -0,0 +1,29 @@ +ReportMessageController = [ + '$scope', + '$mdDialog', + function($scope, $mdDialog) { + + $scope.report = { + reason: '', + typeId: '', + category: '', + description: '' + }; + + $scope.hide = function() { + $mdDialog.hide(); + }; + + $scope.cancel = function() { + $mdDialog.cancel(); + }; + + $scope.save = function() { + if (!$scope.report || s.isBlank($scope.report.reason)) { + return; + } + + $mdDialog.hide($scope.report); + }; + } +] diff --git a/pool/shard007/JavaScript/0044070_mainjs.js b/pool/shard007/JavaScript/0044070_mainjs.js new file mode 100644 index 0000000000000000000000000000000000000000..7736dd4acb2aab9495e82a340d0a4b8f121929eb --- /dev/null +++ b/pool/shard007/JavaScript/0044070_mainjs.js @@ -0,0 +1,38 @@ +'use strict' + +var basePath='http://127.0.0.1:8080/htmltemplate/'; //tomcat + +$(function(){ + + //项目主类用来引入其他公用脚本 + +}); + +var mainjs=new Object({ + initFileList: function(){ + + console.log('-------------start mainjs script load-----------------'); + + //以下ajax可以复制多个来引入公用js + //方案1 + //$.getScript( basePath+'js/lib/toastr/toastr.min.js'); + //方案2 + $.ajax({ + type:'post',//加载方式post + async: false,//使用同步的方式,true为异步方式 + //crossDomain: true,//跨域支持 本地运行时需要解开 + cache:false, //缓存 + url : basePath+'js/lib/toastr/toastr.min.js',//载入脚本路径 正式时需加basePath + dataType: 'script', + scriptCharset:'utf-8' + }); + + console.log('-------------end mainjs script load-----------------'); + + } +}); + +//不要移动这句位置 +mainjs.initFileList(); + + diff --git a/pool/shard007/JavaScript/0044074_bg.js b/pool/shard007/JavaScript/0044074_bg.js new file mode 100644 index 0000000000000000000000000000000000000000..e035c2ff94b8a4656b33e4693800a02bb6ff0acc --- /dev/null +++ b/pool/shard007/JavaScript/0044074_bg.js @@ -0,0 +1,135 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define('element/locale/bg', ['module', 'exports'], factory); + } else if (typeof exports !== "undefined") { + factory(module, exports); + } else { + var mod = { + exports: {} + }; + factory(mod, mod.exports); + global.ELEMENT.lang = global.ELEMENT.lang || {}; + global.ELEMENT.lang.bg = mod.exports; + } +})(this, function (module, exports) { + 'use strict'; + + exports.__esModule = true; + exports.default = { + el: { + colorpicker: { + confirm: 'OK', + clear: 'Изчисти' + }, + datepicker: { + now: 'Сега', + today: 'Днес', + cancel: 'Откажи', + clear: 'Изчисти', + confirm: 'ОК', + selectDate: 'Избери дата', + selectTime: 'Избери час', + startDate: 'Начална дата', + startTime: 'Начален час', + endDate: 'Крайна дата', + endTime: 'Краен час', + prevYear: 'Previous Year', // to be translated + nextYear: 'Next Year', // to be translated + prevMonth: 'Previous Month', // to be translated + nextMonth: 'Next Month', // to be translated + year: '', + month1: 'Януари', + month2: 'Февруари', + month3: 'Март', + month4: 'Април', + month5: 'Май', + month6: 'Юни', + month7: 'Юли', + month8: 'Август', + month9: 'Септември', + month10: 'Октомври', + month11: 'Ноември', + month12: 'Декември', + // week: 'Седмица', + weeks: { + sun: 'Нед', + mon: 'Пон', + tue: 'Вто', + wed: 'Сря', + thu: 'Чет', + fri: 'Пет', + sat: 'Съб' + }, + months: { + jan: 'Яну', + feb: 'Фев', + mar: 'Мар', + apr: 'Апр', + may: 'Май', + jun: 'Юни', + jul: 'Юли', + aug: 'Авг', + sep: 'Сеп', + oct: 'Окт', + nov: 'Ное', + dec: 'Дек' + } + }, + select: { + loading: 'Зареждане', + noMatch: 'Няма намерени', + noData: 'Няма данни', + placeholder: 'Избери' + }, + cascader: { + noMatch: 'Няма намерени', + loading: 'Зареждане', + placeholder: 'Избери', + noData: 'Няма данни' + }, + pagination: { + goto: 'Иди на', + pagesize: '/страница', + total: 'Общо {total}', + pageClassifier: '' + }, + messagebox: { + title: 'Съобщение', + confirm: 'ОК', + cancel: 'Откажи', + error: 'Невалидни данни' + }, + upload: { + deleteTip: 'press delete to remove', // to be translated + delete: 'Изтрий', + preview: 'Прегледай', + continue: 'Продължи' + }, + table: { + emptyText: 'Няма данни', + confirmFilter: 'Потвърди', + resetFilter: 'Изчисти', + clearFilter: 'Всички', + sumText: 'Sum' // to be translated + }, + tree: { + emptyText: 'Няма данни' + }, + transfer: { + noMatch: 'Няма намерени', + noData: 'Няма данни', + titles: ['List 1', 'List 2'], // to be translated + filterPlaceholder: 'Enter keyword', // to be translated + noCheckedFormat: '{total} items', // to be translated + hasCheckedFormat: '{checked}/{total} checked' // to be translated + }, + image: { + error: 'FAILED' // to be translated + }, + pageHeader: { + title: 'Back' // to be translated + } + } + }; + module.exports = exports['default']; +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044075_information.js b/pool/shard007/JavaScript/0044075_information.js new file mode 100644 index 0000000000000000000000000000000000000000..92da95acb0326e5970e5811ae5f7fd2a75539637 --- /dev/null +++ b/pool/shard007/JavaScript/0044075_information.js @@ -0,0 +1,82 @@ +/** + * Created by ForeverW on 2017/4/13. + */ +var express = require('express'); +var crypto = require('crypto'); +var cookie = require('cookie-parser'); +var router = express.Router(); +var bodyParser=require('body-parser'); +var mongoose=require('mongoose'); +mongoose.Promise = global.Promise; +var userInfoSchema=require('../models/user/userInfo'); +var db=mongoose.createConnection('mongodb://127.0.0.1:27017/mySport'); + +/* GET home page. */ +router.get('/', function(req, res, next) { + if(req.cookies) { + var Cookies={}; + var mySportCookies=req.headers.cookie; + mySportCookies.split(';').forEach(function (Cookie) { + var parts=Cookie.split('='); + Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim(); + }); + var usernameCookie=Cookies.usernameCookies; + var mongooseUserInfoModel=db.model('mongoose',userInfoSchema,'userInfo'); + // 查询用户信息 + + mongooseUserInfoModel.find({username:usernameCookie},function (err,result) { + if(err) { + console.log(err); + } else { + var userInfo=result[0]; + console.log(userInfo); + res.render('information',{ + username:usernameCookie, + userInfoUpdateSucceed:'', + userInfo:userInfo, + title:'用户信息' + }) + } + }) + } else { + res.send('lskdfk') + } +}); + + +router.post('/save',function (req,res,next) { + var Cookies={}; + var mySportCookies=req.headers.cookie; + mySportCookies.split(';').forEach(function (Cookie) { + var parts=Cookie.split('='); + Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim(); + }); + var usernameCookie=Cookies.usernameCookies; + var userNickName=req.body.userNickName; + var userActualName=req.body.userActualName; + var usernameIDNum=req.body.usernameIDNum; + var usernameEmail=req.body.usernameEmail; + var userSignature=req.body.userSignature; + var userBirthDay=req.body.userBirthDay; + + var userInfoUpdate={ + userNickName:userNickName, + userActualName:userActualName, + usernameIDNum:usernameIDNum, + usernameEmail:usernameEmail, + userSignature:userSignature, + userBirthDay:userBirthDay + }; + console.log(userInfoUpdate); + var mongooseUserInfoModel=db.model('mongoose',userInfoSchema,'userInfo'); + mongooseUserInfoModel.update({username:usernameCookie},userInfoUpdate,function (err) { + if(err) { + console.log(err); + } else { + res.redirect('/information'); + } + }) + +}); + +module.exports = router; diff --git a/pool/shard007/JavaScript/0044076_UpgradeCommand_1_1_0.js b/pool/shard007/JavaScript/0044076_UpgradeCommand_1_1_0.js new file mode 100644 index 0000000000000000000000000000000000000000..aac9d7e62b61dc22035ccf94ca21a2660f4cef10 --- /dev/null +++ b/pool/shard007/JavaScript/0044076_UpgradeCommand_1_1_0.js @@ -0,0 +1,74 @@ +/// +//import globals = require("../../Globals"); +//import params = require("../../ParamsParser"); +var file = require('../../lib/FileUtil'); +//import config = require('../../lib/ProjectConfig'); +var UpgradeCommand_1_1_0 = (function () { + function UpgradeCommand_1_1_0() { + } + UpgradeCommand_1_1_0.prototype.execute = function () { + this.upgradeTo_1_1_0(); + return 0; + }; + UpgradeCommand_1_1_0.prototype.upgradeTo_1_1_0 = function () { + //替换 全部 html + var projectDir = egret.args.projectDir; + var reg1 = /[^<]*<\/div>/; + var newDiv = '
'; + var fileList = file.getDirectoryListing(file.joinPath(projectDir, "launcher"), true); + for (var key in fileList) { + var fileName = fileList[key]; + var filePath = file.joinPath(projectDir, "launcher", fileName); + if (file.isDirectory(filePath)) { + } + else if (filePath.indexOf(".html") >= 0) { + var fileContent = file.read(filePath); + //替换Div + var matchObj = fileContent.match(/', endIndex); + while (lastIndex >= 0) { + if (fileContent.indexOf("', endIndex + 1); + } + else { + endIndex = lastIndex; + lastIndex = -1; + } + } + fileContent = fileContent.substring(0, firstIndex) + newDiv + fileContent.substring(endIndex, fileContent.length); + //是否存在egret_require.js + if (fileContent.indexOf("launcher/egret_require.js") < 0) { + fileContent = fileContent.replace('\n + + + + `, + }); + }, + }, + ], + }); +} + +module.exports = async function buildAll() { + const experimentDist = path.resolve(__dirname, '../../dist'); + const experimentBuild = path.resolve(experimentDist, '@glimmer'); + if (!fs.existsSync(experimentBuild)) { + return; + } + await build(experimentDist, path.resolve(experimentDist, 'benchmarks/experiment')); + const controlDist = path.resolve(__dirname, '../../control-dist'); + const controlBuild = path.resolve(controlDist, '@glimmer'); + if (fs.existsSync(controlBuild)) { + if (!fs.existsSync(path.join(controlDist, 'node_modules'))) { + fs.mkdirsSync(path.join(controlDist, 'node_modules')); + symlinkOrCopy( + path.join(controlDist, '@glimmer'), + path.join(controlDist, 'node_modules/@glimmer') + ); + } + await build(controlDist, path.resolve(experimentDist, 'benchmarks/control')); + } +}; diff --git a/pool/shard007/JavaScript/0044279_backend.js b/pool/shard007/JavaScript/0044279_backend.js new file mode 100644 index 0000000000000000000000000000000000000000..7585386100a03bae983dd3a7538a19897bb44b94 --- /dev/null +++ b/pool/shard007/JavaScript/0044279_backend.js @@ -0,0 +1,64 @@ +import { dispatchActionFromTopic, sendClientHello } from "./actions.js"; +import conf from "./config.js"; +import { toast } from "react-toastify"; + +class Backend { + startKeepAlivePoller = () => { + setInterval(() => { + if ( + this.socket.readyState !== this.socket.OPEN && + this.socket.readyState !== this.socket.CONNECTING + ) { + this.connect(); + } + }, 25000); + }; + + connect() { + this.url = `${conf.backend_address}/ws`; + + return new Promise((resolve, reject) => { + this.socket = new WebSocket(this.url); + this.socket.onmessage = this._messageReceive; + this.socket.onclose = this.socketClosed; + this.socket.onopen = () => resolve(this); + }) + .then(() => { + sendClientHello(); + }) + .catch(err => { + console.log(err); + toast.error(`Error: ${err}`); + }); + } + + _messageReceive = event => { + const s = event.data; + const type = s.substr(0, s.indexOf(" ")); + const content = s.substr(s.indexOf(" ") + 1); + dispatchActionFromTopic(type, JSON.parse(content)); + }; + + socketClosed = event => { + console.log("socketClosed: ", event); + }; + + send = (msg, obj = {}) => { + if ( + this.socket.readyState !== this.socket.OPEN && + this.socket.readyState !== this.socket.CONNECTING + ) { + console.log( + "Send, socket is not OPEN, restarting websocket and sending new, socketstate is:", + this.socket.readyState + ); + this.connect().then(() => { + this.socket.send(msg + " " + JSON.stringify(obj)); + }); + } else { + this.socket.send(msg + " " + JSON.stringify(obj)); + } + }; +} + +export default new Backend(); diff --git a/pool/shard007/JavaScript/0044280_re-metadata.js b/pool/shard007/JavaScript/0044280_re-metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..08ea0be0f051d6c57f88ba25d813634cbb741418 --- /dev/null +++ b/pool/shard007/JavaScript/0044280_re-metadata.js @@ -0,0 +1,87 @@ +'use strict'; + +const couchdbIterator = require('couchdb-iterator'); +const metadata = require('../../lib/analyze/collect/metadata'); +const packageJsonFromData = require('../../lib/analyze/util/packageJsonFromData'); +const analyze = require('../../lib/analyze'); +const bootstrap = require('../util/bootstrap'); +const stats = require('../util/stats'); + +const log = logger.child({ module: 'cli/re-metadata' }); + +exports.command = 're-metadata [options]'; +exports.describe = 'Iterates over all analyzed packages, running the metadata collector again'; + +exports.builder = (yargs) => + yargs + .usage('Usage: $0 tasks re-metadata [options]\n\n\ +Iterates over all analyzed packages, running the metadata collector again.\nThis command is useful if there was a bug in the \ +metadata collector. Note that the packages score won\'t be updated.'); + +exports.handler = (argv) => { + process.title = 'npms-analyzer-re-metadata'; + logger.level = argv.logLevel || 'info'; + + // Bootstrap dependencies on external services + bootstrap(['couchdbNpm', 'couchdbNpms']) + .spread((npmNano, npmsNano) => { + log.info('Starting packages re-metadata'); + + // Stats + stats.process(); + + // Iterate over all packages + return couchdbIterator(npmsNano, (row) => { + row.index && row.index % 2500 === 0 && log.info(`Processed ${row.index} rows`); + + if (!row.doc) { + return; + } + + const name = row.id.split('!')[1]; + + // Grab package data + return npmNano.getAsync(name) + .then((data) => { + let packageJson; + + // Extract package json + try { + packageJson = packageJsonFromData(name, data); + } catch (err) { + if (!err.unrecoverable) { + throw err; + } + + // Remove the package if an unrecoverable error happened + // We do this to prevent old metadata to stay around, which will probably cause issues further ahead + return analyze.remove(name, npmsNano); + } + + // Re-run metadata + return metadata(data, packageJson) + // Save it! + .then((metadata) => { + row.doc.collected.metadata = metadata; + + return analyze.save(row.doc, npmsNano); + }) + .catch((err) => { + log.error({ err }, `Failed to process ${name}`); + throw err; + }); + }) + // Delete the analisis if the package does not exist in npm (e.g.: was deleted) + .catch({ error: 'not_found' }, () => analyze.remove(name, npmsNano)); + }, { + startkey: 'package!', + endkey: 'package!\ufff0', + concurrency: 25, + limit: 2500, + includeDocs: true, + }) + .then((count) => log.info(`Completed, processed a total of ${count} rows`)); + }) + .then(() => process.exit()) + .done(); +}; diff --git a/pool/shard007/JavaScript/0044286_index.js b/pool/shard007/JavaScript/0044286_index.js new file mode 100644 index 0000000000000000000000000000000000000000..27ac2a93ed6d32c55687f8946ed75169068b8842 --- /dev/null +++ b/pool/shard007/JavaScript/0044286_index.js @@ -0,0 +1,24 @@ +'use strict'; + +var nconf = require('nconf'); +var path = require('path'); + +function Config() { + var environment; + + nconf.argv().env('_'); + environment = nconf.get('NODE:ENV') || 'development'; + + nconf.file(environment, 'lib/config/' + environment + '.json'); + nconf.file('default', 'lib/config/default.json'); +} + +Config.prototype.get = function(key) { + return nconf.get(key); +}; + +Config.prototype.rootPath = function() { + return path.resolve('.'); +}; + +module.exports = new Config(); diff --git a/pool/shard007/JavaScript/0044287_index.js b/pool/shard007/JavaScript/0044287_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4a507e525f720ae89f4d63a737094c05006f30f7 --- /dev/null +++ b/pool/shard007/JavaScript/0044287_index.js @@ -0,0 +1,39 @@ +'use strict'; + +module.exports = { + name: require('./package').name, + + included(appOrAddon) { + let app = appOrAddon.app || appOrAddon; + if (app.__emberBasicDropdownIncludedInvoked) { + this._super.included.apply(this, arguments); + return; + } + app.__emberBasicDropdownIncludedInvoked = true; + this._super.included.apply(this, arguments); + + let hasSass = !!app.registry.availablePlugins['ember-cli-sass']; + let hasLess = !!app.registry.availablePlugins['ember-cli-less']; + + // Don't include the precompiled css file if the user uses a supported CSS preprocessor + if (!hasSass && !hasLess) { + if (!app.__skipEmberBasicDropdownStyles) { + app.import('vendor/ember-basic-dropdown.css'); + } + } + }, + + contentFor(type, config) { + let basicDropdownConfig = config['ember-basic-dropdown']; + if (!basicDropdownConfig || !basicDropdownConfig.destination) { + if ( + config.environment !== 'test' && + type === 'body-footer' && + !config._emberBasicDropdownContentForInvoked + ) { + config._emberBasicDropdownContentForInvoked = true; + return '
'; + } + } + }, +}; diff --git a/pool/shard007/JavaScript/0044290_BarButtons.js b/pool/shard007/JavaScript/0044290_BarButtons.js new file mode 100644 index 0000000000000000000000000000000000000000..addb14c98fb29474a0af8506910257f868362ddf --- /dev/null +++ b/pool/shard007/JavaScript/0044290_BarButtons.js @@ -0,0 +1,67 @@ +/** + * Imports + */ + +import { completeProject } from 'pages/Game/middleware/codeRunMiddleware' +import ConfirmDelete from 'components/ConfirmDelete' +import { component, element } from 'vdux' +import BarButton from './BarButton' +import { Block } from 'vdux-ui' + +/** + * + */ + +export default component({ + render ({ props, actions, context }) { + const { inputType, startOver, canAutoComplete, saveRef, ...rest } = props + + const deleteModal = ( + + ) + + const completeModal = ( + + ) + + return ( + + deleteModal)}> + Reset + + {inputType === 'code' && ( + + )} + {!canAutoComplete && + saveRef && ( + completeModal)} /> + )} + + ) + }, + controller: { + * print () { + yield window.print() + } + } +}) diff --git a/pool/shard007/JavaScript/0044291_shinryou-add-form.js b/pool/shard007/JavaScript/0044291_shinryou-add-form.js new file mode 100644 index 0000000000000000000000000000000000000000..6c3f43b7c05a7ba64e2649019171e972269b7ffe --- /dev/null +++ b/pool/shard007/JavaScript/0044291_shinryou-add-form.js @@ -0,0 +1,138 @@ +"use strict"; + +var $ = require("jquery"); +var hogan = require("hogan.js"); +var task = require("../task"); +var service = require("myclinic-service-api"); + +var tmplSrc = require("raw!./shinryou-add-form.html"); +var resultTmplSrc = require("raw!./shinryou-add-form-search-result.html"); +var resultTmpl = hogan.compile(resultTmplSrc); + +exports.create = function(visitId, at){ + var dom = $(tmplSrc); + var ctx = {shinryoucode: undefined}; + bindEnter(dom, visitId, at, ctx); + bindCancel(dom); + bindSearch(dom, at); + bindResult(dom, at, ctx); + return dom; +} + +var dispNameSelector = "> div[mc-name=disp-area] [mc-name=name]"; +var enterSelector = "> .workarea-commandbox [mc-name=enter]"; +var cancelSelector = "> .workarea-commandbox [mc-name=close]"; +var searchTextInputSelector = "> form[mc-name=search-form] input[mc-name=text]"; +var searchResultSelector = "> form[mc-name=search-form] select"; + +function updateDisp(dom, label){ + dom.find(dispNameSelector).text(label); +} + +function bindEnter(dom, visitId, at, ctx){ + dom.on("click", enterSelector, function(event){ + event.preventDefault(); + event.stopPropagation(); + var shinryoucode = ctx.shinryoucode; + if( !shinryoucode ){ + alert("診療行為が指定されていません。"); + return; + } + shinryoucode = +shinryoucode; + var newShinryouId, newShinryou; + task.run([ + function(done){ + service.batchEnterShinryou([{ + visit_id: visitId, + shinryoucode: shinryoucode + }], function(err, result){ + if( err ){ + done(err); + return; + } + newShinryouId = result; + done(); + }) + }, + function(done){ + service.getFullShinryou(newShinryouId, at, function(err, result){ + if( err ){ + done(err); + return; + } + newShinryou = result; + done(); + }) + } + ], function(err){ + if( err ){ + alert(err); + return; + } + dom.trigger("shinryou-entered", [newShinryou]); + }); + }) +} + +function bindCancel(dom){ + dom.on("click", cancelSelector, function(event){ + event.preventDefault(); + event.stopPropagation(); + dom.trigger("cancel"); + }); +} + +function bindSearch(dom, at){ + dom.on("submit", "> form[mc-name=search-form]", function(event){ + event.preventDefault(); + event.stopPropagation(); + var text = dom.find(searchTextInputSelector).val().trim(); + if( text === "" ){ + return; + } + var list; + task.run(function(done){ + service.searchShinryouMaster(text, at, function(err, result){ + if( err ){ + done(err); + return; + } + list = result; + done(); + }); + }, function(err){ + if( err ){ + alert(err); + return; + } + var select = dom.find(searchResultSelector); + select.html(resultTmpl.render({list: list})); + }); + }); +} + +function bindResult(dom, at, ctx){ + dom.on("change", searchResultSelector, function(event){ + var shinryoucode = +dom.find(searchResultSelector + " option:selected").val(); + var master; + task.run([ + function(done){ + service.resolveShinryouMasterAt(shinryoucode, at, function(err, result){ + if( err ){ + done(err); + return; + } + master = result; + done(); + }) + } + ], function(err){ + if( err ){ + alert(err); + return; + } + ctx.shinryoucode = master.shinryoucode; + updateDisp(dom, master.name); + }) + }); +} diff --git a/pool/shard007/JavaScript/0044293_SampleDetailsTab.js b/pool/shard007/JavaScript/0044293_SampleDetailsTab.js new file mode 100644 index 0000000000000000000000000000000000000000..e0e0179fdc95c95df7bf10c53052b1966d0d5cb6 --- /dev/null +++ b/pool/shard007/JavaScript/0044293_SampleDetailsTab.js @@ -0,0 +1,72 @@ +import React, {Component} from 'react'; +import {Badge,Button, ButtonGroup, ButtonToolbar, ListGroup, ListGroupItem, Glyphicon} from 'react-bootstrap'; +import ScifiStore from './stores/ScifiStore'; +import ScifiQueryButton from './ScifiQueryButton'; +import ScifiLinkButton from './ScifiLinkButton'; +import ElementStore from 'components/stores/ElementStore'; +import ElementActions from 'components/actions/ElementActions'; + + +import SVG from 'react-inlinesvg'; +import classnames from 'classnames'; + +export default class SampleDetailsTabHook extends Component { + + constructor(props) { + super(props) + const scifiStoreState = ScifiStore.getState() + this.state = scifiStoreState + + this.onChange = this.onChange.bind(this) + } + + componentDidMount() { + ScifiStore.listen(this.onChange); + } + + componentWillUnmount() { + ScifiStore.unlisten(this.onChange); + } + + onChange(state) { + this.setState(state); + } + + scifiAnswer(l){ + window.open(l,'_parent'); + } + scifiFrame(link){ + return ( + + ) + } + + + + render() { + let sample = this.props.sample; + let links = this.state.links; + let lastLink = this.state.lastLink || {}; + if ( lastLink.elementId != this.props.sample.id){ lastLink= {};} + return ( +
+
+ + + + + + + +
+
Search History
+ {links.map((l,i)=>) } +
+ ) + } + +} diff --git a/pool/shard007/JavaScript/0044299_sketch.js b/pool/shard007/JavaScript/0044299_sketch.js new file mode 100644 index 0000000000000000000000000000000000000000..56e7c8dfe519171585c7f5672280cfd2cb1bc28a --- /dev/null +++ b/pool/shard007/JavaScript/0044299_sketch.js @@ -0,0 +1,174 @@ + +var im; +var ready = false; +var pieces = []; +var meanColor; +var show = false; +var hermanos = 'images/hermanos.jpg'; + +function setup() { + createCanvas(windowWidth, windowHeight); + //im = loadImage('images/hermanos.jpg', loaded); + //im = loadImage('https://scontent-cdg2-1.xx.fbcdn.net/v/t1.0-9/16473968_1277453392340029_6588372641926006912_n.jpg?oh=0895e81e086f6ecfca867abd7a63d4de&oe=592BE244', loaded); + im = loadImage(hermanos, loaded, failed); + //im = loadImage('https://scontent-cdg2-1.xx.fbcdn.net/v/t31.0-8/12362941_10208211930159729_8239618902904417179_o.jpg?oh=5503faae5f0fb3bf6c4f78ea08cd8140&oe=5933FA6B', loaded); + +//https://scontent-cdg2-1.xx.fbcdn.net/v/t1.0-9/12109188_10156658910950517_1464731762818033736_n.jpg?oh=272dc715904a1f38b99a0f279e949bd1&oe=596A531E +} + + +function loaded() { + im.resize(0, 600); + im.loadPixels(); + resizeCanvas(im.width, im.height) + // var d = 0.95 * min(width, height); + var piece = new Piece(0, 0, width+1, height+1); + pieces.push(piece); + meanColor = piece.color; + ready = true; + clear(); + piece.draw(); +} + + +function failed() { + print('Failed! Trying', hermanos) + im = loadImage(hermanos, loaded); +} + + +function draw() { + if (!ready) { + background( + noise(frameCount / 100)*255, + noise(frameCount / 100 + 1000)*255, + noise(frameCount / 100 + 2000)*255) + return; + } + if (show) { + print('showing') + image(im, 0, 0); + } else { + update(); + } +} + + +function update() { + if (mouseX == 0) {return;} + var onePiece; + for (var i = 0; i < pieces.length; i++) { + onePiece = pieces[i]; + if (onePiece.mouseOver() && onePiece.canDivide()) { + var newPieces = onePiece.divide(); + pieces.splice(i, 1); + pieces = pieces.concat(newPieces); + clear(); + showAll(); + break; + } + } +} + + +function showAll() { + clear(); + for (var i = 0; i < pieces.length; i++) { + pieces[i].draw(); + } +} + + +function Piece(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.image = im.get(this.x, this.y, this.width, this.height); + if(this.image.length == 4) { // one pixel only + this.pixels = this.image + } else { + this.image.loadPixels(); + this.pixels = this.image.pixels; + } + this.color = getMeanColor(this.pixels); + + this.draw = function() { + stroke(this.color); + fill(this.color); + ellipse( + this.x + (width-2)/2, + this.y + (height-2)/2, + this.width, + this.height); + } + + this.mouseOver = function() { + var center = createVector(this.x + this.width/2, this.y + this.height/2); + var d = this.width; + return dist(mouseX, mouseY, center.x, center.y) < d/2; + } + + this.divide = function() { + var newPieces = [] + var minSize = 10; + if (this.height < 2) { // Split vertically + newPieces.push(new Piece( + this.x, this.y, this.width/2, this.height)); + newPieces.push(new Piece( + this.x + this.width/2, this.y, this.width/2, this.height)); + } + else if (this.width < 2) { // Split horizontally + newPieces.push(new Piece( + this.x, this.y, this.width, this.height/2)); + newPieces.push(new Piece( + this.x, this.y + this.height/2, this.width, this.height/2)); + } + else { // Split in 4 + newPieces.push(new Piece( + this.x, this.y, this.width/2, this.height/2)); + newPieces.push(new Piece( + this.x + this.width/2, this.y, this.width/2, this.height/2)); + newPieces.push(new Piece( + this.x, this.y + this.height/2, this.width/2, this.height/2)); + newPieces.push(new Piece( + this.x + this.width/2, this.y + this.height/2, this.width/2, this.height/2)); + } + return newPieces; + } + + this.canDivide = function() { + return this.width >= 2 || this.height >= 2; + } +} + + +function getMeanColor(pixels) { + var r = []; + var g = []; + var b = []; + for(var i = 0; i < pixels.length; i += 4) { + if(pixels[i+3] === 0) continue; + r.push(pixels[i]); + g.push(pixels[i+1]); + b.push(pixels[i+2]); + } + return color(mean(r), mean(g), mean(b)); +} + + +function mean(arr) { + return arr.reduce(function(a, b) { return a + b; }) / arr.length; +} + + +function keyPressed() { + if (key == 's' || key == 'S') { + show = true; + } +} + +function keyReleased() { + show = false; + showAll(); +} diff --git a/pool/shard007/JavaScript/0044300_ui.js b/pool/shard007/JavaScript/0044300_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..7ca5485b1fce13b8d4867674d0a8fcc4727bb48a --- /dev/null +++ b/pool/shard007/JavaScript/0044300_ui.js @@ -0,0 +1,135 @@ +'use strict' + +var units = require('./units') +var $ = window.jQuery + +/** + * User interface module + * @module + * @name ui + * @description A module to provide configured ui elements to the plugin + */ + +module.exports = { + jQuery: $, + lockNode: lockNode, + unlockNode: unlockNode, + addUnselectableCSSClass: addUnselectableCSSClass, + resetMenuItemState: resetMenuItemState, + autoAddMenuItems: autoAddMenuItems, + mapMceLayoutElements: mapMceLayoutElements, + mapPageLayoutElements: mapPageLayoutElements, + getElementHeight: getElementHeight +} + +/** + * Lock a node + * @method + * @mixin + * @returns {undefined} + */ +function lockNode () { + var $this = $(this) + $this.attr('contenteditable', false) + $this.addClass('unselectable') +} + +/** + * Unlock a node + * @method + * @mixin + * @returns {undefined} + */ +function unlockNode () { + var $this = $(this) + $this.attr('contenteditable', true) + $this.removeClass('unselectable') + $this.focus() +} + +/** + * Create and apply the unselectable CSS class to the active document + * @method + * @static + * @param {Editor} editor The tinymce active editor + * @returns {undefined} + */ +function addUnselectableCSSClass (editor) { + var head = $('head', editor.getDoc()) + var unselectableCSSRules = '.unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }' + var style = $(' +
+ ) +} + +export default RandomImage diff --git a/pool/shard007/JavaScript/0044757_thermo.js b/pool/shard007/JavaScript/0044757_thermo.js new file mode 100644 index 0000000000000000000000000000000000000000..004e48fb79579827dd509f9742ad1fc1e48decf2 --- /dev/null +++ b/pool/shard007/JavaScript/0044757_thermo.js @@ -0,0 +1,70 @@ +/*********************************************/ +/* Simple Thermometer */ +/* */ +/* Press button once. If temperature is 25C */ +/* then the RED LED will flash twice and the */ +/* GREEN LED will flash 5 times. */ +/* If temperature is -25C the BLUE LED will */ +/* flash once, the RED LED will flash twice */ +/* and the GREEN LED will flash 5 times. */ +/*********************************************/ + +function flashRED() { + digitalWrite(LED1, 1); + setTimeout(function() { + digitalWrite(LED1,0); + }, 100); +} + +function flashGREEN() { + digitalWrite(LED2, 1); + setTimeout(function() { + digitalWrite(LED2,0); + }, 100); +} + +function flashBLUE() { + digitalWrite(LED3, 1); + setTimeout(function() { + digitalWrite(LED3,0); + }, 100); +} + +var digits = [0, 0]; +var negative = false; +setInterval(function() { + if(digitalRead(BTN)) { + temp = E.getTemperature(); + console.log("temperature: " + temp); + /* check if negative temp exists */ + negative = temp<0 || false; + temp = Math.abs(temp); + /* temp range -99 to +99 */ + if(temp>=100) temp = 99; + digits = parseInt(temp).toString(10).split("").map(Number); + /* always make sure the `digits` array is of length 2 */ + if(digits.length===1) { + digits.unshift(0); + } + console.log(digits); + } + + if(negative) { + console.log("flashBLUE"); + flashBLUE(); + negative = false; + } else { + if(digits[0]>0) { + console.log("flashRED"); + flashRED(); + } + if(digits[0] <= 0) { + if(digits[1]>0) { + console.log("flashGREEN"); + flashGREEN(); + digits[1]--; + } + } + digits[0]--; + } +}, 800); diff --git a/pool/shard007/JavaScript/0044759_file.js b/pool/shard007/JavaScript/0044759_file.js new file mode 100644 index 0000000000000000000000000000000000000000..d163949a03fb7cc6808d0b196aa07194ed89d9e8 --- /dev/null +++ b/pool/shard007/JavaScript/0044759_file.js @@ -0,0 +1,180 @@ +// Generated by CoffeeScript 1.10.0 +var File, Photo, async, download, fileByPage, fs, log, onThumbCreation, thumbHelpers; + +File = require('../models/file'); + +Photo = require('../models/photo'); + +async = require('async'); + +fs = require('fs'); + +thumbHelpers = require('../helpers/thumb'); + +log = require('printit')({ + date: true, + prefix: "file" +}); + +onThumbCreation = require('../helpers/initializer').onThumbCreation; + +fileByPage = 5 * 12; + +module.exports.fetch = function(req, res, next, id) { + if (id.indexOf('.jpg') > 0) { + id = id.substring(0, id.length - 4); + } + return File.find(id, function(err, file) { + if (err) { + return next(err); + } else if (!file) { + err = new Error("File " + id + " not found"); + err.status = 404; + return next(err); + } else { + req.file = file; + return next(); + } + }); +}; + +module.exports.list = function(req, res, next) { + var dates, options, skip; + if (req.params.page != null) { + skip = parseInt(req.params.page) * fileByPage; + } else { + skip = 0; + } + dates = {}; + options = { + limit: fileByPage + 1, + skip: skip, + descending: true + }; + return File.imageByDate(options, function(err, photos) { + var date, hasNext, i, len, mounth, photo; + if (err) { + return next(err); + } + if (photos.length === fileByPage + 1) { + hasNext = true; + } else { + hasNext = false; + } + photos.splice(fileByPage, 1); + for (i = 0, len = photos.length; i < len; i++) { + photo = photos[i]; + date = new Date(photo.lastModification); + mounth = date.getMonth() + 1; + mounth = mounth > 9 ? "" + mounth : "0" + mounth; + date = (date.getFullYear()) + "-" + mounth; + if (dates[date] != null) { + dates[date].push(photo); + } else { + dates[date] = [photo]; + } + } + return res.send({ + files: dates, + hasNext: hasNext + }); + }); +}; + +module.exports.thumb = function(req, res, next) { + var stream, which; + if (res.connection && !res.connection.destroyed) { + which = req.file.binary.thumb ? 'thumb' : 'file'; + stream = req.file.getBinary(which, function(err) { + if (err) { + return next(err); + } + }); + stream.pipe(res); + return res.on('close', function() { + return stream.abort(); + }); + } +}; + +download = function(res, file, rawFile, callback) { + var stream; + if (res.connection && !res.connection.destroyed) { + fs.openSync(rawFile, 'w'); + stream = file.getBinary('file', callback); + stream.pipe(fs.createWriteStream(rawFile)); + return res.on('close', function() { + return stream.abort(); + }); + } +}; + +module.exports.createPhoto = function(req, res, next) { + var file, photo; + file = req.file; + if (file.binary == null) { + return next(new Error('no binary')); + } + photo = { + date: file.lastModification, + title: "", + description: "", + orientation: 1, + albumid: "" + req.body.albumid, + binary: file.binary + }; + return Photo.create(photo, function(err, photo) { + var rawFile, ref; + if (err != null) { + log.error("Error creating photo from file " + file.id); + log.raw(err); + return next(err); + } + if ((((ref = photo.binary) != null ? ref.thumb : void 0) != null) && (photo.binary.screen != null)) { + return res.status(201).send(photo); + } else { + rawFile = "/tmp/" + photo.id; + return download(res, file, rawFile, function(err) { + if (err != null) { + log.error("Error downloading photo from file " + file.id); + log.raw(err); + return fs.unlink(rawfile(function() { + return next(err); + })); + } else { + if (photo.binary.thumb == null) { + return thumbHelpers.resize(rawFile, photo, 'thumb', function(err) { + if (err != null) { + log.error("Error resizing thumb " + photo.id); + log.raw(err); + return fs.unlink(rawfile(function() { + return next(err); + })); + } else { + return thumbHelpers.resize(rawFile, photo, 'screen', function(err) { + if (err != null) { + log.error("Error resizing screen " + photo.id); + log.raw(err); + } + return fs.unlink(rawFile, function() { + return res.status(201).send(photo); + }); + }); + } + }); + } else if (photo.binary.screen == null) { + return thumbHelpers.resize(rawFile, photo, 'screen', function(err) { + if (err != null) { + log.error("Error resizing screen " + photo.id); + log.raw(err); + } + return fs.unlink(rawFile, function() { + return res.status(201).send(photo); + }); + }); + } + } + }); + } + }); +}; diff --git a/pool/shard007/JavaScript/0044760_backend.js b/pool/shard007/JavaScript/0044760_backend.js new file mode 100644 index 0000000000000000000000000000000000000000..7b355aac97f7adf713368d417886fde304afdcad --- /dev/null +++ b/pool/shard007/JavaScript/0044760_backend.js @@ -0,0 +1,319 @@ +/* Documentation for the todoist api is at: https://todoist.com/API + * + * This file implements all the necessary API calls. + */ + +Qt.include("ajax.js"); + +var api_url = "https://todoist.com/API"; +var api_token = ""; + +var colors = [ + "#bde876", + "#ff8581", + "#ffc472", + "#faed75", + "#a8c9e5", + "#999999", + "#e3a8e5", + "#dddddd", + "#fc603c", + "#ffcc00", + "#74e8d4", + "#3cd6fc" + ]; + +function login(data, success, error) { + + var url = api_url + "/login"; + var data_string = "email=" + data.email + + "&password=" + data.password; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function getTimezones(success, error) { + + var url = api_url + "/getTimezones"; + + ajax(url, { + type: "GET", + success: success, + error: error + }); + +} + +function register(data, success, error) { + + var url = api_url + "/register"; + + ajax(url, { + type: "POST", + data: "email=" + encodeURIComponent(data.email) + + "&full_name=" + encodeURIComponent(data.full_name) + + "&password=" + encodeURIComponent(data.password) + + "&timezone=" + encodeURIComponent(data.timezone), + success: success, + error: error + }); + +} + +function updateUser() {} + +function getProjects(data, success, error) { + + var url = api_url + "/getProjects"; + var data_string = "token=" + data.token; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function getProject() {} + +function addProject(data, success, error) { + + var url = api_url + "/addProject"; + var data_string = "token=" + data.token + + "&name=" + data.name; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function updateProject(data, success, error) { + + var url = api_url + "/updateProject"; + var data_string = "token=" + data.token + + "&project_id=" + data.project_id + + "&name=" + data.name + + "&color=" + data.color + + "&indent=" + data.indent; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error, + }); + +} + +function updateProjectOrders(data, success, error) { + + var url = api_url + "/updateProjectOrders"; + + ajax(url, { + type: "POST", + data: "token=" + data.token + "&item_id_list=" + data.id_list, + success: success, + error: error + }); +} + +function deleteProject(data, success, error) { + + var url = api_url + "/deleteProject"; + + ajax(url, { + type: "POST", + data: "token=" + data.token + "&project_id=" + data.project_id, + success: success, + error: error + }); + +} + +function getLabels() {} +function updateLabel() {} +function deleteLabel() {} + +function getUncompletedItems(data, success, error) { + + var url = api_url + "/getUncompletedItems"; + + ajax(url, { + type: "POST", + data: "token=" + data.token + "&project_id=" + data.project_id, + success: success, + error: error + }); +} + +function getCompletedItems(data, success, error) { + + var url = api_url + "/getCompletedItems"; + + ajax(url, { + type: "POST", + data: "token=" + data.token + "&project_id=" + data.project_id, + success: success, + error: error + }); +} + +function getItemsById() {} + +function addItem(data, success, error) { + + var url = api_url + "/addItem"; + var data_string = "token=" + data.token + + "&project_id=" + data.project_id + + "&content=" + encodeURIComponent(data.content); + + if(data.date_string) { + data_string += "&date_string=" + encodeURIComponent(data.date_string); + } + + if(data.priority) { + data_string += "&priority=" + data.priority; + } + + if(data.js_date) { + data_string += "&js_date=" + data.js_date; + } + + // TODO: Ask for support for this in the backend + //if(data.indent) { + // data_string += "&indent=" + data.indent + //} + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function updateItem(data, success, error) { + + var url = api_url + "/updateItem"; + + var data_string = "token=" + data.token + "&id=" + data.id; + + if(data.content) { + data_string += "&content=" + data.content; + } + + if(data.date_string) { + data_string += "&date_string=" + data.date_string; + } + + if(data.priority) { + data_string += "&priority=" + data.priority; + } + + if(data.indent) { + data_string += "&indent=" + data.indent; + } + + if(data.item_order) { + data_string += "&item_order=" + data.item_order; + } + + if(data.collapsed) { + data_string += "&collapsed=" + data.collapsed; + } + + if(data.js_date) { + } + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function updateOrders(data, success, error) { + + var url = api_url + "/updateOrders"; + var data_string = "token=" + data.token + + "&project_id=" + data.project_id + + "&item_id_list=" + data.item_id_list; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function moveItems() {} +function updateRecurringDate() {} + +function deleteItems(data, success, error) { + + var url = api_url + "/deleteItems"; + + var data_string = "token=" + data.token + + "&project_id=" + data.project_id + + "&ids=" + data.ids; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function completeItems(data, success, error) { + + var url = api_url + "/completeItems"; + var data_string = "token=" + data.token + + "&ids=" + data.ids; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function uncompleteItems(data, success, error) { + + var url = api_url + "/uncompleteItems"; + var data_string = "token=" + data.token + + "&ids=" + data.ids; + + ajax(url, { + type: "POST", + data: data_string, + success: success, + error: error + }); + +} + +function addNote() {} +function deleteNote() {} +function getNotes() {} +function query() {} diff --git a/pool/shard007/JavaScript/0044761_group-form.spec.js b/pool/shard007/JavaScript/0044761_group-form.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..22aa0577c495f313881e9f41e6933bc22d399945 --- /dev/null +++ b/pool/shard007/JavaScript/0044761_group-form.spec.js @@ -0,0 +1,184 @@ +/** +* # Group form functional testing +* +* ## License +* +* 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. +* +*/ + +module.exports = (function () { + 'use strict'; + // Dependencies + var common = require('./common.js'); + var fill = common.helper.fill; + + var form = {}; + + // Shared variables + var $el; + var first; + + form.run = function (app) { + + first = function (sel) { return app.document.querySelector(sel); }; + + describe('group form module testing', function () { + + beforeAll(function (done) { + // Login and go to form add page + app.document.querySelector('header nav a:first-child').click(); + window.setTimeout(function () { + fill(app.document.querySelector('input[name=login]'), 'parker'); + fill(app.document.querySelector('input[name=password]'), + 'lovesKubiak'); + app.document.querySelector('input[type=submit]').click(); + window.setTimeout(function () { + app.document.querySelector('a[href$=\'mypads/group/add\']').click(); + window.setTimeout(function () { + $el = { + form: first('form'), + name: first('input[name=name]'), + description: first('textarea[name=description]'), + visibility: first('select[name=visibility]'), + readonly: first('input[name=readonly]'), + submit: first('input[type=submit]') + }; + first('body > section > div p').click(); + window.setTimeout(done, 100); + }, 200); + }, 200); + }, 200); + }); + + afterAll(function (done) { + first('.icon-logout').parentNode.click(); + window.setTimeout(function () { + first('body > section p').click(); + done(); + }, 100); + }); + + describe('group creation', function () { + + it('should forbid creation of a group with no fill', function (done) { + $el.submit.click(); + expect($el.form.checkValidity()).toBeFalsy(); + expect($el.name.checkValidity()).toBeFalsy(); + expect($el.description.checkValidity()).toBeTruthy(); + expect($el.visibility.checkValidity()).toBeTruthy(); + expect($el.visibility.value).toBe('restricted'); + expect($el.readonly.checkValidity()).toBeTruthy(); + done(); + }); + + it('should forbid creation of a private group with no password', + function (done) { + fill($el.name, 'High School Memories'); + $el.visibility.value = 'private'; + $el.visibility.onchange($el.visibility); + window.setTimeout(function () { + expect($el.name.checkValidity()).toBeTruthy(); + expect($el.visibility.value).toBe('private'); + $el.password = first('input[type=password]'); + $el.password.value = ''; + $el.submit.click(); + expect($el.form.checkValidity()).toBeFalsy(); + expect($el.password.checkValidity()).toBeFalsy(); + done(); + }, 100); + } + ); + + it('should create otherwise', function (done) { + fill($el.password, 'WatchSyncing'); + $el.readonly.checked = false; + $el.readonly.onchange($el.readonly); + window.setTimeout(function () { + $el.submit.click(); + window.setTimeout(function () { + var $notif = first('body > section p'); + expect($notif.innerHTML) + .toMatch('Group has been successfully created'); + $notif.click(); + window.setTimeout(done, 100); + }, 200); + }, 200); + }); + + }); + + describe('group edition', function () { + + beforeEach(function (done) { + app.document.querySelector('a[title=Configuration]').click(); + window.setTimeout(function () { + $el = { + form: first('form'), + name: first('input[name=name]'), + description: first('textarea[name=description]'), + visibility: first('select[name=visibility]'), + password: first('input[type=password]'), + readonly: first('input[name=readonly]'), + submit: first('input[type=submit]') + }; + window.setTimeout(done, 200); + }, 200); + }); + + it('should accept changes and letting password empty', function (done) { + expect($el.name.value).toBe('High School Memories'); + expect($el.visibility.value).toBe('private'); + expect($el.readonly.checked).toBeFalsy(); + expect($el.password.value).toBe(''); + fill($el.name, 'High School Memories, again'); + fill($el.description, 'Something quite private.'); + $el.description.onchange($el.description); + window.setTimeout(function () { + $el.submit.click(); + window.setTimeout(function () { + var $notif = first('body > section p'); + expect($notif.innerHTML) + .toMatch('Group has been successfully updated'); + $notif.click(); + window.setTimeout(done, 100); + }, 200); + }, 200); + }); + + it('should accept changes and setting a new password', function (done) { + expect($el.name.value).toBe('High School Memories, again'); + expect($el.description.value).toBe('Something quite private.'); + $el.password.value = 'aNewPassWord'; + $el.submit.click(); + window.setTimeout(function () { + var $notif = first('body > section p'); + expect($notif.innerHTML) + .toMatch('Group has been successfully updated'); + $notif.click(); + window.setTimeout(done, 100); + }, 200); + }); + + }); + + }); + }; + + return form; +}).call(this); diff --git a/pool/shard007/JavaScript/0044771_getting-started.js b/pool/shard007/JavaScript/0044771_getting-started.js new file mode 100644 index 0000000000000000000000000000000000000000..276a44cda137ee1c31726670902a6883310c18d7 --- /dev/null +++ b/pool/shard007/JavaScript/0044771_getting-started.js @@ -0,0 +1,79 @@ +import modal from '../utils/modal'; +import app_state from '../utils/app_state'; +import { computed } from '@ember/object'; + +export default modal.ModalController.extend({ + intro_status_class: computed('model.progress.intro_watched', function() { + var res = "glyphicon "; + if(this.get('model.progress.intro_watched')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-book "; + } + return res; + }), + home_status_class: computed('model.progress.home_board_set', function() { + var res = "glyphicon "; + if(this.get('model.progress.home_board_set')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-home "; + } + return res; + }), + app_status_class: computed('model.progress.app_added', function() { + var res = "glyphicon "; + if(this.get('model.progress.app_added')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-phone "; + } + return res; + }), + preferences_status_class: computed('model.progress.preferences_edited', function() { + var res = "glyphicon "; + if(this.get('model.progress.preferences_edited')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-cog "; + } + return res; + }), + profile_status_class: computed('model.progress.profile_edited', function() { + var res = "glyphicon "; + if(this.get('model.progress.profile_edited')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-user "; + } + return res; + }), + subscription_status_class: computed('model.progress.subscription_set', function() { + var res = "glyphicon "; + if(this.get('model.progress.subscription_set')) { + res = res + "glyphicon-ok "; + } else { + res = res + "glyphicon-usd "; + } + return res; + }), + actions: { + intro: function() { + if(window.ga) { + window.ga('send', 'event', 'Setup', 'launch', 'Setup started'); + } + app_state.set('auto_setup', false); + this.transitionToRoute('setup'); + modal.close(); + }, + app_install: function() { + modal.open('add-app'); + }, + setup_done: function() { + var user = app_state.get('currentUser'); + user.set('preferences.progress.setup_done', true); + user.save().then(null, function() { }); + modal.close(); + } + } +}); diff --git a/pool/shard007/JavaScript/0044772_new.js b/pool/shard007/JavaScript/0044772_new.js new file mode 100644 index 0000000000000000000000000000000000000000..3d0c61777a63d0c6b8149ea9bf52276712f957b0 --- /dev/null +++ b/pool/shard007/JavaScript/0044772_new.js @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) + * + * openAUSIAS: The stunning micro-library that helps you to develop easily + * AJAX web applications by using Java and jQuery + * openAUSIAS is distributed under the MIT License (MIT) + * Sources at https://github.com/rafaelaznar/ + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +'use strict'; +moduloDocumento.controller('DocumentoNewController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService', '$filter', + function ($scope, $routeParams, $location, serverService, sharedSpaceService, $filter) { + + $scope.ob = 'documento'; + $scope.op = 'new'; + + $scope.title = "Edición de documento"; + $scope.icon = "fa-file-text-o"; + + $scope.result = null; + + $scope.obj = {}; + $scope.obj.obj_tipodocumento = {"id": 0}; + $scope.obj.obj_usuario = {"id": 0}; + + if (sharedSpaceService.getFase() == 0) { + if ($routeParams.tipodocumento && $routeParams.tipodocumento > 0) { + $scope.obj.obj_tipodocumento.id = $routeParams.tipodocumento; + } + if ($routeParams.usuario && $routeParams.usuario > 0) { + $scope.obj.obj_usuario.id = $routeParams.usuario; + } + } else { + $scope.obj = sharedSpaceService.getObject(); + sharedSpaceService.setFase(0); + } + + $scope.chooseOne = function (foreignObjectName) { + sharedSpaceService.setObject($scope.obj); + sharedSpaceService.setReturnLink('/' + $scope.ob + '/' + $scope.op); + sharedSpaceService.setFase(1); + $location.path('/' + foreignObjectName + '/selection/1/10'); + } + + $scope.save = function () { + var dateAltaAsString = $filter('date')($scope.obj.alta, "dd/MM/yyyy"); + var dateCambioAsString = $filter('date')($scope.obj.cambio, "dd/MM/yyyy"); + $scope.obj.alta = dateAltaAsString; + $scope.obj.cambio = dateCambioAsString; + //console.log({json: JSON.stringify(serverService.array_identificarArray($scope.obj))}); + serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) { + $scope.result = data; + }); + }; + + $scope.$watch('obj.obj_tipodocumento.id', function () { + if ($scope.obj) { + serverService.getDataFromPromise(serverService.promise_getOne('tipodocumento', $scope.obj.obj_tipodocumento.id)).then(function (data2) { + $scope.obj.obj_tipodocumento = data2.message; + }); + } + }); + $scope.$watch('obj.obj_usuario.id', function () { + if ($scope.obj) { + serverService.getDataFromPromise(serverService.promise_getOne('usuario', $scope.obj.obj_usuario.id)).then(function (data2) { + $scope.obj.obj_usuario = data2.message; + }); + } + }); + + $scope.back = function () { + window.history.back(); + }; + $scope.close = function () { + $location.path('/home'); + }; + $scope.plist = function () { + $location.path('/documento/plist'); + }; + + + //datepicker + $scope.open1 = function () { + $scope.popup1.opened = true; + }; + $scope.popup1 = { + opened: false + }; + $scope.disabled = function (date, mode) { + return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6); + }; + $scope.dateOptions = { + formatYear: 'yyyy', + startingDay: 1 + }; + $scope.open2 = function () { + $scope.popup2.opened = true; + }; + $scope.popup2 = { + opened: false + }; + }]); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044777_test.js b/pool/shard007/JavaScript/0044777_test.js new file mode 100644 index 0000000000000000000000000000000000000000..cd77ab61206b233778489e3fc4dbc7da77e8cbec --- /dev/null +++ b/pool/shard007/JavaScript/0044777_test.js @@ -0,0 +1,144 @@ +var chai = require('chai'), + assert = require('chai').assert, + expect = require('chai').expect, + scv = require('../scv.js'), + chaihttp = require('chai-http'), + should = chai.should(), + config = require('../../config.js'), + effector = require('../helper/effectors.js'), + server = require('../../app.js'); + +chai.use(chaihttp); + + +describe('Initial test', function () { + it('1+1 should be 2', function () { + assert.equal(1 + 1, 2, 'The answer should be 2') + }); + + it('Scv should respond', function () { + var result = scv.hello(); + expect(result).to.be.not.null; + }); + + it('Scv should respond whats going on? scv ready.', function () { + var result = scv.hello(); + assert.equal(result, "What's going on? SCV ready.", "Should say What's going on? SCV ready."); + }); +}); + +describe('Ensure config file is valid', function () { + it('Config file should be populated', function () { + expect(config).to.be.not.null; + }); + + it('Check config.scv', function () { + expect(config.scv).to.be.not.null; + }); + + it('Check config.facebook', function () { + expect(config.scv).to.be.not.null; + }); +}); + +describe('Helper effectors.js (isAscii)', function () { + it('Verify string (whats 1+1) is ascii', function () { + var input = "what's 1+1"; + var result = effector.isAscii(input); + assert.isTrue(result); + }); + + it('Verify string (嗨,我喜歡藍色的顏色) is NOT ascii', function () { + var input = "嗨,我喜歡藍色的顏色"; + var result = effector.isAscii(input); + assert.isFalse(result); + }); + + it('Verify string (Hi Unë si blu ngjyra) is NOT ascii', function () { + var input = "Hi Unë si blu ngjyra"; + var result = effector.isAscii(input); + assert.isFalse(result); + }); + + it('Verify string (Привет мне нравится синий цвет) is NOT ascii', function () { + var input = "Привет мне нравится синий цвет"; + var result = effector.isAscii(input); + assert.isFalse(result); + }); +}); + +describe('Helper effectors.js (getEquation)', function () { + it('whats 1+1 returns 1+1', function () { + var input = "what's 1+1"; + var result = effector.getEquation(input); + assert.equal(result, "1+1"); + }); + + it('Can you tell me what is 3*1+4-6 returns 3*1+4-6', function () { + var input = "Can you tell me what is 3*1+4-6"; + var result = effector.getEquation(input); + assert.equal(result, "3*1+4-6"); + }); + + it('Can you tell me what is (1+2)*6/2 please? return (1+2)*6/2', function () { + var input = "Can you tell me what is (1+2)*6/2 please?"; + var result = effector.getEquation(input); + assert.equal(result, "(1+2)*6/2"); + }); + + it('', function () { + var input = ""; + var result = effector.getEquation(input); + assert.equal(result, "()/"); + }); + + it('xss java', function () { + var input = ""; + var result = effector.getEquation(input); + assert.equal(result, "106971189711599114105112116589710810111411640398883833941"); + }); +}); + +describe('Helper effectors.js (computeAnswer)', function () { + it('(1+2)^2 should return 9', function () { + var input = "(1+2)^2"; + var result = effector.computeAnswer(input); + assert.equal(result, "9"); + }); + + it('12+60-23 should return 49', function () { + var input = "12+60-23"; + var result = effector.computeAnswer(input); + assert.equal(result, "49"); + }); + + it('(5 + 3) * 12 / 3 should return 32', function () { + var input = "(5 + 3) * 12 / 3"; + var result = effector.computeAnswer(input); + assert.equal(result, "32"); + }); + + it('1*2^2/6 should return 0.6666666666666666', function () { + var input = "1*2^2/6"; + var result = effector.computeAnswer(input); + assert.equal(result, "0.6666666666666666"); + }); + it('2*2+1*+2 should fail', function () { + var input = "2*2+1+*2"; + var result = effector.computeAnswer(input); + assert.equal(result, config.scv.error4); + }); +}); + +describe('/GET ping', function () { + it('Ping should respond with a whats going on? scv ready.', function (done) { + chai.request(server) + .get("/api/ping") + .end((err, res) => { + res.should.have.status(200); + res.should.be.a("object"); + assert.equal(res.body.response, "What's going on? SCV ready.", "Should say What's going on? SCV ready."); + done(); + }); + }); +}); diff --git a/pool/shard007/JavaScript/0044778_area.js b/pool/shard007/JavaScript/0044778_area.js new file mode 100644 index 0000000000000000000000000000000000000000..ac5e45d9d6883913dc93c7793301ee6da7a00fb7 --- /dev/null +++ b/pool/shard007/JavaScript/0044778_area.js @@ -0,0 +1,16 @@ +"use strict"; +var Area = (function () { + function Area(id, title, descriptionMain, descriptionSecondary, parking, approachTime, dateCreated, totalBoulders) { + this.Id = id; + this.Title = title; + this.DescriptionMain = descriptionMain; + this.DescriptionSecondary = descriptionSecondary; + this.Parking = parking; + this.ApproachTime = approachTime; + this.DateCreated = dateCreated; + this.TotalBoulders = totalBoulders; + } + return Area; +}()); +exports.Area = Area; +//# sourceMappingURL=area.js.map \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044782_gulpfile.js b/pool/shard007/JavaScript/0044782_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..41d4d8d184a2c6bff9722136bb5ee3a677ad7530 --- /dev/null +++ b/pool/shard007/JavaScript/0044782_gulpfile.js @@ -0,0 +1,15 @@ +var gulp = require('gulp'), + markdown = require('gulp-markdown'), + jade = require('gulp-jade'); + +gulp.task('markdown', function() { + return gulp.src('./src/pages/**/*.md') + .pipe(markdown()) + .pipe(gulp.dest('./build')); +}); + +gulp.task('jade', function() { + return gulp.src('./src/templates/**/*.jade') + .pipe(jade({pretty: true})) + .pipe(gulp.dest('./build/')); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044785_section.js b/pool/shard007/JavaScript/0044785_section.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a82bcc317b6330913a53a2179130975571c112 --- /dev/null +++ b/pool/shard007/JavaScript/0044785_section.js @@ -0,0 +1,20 @@ +define(["knockout"], function(ko) { + return function(name, template, style) { + var self = this; + this.name = name; + this.template = template || name; + this.data = ko.observable(); + this.style = style; + this.loaded = false; + this.activate = function() { + //load view model from the server + if (!this.loaded) { + require(["modules/" + name, "text!../templates/" + self.template + ".html"], function(Module, template) { + ko.templates[self.template] = template; + self.data(typeof Module === "function" ? new Module() : Module); + self.loaded = true; + }); + } + }; + }; +}); diff --git a/pool/shard007/JavaScript/0044788_Scroll.js b/pool/shard007/JavaScript/0044788_Scroll.js new file mode 100644 index 0000000000000000000000000000000000000000..cd8f7c012732fc9fe7af242936e54012e437ec6b --- /dev/null +++ b/pool/shard007/JavaScript/0044788_Scroll.js @@ -0,0 +1,95 @@ +/* ************************************************************************ + + qooxdoo - the new era of web development + + http://qooxdoo.org + + Copyright: + 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de + + License: + LGPL: http://www.gnu.org/licenses/lgpl.html + EPL: http://www.eclipse.org/org/documents/epl-v10.php + See the LICENSE file in the project's top-level directory for details. + + Authors: + * Martin Wittemann (martinwittemann) + +************************************************************************ */ +/** + * This class is responsible for checking the scrolling behavior of the client. + * + * This class is used by {@link qx.core.Environment} and should not be used + * directly. Please check its class comment for details how to use it. + * + * @internal + */ +qx.Bootstrap.define("qx.bom.client.Scroll", +{ + statics : + { + /** + * Check if the scrollbars should be positioned on top of the content. This + * is true of OSX Lion when the scrollbars disappear automatically. + * + * @internal + * + * @return {Boolean} true if the scrollbars should be + * positioned on top of the content. + */ + scrollBarOverlayed : function() { + var scrollBarWidth = qx.bom.element.Scroll.getScrollbarWidth(); + var osx = qx.bom.client.OperatingSystem.getName() === "osx"; + var nativeScrollBars = qx.core.Environment.get("qx.nativeScrollBars"); + + return scrollBarWidth === 0 && osx && nativeScrollBars; + }, + + + /** + * Checks if native scroll can be used for the current mobile device. + * + * @internal + * + * @return {Boolean} true if the current device is capable to + * use native scroll. + */ + getNativeScroll : function() + { + // iOS 8+ + if (qx.core.Environment.get("os.name") == "ios" && + parseInt(qx.core.Environment.get("browser.version"), 10) > 7) { + return true; + } + + // Firefox + if (qx.core.Environment.get("browser.name") == "firefox") { + return true; + } + + // Android 4.4+ + if (qx.core.Environment.get("os.name") == "android") + { + var osVersion = qx.core.Environment.get("os.version"); + var splitVersion = osVersion.split("."); + if (splitVersion[0] > 4 || + (splitVersion.length > 1 && splitVersion[0] > 3 && splitVersion[1] > 3)) { + return true; + } + } + + // IE 10+ + if (qx.core.Environment.get("event.mspointer")) { + return true; + } + + return false; + } + }, + + + defer : function(statics) { + qx.core.Environment.add("os.scrollBarOverlayed", statics.scrollBarOverlayed); + qx.core.Environment.add("qx.mobile.nativescroll", statics.getNativeScroll); + } +}); diff --git a/pool/shard007/JavaScript/0044794_bookyt.js b/pool/shard007/JavaScript/0044794_bookyt.js new file mode 100644 index 0000000000000000000000000000000000000000..edab6aa8e61c8ab1167f85a7b48a36e231645a1f --- /dev/null +++ b/pool/shard007/JavaScript/0044794_bookyt.js @@ -0,0 +1,240 @@ +// Application specific behaviour +function addAlternateTableBehaviour() { + $("table.list tr:odd").addClass("odd"); +} + +function addNestedFormBehaviour() { + $('body').on('click', '.delete-nested-form-item', function(event) { + var item = $(this).parents('.nested-form-item'); + // Hide item + item.hide(); + // Mark as ready to delete + item.find("input[name$='[_destroy]']").val("1"); + item.addClass('delete'); + // Drop input fields to prevent browser validation problems + item.find(":input").not("[name$='[_destroy]'], [name$='[id]']").remove(); + + // TODO: should be callbacks + updatePositions($(this).parents('.nested-form-container')); + updateLineItems(); + + // Don't follow link + event.preventDefault(); + }); +} + +// Currency helpers +function currencyRound(value) { + if (isNaN(value)) { + return 0.0; + }; + + rounded = Math.round(value * 20) / 20; + + return rounded.toFixed(2); +} + +// Line Item calculation +function updateLineItemPrice(lineItem) { + var list = lineItem.parent(); + var reference_code = lineItem.find(":input[name$='[reference_code]']").val(); + var quantity = lineItem.find(":input[name$='[quantity]']").val(); + var after_saldo_line_item = lineItem.prev().hasClass('saldo_line_item'); + var is_saldo_line_item = lineItem.hasClass('saldo_line_item'); + var is_relative_item = (quantity == '%' || quantity == 'saldo_of'); + var no_previous_saldo_line_item = (lineItem.prevAll().find('.saldo_line_item').size() === 0); + + if (is_relative_item && (after_saldo_line_item || is_saldo_line_item || no_previous_saldo_line_item)) { + var included_items; + if (reference_code == '') { + included_items = lineItem.prevAll('.line_item'); + } else { + // Should match using ~= but acts_as_taggable_adds_colons between tags + included_items = list.find(":input[name$='[code]'][value='" + reference_code + "']").parents('.line_item, .saldo_line_item'); + if (included_items.length == 0) { + // Should match using ~= but acts_as_taggable_adds_colons between tags + included_items = list.find(":input[name$='[include_in_saldo_list]'][value*='" + reference_code + "']").parents('.line_item, .saldo_line_item'); + } + } + var price_input = lineItem.find(":input[name$='[price]']"); + price_input.val(calculateTotalAmount(included_items)); + } +} + +function updateAllLineItemPrices() { + $('.line_item, .saldo_line_item').each(function() { + updateLineItemPrice($(this)); + }); +} + +function calculateLineItemTotalAmount(lineItem) { + var times_input = lineItem.find(":input[name$='[times]']"); + var times = accounting.parse(times_input.val()); + if (isNaN(times)) { + times = 1; + }; + + var quantity_input = lineItem.find(":input[name$='[quantity]']"); + var price_input = lineItem.find(":input[name$='[price]']"); + var price = accounting.parse(price_input.val()); + + // For 'saldo_of' items, we don't take accounts into account + if (quantity_input.val() == "saldo_of") { + return currencyRound(price); + }; + + var direct_account_id = $('#line_items').data('direct-account-id'); + var direct_account_factor = $('#line_items').data('direct-account-factor'); + + var factor = 0; + if (lineItem.find(":input[name$='[debit_account_id]']").val() == direct_account_id) { + factor = 1; + }; + if (lineItem.find(":input[name$='[credit_account_id]']").val() == direct_account_id) { + factor = -1; + }; + + if (quantity_input.val() == '%') { + times = times / 100; + }; + + return currencyRound(times * price * factor * direct_account_factor); +} + +function updateLineItemTotalAmount(lineItem) { + var total_amount_input = lineItem.find(".total_amount"); + var total_amount = accounting.formatNumber(calculateLineItemTotalAmount(lineItem)); + + // Update Element + total_amount_input.text(total_amount); +} + +function calculateTotalAmount(lineItems) { + var total_amount = 0; + $(lineItems).each(function() { + total_amount += accounting.parse($(this).find(".total_amount").text()); + }); + + return currencyRound(total_amount); +} + +function updateLineItems() { + if ($('#line_items').length > 0) { + $('.line_item, .saldo_line_item').each(function() { + updateLineItemPrice($(this)); + updateLineItemTotalAmount($(this)); + }); + }; +} + +// Recalculate after every key stroke +function handleLineItemChange(event) { + // If character is + if(event.keyCode == 13) { + // ...trigger form action + $(event.currentTarget).submit(); + } else if(event.keyCode == 32) { + // ...trigger form action + $(event.currentTarget).submit(); + } else { + updateLineItems(); + } +} + +function addCalculateTotalAmountBehaviour() { + $("#line_items").find(":input[name$='[times]'], :input[name$='[quantity]'], :input[name$='[price]'], input[name$='[reference_code]']").on('keyup', handleLineItemChange); + $("#line_items").bind("sortstop", handleLineItemChange); +} + +// Sorting +function updatePositions(collection) { + var items = collection.find('.nested-form-item').not('.delete'); + items.each(function(index, element) { + $(this).find("input[id$='_position']").val(index + 1) + }); +} + +// Override generic version in cyt.js +function addSortableBehaviour() { + $(".sortable").sortable({ + placeholder: "ui-state-highlight", + forcePlaceholderSize: true, + stop: function(event, ui) { + updatePositions($(this)); + } + }); + + $('.sortable').each(function() { + updatePositions($(this)); + }); +} + +function initAccounting() { + // accounting.js + // Settings object that controls default parameters for library methods: + accounting.settings = { + currency: { + symbol : "", // default currency symbol is '$' + format: "%v", // controls output: %s = symbol, %v = value/number (can be object: see below) + decimal : ".", // decimal point separator + thousand: "'", // thousands separator + precision : 2 // decimal places + }, + number: { + precision : 2, // default precision on numbers is 0 + thousand: "'", + decimal : "." + } + } +} + +// Initialize behaviours +function initializeBehaviours() { + // Init settings + initAccounting(); + + // from cyt.js + addComboboxBehaviour(); + addAutofocusBehaviour(); + addDatePickerBehaviour(); + addSortableBehaviour(); + addLinkifyContainersBehaviour(); + addIconTooltipBehaviour(); + addModalBehaviour(); + + // application + addAlternateTableBehaviour(); + addNestedFormBehaviour(); + + addCalculateTotalAmountBehaviour(); + + updateLineItems(); + + // twitter bootstrap + $(function () { + $('.tabs').tabs(); + $(".alert").alert(); + $("*[rel=popover]").popover({ + offset: 10 + }); + }) + + // select2 + $('.select2').select2({ + allowClear: true + }); + $('.select2-tags').each(function(index, element) { + var tags = $(element).data('tags') || ''; + + $(element).select2({ + tags: tags, + tokenSeparators: [","] + }) + }) + + // best_in_place + $(".best_in_place").best_in_place(); +} + +// Loads functions after DOM is ready +$(document).ready(initializeBehaviours); diff --git a/pool/shard007/JavaScript/0044797_jquery.atd.iframe.js b/pool/shard007/JavaScript/0044797_jquery.atd.iframe.js new file mode 100644 index 0000000000000000000000000000000000000000..0a8dd4afa543f27e16c9fa02bc77a172fb365768 --- /dev/null +++ b/pool/shard007/JavaScript/0044797_jquery.atd.iframe.js @@ -0,0 +1,105 @@ +function AtD_IFRAME_isExempt(nodez) { + if (typeof CKEditor !== 'undefined') + return true; + + var node = nodez.context; + + /* disable on draft.blogger.com WYSIWYG editor--too buggy */ + if (node.id == 'postingComposeBox') + return true; + + if (node.contentDocument == undefined || node.contentDocument.body == undefined) + return true; + + if (node.contentDocument.designMode == 'on' || node.contentDocument.body.designMode == 'on') + return false; + + if (node.contentDocument.body.contentEditable == 'true') + return false; + + /* hack to make editor work with Yahoo Mail immediately */ + if (/compArea/.test(node.id)) + return false; + + return true; +}; + +function AtD_IFRAME_Proofreader(container) { + var AtD = new AtD_Proofreader(container); + + AtD.setValue = function(component, value) { + return component.context.contentDocument.body.innerHTML = value; + }; + + AtD.getValue = function(component) { + return component.context.contentDocument.body.innerHTML.replace(/\ \;/g, ' '); + }; + + AtD.getCheckValue = function(component) { + return component.context.contentDocument.body.innerHTML.replace(/\ \;/g, ' ').replace(/\<\;/g, '<').replace(/\>\;/g, '>').replace(/\&\;/g, '&'); + } + + /* changing/setting scroll position is handled by the injected HTML */ + AtD.getScrollPosition = function() { + /* update the relevant iframe with an */ + if (AtD.isProofreading()) { + AtD.getOriginal().attr('AtD_scroll', AtD.getActiveComponent().scrollTop()); + } + }; + + AtD.setScrollPosition = function(value) { + /* changing the proofreading mode from proofreader -> editor */ + if (!AtD.isProofreading()) { + jQuery('body').append(""); + } + }; + + AtD.adjustWidget = function(offset) { + if (AtD.isProofreading()) { + offset.top += 4; + offset.left += 3; + } + + offset.top -= 1; + offset.left -= 1; + + /* check if there is a scrollbar, if there is, adjust accordingly */ + if (AtD.getOriginal().attr('id') == 'wys_frame') { + offset.left -= 15; /* this is a google docs hack, there is always a scrollbar */ + } + else if (AtD.isProofreading()) { + var target = AtD.getActiveComponent(); + target = target.context == undefined ? target[0] : target.context; + + if (target != undefined && target.scrollHeight > target.clientHeight) + offset.left -= 15; + } + else { + var target = AtD.getOriginal().context; + if (target.contentDocument && target.contentDocument.documentElement && (target.contentDocument.documentElement.clientHeight > target.clientHeight)) + offset.left -= 15; + } + }; + + AtD.showProofreader = function(component, proofreader) { + component.attr('AtD_active', 'true'); + AtD.displayValue = component.css('display'); + + proofreader.css('display', 'none'); + component.after(proofreader); + + jQuery('body').append(""); + }; + + AtD.createProofreader = function(contents) { + return jQuery('
' + contents + '
'); + }; + + AtD.inheritLookAndFeel = function(component, proofreader) { + /* load a script to go in like special forces and update some styles */ + return proofreader; + } + + return AtD; +}; + diff --git a/pool/shard007/JavaScript/0044798_good-old-gallery-admin.js b/pool/shard007/JavaScript/0044798_good-old-gallery-admin.js new file mode 100644 index 0000000000000000000000000000000000000000..988e4fd4b22625f9928d4eb30db5f7051587f424 --- /dev/null +++ b/pool/shard007/JavaScript/0044798_good-old-gallery-admin.js @@ -0,0 +1,148 @@ +var $j = jQuery.noConflict(); + +(function ($) { + var addFlattr, showHide, showHideSelect, shortcodeValues, shortcodeGenerator, deleteImageButton; + + // Adds the flattr button + addFlattr = function () { + var s = document.createElement('script'), + t = document.getElementsByTagName('script')[0]; + + s.type = 'text/javascript'; + s.async = true; + s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto'; + t.parentNode.insertBefore(s, t); + }; + + // Show/Hide a div + showHide = function ($div, title, alt, id) { + var $link; + + $div.hide(); + $link = $('').attr('href', '#').addClass(id).text(title).insertBefore($div); + $link.click(function (e) { + $div.slideToggle().toggleClass('open'); + if ($div.hasClass('open')) { + $link.text(alt); + } else { + $link.text(title); + } + e.preventDefault(); + }); + }; + + // Show/Hide slidet plugin info + showHideSelect = function ($select) { + var val = $select.val(); + + if (val.length) { + $('.plugin-info.' + val).show(); + } + + $select.change(function () { + val = $select.val(); + $('.plugin-info').slideUp(); + if (val.length) { + $('.plugin-info.' + val).slideDown(); + } + }); + }; + + // Retreives values for the shortcode generator + shortcodeValues = function () { + var value = ''; + + $('input[type="text"], select').each(function () { + var $this = $(this); + if ($this.val().length) { + value += ' ' + $this.attr('id') + '="' + $this.val() + '"'; + } + }); + + $('input[type="checkbox"]').each(function () { + var $this = $(this); + if ($this.is(':checked')) { + value += ' ' + $this.attr('id') + '="' + $this.val() + '"'; + } else { + value += ' ' + $this.attr('id') + '="' + $this.prev().val() + '"'; + } + }); + + $('#good-old-gallery-shortcode code').text('[good-old-gallery' + value + ']'); + value = ''; + }; + + // Shortcode generator + shortcodeGenerator = function () { + $('#go-gallery-generator input[type="checkbox"], #go-gallery-generator select').each(function () { + $this = $(this); + $this.change(shortcodeValues); + }); + + $('#go-gallery-generator input[type="text"]').each(function () { + $this = $(this); + $this.keyup(shortcodeValues); + }); + }; + + deleteImageButton = function () { + $('a.submitdelete').each(function () { + var $this = $(this).click(function () { + attID = $this.attr('data-id'); + + $.ajax({ + type: 'post', + url: 'admin-ajax.php', + data: { + action: 'delete_attachment', + att_ID: attID, + _ajax_nonce: $this.attr('data-nonce'), + post_type: 'attachment' + }, + success: function (data, textStatus, jqXHR) { + $this.parents('li').html(data).addClass('deleted'); + } + }); + + return false; + }); + }); + }; + + $(function () { + var $this, body = $('body'); + + // Shortcode generator tab + if (body.attr('id') == 'media-upload') { + shortcodeValues(); + shortcodeGenerator(); + } + + console.log(body); + deleteImageButton(); + + // Themes page + if (body.hasClass('goodoldgallery_page_gog_themes')) { + addFlattr(); + showHide($('.goodoldgallery_page_gog_themes .themes-available'), 'View installed themes', 'Hide installed themes', 'themes-link'); + } + + // Settings page + if (body.hasClass('goodoldgallery_page_gog_settings')) { + addFlattr(); + showHideSelect($('select#plugin')); + + // Make fields sortable + if ($.isFunction($.fn.sortable)) { + $('#order').sortable({ + update : function (event, ui) { + var order = $(this).sortable('toArray'); + $.each(order, function(index) { + $('#order_' + order[index]).val(index+1); + }); + } + }).next('table').hide(); + } + } + }); +}($j)); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044803_logs.js b/pool/shard007/JavaScript/0044803_logs.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f677779029c2b86f9e515dc22bf39bf9060670 --- /dev/null +++ b/pool/shard007/JavaScript/0044803_logs.js @@ -0,0 +1,34 @@ +/* @flow */ +'use strict' + +/* :: +import type { + BlinkMRCServer +} from '../types.js' +*/ + +const ora = require('ora') + +const awsRoles = require('./assume-aws-roles.js') + +function authenticate ( + config /* : BlinkMRCServer */, + blinkMobileIdentity /* : Object */, + env /* : string */ +) /* : Promise */ { + const spinner = ora('Authenticating...').start() + return blinkMobileIdentity.getAccessToken() + .then((accessToken) => awsRoles.assumeAWSRoleToViewLogs(config, env, accessToken)) + .then((results) => { + spinner.succeed('Authentication complete!') + return results + }) + .catch((err) => { + spinner.fail('Authentication failed...') + return Promise.reject(err) + }) +} + +module.exports = { + authenticate +} diff --git a/pool/shard007/JavaScript/0044804_Player.js b/pool/shard007/JavaScript/0044804_Player.js new file mode 100644 index 0000000000000000000000000000000000000000..b695e3223a6f9c6ff1f0e42560458e5df153f0f6 --- /dev/null +++ b/pool/shard007/JavaScript/0044804_Player.js @@ -0,0 +1,120 @@ +var events = require('events'); + +function Player(player, queue) { + this.player = player; + this.isPlaying = false; + this.queue = queue; + this.currentTrack = null; + + events.EventEmitter.call(this); + + queue.on("change", function () { + var newTrack = queue.getCurrentTrack() + if (newTrack != this.currentTrack) { + if (newTrack == null) { + //Queue is empty, so unload the current track and update + this.stop(); + this.currentTrack = null; + + //Set play state to false and update clients + this.setIsPlaying(false); + this.changedCurrent(); + } else { + //Play the new current track + this.playTrack(newTrack); + } + } + }.bind(this)); +} + +Player.prototype = { + /** + * Load the provided track into the player and start playing + * @param track + */ + playTrack: function (track) { + //Unload the current track + this.player.stop(); + //Make sure the next track is loaded + this.queue.loadItem(track).then(function (track) { + //If it's empty (invalid) + if ("undefined" === typeof track || track == null) { + console.log("undefined track", track); + this.stop(); + return; + } + try { + //Update the current track + console.log('Playing: %s - %s', track.artists[0].name, track.name); + //Load the track into the player + this.player.play(track); + this.currentTrack = track; + + //Update the current state + this.setIsPlaying(true); + this.changedCurrent(); + } catch (e) { + this.emit("playError", {e: e, track: track}); + this.queue.next(); + } + }.bind(this)); + }, + /** + * Get the current loaded track + * @returns {null|*} + */ + getPlayingTrack: function () { + return this.currentTrack; + }, + /** + * Resume playing the current track (or load a new one if not already playing a track) + */ + play: function () { + if (this.currentTrack === null) { + this.playTrack(this.queue.getCurrentTrack()); + } else { + this.player.resume(); + this.setIsPlaying(true); + } + }, + /** + * Set the current playing state and notify the clients + * @param Booleans isPlaying + */ + setIsPlaying: function (isPlaying) { + if (isPlaying != this.isPlaying) { + this.isPlaying = isPlaying; + this.emit("playState", this.isPlaying); + } + }, + /** + * Pause the current track + */ + pause: function () { + this.player.pause(); + this.setIsPlaying(false); + }, + /** + * Unload the current track and notify the clients + */ + stop: function () { + this.player.seek(0); + this.player.stop(); + this.currentTrack = null; + this.changedCurrent(); + this.setIsPlaying(false); + }, + /** + * Notify the currently connected clients + */ + changedCurrent: function () { + this.emit("changedCurrent", this.getCurrentTrackJson()); + }, + getCurrentTrackJson: function () { + return this.getPlayingTrack() == null ? null : this.getPlayingTrack().getJson(); + } +} + +Player.prototype.__proto__ = events.EventEmitter.prototype; + +module.exports = Player; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044805_app.module.js b/pool/shard007/JavaScript/0044805_app.module.js new file mode 100644 index 0000000000000000000000000000000000000000..b91a4bf4cb0ce23aa27954466f8859742cfcec0f --- /dev/null +++ b/pool/shard007/JavaScript/0044805_app.module.js @@ -0,0 +1,18 @@ +(function(app) { + var NgModule = ng.core.NgModule; + var BrowserModule = ng.platformBrowser.BrowserModule; + var QuoteService = app.QuoteService; + var RandomQuoteComponent = app.RandomQuoteComponent; + var AppComponent = app.AppComponent; + + @NgModule({ + imports: [BrowserModule], + declarations: [AppComponent, RandomQuoteComponent], + providers: [QuoteService], + bootstrap: [AppComponent] + }) + class AppModule { } + + app.AppModule = AppModule; + +})(window.app || (window.app = {})); diff --git a/pool/shard007/JavaScript/0044806_mapgen.js b/pool/shard007/JavaScript/0044806_mapgen.js new file mode 100644 index 0000000000000000000000000000000000000000..fdb86bb47d30689f2da9c15406d5819dec7678bd --- /dev/null +++ b/pool/shard007/JavaScript/0044806_mapgen.js @@ -0,0 +1,113 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const seedInput = fs.readFileSync('/dev/stdin', 'utf-8'); + +const seedList = JSON.parse(seedInput); + +if (!Array.isArray(seedList)) { + console.error('Input not valid JSON or is not an array of seed objects!'); + process.exit(1); +} + +const map = { + id: 'generated-map', + nextId: 0, + type: 'map', + playerIds: [], + territoryIds: [], + edgeIds: [], + unitIds: [], + dataMap: {}, +}; + +for (let i = 0; i < seedList.length; ++i) { + const seed = seedList[i]; + + switch (seed.type) { + case 'player': + processPlayer(map, seed); + break; + case 'territory': + processTerritory(map, seed); + break; + case 'edge': + processEdge(map, seed); + break; + } +} + +console.log(JSON.stringify(map)); + +function processPlayer(map, playerSeed) { + const id = playerSeed.id; + + map.playerIds.push(id); + map.dataMap[id] = { + unitIds: [], + territoryIds: [], + colour: 0, + gold: 0, + goldProduction: 1, + ready: false, + ...playerSeed, + }; +} + +function processTerritory(map, territorySeed) { + const id = territorySeed.id; + + const numUnits = territorySeed.numUnits; + delete territorySeed.numUnits; + + map.territoryIds.push(id); + const territory = { + unitIds: [], + food: 3, + edgeIds: [], + currentAction: null, + properties: [], + ...territorySeed, + }; + + map.dataMap[id] = territory; + + if (territorySeed.playerId) { + map.dataMap[territorySeed.playerId].territoryIds.push(id); + } + + for (let i = 0; i < numUnits; ++i) { + const unitId = '#U' + map.nextId; + map.nextId++; + + map.unitIds.push(unitId); + map.dataMap[id].unitIds.push(unitId); + + map.dataMap[unitId] = { + type: 'unit', + id: unitId, + playerId: territory.playerId || null, + locationId: territory.id, + destinationId: null, + statuses: [], + }; + + if (territory.playerId) { + map.dataMap[territory.playerId].unitIds.push(unitId); + } + } +} + +function processEdge(map, edgeSeed) { + const id = edgeSeed.territoryAId + edgeSeed.territoryBId; + + map.edgeIds.push(id); + map.dataMap[id] = { + id: id, + unitIds: [], + ...edgeSeed, + }; + + map.dataMap[edgeSeed.territoryAId].edgeIds.push(id); + map.dataMap[edgeSeed.territoryBId].edgeIds.push(id); +} diff --git a/pool/shard007/JavaScript/0044810_convertPlexToMovie.js b/pool/shard007/JavaScript/0044810_convertPlexToMovie.js new file mode 100644 index 0000000000000000000000000000000000000000..b41a887044459d294da41d9403710d12f0a20f2b --- /dev/null +++ b/pool/shard007/JavaScript/0044810_convertPlexToMovie.js @@ -0,0 +1,15 @@ +const Movie = require('src/plex/types/movie'); + +function convertPlexToMovie(plexMovie) { + const movie = new Movie(plexMovie.title, plexMovie.year); + movie.rating = plexMovie.rating; + movie.tagline = plexMovie.tagline; + + if (plexMovie.summary !== undefined) { + movie.summary = plexMovie.summary; + } + + return movie; +} + +module.exports = convertPlexToMovie; diff --git a/pool/shard007/JavaScript/0044811_GlobalData.js b/pool/shard007/JavaScript/0044811_GlobalData.js new file mode 100644 index 0000000000000000000000000000000000000000..fc4f856f01c8e78c4ef359f277d2906b987fe3fd --- /dev/null +++ b/pool/shard007/JavaScript/0044811_GlobalData.js @@ -0,0 +1,183 @@ +dojo.provide("wm.packages.zabonline.mod.GlobalData"); +// +dojo.declare("GlobalData", null, { + getNameByIndex: function(index, ret) { + if (this.globalDataFound() === true) { + var item = this.scope.initData.getItem(index); + return item.getValue("name"); + } else { + return ret; + } + }, + getDataValueByIndex: function(index, ret) { + if (this.globalDataFound() === true) { + var item = this.scope.initData.getItem(index); + return item.getValue("dataValue"); + } else { + return ret; + } + }, + globalDataFound: function() { + var item = this.scope.initData.getItem(0); + + return item.getValue("dataValue"); + }, + userName: function() { + return this.getDataValueByIndex(1, ""); + }, + userId: function() { + return this.getDataValueByIndex(2, ""); + }, + tenantId: function(variable) { + var tenant_id = this.getDataValueByIndex(3, ""); + + if (variable) { + variable.setValue("dataValue", tenant_id); + } + + return tenant_id; + }, + sessionId: function() { + return this.getDataValueByIndex(4, ""); + }, + countryId: function() { + return this.getDataValueByIndex(5, ""); + }, + countryCode: function() { + return this.getDataValueByIndex(6, ""); + }, + currencyCode: function() { + return this.getDataValueByIndex(7, ""); + }, + constructor: function(globalScope, resultCallBackStr) { + console.debug('Start GlobalData.constructor'); + + this.scope = globalScope; + this.onResultCallbackStr = resultCallBackStr; + + console.debug('End GlobalData.constructor'); + }, + postscript: function() { + console.debug('Start GlobalData.postscript'); + + this.scope.connect(this.scope.userData, "onResult", this, "onResult"); + this.scope.connect(this.scope.userData, "onSuccess", this, "onSuccess"); + this.scope.connect(this, "onSuccess", this.scope, this.onResultCallbackStr); + + console.debug('End Global.postscript'); + }, + initData: function(username) { + console.debug('Start GlobalData.initData'); + + this.scope.initData.addItem({ + name: "userdatafound", + dataValue: false + }, 0); + this.scope.initData.addItem({ + name: "username", + dataValue: username + }, 1); + this.scope.initData.addItem({ + name: "userid", + dataValue: null + }, 2); + this.scope.initData.addItem({ + name: "tenantid", + dataValue: null + }, 3); + this.scope.initData.addItem({ + name: "sessionid", + dataValue: this.scope.getSessionId() + }, 4); + this.scope.initData.addItem({ + name: "countryid", + dataValue: null + }, 5); + this.scope.initData.addItem({ + name: "countryCode", + dataValue: null + }, 6); + this.scope.initData.addItem({ + name: "currencyCode", + dataValue: null + }, 7); + + console.debug(this.scope.initData.getData()); + + console.debug('End GlobalData.initData'); + }, + refresh: function(username) { + console.debug('Start GlobalData.refresh'); + + this.initData(username); + + //Eingaben für die Servicevariable eintragen + this.scope.userData.input.setValue('Username', username); + //Service der Servicevariable aktivieren + if (this.scope.userData.canUpdate()) { + this.scope.userData.update(); + return 1; + } + else { + console.debug('Kein Update auf this.scope.userData'); + return 0; + } + + console.debug('End GlobalData.refresh'); + }, + onResult: function(inSender, inDeprecated) { + try { + console.debug('Start GlobalData.onResult'); + + var userId = this.scope.userData.getValue('id'); + var tenant = this.scope.userData.getValue('tenant'); + var tenantId = tenant.getValue('id'); + var country = tenant.getValue('country'); + var countryId = country.getValue('id'); + var countryCode = country.getValue('countryCode'); + var currencyCode = country.getValue('currencyCode'); + + this.scope.initData.setItem(2, { + name: "userid", + dataValue: userId + }); + this.scope.initData.setItem(3, { + name: "tenantid", + dataValue: tenantId + }); + this.scope.initData.setItem(5, { + name: "countryid", + dataValue: countryId + }); + this.scope.initData.setItem(6, { + name: "countryCode", + dataValue: countryCode + }); + this.scope.initData.setItem(7, { + name: "currencyCode", + dataValue: currencyCode + }); + + console.debug(this.scope.initData.getData()); + + console.debug('End GlobalData.onResult'); + } catch (e) { + console.error('ERROR IN globalDataResult: ' + e); + } + }, + onSuccess: function(inSender, inDeprecated) { + try { + console.debug('Start GlobalData.onSuccess'); + + this.scope.initData.setItem(0, { + name: "userdatafound", + dataValue: true + }); + + console.debug('End GlobalData.onSuccess'); + } catch (e) { + console.error('ERROR IN globalDataSuccess: ' + e); + } + } +}); + diff --git a/pool/shard007/JavaScript/0044814_errorHandler.js b/pool/shard007/JavaScript/0044814_errorHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..7e7041027db6edec1a479335d1e0ca04b7445895 --- /dev/null +++ b/pool/shard007/JavaScript/0044814_errorHandler.js @@ -0,0 +1,26 @@ +import config from '../config' + +module.exports = async (ctx, next) => { + try { + await next() + } catch (e) { + const status = e.output ? e.output.statusCode : ctx.status + + let resError = { + code: status || 500, + message: e.message, + errors: e.errors + } + + if (e instanceof Error && config.environment !== 'production') { + resError = { + ...resError, + stack: e.stack + } + } + + Object.assign(ctx, { body: resError, status: status || 500 }) + + ctx.log.error(e) + } +} diff --git a/pool/shard007/JavaScript/0044816_circle.js b/pool/shard007/JavaScript/0044816_circle.js new file mode 100644 index 0000000000000000000000000000000000000000..d301ebd8f2507c8649f1d45cc4ad6c6dcc4a4ba9 --- /dev/null +++ b/pool/shard007/JavaScript/0044816_circle.js @@ -0,0 +1,93 @@ +/* @flow */ +'use strict'; +const THREE = require('three'); +const lerp = require('../helpers/lerp'); +const normalize = require('../helpers/normalize'); + +class Circle { + constructor () { + this.root = document.body; + this.container = this.root.querySelector('[data-circle-container]'); + if(!this.container) return; + this.height = this.container.getBoundingClientRect().height; + this.screenWidth = window.innerWidth; + this.screenHeight = window.innerHeight; + this.camera = new THREE.PerspectiveCamera(75, this.screenWidth / this.height, 0.1, 1000); + this.camera.position.z = 5; + this.scene = new THREE.Scene(); + this.renderer = new THREE.WebGLRenderer({antialias: true, alpha: true}); + this.renderer.setSize(this.screenWidth, this.height); + this.container.appendChild( this.renderer.domElement ); + this.init(); + } +}; + +Circle.prototype.init = function () { + this.dx = this.dy = this.sx = this.sy = 0; + this.initMesh(); + this.initAmbLight(); + this.initLight(); + // this.scene.add(new THREE.AxisHelper( 5 )); + this.renderFn = this.render.bind(this); + this.renderFn(); + this.eventManager(); +}; + +Circle.prototype.initMesh = function () { + const geom = new THREE.CylinderGeometry(2, 2, .05, 64); + const met = new THREE.MeshLambertMaterial({color: 0xffac00}); + this.mesh = new THREE.Mesh(geom, met); + this.mesh.rotation.x = Math.PI/2; + this.scene.add(this.mesh); +}; + +Circle.prototype.initAmbLight = function () { + this.ambLight = new THREE.AmbientLight( 0xffffff, .85 ); + this.scene.add( this.ambLight ); +}; + +Circle.prototype.initLight = function () { + this.light = new THREE.PointLight( 0xffffff, .6, 0); + this.light.position.set( 0, 0, 1); + this.scene.add( this.light ); + + // var sphereSize = 1; + // var pointLightHelper = new THREE.PointLightHelper( this.light, sphereSize ); + // this.scene.add( pointLightHelper ); +}; + +Circle.prototype.render = function () { + this.dx = lerp(this.dx, this.sx, 0.1); + this.dy = lerp(this.dy, this.sy, 0.1); + this.sx = lerp(this.sx, this.sx, 0.1); + this.sy = lerp(this.sy, this.sy, 0.1); + this.mesh.rotation.x = normalize(this.dy, 0, this.screenHeight, 4 * Math.PI/10, 6 * Math.PI/10); + this.mesh.rotation.z = normalize(this.dx, 0, this.screenWidth, 4*Math.PI/100, -4*Math.PI/100); + + this.light.position.x = normalize(this.sx, 0, this.screenWidth, -5, 5); + this.light.position.y = normalize(this.sy, 0, this.screenHeight, 5, -5); + + this.renderer.render( this.scene, this.camera ); + window.requestAnimationFrame( this.renderFn ); + +}; + +Circle.prototype.eventManager = function () { + this.onMouseMoveFn = this.onMouseMove.bind(this); + this.root.addEventListener('mousemove', this.onMouseMoveFn); + window.addEventListener('resize', this.onResize.bind(this)); +}; + +Circle.prototype.onMouseMove = function (e){ + this.sx = e.pageX; + this.sy = e.pageY; +}; + +Circle.prototype.onResize = function () { + this.screenWidth = window.innerWidth; + this.height = this.container.getBoundingClientRect().height; + this.renderer.setSize( this.screenWidth, this.height ); + this.camera.aspect = this.screenWidth / this.height; + this.camera.updateProjectionMatrix(); +}; +module.exports = Circle; diff --git a/pool/shard007/JavaScript/0044818_account-factory.js b/pool/shard007/JavaScript/0044818_account-factory.js new file mode 100644 index 0000000000000000000000000000000000000000..1b6340814071b83d2a4009d94a13e6c9b0ad4e02 --- /dev/null +++ b/pool/shard007/JavaScript/0044818_account-factory.js @@ -0,0 +1,32 @@ + +var subclass = require('subclassjs'); + + +var mongo = require('../../mongo'); + + +var AccountFactory = subclass(function (pt) { + 'use strict'; + + pt.constructor.getInstance = function () { + + return new this(); + + }; + + + pt.createFromObject = function (obj) { + + if (!obj) { + + return null; + + } + + return new mongo.Account(obj); + + }; + +}); + +module.exports = AccountFactory; diff --git a/pool/shard007/JavaScript/0044822_spellMenu.js b/pool/shard007/JavaScript/0044822_spellMenu.js new file mode 100644 index 0000000000000000000000000000000000000000..361a8dfe5b8d9cf4de4c44a49a68777404f5e7f2 --- /dev/null +++ b/pool/shard007/JavaScript/0044822_spellMenu.js @@ -0,0 +1,29 @@ +ig.module( + 'game.entities.menus.spellmenu' +) +.requires( + 'impact.entity' +) +.defines(function(){ + EntitySpellMenu = ig.Entity.extend({ + + type: ig.Entity.TYPE.B, + checkAgainst: ig.Entity.TYPE.A, + collides: ig.Entity.COLLIDES.ACTIVE, + + size: {x: 16, y: 16}, + animSheet: new ig.AnimationSheet('media/wizardhat.png', 16, 16), + zIndex: 100, + + init: function(x, y, settings){ + this.parent(x, y, settings); + this.addAnim('idle', 0.1, [0]); + }, + + update: function(){ + this.currentAnim = this.anims.idle; + }, + + + }); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044823_setupdb.js b/pool/shard007/JavaScript/0044823_setupdb.js new file mode 100644 index 0000000000000000000000000000000000000000..2e90da8e347aeeb6daffefb7ed072b636ff3baca --- /dev/null +++ b/pool/shard007/JavaScript/0044823_setupdb.js @@ -0,0 +1,85 @@ +// db.js +// connects to and handles database + +var mysql = require("mysql"); +var secrets = require('../../secrets.json'); + +// First you need to create a connection to the db +var con = mysql.createConnection({ + host: "localhost", + user: secrets.dbusername, + password: secrets.dbpassword +}); + +con.connect(function(err){ + if(err){ + console.error('Error connecting to Db'); + return; + } + console.log('Connection Established.'); +}); + +// create database for BitBunker +con.query('CREATE Database BitBunker', + function(err, result){ + // Case there is an error during the creation + if(err) { + console.log(err); + } else { + console.log("BitBunker Database Created."); + } +}); + +con.end(function(err) { + // Create another connection to the db + con = mysql.createConnection({ + host: "localhost", + user: secrets.dbusername, + password: secrets.dbpassword, + database: "BitBunker" + }); + + con.connect(function(err){ + if(err){ + console.error('Error connecting to Db'); + return; + } + console.log('Connection Reestablished.'); + }); + + //create table vaults + con.query('CREATE TABLE Vaults (vault_name VARCHAR(256) NOT NULL UNIQUE, vault_secret VARCHAR(256) NOT NULL, ' + + 'PRIMARY KEY (vault_name))', + function(err, result){ + // Case there is an error during the creation + if(err) { + console.log(err); + } else { + console.log("Table Vaults Created."); + } + }); + + + //create table files + //fields for files: + //file_name varchar(256) NOT NULL + //content string NOT NULL + //vault_name varchar(256) NOT NULL + con.query('CREATE TABLE Files (filename VARCHAR(256) NOT NULL, content LONGTEXT,' + + 'vault_name varchar(256), PRIMARY KEY (filename, vault_name))', + function(err, result){ + // Case there is an error during the creation + if(err) { + console.log(err); + } else { + console.log("Table Files Created."); + } + }); + + + con.end(function(err) { + console.log('Finished.'); + }); + +}); + diff --git a/pool/shard007/JavaScript/0044824_candidates.js b/pool/shard007/JavaScript/0044824_candidates.js new file mode 100644 index 0000000000000000000000000000000000000000..2919045af565bb0bd26c8ac2b21e63fd9b0632bc --- /dev/null +++ b/pool/shard007/JavaScript/0044824_candidates.js @@ -0,0 +1,129 @@ +'use strict'; + +var _ = require('lodash'); +var b = require('bluebird'); +var fs = require('fs'); +var URL = require('url'); +var path = require('path'); +var utils = require('./utils'); +var moment = require('moment'); + +var WIKI_LANG = process.env.WIKI_LANG || 'en'; +var WIKI_HOST = ['https://' + WIKI_LANG, 'wikipedia', 'org/wiki/'].join('.'); + +var PARTY_INFO_PATH = path.join(process.cwd(), 'data'); +var DEBATE_PARTIES = ['democratic', 'republican']; +var POTENTIAL_ISSUE_PATHS = [ '/issues', '/policy', '/category/issues', '/category/policy', '/on-the-issues', '/positions', '/records', '/campaign-issues', '/' ]; + +var makeRequest = utils.request; +var pageExists = utils.pageExists; + +function rejectedPromise(text) { + var deferred = b.defer(); + b.resolve(text || '{}'); + return deferred.promise; +} + +function createPartyObj(party, candidates) { + return { + name: _.capitalize(party), + compiled: moment().format('YYYY-MM-DD'), + candidates: candidates + }; +} + +function resolveIssueUrl(website, paths, previous) { + var url = URL.parse(website); + + paths = arguments[1] || _.clone(POTENTIAL_ISSUE_PATHS); + + if(!paths.length) return false; + + url.pathname = paths.shift(); + + if(URL.format(url) === previous) return rejectedPromise(); + + // If the promise succeeds, we've resolved (200) an issue URL + // If the promise is rejected, continue down our potential paths. + return pageExists(url) + .then( + _.identity, + _.partial(resolveIssueUrl, URL.format(url), paths, URL.format(url) + ) + ); +} + +function writePartyFilesTo(writePath, parties) { + var names = _.keys(parties); + + return b.each(_.values(parties), function(info, i) { + var deferred = b.defer(); + var partyData = createPartyObj(names[i], info); + + fs.writeFile( + path.join(writePath, partyData.name.toLowerCase() + '-party.json'), + JSON.stringify(partyData, null, 2), + function(err) { + if(!err) return deferred.resolve(true); + deferred.reject(err); + } + ); + + return deferred.promise; + }); +} + +function getPartyElectionInfoURL(party, year) { + return WIKI_HOST + _.capitalize(party.toLowerCase()) + '_Party_presidential_candidates,_' + year; +} + +function getCandidateInfo(party, $) { + return _.filter( + $('table.wikitable.sortable tbody').first().map(function() { + return $(this).children('tr').map(function() { + var $cells = $(this).find('td'); + var deferred = b.defer(); + + var candidateInfo = { + name: _.trim($cells.first().find('a').last().text()), + website: $cells.eq($cells.length-2).find('a.external').attr('href'), + party: party + }; + + if(candidateInfo.website) { + return resolveIssueUrl(candidateInfo.website) + .then(function(url) { + return _.extend(candidateInfo, { + issuesUrl: url + }); + }, function(err) { + console.log(err); + }); + } + else { + return undefined; + } + }).get(); + }).get(), + _.identity + ); +} + +module.exports = function getCandidates(electionYear) { + return b.all( + _.map(DEBATE_PARTIES, function(party) { + return makeRequest(getPartyElectionInfoURL(party, electionYear)); + }) + ).then(function(parties) { + return b.all( + _.flatten( + _.map(parties, function($partyWikiPage, i) { + return getCandidateInfo(DEBATE_PARTIES[i], $partyWikiPage); + }) + ) + ); + }, function(err) { console.log(err); }) + .then(function(candidates) { + return writePartyFilesTo(PARTY_INFO_PATH, _.groupBy(candidates, 'party')); + }, function(err) { console.log(err); }); +}; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044827_classnames.js b/pool/shard007/JavaScript/0044827_classnames.js new file mode 100644 index 0000000000000000000000000000000000000000..89ecc816c5f29e5381123cbe6a6d4cde5ece2f4f --- /dev/null +++ b/pool/shard007/JavaScript/0044827_classnames.js @@ -0,0 +1,42 @@ +/*! + Copyright (c) 2015 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/ +/* global define */ +cx = function(){ + +}; + +(function() { + 'use strict'; + + var hasOwn = {}.hasOwnProperty; + + function classNames() { + var classes = ''; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (!arg) continue; + + var argType = typeof arg; + + if (argType === 'string' || argType === 'number') { + classes += ' ' + arg; + } else if (Array.isArray(arg)) { + classes += ' ' + classNames.apply(null, arg); + } else if (argType === 'object') { + for (var key in arg) { + if (hasOwn.call(arg, key) && arg[key]) { + classes += ' ' + key; + } + } + } + } + + return classes.substr(1); + } + + cx = classNames; +}()); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044829_get-router.js b/pool/shard007/JavaScript/0044829_get-router.js new file mode 100644 index 0000000000000000000000000000000000000000..badec98ca8a18d7107900dd3bca58e3b86040596 --- /dev/null +++ b/pool/shard007/JavaScript/0044829_get-router.js @@ -0,0 +1,42 @@ +import React from 'react' +import { Router, useRouterHistory } from 'react-router' +import { Provider } from 'react-redux' +import configureStore from 'shared/configure-store.js' +import { syncHistoryWithStore } from 'react-router-redux' +import routes from './routes' +import analytics from 'utils/analytics' + +import { createHistory } from 'history' + +//set's /widgets as a history root so routes can be defined acoordingly +const browserHistory = useRouterHistory(createHistory)({ + basename: '/widgets' +}) + +const store = configureStore() +const getStore = () => store +const history = syncHistoryWithStore(browserHistory, store) +history.listen(location => analytics.page()) + +//overriding Router function to pass custom props to a child components, building a higer order function to +//provide containerWidth to inner-clojure +const buildCreateElement = containerW => + (Component, props) => + +const getRouter = containerWidth => { + return +} + +const getConfiguredWithStoreRouter = containerWidth => { + return ( + + {getRouter(containerWidth)} + + ) +} + +export { + getRouter, + getConfiguredWithStoreRouter, + getStore, +} diff --git a/pool/shard007/JavaScript/0044830_Request.JSON.js b/pool/shard007/JavaScript/0044830_Request.JSON.js new file mode 100644 index 0000000000000000000000000000000000000000..aa42b5f02d0edc391ac0a4968b593923fd8b8d24 --- /dev/null +++ b/pool/shard007/JavaScript/0044830_Request.JSON.js @@ -0,0 +1,109 @@ +/** + * Request.JSON - extended to get some informations about calls and creates info for user if a call fails. + */ +Request.JSON = new Class({ + Extends: Request.JSON, + + initialize: function (options) { + if (!'secure' in options) { + options.secure = true; + } + this.parent(options); + this.addEvent('failure', this.booboo.bind(this)); + this.addEvent('error', this.invalidJson.bind(this)); + + this.addEvent('complete', function (pData) { + window.fireEvent('restCall', [pData, this]); + }.bind(this)); + + if (options.noErrorReporting === true) { + return; + } + this.addEvent('complete', this.checkError.bind(this)); + }, + + send: function (options) { + this.data = options.data; + this.options.url += (this.options.url.indexOf('?') == -1 ? '?' : '&') + '_suppress_status_code=1'; + return this.parent(options); + }, + + invalidJson: function () { + if (ka.lastRequestBubble) { + ka.lastRequestBubble.die(); + delete ka.lastRequestBubble; + } + + if (ka.helpsystem) { + ka.lastRequestBubble = ka.helpsystem.newBubble( + t('Response error'), + t('Server\' response is not valid JSON. Looks like the server has serious troubles. :-(') + + "
" + 'URI: %s'.replace('%s', this.options.url) + + '
Details', + 15000); + throw 'Response Error %s'.replace('%s', this.options.url); + } + }, + + booboo: function () { + if (ka.lastRequestBubble) { + ka.lastRequestBubble.die(); + delete ka.lastRequestBubble; + } + + if (ka.helpsystem) { + ka.lastRequestBubble = ka.helpsystem.newBubble( + t('Request error'), + t('There has been a error occured during the last request. Either you lost your internet connection or the server has serious troubles.') + + "
" + 'URI: %s'.replace('%s', this.options.url) + + '
Details', + 15000); + throw 'Request Error %s'.replace('%s', this.options.url); + } + }, + + checkError: function (pResult) { + if (pResult && pResult.error) { + + if (typeOf(this.options.noErrorReporting) == 'array' && + this.options.noErrorReporting.contains(pResult.error)) { + return false; + } + + if (true === this.options.noErrorReporting) { + return false; + } + + if (ka.lastRequestBubble) { + ka.lastRequestBubble.die(); + delete ka.lastRequestBubble; + } + + if (!ka.adminInterface || !ka.adminInterface.getHelpSystem()) { + return false; + } + + if ('AccessDeniedException' === pResult.error) { + ka.lastRequestBubble = ka.adminInterface.getHelpSystem().newBubble( + t('Access denied'), + t('You started a secured action or requested a secured information.') + + "
" + 'URI: %s'.replace('%s', this.options.url) + + '
Details', + 15000 + ); + throw 'Access Denied %s'.replace('%s', this.options.url); + } else { + ka.lastRequestBubble = ka.adminInterface.getHelpSystem().newBubble( + t('Request error'), + t('There has been a error occured during the last request. It looks like the server has currently some troubles. Please try it again.') + + "

" + t('Error code: %s').replace('%s', pResult.error) + + "
" + t('Error message: %s').replace('%s', pResult.message) + + "
" + 'URI: %s'.replace('%s', this.options.url) + + '
Details', + 15000 + ); + throw 'Request Error %s'.replace('%s', this.options.url); + } + } + } +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044831_scripts.babel.js b/pool/shard007/JavaScript/0044831_scripts.babel.js new file mode 100644 index 0000000000000000000000000000000000000000..d17f0bd29bf98d1203141bacee1d012f12316865 --- /dev/null +++ b/pool/shard007/JavaScript/0044831_scripts.babel.js @@ -0,0 +1,14 @@ +/* global require */ +/* eslint-disable import/no-extraneous-dependencies */ +const path = require('path'); +const gulp = require('gulp'); +const conf = require('./conf'); +const { packScripts } = require('./utils.babel'); + + +gulp.task('scripts', () => packScripts(false, gulp.src(path.join(conf.paths.src, '/main.js')), { + libraryTarget : 'umd', + filename : 'om-core.js', + minFilename : 'om-core.min.js', + dest : path.join(conf.paths.dist, '/scripts/') +})); diff --git a/pool/shard007/JavaScript/0044832_api.js b/pool/shard007/JavaScript/0044832_api.js new file mode 100644 index 0000000000000000000000000000000000000000..abc72f1ca9c4651b2fab3b750e8a56b24957d4a9 --- /dev/null +++ b/pool/shard007/JavaScript/0044832_api.js @@ -0,0 +1,88 @@ +const lib = require('../lib'); +const express = require('express'); +const router = express.Router(); +const passport = require('passport'); + +function apiResponse(className, functionName, tokenNeeded=true, reqFuncs=[]){ + let args = Array.prototype.slice.call(arguments, 4); + let deepFind = function(obj, pathStr){ + let path = pathStr.split('.'); + let len=path.length; + for (let i=0; i { + res.status(200) + .json(data); + }) + .catch(err=> { + console.log(`${className}/${functionName}: `, err.message); + res.status(err.status||500) + .send(err.message || err); + }); + } + }); +} + +router.get('/', function(req, res) { + res.send('respond with a resource'); +}); + +//User API +router.post('/login', apiResponse('User', 'login', false, ['body.username', 'body.password'])); +router.put('/user', apiResponse('User', 'insert', false, ['body'])); +router.delete('/user/:id', apiResponse('User', 'delete', true, ['params.id'])); +router.post('/user/:id', apiResponse('User', 'update', true, ['params.id', 'body'])); +router.post('/isLoggedIn', apiResponse('User', 'checkLogin', true, ['user.username', 'user.password'])); +router.get('/user/top', apiResponse('User', 'getTopPeople', false)); +router.get('/user', apiResponse('User', 'select', true)); + + +//Organ API +router.get('/organ/accessLevel', apiResponse('Organ', 'getAccessLevels', true)); +router.get('/organ/part', apiResponse('Organ', 'getParts', true)); +router.put('/organ/part', apiResponse('Organ', 'saveOrgan', true, ['body'])); + + +//Criticism API +router.get('/criticism/subject', apiResponse('Criticism', 'getSubjects', true)); +router.get('/criticism', apiResponse('Criticism', 'getCriticisms', false)); +router.get('/criticism/user', apiResponse('Criticism', 'getMyCriticisms', true, ['user.uid'])); +router.get('/criticism/best', apiResponse('Criticism', 'getTheBest', false)); +router.put('/criticism', apiResponse('Criticism', 'saveCriticism', true, ['user.uid', 'body'])); +router.post('/criticism', apiResponse('Criticism', 'saveCriticism', true, ['user.uid', 'body', 'body.cid'])); +router.post('/criticism/vote/:cid', apiResponse('Criticism', 'votingCriticism', true, ['params.cid', 'body.value', 'user.uid'])); +router.post('/criticism/backward/:cid', apiResponse('Criticism', 'backwardCriticism', true, ['body', 'params.cid', 'user.uid'])); + +//Replies API +router.get('/criticism/notreply', apiResponse('User', 'getNotifications', true, ['user.uid'])); +router.put('/reply', apiResponse('Criticism', 'saveReply', true, ['body', 'user.uid'])); +router.get('/reply/:cid', apiResponse('Criticism', 'getReplies', false, ['params.cid'])); +router.post('/reply/vote/:rid', apiResponse('Criticism', 'votingReply', true, ['params.rid', 'body.value', 'user.uid'])); +router.post('/reply/thank/:rid', apiResponse('Criticism', 'thankReply', true, ['params.rid', 'body.value', 'user.uid'])); + +module.exports = router; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044834_field_flydown.js b/pool/shard007/JavaScript/0044834_field_flydown.js new file mode 100644 index 0000000000000000000000000000000000000000..dcfc9c4a2496ed6fb1748fb96b670d7b3da5aec1 --- /dev/null +++ b/pool/shard007/JavaScript/0044834_field_flydown.js @@ -0,0 +1,219 @@ +/** + * Visual Blocks Editor + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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. + */ + +/** + * @fileoverview Field in which mouseover displays flyout-like menu of blocks + * and mouse click edits the field name. + * Flydowns are used in App Inventor for displaying get/set blocks for parameter names + * and callers for procedure declarations. + * @author fturbak@wellesley.edu (Lyn Turbak) + */ +'use strict'; + +goog.provide('Blockly.FieldFlydown'); + +goog.require('Blockly.FieldTextInput'); + +/** + * Class for a clickable parameter field. + * @param {string} text The initial parameter name in the field. + * @param {Function} opt_changeHandler An optional function that is called + * to validate any constraints on what the user entered. Takes the new + * text as an argument and returns the accepted text or null to abort + * the change. E.g., for an associated getter/setter this could change + * references to names in this field. + * @extends {Blockly.Field} + * @constructor + */ + +Blockly.FieldFlydown = function(name, isEditable, displayLocation, opt_changeHandler) { + Blockly.FieldFlydown.superClass_.constructor.call(this, name, opt_changeHandler); + + this.EDITABLE = isEditable; // This by itself does not control editability + this.displayLocation = displayLocation; // [lyn, 10/27/13] Make flydown direction an instance variable + // this.fieldGroup_.style.cursor = ''; + + // Remove inherited field css classes ... + Blockly.removeClass_(/** @type {!Element} */ (this.fieldGroup_), + 'blocklyEditableText'); + Blockly.removeClass_(/** @type {!Element} */ (this.fieldGroup_), + 'blocklyNoNEditableText'); + // ... and add new one, so that look and feel of flyout fields can be customized + Blockly.addClass_(/** @type {!Element} */ (this.fieldGroup_), + this.fieldCSSClassName); + + // Only want one flydown object and associated svg per workspace + if (! Blockly.mainWorkspace.FieldFlydown) { + var flydown = new Blockly.Flydown(); + // ***** [lyn, 10/05/2013] NEED TO WORRY ABOUT MULTIPLE BLOCKLIES! ***** + Blockly.mainWorkspace.FieldFlydown = flydown; + var flydownSvg = flydown.createDom(this.flyoutCSSClassName); + Blockly.svg.appendChild(flydownSvg); // Add flydown to top-level svg, *not* to main workspace svg + // This is essential for correct positioning of flydown via translation + // (If it's in workspace svg, it will be additionally translated by + // workspace svg translation relative to Blockly.svg.) + flydown.init(Blockly.mainWorkspace, false); // false means no scrollbar + flydown.autoClose = true; // Flydown closes after selecting a block + } +}; +goog.inherits(Blockly.FieldFlydown, Blockly.FieldTextInput); + +/** + * Milliseconds to wait before showing flydown after mouseover event on flydown field. + * @type {number} + * @const + */ +Blockly.FieldFlydown.timeout = 500; + +/** + * Process ID for timer event to show flydown (scheduled by mouseover event) + * @type {number} + * @const + */ +Blockly.FieldFlydown.showPid_ = 0; + +/** + * Which instance of FieldFlydown (or a subclass) is an open flydown attached to? + * @type {Blockly.FieldFlydown (or subclass)} + * @private + */ +Blockly.FieldFlydown.openFieldFlydown_ = null; + +/** + * Control positioning of flydown + */ +Blockly.FieldFlydown.DISPLAY_BELOW = "BELOW"; +Blockly.FieldFlydown.DISPLAY_RIGHT = "RIGHT"; +Blockly.FieldFlydown.DISPLAY_LOCATION = Blockly.FieldFlydown.DISPLAY_BELOW; // [lyn, 10/14/13] Make global for now, change in future + +/** + * Default CSS class name for the field itself + * @type {String} + * @const + */ +Blockly.FieldFlydown.prototype.fieldCSSClassName = 'blocklyFieldFlydownField'; + +/** + * Default CSS class name for the flydown that flies down from the field + * @type {String} + * @const + */ +Blockly.FieldFlydown.prototype.flyoutCSSClassName = 'blocklyFieldFlydownFlydown'; + +// Override FieldTextInput's showEditor_ so it's only called for EDITABLE field. +Blockly.FieldFlydown.prototype.showEditor_ = function() { + if (this.EDITABLE) { + Blockly.FieldFlydown.superClass_.showEditor_.call(this); + } +} + +Blockly.FieldFlydown.prototype.init = function(block) { + Blockly.FieldFlydown.superClass_.init.call(this, block); + this.mouseOverWrapper_ = + Blockly.bindEvent_(this.fieldGroup_, 'mouseover', this, this.onMouseOver_); + this.mouseOutWrapper_ = + Blockly.bindEvent_(this.fieldGroup_, 'mouseout', this, this.onMouseOut_); +}; + +Blockly.FieldFlydown.prototype.onMouseOver_ = function(e) { + // alert("FieldFlydown mouseover"); + if (! this.sourceBlock_.isInFlyout) { // [lyn, 10/22/13] No flydowns in a flyout! + Blockly.FieldFlydown.showPid_ = + window.setTimeout(this.showFlydownMaker_(), Blockly.FieldFlydown.timeout); + // This event has been handled. No need to bubble up to the document. + } + e.stopPropagation(); +}; + +Blockly.FieldFlydown.prototype.onMouseOut_ = function(e) { + // Clear any pending timer event to show flydown + window.clearTimeout(Blockly.FieldFlydown.showPid_); + var flydown = Blockly.mainWorkspace.FieldFlydown; + e.stopPropagation(); +}; + +/** + * Returns a thunk that creates a Flydown block of the getter and setter blocks for receiver field. + * @return A thunk (zero-parameter function). + */ +Blockly.FieldFlydown.prototype.showFlydownMaker_ = function() { + var field = this; // Name receiver in variable so can close over this variable in returned thunk + return function() { + if (Blockly.FieldFlydown.showPid_ != 0) { + field.showFlydown_(); + Blockly.FieldFlydown.showPid_ = 0; + } + }; +}; + +/** + * Creates a Flydown block of the getter and setter blocks for the parameter name in this field. + */ +Blockly.FieldFlydown.prototype.showFlydown_ = function() { + // Create XML elements from blocks and then create the blocks from the XML elements. + // This is a bit crazy, but it's simplest that way. Otherwise, we'd have to duplicate + // much of the code in Blockly.Flydown.prototype.show. + // alert("FieldFlydown show Flydown"); + Blockly.hideChaff(); // Hide open context menus, dropDowns, flyouts, and other flydowns + Blockly.FieldFlydown.openFieldFlydown_ = this; // Remember field to which flydown is attached + var flydown = Blockly.mainWorkspace.FieldFlydown; + flydown.setCSSClass(this.flyoutCSSClassName); // This could have been changed by another field. + var blocksXMLText = this.flydownBlocksXML_() + var blocksDom = Blockly.Xml.textToDom(blocksXMLText); + // [lyn, 11/10/13] Use goog.dom.getChildren rather than .children or .childNodes + // to make this code work across browsers. + var blocksXMLList = goog.dom.getChildren(blocksDom); // List of blocks for flydown + var xy = Blockly.getSvgXY_(this.borderRect_); + var borderBBox = this.borderRect_.getBBox(); + var x = xy.x; + var y = xy.y; + if (this.displayLocation === Blockly.FieldFlydown.DISPLAY_BELOW) { + y = y + borderBBox.height; + } else { // if (this.displayLocation === Blockly.FieldFlydown.DISPLAY_RIGHT) { + x = x + borderBBox.width; + } + Blockly.mainWorkspace.FieldFlydown.showAt(blocksXMLList, x, y); +}; + +/** + * Hide the flydown menu and squash any timer-scheduled flyout creation + */ +Blockly.FieldFlydown.hide = function() { + // Clear any pending timer event to show flydown + window.clearTimeout(Blockly.FieldFlydown.showPid_); + // Clear any displayed flydown + var flydown = Blockly.mainWorkspace.FieldFlydown; + if (flydown) { + flydown.hide(); + } + Blockly.FieldDropdown.openFieldFlydown_ = null; +}; + +/** + * Close the flydown and dispose of all UI. + */ +Blockly.FieldFlydown.prototype.dispose = function() { + if (Blockly.FieldFlydown.openFieldFlydown_ == this) { + Blockly.FieldFlydown.hide(); + } + // Call parent's destructor. + Blockly.FieldTextInput.prototype.dispose.call(this); +}; + + diff --git a/pool/shard007/JavaScript/0044837_jb_run.js b/pool/shard007/JavaScript/0044837_jb_run.js new file mode 100644 index 0000000000000000000000000000000000000000..17b97f257dc44040efde28686375eec526ea04e5 --- /dev/null +++ b/pool/shard007/JavaScript/0044837_jb_run.js @@ -0,0 +1,57 @@ +#!/usr/bin/env node + +/* express server for jbrowse + * (this script gets copied to the app root directory upon npm install) + */ + +var express = require('express'); +var getopt = require('node-getopt'); +var fs = require("fs-extra"); + +var thisPath = process.cwd(); +var jbrowsePath = "./"; + +// check if jbrowse is a module +if (fs.pathExistsSync(thisPath+"/node_modules/@gmod/jbrowse/utils")) { + jbrowsePath = "./node_modules/@gmod/jbrowse"; +} + +// command line options +var getopt = new getopt([ + ['p', 'port=NUMBER' , 'listening port'], + ['s', 'suburi=STRING', 'sub-URI path'], + ['h', 'help', 'display this help'] +]); // create Getopt instance +getopt.bindHelp(); // bind option 'help' to default action +opt = getopt.parseSystem(); // parse command line + +var port = 3000; +var setPort = opt.options['port']; +if (typeof setPort !== 'undefined') { + port = setPort; +} + +// start the server +var app = express(); + +var dispPort = ""; +if (port !== 80) dispPort = ":"+port; + + +app.use('/'+(opt.options['suburi']||''), express.static( + jbrowsePath, + { + // set Content-Encoding: gzip on .jsonz and .gz files + setHeaders(res,path,stat) { + if( /\.(txt|json|g)z$/.test(path) && ! res.req.headers.range ) { + res.setHeader('Content-Encoding','gzip'); + } + res.setHeader('Cache-Control', 'public') + } + } +)); + +app.listen(port, function () { + console.log('JBrowse is running on port %s',port); + console.log('Point your browser to http://localhost%s',dispPort); +}); diff --git a/pool/shard007/JavaScript/0044838_jobs.js b/pool/shard007/JavaScript/0044838_jobs.js new file mode 100644 index 0000000000000000000000000000000000000000..5582a6f0ff4ebfcf30a08fe414394042044f1569 --- /dev/null +++ b/pool/shard007/JavaScript/0044838_jobs.js @@ -0,0 +1,197 @@ +require('enyo'); + +var + utils = require('./utils'), + kind = require('./kind'); + +var CoreObject = require('./CoreObject'); + +/** +* The {@link module:enyo/jobs} singleton provides a mechanism for queueing tasks +* (i.e., functions) for execution in order of priority. The execution of the +* current job stack may be blocked programmatically by setting a priority +* level (run level) below which no jobs are executed. +* +* At the moment, only {@link module:enyo/Animator~Animator} uses this interface, setting a +* priority of 4, which blocks all low priority tasks from executing during +* animations. To maintain backward compatibility, jobs are assigned a priority +* of 5 by default; thus they are not blocked by animations. +* +* Normally, application code will not use `enyo/jobs` directly, but will +* instead use the [job()]{@link module:enyo/Component~Component#job} method of +* {@link module:enyo/Component~Component}. +* +* @module enyo/jobs +* @public +*/ +module.exports = kind.singleton( + /** @lends module:enyo/jobs */ { + + kind: CoreObject, + + /** + * @private + */ + published: /** @lends module:enyo/jobs~jobs */ { + + /** + * The current priority level. + * + * @type {Number} + * @default 0 + * @public + */ + priorityLevel: 0 + }, + + /** + * Prioritized by index. + * + * @private + */ + _jobs: [ [], [], [], [], [], [], [], [], [], [] ], + + /** + * @private + */ + _priorities: {}, + + /** + * @private + */ + _namedJobs: {}, + + /** + * @private + */ + _magicWords: { + 'low': 3, + 'normal': 5, + 'high': 7 + }, + + /** + * Adds a [job]{@link module:enyo/job} to the job queue. If the current priority + * level is higher than this job's priority, this job gets deferred until the + * job level drops; if it is lower, this job is run immediately. + * + * @param {Function} job - The actual {@glossary Function} to execute as the + * [job]{@link module:enyo/job}. + * @param {Number} priority - The priority of the job. + * @param {String} nom - The name of the job for later reference. + * @public + */ + add: function (job, priority, nom) { + priority = priority || 5; + + // magic words: low = 3, normal = 5, high = 7 + priority = utils.isString(priority) ? this._magicWords[priority] : priority; + + // if a job of the same name exists, remove it first (replace it) + if(nom){ + this.remove(nom); + this._namedJobs[nom] = priority; + } + + // if the job is of higher priority than the current priority level then + // there's no point in queueing it + if(priority >= this.priorityLevel){ + job(); + } else { + this._jobs[priority - 1].push({fkt: job, name: nom}); + } + }, + + /** + * Will remove the named [job]{@link module:enyo/job} from the queue. + * + * @param {String} nom - The name of the [job]{@link module:enyo/job} to remove. + * @returns {Array} An {@glossary Array} that will contain the removed job if + * it was found, or empty if it was not found. + * @public + */ + remove: function (nom) { + var jobs = this._jobs[this._namedJobs[nom] - 1]; + if(jobs){ + for(var j = jobs.length-1; j >= 0; j--){ + if(jobs[j].name === nom){ + return jobs.splice(j, 1); + } + } + } + }, + + /** + * Adds a new priority level at which jobs will be executed. If it is higher than the + * highest current priority, the priority level rises. Newly added jobs below that priority + * level are deferred until the priority is removed (i.e., unregistered). + * + * @param {Number} priority - The priority value to register. + * @param {String} id - The name of the priority. + * @public + */ + registerPriority: function(priority, id) { + this._priorities[id] = priority; + this.setPriorityLevel( Math.max(priority, this.priorityLevel) ); + }, + + /** + * Removes a priority level. If the removed priority was previously the + * highest priority, the priority level drops to the next highest priority + * and queued jobs with a higher priority are executed. + * + * @param {String} id - The name of the priority level to remove. + * @public + */ + unregisterPriority: function (id) { + var highestPriority = 0; + + // remove priority + delete this._priorities[id]; + + // find new highest current priority + for( var i in this._priorities ){ + highestPriority = Math.max(highestPriority, this._priorities[i]); + } + + this.setPriorityLevel( highestPriority ); + }, + + /** + * Tries to run next job if priority level has dropped. + * + * @type {module:enyo/ObserverSupport~ObserverSupport~Observer} + * @private + */ + priorityLevelChanged: function (was) { + if(was > this.priorityLevel){ + this._doJob(); + } + }, + + /** + * Finds and executes the job of highest priority; in this way, all jobs with priority + * greater than or equal to the current level are run, in order of their priority (highest + * to lowest). + * + * @private + */ + _doJob: function () { + var job; + // find the job of highest priority above the current priority level + // and remove from the job list + for (var i = 9; i >= this.priorityLevel; i--){ + if (this._jobs[i].length) { + job = this._jobs[i].shift(); + break; + } + } + + // allow other events to pass through + if (job) { + job.fkt(); + delete this._namedJobs[job.name]; + setTimeout(utils.bind(this, '_doJob'), 10); + } + } +}); diff --git a/pool/shard007/JavaScript/0044840_Queue.js b/pool/shard007/JavaScript/0044840_Queue.js new file mode 100644 index 0000000000000000000000000000000000000000..cd1713f4a828cd4c92fc98d8d285109ad1f4b970 --- /dev/null +++ b/pool/shard007/JavaScript/0044840_Queue.js @@ -0,0 +1,69 @@ +/** + * @public + * @function Queue + * @description base class for a queue + */ +class Queue { + + /** + * @public + * @function constructor + * @description initializes the basic array + */ + constructor() { + this._array = []; + } + + /** + * @public + * @function enqueu + * @description enqueues the next item + * @param {object} item - item to enqueue + * @returns {object} this + */ + enqueue(item) { + this._array.push(item); + return this; + } + + /** + * @public + * @function dequeue + * @description dequeues the first item and shifts the rest + * @returns {object} the dequeued item + */ + dequeue() { + return this._array.shift(); + } + + /** + * @public + * @function size + * @returns {number} the length of the array + */ + get size() { + return this._array.length; + } + + /** + * @public + * @function hasAnItem + * @description checks if the queue has a new item + * @returns {bool} true when size is larger then 1 + */ + hasAnItem() { + return this.size > 0; + } + + /** + * @public + * @function removeItems + * @description removes all items from the filter function + * @param {function} filter - filter function to delete shouts from user + */ + removeItems(filter) { + this._array = this._array.filter(filter); + } +}; + +export default Queue; \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044841_index.js b/pool/shard007/JavaScript/0044841_index.js new file mode 100644 index 0000000000000000000000000000000000000000..eba8c9bf1679d6f9601f7aeda29988d122fb5899 --- /dev/null +++ b/pool/shard007/JavaScript/0044841_index.js @@ -0,0 +1,42 @@ + +module.exports.beforeFilters = [ + { + actions : ['new','create','update','edit','distroy'], + method : function(req,res,next) + { + if(req.isAuthenticated()) + next(); + else{ + console.log('The value of the current account is '+req.current_account); + res.redirect('/login'); + } + } + } +] + +module.exports.index = function(req, res){ + res.send('stupid '); +}; + +module.exports.new = function(req, res){ + res.render('post/new',{user:req.user}); +}; + +module.exports.create = function(req, res){ +}; + +module.exports.show = function(req, res){ + res.send('show forum ' + req.params.forum); +}; + +module.exports.edit = function(req, res){ + res.send('edit forum ' + req.params.forum); +}; + +module.exports.update = function(req, res){ + res.send('update forum ' + req.params.forum); +}; + +module.exports.destroy = function(req, res){ + res.send('destroy forum ' + req.params.forum); +}; diff --git a/pool/shard007/JavaScript/0044845_Mixin.js b/pool/shard007/JavaScript/0044845_Mixin.js new file mode 100644 index 0000000000000000000000000000000000000000..646af07e7e483bfac3d5560d849e2cad6c04e661 --- /dev/null +++ b/pool/shard007/JavaScript/0044845_Mixin.js @@ -0,0 +1,180 @@ +var utils = require('./utils.js'); +var React = global.React || require('react'); +var PropTypes = require('prop-types'); + +var convertValidationsToObject = function (validations) { + + if (typeof validations === 'string') { + + return validations.split(/\,(?![^{\[]*[}\]])/g).reduce(function (validations, validation) { + var args = validation.split(':'); + var validateMethod = args.shift(); + + args = args.map(function (arg) { + try { + return JSON.parse(arg); + } catch (e) { + return arg; // It is a string if it can not parse it + } + }); + + if (args.length > 1) { + throw new Error('Formsy does not support multiple args on string validations. Use object format of validations instead.'); + } + + validations[validateMethod] = args.length ? args[0] : true; + return validations; + }, {}); + + } + + return validations || {}; +}; + +module.exports = { + getInitialState: function () { + return { + _value: this._getPristineValue(), + _isRequired: false, + _isValid: true, + _isPristine: true, + _pristineValue: this._getPristineValue(), + _validationError: [], + _externalError: null, + _formSubmitted: false + }; + }, + _getPristineValue: function() { + // matches React https://github.com/facebook/react/blob/d684b1598d16936f9539b48310fa4584193063cb/src/renderers/dom/client/wrappers/ReactDOMInput.js#L79 + return this.props.value != null ? this.props.value : this.props.defaultValue; + }, + contextTypes: { + formsy: PropTypes.object // What about required? + }, + getDefaultProps: function () { + return { + validationError: '', + validationErrors: {} + }; + }, + + componentWillMount: function () { + var configure = function () { + this.setValidations(this.props.validations, this.props.required); + + // Pass a function instead? + this.context.formsy.attachToForm(this); + //this.props._attachToForm(this); + }.bind(this); + + if (!this.props.name) { + throw new Error('Form Input requires a name property when used'); + } + + /* + if (!this.props._attachToForm) { + return setTimeout(function () { + if (!this.isMounted()) return; + if (!this.props._attachToForm) { + throw new Error('Form Mixin requires component to be nested in a Form'); + } + configure(); + }.bind(this), 0); + } + */ + configure(); + }, + + // We have to make the validate method is kept when new props are added + componentWillReceiveProps: function (nextProps) { + this.setValidations(nextProps.validations, nextProps.required); + + }, + + componentDidUpdate: function (prevProps) { + + // If the value passed has changed, set it. If value is not passed it will + // internally update, and this will never run + if (!utils.isSame(this.props.value, prevProps.value)) { + this.setValue(this.props.value); + } + + // If validations or required is changed, run a new validation + if (!utils.isSame(this.props.validations, prevProps.validations) || !utils.isSame(this.props.required, prevProps.required)) { + this.context.formsy.validate(this); + } + }, + + // Detach it when component unmounts + componentWillUnmount: function () { + this.context.formsy.detachFromForm(this); + //this.props._detachFromForm(this); + }, + + setValidations: function (validations, required) { + + // Add validations to the store itself as the props object can not be modified + this._validations = convertValidationsToObject(validations) || {}; + this._requiredValidations = required === true ? {isDefaultRequiredValue: true} : convertValidationsToObject(required); + + }, + + // We validate after the value has been set + setValue: function (value) { + this.setState({ + _value: value, + _isPristine: false + }, function () { + this.context.formsy.validate(this); + //this.props._validate(this); + }.bind(this)); + }, + resetValue: function () { + this.setState({ + _value: this.state._pristineValue, + _isPristine: true + }, function () { + this.context.formsy.validate(this); + //this.props._validate(this); + }); + }, + getValue: function () { + return this.state._value; + }, + hasValue: function () { + return this.state._value !== ''; + }, + getErrorMessage: function () { + var messages = this.getErrorMessages(); + return messages.length ? messages[0] : null; + }, + getErrorMessages: function () { + return !this.isValid() || this.showRequired() ? (this.state._externalError || this.state._validationError || []) : []; + }, + isFormDisabled: function () { + return this.context.formsy.isFormDisabled(); + //return this.props._isFormDisabled(); + }, + isValid: function () { + return this.state._isValid; + }, + isPristine: function () { + return this.state._isPristine; + }, + isFormSubmitted: function () { + return this.state._formSubmitted; + }, + isRequired: function () { + return !!this.props.required; + }, + showRequired: function () { + return this.state._isRequired; + }, + showError: function () { + return !this.showRequired() && !this.isValid(); + }, + isValidValue: function (value) { + return this.context.formsy.isValidValue.call(null, this, value); + //return this.props._isValidValue.call(null, this, value); + } +}; diff --git a/pool/shard007/JavaScript/0044846_webpack.dev.main.config.js b/pool/shard007/JavaScript/0044846_webpack.dev.main.config.js new file mode 100644 index 0000000000000000000000000000000000000000..092fbefbbeb4089846e0ef73babd98b13648802a --- /dev/null +++ b/pool/shard007/JavaScript/0044846_webpack.dev.main.config.js @@ -0,0 +1,82 @@ +const path = require("path"); +const webpack = require("webpack"); +const ExtractTextPlugin = require("extract-text-webpack-plugin"); +const StatsWriterPlugin = require("webpack-stats-plugin").StatsWriterPlugin; +const HtmlWebpackPlugin = require('html-webpack-plugin'); + +const config = { + // Don't attempt to continue if there are any errors. + bail: true, + // We generate sourcemaps in production. This is slow but gives good results. + // You can exclude the *.map files from the build during deployment. + devtool: "source-map", + + target: 'electron-main', + entry: { main: './src/main/main.ts' }, + + output: { + path: path.resolve(__dirname, "../out"), + filename: "static/js/[name].js", + chunkFilename: "static/js/[name].chunk.js", + sourceMapFilename: "[file].map", + publicPath: "./" + }, + + node: { + __dirname: true + }, + + module: { + rules: [ + { + exclude: [/\.html$/, /\.(js|jsx)$/, /\.(ts|tsx)$/, /\.css$/, /\.scss$/, /\.json$/, /\.svg$/], + loader: "url-loader", + query: { + limit: 10000, + name: "static/media/[name].[ext]" + } + }, + { + test: /\.tsx?$/, + use: "ts-loader" + }, + { + test: /\.scss$/, + loader: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: [ + "css-loader?modules&namedExport&camelCase&sourceMap&importLoaders=1&localIdentName=[local]_[hash:base64:8]", + "sass-loader?outputStyle=expanded&sourceMap=true&sourceMapContents=true" + ] + }) + }, + { + test: /\.svg$/, + loader: "file-loader", + query: { + name: "static/media/[name].[ext]" + } + } + ] + }, + + resolve: { + extensions: ['.js', '.ts', '.tsx', '.jsx', '.json'] + }, + + plugins: [ + // This helps ensure the builds are consistent if source hasn't changed: + new webpack.optimize.OccurrenceOrderPlugin(), + // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. + new ExtractTextPlugin("static/css/[name].css"), + // Write out stats file to build directory. + new StatsWriterPlugin({ + transform: function(data, opts) { + let stats = opts.compiler.getStats().toJson({ chunkModules: true }); + return JSON.stringify(stats, null, 2); + } + }) + ] +}; + +module.exports = config; diff --git a/pool/shard007/JavaScript/0044852_autocomplate.js b/pool/shard007/JavaScript/0044852_autocomplate.js new file mode 100644 index 0000000000000000000000000000000000000000..2785a113b5c2defc3514e261f9a37fc7b0e5baf6 --- /dev/null +++ b/pool/shard007/JavaScript/0044852_autocomplate.js @@ -0,0 +1,111 @@ +/** + * Created by cqb on 2014/9/18. + */ +(function(){ + + function init(ele){ + var timer; + $(ele).bind("keyup", function(e){ + if(timer){ + window.clearTimeout(timer); + } + timer = window.setTimeout(function(){ + filterData(ele); + }, 300); + }); + $(document).bind("click.autocomplate", function(e){ + if($(e.target).parent().hasClass("autocomplate_dropdown")){ + return false; + } + var dropdown = $.data(ele, "autocomplate").dropdown; + if(dropdown){ + dropdown.hide(); + } + }); + + createDropdown(ele); + } + + function createDropdown(ele){ + var options = $.data(ele, "autocomplate").options; + var data = options.data; + + var dropdown = $("
"); + $.data(ele, "autocomplate").dropdown = dropdown; + var w = $(ele).width(); + var h = $(ele).outerHeight(true)-2; + var pos = $(ele).position(); + var pl = parseFloat($(ele).offsetParent().css("padding-left")); + dropdown.css({ + "position": "absolute", + "top": h, + "left": pos.left-pl, + "width": w, + "max-height": 200, + "min-height": 20 + }); + $(ele).after(dropdown); + $(ele).parent().css("position", "relative"); + + data.forEach(function(item){ + var el = $('
'+item+'
'); + dropdown.append(el); + }); + + dropdown.children("div").bind("click", function(){ + $(ele).focus(); + var theval = $(this).data("value"); + $(ele).val(theval); + dropdown.hide(); + }); + } + + function filterData(ele){ + var val = $(ele).val(); + var options = $.data(ele, "autocomplate").options; + + showList(ele, val); + } + + function showList(ele, val){ + var dropdown = $.data(ele, "autocomplate").dropdown; + dropdown.show(); + + dropdown.children("div").each(function(){ + var text = $(this).data("value"); + if(text.indexOf(val) == -1){ + $(this).hide(); + }else { + $(this).show(); + } + }); + } + + $.fn.autocomplate = function(options, param){ + if (typeof options == 'string'){ + return $.fn.autocomplate.methods[options](this, param); + } + + options = options || {}; + + return this.each(function(){ + var state = $.data(this, 'autocomplate'); + if (state){ + $.extend(state.options, options); + } else { + state = $.data(this, 'autocomplate', { + options: $.extend({}, $.fn.autocomplate.defaults, options) + }); + init(this); + } + }); + } + + $.fn.autocomplate.methods = { + + } + + $.fn.autocomplate.defaults = { + + } +})(); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044857_document_write_restore.js b/pool/shard007/JavaScript/0044857_document_write_restore.js new file mode 100644 index 0000000000000000000000000000000000000000..314d1fce78cfae9a3603d6c67cb295fc160e89c7 --- /dev/null +++ b/pool/shard007/JavaScript/0044857_document_write_restore.js @@ -0,0 +1,17 @@ +test("document_write_restore.php", function (assert, document) { + var initialElements = document.getElementsByTagName("h1"); + assert.equal( + initialElements.length, + 1, + "There should be one h1 on the page before document.write" + ); + + document.defaultView.callDocumentWrite(); + + var elements = document.getElementsByTagName("h1"); + assert.equal( + elements.length, + 0, + "There should be no h1 on the page after document.write" + ); +}); diff --git a/pool/shard007/JavaScript/0044860_spec.js b/pool/shard007/JavaScript/0044860_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..867ee7705c24161f4056cfff3082242c14e99894 --- /dev/null +++ b/pool/shard007/JavaScript/0044860_spec.js @@ -0,0 +1,382 @@ +var Spec = function() { + this.tags = { + // Stores arbitrary define statements that appear at the top of the + // spec file. Each entry will be prepended with the %define directive. + defines: [], + + // The name tag is used to define the name of the software being + // packaged. In most (if not all) cases, the name used for a package + // should be identical in spelling and case to the software being + // packaged. The name cannot contain any whitespace: If it does, RPM + // will only use the first part of the name (up to the first space). + name: null, + + // The version tag defines the version of the software being packaged. + // The version specified should be as close as possible to the format + // of the original software's version. In most cases, there should be + // no problem specifying the version just as the software's original + // developer did. However, there is a restriction. There can be no + // dashes in the version. Spaces in the version will also cause + // problems, in that anything after the first space will be ignored by + // RPM. Bottom line: Stick with alphanumeric characters and periods, + // and you'll never have to worry about it. + version: null, + + // The release tag can be thought of as the package's version. The + // release is traditionally an integer — for example, when a specific + // piece of software at a particular version is first packaged, the + // release should be "1". If it is necessary to repackage that software + // at the same version, the release should be incremented. When a new + // version of the software becomes available, the release should drop + // back to "1" when it is first packaged. + release: null, + + // Specifies the achitecture for the package and is also included in + // the final RPM filename. Use 'noarch' for packages that are + // achitecture independent. + buildArch: null, + + // Can span multiple lines. If a line starts with a space, that line + // will be displayed verbatim by RPM. Lines that do not start with a + // space are assumed to be part of a paragraph and will be formatted by + // RPM. It's even possible to mix and match formatted and unformatted + // lines. + description: null, + + // The summary tag is used to define a one-line description of the + // packaged software. + summary: null, + + // The license tag is used to define the license terms applicable to the + // software being packaged. This is also known as the copyright tag. + license: null, + + // The epoch tag is another part of RPM's dependency upgrade processing. + // Consult the documentation on the RPM spec for its use. It should be + // an integer value. + epoch: null, + + // The distribution tag is used to define a group of packages, of which + // this package is a part. + distribution: null, + + // The vendor tag is used to define the name of the entity that is + // responsible for packaging the software. Normally, this would be the + // name of an organization. + vendor: null, + + // The url tag is used to define a Uniform Resource Locator that can be + // used to obtain additional information about the packaged software. At + // present, RPM doesn't actively make use of this tag. The data is + // stored in the package however, and will be written into RPM's + // database when the package is installed. + url: null, + + // The group tag is used to group packages together by the types of + // functionality they provide. The group specification looks like a path + // and is similar in function, in that it specifies more general + // groupings before more detailed ones. + group: null, + + // The packager tag is used to hold the name and contact information for + // the person or persons who built the package. Normally, this would be + // the person that actually built the package, or in a larger + // organization, a public relations contact. + packager: null, + + // The requires tag is used to alert RPM to the fact that the package + // needs to have certain capabilities available in order to operate + // properly. These capabilities refer to the name of another package, or + // to a virtual package provided by one or more packages that use the + // provides tag. When the requires tag references a package name, + // version comparisons may also be included by following the package + // name with <, >, =, >=, or <=, and a version specification. To get + // even more specific, a package's release may be included as well. + requires: [], + + // The buildRequires tag is used to alert RPM to the fact that the + // package needs to have certain capabilities available in order to + // build properly. These capabilities refer to the name of another + // package, or to a virtual package provided by one or more packages + // that use the provides tag. When the requires tag references a + // package name, version comparisons may also be included by following + // the package name with <, >, =, >=, or <=, and a version + // specification. To get even more specific, a package's release may be + // included as well. + buildRequires: [], + + // The provides tag is used to alert RPM to the fact that the package + // will provide a virtual package. + provides: [], + + // The conflicts tag is the logical complement to the requires tag. The + // requires tag is used to specify what packages must be present in + // order for the current package to operate properly. The conflicts tag + // is used to specify what packages cannot be installed if the current + // package is to operate properly. + conflicts: [], + + // The autoreqprov, autoreq, and autoprov tags are used to control the + // automatic dependency processing performed when the package is being + // built. When both of these are set to false, the AutoReqProv tag is + // instead set to 'no'. + autoReq: true, + autoProv: true, + + // The excludearch tag directs RPM to ensure that the package does not + // attempt to build on the excluded architecture(s). One or more + // architectures may be specified after the excludearch tag, separated + // by either spaces or commas. + excludeArchs: [], + + // The exclusivearch tag is used to direct RPM to ensure the package is + // only built on the specified architecture(s). One or more + // architectures may be specified after the exclusivearch tag, separated + // by either spaces or commas. + exclusiveArchs: [], + + // The excludeos tag is used to direct RPM to ensure that the package + // does not attempt to build on the excluded operating system(s). + excludeOS: [], + + // The exclusiveos tag has the same syntax as excludeos, but it has the + // opposite logic. The exclusiveos tag is used to denote which operating + // system(s) should only be be permitted to build the package. + exclusiveOS: [], + + // The prefix tag is used when a relocatable package is to be built. + // A relocatable package can be installed normally or can be installed + // in a user-specified directory, by using RPM's --prefix install-time + // option. The data specified after the prefix tag should be the part of + // the package's path that may be changed during installation. + prefix: null, + + // The buildroot tag is used to define an alternate build root. The name + // is a bit misleading, as the build root is actually used when the + // software is installed during the build process. In order for a build + // root to be defined and actually used, a number of issues must be + // taken into account. + // See http://www.rpm.org/max-rpm-snapshot/ch-rpm-anywhere.html + buildRoot: null, + + // Effectively points to the source locations provided by the + // developer(s). It is best to read about this at: + // http://www.rpm.org/max-rpm-snapshot/s1-rpm-inside-tags.html + sources: [], + + // The nosource tag is used to direct RPM to omit one or more source + // files from the source package. More information at: + // http://www.rpm.org/max-rpm-snapshot/s1-rpm-inside-tags.html + noSources: [], + + // The patch tag is used to identify which patches are associated with + // the software being packaged. The patch files are kept in RPM's + // SOURCES directory, so only the name of the patch file should be + // specified. + patches: [], + + // Just like the nosource tag, the nopatch tag is used to direct RPM to + // omit something from the source package. In the case of nosource, that + // "something" was one or more sources. For the nopatch tag, the + // "something" is one or more patches. + noPatches: [] + }; + + this.scripts = { + // The %prep script is the first script RPM executes during a build. + // Prior to the %prep script, RPM has performed preliminary consistency + // checks, such as whether the spec file's source tag points to files + // that actually exist. Just prior to passing control over to the %prep + // script's contents, RPM changes directory into RPM's build area. + // At that point, it is the responsibility of the %prep script to: + // * Create the top-level build directory. + // * Unpack the original sources into the build directory. + // * Apply patches to the sources, if necessary. + // * Perform any other actions required to get the sources in a + // ready-to-build state. + // It is useful to be aware of the %setup and %patch macros that can be + // used within %prep. See: + // http://www.rpm.org/max-rpm-snapshot/s1-rpm-inside-macros.html + prep: [], + + // The %build script picks up where the %prep script left off. Once the + // %prep script has gotten everything ready for the build, the %build + // script is usually somewhat anti-climactic — normally invoking make, + // maybe a configuration script, and little else. + build: [], + + // The environment in which the %install script executes is identical + // to the other scripts. Like the other scripts, the %install script's + // working directory is set to the software's top-level directory. + install: [], + + // The environment in which the %check script executes is identical to + // the other scripts. Like the other scripts, the %check script's + // working directory is set to the software's top-level directory. + // This script's primary function is to run the test suite of the built + // software to ensure that the binaries work correctly. Some typical + // commands to run in this script are make test or make check. + check: [], + + // The %clean script, as the name implies, is used to clean up the + // software's build directory tree. RPM normally does this for you, but + // in certain cases (most notably in those packages that use a build + // root) you'll need to include a %clean script. + clean: [], + + // The %pre script executes just before the package is to be installed. + preInstall: [], + + // The %post script executes after the package has been installed. + // If a package uses a %post script to perform some function, quite + // often it will include a %postun script that performs the inverse of + // the %post script, after the package has been removed. + postInstall: [], + + // If there's a time when your package needs to have one last look + // around before the user erases it, the place to do it is in the + // %preun script. Anything that a package needs to do immediately prior + // to RPM taking any action to erase the package, can be done here. + preUninstall: [], + + // The %postun script executes after the package has been removed. It + // is the last chance for a package to clean up after itself. + postUninstall: [], + + // The %verifyscript executes whenever the installed package is + // verified by RPM's verification command. The contents of this script + // is entirely up to the package builder, but in general the script + // should do whatever is necessary to verify the package's proper + // installation. Since RPM automatically verifies the existence of a + // package's files, along with other file attributes, the %verifyscript + // should concentrate on different aspects of the package's + // installation. + verify: [] + }; + + this.files = { + defaultAttributes: null, + list: [] + }; + + this.other = { + changelog: [] + }; +}; + +Spec.prototype._bulkArgAdd = function(arr, args) { + for (var i = 0; i < args.length; i++) { + arr.push(args[i]); + } +}; + +Spec.prototype.addDefines = function() { + this._bulkArgAdd(this.tags.defines, arguments); +}; + +Spec.prototype.addRequirements = function() { + this._bulkArgAdd(this.tags.requires, arguments); +}; + +Spec.prototype.addBuildRequirements = function() { + this._bulkArgAdd(this.tags.buildRequires, arguments); +}; + +Spec.prototype.addProvides = function() { + this._bulkArgAdd(this.tags.provides, arguments); +}; + +Spec.prototype.addConflicts = function() { + this._bulkArgAdd(this.tags.conflicts, arguments); +}; + +Spec.prototype.addExcludeArchs = function() { + this._bulkArgAdd(this.tags.excludeArchs, arguments); +}; + +Spec.prototype.addExclusiveArchs = function() { + this._bulkArgAdd(this.tags.exclusiveArchs, arguments); +}; + +Spec.prototype.addExcludeOS = function() { + this._bulkArgAdd(this.tags.excludeOS, arguments); +}; + +Spec.prototype.addExclusiveOS = function() { + this._bulkArgAdd(this.tags.exclusiveOS, arguments); +}; + +Spec.prototype.addSources = function() { + this._bulkArgAdd(this.tags.sources, arguments); +}; + +Spec.prototype.addNoSources = function() { + this._bulkArgAdd(this.tags.noSources, arguments); +}; + +Spec.prototype.addPatches = function() { + this._bulkArgAdd(this.tags.patches, arguments); +}; + +Spec.prototype.addNoPatches = function() { + this._bulkArgAdd(this.tags.noPatches, arguments); +}; + +Spec.prototype.addPrepScripts = function() { + this._bulkArgAdd(this.scripts.prep, arguments); +}; + +Spec.prototype.addBuildScripts = function() { + this._bulkArgAdd(this.scripts.build, arguments); +}; + +Spec.prototype.addInstallScripts = function() { + this._bulkArgAdd(this.scripts.install, arguments); +}; + +Spec.prototype.addCheckScripts = function() { + this._bulkArgAdd(this.scripts.check, arguments); +}; + +Spec.prototype.addCleanScripts = function() { + this._bulkArgAdd(this.scripts.clean, arguments); +}; + +Spec.prototype.addPreInstallScripts = function() { + this._bulkArgAdd(this.scripts.preInstall, arguments); +}; + +Spec.prototype.addPostInstallScripts = function() { + this._bulkArgAdd(this.scripts.postInstall, arguments); +}; + +Spec.prototype.addPreUninstallScripts = function() { + this._bulkArgAdd(this.scripts.preUninstall, arguments); +}; + +Spec.prototype.addPostUninstallScripts = function() { + this._bulkArgAdd(this.scripts.postUninstall, arguments); +}; + +Spec.prototype.addVerifyScripts = function() { + this._bulkArgAdd(this.scripts.verify, arguments); +}; + +Spec.prototype.addFiles = function() { + this._bulkArgAdd(this.files.list, arguments); +}; + +Spec.prototype.setDefaultAttributes = function(attrs) { + this.files.defaultAttributes = { + mode: attrs.mode || null, + user: attrs.user || null, + group: attrs.group || null, + dirMode: attrs.dirMode || null + }; +}; + +Spec.prototype.addChangelogs = function() { + this._bulkArgAdd(this.other.changelog, arguments); +}; + +module.exports = Spec; diff --git a/pool/shard007/JavaScript/0044862_4000_mapping_-_dimensions.js b/pool/shard007/JavaScript/0044862_4000_mapping_-_dimensions.js new file mode 100644 index 0000000000000000000000000000000000000000..185b3045d85bd489fff3fccb2044bfacbf02c5fa --- /dev/null +++ b/pool/shard007/JavaScript/0044862_4000_mapping_-_dimensions.js @@ -0,0 +1,58 @@ +"use strict"; +/** + * map the dimensions of the ontologies to SynSets + * + * output + * - "mapDimension" ... list of SynSets + */ + +// includes +var Q = require( 'q' ), + Log = require( './util/log.js' ), + OntoStore = require( './util/OntoStore' ), + mapObjects = require( './util/mapObjects' ); + +// local settings +var localCfg = { + moduleName: 'mapDimension', + moduleKey: '4000' + }, + log = function( msg, type ) { + Log( localCfg.moduleName, msg, type ); + }; + + +function mapDimensions() { + + // log + log( 'matching dimensions' ); + + // get dimension list + var dimensions = OntoStore.getResult( 'dimension' ); + + // do the mapping + var mappedDimensions = mapObjects({ + values: dimensions, + manual: [ '4000 mapDimension.csv', '4000 mapDimension_ext.csv' ] + }, log ); + + // save the results + OntoStore.storeResult( localCfg.moduleKey, localCfg.moduleName, mappedDimensions ); + + // log output + log( 'finished mapping dimensions' ); + log( ' dimensions: ' + dimensions.length ); + log( ' synonym sets: ' + mappedDimensions.length ); + + // done + return Q( true ); +} + +/* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Export XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ + +// if called directly, execute, else export +if(require.main === module) { + mapDimensions().done(); +} else { + module.exports = mapDimensions; +} diff --git a/pool/shard007/JavaScript/0044863_user.js b/pool/shard007/JavaScript/0044863_user.js new file mode 100644 index 0000000000000000000000000000000000000000..8d6e885c76d53cd7eddeacc5958ea7684768444f --- /dev/null +++ b/pool/shard007/JavaScript/0044863_user.js @@ -0,0 +1,13 @@ +angular +.module('eventMatchApp') + .factory('User', User); +User.$inject = ['$resource']; +function User ($resource) { + var url = 'http://eventmatch.herokuapp.com/api/'; + var UserResource = $resource(url + 'users/:id', {id: '@_id'}, { + 'update': { method: 'PUT'}, + 'login': { url: url + 'login', method: 'POST'}, + 'signup': { url: url + 'join', method: 'POST' } + }) + return UserResource; +} diff --git a/pool/shard007/JavaScript/0044864_spec.js b/pool/shard007/JavaScript/0044864_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..724ae3fafd372e33082a570798fdeb528972c124 --- /dev/null +++ b/pool/shard007/JavaScript/0044864_spec.js @@ -0,0 +1,87 @@ +describe('the daterange directive', function() { + + var $ngCompile, $ngRootScope; + + beforeEach(module('lfzBootstrapDaterangepicker')); + + beforeEach(inject(function($compile, $rootScope) { + $ngCompile = $compile; + $ngRootScope = $rootScope; + })); + + it('creates an instance of daterangepicker', function() { + var element = $ngCompile('')($ngRootScope); + expect(element.data('daterangepicker')).toBeDefined(); + }); + + it('creates an instance with default values', function() { + + var element = $ngCompile('')($ngRootScope); + $ngRootScope.$apply(); + + expect(element.data('daterangepicker').startDate.format('YYYY-MM-DD')).toBe(moment().format('YYYY-MM-DD')); + expect(element.data('daterangepicker').endDate.format('YYYY-MM-DD')).toBe(moment().format('YYYY-MM-DD')); + expect(element.data('daterangepicker').format).toBe('YYYY-MM-DD'); + expect(element.data('daterangepicker').separator).toBe(' - '); + expect(element.data('daterangepicker').minDate).toBe(false); + expect(element.data('daterangepicker').maxDate).toBe(false); + expect(element.data('daterangepicker').dateLimit).toBe(false); + expect(JSON.stringify(element.data('daterangepicker').ranges)).toBe(JSON.stringify({})); + + }); + + it('creates an instance with provided values', function() { + + var normalized = 'YYYY-MM-DD', + startDate = '2013-09-10', + endDate = '2013-09-20', + format = 'L', + separator = '/', + minDate = '2013-09-05', + maxDate = '2013-09-25', + limitAmount = 1, + limitUnit = 'week', + element = $ngCompile('')($ngRootScope); + + $ngRootScope.dates = { + startDate: startDate, + endDate: endDate + }; + + $ngRootScope.$apply(); + + expect(element.data('daterangepicker').startDate.format(normalized)).toBe(moment(startDate).format(normalized)); + expect(element.data('daterangepicker').endDate.format(normalized)).toBe(moment(endDate).format(normalized)); + expect(element.data('daterangepicker').format).toBe('L'); + expect(element.data('daterangepicker').separator).toBe('/'); + expect(element.data('daterangepicker').minDate.format(normalized)).toBe(moment(minDate).format(normalized)); + expect(element.data('daterangepicker').maxDate.format(normalized)).toBe(moment(maxDate).format(normalized)); + expect(element.data('daterangepicker').dateLimit.asSeconds()).toBe(moment.duration(limitAmount, limitUnit).asSeconds()); + + }); + + it('passes on ranges from scope to daterangepicker instance', function() { + + $ngRootScope.ranges = { + 'Today': [moment().startOf('day'), moment()], + // accepts string formatted dates + 'Yesterday': [moment().subtract(1, 'days').format('YYYY-MM-DD'), moment().subtract(1, 'days').format('YYYY-MM-DD')] + }; + + var element = $ngCompile('')($ngRootScope); + + expect(element.data('daterangepicker').ranges.Today).not.toBeUndefined(); + expect(element.data('daterangepicker').ranges.Today[0].format('YYYY-MM-DD')).toBe(moment().startOf('day').format('YYYY-MM-DD')); + expect(element.data('daterangepicker').ranges.Today[1].format('YYYY-MM-DD')).toBe(moment().format('YYYY-MM-DD')); + expect(element.data('daterangepicker').ranges.Yesterday).not.toBeUndefined(); + expect(element.data('daterangepicker').ranges.Yesterday[0].format('YYYY-MM-DD')).toBe(moment().subtract(1, 'days').format('YYYY-MM-DD')); + expect(element.data('daterangepicker').ranges.Yesterday[1].format('YYYY-MM-DD')).toBe(moment().subtract(1, 'days').format('YYYY-MM-DD')); + + }); + + it('passes opens option from attributes to daterangepicker instance', function() { + var element = $ngCompile('')($ngRootScope); + expect(element.data('daterangepicker').opens).toBe('left'); + }); + +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044868_server.js b/pool/shard007/JavaScript/0044868_server.js new file mode 100644 index 0000000000000000000000000000000000000000..21b41549d49c96f9611afcfacf9d7d2c25fe25f6 --- /dev/null +++ b/pool/shard007/JavaScript/0044868_server.js @@ -0,0 +1,14 @@ +var http = require('http'); +var fs = require('fs'); + +var server = http.createServer(function(req, res){ + console.log(req.url); + res.writeHead(200, {'Content-Type': 'text/html'}); + // var leitor = "fs.createReadStream( __dirname + '/index.html', 'utf-8');"; + var leitor = fs.createReadStream( __dirname + '/home.html', 'utf-8'); + + leitor.pipe(res); +}); + +server.listen(3000, '127.0.0.1'); +console.log("req.url"); diff --git a/pool/shard007/JavaScript/0044874_code-frame.js b/pool/shard007/JavaScript/0044874_code-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..b123efb6fd83347fec6656d5d770d024b15f0a3d --- /dev/null +++ b/pool/shard007/JavaScript/0044874_code-frame.js @@ -0,0 +1,91 @@ +var lineNumbers = require("line-numbers"); +var repeating = require("repeating"); +var jsTokens = require("js-tokens"); +var esutils = require("esutils"); +var chalk = require("chalk"); +var ary = require("lodash/function/ary"); + +var defs = { + string: chalk.red, + punctuation: chalk.white.bold, + operator: chalk.white.bold, + curly: chalk.green, + parens: chalk.blue.bold, + square: chalk.yellow, + name: chalk.white, + keyword: chalk.cyan, + number: chalk.magenta, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.inverse +}; + +var newline = /\r\n|[\n\r\u2028\u2029]/; + +var highlight = function (text) { + var tokenType = function (match) { + var token = jsTokens.matchToToken(match); + if (token.type === "name" && esutils.keyword.isKeywordES6(token.value)) { + return "keyword"; + } + + if (token.type === "punctuation") { + switch (token.value) { + case "{": + case "}": + return "curly"; + case "(": + case ")": + return "parens"; + case "[": + case "]": + return "square"; + } + } + + return token.type; + }; + + return text.replace(jsTokens, function (match) { + var type = tokenType(arguments); + if (type in defs) { + var colorize = ary(defs[type], 1); + return match.split(newline).map(colorize).join("\n"); + } + return match; + }); +}; + +module.exports = function (lines, lineNumber, colNumber) { + colNumber = Math.max(colNumber, 0); + + if (chalk.supportsColor) { + lines = highlight(lines); + } + + lines = lines.split(newline); + + var start = Math.max(lineNumber - 3, 0); + var end = Math.min(lines.length, lineNumber + 3); + + if (!lineNumber && !colNumber) { + start = 0; + end = lines.length; + } + + return "\n" + lineNumbers(lines.slice(start, end), { + start: start + 1, + before: " ", + after: " | ", + transform: function (params) { + if (params.number !== lineNumber) { + return; + } + if (colNumber) { + params.line += "\n" + params.before + repeating(" ", params.width) + + params.after + repeating(" ", colNumber - 1) + "^"; + } + params.before = params.before.replace(/^./, ">"); + } + }).join("\n"); +}; diff --git a/pool/shard007/JavaScript/0044875_test.js b/pool/shard007/JavaScript/0044875_test.js new file mode 100644 index 0000000000000000000000000000000000000000..901134120b8dd739d73b7ce003560e70e4271292 --- /dev/null +++ b/pool/shard007/JavaScript/0044875_test.js @@ -0,0 +1,66 @@ +var libPath = process.env.JS_COV ? "../lib-cov" : "../lib"; +var srcPath = "../src"; + +var abhisekpFCCbasicBonfireSolutions = require(srcPath + + "/fcc-basic-bonfire-solutions"), + apFCCbbfs = abhisekpFCCbasicBonfireSolutions; + +var chai = require("chai"), + should = chai.should, + expect = chai.expect, + assert = chai.assert; + +describe("# abhisekp Basic Bonfires", function() { + describe("## 01. Bonfire: Meet Bonfire", function() { + + describe("### Using meetBonfire()", function() { + it("meetBonfire() returns a boolean", function() { + assert.isBoolean(apFCCbbfs.meetBonfire(1)); + }); + + it("always returns true", function() { + assert.isTrue(apFCCbbfs.meetBonfire("Empty")); + }); + }); + + }); + + describe("## 02. Bonfire: Reverse a String", function() { + + describe("### Using reveseString()", function() { + it("reverseString() returns a string", function() { + assert.isString(apFCCbbfs.reverseString("")); + }); + + it("reverses given strings", function() { + assert.strictEqual(apFCCbbfs.reverseString("hello"), "olleh", + "'hello' reverses to 'olleh"); + assert.strictEqual(apFCCbbfs.reverseString("Howdy"), "ydwoH", + "'Howdy' reverses to 'ydwoH"); + assert.strictEqual(apFCCbbfs.reverseString("Greetings from Earth"), + "htraE morf sgniteerG", + "'Greetings from Earth' reverses to 'htraE morf sgniteerG"); + }); + }); + + }); + + describe("## 03. Bonfire: Factorialize a Number", function() { + describe("### Using factorializeRecursive()", function() { + it("factorializeRecursive() returns a number", function() { + assert.isNumber(apFCCbbfs.factorializeRecursive(1)); + }); + + it("factorializes given values", function() { + assert.strictEqual(apFCCbbfs.factorializeRecursive(5), 120, + "5! factorial results 120"); + assert.strictEqual(apFCCbbfs.factorializeRecursive(10), 3628800, + "10! factorial results 3628800"); + assert.strictEqual(apFCCbbfs.factorializeRecursive(20), + 2432902008176640000, + "20! factorial results 2432902008176640000"); + }); + }); + }); + +}); diff --git a/pool/shard007/JavaScript/0044878_prep-operation.js b/pool/shard007/JavaScript/0044878_prep-operation.js new file mode 100644 index 0000000000000000000000000000000000000000..9f3583ff721288a02f79e2f4c289548acccb367d --- /dev/null +++ b/pool/shard007/JavaScript/0044878_prep-operation.js @@ -0,0 +1,77 @@ +const _ = require('lodash') +const path = require('path') +const Directory = require('kelex/lib/directory') +const pluginConfig = require('../config.json') +const {generateRoutesConfig} = require('./route') + +module.exports = (operation) => { + try{ + const thisRootDir = path.join(__dirname, '../') + const thisDistDir = path.join(thisRootDir, '_dist', operation.app.name) + const config = { + distDir: thisDistDir, + clientDir: pluginConfig.clientDir, + port: 'PORT', + fallbackPort: 3000, + useFallbackPort: true, + html: { + minification: { + minifyCSS: true, + removeAttributeQuotes: true, + removeComments: true, + removeRedundantAttributes: true, + collapseWhitespace: true + } + } + } + + _.merge(config, normalisedConfig(operation.plugin.app.config, operation)) + + operation.plugin.app.config = config + + _.extend(operation.plugin.app, { + get port () { + let port = config.port + + if (typeof port === 'string') { + if (process.env[port] === undefined && !config.useFallbackPort) { + throw new Error(`There is no environment variable named '${port}'`) + } + port = process.env[port] + } + + if (!port) { + port = config.fallbackPort + } + + return port + }, + generateRoutesConfig ({watch = false} = {}) { + generateRoutesConfig(operation.app, {watch}) + } + }) + + operation.app.dist.dir.path = config.distDir + operation.app.dist.wwwDir.path = path.join(config.distDir, pluginConfig.distWwwDir) + operation.app.dist.libDir.path = path.join(config.distDir, pluginConfig.distLibDir) + operation.app.client.dir.path = path.join(operation.app.dir.path, config.clientDir) + + operation.set({ + 'dev.server': () => require('../server/dev-server')(operation), + 'prod.server': () => require('../server/prod-server')(operation), + 'compiled.dev.server': () => require(path.resolve(operation.app.dist.dir.path, 'server/dev-server'))(operation), + 'compiled.prod.server': () => require(path.resolve(operation.app.dist.dir.path, 'server/prod-server'))(operation), + }) + } + catch(error) { + operation.indicate.failure(error) + } +} + +function normalisedConfig (config, operation) { + if (config.distDir) { + config.distDir = path.join(operation.app.dir.path, config.distDir) + } + + return config +} diff --git a/pool/shard007/JavaScript/0044879_binaryServerDemo.js b/pool/shard007/JavaScript/0044879_binaryServerDemo.js new file mode 100644 index 0000000000000000000000000000000000000000..4e960430f52a6b6a7cd093dea6508a5f5f63c4b7 --- /dev/null +++ b/pool/shard007/JavaScript/0044879_binaryServerDemo.js @@ -0,0 +1,66 @@ +var fs=require('fs') +var http = require('http') + +var Surku=require('../Surku.js') +var Demo=new Surku() +console.error('Initializing new Surku with default config.') + +var timeout=10 + +var mime='image/png' +var tagtype='img' +var port=1337 + +if(process.argv[2]) + var sampleFolder=process.argv[2] +if(process.argv[3]) + var mime=process.argv[3] +if(process.argv[4]) + var timeout=process.argv[4] +if(mime.indexOf('video/')==0) + tagtype='video' + +if(!fs.existsSync(sampleFolder)){ + console.log("You must provide sample folder.") +} + +var clientFile='' + +'' + +'' + +'<'+tagtype+' id="test" autoplay="true"' + +'src="/img1"' + +'onended="newTestCase"' + +'onload="newTestCase"' + +'onerror="newTestCase">' + +'' + +'' + +console.error('Checking the sample folder: '+sampleFolder) +var files=fs.readdirSync(sampleFolder) +console.error('Found '+files.length+' sample files') + +var server = http.createServer(function(request, response) { + if(request.url=='/'){ + response.writeHead(200,{'Content-Type':'text/html'}); + response.write(clientFile) + response.end(); + } + else if(request.url.indexOf('/img')==0){ + response.writeHead(200,{'Content-Type':mime}); + response.write(Demo.generateTestCase(fs.readFileSync(sampleFolder+'/'+files[Math.floor(Math.random()*files.length)]))) + response.end(); + } +}); +server.listen(port, function(err) { + console.log('Server listening port :'+port) +}); + diff --git a/pool/shard007/JavaScript/0044884_Renderbuffer.js b/pool/shard007/JavaScript/0044884_Renderbuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..bc6dacdad7e88cc8e581ab3f2d0ccfe3a11cfddf --- /dev/null +++ b/pool/shard007/JavaScript/0044884_Renderbuffer.js @@ -0,0 +1,203 @@ +/*global context: false */ + +/** + * @module context + */ + +/** + * Wraps a GL renderbuffer. + * + * Instancing an object of this class is equivalent to calling the GL function + * `createRenderbuffer`. The returned `WebGLRenderbuffer` object is extended by + * OOGL-specific features and returned by the `Renderbuffer` constructor. + * + * @class context.Renderbuffer + * @constructor + * @example + * var oogl = new OOGL.Context('canvas'); + * var renderbuffer = new oogl.Renderbuffer(); + */ +context.Renderbuffer = function () { + var renderbuffer = context.createRenderbuffer(); + + /** + * Indicates whether this is a valid GL renderbuffer. + * + * `gl.isRenderbuffer` equivalent. + * + * @method is + * @return {Boolean} `true` is this is a valid GL renderbuffer, `false` + * otherwise. + * @example + * if (renderbuffer.is()) { + * // ... + */ + renderbuffer.is = function () { + return context.isRenderbuffer(renderbuffer); + }; + + /** + * Queries a renderbuffer-related parameter. + * + * `gl.getRenderbufferParameter` equivalent. + * + * @method getParameter + * @param name {String} TODO + * @return {Mixed} TODO + * @example + * TODO + */ + renderbuffer.getParameter = function (name) { + return context.getRenderbufferParameter(context.RENDERBUFFER, name); + }; + + /** + * TODO + * + * @method getWidth + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getWidth = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_WIDTH); + }; + + /** + * TODO + * + * @method getHeight + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getHeight = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_HEIGHT); + }; + + /** + * TODO + * + * @method getInternalFormat + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getInternalFormat = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_INTERNAL_FORMAT); + }; + + /** + * TODO + * + * @method getRedSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getRedSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_RED_SIZE); + }; + + /** + * TODO + * + * @method getGreenSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getGreenSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_GREEN_SIZE); + }; + + /** + * TODO + * + * @method getBlueSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getBlueSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_BLUE_SIZE); + }; + + /** + * TODO + * + * @method getAlphaSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getAlphaSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_ALPHA_SIZE); + }; + + /** + * TODO + * + * @method getDepthSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getDepthSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_DEPTH_SIZE); + }; + + /** + * TODO + * + * @method getStencilSize + * @return {Number} TODO + * @example + * TODO + */ + renderbuffer.getStencilSize = function () { + return context.getRenderbufferParameter(context.RENDERBUFFER, context.RENDERBUFFER_STENCIL_SIZE); + }; + + /** + * Binds this renderbuffer. + * + * `gl.bindRenderbuffer` equivalent. + * + * @method bind + * @example + * renderbuffer.bind(); + */ + renderbuffer.bind = function () { + context.bindRenderbuffer(context.RENDERBUFFER, renderbuffer); + }; + + /** + * TODO + * + * @method storage + * @param internalFormat {Number} TODO + * @param width {Number} TODO + * @param height {Number} TODO + * @example + * TODO + */ + renderbuffer.storage = function (internalFormat, width, height) { + context.renderbufferStorage(context.RENDERBUFFER, internalFormat, width, height); + }; + + /** + * Deletes this renderbuffer. + * + * `gl.deleteRenderbuffer` equivalent. + * + * @method _delete + * @example + * renderbuffer._delete(); + */ + renderbuffer._delete = function () { + context.deleteRenderbuffer(renderbuffer); + }; + + return renderbuffer; +}; diff --git a/pool/shard007/JavaScript/0044885_mass_function.js b/pool/shard007/JavaScript/0044885_mass_function.js new file mode 100644 index 0000000000000000000000000000000000000000..36518e441dd86ce7b271de46045b2f4f51ed70d7 --- /dev/null +++ b/pool/shard007/JavaScript/0044885_mass_function.js @@ -0,0 +1,18 @@ +document.getElementById('button_mass').onclick = function mass(banana_field, metric_field, imperial_field){ + var banana_mass, metric_mass, imperial_mass; + if(banana_field != 0){ + metric_mass = 113.398 * banana_field; + imperial_mass = 4 * banana_field; + return metric_mass, imperial_mass, banana_field; + } + else if(metric_field != 0){ + banana_mass = (metric_field / 113.398); + imperial_mass = (metric_field * .035274); + return banana_mass, imperial_mass, metric_field; + } + else(imperial_field != 0){ + banana_mass = (imperial_field / 4); + metric_mass = (imperial_field * 28.3495); + return banana_mass, metic_mass, imperial_field; + } +} \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044887_proxy.test.js b/pool/shard007/JavaScript/0044887_proxy.test.js new file mode 100644 index 0000000000000000000000000000000000000000..53a7d0185548ad27bb9e6cd08de2970633497523 --- /dev/null +++ b/pool/shard007/JavaScript/0044887_proxy.test.js @@ -0,0 +1,138 @@ +import { + proxyStringToObject, + proxyObjectToString, + agentFromProxy +} from '../lib/proxy' + +jest.mock('https-proxy-agent', () => { + const mock = jest.fn() + return class mocked { + constructor (args) { + this.mock = mock + mock(args) + } + } +}) + +test('proxyString with basic auth, with protocol', () => { + const proxyString = 'http://foo:bar@127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + + const expectedStringified = 'foo:bar@127.0.0.1:8213' + const expectedParsed = { + host: '127.0.0.1', + port: 8213, + isHttps: false, + auth: { + username: 'foo', + password: 'bar' + } + } + + expect(parsed).toEqual(expectedParsed) + expect(stringified).toEqual(expectedStringified) +}) + +test('proxyString without auth, with protocol', () => { + const proxyString = 'http://127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + + const expectedStringified = '127.0.0.1:8213' + const expected = { + host: '127.0.0.1', + port: 8213, + isHttps: false + } + + expect(parsed).toEqual(expected) + expect(stringified).toEqual(expectedStringified) +}) + +test('proxyString with basic auth, without protocol', () => { + const proxyString = 'foo:bar@127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + + const expectedStringified = 'foo:bar@127.0.0.1:8213' + const expectedParsed = { + host: '127.0.0.1', + port: 8213, + isHttps: false, + auth: { + username: 'foo', + password: 'bar' + } + } + + expect(parsed).toEqual(expectedParsed) + expect(stringified).toEqual(expectedStringified) +}) + +test('proxyString without auth, without protocol', () => { + const proxyString = '127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + + const expectedStringified = '127.0.0.1:8213' + const expected = { + host: '127.0.0.1', + port: 8213, + isHttps: false + } + + expect(parsed).toEqual(expected) + expect(stringified).toEqual(expectedStringified) +}) + +test('proxyString without username & password (empty auth in url.parse)', () => { + const proxyString = '127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + const expectedStringified = '127.0.0.1:8213' + expect(parsed).not.toHaveProperty('auth') + expect(stringified).toBe(expectedStringified) +}) + +test('proxyString with username', () => { + const proxyString = 'user@127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + const expectedStringified = 'user@127.0.0.1:8213' + expect(parsed.auth.username).toBe('user') + expect(parsed.auth.password).toBeFalsy() + expect(stringified).toBe(expectedStringified) +}) + +test('parseString with username & password', () => { + const proxyString = 'user:53cr37@127.0.0.1:8213' + const parsed = proxyStringToObject(proxyString) + const stringified = proxyObjectToString(parsed) + const expectedStringified = 'user:53cr37@127.0.0.1:8213' + expect(parsed.auth.username).toBe('user') + expect(parsed.auth.password).toBe('53cr37') + expect(stringified).toBe(expectedStringified) +}) + +test('agentFromProxy with no proxy passed', () => { + const agent = agentFromProxy() + expect(agent).toMatchObject({}) +}) + +test('agentFromProxy creates https agent and removes proxy env variables', () => { + process.env.HTTP_PROXY = true + process.env.http_proxy = true + process.env.HTTPS_PROXY = true + process.env.https_proxy = true + const agentParams = { + host: 'foo.bar', + port: 1234 + } + const agent = agentFromProxy(agentParams) + expect(process.env).not.toHaveProperty('HTTP_PROXY') + expect(process.env).not.toHaveProperty('http_proxy') + expect(process.env).not.toHaveProperty('HTTPS_PROXY') + expect(process.env).not.toHaveProperty('https_proxy') + expect(agent.mock.mock.calls[0][0]).toMatchObject(agentParams) +}) diff --git a/pool/shard007/JavaScript/0044893_unitTest.js b/pool/shard007/JavaScript/0044893_unitTest.js new file mode 100644 index 0000000000000000000000000000000000000000..cd4d2f98cfb341cf6dae9084e49297cd779caf25 --- /dev/null +++ b/pool/shard007/JavaScript/0044893_unitTest.js @@ -0,0 +1,153 @@ +/* +Copied snippets of code from https://github.com/orbotix/sphero.js/tree/master/examples +in order to test the general idea of how I'm going to be controlling my Sphero. +*/ + +"use strict"; +var keypress = require("keypress"); +var sphero = require("sphero"); +var orb = sphero("com4"); + +orb.connect(function() { + // sets color to the provided r/g/b values + orb.getColor(function(err, data) { + if (err) { + console.log(err); + } else { + console.log("Color is:", data.color); + } + }); + +}); + +orb.connect(listen); + +function handle(ch, key) { + var stop = orb.roll.bind(orb, 0, 0), + roll = orb.roll.bind(orb, 60); + + if (key.ctrl && key.name === "c") { + process.stdin.pause(); + process.exit(); + } + + if (key.name === "e") { + orb.startCalibration(); + } + + if (key.name === "q") { + orb.finishCalibration(); + } + + if (key.name === "up") { + roll(0); + } + + if (key.name === "down") { + roll(180); + } + + if (key.name === "left") { + roll(270); + } + + if (key.name === "right") { + roll(90); + } + + if (key.name === "space") { + stop(); + } +} + +function listen() { + keypress(process.stdin); + process.stdin.on("keypress", handle); + + console.log("starting to listen for arrow key presses"); + + process.stdin.setRawMode(true); + process.stdin.resume(); +} + +orb.connect(function() { + // sets color to the provided r/g/b values + orb.color({ red: 255, green: 0, blue: 255 }); + + setTimeout(function() { + console.log("color 1"); + // sets color to the provided hex value + orb.color(0xff0000); + }, 1000); + + setTimeout(function() { + console.log("color 2"); + // hex numbers can also be passed in strings + orb.color("00ff00"); + }, 2000); + + setTimeout(function() { + console.log("color 3"); + // sets color to the provided color name + orb.color("magenta"); + }, 3000); +}); + +orb.connect(function() { + console.log("::START CALIBRATION::"); + orb.startCalibration(); + setTimeout(function() { + console.log("::FINISH CALIBRATION::"); + orb.finishCalibration(); + }, 5000); +}); + +orb.connect(function() { + var max = 0, + updating = false; + + // enable streaming of velocity data + orb.setDataStreaming({ + mask1: 0x00000000, + mask2: 0x01800000, + n: 40, + m: 1, + pcnt: 0 + }); + + orb.on("dataStreaming", function(data) { + if (updating) { return; } + + var x = Math.abs(data.xVelocity.value), + y = Math.abs(data.yVelocity.value); + + var localmax = Math.max(x, y); + + if (localmax > max) { max = localmax; } + }); + + function update() { + updating = true; + + if (max < 10) { + orb.color("white"); + } else if (max < 100) { + orb.color("lightyellow"); + } else if (max < 150) { + orb.color("yellow"); + } else if (max < 250) { + orb.color("orange"); + } else if (max < 350) { + orb.color("orangered"); + } else if (max < 450) { + orb.color("red"); + } else { + orb.color("darkred"); + } + + max = 0; + updating = false; + } + + setInterval(update, 600); +}); diff --git a/pool/shard007/JavaScript/0044894_chat.js b/pool/shard007/JavaScript/0044894_chat.js new file mode 100644 index 0000000000000000000000000000000000000000..90b759793dfa4a02b1f4dc3744a4877d7ae8d857 --- /dev/null +++ b/pool/shard007/JavaScript/0044894_chat.js @@ -0,0 +1,267 @@ + +$(function() { + var FADE_TIME = 150; // ms + var TYPING_TIMER_LENGTH = 400; // ms + var COLORS = [ + '#e21400', '#91580f', '#f8a700', '#f78b00', + '#58dc00', '#287b00', '#a8f07a', '#4ae8c4', + '#3b88eb', '#3824aa', '#a700ff', '#d300e7' + ]; + + // Initialize varibles + var $window = $(window); + var $usernameInput = $('.usernameInput'); // Input for username + var $messages = $('.messages'); // Messages area + var $inputMessage = $('.inputMessage'); // Input message input box + + var $loginPage = $('.login.page'); // The login page + var $chatPage = $('.chat.page'); // The chatroom page + + // Prompt for setting a username + var username; + var connected = false; + var typing = false; + var lastTypingTime; + var $currentInput = $usernameInput.focus(); + + var socket = io.connect(); + + function addParticipantsMessage (data) { + var message = ''; + if (data.numUsers === 1) { + message += "there's 1 participant"; + } else { + message += "there are " + data.numUsers + " participants"; + } + log(message); + } + + // Sets the client's username + function setUsername () { + username = cleanInput($usernameInput.val().trim()); + + // If the username is valid + if (username) { + $loginPage.fadeOut(); + $chatPage.show(); + $loginPage.off('click'); + $currentInput = $inputMessage.focus(); + + // Tell the server your username + socket.emit('add user', username); + } + } + + // Sends a chat message + function sendMessage () { + var message = $inputMessage.val(); + // Prevent markup from being injected into the message + message = cleanInput(message); + // if there is a non-empty message and a socket connection + if (message && connected) { + $inputMessage.val(''); + addChatMessage({ + username: username, + message: message + }); + // tell server to execute 'new message' and send along one parameter + socket.emit('new message', message); + } + } + + // Log a message + function log (message, options) { + var $el = $('
  • ').addClass('log').text(message); + addMessageElement($el, options); + } + + // Adds the visual chat message to the message list + function addChatMessage (data, options) { + // Don't fade the message in if there is an 'X was typing' + var $typingMessages = getTypingMessages(data); + options = options || {}; + if ($typingMessages.length !== 0) { + options.fade = false; + $typingMessages.remove(); + } + + var $usernameDiv = $('') + .text(data.username) + .css('color', getUsernameColor(data.username)); + var $messageBodyDiv = $('') + .text(data.message); + + var typingClass = data.typing ? 'typing' : ''; + var $messageDiv = $('
  • ') + .data('username', data.username) + .addClass(typingClass) + .append($usernameDiv, $messageBodyDiv); + + addMessageElement($messageDiv, options); + } + + // Adds the visual chat typing message + function addChatTyping (data) { + data.typing = true; + data.message = 'is typing'; + addChatMessage(data); + } + + // Removes the visual chat typing message + function removeChatTyping (data) { + getTypingMessages(data).fadeOut(function () { + $(this).remove(); + }); + } + + // Adds a message element to the messages and scrolls to the bottom + // el - The element to add as a message + // options.fade - If the element should fade-in (default = true) + // options.prepend - If the element should prepend + // all other messages (default = false) + function addMessageElement (el, options) { + var $el = $(el); + + // Setup default options + if (!options) { + options = {}; + } + if (typeof options.fade === 'undefined') { + options.fade = true; + } + if (typeof options.prepend === 'undefined') { + options.prepend = false; + } + + // Apply options + if (options.fade) { + $el.hide().fadeIn(FADE_TIME); + } + if (options.prepend) { + $messages.prepend($el); + } else { + $messages.append($el); + } + $messages[0].scrollTop = $messages[0].scrollHeight; + } + + // Prevents input from having injected markup + function cleanInput (input) { + return $('
    ').text(input).text(); + } + + // Updates the typing event + function updateTyping () { + if (connected) { + if (!typing) { + typing = true; + socket.emit('typing'); + } + lastTypingTime = (new Date()).getTime(); + + setTimeout(function () { + var typingTimer = (new Date()).getTime(); + var timeDiff = typingTimer - lastTypingTime; + if (timeDiff >= TYPING_TIMER_LENGTH && typing) { + socket.emit('stop typing'); + typing = false; + } + }, TYPING_TIMER_LENGTH); + } + } + + // Gets the 'X is typing' messages of a user + function getTypingMessages (data) { + return $('.typing.message').filter(function (i) { + return $(this).data('username') === data.username; + }); + } + + // Gets the color of a username through our hash function + function getUsernameColor (username) { + // Compute hash code + var hash = 7; + for (var i = 0; i < username.length; i++) { + hash = username.charCodeAt(i) + (hash << 5) - hash; + } + // Calculate color + var index = Math.abs(hash % COLORS.length); + return COLORS[index]; + } + + // Keyboard events + + $window.keydown(function (event) { + // Auto-focus the current input when a key is typed + if (!(event.ctrlKey || event.metaKey || event.altKey)) { + $currentInput.focus(); + } + // When the client hits ENTER on their keyboard + if (event.which === 13) { + if (username) { + sendMessage(); + socket.emit('stop typing'); + typing = false; + } else { + setUsername(); + } + } + }); + + $inputMessage.on('input', function() { + updateTyping(); + }); + + // Click events + + // Focus input when clicking anywhere on login page + $loginPage.click(function () { + $currentInput.focus(); + }); + + // Focus input when clicking on the message input's border + $inputMessage.click(function () { + $inputMessage.focus(); + }); + + // Socket events + + // Whenever the server emits 'login', log the login message + socket.on('login', function (data) { + connected = true; + // Display the welcome message + var message = "IFC 揮手區"; + log(message, { + prepend: true + }); + addParticipantsMessage(data); + }); + + // Whenever the server emits 'new message', update the chat body + socket.on('new message', function (data) { + addChatMessage(data); + }); + + // Whenever the server emits 'user joined', log it in the chat body + socket.on('user joined', function (data) { + log(data.username + ' joined'); + addParticipantsMessage(data); + }); + + // Whenever the server emits 'user left', log it in the chat body + socket.on('user left', function (data) { + log(data.username + ' left'); + addParticipantsMessage(data); + removeChatTyping(data); + }); + + // Whenever the server emits 'typing', show the typing message + socket.on('typing', function (data) { + addChatTyping(data); + }); + + // Whenever the server emits 'stop typing', kill the typing message + socket.on('stop typing', function (data) { + removeChatTyping(data); + }); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044896_jquery.blueimp-gallery.js b/pool/shard007/JavaScript/0044896_jquery.blueimp-gallery.js new file mode 100644 index 0000000000000000000000000000000000000000..e9e6d003b3495383c688b3ef96908e4b86ae41c0 --- /dev/null +++ b/pool/shard007/JavaScript/0044896_jquery.blueimp-gallery.js @@ -0,0 +1,84 @@ +/* + * blueimp Gallery jQuery plugin 1.2.2 + * https://github.com/blueimp/Gallery + * + * Copyright 2013, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/* global define, window, document */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + define([ + 'jquery', + './blueimp-gallery' + ], factory); + } else { + factory( + window.jQuery, + window.blueimp.Gallery + ); + } +}(function ($, Gallery) { + 'use strict'; + + // Global click handler to open links with data-gallery attribute + // in the Gallery lightbox: + $(document).on('click', '[data-gallery]', function (event) { + // Get the container id from the data-gallery attribute: + var id = $(this).data('gallery'), + widget = $(id), + container = (widget.length && widget) || + $(Gallery.prototype.options.container), + callbacks = { + onopen: function () { + container + .data('gallery', this) + .trigger('open'); + }, + onopened: function () { + container.trigger('opened'); + }, + onslide: function () { + container.trigger('slide', arguments); + }, + onslideend: function () { + container.trigger('slideend', arguments); + }, + onslidecomplete: function () { + container.trigger('slidecomplete', arguments); + }, + onclose: function () { + container.trigger('close'); + }, + onclosed: function () { + container + .trigger('closed') + .removeData('gallery'); + } + }, + options = $.extend( + // Retrieve custom options from data-attributes + // on the Gallery widget: + container.data(), + { + container: container[0], + index: this, + event: event + }, + callbacks + ), + // Select all links with the same data-gallery attribute: + links = $('[data-gallery="' + id + '"]'); + if (options.filter) { + links = links.filter(options.filter); + } + return new Gallery(links, options); + }); + +})); diff --git a/pool/shard007/JavaScript/0044898_mr_i2c_range_sensor.js b/pool/shard007/JavaScript/0044898_mr_i2c_range_sensor.js new file mode 100644 index 0000000000000000000000000000000000000000..4ea993e44975ad4538fa6674b6c57d252ed65def --- /dev/null +++ b/pool/shard007/JavaScript/0044898_mr_i2c_range_sensor.js @@ -0,0 +1,173 @@ +/** + * @fileoverview FTC robot blocks related to ModernRoboticsI2cRangeSensor. + * @author lizlooney@google.com (Liz Looney) + */ + +// The following are generated dynamically in HardwareUtil.fetchJavaScriptForHardware(): +// createMrI2cRangeSensorDropdown +// The following are defined in vars.js: +// functionColor +// getPropertyColor +// setPropertyColor + +Blockly.Blocks['mrI2cRangeSensor_setProperty'] = { + init: function() { + var PROPERTY_CHOICES = [ + ['I2cAddress7Bit', 'I2cAddress7Bit'], + ['I2cAddress8Bit', 'I2cAddress8Bit'], + ]; + this.appendValueInput('VALUE') + .appendField('set') + .appendField(createMrI2cRangeSensorDropdown(), 'IDENTIFIER') + .appendField('.') + .appendField(new Blockly.FieldDropdown(PROPERTY_CHOICES), 'PROP') + .appendField('to'); + this.setPreviousStatement(true); + this.setNextStatement(true); + // Assign 'this' to a variable for use in the tooltip closure below. + var thisBlock = this; + var TOOLTIPS = [ + ['I2cAddress7Bit', 'The 7 bit I2C address of the range sensor.'], + ['I2cAddress8Bit', 'The 8 bit I2C address of the range sensor.'], + ]; + this.setTooltip(function() { + var key = thisBlock.getFieldValue('PROP'); + for (var i = 0; i < TOOLTIPS.length; i++) { + if (TOOLTIPS[i][0] == key) { + return TOOLTIPS[i][1]; + } + } + return ''; + }); + this.setColour(setPropertyColor); + } +}; + +Blockly.JavaScript['mrI2cRangeSensor_setProperty'] = function(block) { + var identifier = block.getFieldValue('IDENTIFIER'); + var property = block.getFieldValue('PROP'); + var value = Blockly.JavaScript.valueToCode( + block, 'VALUE', Blockly.JavaScript.ORDER_NONE); + return identifier + '.set' + property + '(' + value + ');\n'; +}; + +Blockly.Blocks['mrI2cRangeSensor_getProperty'] = { + init: function() { + var PROPERTY_CHOICES = [ + ['CmOptical', 'CmOptical'], + ['CmUltrasonic', 'CmUltrasonic'], + ['I2cAddress7Bit', 'I2cAddress7Bit'], + ['I2cAddress8Bit', 'I2cAddress8Bit'], + ['LightDetected', 'LightDetected'], + ['RawLightDetected', 'RawLightDetected'], + ['RawLightDetectedMax', 'RawLightDetectedMax'], + ['RawOptical', 'RawOptical'], + ['RawUltrasonic', 'RawUltrasonic'], + ]; + this.setOutput(true); + this.appendDummyInput() + .appendField(createMrI2cRangeSensorDropdown(), 'IDENTIFIER') + .appendField('.') + .appendField(new Blockly.FieldDropdown(PROPERTY_CHOICES), 'PROP'); + // Assign 'this' to a variable for use in the tooltip closure below. + var thisBlock = this; + var TOOLTIPS = [ + ['CmOptical', 'Returns the distance in centimeters, according to the optical sensor.'], + ['CmUltrasonic', 'Returns the distance in centimeters, according to the ultrasonic sensor.'], + ['I2cAddress7Bit', 'The 7 bit I2C address of the range sensor.'], + ['I2cAddress8Bit', 'The 8 bit I2C address of the range sensor.'], + ['LightDetected', 'Gets the amount of light detected by the range sensor. ' + + 'The value is between 0.0 and 1.0.'], + ['RawLightDetected', 'Returns a signal whose strength is proportional to the intensity ' + + 'of the light measured.'], + ['RawLightDetectedMax', 'Returns the maximum value that can be returned for ' + + 'RawLightDetected.'], + ['RawOptical', 'Returns the raw optical value.'], + ['RawUltrasonic', 'Returns the raw ultrasonic value.'], + ]; + this.setTooltip(function() { + var key = thisBlock.getFieldValue('PROP'); + for (var i = 0; i < TOOLTIPS.length; i++) { + if (TOOLTIPS[i][0] == key) { + return TOOLTIPS[i][1]; + } + } + return ''; + }); + this.setColour(getPropertyColor); + } +}; + +Blockly.JavaScript['mrI2cRangeSensor_getProperty'] = function(block) { + var identifier = block.getFieldValue('IDENTIFIER'); + var property = block.getFieldValue('PROP'); + var code = identifier + '.get' + property + '()'; + return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; +}; + +// Enums + +Blockly.Blocks['mrI2cRangeSensor_enum_distanceUnit'] = { + init: function() { + var DISTANCE_UNIT_CHOICES = [ + ['METER', 'METER'], + ['CM', 'CM'], + ['MM', 'MM'], + ['INCH', 'INCH'], + ]; + this.setOutput(true); + this.appendDummyInput() + .appendField('DistanceUnit') + .appendField('.') + .appendField(new Blockly.FieldDropdown(DISTANCE_UNIT_CHOICES), 'DISTANCE_UNIT'); + // Assign 'this' to a variable for use in the tooltip closure below. + var thisBlock = this; + var TOOLTIPS = [ + ['METER', 'The DistanceUnit value METER.'], + ['CM', 'The DistanceUnit value CM (centimeter).'], + ['MM', 'The DistanceUnit value MM (millimeter).'], + ['INCH', 'The DistanceUnit value INCH.'], + ]; + this.setTooltip(function() { + var key = thisBlock.getFieldValue('DISTANCE_UNIT'); + for (var i = 0; i < TOOLTIPS.length; i++) { + if (TOOLTIPS[i][0] == key) { + return TOOLTIPS[i][1]; + } + } + return ''; + }); + this.setColour(getPropertyColor); + } +}; + +Blockly.JavaScript['mrI2cRangeSensor_enum_distanceUnit'] = function(block) { + var code = '"' + block.getFieldValue('DISTANCE_UNIT') + '"'; + return [code, Blockly.JavaScript.ORDER_ATOMIC]; +}; + +// Functions + +Blockly.Blocks['mrI2cRangeSensor_getDistance'] = { + init: function() { + this.setOutput(true); + this.appendDummyInput() + .appendField('call') + .appendField(createMrI2cRangeSensorDropdown(), 'IDENTIFIER') + .appendField('.') + .appendField(createNonEditableField('getDistance')); + this.appendValueInput('UNIT') + .appendField('unit') + .setAlign(Blockly.ALIGN_RIGHT); + this.setTooltip('Returns the current distance in the indicated distance units.'); + this.setColour(functionColor); + } +}; + +Blockly.JavaScript['mrI2cRangeSensor_getDistance'] = function(block) { + var identifier = block.getFieldValue('IDENTIFIER'); + var unit = Blockly.JavaScript.valueToCode( + block, 'UNIT', Blockly.JavaScript.ORDER_NONE); + var code = identifier + '.getDistance(' + unit + ')'; + return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; +}; diff --git a/pool/shard007/JavaScript/0044901_test-origin-experiments.js b/pool/shard007/JavaScript/0044901_test-origin-experiments.js new file mode 100644 index 0000000000000000000000000000000000000000..672f1b48a6c1d25328d04b8f93c8cd3da48a2798 --- /dev/null +++ b/pool/shard007/JavaScript/0044901_test-origin-experiments.js @@ -0,0 +1,248 @@ +/** + * Copyright 2017 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS-IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + OriginExperiments, + TokenMaster, +} from '../../src/service/origin-experiments-impl'; +import {Services} from '../../src/services'; +import {bytesToString} from '../../src/utils/bytes'; +import {user} from '../../src/log'; + +describes.fakeWin('OriginExperiments', {amp: true}, env => { + const TAG = 'OriginExperiments'; + // Token enables experiment "foo" for origin "https://origin.com". + const token = + 'AAAAAFd7Im9yaWdpbiI6Imh0dHBzOi8vb3JpZ2luLmNvbSIsImV4cGVyaW1lbnQiOiJmb28iLCJleHBpcmF0aW9uIjoxLjc5NzY5MzEzNDg2MjMxNTdlKzMwOH0+0WnsFJFtFJzkrzqxid2h3jnFI2C7FTK+8iRYcU1r+9PZtnMPJCVCkNkxWGpXFZ6z2FwIa/hY4XDM//GJHr+2pdChx67wm6RIY1NDwcYqFbUrugEqWiT/2RviS9PPhtP6PKgUDI+0opQUt2ibXhsc1KynroAcGTaaxofmpnuMdj7vjGlWTF+6WCFYfAzqcLJB5a4+Drop9ZTEYRbRROMVROC8EGHwugeMfoNf3roCqaJydADQ/tSTY/fPZOlcwOtGW8GE4s/KlNyFaonjEYOROuLctJxYAqwIStQ4TdS7xfy70hsgVLCKnLeXIRJKN0eaJCkLy6BFbIrCH5FhjhbY'; // eslint-disable-line max-len + + let ampdoc; + let isPkcsAvailable; + let originExperiments; + let win; + let error; + + beforeEach(() => { + ({win, ampdoc} = env); + + const crypto = Services.cryptoFor(win); + isPkcsAvailable = env.sandbox.stub(crypto, 'isPkcsAvailable').returns(true); + + error = env.sandbox.stub(user(), 'error'); + + originExperiments = new OriginExperiments(ampdoc); + }); + + function setupMetaTagWith(token) { + const meta = win.document.createElement('meta'); + meta.setAttribute('name', 'amp-experiment-token'); + meta.setAttribute('content', token); + win.document.head.appendChild(meta); + } + + it('should return false if no token is found', function*() { + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal([]); + yield experiments; + expect(error).to.not.be.called; + }); + + it('should return false if crypto is unavailable', function*() { + isPkcsAvailable.returns(false); + + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal([]); + expect(error).calledWithMatch(TAG, 'Crypto is unavailable'); + }); + + it('should return false for missing token', function*() { + setupMetaTagWith(''); + + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal([]); + yield experiments; + expect(error).calledWithMatch(TAG, 'Missing content for experiment token'); + }); + + it('should return false if origin does not match', function*() { + setupMetaTagWith(token); + win.location.href = 'https://not-origin.com'; + + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal([]); + yield experiments; + expect(error).calledWithMatch(TAG, 'Failed to verify experiment token'); + }); + + // TODO(amphtml, #25621): Cannot find atob / btoa on Safari on Sauce Labs. + it.configure().skipSafari( + 'should return true for valid token with matching origin', + function*() { + setupMetaTagWith(token); + win.location.href = 'https://origin.com'; + + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal(['foo']); + yield experiments; + expect(error).to.not.be.called; + } + ); + + // TODO(amphtml, #25621): Cannot find atob / btoa on Safari on Sauce Labs. + it.configure().skipSafari( + 'should return false if experiment is not in config', + function*() { + setupMetaTagWith(token); + win.location.href = 'https://origin.com'; + + const experiments = originExperiments.getExperiments(); + expect(experiments).to.eventually.deep.equal([]); + yield experiments; + expect(error).to.not.be.called; + } + ); +}); + +describes.fakeWin('TokenMaster', {amp: true}, env => { + let tokenMaster; + + let publicKey; + let privateKey; + + let token; + let tokenWithBadVersion; + let tokenWithExpiredExperiment; + let tokenWithBadConfigLength; + let tokenWithBadSignature; + + // TODO(amphtml, #25621): Cannot find atob / btoa on Safari on Sauce Labs. + describe + .configure() + .skipSafari() + .run('TokenMaster', () => { + // Generate test tokens once since generating keys is slow. + beforeEach(() => { + const crypto = Services.cryptoFor(env.win); + const url = Services.urlForDoc(env.ampdoc.getHeadNode()); + tokenMaster = new TokenMaster(crypto, url); + + return tokenMaster.generateKeys().then(keyPair => { + ({publicKey, privateKey} = keyPair); + + const config = { + origin: 'https://origin.com', + experiment: 'origin', + expiration: Date.now() + 1000 * 1000, // 1000s in the future. + }; + const expired = { + origin: 'https://origin.com', + experiment: 'expired', + expiration: Date.now() - 1000, // 1s in the past. + }; + + return Promise.all([ + tokenMaster.generateToken(0, config, privateKey), + tokenMaster.generateToken(42, config, privateKey), + tokenMaster.generateToken(0, expired, privateKey), + ]).then(results => { + token = results[0]; + tokenWithBadVersion = results[1]; + tokenWithExpiredExperiment = results[2]; + + // Generate token with bad signature by truncating. + tokenWithBadSignature = token.slice(0, token.length - 5); + + // Generate token with bad config length by hand. + const data = new Uint8Array(5); + new DataView(data.buffer).setUint32(1, 999, false); // 999 length. + tokenWithBadConfigLength = btoa(bytesToString(data)); + }); + }); + }); + + it('should throw for an unknown token version number', () => { + const verify = tokenMaster.verifyToken( + tokenWithBadVersion, + 'https://origin.com', + publicKey + ); + return expect(verify).to.eventually.be.rejectedWith( + 'Unrecognized token version: 42' + ); + }); + + it('should throw if config length exceeds byte length', () => { + const verify = tokenMaster.verifyToken( + tokenWithBadConfigLength, + 'https://origin.com', + publicKey + ); + return expect(verify).to.eventually.be.rejectedWith( + 'Unexpected config length: 999' + ); + }); + + it('should throw if signature cannot be verified', () => { + const verify = tokenMaster.verifyToken( + tokenWithBadSignature, + 'https://origin.com', + publicKey + ); + return expect(verify).to.eventually.be.rejectedWith( + 'Failed to verify token signature.' + ); + }); + + it('should throw if approved origin is not current origin', () => { + const verify = tokenMaster.verifyToken( + token, + 'https://not-origin.com', + publicKey + ); + return expect(verify).to.eventually.be.rejectedWith( + /does not match window/ + ); + }); + + it('should return false if trial has expired', () => { + const verify = tokenMaster.verifyToken( + tokenWithExpiredExperiment, + 'https://origin.com', + publicKey + ); + return expect(verify).to.eventually.be.rejectedWith( + 'Experiment "expired" has expired.' + ); + }); + + it('should return true for a well-formed, unexpired token', () => { + const verify = tokenMaster.verifyToken( + token, + 'https://origin.com', + publicKey + ); + return expect(verify).to.eventually.be.fulfilled; + }); + + it('should ignore trailing slash on location', () => { + const verify = tokenMaster.verifyToken( + token, + 'https://origin.com/', + publicKey + ); + return expect(verify).to.eventually.be.fulfilled; + }); + }); +}); diff --git a/pool/shard007/JavaScript/0044905_test.js b/pool/shard007/JavaScript/0044905_test.js new file mode 100644 index 0000000000000000000000000000000000000000..64c7c6009b166c0ee15ab58c8fbf474f324e0849 --- /dev/null +++ b/pool/shard007/JavaScript/0044905_test.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * Run complete package tests. + * (C) 2014 Alex Fernández. + */ + +// requires +var Log = require('log'); +var testing = require('testing'); + +// globals +var log = new Log('info'); + + +/** + * Run module tests. + */ +exports.test = function(callback) +{ + log.debug('Running tests'); + var tests = {}; + var modules = ['profiler']; + modules.forEach(function(name) + { + var filename = './lib/' + name + '.js'; + tests[name] = require(filename).test; + }); + testing.run(tests, 10000, callback); +}; + +// run tests if invoked directly +if (__filename == process.argv[1]) +{ + exports.test(testing.show); +} + diff --git a/pool/shard007/JavaScript/0044909_index.js b/pool/shard007/JavaScript/0044909_index.js new file mode 100644 index 0000000000000000000000000000000000000000..69d7edaf534f248bd10edb0b0e8cfcdaf99edd36 --- /dev/null +++ b/pool/shard007/JavaScript/0044909_index.js @@ -0,0 +1,132 @@ +// TODO: alternatively we can download all events from bikereg and do better and more advanced +// search and matching locally +// TODO: make sure both EventUrl and EvnetPermalink are stored in RCN so we can do rolling reg links +// this means we would show +//TODO: if fetching by permit fails collect failed requests and try fetching by name +// return result from scraping func with metadata and status like "not found" so we can do second +// pass on it +// alternatively this could be a good case to introduce smarter way to generate urls which is +// a generator or a function that gets called every time during scraping and access to current +// scraping state is provided to it so it can decide what to do next. This way we can build a +// smart function that encapsulates decisions on how to build urls and what to request next +//TODO: CCCX returns multiple results for the same permit, need to handle that somehow + +import { log } from 'console-tools' +import { get, partialRight, pipe, uniq, map, keyBy } from 'lodash/fp' +// import buildScraper from 'little-scraper' +import buildScraperWithProxy from 'scrapers/utils/scraper-with-proxy.js' +import usac2017Events from '../../../data/events/2017/CN_all-types_noncomp-0_rrfilter-rr.json' + +const createUrlsWithPermits = ({ usacEvents, year }) => { + // bikereg by default would only return future events, unless year parameter is provided + const createUrl = permit => + `https://www.bikereg.com/api/search?permit=${permit}&year=${year}` + + const permits = pipe( + map(x => x.permit), + uniq + // take(20), + )(usacEvents) + + return permits.map(permit => ({ + url: createUrl(permit), + context: { permit: permit } + })) +} + +const createUrlsWithNames = ({ usacEvents, year }) => { + // bikereg by default would only return future events, unless year parameter is provided + const createUrl = name => + `https://www.bikereg.com/api/search?name=${encodeURIComponent( + name + )}&year=${year}` + + const names = pipe(map(x => x.name), uniq)(usacEvents) + + return names.map(name => ({ + url: createUrl(name), + context: { eventName: name } + })) +} + +const getEeventByPermit = ({ response, urlWithContext }) => { + if (!response.body) { + log.fail(`${urlWithContext.url} - no "response.body"`) + } + + const createResponse = ({ status }) => ({ + status: status, + context: urlWithContext.context + }) + + try { + const responseJson = JSON.parse(response.body) + const getResponseProp = partialRight(get, [responseJson]) + + if (getResponseProp('ResultCount') > 1) { + log.fail( + `${urlWithContext.url} - returned ` + + `${getResponseProp('ResultCount')} ` + + `matching events, while expeced 1` + ) + return [createResponse({ status: 'Error' })] + } + + if (getResponseProp('ResultCount') === 0) { + log.warn(`${urlWithContext.url} - event not found`) + return [createResponse({ status: 'Not Found' })] + } + + const event = getResponseProp('MatchingEvents[0]') + + log.done(`${urlWithContext.url}`) + + return [ + { + data: { + regUrl: event.EventUrl, + permanentUrl: event.EventPermalink + }, + ...createResponse({ status: 'Success' }) + } + ] + } catch (e) { + log.fail(`${urlWithContext.url} - can not parse response body json, got this:`) + log.json(response.body) + log.error(e) + } +} + +const scrape = buildScraperWithProxy({ + scrapingFunc: getEeventByPermit, + concurrency: 10, + delay: 500 +}) + +async function runScraping() { + const results = await scrape({ + fromUrls: createUrlsWithPermits({ usacEvents: usac2017Events, year: 2017 }) + }) + + // if we couldn't find event by permit try by name + const notFoundEventPermits = results + .filter(x => x.status === 'Not Found') + .map(x => x.context.permit) + const usacEventsMap = keyBy('permit', usac2017Events) + const notFoundUsacEvents = notFoundEventPermits.map( + permit => usacEventsMap[permit] + ) + const additionalResults = await scrape({ + fromUrls: createUrlsWithNames({ + usacEvents: notFoundUsacEvents, + year: 2017 + }) + }) + + // log.json(notFoundUsacEvents) + // log.json(results, 3) +} + +runScraping() + +export default scrape diff --git a/pool/shard007/JavaScript/0044912_the_watchers.js b/pool/shard007/JavaScript/0044912_the_watchers.js new file mode 100644 index 0000000000000000000000000000000000000000..be24590c67dd81162c82a0c4fbba46c9b30d8297 --- /dev/null +++ b/pool/shard007/JavaScript/0044912_the_watchers.js @@ -0,0 +1,19 @@ +jQuery(document).ready(function() { + + function sizeFeature(){ + var windowHeight = $(window).height(); + var windowWidth = $(window).width(); + if($('video').length){ + featureHeight = windowWidth * 0.5; + $('.main-feature').css("height", featureHeight + "px"); + } + } + + $(window).load(function(){ + sizeFeature(); + }); + + $(window).resize(function(){ + sizeFeature(); + }); +}); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044914_field.js b/pool/shard007/JavaScript/0044914_field.js new file mode 100644 index 0000000000000000000000000000000000000000..accb2dde9b126140dce8cdf3bba031800cb2c75c --- /dev/null +++ b/pool/shard007/JavaScript/0044914_field.js @@ -0,0 +1,197 @@ +// todo: why isn't _references.js working? +/// + +// original source http://plnkr.co/edit/3zMsNnpNfOFwExSqLj2I?p=preview which derived from https://github.com/angular-ui/angular-ui/pull/191. + +'use strict'; + +var textfield = angular.module('field', ['services.humanizer']) + +textfield.directive('field', function ($compile, $http, $templateCache, $interpolate, humanizer) { + + function findInputElement(element) { + return angular.element(element.find('input')[0] || element.find('textarea')[0] || element.find('select')[0]); + }; + + function getLabelContent(element, ngModel) { + + if (element.attr('label')) { + + return element.attr('label'); + } + if (element.find('label')[0]) { + + return element.find('label').html(); + } + else { + + var fullModelName = ngModel; + var fieldName = fullModelName.substring(fullModelName.indexOf(".") + 1); + var humanized = humanizer.humanize(fieldName); + + return humanized; + } + + }; + + function getTemplate(element, attrs) { + + var template = attrs.template; + + if (template !== undefined) { + return template; + } + + var type = attrs.type; + + if (type !== undefined && type !== 'email') { + return type; + } + + return 'input'; + } + + function tryRemoveAttribute(element, name) { + + var attribute = element.attr(name); + + if (attribute === undefined) { + return; + } + + element[0].removeAttribute(name); + }; + + return { + restrict: 'E', + priority: 100, // We need this directive to happen before ng-model + terminal: true, // We are going to deal with this element + require: '?^form', // If we are in a form then we can access the ngModelController + compile: function compile(element, attrs) { + + var labelContent = getLabelContent(element, attrs.ngModel); + tryRemoveAttribute(element, 'label'); + + // Find all the child elements and extract their validation message info + var hasRequiredValidator = false; + var validationMessages = []; + + angular.forEach(element.find('validator'), + function (validatorElement) { + + validatorElement = angular.element(validatorElement); + + var key = validatorElement.attr('key'); + + if (key === 'required') { + hasRequiredValidator = true; + } + + validationMessages.push({ + key: key, + getMessage: $interpolate(validatorElement.text()) + }); + } + ); + + if (!hasRequiredValidator && attrs.required !== undefined) { + + validationMessages.push({ + key: "required", + getMessage: $interpolate(labelContent + " is required.") + }); + } + + var template = getTemplate(element, attrs); + var getFieldElement = $http.get('/App/infrastructure/ui/' + template + '.template.html', { cache: $templateCache }) + + .then(function (response) { + + var newElement = angular.element(response.data); + var inputElement = findInputElement(newElement); + + // Copy over the attributes to the input element + // At least the ng-model attribute must be copied because we can't use interpolation in the template + angular.forEach(element[0].attributes, function (attribute) { + var value = attribute.value; + var key = attribute.name; + inputElement.attr(key, value); + }); + + // Add a default placeholder + if (inputElement.attr('placeholder') == undefined) { + inputElement.attr('placeholder', labelContent); + } + + // Update the label's contents + var labelElement = newElement.find('label'); + labelElement.html(labelContent); + + + return newElement; + }); + + return function (scope, element, attrs, formController) { + + // We have to wait for the field element template to be loaded + getFieldElement.then(function (newElement) { + + // Our template will have its own child scope + var childScope = scope.$new(); + + // Generate an id for the input from the ng-model expression + // (we need to replace dots with something to work with browsers and also form scope) + // (We couldn't do this in the compile function as we need the scope to + // be able to calculate the unique id) + childScope.$modelId = attrs.ngModel.replace('.', '-'); + + // Wire up the input (id and name) and its label (for) + // (We need to set the input element's name here before we compile. + // If we leave it to interpolation, the formController doesn't pick it up) + var inputElement = findInputElement(newElement); + + inputElement.attr('name', childScope.$modelId); + inputElement.attr('id', childScope.$modelId); + + + newElement.find('label').attr('for', childScope.$modelId); + + // TODO: Consider moving this validator stuff into its own directive + // and use a directive controller to wire it all up + childScope.$validationMessages = {}; + + angular.forEach(validationMessages, function (validationMessage) { + + // We need to watch in case it has interpolated values that need processing + scope.$watch( + validationMessage.getMessage, + function (message) { + childScope.$validationMessages[validationMessage.key] = message; + } + ); + }); + + // We must compile our new element in the postLink function rather than in the compile function + // (i.e. after any parent form element has been linked) + // otherwise the new input won't pick up the FormController + $compile(newElement)(childScope, function (clone) { + + // Place our new element after the original element + element.after(clone); + + // Remove our original element + element.remove(); + }); + + // Only after the new element has been compiled do we have access to the ngModelController + // (i.e. formController[childScope.name]) + if (formController) { + + childScope.$form = formController; + childScope.$field = formController[childScope.$modelId]; + } + }); + }; + } + }; +}); diff --git a/pool/shard007/JavaScript/0044918_hat.js b/pool/shard007/JavaScript/0044918_hat.js new file mode 100644 index 0000000000000000000000000000000000000000..3067cbb6dc6ebd851860f50bc341b4b88e3300dd --- /dev/null +++ b/pool/shard007/JavaScript/0044918_hat.js @@ -0,0 +1,23 @@ +module.exports = (function(){ + 'use strict'; + + var config = require('../config'); + var utils = require('../utils'); + + return { + getAll: function(callback){ + var options = {}; + options.method = 'GET'; + options.uri = config.uri.GET_ALL_HAT; + + utils.exec(options, callback); + }, + getTemplates: function(callback){ + var options = {}; + options.method = 'GET'; + options.uri = config.uri.GET_TEMPLATES_HAT; + + utils.exec(options, callback); + } + } +})(); diff --git a/pool/shard007/JavaScript/0044921_Log.js b/pool/shard007/JavaScript/0044921_Log.js new file mode 100644 index 0000000000000000000000000000000000000000..8acb67a1aab98c29238f70bab89c9563bb013444 --- /dev/null +++ b/pool/shard007/JavaScript/0044921_Log.js @@ -0,0 +1,60 @@ +import React from 'react'; +import Card from './Card'; +import * as time from '../time'; + +function Log(props) { + + let cpTime = props.loadTime; + const entries = props.entries.map((entry, index) => { + + if (entry.level == 'checkpoint') { + cpTime = entry.time; + } + + let dur = new time.Duration(entry.time - cpTime); + + switch (entry.level) { + case 'checkpoint': + return ( + +   + {cpTime.toISOString()} + + ); + + case 'info': + return ( + + {dur.toString()} + {entry.message} + + ); + + case 'error': + return ( + + {dur.toString()} + {entry.message} + + ); + } + + }); + + return ( + + + + + + + + + {entries} +
    δmessage
    +
    + + ); +} + +export default Log; diff --git a/pool/shard007/JavaScript/0044923_tile_pyramid.js b/pool/shard007/JavaScript/0044923_tile_pyramid.js new file mode 100644 index 0000000000000000000000000000000000000000..714ebf536c3fd06413689645e808f40a5a7e72fc --- /dev/null +++ b/pool/shard007/JavaScript/0044923_tile_pyramid.js @@ -0,0 +1,142 @@ +import Geo from './geo'; +import Tile from './tile'; + +export default class TilePyramid { + + constructor() { + this.coords = {}; + this.max_proxy_descendant_depth = 3; // # of levels deep to search for descendant proxy tiles + } + + sourceTiles(coord, source) { + return ( + this.coords[coord.key] && + this.coords[coord.key].sources && + this.coords[coord.key].sources.get(source.name)); + } + + addTile(tile) { + // Add target tile + let key = tile.coords.key; + let coord = this.coords[key]; + if (!coord) { + coord = this.coords[key] = { descendants: 0 }; + } + + if (!coord.sources) { + coord.sources = new Map(); + } + + if (!coord.sources.get(tile.source.name)) { + coord.sources.set(tile.source.name, new Map()); + } + coord.sources.get(tile.source.name).set(tile.style_zoom, tile); + + // Increment reference count up the tile pyramid + for (let z = tile.coords.z - 1; z >= 0; z--) { + let up = Tile.coordinateAtZoom(tile.coords, z); + if (!this.coords[up.key]) { + this.coords[up.key] = { descendants: 0 }; + } + this.coords[up.key].descendants++; + } + } + + removeTile(tile) { + // Remove target tile + let source_tiles = this.sourceTiles(tile.coords, tile.source); + let key = tile.coords.key; + + if (source_tiles) { + source_tiles.delete(tile.style_zoom); + if (source_tiles.size === 0) { + // remove source + this.coords[key].sources.delete(tile.source.name); + if (this.coords[key].sources.size === 0) { + delete this.coords[key].sources; + + if (this.coords[key].descendants === 0) { + // remove whole coord + delete this.coords[key]; + } + } + } + } + + // Decrement reference count up the tile pyramid + for (let z = tile.coords.z - 1; z >= 0; z--) { + let down = Tile.coordinateAtZoom(tile.coords, z); + if (this.coords[down.key] && this.coords[down.key].descendants > 0) { + this.coords[down.key].descendants--; + if (this.coords[down.key].descendants === 0 && !this.coords[down.key].sources) { + delete this.coords[down.key]; + } + } + } + } + + getAncestor ({ coords, style_zoom, source }) { + // First check overzoomed tiles at same coordinate zoom + if (style_zoom > source.max_zoom) { + let source_tiles = this.sourceTiles(coords, source); + if (source_tiles) { + for (let z = style_zoom - 1; z >= source.max_zoom; z--) { + if (source_tiles.has(z) && source_tiles.get(z).loaded) { + return source_tiles.get(z); + } + } + } + style_zoom = source.max_zoom; + } + + // Check tiles at next zoom up + style_zoom--; + let parent = Tile.coordinateAtZoom(coords, coords.z - 1); + let parent_tiles = this.sourceTiles(parent, source); + if (parent_tiles && parent_tiles.has(style_zoom) && parent_tiles.get(style_zoom).loaded) { + return parent_tiles.get(style_zoom); + } + // didn't find ancestor, try next level + // TODO: max depth levels to check + if (parent.z > 0) { + return this.getAncestor({ coords: parent, style_zoom, source }); + } + } + + getDescendants ({ coords, style_zoom, source }, level = 1) { + let descendants = []; + + // First check overzoomed tiles at same coordinate zoom + if (style_zoom >= source.max_zoom) { + let source_tiles = this.sourceTiles(coords, source); + if (source_tiles) { + let search_max_zoom = Math.max(Geo.default_view_max_zoom, style_zoom + this.max_proxy_descendant_depth); + for (let z = style_zoom + 1; z <= search_max_zoom; z++) { + if (source_tiles.has(z) && source_tiles.get(z).loaded) { + descendants.push(source_tiles.get(z)); + return descendants; + } + } + } + return descendants; + } + + // Check tiles at next zoom down + if (this.coords[coords.key] && this.coords[coords.key].descendants > 0) { + style_zoom++; + for (let child of Tile.childrenForCoordinate(coords)) { + let child_tiles = this.sourceTiles(child, source); + if (child_tiles && child_tiles.has(style_zoom) && child_tiles.get(style_zoom).loaded) { + descendants.push(child_tiles.get(style_zoom)); + } + // didn't find child, try next level + else if (level <= this.max_proxy_descendant_depth && child.z <= source.max_zoom) { + descendants.push(...this.getDescendants({ coords: child, source, style_zoom }, level + 1)); + } + } + } + + return descendants; + } + +} diff --git a/pool/shard007/JavaScript/0044928_membership.spec.js b/pool/shard007/JavaScript/0044928_membership.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c1cd52f70cc5efb781138814109df55abceb5588 --- /dev/null +++ b/pool/shard007/JavaScript/0044928_membership.spec.js @@ -0,0 +1,139 @@ +'use strict'; + +const expect = require('chai').expect; +const path = require('path'); + +const utils = require('../utils'); +const config = utils.config; +const mongoose = utils.mongoose; +const time = utils.time; + +describe('models: membership', function () { + + let Group = null; + let Membership = null; + let User = null; + let mocks = {}; + + before(function () { + mongoose.models = {}; + mongoose.modelSchemas = {}; + + Membership = mongoose.model( + 'Membership', + require(path.join(config.path.main, 'models', 'membership')) + ); + + Group = mongoose.model( + 'Group', + new mongoose.Schema({ + name: String + }) + ); + + User = mongoose.model( + 'User', + new mongoose.Schema({ + name: String + }) + ); + }); + + beforeEach(function (done) { + mocks.group = { name: 'testgroup' }; + mocks.user = { name: 'testuser' }; + + Group.create(mocks.group, function (err, group) { + expect(err).to.not.exist; + expect(group).to.exist; + + User.create(mocks.user, function (err, user) { + expect(err).to.not.exist; + expect(user).to.exist; + + mocks.membership = { + user: user._id, + group: group._id + }; + + done(); + }); + }); + }); + + describe('#create', function () { + + it('should create membership', function (done) { + Membership.create(mocks.membership, function (err, member) { + expect(err).to.not.exist; + expect(member).to.exist; + done(); + }); + }); + + it('should require user', function (done) { + mocks.membership.user = null; + Membership.create(mocks.membership, function (err, member) { + expect(err).to.exist; + done(); + }); + }); + + it('should require group', function (done) { + mocks.membership.group = null; + Membership.create(mocks.membership, function (err, member) { + expect(err).to.exist; + done(); + }); + }); + + it('should set joined', function (done) { + let before = time(); + + Membership.create(mocks.membership, function (err, member) { + let after = time(); + let joined = member.joined.getTime(); + + expect(err).to.not.exist; + expect(member).to.exist; + expect(joined).to.exist; + expect(joined).to.be.at.most(after); + expect(joined).to.be.at.least(before); + done(); + }); + }); + }); + + describe('#populate', function () { + + it('should populate group', function (done) { + Membership.create(mocks.membership, function (err, member) { + expect(err).to.not.exist; + expect(member).to.exist; + + member.populate('user', function (err, populated) { + expect(err).to.not.exist; + expect(populated).to.exist; + expect(populated.user.name).to.equal(mocks.user.name); + done(); + }); + }); + }); + + it('should populate group', function (done) { + Membership.create(mocks.membership, function (err, member) { + expect(err).to.not.exist; + expect(member).to.exist; + + member.populate('group', function (err, populated) { + expect(err).to.not.exist; + expect(populated).to.exist; + expect(populated.group.name).to.equal(mocks.group.name); + done(); + }); + }); + }); + + }); + +}); diff --git a/pool/shard007/JavaScript/0044932_index.js b/pool/shard007/JavaScript/0044932_index.js new file mode 100644 index 0000000000000000000000000000000000000000..c98a2247d24377b722cfc42c872877991e25803b --- /dev/null +++ b/pool/shard007/JavaScript/0044932_index.js @@ -0,0 +1,63 @@ +import React, { Component, PropTypes } from 'react'; + +import css from './styles.css'; + +const searchProvider = 'https://www.starcitygames.com/results?name='; + +export default class ScgSearchHelper extends Component { + constructor() { + super(); + + this.state = { + searchText: '', + }; + + this.updateSearchText = this.updateSearchText.bind(this); + this.submitSearch = this.submitSearch.bind(this); + } + + updateSearchText(event) { + this.setState({ + searchText: event.target.value, + }) + } + + submitSearch(event) { + event.preventDefault() + + const initialText = this.state.searchText; + + let searchQuery = initialText.replace(/(\s)+/g, '+') + .replace(/^\+/g, '') + .replace(/\+$/g, ''); + + const searchUrl = `${searchProvider}${searchQuery}`; + window.open(searchUrl); + } + + render() { + return ( +
    +
    + + +
    +
    + ) + } +} diff --git a/pool/shard007/JavaScript/0044933_route-list-component.js b/pool/shard007/JavaScript/0044933_route-list-component.js new file mode 100644 index 0000000000000000000000000000000000000000..f5b11bbd9dabd1a17f818eda6eb481598a6f0625 --- /dev/null +++ b/pool/shard007/JavaScript/0044933_route-list-component.js @@ -0,0 +1,77 @@ +import { Component } from '../component' +import { listComponent } from '../composite/list' + +import { + Route, StaticRoute, DynamicRoute, RegexRoute, ParamRoute +} from './route-component' + +import { + ExtensibleComponent +} from '../extensible-component' + +import { + combineBuilderWithMiddleware +} from '../util/middleware' + +export class RouteList extends ExtensibleComponent { + constructor(options={}) { + super(options) + + this.subComponents.routeList = listComponent() + } + + get routes() { + return this.subComponents.routeList.array + } + + toRouteBuildSpecs() { + const middleware = this.toExtendMiddleware() + + return this.routes.map(route => { + const builder = route.toHandleableBuilder() + const routeSpec = route.routeSpec + + routeSpec.builder = combineBuilderWithMiddleware( + builder, middleware) + + return routeSpec + }) + } + + addRoute(route) { + if(!route.isRouteComponent) { + throw new Error('route must be of type Route') + } + + this.routes.push(route) + + return this + } + + staticRoute(path, handler) { + return this.addRoute(new StaticRoute(handler, path)) + } + + paramRoute(path, handler) { + return this.addRoute(new ParamRoute(handler, path)) + } + + regexRoute(regex, fields, handler) { + return this.addRoute(new RegexRoute(handler, regex, fields)) + } + + dynamicRoute(matcher, handler) { + return this.addRoute(new DynamicRoute(handler, matcher)) + } + + get componentType() { + return 'RouteList' + } + + get isRouteListComponent() { + return true + } +} + +export const routeList = options => + new RouteList(options) \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044934_check-folder-meta.js b/pool/shard007/JavaScript/0044934_check-folder-meta.js new file mode 100644 index 0000000000000000000000000000000000000000..fee5bbf1d6f1941c7250054de75a48a298c26c7e --- /dev/null +++ b/pool/shard007/JavaScript/0044934_check-folder-meta.js @@ -0,0 +1,381 @@ +// +// The meta.files screwed to array by sorting bug. +// abc, tmpab, 0201, 2015 +// +// .load this file into REPL for easy checking +// +var assert = require("assert"); +var u = require("underscore"); +var async = require("async"); +var path = require("path"); +var Promise = require("bluebird"); + +var folder_module = require("../aws/folder-v5.js"); + +var config = require("../test/config.js"); + +var tutil = require ("../myutils/test-util.js"); + +var _folder_path = 'abc'; +var _user_name = 'abc'; +var _gg_folder_name = 'goodagood'; +var _new_folder_name= 'test'; + + +var p = console.log; + +var stop = function(period) { + var milli_seconds; + period = period || 1; + if (!u.isNumber(period)) { + period = 1; + } + milli_seconds = period * 1000; + return setTimeout(process.exit, milli_seconds); +}; + +function get_folder(name, dir){ + folder_module.retrieve_folder(dir).then(function(folder){ + this[name] = folder; + }); +} + +//test_get_all_uuid = function(test){ +// test.expect(1); +// folder_module.retrieve_promisified_folder(_folder_path).then(function(folder) { +// meta = folder.get_meta(); +// uuid_list = Object.keys(meta.files); +// return uuid_list; +// }).then(function(list){ +// //p('list: ', list); +// test.ok(u.isArray(list)); +// test.done(); +// }); +//}; +// +// +//test_get_text_of_the_1st = function(test){ +// _folder_path = 'abc/goodagood/message'; +// var Folder; +// test.expect(9); +// folder_module.retrieve_promisified_folder(_folder_path).then(function(folder) { +// Folder = folder; +// meta = folder.get_meta(); +// uuid_list = Object.keys(meta.files); +// return uuid_list; +// }).then(function(list){ +// //p('list: ', list); +// test.ok(u.isArray(list)); //1 +// test.ok(list.length > 0); //2 +// return list[0]; +// }).then(function(first){ +// // 'first' is the first uuid of msg file. +// //p('the first uuid: ', first); +// test.ok(u.isString(first)); //3 +// +// Folder.uuid_to_file_obj(first, function(err, file){ +// //p('get the file obj: \n',err, file); +// test.ok(u.isObject(file)); //4 +// test.ok(u.isFunction(file.delete_s3_storage)); //5 +// +// var info = file.get_meta(); +// test.ok(u.isObject(info)); //6 +// p('the first file name: ', info.name); +// test.ok(u.isString(info.name)); +// +// file.fetch_msg_json(function(err,json){ +// p('json: ', json); +// test.ok(u.isString(json.to)); +// test.ok(u.isString(json.from)); +// //file.get_msg_text(function(err, txt){ +// // p ('text of the msg: ', txt); +// // //test.ok(u.isString(txt)); +// // //test.done(); +// //}); +// test.done(); +// }); +// }); +// +// }); +//}; +// +// +//test_del_first_msg = function(test){ +// msg_folder = 'abc/goodagood/message'; +// +// var Mfolder; +// test.expect(2); +// folder_module.retrieve_promisified_folder(msg_folder).then(function(folder) { +// Mfolder = folder; +// meta = folder.get_meta(); +// uuid_list = Object.keys(meta.files); +// return uuid_list; +// }).then(function(list){ +// p('list got in "test del first":\n', list); +// test.ok(u.isArray(list)); +// //test.done(); +// return list; +// }).then(function(list){ +// var la = list[0]; +// p('the first in "test del first":\n', la); +// test.ok(u.isString(la)); +// Mfolder.delete_uuid(la, function(err, reply){ +// p('delete one? err, rep: ', err, reply); +// test.done(); +// }); +// }); +// +//}; +// +//check_to_get_file_obj = function(test){ +// msg_folder = 'abc/goodagood/message'; +// //delete uuid: 5095f6ac-94ad-467c-a619-5917073db1cf +// //name is To_aa_1416917760452.ggmsg +// +// uuid = "5095f6ac-94ad-467c-a619-5917073db1cf"; +// folder_module.retrieve_promisified_folder(msg_folder).then(function(folder) { +// //var folder_meta = folder.get_meta(); +// +// //p ("folder meta\n", folder_meta); +// //p ("file meta in folder\n", folder_meta.files[uuid]); +// +// //folder.get_file_obj_by_uuid(uuid).then(function(file){ +// // var file_meta = file.get_meta(); +// // p ('file meta\n', file_meta); +// // test.done(); +// //}); +// +// folder.delete_uuid(uuid, function(err, reply){ +// p('delete one got : err, rep: ', err, reply); +// test.done(); +// }); +// }) +//} +// +// +// +//test_write_and_get_uuid = function(test){ +// +// // settings of the test: +// var folder_path = 'abc'; +// var file_name = "test-write-and-get-uuid"; +// var file_text = "this is a test\n" + +// "this is the second line\n" + +// " -- to wriet this file, and check to get it by uuid --" + +// "this is the time: " + new Date() ; +// +// // global vars: +// var Meta, Folder; +// +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder) { +// Folder = folder; +// test.expect(5); // number of tests: +// test.ok(u.isObject(Folder)); +// return folder.write_text_file(file_name, file_text); +// }).then(function(what){ +// p('Going to sleep 30 secs. We should already wrote the file: ', file_name); +// return config.promise_to_wait(30); +// }).then(function(){ +// return Folder.promise_to_retrieve_saved_meta(); +// }).then(function(meta){ +// Meta = meta; +// test.ok(u.isObject(Meta)); +// test.ok(u.isString(Meta.name)); +// test.ok(Meta.path === folder_path); +// //test.ok(Folder.file_exists(file_name)); // till not wrote. +// test.done(); +// }); +// +//}; +// +////#? +//ta1_delete_folder = function(test){ +// // without consider the contents of the folder +// //test.expect(1); +// folder_module.retrieve_promisified_folder(_folder_path).then(function(folder) { +// meta = folder.get_meta(); +// }); +//}; + +////-- for testing group one --// +//module.exports.group_one = { +// setUp: function (callback) { +// //this.foo = 'bar'; +// callback(); +// }, +// tearDown: function (callback) { +// callback(); +// }, +// +// //"test-1 : get all uuids" : test_get_all_uuid, +// //"test-4 : get text of the 1st" : test_get_text_of_the_1st +// +// //"test-2 : del first msg for abc" : test_del_first_msg +// //"test-3 : tmp when other failed " : check_to_get_file_obj, +//}; +// +// +//module.exports.file_stop = function(test){ +// test.expect(1); +// test.ok(true); +// stop(); +// test.done(); +//} +// + +// -- the following is for fast checkings -- + +//function check_get_uuids(_path){ +// _path = _path || 'abc/test'; +// +// var folder_path = path.dirname (_path); +// var basename = path.basename(_path); +// p(folder_path, basename); +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder){ +// var list = folder.get_uuids(basename); +// //p (1, list); +// return list; +// }).then(function(uuid_list){ +// p(uuid_list); +// stop(); +// }); +//} +// +//function check_del_file(file_path){ +// var _path = file_path || 'abc/txt-15'; +// +// var folder_path = path.dirname (_path); +// var basename = path.basename(_path); +// p(folder_path, basename); +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder){ +// assert(u.isFunction(folder.delete_file_promised)); +// return folder.delete_file_promised(basename); +// }).then(function(del){ +// p('after del the ' + _path); +// p(del); +// stop(); +// }); +//} +// +//function check_pattern(file_path){ +// var _path = file_path || 'abc/txt22'; +// +// var folder_path = path.dirname (_path); +// var basename = path.basename(_path); +// p(folder_path, basename); +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder){ +// var uuid_list = folder.pattern_to_uuids(/funn.+/); +// p(uuid_list); +// stop(); +// }); +//} +// +//function delete_one_file_by_pattern(folder_path, pat){ +// var Folder; +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder){ +// Folder = folder; +// var uuid_list = folder.pattern_to_uuids(pat); +// p(uuid_list); +// if(uuid_list.length >= 1){ return uuid_list[0];} +// else {throw 'not found any one can get deleted';} +// }).then(function(uuid){ +// p(uuid); +// return Folder.delete_file_by_uuid(uuid); +// }).then(function(del){ +// p('it should deleted'); +// p(del); +// stop(); +// });; +//} +// +// +//function delete_one_folder(folder_path, pat){ +// var Folder; +// folder_module.retrieve_promisified_folder(folder_path).then(function(folder){ +// Folder = folder; +// var uuids = Folder.pattern_to_uuids(pat); +// p(uuids); +// if(uuids.length > 0){ return uuids[0];} +// else {throw 'only one can get deleted';} +// }).then(function(uuid){ +// p(uuid); +// Folder.delete_folder(uuid, function(err, what){ +// p('ok, what you got?'); +// p(err, what); +// stop(); +// }); +// }); +//} +// +//function check_add_folder(folder_path){ +// folder_path = folder_path || 'abc/tadd'; +// var dir = path.dirname (folder_path); +// var name = path.basename(folder_path); +// +// // Sub is added new folder +// var Folder, Meta, Sub; +// folder_module.retrieve_promisified_folder(dir).then(function(folder){ +// Folder = folder; +// Meta = Folder.get_meta(); +// p('path: ', Meta.path); +// p('uuid: ', Meta.uuid); +// +// return Folder.add_folder(name); +// +// //Folder.add_folder(name); +// }).then(function(obj){ +// Sub = obj; +// var new_meta = Sub.get_meta(); +// p('new meta: ', new_meta); +// stop(); +// }); +// +//} +// +// +//function delete_folder(folder_path){ +// folder_path = folder_path || 'abc/test-add'; +// var dir = path.dirname (folder_path); +// var name = path.basename(folder_path); +// +// // Sub is added new folder +// var Folder, Meta, Sub; +// folder_module.retrieve_promisified_folder(dir).then(function(folder){ +// Folder = folder; +// if(! Folder.file_exists(name)){return Promise.reject('not exists: ' + folder_path);} +// assert(Folder.file_exists(name)); +// assert(u.isFunction(Folder.delete_folder_promised)); +// return Folder.get_uuids(name); +// }).then(function(uuids){ +// assert(u.isArray(uuids)); +// assert(uuids.length >= 1); +// return Folder.delete_folder_promised(uuids[0]); +// }).then(function(what){ +// p('should be aws reply:\n', what); +// }).then(function(){ +// tutil.stop(); +// }).catch(function(err){ +// p('caught what:\n', err); +// tutil.stop(); +// }); +//} +// +//list_file_names = function(test){ +// // todo +// test.expect(1); +// folder_module.retrieve_promisified_folder(_folder_path).then(function(folder) { +// meta = folder.get_meta(); +// uuid_list = Object.keys(meta.files); +// }); +//} + +if(require.main === module){ + //check_get_uuids('abc/test'); + //check_del_file(); + //check_pattern(); + delete_one_file_by_pattern('tmpab', /Home.md/); + //delete_folder(); + + //delete_one_folder('abc', /test-add$/); + //check_add_folder(); +} diff --git a/pool/shard007/JavaScript/0044946_site.wordads.earnings.js b/pool/shard007/JavaScript/0044946_site.wordads.earnings.js new file mode 100644 index 0000000000000000000000000000000000000000..b61dad26aa11e78064a847c55d1b51b9390ec333 --- /dev/null +++ b/pool/shard007/JavaScript/0044946_site.wordads.earnings.js @@ -0,0 +1,36 @@ +/** + * `SiteWordAdsEarnings` constructor. + * + * @param {String} sid - site identifier + * @param {WPCOM} wpcom - wpcom instance + * @return {Null} null + */ +export default function SiteWordAdsEarnings( sid, wpcom ) { + if ( ! ( this instanceof SiteWordAdsEarnings ) ) { + return new SiteWordAdsEarnings( sid, wpcom ); + } + + this._sid = sid; + this.wpcom = wpcom; +} + +/** + * Get detailed WordAds earnings information about the site. + * + * *Example:* + * // Get site earnings information + * wpcom + * .site( 'my-blog.wordpress.com' ) + * .wordAds() + * .earnings() + * .get( function( err, data ) { + * // `earnings` information object + * } ); + * + * @param {Object} [query] - query object parameter + * @param {Function} fn - callback function + * @return {Function} request handler + */ +SiteWordAdsEarnings.prototype.get = function( query, fn ) { + return this.wpcom.req.get( '/sites/' + this._sid + '/wordads/earnings', query, fn ); +}; diff --git a/pool/shard007/JavaScript/0044948_service.js b/pool/shard007/JavaScript/0044948_service.js new file mode 100644 index 0000000000000000000000000000000000000000..81325c8059c63c7fd4c393f9e9bb1640b6294fdb --- /dev/null +++ b/pool/shard007/JavaScript/0044948_service.js @@ -0,0 +1,78 @@ +'use strict'; + +/** + * @ngdoc function + * @name openshiftConsole.controller:ServiceController + * @description + * Controller of the openshiftConsole + */ +angular.module('openshiftConsole') + .controller('ServiceController', function ($scope, $routeParams, DataService, ProjectsService, $filter) { + $scope.projectName = $routeParams.project; + $scope.service = null; + $scope.alerts = {}; + $scope.renderOptions = $scope.renderOptions || {}; + $scope.renderOptions.hideFilterWidget = true; + $scope.breadcrumbs = [ + { + title: "Services", + link: "project/" + $routeParams.project + "/browse/services" + }, + { + title: $routeParams.service + } + ]; + + var watches = []; + + ProjectsService + .get($routeParams.project) + .then(_.spread(function(project, context) { + $scope.project = project; + $scope.projectContext = context; + DataService.get("services", $routeParams.service, context).then( + // success + function(service) { + $scope.loaded = true; + $scope.service = service; + + // If we found the item successfully, watch for changes on it + watches.push(DataService.watchObject("services", $routeParams.service, context, function(service, action) { + if (action === "DELETED") { + $scope.alerts["deleted"] = { + type: "warning", + message: "This service has been deleted." + }; + } + $scope.service = service; + })); + }, + // failure + function(e) { + $scope.loaded = true; + $scope.alerts["load"] = { + type: "error", + message: "The service details could not be loaded.", + details: "Reason: " + $filter('getErrorDetails')(e) + }; + } + ); + + watches.push(DataService.watch("routes", context, function(routes) { + $scope.routesForService = []; + angular.forEach(routes.by("metadata.name"), function(route) { + if (route.spec.to.kind === "Service" && + route.spec.to.name === $routeParams.service) { + $scope.routesForService.push(route); + } + }); + + Logger.log("routes (subscribe)", $scope.routesByService); + })); + + $scope.$on('$destroy', function(){ + DataService.unwatchAll(watches); + }); + + })); + }); diff --git a/pool/shard007/JavaScript/0044951_phpmyfaq.tinymce.plugin.js b/pool/shard007/JavaScript/0044951_phpmyfaq.tinymce.plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..59d742730a359bf8a9a1249e0ccfc965d8c6bd58 --- /dev/null +++ b/pool/shard007/JavaScript/0044951_phpmyfaq.tinymce.plugin.js @@ -0,0 +1,90 @@ +/** + * TinyMCE v5 plugin to fetch and insert internal links via Ajax call + * + * This Source Code Form is subject to the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at https://mozilla.org/MPL/2.0/. + * + * @package phpMyFAQ + * @author Thorsten Rinne + * @copyright 2015-2022 phpMyFAQ Team + * @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0 + * @link https://www.phpmyfaq.de + * @since 2015-10-08 + */ + +/*global tinymce:false, $:false */ + +tinymce.PluginManager.add('phpmyfaq', function (editor, url) { + 'use strict'; + + const openDialog = function (csrfToken) { + return editor.windowManager.open({ + title: 'phpMyFAQ TinyMCE plugin', + body: { + type: 'panel', + items: [ + { type: 'input', name: 'search', label: 'Search', id: 'pmf-internal-links' }, + { type: 'htmlpanel', html: '
    ' }, + ], + }, + buttons: [ + { + type: 'cancel', + text: 'Close', + }, + { + type: 'submit', + text: 'Save', + primary: true, + }, + ], + onChange: (api) => { + const data = api.getData(); + const url = location.protocol + '//' + location.host + location.pathname; + const list = $('#pmf-faq-list'); + + if (data.search.length > 0) { + $.ajax({ + type: 'POST', + url: url + '?action=ajax&ajax=records&ajaxaction=search_records', + data: 'search=' + data.search + '&csrf=' + csrfToken, + success: (searchResults) => { + list.empty(); + if (searchResults.length > 0) { + list.append(searchResults); + } + }, + }); + } + }, + onSubmit: (api) => { + const selected = $('input:radio[name=faqURL]:checked'); + const url = selected.val(); + const title = selected.parent().text(); + const anchor = '' + title + ''; + editor.insertContent(anchor); + api.close(); + }, + }); + }; + + // Add button to editor + editor.ui.registry.addButton('phpmyfaq', { + text: 'phpMyFAQ', + //image: 'images/phpmyfaq.gif', + onAction: () => { + const csrfToken = document.getElementById('csrf').value; + openDialog(csrfToken); + }, + }); + + return { + getMetadata: function () { + return { + name: 'phpMyFAQ TinyMCE plugin', + url: 'https://www.phpmyfaq.de/documentation', + }; + }, + }; +}); diff --git a/pool/shard007/JavaScript/0044954_playground.js b/pool/shard007/JavaScript/0044954_playground.js new file mode 100644 index 0000000000000000000000000000000000000000..d3de0e3f9abbe62ec0361a3c023ba8245f58d38f --- /dev/null +++ b/pool/shard007/JavaScript/0044954_playground.js @@ -0,0 +1,183 @@ +/* global require, window, console */ +require( + [ + 'brix/loader', 'brix/event', 'brix/vue', + 'vue', 'jquery', 'accounting', 'moment'/*, 'log'*/ + ], + function( + Loader, EventManager, VueDecorator, + Vue, $, Accounting, moment/*, log*/ + ) { + window.Vue = Vue + Vue.config.debug = true + + Vue.filter('tahoma', function(value) { + return '' + value + '' + }) + Vue.filter('bold', function(value) { + return '' + value + '' + }) + Vue.filter('X.xx', function(value) { + if (value === undefined) value = 0 + var isNumber = typeof value === 'number' + var arr = (isNumber ? value.toFixed(2) : ('' + value)).split('.') + return '' + arr[0] + '' + + '.' + arr[1] + '' + }) + + // + Vue.filter('color.brand', function(value) { + return '' + value + '' + }) + Vue.filter('color.help', function(value) { + return '' + value + '' + }) + Vue.filter('color.info', function(value) { + return '' + value + '' + }) + Vue.filter('color.gray', function(value) { + return '' + value + '' + }) + Vue.filter('color.border', function(value) { + return '' + value + '' + }) + Vue.filter('color.warning', function(value) { + return '' + value + '' + }) + Vue.filter('color.danger', function(value) { + return '' + value + '' + }) + Vue.filter('color.success', function(value) { + return '' + value + '' + }) + Vue.filter('color.fail', function(value) { + return '' + value + '' + }) + + // + Vue.filter('accounting', function(value, precision) { + return Accounting.formatNumber(value, precision) + }) + Vue.filter('moment', { + read: function(value, format) { + format = format || 'YYYY-MM-DD HH:mm:ss' + return moment(value).format(format) + }, + /* jshint unused:false */ + write: function(value, oldValue, format) { + return moment(value).toDate() + } + }) + + // + Vue.filter('length', function(value) { + return value.length + }) + + // + Vue.filter('popover', function(value, content) { + return '' + value + '' + }) + + Vue.filter('length', function(value) { + return value.length + }) + + function View() {} + + View.prototype.init = function() { + var view = this + this.$manager = new EventManager('mx-') + + this.options = { + el: '#hero', + data: { + iamnull: null, + array: ['foo', 'bar', 'faz'], + object: { + foo: 0, + bar: 1, + faz: 2 + }, + number: 10, + string: 'foo', + model: { + checked3: [], + checked4: false + }, + imageSrc: 'http://cn.vuejs.org/images/logo.png', + ifNested: '', + + msg: Math.random(), + html: $('
    ').html(Math.random()).html(), + // pagination + total: 100, + cursor: 1, + limit: 10, + list: [0, 1, 2], + dropdowns: [ + { disabled: true }, + { disabled: false } + ], + name: '', + users: [{ + name: 'Bruce', + desc: 'foo' + }, { + name: 'Chuck', + desc: 'bar' + }, { + name: 'Jackie', + desc: 'faz' + }], + filterBy1: [], + myCustomFilterFunction: function(item, index, arr){ + console.log(view.options.data.filterBy1) + return false // 显示返回 true,不显示返回 false + }, + icon: '' + }, + computed: {}, + methods: {}, + created: function() { + console.log('[ LifeCycle ] _created_ ', arguments) + }, + compiled: function() { + console.log('[ LifeCycle ] _compiled_ ', arguments) + }, + ready: function() { + console.log('[ LifeCycle ] _ready_ ', arguments) + var vm = this + Loader.boot(this.el, function() { + Vue.Decorator.fixComponents() + view.$manager.delegate(vm.$el, view) + }) + }, + beforeDestroy: function() { + console.log('[ LifeCycle ] _beforeDestroy_ ', arguments) + }, + destroyed: function() { + console.log('[ LifeCycle ] _destroyed_ ', arguments) + this.view = undefined + } + } + return this + } + + View.prototype.render = function() { + this.vm = new Vue(this.options) + this.vm.__owner = this + return this + } + + View.prototype.handler = function(event, extra) { + console.log(event.type, event.namespace, extra) + } + + var view = new View() + view.init() + view.render() + + window.view = view + } +) \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044958_obstacle.js b/pool/shard007/JavaScript/0044958_obstacle.js new file mode 100644 index 0000000000000000000000000000000000000000..570501041ff4864ab49a55478673d30d6bc6e8b7 --- /dev/null +++ b/pool/shard007/JavaScript/0044958_obstacle.js @@ -0,0 +1,61 @@ +"use strict"; + +var app = app || {}; + +/* + * Obstacle for Balloon + */ +app.Obstacle = (function() +{ + var BASE_X = app.canvas.width + (app.canvas.width / 10.0) + app.OFFSET_LEFT; + var BASE_Y = app.canvas.height / 2; + var BASE_SPEED = -5; + + /* + * Creates an obstacle with the given parameters + * + * @param image Path of the image to use for the obstacle + * @param x [Optional] x-position of the obstacle + * @param y [Optional] y-position of the obstacle + * @param speed [Optional] speed of the obstacle + */ + var Obstacle = function(image, x, y, speed) + { + this.image = image; + + this.x = ( x === undefined ? BASE_X : x ); + this.y = ( y === undefined ? BASE_Y : y ); + this.speed = ( speed === undefined ? BASE_SPEED : speed ); + } + + /* + * Updates the obstacle + */ + Obstacle.prototype.update = function(timeElapsed) + { + //console.log(timeElapsed); + //console.log(app.FRAME_RATE); + + this.x += this.speed * (timeElapsed/app.FRAME_RATE); + //console.log("[" + this.x + "," + this.y + "]"); + //console.log(this.image); + }; + + /* + * Draws the obstacle on the canvas + */ + Obstacle.prototype.draw = function() + { + app.ctx.save(); + + //app.ctx.fillStyle = "green"; + //app.ctx.fillRect(300, 200, 100, 100); + + app.ctx.drawImage(this.image, this.x, this.y, 50, 50); + + app.ctx.restore(); + }; + + return Obstacle; + +})(); \ No newline at end of file diff --git a/pool/shard007/JavaScript/0044960_WorkspaceGrid.js b/pool/shard007/JavaScript/0044960_WorkspaceGrid.js new file mode 100644 index 0000000000000000000000000000000000000000..a21e085e9b60ff36c17b5195836bf48d2c778bd4 --- /dev/null +++ b/pool/shard007/JavaScript/0044960_WorkspaceGrid.js @@ -0,0 +1,267 @@ +define("p3/widget/WorkspaceGrid", [ + 'dojo/_base/declare', 'dgrid/Grid', 'dojo/store/JsonRest', 'dgrid/extensions/DijitRegistry', + 'dgrid/Keyboard', 'dgrid/Selection', './formatter', 'dgrid/extensions/ColumnResizer', 'dgrid/extensions/ColumnHider', + 'dgrid/extensions/DnD', 'dojo/dnd/Source', 'dojo/_base/Deferred', 'dojo/aspect', 'dojo/_base/lang', 'dojo/dom-construct', + 'dojo/topic', 'dgrid/editor', 'dijit/Menu', 'dijit/MenuItem', '../WorkspaceManager', 'dojo/on', 'dijit/form/TextBox' +], function ( + declare, Grid, Store, DijitRegistry, + Keyboard, Selection, formatter, ColumnResizer, + ColumnHider, DnD, DnDSource, + Deferred, aspect, lang, domConstruct, + Topic, editor, Menu, MenuItem, WorkspaceManager, on, TextBox +) { + return declare([Grid, ColumnHider, Selection, Keyboard, ColumnResizer, DijitRegistry], { + columns: { + type: { + label: '', + get: function (item) { + if (item.type == 'job_result' && item.autoMeta && item.autoMeta.app) { + return item.type + '_' + (item.autoMeta.app.id ? item.autoMeta.app.id : item.autoMeta.app); + } else if (item.type == 'folder' && item.path.split('/').length <= 3) { + if (item.global_permission != 'n') + { return 'publicWorkspace'; } + + // determine if shared or not + return item.permissions.length > 1 ? 'sharedWorkspace' : 'workspace'; + } + return item.type; + }, + className: 'wsObjIcon', + formatter: formatter.wsItemType, + unhidable: true + }, + name: editor({ + label: 'Name', + field: 'name', + className: 'wsItemName', + canEdit: function (obj, val) { + return obj.id == 'untitled'; + }, + autoSave: true, + editOn: 'click', + editor: TextBox, + editorArgs: { placeHolder: 'Untitled Folder', trim: true } + }), + size: { + label: 'Size', + field: 'size', + get: function (item) { + return item; + }, + className: 'wsItemSize', + hidden: false, + formatter: formatter.objectOrFileSize + }, + obj_type: { + label: 'Type', + field: 'type', + className: 'wsItemType', + hidden: true + }, + owner_id: { + label: 'Owner', + field: 'owner_id', + className: 'wsItemOwnerId', + formatter: formatter.baseUsername, + hidden: false + }, + sharedWith: { + label: 'Members', + field: '_item', + className: 'wsItemMembers', + formatter: formatter.usersFormatter + }, + creation_time: { + label: 'Created', + field: 'creation_time', + className: 'wsItemCreationTime', + formatter: formatter.date + } + /* + userMeta: { + label: "User Metadata", + field: "userMeta", + hidden: true + }, + autoMeta: { + label: "Metadata", + field: "autoMeta", + hidden: true + } + */ + }, + constructor: function () { + this.dndParams.creator = lang.hitch(this, function (item, hint) { + // console.log("item: ", item, " hint:", hint, "dataType: ", this.dndDataType); + var avatar = domConstruct.create('div', { + innerHTML: item.organism_name || item.ncbi_taxon_id || item.id + }); + avatar.data = item; + if (hint == 'avatar') { + // create your avatar if you want + } + + return { + node: avatar, + data: item, + type: this.dndDataType + }; + }); + + }, + store: null, + selectionMode: 'extended', + allowTextSelection: false, + deselectOnRefresh: false, + minRowsPerPage: 50, + bufferRows: 100, + maxRowsPerPage: 1000, + pagingDelay: 250, + farOffRemoval: 2000, + keepScrollPosition: true, + rowHeight: 24, + loadingMessage: 'Loading...', + dndDataType: 'genome', + dndParams: { + accept: 'none', + selfAccept: false, + copyOnly: true + }, + + /* + _setApiServer: function(server){ + console.log("_setapiServerAttr: ", server); + this.apiServer = server; + this.set('store', this.createStore(this.dataModel), this.buildQuery()); + }, + */ + + _setTotalRows: function (rows) { + this.totalRows = rows; + // console.log("Total Rows: ", rows); + if (this.controlButton) { + // console.log("this.controlButton: ", this.controlButton); + if (!this._originalTitle) { + this._originalTitle = this.controlButton.get('label'); + } + this.controlButton.set('label', this._originalTitle + ' (' + rows + ')'); + + // console.log(this.controlButton); + } + }, + + startup: function () { + if (this._started) { + return; + } + var _self = this; + aspect.before(_self, 'renderArray', function (results) { + Deferred.when(results.total, function (x) { + _self.set('totalRows', x); + }); + }); + + this.on('.dgrid-content .dgrid-row:dblclick', function (evt) { + var row = _self.row(evt); + + var path = _self.path.split('/')[1] == 'public' ? '/public' + row.data.path : row.data.path; + + on.emit(_self.domNode, 'ItemDblClick', { + item_path: path, + item: row.data, + bubbles: true, + cancelable: true + }); + // console.log('after emit'); + // if (row.data.type == "folder"){ + // Topic.publish("/select", []); + + // Topic.publish("/navigate", {href:"/workspace" + row.data.path }) + // _selection={}; + // } + }); + + this.on('.dgrid-content .dgrid-cell.wsObjIcon:click', function (evt) { + var row = _self.row(evt); + evt.preventDefault(); + evt.stopPropagation(); + + var path = _self.path.split('/')[1] == 'public' ? '/public' + row.data.path : row.data.path; + + on.emit(_self.domNode, 'ItemDblClick', { + item_path: path, + item: row.data, + bubbles: true, + cancelable: true + }); + + }); + // _selection={}; + // Topic.publish("/select", []); + + this.on('dgrid-select', function (evt) { + setTimeout(function () { + var newEvt = { + rows: evt.rows, + selected: evt.grid.selection, + grid: _self, + bubbles: true, + cancelable: true + }; + on.emit(_self.domNode, 'select', newEvt); + }, 250); + }); + + this.on('dgrid-deselect', function (evt) { + var newEvt = { + rows: evt.rows, + selected: evt.grid.selection, + grid: _self, + bubbles: true, + cancelable: true + }; + on.emit(_self.domNode, 'deselect', newEvt); + + }); + + // see WorkspaceExplorerView.listWorkspaceContents for sorting + _self.set('sort', [{ attribute: 'name', descending: false }] ); + + this.inherited(arguments); + this._started = true; + }, + _setActiveFilter: function (filter) { + // console.log("Set Active Filter: ", filter, "started:", this._started); + this.activeFilter = filter; + this.set('query', this.buildQuery()); + }, + + buildQuery: function (table, extra) { + var q = '?' + (this.activeFilter ? ('in(gid,query(genomesummary,and(' + this.activeFilter + ',limit(Infinity),values(genome_info_id))))') : '') + (this.extra || ''); + // console.log("Feature Grid Query:", q); + return q; + }, + createStore: function (dataModel) { + // console.log("Create Store for ", dataModel, " at ", this.apiServer); + var store = new Store({ + target: (this.apiServer ? (this.apiServer) : '') + '/' + dataModel + '/', + idProperty: 'rownum', + headers: { + accept: 'application/json', + 'content-type': 'application/json', + 'X-Requested-With': null, + Authorization: (window.App.authorizationToken || '') + } + }); + // console.log("store: ", store); + return store; + } + + // getFilterPanel: function () { + // // console.log("getFilterPanel()"); + // return FilterPanel; + // } + + }); + +}); diff --git a/pool/shard007/JavaScript/0044963_angular.directive.msd-elastic.js b/pool/shard007/JavaScript/0044963_angular.directive.msd-elastic.js new file mode 100644 index 0000000000000000000000000000000000000000..fbc911f755f289a0a99fceb9588672a724a62426 --- /dev/null +++ b/pool/shard007/JavaScript/0044963_angular.directive.msd-elastic.js @@ -0,0 +1,216 @@ +/* + * angular-elastic v2.4.2 + * (c) 2014 Monospaced http://monospaced.com + * License: MIT + */ +define([], function() { + + return [ + '$timeout', '$window', 'msdElasticConfig', + function($timeout, $window, config) { + + 'use strict'; + + return { + require: 'ngModel', + restrict: 'A, C', + link: function(scope, element, attrs, ngModel) { + + // cache a reference to the DOM element + var ta = element[0], + $ta = element; + + // ensure the element is a textarea, and browser is capable + if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) { + return; + } + + // set these properties before measuring dimensions + $ta.css({ + 'overflow': 'hidden', + 'overflow-y': 'hidden', + 'word-wrap': 'break-word' + }); + + // force text reflow + var text = ta.value; + ta.value = ''; + ta.value = text; + + var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append, + $win = angular.element($window), + mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + + '-moz-box-sizing: content-box; box-sizing: content-box;' + + 'min-height: 0 !important; height: 0 !important; padding: 0;' + + 'word-wrap: break-word; border: 0;', + $mirror = angular.element('